From 4501d5a51d49e2e709930188a02af8d3dec5da61 Mon Sep 17 00:00:00 2001 From: gero3 Date: Thu, 19 Feb 2015 17:34:37 +0000 Subject: [PATCH] revert last commit --- editor/js/Sidebar.Object3D.js | 2 +- examples/js/BlendCharacter.js | 12 +- examples/js/CurveExtras.js | 16 +- examples/js/ParametricGeometries.js | 6 +- examples/js/SimplexNoise.js | 422 ++-- examples/js/Sparks.js | 290 +-- examples/js/controls/MouseControls.js | 50 +- examples/js/controls/TransformControls.js | 24 +- examples/js/effects/VREffect.js | 2 +- examples/js/geometries/ConvexGeometry.js | 10 +- examples/js/geometries/DecalGeometry.js | 4 +- examples/js/loaders/AWDLoader.js | 1288 ++++++------ examples/js/loaders/ColladaLoader.js | 52 +- examples/js/loaders/PVRLoader.js | 32 +- examples/js/loaders/RGBELoader.js | 6 +- examples/js/loaders/STLLoader.js | 14 +- examples/js/loaders/TGALoader.js | 12 +- examples/js/loaders/UTF8Loader.js | 572 +++--- examples/js/loaders/VRMLLoader.js | 2 +- examples/js/loaders/ctm/ctm.js | 714 +++---- examples/js/loaders/ctm/lzma.js | 696 +++---- examples/js/loaders/deprecated/SceneLoader.js | 2 +- examples/js/loaders/gltf/glTF-parser.js | 336 ++-- examples/js/loaders/gltf/glTFLoader.js | 1784 ++++++++--------- examples/js/loaders/gltf/glTFLoaderUtils.js | 204 +- examples/js/renderers/SVGRenderer.js | 2 +- examples/js/renderers/SoftwareRenderer.js | 4 +- examples/js/utils/UVsDebug.js | 110 +- examples/js/wip/benchmark/Geometry4.js | 50 +- src/extras/FontUtils.js | 6 +- src/extras/core/Curve.js | 8 +- src/extras/core/Path.js | 4 +- src/extras/geometries/ExtrudeGeometry.js | 12 +- src/loaders/CompressedTextureLoader.js | 2 +- src/loaders/JSONLoader.js | 2 +- src/math/Matrix4.js | 8 +- src/math/Sphere.js | 2 +- src/math/Vector2.js | 14 +- src/math/Vector3.js | 16 +- src/math/Vector4.js | 58 +- src/renderers/WebGLRenderer.js | 46 +- 41 files changed, 3448 insertions(+), 3448 deletions(-) diff --git a/editor/js/Sidebar.Object3D.js b/editor/js/Sidebar.Object3D.js index b2b0394e3b..4bea46dc1e 100644 --- a/editor/js/Sidebar.Object3D.js +++ b/editor/js/Sidebar.Object3D.js @@ -84,7 +84,7 @@ Sidebar.Object3D = function ( editor ) { var objectNameRow = new UI.Panel(); var objectName = new UI.Input().setWidth( '150px' ).setFontSize( '12px' ).onChange( function () { - editor.nameObject( editor.selected, objectName.getValue() ); + editor.nameObject( editor.selected, objectName.getValue() ); } ); diff --git a/examples/js/BlendCharacter.js b/examples/js/BlendCharacter.js index ca7a142a95..430eb7f4f2 100644 --- a/examples/js/BlendCharacter.js +++ b/examples/js/BlendCharacter.js @@ -203,17 +203,17 @@ THREE.BlendCharacter = function () { this.unPauseAll = function() { - for ( var a in this.animations ) { + for ( var a in this.animations ) { - if ( this.animations[ a ].isPlaying && this.animations[ a ].isPaused ) { + if ( this.animations[ a ].isPlaying && this.animations[ a ].isPaused ) { - this.animations[ a ].pause(); + this.animations[ a ].pause(); - } + } - } + } - }; + }; this.stopAll = function() { diff --git a/examples/js/CurveExtras.js b/examples/js/CurveExtras.js index f9340f9fe8..6b0864d60e 100644 --- a/examples/js/CurveExtras.js +++ b/examples/js/CurveExtras.js @@ -18,12 +18,12 @@ THREE.Curves = {}; THREE.Curves.GrannyKnot = THREE.Curve.create( function() {}, function(t) { - t = 2 * Math.PI * t; + t = 2 * Math.PI * t; - var x = -0.22 * Math.cos(t) - 1.28 * Math.sin(t) - 0.44 * Math.cos(3 * t) - 0.78 * Math.sin(3 * t); - var y = -0.1 * Math.cos(2 * t) - 0.27 * Math.sin(2 * t) + 0.38 * Math.cos(4 * t) + 0.46 * Math.sin(4 * t); - var z = 0.7 * Math.cos(3 * t) - 0.4 * Math.sin(3 * t); - return new THREE.Vector3(x, y, z).multiplyScalar(20); + var x = -0.22 * Math.cos(t) - 1.28 * Math.sin(t) - 0.44 * Math.cos(3 * t) - 0.78 * Math.sin(3 * t); + var y = -0.1 * Math.cos(2 * t) - 0.27 * Math.sin(2 * t) + 0.38 * Math.cos(4 * t) + 0.46 * Math.sin(4 * t); + var z = 0.7 * Math.cos(3 * t) - 0.4 * Math.sin(3 * t); + return new THREE.Vector3(x, y, z).multiplyScalar(20); } ); @@ -214,10 +214,10 @@ THREE.Curves.TrefoilPolynomialKnot = THREE.Curve.create( // } var scaleTo = function(x, y, t) { - var r = y - x; - return t * r + x; + var r = y - x; + return t * r + x; - } +} THREE.Curves.FigureEightPolynomialKnot = THREE.Curve.create( diff --git a/examples/js/ParametricGeometries.js b/examples/js/ParametricGeometries.js index 41cf6aab9b..8c2cc66c79 100644 --- a/examples/js/ParametricGeometries.js +++ b/examples/js/ParametricGeometries.js @@ -108,9 +108,9 @@ THREE.ParametricGeometries.TubeGeometry = function(path, segments, radius, segme binormals = frames.binormals; // proxy internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; diff --git a/examples/js/SimplexNoise.js b/examples/js/SimplexNoise.js index d0952c1979..1dd120d443 100644 --- a/examples/js/SimplexNoise.js +++ b/examples/js/SimplexNoise.js @@ -13,11 +13,11 @@ */ var SimplexNoise = function(r) { if (r == undefined) r = Math; - this.grad3 = [[ 1,1,0 ],[ -1,1,0 ],[ 1,-1,0 ],[ -1,-1,0 ], + this.grad3 = [[ 1,1,0 ],[ -1,1,0 ],[ 1,-1,0 ],[ -1,-1,0 ], [ 1,0,1 ],[ -1,0,1 ],[ 1,0,-1 ],[ -1,0,-1 ], [ 0,1,1 ],[ 0,-1,1 ],[ 0,1,-1 ],[ 0,-1,-1 ]]; - this.grad4 = [[ 0,1,1,1 ], [ 0,1,1,-1 ], [ 0,1,-1,1 ], [ 0,1,-1,-1 ], + this.grad4 = [[ 0,1,1,1 ], [ 0,1,1,-1 ], [ 0,1,-1,1 ], [ 0,1,-1,-1 ], [ 0,-1,1,1 ], [ 0,-1,1,-1 ], [ 0,-1,-1,1 ], [ 0,-1,-1,-1 ], [ 1,0,1,1 ], [ 1,0,1,-1 ], [ 1,0,-1,1 ], [ 1,0,-1,-1 ], [ -1,0,1,1 ], [ -1,0,1,-1 ], [ -1,0,-1,1 ], [ -1,0,-1,-1 ], @@ -26,19 +26,19 @@ var SimplexNoise = function(r) { [ 1,1,1,0 ], [ 1,1,-1,0 ], [ 1,-1,1,0 ], [ 1,-1,-1,0 ], [ -1,1,1,0 ], [ -1,1,-1,0 ], [ -1,-1,1,0 ], [ -1,-1,-1,0 ]]; - this.p = []; - for (var i = 0; i < 256; i ++) { - this.p[i] = Math.floor(r.random() * 256); - } + this.p = []; + for (var i = 0; i < 256; i ++) { + this.p[i] = Math.floor(r.random() * 256); + } // To remove the need for index wrapping, double the permutation table length - this.perm = []; - for (var i = 0; i < 512; i ++) { + this.perm = []; + for (var i = 0; i < 512; i ++) { this.perm[i] = this.p[i & 255]; } // A lookup table to traverse the simplex around a given point in 4D. // Details can be found where this table is used, in the 4D noise method. - this.simplex = [ + this.simplex = [ [ 0,1,2,3 ],[ 0,1,3,2 ],[ 0,0,0,0 ],[ 0,2,3,1 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 1,2,3,0 ], [ 0,2,1,3 ],[ 0,0,0,0 ],[ 0,3,1,2 ],[ 0,3,2,1 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 1,3,2,0 ], [ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ], @@ -54,149 +54,149 @@ SimplexNoise.prototype.dot = function(g, x, y) { }; SimplexNoise.prototype.dot3 = function(g, x, y, z) { - return g[0] * x + g[1] * y + g[2] * z; + return g[0] * x + g[1] * y + g[2] * z; } SimplexNoise.prototype.dot4 = function(g, x, y, z, w) { - return g[0] * x + g[1] * y + g[2] * z + g[3] * w; + return g[0] * x + g[1] * y + g[2] * z + g[3] * w; }; SimplexNoise.prototype.noise = function(xin, yin) { - var n0, n1, n2; // Noise contributions from the three corners + var n0, n1, n2; // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in - var F2 = 0.5 * (Math.sqrt(3.0) - 1.0); - var s = (xin + yin) * F2; // Hairy factor for 2D - var i = Math.floor(xin + s); - var j = Math.floor(yin + s); - var G2 = (3.0 - Math.sqrt(3.0)) / 6.0; - var t = (i + j) * G2; - var X0 = i - t; // Unskew the cell origin back to (x,y) space - var Y0 = j - t; - var x0 = xin - X0; // The x,y distances from the cell origin - var y0 = yin - Y0; + var F2 = 0.5 * (Math.sqrt(3.0) - 1.0); + var s = (xin + yin) * F2; // Hairy factor for 2D + var i = Math.floor(xin + s); + var j = Math.floor(yin + s); + var G2 = (3.0 - Math.sqrt(3.0)) / 6.0; + var t = (i + j) * G2; + var X0 = i - t; // Unskew the cell origin back to (x,y) space + var Y0 = j - t; + var x0 = xin - X0; // The x,y distances from the cell origin + var y0 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. - var i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords - if (x0 > y0) {i1 = 1; j1 = 0;} // lower triangle, XY order: (0,0)->(1,0)->(1,1) - else {i1 = 0; j1 = 1;} // upper triangle, YX order: (0,0)->(0,1)->(1,1) + var i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords + if (x0 > y0) {i1 = 1; j1 = 0;} // lower triangle, XY order: (0,0)->(1,0)->(1,1) + else {i1 = 0; j1 = 1;} // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 - var x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords - var y1 = y0 - j1 + G2; - var x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords - var y2 = y0 - 1.0 + 2.0 * G2; + var x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + var y1 = y0 - j1 + G2; + var x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords + var y2 = y0 - 1.0 + 2.0 * G2; // Work out the hashed gradient indices of the three simplex corners - var ii = i & 255; - var jj = j & 255; - var gi0 = this.perm[ii + this.perm[jj]] % 12; - var gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12; - var gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12; + var ii = i & 255; + var jj = j & 255; + var gi0 = this.perm[ii + this.perm[jj]] % 12; + var gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12; + var gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12; // Calculate the contribution from the three corners - var t0 = 0.5 - x0 * x0 - y0 * y0; - if (t0 < 0) n0 = 0.0; - else { - t0 *= t0; - n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient - } - var t1 = 0.5 - x1 * x1 - y1 * y1; - if (t1 < 0) n1 = 0.0; - else { - t1 *= t1; - n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1); - } - var t2 = 0.5 - x2 * x2 - y2 * y2; - if (t2 < 0) n2 = 0.0; - else { - t2 *= t2; - n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2); - } + var t0 = 0.5 - x0 * x0 - y0 * y0; + if (t0 < 0) n0 = 0.0; + else { + t0 *= t0; + n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient + } + var t1 = 0.5 - x1 * x1 - y1 * y1; + if (t1 < 0) n1 = 0.0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1); + } + var t2 = 0.5 - x2 * x2 - y2 * y2; + if (t2 < 0) n2 = 0.0; + else { + t2 *= t2; + n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2); + } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. - return 70.0 * (n0 + n1 + n2); + return 70.0 * (n0 + n1 + n2); }; // 3D simplex noise SimplexNoise.prototype.noise3d = function(xin, yin, zin) { - var n0, n1, n2, n3; // Noise contributions from the four corners + var n0, n1, n2, n3; // Noise contributions from the four corners // Skew the input space to determine which simplex cell we're in - var F3 = 1.0 / 3.0; - var s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D - var i = Math.floor(xin + s); - var j = Math.floor(yin + s); - var k = Math.floor(zin + s); - var G3 = 1.0 / 6.0; // Very nice and simple unskew factor, too - var t = (i + j + k) * G3; - var X0 = i - t; // Unskew the cell origin back to (x,y,z) space - var Y0 = j - t; - var Z0 = k - t; - var x0 = xin - X0; // The x,y,z distances from the cell origin - var y0 = yin - Y0; - var z0 = zin - Z0; + var F3 = 1.0 / 3.0; + var s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D + var i = Math.floor(xin + s); + var j = Math.floor(yin + s); + var k = Math.floor(zin + s); + var G3 = 1.0 / 6.0; // Very nice and simple unskew factor, too + var t = (i + j + k) * G3; + var X0 = i - t; // Unskew the cell origin back to (x,y,z) space + var Y0 = j - t; + var Z0 = k - t; + var x0 = xin - X0; // The x,y,z distances from the cell origin + var y0 = yin - Y0; + var z0 = zin - Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. - var i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords - var i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords - if (x0 >= y0) { - if (y0 >= z0) + var i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords + var i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords + if (x0 >= y0) { + if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // X Y Z order else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } // X Z Y order - else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } // Z X Y order - } - else { // x0 y0) ? 32 : 0; - var c2 = (x0 > z0) ? 16 : 0; - var c3 = (y0 > z0) ? 8 : 0; - var c4 = (x0 > w0) ? 4 : 0; - var c5 = (y0 > w0) ? 2 : 0; - var c6 = (z0 > w0) ? 1 : 0; - var c = c1 + c2 + c3 + c4 + c5 + c6; - var i1, j1, k1, l1; // The integer offsets for the second simplex corner - var i2, j2, k2, l2; // The integer offsets for the third simplex corner - var i3, j3, k3, l3; // The integer offsets for the fourth simplex corner + var c1 = (x0 > y0) ? 32 : 0; + var c2 = (x0 > z0) ? 16 : 0; + var c3 = (y0 > z0) ? 8 : 0; + var c4 = (x0 > w0) ? 4 : 0; + var c5 = (y0 > w0) ? 2 : 0; + var c6 = (z0 > w0) ? 1 : 0; + var c = c1 + c2 + c3 + c4 + c5 + c6; + var i1, j1, k1, l1; // The integer offsets for the second simplex corner + var i2, j2, k2, l2; // The integer offsets for the third simplex corner + var i3, j3, k3, l3; // The integer offsets for the fourth simplex corner // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. // Many values of c will never occur, since e.g. x>y>z>w makes x= 3 ? 1 : 0; - j1 = simplex[c][1] >= 3 ? 1 : 0; - k1 = simplex[c][2] >= 3 ? 1 : 0; - l1 = simplex[c][3] >= 3 ? 1 : 0; + i1 = simplex[c][0] >= 3 ? 1 : 0; + j1 = simplex[c][1] >= 3 ? 1 : 0; + k1 = simplex[c][2] >= 3 ? 1 : 0; + l1 = simplex[c][3] >= 3 ? 1 : 0; // The number 2 in the "simplex" array is at the second largest coordinate. - i2 = simplex[c][0] >= 2 ? 1 : 0; - j2 = simplex[c][1] >= 2 ? 1 : 0; k2 = simplex[c][2] >= 2 ? 1 : 0; - l2 = simplex[c][3] >= 2 ? 1 : 0; + i2 = simplex[c][0] >= 2 ? 1 : 0; + j2 = simplex[c][1] >= 2 ? 1 : 0; k2 = simplex[c][2] >= 2 ? 1 : 0; + l2 = simplex[c][3] >= 2 ? 1 : 0; // The number 1 in the "simplex" array is at the second smallest coordinate. - i3 = simplex[c][0] >= 1 ? 1 : 0; - j3 = simplex[c][1] >= 1 ? 1 : 0; - k3 = simplex[c][2] >= 1 ? 1 : 0; - l3 = simplex[c][3] >= 1 ? 1 : 0; + i3 = simplex[c][0] >= 1 ? 1 : 0; + j3 = simplex[c][1] >= 1 ? 1 : 0; + k3 = simplex[c][2] >= 1 ? 1 : 0; + l3 = simplex[c][3] >= 1 ? 1 : 0; // The fifth corner has all coordinate offsets = 1, so no need to look that up. - var x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords - var y1 = y0 - j1 + G4; - var z1 = z0 - k1 + G4; - var w1 = w0 - l1 + G4; - var x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords - var y2 = y0 - j2 + 2.0 * G4; - var z2 = z0 - k2 + 2.0 * G4; - var w2 = w0 - l2 + 2.0 * G4; - var x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords - var y3 = y0 - j3 + 3.0 * G4; - var z3 = z0 - k3 + 3.0 * G4; - var w3 = w0 - l3 + 3.0 * G4; - var x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords - var y4 = y0 - 1.0 + 4.0 * G4; - var z4 = z0 - 1.0 + 4.0 * G4; - var w4 = w0 - 1.0 + 4.0 * G4; + var x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords + var y1 = y0 - j1 + G4; + var z1 = z0 - k1 + G4; + var w1 = w0 - l1 + G4; + var x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords + var y2 = y0 - j2 + 2.0 * G4; + var z2 = z0 - k2 + 2.0 * G4; + var w2 = w0 - l2 + 2.0 * G4; + var x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords + var y3 = y0 - j3 + 3.0 * G4; + var z3 = z0 - k3 + 3.0 * G4; + var w3 = w0 - l3 + 3.0 * G4; + var x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords + var y4 = y0 - 1.0 + 4.0 * G4; + var z4 = z0 - 1.0 + 4.0 * G4; + var w4 = w0 - 1.0 + 4.0 * G4; // Work out the hashed gradient indices of the five simplex corners - var ii = i & 255; - var jj = j & 255; - var kk = k & 255; - var ll = l & 255; - var gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; - var gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; - var gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; - var gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; - var gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; + var ii = i & 255; + var jj = j & 255; + var kk = k & 255; + var ll = l & 255; + var gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; + var gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; + var gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; + var gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; + var gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; // Calculate the contribution from the five corners - var t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; - if (t0 < 0) n0 = 0.0; - else { - t0 *= t0; - n0 = t0 * t0 * this.dot4(grad4[gi0], x0, y0, z0, w0); - } - var t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; - if (t1 < 0) n1 = 0.0; - else { - t1 *= t1; - n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1); - } - var t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; - if (t2 < 0) n2 = 0.0; - else { - t2 *= t2; - n2 = t2 * t2 * this.dot4(grad4[gi2], x2, y2, z2, w2); - } var t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; - if (t3 < 0) n3 = 0.0; - else { - t3 *= t3; - n3 = t3 * t3 * this.dot4(grad4[gi3], x3, y3, z3, w3); - } - var t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; - if (t4 < 0) n4 = 0.0; - else { - t4 *= t4; - n4 = t4 * t4 * this.dot4(grad4[gi4], x4, y4, z4, w4); - } + var t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; + if (t0 < 0) n0 = 0.0; + else { + t0 *= t0; + n0 = t0 * t0 * this.dot4(grad4[gi0], x0, y0, z0, w0); + } + var t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; + if (t1 < 0) n1 = 0.0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1); + } + var t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; + if (t2 < 0) n2 = 0.0; + else { + t2 *= t2; + n2 = t2 * t2 * this.dot4(grad4[gi2], x2, y2, z2, w2); + } var t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; + if (t3 < 0) n3 = 0.0; + else { + t3 *= t3; + n3 = t3 * t3 * this.dot4(grad4[gi3], x3, y3, z3, w3); + } + var t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; + if (t4 < 0) n4 = 0.0; + else { + t4 *= t4; + n4 = t4 * t4 * this.dot4(grad4[gi4], x4, y4, z4, w4); + } // Sum up and scale the result to cover the range [-1,1] - return 27.0 * (n0 + n1 + n2 + n3 + n4); + return 27.0 * (n0 + n1 + n2 + n3 + n4); }; diff --git a/examples/js/Sparks.js b/examples/js/Sparks.js index 5d2fdea3e8..230d39cd06 100644 --- a/examples/js/Sparks.js +++ b/examples/js/Sparks.js @@ -19,18 +19,18 @@ var SPARKS = {}; SPARKS.Emitter = function (counter) { - this._counter = counter ? counter : new SPARKS.SteadyCounter(10); // provides number of particles to produce + this._counter = counter ? counter : new SPARKS.SteadyCounter(10); // provides number of particles to produce - this._particles = []; + this._particles = []; - this._initializers = []; // use for creation of particles - this._actions = []; // uses action to update particles - this._activities = []; // not supported yet + this._initializers = []; // use for creation of particles + this._actions = []; // uses action to update particles + this._activities = []; // not supported yet - this._handlers = []; + this._handlers = []; - this.callbacks = {}; + this.callbacks = {}; }; @@ -99,108 +99,108 @@ SPARKS.Emitter.prototype = { // Update particle engine in seconds, not milliseconds update: function(time) { - var i, j; - var len = this._counter.updateEmitter( this, time ); + var i, j; + var len = this._counter.updateEmitter( this, time ); // Create particles - for ( i = 0; i < len; i ++ ) { - this.createParticle(); - } + for ( i = 0; i < len; i ++ ) { + this.createParticle(); + } // Update activities - len = this._activities.length; - for ( i = 0; i < len; i ++ ) + len = this._activities.length; + for ( i = 0; i < len; i ++ ) { - this._activities[i].update( this, time ); - } + this._activities[i].update( this, time ); + } - len = this._actions.length; + len = this._actions.length; - var particle; - var action; - var len2 = this._particles.length; + var particle; + var action; + var len2 = this._particles.length; - for ( j = 0; j < len; j ++ ) + for ( j = 0; j < len; j ++ ) { - action = this._actions[j]; - for ( i = 0; i < len2; ++ i ) + action = this._actions[j]; + for ( i = 0; i < len2; ++ i ) { - particle = this._particles[i]; - action.update( this, particle, time ); - } - } + particle = this._particles[i]; + action.update( this, particle, time ); + } + } // remove dead particles - for ( i = len2; i --; ) + for ( i = len2; i --; ) { - particle = this._particles[i]; - if ( particle.isDead ) + particle = this._particles[i]; + if ( particle.isDead ) { //particle = - this._particles.splice( i, 1 ); - this.dispatchEvent("dead", particle); - SPARKS.VectorPool.release(particle.position); // - SPARKS.VectorPool.release(particle.velocity); + this._particles.splice( i, 1 ); + this.dispatchEvent("dead", particle); + SPARKS.VectorPool.release(particle.position); // + SPARKS.VectorPool.release(particle.velocity); - } else { - this.dispatchEvent("updated", particle); - } - } + } else { + this.dispatchEvent("updated", particle); + } + } - this.dispatchEvent("loopUpdated"); + this.dispatchEvent("loopUpdated"); }, createParticle: function() { - var particle = new SPARKS.Particle(); + var particle = new SPARKS.Particle(); // In future, use a Particle Factory - var len = this._initializers.length, i; + var len = this._initializers.length, i; - for ( i = 0; i < len; i ++ ) { - this._initializers[i].initialize( this, particle ); - } + for ( i = 0; i < len; i ++ ) { + this._initializers[i].initialize( this, particle ); + } - this._particles.push( particle ); + this._particles.push( particle ); - this.dispatchEvent("created", particle); // ParticleCreated + this.dispatchEvent("created", particle); // ParticleCreated - return particle; + return particle; }, addInitializer: function (initializer) { - this._initializers.push(initializer); + this._initializers.push(initializer); }, addAction: function (action) { - this._actions.push(action); + this._actions.push(action); }, removeInitializer: function (initializer) { - var index = this._initializers.indexOf(initializer); - if (index > -1) { - this._initializers.splice( index, 1 ); - } + var index = this._initializers.indexOf(initializer); + if (index > -1) { + this._initializers.splice( index, 1 ); + } }, removeAction: function (action) { - var index = this._actions.indexOf(action); - if (index > -1) { - this._actions.splice( index, 1 ); - } + var index = this._actions.indexOf(action); + if (index > -1) { + this._actions.splice( index, 1 ); + } //console.log('removeAction', index, this._actions); }, addCallback: function(name, callback) { - this.callbacks[name] = callback; + this.callbacks[name] = callback; }, dispatchEvent: function(name, args) { - var callback = this.callbacks[name]; - if (callback) { - callback(args); - } + var callback = this.callbacks[name]; + if (callback) { + callback(args); + } } @@ -227,7 +227,7 @@ SPARKS.EVENT_LOOP_UPDATED = "loopUpdated"; // Number of particles per seconds SPARKS.SteadyCounter = function(rate) { - this.rate = rate; + this.rate = rate; // we use a shortfall counter to make up for slow emitters this.leftover = 0; @@ -277,31 +277,31 @@ SPARKS.Particle = function() { /** * The lifetime of the particle, in seconds. */ - this.lifetime = 0; + this.lifetime = 0; /** * The age of the particle, in seconds. */ - this.age = 0; + this.age = 0; /** * The energy of the particle. */ - this.energy = 1; + this.energy = 1; /** * Whether the particle is dead and should be removed from the stage. */ - this.isDead = false; + this.isDead = false; - this.target = null; // tag + this.target = null; // tag /** * For 3D */ - this.position = SPARKS.VectorPool.get().set(0, 0, 0); //new THREE.Vector3( 0, 0, 0 ); - this.velocity = SPARKS.VectorPool.get().set(0, 0, 0); //new THREE.Vector3( 0, 0, 0 ); + this.position = SPARKS.VectorPool.get().set(0, 0, 0); //new THREE.Vector3( 0, 0, 0 ); + this.velocity = SPARKS.VectorPool.get().set(0, 0, 0); //new THREE.Vector3( 0, 0, 0 ); this._oldvelocity = SPARKS.VectorPool.get().set(0, 0, 0); // rotation vec3 // angVelocity vec3 @@ -317,26 +317,26 @@ SPARKS.Particle = function() { * update function *********************************/ SPARKS.Action = function() { - this._priority = 0; + this._priority = 0; }; SPARKS.Age = function(easing) { - this._easing = (easing == null) ? TWEEN.Easing.Linear.None : easing; + this._easing = (easing == null) ? TWEEN.Easing.Linear.None : easing; }; SPARKS.Age.prototype.update = function (emitter, particle, time) { - particle.age += time; - if ( particle.age >= particle.lifetime ) + particle.age += time; + if ( particle.age >= particle.lifetime ) { - particle.energy = 0; - particle.isDead = true; - } + particle.energy = 0; + particle.isDead = true; + } else - { - var t = this._easing(particle.age / particle.lifetime); - particle.energy = -1 * t + 1; - } + { + var t = this._easing(particle.age / particle.lifetime); + particle.energy = -1 * t + 1; + } }; /* @@ -360,9 +360,9 @@ SPARKS.Move = function() { SPARKS.Move.prototype.update = function(emitter, particle, time) { // attempt verlet velocity updating. - var p = particle.position; + var p = particle.position; var v = particle.velocity; - var old = particle._oldvelocity; + var old = particle._oldvelocity; if (this._velocityVerlet) { p.x += (v.x + old.x) * 0.5 * time; @@ -384,12 +384,12 @@ SPARKS.Move.prototype.update = function(emitter, particle, time) { /* Marks particles found in specified zone dead */ SPARKS.DeathZone = function(zone) { - this.zone = zone; + this.zone = zone; }; SPARKS.DeathZone.prototype.update = function(emitter, particle, time) { - if (this.zone.contains(particle.position)) { + if (this.zone.contains(particle.position)) { particle.isDead = true; } @@ -400,12 +400,12 @@ SPARKS.DeathZone.prototype.update = function(emitter, particle, time) { */ SPARKS.ActionZone = function(action, zone) { this.action = action; - this.zone = zone; + this.zone = zone; }; SPARKS.ActionZone.prototype.update = function(emitter, particle, time) { - if (this.zone.contains(particle.position)) { + if (this.zone.contains(particle.position)) { this.action.update( emitter, particle, time ); } @@ -421,20 +421,20 @@ SPARKS.Accelerate = function(x,y,z) { return; } - this.acceleration = new THREE.Vector3(x,y,z); + this.acceleration = new THREE.Vector3(x,y,z); }; SPARKS.Accelerate.prototype.update = function(emitter, particle, time) { - var acc = this.acceleration; + var acc = this.acceleration; - var v = particle.velocity; + var v = particle.velocity; particle._oldvelocity.set(v.x, v.y, v.z); - v.x += acc.x * time; - v.y += acc.y * time; - v.z += acc.z * time; + v.x += acc.x * time; + v.y += acc.y * time; + v.z += acc.z * time; }; @@ -442,16 +442,16 @@ SPARKS.Accelerate.prototype.update = function(emitter, particle, time) { * Accelerate Factor accelerate based on a factor of particle's velocity. */ SPARKS.AccelerateFactor = function(factor) { - this.factor = factor; + this.factor = factor; }; SPARKS.AccelerateFactor.prototype.update = function(emitter, particle, time) { - var factor = this.factor; + var factor = this.factor; - var v = particle.velocity; + var v = particle.velocity; var len = v.length(); var adjFactor; - if (len > 0) { + if (len > 0) { adjFactor = factor * time / len; adjFactor += 1; @@ -475,14 +475,14 @@ SPARKS.AccelerateVelocity = function(factor) { }; SPARKS.AccelerateVelocity.prototype.update = function(emitter, particle, time) { - var factor = this.factor; + var factor = this.factor; - var v = particle.velocity; + var v = particle.velocity; - v.z += - v.x * factor; - v.y += v.z * factor; - v.x += v.y * factor; + v.z += - v.x * factor; + v.y += v.z * factor; + v.x += v.y * factor; }; @@ -494,18 +494,18 @@ SPARKS.RandomDrift = function(x,y,z) { return; } - this.drift = new THREE.Vector3(x,y,z); + this.drift = new THREE.Vector3(x,y,z); } SPARKS.RandomDrift.prototype.update = function(emitter, particle, time) { - var drift = this.drift; + var drift = this.drift; - var v = particle.velocity; + var v = particle.velocity; - v.x += ( Math.random() - 0.5 ) * drift.x * time; - v.y += ( Math.random() - 0.5 ) * drift.y * time; - v.z += ( Math.random() - 0.5 ) * drift.z * time; + v.x += ( Math.random() - 0.5 ) * drift.x * time; + v.y += ( Math.random() - 0.5 ) * drift.y * time; + v.z += ( Math.random() - 0.5 ) * drift.z * time; }; @@ -521,29 +521,29 @@ SPARKS.Zone = function() { // TODO, contains() for Zone SPARKS.PointZone = function(pos) { - this.pos = pos; + this.pos = pos; }; SPARKS.PointZone.prototype.getLocation = function() { - return this.pos; + return this.pos; }; SPARKS.PointZone = function(pos) { - this.pos = pos; + this.pos = pos; }; SPARKS.PointZone.prototype.getLocation = function() { - return this.pos; + return this.pos; }; SPARKS.LineZone = function(start, end) { - this.start = start; + this.start = start; this.end = end; this._length = end.clone().sub( start ); }; SPARKS.LineZone.prototype.getLocation = function() { - var len = this._length.clone(); + var len = this._length.clone(); len.multiplyScalar( Math.random() ); return len.add( this.start ); @@ -552,7 +552,7 @@ SPARKS.LineZone.prototype.getLocation = function() { // Basically a RectangleZone SPARKS.ParallelogramZone = function(corner, side1, side2) { - this.corner = corner; + this.corner = corner; this.side1 = side1; this.side2 = side2; }; @@ -567,7 +567,7 @@ SPARKS.ParallelogramZone.prototype.getLocation = function() { }; SPARKS.CubeZone = function(position, x, y, z) { - this.position = position; + this.position = position; this.x = x; this.y = y; this.z = z; @@ -674,29 +674,29 @@ SPARKS.DiscZone.prototype.getLocation = function() { */ SPARKS.SphereCapZone = function(x, y, z, minr, maxr, angle) { - this.x = x; - this.y = y; - this.z = z; - this.minr = minr; - this.maxr = maxr; - this.angle = angle; + this.x = x; + this.y = y; + this.z = z; + this.minr = minr; + this.maxr = maxr; + this.angle = angle; }; SPARKS.SphereCapZone.prototype.getLocation = function() { - var theta = Math.PI * 2 * SPARKS.Utils.random(); - var r = SPARKS.Utils.random(); + var theta = Math.PI * 2 * SPARKS.Utils.random(); + var r = SPARKS.Utils.random(); //new THREE.Vector3 - var v = SPARKS.VectorPool.get().set(r * Math.cos(theta), -1 / Math.tan(this.angle * SPARKS.Utils.DEGREE_TO_RADIAN), r * Math.sin(theta)); + var v = SPARKS.VectorPool.get().set(r * Math.cos(theta), -1 / Math.tan(this.angle * SPARKS.Utils.DEGREE_TO_RADIAN), r * Math.sin(theta)); //v.length = StardustMath.interpolate(0, _minRadius, 1, _maxRadius, Math.random()); - var i = this.minr - ((this.minr - this.maxr) * Math.random() ); - v.multiplyScalar(i); + var i = this.minr - ((this.minr - this.maxr) * Math.random() ); + v.multiplyScalar(i); v.__markedForReleased = true; - return v; + return v; }; @@ -709,33 +709,33 @@ SPARKS.SphereCapZone.prototype.getLocation = function() { // Specifies random life between max and min SPARKS.Lifetime = function(min, max) { - this._min = min; + this._min = min; - this._max = max ? max : min; + this._max = max ? max : min; }; SPARKS.Lifetime.prototype.initialize = function( emitter/*Emitter*/, particle/*Particle*/ ) { - particle.lifetime = this._min + SPARKS.Utils.random() * ( this._max - this._min ); + particle.lifetime = this._min + SPARKS.Utils.random() * ( this._max - this._min ); }; SPARKS.Position = function(zone) { - this.zone = zone; + this.zone = zone; }; SPARKS.Position.prototype.initialize = function( emitter/*Emitter*/, particle/*Particle*/ ) { - var pos = this.zone.getLocation(); - particle.position.set(pos.x, pos.y, pos.z); + var pos = this.zone.getLocation(); + particle.position.set(pos.x, pos.y, pos.z); }; SPARKS.Velocity = function(zone) { - this.zone = zone; + this.zone = zone; }; SPARKS.Velocity.prototype.initialize = function( emitter/*Emitter*/, particle/*Particle*/ ) { - var pos = this.zone.getLocation(); - particle.velocity.set(pos.x, pos.y, pos.z); + var pos = this.zone.getLocation(); + particle.velocity.set(pos.x, pos.y, pos.z); if (pos.__markedForReleased) { //console.log("release"); SPARKS.VectorPool.release(pos); @@ -744,17 +744,17 @@ SPARKS.Velocity.prototype.initialize = function( emitter/*Emitter*/, particle/*P }; SPARKS.Target = function(target, callback) { - this.target = target; - this.callback = callback; + this.target = target; + this.callback = callback; }; SPARKS.Target.prototype.initialize = function( emitter, particle ) { - if (this.callback) { - particle.target = this.callback(); - } else { - particle.target = this.target; - } + if (this.callback) { + particle.target = this.callback(); + } else { + particle.target = this.target; + } }; @@ -807,7 +807,7 @@ SPARKS.VectorPool = { *********************************/ SPARKS.Utils = { random: function() { - return Math.random(); + return Math.random(); }, DEGREE_TO_RADIAN: Math.PI / 180, TWOPI: Math.PI * 2, diff --git a/examples/js/controls/MouseControls.js b/examples/js/controls/MouseControls.js index d8295ab8e1..470e50768b 100644 --- a/examples/js/controls/MouseControls.js +++ b/examples/js/controls/MouseControls.js @@ -6,50 +6,50 @@ THREE.MouseControls = function ( object ) { - var scope = this; - var PI_2 = Math.PI / 2; - var mouseQuat = { + var scope = this; + var PI_2 = Math.PI / 2; + var mouseQuat = { x: new THREE.Quaternion(), y: new THREE.Quaternion() }; - var object = object; - var xVector = new THREE.Vector3( 1, 0, 0 ); - var yVector = new THREE.Vector3( 0, 1, 0 ); + var object = object; + var xVector = new THREE.Vector3( 1, 0, 0 ); + var yVector = new THREE.Vector3( 0, 1, 0 ); - var onMouseMove = function ( event ) { + var onMouseMove = function ( event ) { - if ( scope.enabled === false ) return; + if ( scope.enabled === false ) return; - var orientation = scope.orientation; + var orientation = scope.orientation; - var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0; - var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0; + var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0; + var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0; - orientation.y += movementX * 0.0025; - orientation.x += movementY * 0.0025; + orientation.y += movementX * 0.0025; + orientation.x += movementY * 0.0025; - orientation.x = Math.max( - PI_2, Math.min( PI_2, orientation.x ) ); + orientation.x = Math.max( - PI_2, Math.min( PI_2, orientation.x ) ); - }; + }; - this.enabled = true; + this.enabled = true; - this.orientation = { + this.orientation = { x: 0, y: 0, }; - this.update = function() { + this.update = function() { - if ( this.enabled === false ) return; + if ( this.enabled === false ) return; - mouseQuat.x.setFromAxisAngle( xVector, this.orientation.x ); - mouseQuat.y.setFromAxisAngle( yVector, this.orientation.y ); - object.quaternion.copy(mouseQuat.y).multiply(mouseQuat.x) - return; + mouseQuat.x.setFromAxisAngle( xVector, this.orientation.x ); + mouseQuat.y.setFromAxisAngle( yVector, this.orientation.y ); + object.quaternion.copy(mouseQuat.y).multiply(mouseQuat.x) + return; - }; + }; - document.addEventListener( 'mousemove', onMouseMove, false ); + document.addEventListener( 'mousemove', onMouseMove, false ); }; diff --git a/examples/js/controls/TransformControls.js b/examples/js/controls/TransformControls.js index 809c28374d..a87b41a5dc 100644 --- a/examples/js/controls/TransformControls.js +++ b/examples/js/controls/TransformControls.js @@ -30,8 +30,8 @@ } else { - this.color.copy( this.oldColor ); - this.opacity = this.oldOpacity; + this.color.copy( this.oldColor ); + this.opacity = this.oldOpacity; } @@ -65,8 +65,8 @@ } else { - this.color.copy( this.oldColor ); - this.opacity = this.oldOpacity; + this.color.copy( this.oldColor ); + this.opacity = this.oldOpacity; } @@ -331,15 +331,15 @@ var CircleGeometry = function ( radius, facing, arc ) { - var geometry = new THREE.Geometry(); - arc = arc ? arc : 1; - for ( var i = 0; i <= 64 * arc; ++ i ) { - if ( facing == 'x' ) geometry.vertices.push( new THREE.Vector3( 0, Math.cos( i / 32 * Math.PI ), Math.sin( i / 32 * Math.PI ) ).multiplyScalar(radius) ); - if ( facing == 'y' ) geometry.vertices.push( new THREE.Vector3( Math.cos( i / 32 * Math.PI ), 0, Math.sin( i / 32 * Math.PI ) ).multiplyScalar(radius) ); - if ( facing == 'z' ) geometry.vertices.push( new THREE.Vector3( Math.sin( i / 32 * Math.PI ), Math.cos( i / 32 * Math.PI ), 0 ).multiplyScalar(radius) ); - } + var geometry = new THREE.Geometry(); + arc = arc ? arc : 1; + for ( var i = 0; i <= 64 * arc; ++ i ) { + if ( facing == 'x' ) geometry.vertices.push( new THREE.Vector3( 0, Math.cos( i / 32 * Math.PI ), Math.sin( i / 32 * Math.PI ) ).multiplyScalar(radius) ); + if ( facing == 'y' ) geometry.vertices.push( new THREE.Vector3( Math.cos( i / 32 * Math.PI ), 0, Math.sin( i / 32 * Math.PI ) ).multiplyScalar(radius) ); + if ( facing == 'z' ) geometry.vertices.push( new THREE.Vector3( Math.sin( i / 32 * Math.PI ), Math.cos( i / 32 * Math.PI ), 0 ).multiplyScalar(radius) ); + } - return geometry; + return geometry; }; this.handleGizmos = { diff --git a/examples/js/effects/VREffect.js b/examples/js/effects/VREffect.js index 8e71ea7f2d..1c48e2fede 100644 --- a/examples/js/effects/VREffect.js +++ b/examples/js/effects/VREffect.js @@ -56,7 +56,7 @@ THREE.VREffect = function ( renderer, done ) { } if ( done ) { if ( !vrHMD ) { - error = 'HMD not available'; + error = 'HMD not available'; } done( error ); } diff --git a/examples/js/geometries/ConvexGeometry.js b/examples/js/geometries/ConvexGeometry.js index 37b41a6430..57f10fff13 100644 --- a/examples/js/geometries/ConvexGeometry.js +++ b/examples/js/geometries/ConvexGeometry.js @@ -176,14 +176,14 @@ THREE.ConvexGeometry = function( vertices ) { for ( var j = 0; j < 3; j ++ ) { - if ( newId[ face[ j ] ] === undefined ) { + if ( newId[ face[ j ] ] === undefined ) { - newId[ face[ j ] ] = id ++; - this.vertices.push( vertices[ face[ j ] ] ); + newId[ face[ j ] ] = id ++; + this.vertices.push( vertices[ face[ j ] ] ); - } + } - face[ j ] = newId[ face[ j ] ]; + face[ j ] = newId[ face[ j ] ]; } diff --git a/examples/js/geometries/DecalGeometry.js b/examples/js/geometries/DecalGeometry.js index bc3c2cd008..c5ec7fa8ae 100644 --- a/examples/js/geometries/DecalGeometry.js +++ b/examples/js/geometries/DecalGeometry.js @@ -191,8 +191,8 @@ THREE.DecalGeometry = function( mesh, position, rotation, dimensions, check ) { vertices = this.clipFace( vertices, new THREE.Vector3( -1, 0, 0 ) ); } if ( check.y ) { - vertices = this.clipFace( vertices, new THREE.Vector3( 0, 1, 0 ) ); - vertices = this.clipFace( vertices, new THREE.Vector3( 0, -1, 0 ) ); + vertices = this.clipFace( vertices, new THREE.Vector3( 0, 1, 0 ) ); + vertices = this.clipFace( vertices, new THREE.Vector3( 0, -1, 0 ) ); } if ( check.z ) { vertices = this.clipFace( vertices, new THREE.Vector3( 0, 0, 1 ) ); diff --git a/examples/js/loaders/AWDLoader.js b/examples/js/loaders/AWDLoader.js index d0dcc1daaf..22b86d787b 100644 --- a/examples/js/loaders/AWDLoader.js +++ b/examples/js/loaders/AWDLoader.js @@ -7,7 +7,7 @@ THREE.AWDLoader = (function () { - var UNCOMPRESSED = 0, + var UNCOMPRESSED = 0, DEFLATE = 1, LZMA = 2, @@ -46,139 +46,139 @@ THREE.AWDLoader = (function () { FLOAT64 = 8; - var littleEndian = true; + var littleEndian = true; // ResourcesLoader // ============= // handle loading for external resources - function ResourcesLoader( awdUrl ) { + function ResourcesLoader( awdUrl ) { - this._baseDir = awdUrl.substr( 0, awdUrl.lastIndexOf( '/' ) + 1 ); + this._baseDir = awdUrl.substr( 0, awdUrl.lastIndexOf( '/' ) + 1 ); - this._loadingManager = new THREE.LoadingManager(); + this._loadingManager = new THREE.LoadingManager(); - } + } - ResourcesLoader.prototype = { + ResourcesLoader.prototype = { loadTexture : function( path ) { - var tex = new THREE.Texture(); + var tex = new THREE.Texture(); - var loader = new THREE.ImageLoader( this._loadingManager ); + var loader = new THREE.ImageLoader( this._loadingManager ); - loader.load( this._baseDir + path, function( image ) { - tex.image = image; - tex.needsUpdate = true; - }); + loader.load( this._baseDir + path, function( image ) { + tex.image = image; + tex.needsUpdate = true; + }); - return tex; + return tex; } } - function Block() { - this.id = 0; - this.data = null; - } + function Block() { + this.id = 0; + this.data = null; + } - function AWDLoader( showStatus ) { + function AWDLoader( showStatus ) { - THREE.Loader.call( this, showStatus ); + THREE.Loader.call( this, showStatus ); - this.trunk = new THREE.Object3D(); + this.trunk = new THREE.Object3D(); - this.materialFactory = undefined; + this.materialFactory = undefined; - this._resourceLoader = null; - this._url = ''; + this._resourceLoader = null; + this._url = ''; - this._data; - this._ptr = 0; + this._data; + this._ptr = 0; - this._version = []; - this._streaming = false; - this._optimized_for_accuracy = false; - this._compression = 0; - this._bodylen = 0xFFFFFFFF; + this._version = []; + this._streaming = false; + this._optimized_for_accuracy = false; + this._compression = 0; + this._bodylen = 0xFFFFFFFF; - this._blocks = [ new Block() ]; + this._blocks = [ new Block() ]; - this._accuracyMatrix = false; - this._accuracyGeo = false; - this._accuracyProps = false; + this._accuracyMatrix = false; + this._accuracyGeo = false; + this._accuracyProps = false; - }; + }; - AWDLoader.prototype = Object.create( THREE.Loader.prototype ); - AWDLoader.prototype.constructor = AWDLoader; + AWDLoader.prototype = Object.create( THREE.Loader.prototype ); + AWDLoader.prototype.constructor = AWDLoader; - AWDLoader.prototype.load = function ( url, callback ) { + AWDLoader.prototype.load = function ( url, callback ) { - var that = this; - this._url = url; - var xhr = new XMLHttpRequest(); - xhr.open( "GET", url, true ); - xhr.responseType = 'arraybuffer'; + var that = this; + this._url = url; + var xhr = new XMLHttpRequest(); + xhr.open( "GET", url, true ); + xhr.responseType = 'arraybuffer'; - xhr.onreadystatechange = function () { + xhr.onreadystatechange = function () { - if ( xhr.readyState == 4 ) { + if ( xhr.readyState == 4 ) { - if ( xhr.status == 200 || xhr.status == 0 ) { - that.parse( xhr.response ); - callback( that.trunk ); + if ( xhr.status == 200 || xhr.status == 0 ) { + that.parse( xhr.response ); + callback( that.trunk ); - } else { + } else { - console.error( 'AWDLoader: Couldn\'t load ' + url + ' (' + xhr.status + ')' ); + console.error( 'AWDLoader: Couldn\'t load ' + url + ' (' + xhr.status + ')' ); - } + } - } + } - }; + }; - xhr.send( null ); + xhr.send( null ); - }; + }; - AWDLoader.prototype.parse = function ( data ) { + AWDLoader.prototype.parse = function ( data ) { - var blen = data.byteLength; + var blen = data.byteLength; - this._ptr = 0; - this._data = new DataView( data ); + this._ptr = 0; + this._data = new DataView( data ); - this._parseHeader( ); + this._parseHeader( ); - if ( this._compression != 0 ) { - console.error( 'compressed AWD not supported' ); - } + if ( this._compression != 0 ) { + console.error( 'compressed AWD not supported' ); + } - if (!this._streaming && this._bodylen != data.byteLength - this._ptr ) { - console.error('AWDLoader: body len does not match file length', this._bodylen, blen - this._ptr); - } + if (!this._streaming && this._bodylen != data.byteLength - this._ptr ) { + console.error('AWDLoader: body len does not match file length', this._bodylen, blen - this._ptr); + } - while ( this._ptr < blen ) { - this.parseNextBlock(); - } + while ( this._ptr < blen ) { + this.parseNextBlock(); + } - return this.trunk; + return this.trunk; - } + } - AWDLoader.prototype.parseNextBlock = function ( ) { + AWDLoader.prototype.parseNextBlock = function ( ) { - var assetData, + var assetData, ns, type, len, block, blockId = this.readU32(), ns = this.readU8(), @@ -187,127 +187,127 @@ THREE.AWDLoader = (function () { len = this.readU32(); - switch (type) { - case 1: - assetData = this.parseMeshData(len); - break; - case 22: - assetData = this.parseContainer(len); - break; - case 23: - assetData = this.parseMeshInstance(len); - break; - case 81: - assetData = this.parseMaterial(len); - break; - case 82: - assetData = this.parseTexture(len); - break; - case 101: - assetData = this.parseSkeleton(len); - break; + switch (type) { + case 1: + assetData = this.parseMeshData(len); + break; + case 22: + assetData = this.parseContainer(len); + break; + case 23: + assetData = this.parseMeshInstance(len); + break; + case 81: + assetData = this.parseMaterial(len); + break; + case 82: + assetData = this.parseTexture(len); + break; + case 101: + assetData = this.parseSkeleton(len); + break; // case 111: // assetData = this.parseMeshPoseAnimation(len, true); // break; - case 112: - assetData = this.parseMeshPoseAnimation(len, false); - break; - case 113: - assetData = this.parseVertexAnimationSet(len); - break; - case 102: - assetData = this.parseSkeletonPose(len); - break; - case 103: - assetData = this.parseSkeletonAnimation(len); - break; - case 122: - assetData = this.parseAnimatorSet(len); - break; + case 112: + assetData = this.parseMeshPoseAnimation(len, false); + break; + case 113: + assetData = this.parseVertexAnimationSet(len); + break; + case 102: + assetData = this.parseSkeletonPose(len); + break; + case 103: + assetData = this.parseSkeletonAnimation(len); + break; + case 122: + assetData = this.parseAnimatorSet(len); + break; // case 121: // assetData = parseUVAnimation(len); // break; - default: + default: //debug('Ignoring block!',type, len); - this._ptr += len; - break; - } + this._ptr += len; + break; + } // Store block reference for later use - this._blocks[blockId] = block = new Block(); - block.data = assetData; - block.id = blockId; + this._blocks[blockId] = block = new Block(); + block.data = assetData; + block.id = blockId; - } + } - AWDLoader.prototype._parseHeader = function () { + AWDLoader.prototype._parseHeader = function () { - var version = this._version, + var version = this._version, awdmagic = ( this.readU8()<<16) | ( this.readU8()<<8 ) | this.readU8(); - if ( awdmagic != 4282180 ) + if ( awdmagic != 4282180 ) throw new Error( "AWDLoader - bad magic" ); - version[0] = this.readU8(); - version[1] = this.readU8(); + version[0] = this.readU8(); + version[1] = this.readU8(); - var flags = this.readU16(); + var flags = this.readU16(); - this._streaming = (flags & 0x1) == 0x1; + this._streaming = (flags & 0x1) == 0x1; - if ((version[0] === 2) && (version[1] === 1)) { - this._accuracyMatrix = (flags & 0x2) === 0x2; - this._accuracyGeo = (flags & 0x4) === 0x4; - this._accuracyProps = (flags & 0x8) === 0x8; - } + if ((version[0] === 2) && (version[1] === 1)) { + this._accuracyMatrix = (flags & 0x2) === 0x2; + this._accuracyGeo = (flags & 0x4) === 0x4; + this._accuracyProps = (flags & 0x8) === 0x8; + } - this._geoNrType = this._accuracyGeo ? FLOAT64 : FLOAT32; - this._matrixNrType = this._accuracyMatrix ? FLOAT64 : FLOAT32; - this._propsNrType = this._accuracyProps ? FLOAT64 : FLOAT32; + this._geoNrType = this._accuracyGeo ? FLOAT64 : FLOAT32; + this._matrixNrType = this._accuracyMatrix ? FLOAT64 : FLOAT32; + this._propsNrType = this._accuracyProps ? FLOAT64 : FLOAT32; - this._optimized_for_accuracy = (flags & 0x2) === 0x2; + this._optimized_for_accuracy = (flags & 0x2) === 0x2; - this._compression = this.readU8(); - this._bodylen = this.readU32(); + this._compression = this.readU8(); + this._bodylen = this.readU32(); - } + } - AWDLoader.prototype.parseContainer = function ( len ) { - var parent, + AWDLoader.prototype.parseContainer = function ( len ) { + var parent, ctr = new THREE.Object3D(), par_id = this.readU32(), mtx = this.parseMatrix4(); - ctr.name = this.readUTF(); - ctr.applyMatrix( mtx ); + ctr.name = this.readUTF(); + ctr.applyMatrix( mtx ); - parent = this._blocks[par_id].data || this.trunk; - parent.add(ctr); + parent = this._blocks[par_id].data || this.trunk; + parent.add(ctr); - this.parseProperties({ + this.parseProperties({ 1:this._matrixNrType, 2:this._matrixNrType, 3:this._matrixNrType, 4:UINT8 }); - ctr.extra = this.parseUserAttributes(); + ctr.extra = this.parseUserAttributes(); - return ctr; - } + return ctr; + } - AWDLoader.prototype.parseMeshInstance = function ( len ) { - var name, + AWDLoader.prototype.parseMeshInstance = function ( len ) { + var name, mesh, geometries, meshLen, meshes, par_id, data_id, mtx, @@ -317,68 +317,68 @@ THREE.AWDLoader = (function () { parent, i; - par_id = this.readU32(); - mtx = this.parseMatrix4(); - name = this.readUTF(); - data_id = this.readU32(); - num_materials = this.readU16(); + par_id = this.readU32(); + mtx = this.parseMatrix4(); + name = this.readUTF(); + data_id = this.readU32(); + num_materials = this.readU16(); - geometries = this.getBlock( data_id ); + geometries = this.getBlock( data_id ); - materials = []; - materials_parsed = 0; + materials = []; + materials_parsed = 0; - for ( i = 0; i < num_materials; i ++) { - mat_id = this.readU32(); - mat = this.getBlock( mat_id ); - materials.push( mat ); - } + for ( i = 0; i < num_materials; i ++) { + mat_id = this.readU32(); + mat = this.getBlock( mat_id ); + materials.push( mat ); + } - meshLen = geometries.length - meshes = []; + meshLen = geometries.length + meshes = []; // TODO : BufferGeometry don't support "geometryGroups" for now. // so we create sub meshes for each groups - if ( meshLen > 1 ) { - mesh = new THREE.Object3D() - for ( i = 0; i < meshLen; i ++) { - var sm = new THREE.Mesh( geometries[i] ); - meshes.push( sm ); - mesh.add( sm ); - } - } - else { - mesh = new THREE.Mesh( geometries[0] ); - meshes.push( mesh ); - } - - mesh.applyMatrix( mtx ); - mesh.name = name; - - - parent = this.getBlock( par_id ) || this.trunk; - parent.add( mesh ); - - - var matLen = materials.length; - var maxLen = Math.max( meshLen, matLen); - for ( i = 0; i < maxLen; i ++ ) + if ( meshLen > 1 ) { + mesh = new THREE.Object3D() + for ( i = 0; i < meshLen; i ++) { + var sm = new THREE.Mesh( geometries[i] ); + meshes.push( sm ); + mesh.add( sm ); + } + } + else { + mesh = new THREE.Mesh( geometries[0] ); + meshes.push( mesh ); + } + + mesh.applyMatrix( mtx ); + mesh.name = name; + + + parent = this.getBlock( par_id ) || this.trunk; + parent.add( mesh ); + + + var matLen = materials.length; + var maxLen = Math.max( meshLen, matLen); + for ( i = 0; i < maxLen; i ++ ) meshes[ i%meshLen ].material = materials[ i % matLen ]; // Ignore for now - this.parseProperties( null ); - mesh.extra = this.parseUserAttributes(); + this.parseProperties( null ); + mesh.extra = this.parseUserAttributes(); - return mesh; - } + return mesh; + } - AWDLoader.prototype.parseMaterial = function ( len ) { - var name, + AWDLoader.prototype.parseMaterial = function ( len ) { + var name, type, props, mat, @@ -387,15 +387,15 @@ THREE.AWDLoader = (function () { num_methods, methods_parsed; - name = this.readUTF(); - type = this.readU8(); - num_methods = this.readU8(); + name = this.readUTF(); + type = this.readU8(); + num_methods = this.readU8(); //log( "AWDLoader parseMaterial ",name ) // Read material numerical properties // (1=color, 2=bitmap url, 11=alpha_blending, 12=alpha_threshold, 13=repeat) - props = this.parseProperties({ + props = this.parseProperties({ 1: AWD_FIELD_INT32, 2: AWD_FIELD_BADDR, 11: AWD_FIELD_BOOL, @@ -403,276 +403,276 @@ THREE.AWDLoader = (function () { 13: AWD_FIELD_BOOL }); - methods_parsed = 0; + methods_parsed = 0; - while ( methods_parsed < num_methods ) { - var method_type = this.readU16(); - this.parseProperties( null ); - this.parseUserAttributes(); - } + while ( methods_parsed < num_methods ) { + var method_type = this.readU16(); + this.parseProperties( null ); + this.parseUserAttributes(); + } - attributes = this.parseUserAttributes(); + attributes = this.parseUserAttributes(); - if ( this.materialFactory !== undefined ) { - mat = this.materialFactory( name ); - if ( mat ) return mat; - } + if ( this.materialFactory !== undefined ) { + mat = this.materialFactory( name ); + if ( mat ) return mat; + } - mat = new THREE.MeshPhongMaterial(); + mat = new THREE.MeshPhongMaterial(); - if (type === 1) { // Color material - mat.color.setHex( props.get(1, 0xcccccc) ); - } + if (type === 1) { // Color material + mat.color.setHex( props.get(1, 0xcccccc) ); + } else if (type === 2) { // Bitmap material - var tex_addr = props.get(2, 0); - mat.map = this.getBlock( tex_addr ); + var tex_addr = props.get(2, 0); + mat.map = this.getBlock( tex_addr ); } - mat.extra = attributes; - mat.alphaThreshold = props.get(12, 0.0); - mat.repeat = props.get(13, false); + mat.extra = attributes; + mat.alphaThreshold = props.get(12, 0.0); + mat.repeat = props.get(13, false); - return mat; - } + return mat; + } - AWDLoader.prototype.parseTexture = function( len ) { + AWDLoader.prototype.parseTexture = function( len ) { - var name = this.readUTF(), + var name = this.readUTF(), type = this.readU8(), asset, data_len; // External - if (type === 0) { - data_len = this.readU32(); - var url = this.readUTFBytes(data_len); - console.log( url ); + if (type === 0) { + data_len = this.readU32(); + var url = this.readUTFBytes(data_len); + console.log( url ); - asset = this.loadTexture( url ); - } else { + asset = this.loadTexture( url ); + } else { // embed texture not supported - } + } // Ignore for now - this.parseProperties( null ); + this.parseProperties( null ); - this.parseUserAttributes(); - return asset; - } + this.parseUserAttributes(); + return asset; + } - AWDLoader.prototype.loadTexture = function( url ) { + AWDLoader.prototype.loadTexture = function( url ) { - if ( null === this._resourceLoader ) + if ( null === this._resourceLoader ) this._resourceLoader = new ResourcesLoader( this._url ); - return this._resourceLoader.loadTexture( url ); - } + return this._resourceLoader.loadTexture( url ); + } // broken : skeleton pose format is different than threejs one - AWDLoader.prototype.parseSkeleton = function(len) // Array + AWDLoader.prototype.parseSkeleton = function(len) // Array { - var name = this.readUTF(), + var name = this.readUTF(), num_joints = this.readU16(), skeleton = [], joints_parsed = 0; - this.parseProperties( null ); + this.parseProperties( null ); - while (joints_parsed < num_joints) { - var joint, ibp; + while (joints_parsed < num_joints) { + var joint, ibp; // Ignore joint id - this.readU16(); + this.readU16(); - joint = new THREE.Bone(); - joint.parent = this.readU16() - 1; // 0=null in AWD - joint.name = this.readUTF(); + joint = new THREE.Bone(); + joint.parent = this.readU16() - 1; // 0=null in AWD + joint.name = this.readUTF(); - ibp = this.parseMatrix4(); - joint.skinMatrix = ibp; + ibp = this.parseMatrix4(); + joint.skinMatrix = ibp; // Ignore joint props/attributes for now - this.parseProperties(null); - this.parseUserAttributes(); + this.parseProperties(null); + this.parseUserAttributes(); - skeleton.push(joint); - joints_parsed ++; - } + skeleton.push(joint); + joints_parsed ++; + } // Discard attributes for now - this.parseUserAttributes(); + this.parseUserAttributes(); - return skeleton; - } + return skeleton; + } - AWDLoader.prototype.parseSkeletonPose = function(blockID) + AWDLoader.prototype.parseSkeletonPose = function(blockID) { - var name = this.readUTF(); + var name = this.readUTF(); - var num_joints = this.readU16(); - this.parseProperties(null); + var num_joints = this.readU16(); + this.parseProperties(null); // debug( 'parse Skeleton Pose. joints : ' + num_joints); - var pose = []; + var pose = []; - var joints_parsed = 0; + var joints_parsed = 0; - while (joints_parsed < num_joints) { + while (joints_parsed < num_joints) { - var joint_pose; + var joint_pose; - var has_transform; //:uint; - var mtx_data; + var has_transform; //:uint; + var mtx_data; - has_transform = this.readU8(); + has_transform = this.readU8(); - if (has_transform === 1) { - mtx_data = this.parseMatrix4(); - } else - { - mtx_data = new THREE.Matrix4(); - } - pose[joints_parsed] = mtx_data; - joints_parsed ++; - } + if (has_transform === 1) { + mtx_data = this.parseMatrix4(); + } else + { + mtx_data = new THREE.Matrix4(); + } + pose[joints_parsed] = mtx_data; + joints_parsed ++; + } // Skip attributes for now - this.parseUserAttributes(); + this.parseUserAttributes(); - return pose - } + return pose + } - AWDLoader.prototype.parseSkeletonAnimation = function(blockID) + AWDLoader.prototype.parseSkeletonAnimation = function(blockID) { - var frame_dur; - var pose_addr; - var pose; + var frame_dur; + var pose_addr; + var pose; - var name = this.readUTF(); + var name = this.readUTF(); - var clip = []; + var clip = []; - var num_frames = this.readU16(); - this.parseProperties(null); + var num_frames = this.readU16(); + this.parseProperties(null); - var frames_parsed = 0; - var returnedArray; + var frames_parsed = 0; + var returnedArray; // debug( 'parse Skeleton Animation. frames : ' + num_frames); - while (frames_parsed < num_frames) { - pose_addr = this.readU32(); - frame_dur = this.readU16(); + while (frames_parsed < num_frames) { + pose_addr = this.readU32(); + frame_dur = this.readU16(); - pose = this._blocks[pose_addr].data + pose = this._blocks[pose_addr].data // debug( 'pose address ',pose[2].elements[12],pose[2].elements[13],pose[2].elements[14] ); - clip.push( { + clip.push( { pose : pose, duration : frame_dur } ); - frames_parsed ++; - } - if (clip.length == 0) { + frames_parsed ++; + } + if (clip.length == 0) { // debug("Could not this SkeletonClipNode, because no Frames where set."); - return; - } + return; + } // Ignore attributes for now - this.parseUserAttributes(); - return clip; - } + this.parseUserAttributes(); + return clip; + } - AWDLoader.prototype.parseVertexAnimationSet = function(len) + AWDLoader.prototype.parseVertexAnimationSet = function(len) { - var poseBlockAdress, + var poseBlockAdress, name = this.readUTF(), num_frames = this.readU16(), props = this.parseProperties({ 1:UINT16 }), frames_parsed = 0, skeletonFrames = []; - while (frames_parsed < num_frames) { - poseBlockAdress = this.readU32(); - skeletonFrames.push(this._blocks[poseBlockAdress].data); - frames_parsed ++; - } + while (frames_parsed < num_frames) { + poseBlockAdress = this.readU32(); + skeletonFrames.push(this._blocks[poseBlockAdress].data); + frames_parsed ++; + } - this.parseUserAttributes(); + this.parseUserAttributes(); - return skeletonFrames; - } + return skeletonFrames; + } - AWDLoader.prototype.parseAnimatorSet = function(len) + AWDLoader.prototype.parseAnimatorSet = function(len) { - var targetMesh; + var targetMesh; - var animSetBlockAdress; //:int + var animSetBlockAdress; //:int - var targetAnimationSet; //:AnimationSetBase; - var outputString = ""; //:String = ""; - var name = this.readUTF(); - var type = this.readU16(); + var targetAnimationSet; //:AnimationSetBase; + var outputString = ""; //:String = ""; + var name = this.readUTF(); + var type = this.readU16(); - var props = this.parseProperties({ 1:BADDR }); + var props = this.parseProperties({ 1:BADDR }); - animSetBlockAdress = this.readU32(); - var targetMeshLength = this.readU16(); + animSetBlockAdress = this.readU32(); + var targetMeshLength = this.readU16(); - var meshAdresses = []; //:Vector. = new Vector.; + var meshAdresses = []; //:Vector. = new Vector.; - for (var i = 0; i < targetMeshLength; i ++) + for (var i = 0; i < targetMeshLength; i ++) meshAdresses.push( this.readU32() ); - var activeState = this.readU16(); - var autoplay = Boolean(this.readU8()); - this.parseUserAttributes(); - this.parseUserAttributes(); + var activeState = this.readU16(); + var autoplay = Boolean(this.readU8()); + this.parseUserAttributes(); + this.parseUserAttributes(); - var returnedArray; - var targetMeshes = []; //:Vector. = new Vector.; + var returnedArray; + var targetMeshes = []; //:Vector. = new Vector.; - for (i = 0; i < meshAdresses.length; i ++) { + for (i = 0; i < meshAdresses.length; i ++) { // returnedArray = getAssetByID(meshAdresses[i], [AssetType.MESH]); // if (returnedArray[0]) - targetMeshes.push(this._blocks[meshAdresses[i]].data); - } + targetMeshes.push(this._blocks[meshAdresses[i]].data); + } - targetAnimationSet = this._blocks[animSetBlockAdress].data - var thisAnimator; + targetAnimationSet = this._blocks[animSetBlockAdress].data + var thisAnimator; - if (type == 1) { + if (type == 1) { - thisAnimator = { + thisAnimator = { animationSet : targetAnimationSet, skeleton : this._blocks[props.get(1, 0)].data }; - } else if (type == 2) { + } else if (type == 2) { // debug( "vertex Anim???"); - } + } - for (i = 0; i < targetMeshes.length; i ++) { - targetMeshes[i].animator = thisAnimator; - } + for (i = 0; i < targetMeshes.length; i ++) { + targetMeshes[i].animator = thisAnimator; + } // debug("Parsed a Animator: Name = " + name); - return thisAnimator; - } + return thisAnimator; + } @@ -680,9 +680,9 @@ THREE.AWDLoader = (function () { - AWDLoader.prototype.parseMeshData = function ( len ) { + AWDLoader.prototype.parseMeshData = function ( len ) { - var name = this.readUTF(), + var name = this.readUTF(), num_subs = this.readU16(), geom, subs_parsed = 0, @@ -694,7 +694,7 @@ THREE.AWDLoader = (function () { - props = this.parseProperties({ + props = this.parseProperties({ 1: this._geoNrType, 2: this._geoNrType }); @@ -702,27 +702,27 @@ THREE.AWDLoader = (function () { // Loop through sub meshes - while (subs_parsed < num_subs) { + while (subs_parsed < num_subs) { - var sm_len, sm_end, attrib; + var sm_len, sm_end, attrib; - geom = new THREE.BufferGeometry(); - geom.name = name; - geometries.push( geom ); + geom = new THREE.BufferGeometry(); + geom.name = name; + geometries.push( geom ); - sm_len = this.readU32(); - sm_end = this._ptr + sm_len; + sm_len = this.readU32(); + sm_end = this._ptr + sm_len; // Ignore for now - this.parseProperties({ 1:this._geoNrType, 2:this._geoNrType }); + this.parseProperties({ 1:this._geoNrType, 2:this._geoNrType }); // Loop through data streams - while ( this._ptr < sm_end ) { + while ( this._ptr < sm_end ) { - var idx = 0, + var idx = 0, str_type = this.readU8(), str_ftype = this.readU8(), str_len = this.readU32(), @@ -734,78 +734,78 @@ THREE.AWDLoader = (function () { // VERTICES // ------------------ - if ( str_type === 1 ) { + if ( str_type === 1 ) { - buffer = new Float32Array( ( str_len / 12 ) * 3 ); - attrib = new THREE.BufferAttribute( buffer, 3 ); + buffer = new Float32Array( ( str_len / 12 ) * 3 ); + attrib = new THREE.BufferAttribute( buffer, 3 ); - geom.addAttribute( 'position', attrib ); - idx = 0; + geom.addAttribute( 'position', attrib ); + idx = 0; - while (this._ptr < str_end) { - buffer[idx] = -this.readF32(); - buffer[idx + 1] = this.readF32(); - buffer[idx + 2] = this.readF32(); - idx+=3; - } - } + while (this._ptr < str_end) { + buffer[idx] = -this.readF32(); + buffer[idx + 1] = this.readF32(); + buffer[idx + 2] = this.readF32(); + idx+=3; + } + } // INDICES // ----------------- else if (str_type === 2) { - buffer = new Uint16Array( str_len / 2 ); - attrib = new THREE.BufferAttribute( buffer, 1 ); - geom.addAttribute( 'index', attrib ); + buffer = new Uint16Array( str_len / 2 ); + attrib = new THREE.BufferAttribute( buffer, 1 ); + geom.addAttribute( 'index', attrib ); - geom.offsets.push({ + geom.offsets.push({ start: 0, index: 0, count: str_len / 2 }); - idx = 0; + idx = 0; - while (this._ptr < str_end) { - buffer[idx + 1] = this.readU16(); - buffer[idx] = this.readU16(); - buffer[idx + 2] = this.readU16(); - idx+=3; - } + while (this._ptr < str_end) { + buffer[idx + 1] = this.readU16(); + buffer[idx] = this.readU16(); + buffer[idx + 2] = this.readU16(); + idx+=3; + } } // UVS // ------------------- else if (str_type === 3) { - buffer = new Float32Array( ( str_len / 8 ) * 2 ); - attrib = new THREE.BufferAttribute( buffer, 2 ); + buffer = new Float32Array( ( str_len / 8 ) * 2 ); + attrib = new THREE.BufferAttribute( buffer, 2 ); - geom.addAttribute( 'uv', attrib ); - idx = 0; + geom.addAttribute( 'uv', attrib ); + idx = 0; - while (this._ptr < str_end) { - buffer[idx] = this.readF32(); - buffer[idx + 1] = 1.0 - this.readF32(); - idx+=2; - } + while (this._ptr < str_end) { + buffer[idx] = this.readF32(); + buffer[idx + 1] = 1.0 - this.readF32(); + idx+=2; + } } // NORMALS else if (str_type === 4) { - buffer = new Float32Array( ( str_len / 12 ) * 3 ); - attrib = new THREE.BufferAttribute( buffer, 3 ); - geom.addAttribute( 'normal', attrib ); - idx = 0; + buffer = new Float32Array( ( str_len / 12 ) * 3 ); + attrib = new THREE.BufferAttribute( buffer, 3 ); + geom.addAttribute( 'normal', attrib ); + idx = 0; - while (this._ptr < str_end) { - buffer[idx] = -this.readF32(); - buffer[idx + 1] = this.readF32(); - buffer[idx + 2] = this.readF32(); - idx+=3; - } + while (this._ptr < str_end) { + buffer[idx] = -this.readF32(); + buffer[idx + 1] = this.readF32(); + buffer[idx + 2] = this.readF32(); + idx+=3; + } } @@ -828,34 +828,34 @@ THREE.AWDLoader = (function () { // idx++; // } // } - else { - this._ptr = str_end; - } + else { + this._ptr = str_end; + } - } + } - this.parseUserAttributes(); + this.parseUserAttributes(); - geom.computeBoundingSphere(); - subs_parsed ++; - } + geom.computeBoundingSphere(); + subs_parsed ++; + } //geom.computeFaceNormals(); - this.parseUserAttributes(); + this.parseUserAttributes(); //finalizeAsset(geom, name); - return geometries; - } + return geometries; + } - AWDLoader.prototype.parseMeshPoseAnimation = function(len, poseOnly) + AWDLoader.prototype.parseMeshPoseAnimation = function(len, poseOnly) { - var num_frames = 1, + var num_frames = 1, num_submeshes, frames_parsed, subMeshParsed, @@ -880,84 +880,84 @@ THREE.AWDLoader = (function () { geoAdress = this.readU32(); - var mesh = this.getBlock( geoAdress ); + var mesh = this.getBlock( geoAdress ); - if (mesh == null) { - console.log( "parseMeshPoseAnimation target mesh not found at:", geoAdress ); - return; - } + if (mesh == null) { + console.log( "parseMeshPoseAnimation target mesh not found at:", geoAdress ); + return; + } - geom = mesh.geometry; - geom.morphTargets = []; + geom = mesh.geometry; + geom.morphTargets = []; - if (!poseOnly) + if (!poseOnly) num_frames = this.readU16(); - num_submeshes = this.readU16(); - num_Streams = this.readU16(); + num_submeshes = this.readU16(); + num_Streams = this.readU16(); // debug("VA num_frames : ", num_frames ); // debug("VA num_submeshes : ", num_submeshes ); // debug("VA numstreams : ", num_Streams ); - streamsParsed = 0; - while (streamsParsed < num_Streams) { - streamtypes.push(this.readU16()); - streamsParsed ++; - } - props = this.parseProperties({ 1:BOOL, 2:BOOL }); + streamsParsed = 0; + while (streamsParsed < num_Streams) { + streamtypes.push(this.readU16()); + streamsParsed ++; + } + props = this.parseProperties({ 1:BOOL, 2:BOOL }); - clip.looping = props.get(1, true); - clip.stitchFinalFrame = props.get(2, false); + clip.looping = props.get(1, true); + clip.stitchFinalFrame = props.get(2, false); - frames_parsed = 0; + frames_parsed = 0; - while (frames_parsed < num_frames) { + while (frames_parsed < num_frames) { - frame_dur = this.readU16(); - subMeshParsed = 0; + frame_dur = this.readU16(); + subMeshParsed = 0; - while (subMeshParsed < num_submeshes) { + while (subMeshParsed < num_submeshes) { - streamsParsed = 0; - str_len = this.readU32(); - str_end = this._ptr + str_len; + streamsParsed = 0; + str_len = this.readU32(); + str_end = this._ptr + str_len; - while (streamsParsed < num_Streams) { + while (streamsParsed < num_Streams) { - if (streamtypes[streamsParsed] == 1) { + if (streamtypes[streamsParsed] == 1) { //geom.addAttribute( 'morphTarget'+frames_parsed, Float32Array, str_len/12, 3 ); - var buffer = new Float32Array(str_len / 4); - geom.morphTargets.push( { + var buffer = new Float32Array(str_len / 4); + geom.morphTargets.push( { array : buffer }); //buffer = geom.attributes['morphTarget'+frames_parsed].array - idx = 0; + idx = 0; - while ( this._ptr < str_end ) { - buffer[idx] = this.readF32(); - buffer[idx + 1] = this.readF32(); - buffer[idx + 2] = this.readF32(); - idx += 3; - } + while ( this._ptr < str_end ) { + buffer[idx] = this.readF32(); + buffer[idx + 1] = this.readF32(); + buffer[idx + 2] = this.readF32(); + idx += 3; + } - subMeshParsed ++; - } else + subMeshParsed ++; + } else this._ptr = str_end; - streamsParsed ++; - } - } + streamsParsed ++; + } + } - frames_parsed ++; - } - this.parseUserAttributes(); + frames_parsed ++; + } + this.parseUserAttributes(); - return null; - } + return null; + } @@ -967,191 +967,191 @@ THREE.AWDLoader = (function () { - AWDLoader.prototype.getBlock = function ( id ) { - return this._blocks[id].data; - }, + AWDLoader.prototype.getBlock = function ( id ) { + return this._blocks[id].data; + }, AWDLoader.prototype.parseMatrix4 = function ( ) { - var mtx = new THREE.Matrix4(); - var e = mtx.elements; + var mtx = new THREE.Matrix4(); + var e = mtx.elements; - e[0] = this.readF32(); - e[1] = this.readF32(); - e[2] = this.readF32(); - e[3] = 0.0; + e[0] = this.readF32(); + e[1] = this.readF32(); + e[2] = this.readF32(); + e[3] = 0.0; //e[3] = 0.0; - e[4] = this.readF32(); - e[5] = this.readF32(); - e[6] = this.readF32(); + e[4] = this.readF32(); + e[5] = this.readF32(); + e[6] = this.readF32(); //e[7] = this.readF32(); - e[7] = 0.0; + e[7] = 0.0; - e[8] = this.readF32(); - e[9] = this.readF32(); - e[10] = this.readF32(); + e[8] = this.readF32(); + e[9] = this.readF32(); + e[10] = this.readF32(); //e[11] = this.readF32(); - e[11] = 0.0; + e[11] = 0.0; - e[12] = -this.readF32(); - e[13] = this.readF32(); - e[14] = this.readF32(); + e[12] = -this.readF32(); + e[13] = this.readF32(); + e[14] = this.readF32(); //e[15] = this.readF32(); - e[15] = 1.0; - return mtx; + e[15] = 1.0; + return mtx; } - AWDLoader.prototype.parseProperties = function ( expected ) { - var list_len = this.readU32(); - var list_end = this._ptr + list_len; + AWDLoader.prototype.parseProperties = function ( expected ) { + var list_len = this.readU32(); + var list_end = this._ptr + list_len; - var props = new AWDProperties(); + var props = new AWDProperties(); - if ( expected ) { + if ( expected ) { - while ( this._ptr < list_end ) { + while ( this._ptr < list_end ) { - var key = this.readU16(); - var len = this.readU32(); - var type; + var key = this.readU16(); + var len = this.readU32(); + var type; - if ( expected.hasOwnProperty( key ) ) { - type = expected[ key ]; - props.set( key, this.parseAttrValue( type, len ) ); - } else { - this._ptr += len; - } - } + if ( expected.hasOwnProperty( key ) ) { + type = expected[ key ]; + props.set( key, this.parseAttrValue( type, len ) ); + } else { + this._ptr += len; + } + } - } + } - return props; + return props; - }; + }; - AWDLoader.prototype.parseUserAttributes = function ( ) { + AWDLoader.prototype.parseUserAttributes = function ( ) { // skip for now - this._ptr = this.readU32() + this._ptr; - return null; - }; - - - AWDLoader.prototype.parseAttrValue = function ( type, len ) { - - var elem_len; - var read_func; - - switch (type) { - case AWD_FIELD_INT8: - elem_len = 1; - read_func = this.readI8; - break; - case AWD_FIELD_INT16: - elem_len = 2; - read_func = this.readI16; - break; - case AWD_FIELD_INT32: - elem_len = 4; - read_func = this.readI32; - break; - case AWD_FIELD_BOOL: - case AWD_FIELD_UINT8: - elem_len = 1; - read_func = this.readU8; - break; - case AWD_FIELD_UINT16: - elem_len = 2; - read_func = this.readU16; - break; - case AWD_FIELD_UINT32: - case AWD_FIELD_BADDR: - elem_len = 4; - read_func = this.readU32; - break; - case AWD_FIELD_FLOAT32: - elem_len = 4; - read_func = this.readF32; - break; - case AWD_FIELD_FLOAT64: - elem_len = 8; - read_func = this.readF64; - break; - case AWD_FIELD_VECTOR2x1: - case AWD_FIELD_VECTOR3x1: - case AWD_FIELD_VECTOR4x1: - case AWD_FIELD_MTX3x2: - case AWD_FIELD_MTX3x3: - case AWD_FIELD_MTX4x3: - case AWD_FIELD_MTX4x4: - elem_len = 8; - read_func = this.readF64; - break; - } - - if (elem_len < len) { - var list; - var num_read; - var num_elems; - - list = []; - num_read = 0; - num_elems = len / elem_len; - - while (num_read < num_elems) { - list.push(read_func.call( this ) ); - num_read ++; - } - - return list; - } - else { - return read_func.call( this ); - } - - } - - - AWDLoader.prototype.readU8 = function () { - return this._data.getUint8( this._ptr ++ ); - } - AWDLoader.prototype.readI8 = function () { - return this._data.getInt8( this._ptr ++ ); - } - - AWDLoader.prototype.readU16 = function () { - var a = this._data.getUint16( this._ptr, littleEndian ); - this._ptr += 2; - return a; - } - AWDLoader.prototype.readI16 = function () { - var a = this._data.getInt16( this._ptr, littleEndian ); - this._ptr += 2; - return a; - } - - AWDLoader.prototype.readU32 = function () { - var a = this._data.getUint32( this._ptr, littleEndian ); - this._ptr += 4; - return a; - } - AWDLoader.prototype.readI32 = function () { - var a = this._data.getInt32( this._ptr, littleEndian ); - this._ptr += 4; - return a; - } - AWDLoader.prototype.readF32 = function () { - var a = this._data.getFloat32( this._ptr, littleEndian ); - this._ptr += 4; - return a; - } - AWDLoader.prototype.readF64 = function () { - var a = this._data.getFloat64( this._ptr, littleEndian ); - this._ptr += 8; - return a; - } + this._ptr = this.readU32() + this._ptr; + return null; + }; + + + AWDLoader.prototype.parseAttrValue = function ( type, len ) { + + var elem_len; + var read_func; + + switch (type) { + case AWD_FIELD_INT8: + elem_len = 1; + read_func = this.readI8; + break; + case AWD_FIELD_INT16: + elem_len = 2; + read_func = this.readI16; + break; + case AWD_FIELD_INT32: + elem_len = 4; + read_func = this.readI32; + break; + case AWD_FIELD_BOOL: + case AWD_FIELD_UINT8: + elem_len = 1; + read_func = this.readU8; + break; + case AWD_FIELD_UINT16: + elem_len = 2; + read_func = this.readU16; + break; + case AWD_FIELD_UINT32: + case AWD_FIELD_BADDR: + elem_len = 4; + read_func = this.readU32; + break; + case AWD_FIELD_FLOAT32: + elem_len = 4; + read_func = this.readF32; + break; + case AWD_FIELD_FLOAT64: + elem_len = 8; + read_func = this.readF64; + break; + case AWD_FIELD_VECTOR2x1: + case AWD_FIELD_VECTOR3x1: + case AWD_FIELD_VECTOR4x1: + case AWD_FIELD_MTX3x2: + case AWD_FIELD_MTX3x3: + case AWD_FIELD_MTX4x3: + case AWD_FIELD_MTX4x4: + elem_len = 8; + read_func = this.readF64; + break; + } + + if (elem_len < len) { + var list; + var num_read; + var num_elems; + + list = []; + num_read = 0; + num_elems = len / elem_len; + + while (num_read < num_elems) { + list.push(read_func.call( this ) ); + num_read ++; + } + + return list; + } + else { + return read_func.call( this ); + } + + } + + + AWDLoader.prototype.readU8 = function () { + return this._data.getUint8( this._ptr ++ ); + } + AWDLoader.prototype.readI8 = function () { + return this._data.getInt8( this._ptr ++ ); + } + + AWDLoader.prototype.readU16 = function () { + var a = this._data.getUint16( this._ptr, littleEndian ); + this._ptr += 2; + return a; + } + AWDLoader.prototype.readI16 = function () { + var a = this._data.getInt16( this._ptr, littleEndian ); + this._ptr += 2; + return a; + } + + AWDLoader.prototype.readU32 = function () { + var a = this._data.getUint32( this._ptr, littleEndian ); + this._ptr += 4; + return a; + } + AWDLoader.prototype.readI32 = function () { + var a = this._data.getInt32( this._ptr, littleEndian ); + this._ptr += 4; + return a; + } + AWDLoader.prototype.readF32 = function () { + var a = this._data.getFloat32( this._ptr, littleEndian ); + this._ptr += 4; + return a; + } + AWDLoader.prototype.readF64 = function () { + var a = this._data.getFloat64( this._ptr, littleEndian ); + this._ptr += 8; + return a; + } /** @@ -1159,41 +1159,41 @@ THREE.AWDLoader = (function () { * @param {Array.} bytes UTF-8 byte array. * @return {string} 16-bit Unicode string. */ - AWDLoader.prototype.readUTF = function () { - var len = this.readU16(); + AWDLoader.prototype.readUTF = function () { + var len = this.readU16(); - return this.readUTFBytes( len ); - }; + return this.readUTFBytes( len ); + }; /** * Converts a UTF-8 byte array to JavaScript's 16-bit Unicode. * @param {Array.} bytes UTF-8 byte array. * @return {string} 16-bit Unicode string. */ - AWDLoader.prototype.readUTFBytes = function ( len ) { + AWDLoader.prototype.readUTFBytes = function ( len ) { // TODO(user): Use native implementations if/when available - var out = [], c = 0; - - while ( out.length < len ) { - var c1 = this._data.getUint8( this._ptr ++, littleEndian ); - if (c1 < 128) { - out[c ++] = String.fromCharCode(c1); - } else if (c1 > 191 && c1 < 224) { - var c2 = this._data.getUint8( this._ptr ++, littleEndian ); - out[c ++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63); - } else { - var c2 = this._data.getUint8( this._ptr ++, littleEndian ); - var c3 = this._data.getUint8( this._ptr ++, littleEndian ); - out[c ++] = String.fromCharCode( + var out = [], c = 0; + + while ( out.length < len ) { + var c1 = this._data.getUint8( this._ptr ++, littleEndian ); + if (c1 < 128) { + out[c ++] = String.fromCharCode(c1); + } else if (c1 > 191 && c1 < 224) { + var c2 = this._data.getUint8( this._ptr ++, littleEndian ); + out[c ++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63); + } else { + var c2 = this._data.getUint8( this._ptr ++, littleEndian ); + var c3 = this._data.getUint8( this._ptr ++, littleEndian ); + out[c ++] = String.fromCharCode( (c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63 ); - } - } - return out.join(''); - }; + } + } + return out.join(''); + }; @@ -1203,24 +1203,24 @@ THREE.AWDLoader = (function () { - AWDProperties = function() {} + AWDProperties = function() {} - AWDProperties.prototype = { + AWDProperties.prototype = { set : function(key, value) { - this[key] = value; + this[key] = value; }, get : function(key, fallback) { - if ( this.hasOwnProperty(key) ) + if ( this.hasOwnProperty(key) ) return this[key]; else return fallback; } } - return AWDLoader; + return AWDLoader; })(); diff --git a/examples/js/loaders/ColladaLoader.js b/examples/js/loaders/ColladaLoader.js index 1d0f43d007..324475d565 100644 --- a/examples/js/loaders/ColladaLoader.js +++ b/examples/js/loaders/ColladaLoader.js @@ -735,7 +735,7 @@ THREE.ColladaLoader = function () { // move vertices to bind shape for ( i = 0; i < geometry.vertices.length; i ++ ) { - geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix ); + geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix ); } var skinIndices = []; @@ -1343,17 +1343,17 @@ THREE.ColladaLoader = function () { function getLibraryNode( id ) { - var nodes = COLLADA.querySelectorAll('library_nodes node'); + var nodes = COLLADA.querySelectorAll('library_nodes node'); - for ( var i = 0; i < nodes.length; i ++ ) { + for ( var i = 0; i < nodes.length; i ++ ) { - var attObj = nodes[i].attributes.getNamedItem('id'); - if ( attObj && attObj.value === id ) { - return nodes[i]; - } - } + var attObj = nodes[i].attributes.getNamedItem('id'); + if ( attObj && attObj.value === id ) { + return nodes[i]; + } + } - return undefined; + return undefined; }; @@ -3365,35 +3365,35 @@ THREE.ColladaLoader = function () { //for (var i = 0; i < this.accessor.params.length; i++) { - var param = this.accessor.params[ 0 ]; + var param = this.accessor.params[ 0 ]; //console.log(param.name + " " + param.type); - switch ( param.type ) { + switch ( param.type ) { - case 'IDREF': - case 'Name': case 'name': - case 'float': + case 'IDREF': + case 'Name': case 'name': + case 'float': - return this.data; + return this.data; - case 'float4x4': + case 'float4x4': - for ( var j = 0; j < this.data.length; j += 16 ) { + for ( var j = 0; j < this.data.length; j += 16 ) { - var s = this.data.slice( j, j + 16 ); - var m = getConvertedMat4( s ); - result.push( m ); - } + var s = this.data.slice( j, j + 16 ); + var m = getConvertedMat4( s ); + result.push( m ); + } - break; + break; - default: + default: - console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' ); - break; + console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' ); + break; - } + } //} diff --git a/examples/js/loaders/PVRLoader.js b/examples/js/loaders/PVRLoader.js index b840351fa6..71fd264a85 100644 --- a/examples/js/loaders/PVRLoader.js +++ b/examples/js/loaders/PVRLoader.js @@ -77,16 +77,16 @@ THREE.PVRLoader._parseV3 = function ( pvrDatas ) { } pvrDatas.dataPtr = 52 + metaLen; - pvrDatas.bpp = bpp; - pvrDatas.format = format; - pvrDatas.width = width; - pvrDatas.height = height; - pvrDatas.numSurfaces = numFaces; - pvrDatas.numMipmaps = numMipmaps; + pvrDatas.bpp = bpp; + pvrDatas.format = format; + pvrDatas.width = width; + pvrDatas.height = height; + pvrDatas.numSurfaces = numFaces; + pvrDatas.numMipmaps = numMipmaps; - pvrDatas.isCubemap = (numFaces === 6); + pvrDatas.isCubemap = (numFaces === 6); - return THREE.PVRLoader._extract( pvrDatas ); + return THREE.PVRLoader._extract( pvrDatas ); }; THREE.PVRLoader._parseV2 = function ( pvrDatas ) { @@ -133,18 +133,18 @@ THREE.PVRLoader._parseV2 = function ( pvrDatas ) { pvrDatas.dataPtr = headerLength; - pvrDatas.bpp = bpp; - pvrDatas.format = format; - pvrDatas.width = width; - pvrDatas.height = height; - pvrDatas.numSurfaces = numSurfs; - pvrDatas.numMipmaps = numMipmaps + 1; + pvrDatas.bpp = bpp; + pvrDatas.format = format; + pvrDatas.width = width; + pvrDatas.height = height; + pvrDatas.numSurfaces = numSurfs; + pvrDatas.numMipmaps = numMipmaps + 1; // guess cubemap type seems tricky in v2 // it juste a pvr containing 6 surface (no explicit cubemap type) - pvrDatas.isCubemap = (numSurfs === 6); + pvrDatas.isCubemap = (numSurfs === 6); - return THREE.PVRLoader._extract( pvrDatas ); + return THREE.PVRLoader._extract( pvrDatas ); }; diff --git a/examples/js/loaders/RGBELoader.js b/examples/js/loaders/RGBELoader.js index d638c89b6b..9d0e210bb6 100644 --- a/examples/js/loaders/RGBELoader.js +++ b/examples/js/loaders/RGBELoader.js @@ -30,11 +30,11 @@ THREE.RGBELoader.prototype._parser = function( buffer ) { rgbe_error = function(rgbe_error_code, msg) { switch (rgbe_error_code) { case rgbe_read_error: console.error("THREE.RGBELoader Read Error: " + (msg||'')); - break; + break; case rgbe_write_error: console.error("THREE.RGBELoader Write Error: " + (msg||'')); - break; + break; case rgbe_format_error: console.error("THREE.RGBELoader Bad File Format: " + (msg||'')); - break; + break; default: case rgbe_memory_error: console.error("THREE.RGBELoader: Error: " + (msg||'')); } diff --git a/examples/js/loaders/STLLoader.js b/examples/js/loaders/STLLoader.js index e317002dac..71bb4add69 100644 --- a/examples/js/loaders/STLLoader.js +++ b/examples/js/loaders/STLLoader.js @@ -110,15 +110,15 @@ THREE.STLLoader.prototype = { (reader.getUint8(index + 4) == 0x52 /*'R'*/) && (reader.getUint8(index + 5) == 0x3D /*'='*/)) { - hasColors = true; - colors = new Float32Array( faces * 3 * 3); + hasColors = true; + colors = new Float32Array( faces * 3 * 3); - defaultR = reader.getUint8(index + 6) / 255; - defaultG = reader.getUint8(index + 7) / 255; - defaultB = reader.getUint8(index + 8) / 255; - alpha = reader.getUint8(index + 9) / 255; - } + defaultR = reader.getUint8(index + 6) / 255; + defaultG = reader.getUint8(index + 7) / 255; + defaultB = reader.getUint8(index + 8) / 255; + alpha = reader.getUint8(index + 9) / 255; } + } var dataOffset = 84; var faceLength = 12 * 4 + 2; diff --git a/examples/js/loaders/TGALoader.js b/examples/js/loaders/TGALoader.js index cd9d2dfc3a..7df35c066e 100644 --- a/examples/js/loaders/TGALoader.js +++ b/examples/js/loaders/TGALoader.js @@ -154,8 +154,8 @@ THREE.TGALoader.prototype._parser = function ( buffer ) { pixel_total, palettes; - pixel_size = header.pixel_size >> 3; - pixel_total = header.width * header.height * pixel_size; + pixel_size = header.pixel_size >> 3; + pixel_total = header.width * header.height * pixel_size; // Read palettes if ( use_pal ) { @@ -178,12 +178,12 @@ THREE.TGALoader.prototype._parser = function ( buffer ) { if (c & 0x80) { // Bind pixel tmp array for (i = 0; i < pixel_size; ++ i) { - pixels[i] = data[offset ++]; + pixels[i] = data[offset ++]; } // Copy pixel array for (i = 0; i < count; ++ i) { - pixel_data.set(pixels, shift + i * pixel_size); + pixel_data.set(pixels, shift + i * pixel_size); } shift += pixel_size * count; @@ -192,7 +192,7 @@ THREE.TGALoader.prototype._parser = function ( buffer ) { // Raw pixels. count *= pixel_size; for (i = 0; i < count; ++ i) { - pixel_data[shift + i] = data[offset ++]; + pixel_data[shift + i] = data[offset ++]; } shift += count; } @@ -214,7 +214,7 @@ THREE.TGALoader.prototype._parser = function ( buffer ) { var colormap = palettes; var color, i = 0, x, y; - var width = header.width; + var width = header.width; for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i ++) { diff --git a/examples/js/loaders/UTF8Loader.js b/examples/js/loaders/UTF8Loader.js index 483c1e6a46..6e9e9e9257 100644 --- a/examples/js/loaders/UTF8Loader.js +++ b/examples/js/loaders/UTF8Loader.js @@ -94,12 +94,12 @@ THREE.UTF8Loader.BufferGeometryCreator.prototype.create = function ( attribArray } - geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); - geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); - geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); + geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); - geometry.offsets.push( { start: 0, count: indices.length, index: 0 } ); + geometry.offsets.push( { start: 0, count: indices.length, index: 0 } ); geometry.computeBoundingSphere(); @@ -158,17 +158,17 @@ THREE.UTF8Loader.prototype.decompressAttribsInner_ = function ( str, inputStart, output, outputStart, stride, decodeOffset, decodeScale ) { - var prev = 0; + var prev = 0; - for ( var j = inputStart; j < inputEnd; j ++ ) { + for ( var j = inputStart; j < inputEnd; j ++ ) { - var code = str.charCodeAt( j ); - prev += ( code >> 1 ) ^ ( -( code & 1 ) ); + var code = str.charCodeAt( j ); + prev += ( code >> 1 ) ^ ( -( code & 1 ) ); - output[ outputStart ] = decodeScale * ( prev + decodeOffset ); - outputStart += stride; + output[ outputStart ] = decodeScale * ( prev + decodeOffset ); + outputStart += stride; - } + } }; @@ -177,52 +177,52 @@ THREE.UTF8Loader.prototype.decompressIndices_ = function( str, inputStart, numIn var highest = 0; - for ( var i = 0; i < numIndices; i ++ ) { + for ( var i = 0; i < numIndices; i ++ ) { - var code = str.charCodeAt( inputStart ++ ); + var code = str.charCodeAt( inputStart ++ ); - output[ outputStart ++ ] = highest - code; + output[ outputStart ++ ] = highest - code; - if ( code === 0 ) { + if ( code === 0 ) { - highest ++; + highest ++; - } + } - } + } }; THREE.UTF8Loader.prototype.decompressAABBs_ = function ( str, inputStart, numBBoxen, decodeOffsets, decodeScales ) { - var numFloats = 6 * numBBoxen; + var numFloats = 6 * numBBoxen; - var inputEnd = inputStart + numFloats; - var outputStart = 0; + var inputEnd = inputStart + numFloats; + var outputStart = 0; - var bboxen = new Float32Array( numFloats ); + var bboxen = new Float32Array( numFloats ); - for ( var i = inputStart; i < inputEnd; i += 6 ) { + for ( var i = inputStart; i < inputEnd; i += 6 ) { - var minX = str.charCodeAt(i + 0) + decodeOffsets[0]; - var minY = str.charCodeAt(i + 1) + decodeOffsets[1]; - var minZ = str.charCodeAt(i + 2) + decodeOffsets[2]; + var minX = str.charCodeAt(i + 0) + decodeOffsets[0]; + var minY = str.charCodeAt(i + 1) + decodeOffsets[1]; + var minZ = str.charCodeAt(i + 2) + decodeOffsets[2]; - var radiusX = (str.charCodeAt(i + 3) + 1) >> 1; - var radiusY = (str.charCodeAt(i + 4) + 1) >> 1; - var radiusZ = (str.charCodeAt(i + 5) + 1) >> 1; + var radiusX = (str.charCodeAt(i + 3) + 1) >> 1; + var radiusY = (str.charCodeAt(i + 4) + 1) >> 1; + var radiusZ = (str.charCodeAt(i + 5) + 1) >> 1; - bboxen[ outputStart ++ ] = decodeScales[0] * (minX + radiusX); - bboxen[ outputStart ++ ] = decodeScales[1] * (minY + radiusY); - bboxen[ outputStart ++ ] = decodeScales[2] * (minZ + radiusZ); + bboxen[ outputStart ++ ] = decodeScales[0] * (minX + radiusX); + bboxen[ outputStart ++ ] = decodeScales[1] * (minY + radiusY); + bboxen[ outputStart ++ ] = decodeScales[2] * (minZ + radiusZ); - bboxen[ outputStart ++ ] = decodeScales[0] * radiusX; - bboxen[ outputStart ++ ] = decodeScales[1] * radiusY; - bboxen[ outputStart ++ ] = decodeScales[2] * radiusZ; + bboxen[ outputStart ++ ] = decodeScales[0] * radiusX; + bboxen[ outputStart ++ ] = decodeScales[1] * radiusY; + bboxen[ outputStart ++ ] = decodeScales[2] * radiusZ; - } + } - return bboxen; + return bboxen; }; @@ -230,67 +230,67 @@ THREE.UTF8Loader.prototype.decompressMesh = function ( str, meshParams, decodeP // Extract conversion parameters from attribArrays. - var stride = decodeParams.decodeScales.length; + var stride = decodeParams.decodeScales.length; - var decodeOffsets = decodeParams.decodeOffsets; - var decodeScales = decodeParams.decodeScales; + var decodeOffsets = decodeParams.decodeOffsets; + var decodeScales = decodeParams.decodeScales; - var attribStart = meshParams.attribRange[0]; - var numVerts = meshParams.attribRange[1]; + var attribStart = meshParams.attribRange[0]; + var numVerts = meshParams.attribRange[1]; // Decode attributes. - var inputOffset = attribStart; - var attribsOut = new Float32Array( stride * numVerts ); + var inputOffset = attribStart; + var attribsOut = new Float32Array( stride * numVerts ); - for (var j = 0; j < stride; j ++ ) { + for (var j = 0; j < stride; j ++ ) { - var end = inputOffset + numVerts; + var end = inputOffset + numVerts; var decodeScale = decodeScales[j]; - if ( decodeScale ) { + if ( decodeScale ) { // Assume if decodeScale is never set, simply ignore the // attribute. - this.decompressAttribsInner_( str, inputOffset, end, + this.decompressAttribsInner_( str, inputOffset, end, attribsOut, j, stride, decodeOffsets[j], decodeScale ); - } + } - inputOffset = end; + inputOffset = end; - } + } - var indexStart = meshParams.indexRange[ 0 ]; - var numIndices = 3 * meshParams.indexRange[ 1 ]; + var indexStart = meshParams.indexRange[ 0 ]; + var numIndices = 3 * meshParams.indexRange[ 1 ]; - var indicesOut = new Uint16Array( numIndices ); + var indicesOut = new Uint16Array( numIndices ); - this.decompressIndices_( str, inputOffset, numIndices, indicesOut, 0 ); + this.decompressIndices_( str, inputOffset, numIndices, indicesOut, 0 ); // Decode bboxen. - var bboxen = undefined; - var bboxOffset = meshParams.bboxes; + var bboxen = undefined; + var bboxOffset = meshParams.bboxes; - if ( bboxOffset ) { + if ( bboxOffset ) { - bboxen = this.decompressAABBs_( str, bboxOffset, meshParams.names.length, decodeOffsets, decodeScales ); - } + bboxen = this.decompressAABBs_( str, bboxOffset, meshParams.names.length, decodeOffsets, decodeScales ); + } - callback( name, idx, attribsOut, indicesOut, bboxen, meshParams ); + callback( name, idx, attribsOut, indicesOut, bboxen, meshParams ); }; THREE.UTF8Loader.prototype.copyAttrib = function ( stride, attribsOutFixed, lastAttrib, index ) { - for ( var j = 0; j < stride; j ++ ) { + for ( var j = 0; j < stride; j ++ ) { - lastAttrib[ j ] = attribsOutFixed[ stride * index + j ]; + lastAttrib[ j ] = attribsOutFixed[ stride * index + j ]; - } + } }; @@ -298,343 +298,343 @@ THREE.UTF8Loader.prototype.decodeAttrib2 = function ( str, stride, decodeOffsets numVerts, attribsOut, attribsOutFixed, lastAttrib, index ) { - for ( var j = 0; j < 5; j ++ ) { + for ( var j = 0; j < 5; j ++ ) { - var code = str.charCodeAt( deltaStart + numVerts * j + index ); - var delta = ( code >> 1) ^ (-(code & 1)); + var code = str.charCodeAt( deltaStart + numVerts * j + index ); + var delta = ( code >> 1) ^ (-(code & 1)); - lastAttrib[ j ] += delta; - attribsOutFixed[ stride * index + j ] = lastAttrib[ j ]; - attribsOut[ stride * index + j ] = decodeScales[ j ] * ( lastAttrib[ j ] + decodeOffsets[ j ] ); - } + lastAttrib[ j ] += delta; + attribsOutFixed[ stride * index + j ] = lastAttrib[ j ]; + attribsOut[ stride * index + j ] = decodeScales[ j ] * ( lastAttrib[ j ] + decodeOffsets[ j ] ); + } }; THREE.UTF8Loader.prototype.accumulateNormal = function ( i0, i1, i2, attribsOutFixed, crosses ) { - var p0x = attribsOutFixed[ 8 * i0 ]; - var p0y = attribsOutFixed[ 8 * i0 + 1 ]; - var p0z = attribsOutFixed[ 8 * i0 + 2 ]; + var p0x = attribsOutFixed[ 8 * i0 ]; + var p0y = attribsOutFixed[ 8 * i0 + 1 ]; + var p0z = attribsOutFixed[ 8 * i0 + 2 ]; - var p1x = attribsOutFixed[ 8 * i1 ]; - var p1y = attribsOutFixed[ 8 * i1 + 1 ]; - var p1z = attribsOutFixed[ 8 * i1 + 2 ]; + var p1x = attribsOutFixed[ 8 * i1 ]; + var p1y = attribsOutFixed[ 8 * i1 + 1 ]; + var p1z = attribsOutFixed[ 8 * i1 + 2 ]; - var p2x = attribsOutFixed[ 8 * i2 ]; - var p2y = attribsOutFixed[ 8 * i2 + 1 ]; - var p2z = attribsOutFixed[ 8 * i2 + 2 ]; + var p2x = attribsOutFixed[ 8 * i2 ]; + var p2y = attribsOutFixed[ 8 * i2 + 1 ]; + var p2z = attribsOutFixed[ 8 * i2 + 2 ]; - p1x -= p0x; - p1y -= p0y; - p1z -= p0z; + p1x -= p0x; + p1y -= p0y; + p1z -= p0z; - p2x -= p0x; - p2y -= p0y; - p2z -= p0z; + p2x -= p0x; + p2y -= p0y; + p2z -= p0z; - p0x = p1y * p2z - p1z * p2y; - p0y = p1z * p2x - p1x * p2z; - p0z = p1x * p2y - p1y * p2x; + p0x = p1y * p2z - p1z * p2y; + p0y = p1z * p2x - p1x * p2z; + p0z = p1x * p2y - p1y * p2x; - crosses[ 3 * i0 ] += p0x; - crosses[ 3 * i0 + 1 ] += p0y; - crosses[ 3 * i0 + 2 ] += p0z; + crosses[ 3 * i0 ] += p0x; + crosses[ 3 * i0 + 1 ] += p0y; + crosses[ 3 * i0 + 2 ] += p0z; - crosses[ 3 * i1 ] += p0x; - crosses[ 3 * i1 + 1 ] += p0y; - crosses[ 3 * i1 + 2 ] += p0z; + crosses[ 3 * i1 ] += p0x; + crosses[ 3 * i1 + 1 ] += p0y; + crosses[ 3 * i1 + 2 ] += p0z; - crosses[ 3 * i2 ] += p0x; - crosses[ 3 * i2 + 1 ] += p0y; - crosses[ 3 * i2 + 2 ] += p0z; + crosses[ 3 * i2 ] += p0x; + crosses[ 3 * i2 + 1 ] += p0y; + crosses[ 3 * i2 + 2 ] += p0z; }; THREE.UTF8Loader.prototype.decompressMesh2 = function( str, meshParams, decodeParams, name, idx, callback ) { - var MAX_BACKREF = 96; + var MAX_BACKREF = 96; // Extract conversion parameters from attribArrays. - var stride = decodeParams.decodeScales.length; + var stride = decodeParams.decodeScales.length; var decodeOffsets = decodeParams.decodeOffsets; - var decodeScales = decodeParams.decodeScales; + var decodeScales = decodeParams.decodeScales; - var deltaStart = meshParams.attribRange[ 0 ]; - var numVerts = meshParams.attribRange[ 1 ]; + var deltaStart = meshParams.attribRange[ 0 ]; + var numVerts = meshParams.attribRange[ 1 ]; - var codeStart = meshParams.codeRange[ 0 ]; - var codeLength = meshParams.codeRange[ 1 ]; + var codeStart = meshParams.codeRange[ 0 ]; + var codeLength = meshParams.codeRange[ 1 ]; - var numIndices = 3 * meshParams.codeRange[ 2 ]; + var numIndices = 3 * meshParams.codeRange[ 2 ]; - var indicesOut = new Uint16Array( numIndices ); + var indicesOut = new Uint16Array( numIndices ); - var crosses = new Int32Array( 3 * numVerts ); + var crosses = new Int32Array( 3 * numVerts ); - var lastAttrib = new Uint16Array( stride ); + var lastAttrib = new Uint16Array( stride ); - var attribsOutFixed = new Uint16Array( stride * numVerts ); - var attribsOut = new Float32Array( stride * numVerts ); + var attribsOutFixed = new Uint16Array( stride * numVerts ); + var attribsOut = new Float32Array( stride * numVerts ); - var highest = 0; - var outputStart = 0; + var highest = 0; + var outputStart = 0; - for ( var i = 0; i < numIndices; i += 3 ) { + for ( var i = 0; i < numIndices; i += 3 ) { - var code = str.charCodeAt( codeStart ++ ); + var code = str.charCodeAt( codeStart ++ ); - var max_backref = Math.min( i, MAX_BACKREF ); + var max_backref = Math.min( i, MAX_BACKREF ); - if ( code < max_backref ) { + if ( code < max_backref ) { // Parallelogram - var winding = code % 3; - var backref = i - ( code - winding ); - var i0, i1, i2; + var winding = code % 3; + var backref = i - ( code - winding ); + var i0, i1, i2; - switch ( winding ) { + switch ( winding ) { - case 0: + case 0: - i0 = indicesOut[ backref + 2 ]; - i1 = indicesOut[ backref + 1 ]; - i2 = indicesOut[ backref + 0 ]; - break; + i0 = indicesOut[ backref + 2 ]; + i1 = indicesOut[ backref + 1 ]; + i2 = indicesOut[ backref + 0 ]; + break; - case 1: + case 1: - i0 = indicesOut[ backref + 0 ]; - i1 = indicesOut[ backref + 2 ]; - i2 = indicesOut[ backref + 1 ]; - break; + i0 = indicesOut[ backref + 0 ]; + i1 = indicesOut[ backref + 2 ]; + i2 = indicesOut[ backref + 1 ]; + break; - case 2: + case 2: - i0 = indicesOut[ backref + 1 ]; - i1 = indicesOut[ backref + 0 ]; - i2 = indicesOut[ backref + 2 ]; - break; + i0 = indicesOut[ backref + 1 ]; + i1 = indicesOut[ backref + 0 ]; + i2 = indicesOut[ backref + 2 ]; + break; - } + } - indicesOut[ outputStart ++ ] = i0; - indicesOut[ outputStart ++ ] = i1; + indicesOut[ outputStart ++ ] = i0; + indicesOut[ outputStart ++ ] = i1; - code = str.charCodeAt( codeStart ++ ); + code = str.charCodeAt( codeStart ++ ); - var index = highest - code; - indicesOut[ outputStart ++ ] = index; + var index = highest - code; + indicesOut[ outputStart ++ ] = index; - if ( code === 0 ) { + if ( code === 0 ) { - for (var j = 0; j < 5; j ++ ) { + for (var j = 0; j < 5; j ++ ) { - var deltaCode = str.charCodeAt( deltaStart + numVerts * j + highest ); + var deltaCode = str.charCodeAt( deltaStart + numVerts * j + highest ); - var prediction = ((deltaCode >> 1) ^ (-(deltaCode & 1))) + + var prediction = ((deltaCode >> 1) ^ (-(deltaCode & 1))) + attribsOutFixed[stride * i0 + j] + attribsOutFixed[stride * i1 + j] - attribsOutFixed[stride * i2 + j]; - lastAttrib[j] = prediction; + lastAttrib[j] = prediction; - attribsOutFixed[ stride * highest + j ] = prediction; - attribsOut[ stride * highest + j ] = decodeScales[ j ] * ( prediction + decodeOffsets[ j ] ); + attribsOutFixed[ stride * highest + j ] = prediction; + attribsOut[ stride * highest + j ] = decodeScales[ j ] * ( prediction + decodeOffsets[ j ] ); - } + } - highest ++; + highest ++; - } else { + } else { - this.copyAttrib( stride, attribsOutFixed, lastAttrib, index ); + this.copyAttrib( stride, attribsOutFixed, lastAttrib, index ); - } + } - this.accumulateNormal( i0, i1, index, attribsOutFixed, crosses ); + this.accumulateNormal( i0, i1, index, attribsOutFixed, crosses ); - } else { + } else { // Simple - var index0 = highest - ( code - max_backref ); + var index0 = highest - ( code - max_backref ); - indicesOut[ outputStart ++ ] = index0; + indicesOut[ outputStart ++ ] = index0; - if ( code === max_backref ) { + if ( code === max_backref ) { - this.decodeAttrib2( str, stride, decodeOffsets, decodeScales, deltaStart, + this.decodeAttrib2( str, stride, decodeOffsets, decodeScales, deltaStart, numVerts, attribsOut, attribsOutFixed, lastAttrib, highest ++ ); - } else { + } else { - this.copyAttrib(stride, attribsOutFixed, lastAttrib, index0); + this.copyAttrib(stride, attribsOutFixed, lastAttrib, index0); - } + } - code = str.charCodeAt( codeStart ++ ); + code = str.charCodeAt( codeStart ++ ); - var index1 = highest - code; - indicesOut[ outputStart ++ ] = index1; + var index1 = highest - code; + indicesOut[ outputStart ++ ] = index1; - if ( code === 0 ) { + if ( code === 0 ) { - this.decodeAttrib2( str, stride, decodeOffsets, decodeScales, deltaStart, + this.decodeAttrib2( str, stride, decodeOffsets, decodeScales, deltaStart, numVerts, attribsOut, attribsOutFixed, lastAttrib, highest ++ ); - } else { + } else { - this.copyAttrib( stride, attribsOutFixed, lastAttrib, index1 ); + this.copyAttrib( stride, attribsOutFixed, lastAttrib, index1 ); - } + } - code = str.charCodeAt( codeStart ++ ); + code = str.charCodeAt( codeStart ++ ); - var index2 = highest - code; - indicesOut[ outputStart ++ ] = index2; + var index2 = highest - code; + indicesOut[ outputStart ++ ] = index2; - if ( code === 0 ) { + if ( code === 0 ) { - for ( var j = 0; j < 5; j ++ ) { + for ( var j = 0; j < 5; j ++ ) { - lastAttrib[ j ] = ( attribsOutFixed[ stride * index0 + j ] + attribsOutFixed[ stride * index1 + j ] ) / 2; + lastAttrib[ j ] = ( attribsOutFixed[ stride * index0 + j ] + attribsOutFixed[ stride * index1 + j ] ) / 2; - } + } - this.decodeAttrib2( str, stride, decodeOffsets, decodeScales, deltaStart, + this.decodeAttrib2( str, stride, decodeOffsets, decodeScales, deltaStart, numVerts, attribsOut, attribsOutFixed, lastAttrib, highest ++ ); - } else { + } else { - this.copyAttrib( stride, attribsOutFixed, lastAttrib, index2 ); + this.copyAttrib( stride, attribsOutFixed, lastAttrib, index2 ); - } + } - this.accumulateNormal( index0, index1, index2, attribsOutFixed, crosses ); + this.accumulateNormal( index0, index1, index2, attribsOutFixed, crosses ); - } + } - } + } - for ( var i = 0; i < numVerts; i ++ ) { + for ( var i = 0; i < numVerts; i ++ ) { - var nx = crosses[ 3 * i ]; - var ny = crosses[ 3 * i + 1 ]; - var nz = crosses[ 3 * i + 2 ]; + var nx = crosses[ 3 * i ]; + var ny = crosses[ 3 * i + 1 ]; + var nz = crosses[ 3 * i + 2 ]; - var norm = 511.0 / Math.sqrt( nx * nx + ny * ny + nz * nz ); + var norm = 511.0 / Math.sqrt( nx * nx + ny * ny + nz * nz ); - var cx = str.charCodeAt( deltaStart + 5 * numVerts + i ); - var cy = str.charCodeAt( deltaStart + 6 * numVerts + i ); - var cz = str.charCodeAt( deltaStart + 7 * numVerts + i ); + var cx = str.charCodeAt( deltaStart + 5 * numVerts + i ); + var cy = str.charCodeAt( deltaStart + 6 * numVerts + i ); + var cz = str.charCodeAt( deltaStart + 7 * numVerts + i ); - attribsOut[ stride * i + 5 ] = norm * nx + ((cx >> 1) ^ (-(cx & 1))); - attribsOut[ stride * i + 6 ] = norm * ny + ((cy >> 1) ^ (-(cy & 1))); - attribsOut[ stride * i + 7 ] = norm * nz + ((cz >> 1) ^ (-(cz & 1))); - } + attribsOut[ stride * i + 5 ] = norm * nx + ((cx >> 1) ^ (-(cx & 1))); + attribsOut[ stride * i + 6 ] = norm * ny + ((cy >> 1) ^ (-(cy & 1))); + attribsOut[ stride * i + 7 ] = norm * nz + ((cz >> 1) ^ (-(cz & 1))); + } - callback( name, idx, attribsOut, indicesOut, undefined, meshParams ); + callback( name, idx, attribsOut, indicesOut, undefined, meshParams ); }; THREE.UTF8Loader.prototype.downloadMesh = function ( path, name, meshEntry, decodeParams, callback ) { - var loader = this; - var idx = 0; + var loader = this; + var idx = 0; - function onprogress( req, e ) { + function onprogress( req, e ) { - while ( idx < meshEntry.length ) { + while ( idx < meshEntry.length ) { - var meshParams = meshEntry[ idx ]; - var indexRange = meshParams.indexRange; + var meshParams = meshEntry[ idx ]; + var indexRange = meshParams.indexRange; - if ( indexRange ) { + if ( indexRange ) { - var meshEnd = indexRange[ 0 ] + 3 * indexRange[ 1 ]; + var meshEnd = indexRange[ 0 ] + 3 * indexRange[ 1 ]; - if ( req.responseText.length < meshEnd ) break; + if ( req.responseText.length < meshEnd ) break; - loader.decompressMesh( req.responseText, meshParams, decodeParams, name, idx, callback ); + loader.decompressMesh( req.responseText, meshParams, decodeParams, name, idx, callback ); - } else { + } else { - var codeRange = meshParams.codeRange; - var meshEnd = codeRange[ 0 ] + codeRange[ 1 ]; + var codeRange = meshParams.codeRange; + var meshEnd = codeRange[ 0 ] + codeRange[ 1 ]; - if ( req.responseText.length < meshEnd ) break; + if ( req.responseText.length < meshEnd ) break; - loader.decompressMesh2( req.responseText, meshParams, decodeParams, name, idx, callback ); - } + loader.decompressMesh2( req.responseText, meshParams, decodeParams, name, idx, callback ); + } - ++ idx; + ++ idx; - } + } - }; + }; - getHttpRequest( path, function( req, e ) { + getHttpRequest( path, function( req, e ) { - if ( req.status === 200 || req.status === 0 ) { + if ( req.status === 200 || req.status === 0 ) { - onprogress( req, e ); + onprogress( req, e ); - } + } // TODO: handle errors. - }, onprogress ); + }, onprogress ); }; THREE.UTF8Loader.prototype.downloadMeshes = function ( path, meshUrlMap, decodeParams, callback ) { - for ( var url in meshUrlMap ) { + for ( var url in meshUrlMap ) { - var meshEntry = meshUrlMap[url]; - this.downloadMesh( path + url, url, meshEntry, decodeParams, callback ); + var meshEntry = meshUrlMap[url]; + this.downloadMesh( path + url, url, meshEntry, decodeParams, callback ); - } + } }; THREE.UTF8Loader.prototype.createMeshCallback = function( materialBaseUrl, loadModelInfo, allDoneCallback ) { var nCompletedUrls = 0; - var nExpectedUrls = 0; + var nExpectedUrls = 0; - var expectedMeshesPerUrl = {}; - var decodedMeshesPerUrl = {}; + var expectedMeshesPerUrl = {}; + var decodedMeshesPerUrl = {}; var modelParts = {}; var meshUrlMap = loadModelInfo.urls; - for ( var url in meshUrlMap ) { + for ( var url in meshUrlMap ) { - expectedMeshesPerUrl[ url ] = meshUrlMap[ url ].length; - decodedMeshesPerUrl[ url ] = 0; + expectedMeshesPerUrl[ url ] = meshUrlMap[ url ].length; + decodedMeshesPerUrl[ url ] = 0; nExpectedUrls ++; - modelParts[ url ] = new THREE.Object3D(); + modelParts[ url ] = new THREE.Object3D(); - } + } - var model = new THREE.Object3D(); + var model = new THREE.Object3D(); // Prepare materials first... - var materialCreator = new THREE.MTLLoader.MaterialCreator( materialBaseUrl, loadModelInfo.options ); - materialCreator.setMaterials( loadModelInfo.materials ); + var materialCreator = new THREE.MTLLoader.MaterialCreator( materialBaseUrl, loadModelInfo.options ); + materialCreator.setMaterials( loadModelInfo.materials ); - materialCreator.preload(); + materialCreator.preload(); // Create callback for creating mesh parts @@ -652,32 +652,32 @@ THREE.UTF8Loader.prototype.createMeshCallback = function( materialBaseUrl, loadM // meshParams contains the material info var geometry = bufferGeometryCreator.create( attribArray, indexArray ); - var material = materialCreator.create( meshParams.material ); + var material = materialCreator.create( meshParams.material ); var mesh = new THREE.Mesh( geometry, material ); - modelParts[ name ].add( mesh ); + modelParts[ name ].add( mesh ); //model.add(new THREE.Mesh(geometry, material)); - decodedMeshesPerUrl[ name ] ++; + decodedMeshesPerUrl[ name ] ++; - if ( decodedMeshesPerUrl[ name ] === expectedMeshesPerUrl[ name ] ) { + if ( decodedMeshesPerUrl[ name ] === expectedMeshesPerUrl[ name ] ) { - nCompletedUrls ++; + nCompletedUrls ++; - model.add( modelParts[ name ] ); + model.add( modelParts[ name ] ); - if ( nCompletedUrls === nExpectedUrls ) { + if ( nCompletedUrls === nExpectedUrls ) { // ALL DONE!!! - allDoneCallback( model ); + allDoneCallback( model ); - } + } - } + } - }; + }; return meshCallback; @@ -685,61 +685,61 @@ THREE.UTF8Loader.prototype.createMeshCallback = function( materialBaseUrl, loadM THREE.UTF8Loader.prototype.downloadModel = function ( geometryBase, materialBase, model, callback ) { - var meshCallback = this.createMeshCallback( materialBase, model, callback ); - this.downloadMeshes( geometryBase, model.urls, model.decodeParams, meshCallback ); + var meshCallback = this.createMeshCallback( materialBase, model, callback ); + this.downloadMeshes( geometryBase, model.urls, model.decodeParams, meshCallback ); }; THREE.UTF8Loader.prototype.downloadModelJson = function ( jsonUrl, callback, options ) { - getJsonRequest( jsonUrl, function( loaded ) { + getJsonRequest( jsonUrl, function( loaded ) { - if ( ! loaded.decodeParams ) { + if ( ! loaded.decodeParams ) { - if ( options && options.decodeParams ) { + if ( options && options.decodeParams ) { - loaded.decodeParams = options.decodeParams; + loaded.decodeParams = options.decodeParams; - } else { + } else { - loaded.decodeParams = DEFAULT_DECODE_PARAMS; + loaded.decodeParams = DEFAULT_DECODE_PARAMS; - } + } - } + } - loaded.options = options; + loaded.options = options; - var geometryBase = jsonUrl.substr( 0, jsonUrl.lastIndexOf( "/" ) + 1 ); - var materialBase = geometryBase; + var geometryBase = jsonUrl.substr( 0, jsonUrl.lastIndexOf( "/" ) + 1 ); + var materialBase = geometryBase; - if ( options && options.geometryBase ) { + if ( options && options.geometryBase ) { - geometryBase = options.geometryBase; + geometryBase = options.geometryBase; - if ( geometryBase.charAt( geometryBase.length - 1 ) !== "/" ) { + if ( geometryBase.charAt( geometryBase.length - 1 ) !== "/" ) { - geometryBase = geometryBase + "/"; + geometryBase = geometryBase + "/"; - } + } - } + } - if ( options && options.materialBase ) { + if ( options && options.materialBase ) { - materialBase = options.materialBase; + materialBase = options.materialBase; - if ( materialBase.charAt( materialBase.length - 1 ) !== "/" ) { + if ( materialBase.charAt( materialBase.length - 1 ) !== "/" ) { - materialBase = materialBase + "/"; + materialBase = materialBase + "/"; - } + } - } + } - this.downloadModel( geometryBase, materialBase, loaded, callback ); + this.downloadModel( geometryBase, materialBase, loaded, callback ); - }.bind( this ) ); + }.bind( this ) ); }; @@ -747,23 +747,23 @@ THREE.UTF8Loader.prototype.downloadModelJson = function ( jsonUrl, callback, opt function getHttpRequest( url, onload, opt_onprogress ) { - var LISTENERS = { + var LISTENERS = { load: function( e ) { onload( req, e ); }, progress: function( e ) { opt_onprogress( req, e ); } }; - var req = new XMLHttpRequest(); - addListeners( req, LISTENERS ); + var req = new XMLHttpRequest(); + addListeners( req, LISTENERS ); - req.open( 'GET', url, true ); - req.send( null ); + req.open( 'GET', url, true ); + req.send( null ); } function getJsonRequest( url, onjson ) { - getHttpRequest( url, + getHttpRequest( url, function( e ) { onjson( JSON.parse( e.responseText ) ); }, function() {} ); @@ -773,9 +773,9 @@ function addListeners( dom, listeners ) { // TODO: handle event capture, object binding. - for ( var key in listeners ) { + for ( var key in listeners ) { - dom.addEventListener( key, listeners[ key ] ); + dom.addEventListener( key, listeners[ key ] ); - } + } } diff --git a/examples/js/loaders/VRMLLoader.js b/examples/js/loaders/VRMLLoader.js index bf67886d4c..526434e7b7 100644 --- a/examples/js/loaders/VRMLLoader.js +++ b/examples/js/loaders/VRMLLoader.js @@ -260,7 +260,7 @@ THREE.VRMLLoader.prototype = { // end of current face if (parts[ind] === "-1") { if (index.length > 0) { - this.indexes.push(index); + this.indexes.push(index); } // start new one diff --git a/examples/js/loaders/ctm/ctm.js b/examples/js/loaders/ctm/ctm.js index df5c1f6f7d..f1f2a5277d 100755 --- a/examples/js/loaders/ctm/ctm.js +++ b/examples/js/loaders/ctm/ctm.js @@ -46,552 +46,552 @@ CTM.Flags = { }; CTM.File = function(stream) { - this.load(stream); + this.load(stream); }; CTM.File.prototype.load = function(stream) { - this.header = new CTM.FileHeader(stream); + this.header = new CTM.FileHeader(stream); - this.body = new CTM.FileBody(this.header); + this.body = new CTM.FileBody(this.header); - this.getReader().read(stream, this.body); + this.getReader().read(stream, this.body); }; CTM.File.prototype.getReader = function() { - var reader; + var reader; - switch (this.header.compressionMethod){ - case CTM.CompressionMethod.RAW: - reader = new CTM.ReaderRAW(); - break; - case CTM.CompressionMethod.MG1: - reader = new CTM.ReaderMG1(); - break; - case CTM.CompressionMethod.MG2: - reader = new CTM.ReaderMG2(); - break; - } + switch (this.header.compressionMethod){ + case CTM.CompressionMethod.RAW: + reader = new CTM.ReaderRAW(); + break; + case CTM.CompressionMethod.MG1: + reader = new CTM.ReaderMG1(); + break; + case CTM.CompressionMethod.MG2: + reader = new CTM.ReaderMG2(); + break; + } - return reader; + return reader; }; CTM.FileHeader = function(stream) { - stream.readInt32(); //magic "OCTM" - this.fileFormat = stream.readInt32(); - this.compressionMethod = stream.readInt32(); - this.vertexCount = stream.readInt32(); - this.triangleCount = stream.readInt32(); - this.uvMapCount = stream.readInt32(); - this.attrMapCount = stream.readInt32(); - this.flags = stream.readInt32(); - this.comment = stream.readString(); + stream.readInt32(); //magic "OCTM" + this.fileFormat = stream.readInt32(); + this.compressionMethod = stream.readInt32(); + this.vertexCount = stream.readInt32(); + this.triangleCount = stream.readInt32(); + this.uvMapCount = stream.readInt32(); + this.attrMapCount = stream.readInt32(); + this.flags = stream.readInt32(); + this.comment = stream.readString(); }; CTM.FileHeader.prototype.hasNormals = function() { - return this.flags & CTM.Flags.NORMALS; + return this.flags & CTM.Flags.NORMALS; }; CTM.FileBody = function(header) { - var i = header.triangleCount * 3, + var i = header.triangleCount * 3, v = header.vertexCount * 3, n = header.hasNormals() ? header.vertexCount * 3 : 0, u = header.vertexCount * 2, a = header.vertexCount * 4, j = 0; - var data = new ArrayBuffer( + var data = new ArrayBuffer( (i + v + n + (u * header.uvMapCount) + (a * header.attrMapCount) ) * 4); - this.indices = new Uint32Array(data, 0, i); + this.indices = new Uint32Array(data, 0, i); - this.vertices = new Float32Array(data, i * 4, v); + this.vertices = new Float32Array(data, i * 4, v); - if ( header.hasNormals() ) { - this.normals = new Float32Array(data, (i + v) * 4, n); - } + if ( header.hasNormals() ) { + this.normals = new Float32Array(data, (i + v) * 4, n); + } - if (header.uvMapCount) { - this.uvMaps = []; - for (j = 0; j < header.uvMapCount; ++ j) { - this.uvMaps[j] = { uv: new Float32Array(data, + if (header.uvMapCount) { + this.uvMaps = []; + for (j = 0; j < header.uvMapCount; ++ j) { + this.uvMaps[j] = { uv: new Float32Array(data, (i + v + n + (j * u) ) * 4, u) }; - } - } + } + } - if (header.attrMapCount) { - this.attrMaps = []; - for (j = 0; j < header.attrMapCount; ++ j) { - this.attrMaps[j] = { attr: new Float32Array(data, + if (header.attrMapCount) { + this.attrMaps = []; + for (j = 0; j < header.attrMapCount; ++ j) { + this.attrMaps[j] = { attr: new Float32Array(data, (i + v + n + (u * header.uvMapCount) + (j * a) ) * 4, a) }; - } - } + } + } }; CTM.FileMG2Header = function(stream) { - stream.readInt32(); //magic "MG2H" - this.vertexPrecision = stream.readFloat32(); - this.normalPrecision = stream.readFloat32(); - this.lowerBoundx = stream.readFloat32(); - this.lowerBoundy = stream.readFloat32(); - this.lowerBoundz = stream.readFloat32(); - this.higherBoundx = stream.readFloat32(); - this.higherBoundy = stream.readFloat32(); - this.higherBoundz = stream.readFloat32(); - this.divx = stream.readInt32(); - this.divy = stream.readInt32(); - this.divz = stream.readInt32(); + stream.readInt32(); //magic "MG2H" + this.vertexPrecision = stream.readFloat32(); + this.normalPrecision = stream.readFloat32(); + this.lowerBoundx = stream.readFloat32(); + this.lowerBoundy = stream.readFloat32(); + this.lowerBoundz = stream.readFloat32(); + this.higherBoundx = stream.readFloat32(); + this.higherBoundy = stream.readFloat32(); + this.higherBoundz = stream.readFloat32(); + this.divx = stream.readInt32(); + this.divy = stream.readInt32(); + this.divz = stream.readInt32(); - this.sizex = (this.higherBoundx - this.lowerBoundx) / this.divx; - this.sizey = (this.higherBoundy - this.lowerBoundy) / this.divy; - this.sizez = (this.higherBoundz - this.lowerBoundz) / this.divz; + this.sizex = (this.higherBoundx - this.lowerBoundx) / this.divx; + this.sizey = (this.higherBoundy - this.lowerBoundy) / this.divy; + this.sizez = (this.higherBoundz - this.lowerBoundz) / this.divz; }; CTM.ReaderRAW = function() { }; CTM.ReaderRAW.prototype.read = function(stream, body) { - this.readIndices(stream, body.indices); - this.readVertices(stream, body.vertices); + this.readIndices(stream, body.indices); + this.readVertices(stream, body.vertices); - if (body.normals) { - this.readNormals(stream, body.normals); - } - if (body.uvMaps) { - this.readUVMaps(stream, body.uvMaps); - } - if (body.attrMaps) { - this.readAttrMaps(stream, body.attrMaps); - } + if (body.normals) { + this.readNormals(stream, body.normals); + } + if (body.uvMaps) { + this.readUVMaps(stream, body.uvMaps); + } + if (body.attrMaps) { + this.readAttrMaps(stream, body.attrMaps); + } }; CTM.ReaderRAW.prototype.readIndices = function(stream, indices) { - stream.readInt32(); //magic "INDX" - stream.readArrayInt32(indices); + stream.readInt32(); //magic "INDX" + stream.readArrayInt32(indices); }; CTM.ReaderRAW.prototype.readVertices = function(stream, vertices) { - stream.readInt32(); //magic "VERT" - stream.readArrayFloat32(vertices); + stream.readInt32(); //magic "VERT" + stream.readArrayFloat32(vertices); }; CTM.ReaderRAW.prototype.readNormals = function(stream, normals) { - stream.readInt32(); //magic "NORM" - stream.readArrayFloat32(normals); + stream.readInt32(); //magic "NORM" + stream.readArrayFloat32(normals); }; CTM.ReaderRAW.prototype.readUVMaps = function(stream, uvMaps) { - var i = 0; - for (; i < uvMaps.length; ++ i) { - stream.readInt32(); //magic "TEXC" + var i = 0; + for (; i < uvMaps.length; ++ i) { + stream.readInt32(); //magic "TEXC" - uvMaps[i].name = stream.readString(); - uvMaps[i].filename = stream.readString(); - stream.readArrayFloat32(uvMaps[i].uv); - } + uvMaps[i].name = stream.readString(); + uvMaps[i].filename = stream.readString(); + stream.readArrayFloat32(uvMaps[i].uv); + } }; CTM.ReaderRAW.prototype.readAttrMaps = function(stream, attrMaps) { - var i = 0; - for (; i < attrMaps.length; ++ i) { - stream.readInt32(); //magic "ATTR" + var i = 0; + for (; i < attrMaps.length; ++ i) { + stream.readInt32(); //magic "ATTR" - attrMaps[i].name = stream.readString(); - stream.readArrayFloat32(attrMaps[i].attr); - } + attrMaps[i].name = stream.readString(); + stream.readArrayFloat32(attrMaps[i].attr); + } }; CTM.ReaderMG1 = function() { }; CTM.ReaderMG1.prototype.read = function(stream, body) { - this.readIndices(stream, body.indices); - this.readVertices(stream, body.vertices); + this.readIndices(stream, body.indices); + this.readVertices(stream, body.vertices); - if (body.normals) { - this.readNormals(stream, body.normals); - } - if (body.uvMaps) { - this.readUVMaps(stream, body.uvMaps); - } - if (body.attrMaps) { - this.readAttrMaps(stream, body.attrMaps); - } + if (body.normals) { + this.readNormals(stream, body.normals); + } + if (body.uvMaps) { + this.readUVMaps(stream, body.uvMaps); + } + if (body.attrMaps) { + this.readAttrMaps(stream, body.attrMaps); + } }; CTM.ReaderMG1.prototype.readIndices = function(stream, indices) { - stream.readInt32(); //magic "INDX" - stream.readInt32(); //packed size + stream.readInt32(); //magic "INDX" + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(indices, 3); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + var interleaved = new CTM.InterleavedStream(indices, 3); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); - CTM.restoreIndices(indices, indices.length); + CTM.restoreIndices(indices, indices.length); }; CTM.ReaderMG1.prototype.readVertices = function(stream, vertices) { - stream.readInt32(); //magic "VERT" - stream.readInt32(); //packed size + stream.readInt32(); //magic "VERT" + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(vertices, 1); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + var interleaved = new CTM.InterleavedStream(vertices, 1); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); }; CTM.ReaderMG1.prototype.readNormals = function(stream, normals) { - stream.readInt32(); //magic "NORM" - stream.readInt32(); //packed size + stream.readInt32(); //magic "NORM" + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(normals, 3); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + var interleaved = new CTM.InterleavedStream(normals, 3); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); }; CTM.ReaderMG1.prototype.readUVMaps = function(stream, uvMaps) { - var i = 0; - for (; i < uvMaps.length; ++ i) { - stream.readInt32(); //magic "TEXC" + var i = 0; + for (; i < uvMaps.length; ++ i) { + stream.readInt32(); //magic "TEXC" - uvMaps[i].name = stream.readString(); - uvMaps[i].filename = stream.readString(); + uvMaps[i].name = stream.readString(); + uvMaps[i].filename = stream.readString(); - stream.readInt32(); //packed size + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(uvMaps[i].uv, 2); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); - } + var interleaved = new CTM.InterleavedStream(uvMaps[i].uv, 2); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + } }; CTM.ReaderMG1.prototype.readAttrMaps = function(stream, attrMaps) { - var i = 0; - for (; i < attrMaps.length; ++ i) { - stream.readInt32(); //magic "ATTR" + var i = 0; + for (; i < attrMaps.length; ++ i) { + stream.readInt32(); //magic "ATTR" - attrMaps[i].name = stream.readString(); + attrMaps[i].name = stream.readString(); - stream.readInt32(); //packed size + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(attrMaps[i].attr, 4); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); - } + var interleaved = new CTM.InterleavedStream(attrMaps[i].attr, 4); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + } }; CTM.ReaderMG2 = function() { }; CTM.ReaderMG2.prototype.read = function(stream, body) { - this.MG2Header = new CTM.FileMG2Header(stream); + this.MG2Header = new CTM.FileMG2Header(stream); - this.readVertices(stream, body.vertices); - this.readIndices(stream, body.indices); + this.readVertices(stream, body.vertices); + this.readIndices(stream, body.indices); - if (body.normals) { - this.readNormals(stream, body); - } - if (body.uvMaps) { - this.readUVMaps(stream, body.uvMaps); - } - if (body.attrMaps) { - this.readAttrMaps(stream, body.attrMaps); - } + if (body.normals) { + this.readNormals(stream, body); + } + if (body.uvMaps) { + this.readUVMaps(stream, body.uvMaps); + } + if (body.attrMaps) { + this.readAttrMaps(stream, body.attrMaps); + } }; CTM.ReaderMG2.prototype.readVertices = function(stream, vertices) { - stream.readInt32(); //magic "VERT" - stream.readInt32(); //packed size + stream.readInt32(); //magic "VERT" + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(vertices, 3); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + var interleaved = new CTM.InterleavedStream(vertices, 3); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); - var gridIndices = this.readGridIndices(stream, vertices); + var gridIndices = this.readGridIndices(stream, vertices); - CTM.restoreVertices(vertices, this.MG2Header, gridIndices, this.MG2Header.vertexPrecision); + CTM.restoreVertices(vertices, this.MG2Header, gridIndices, this.MG2Header.vertexPrecision); }; CTM.ReaderMG2.prototype.readGridIndices = function(stream, vertices) { - stream.readInt32(); //magic "GIDX" - stream.readInt32(); //packed size + stream.readInt32(); //magic "GIDX" + stream.readInt32(); //packed size - var gridIndices = new Uint32Array(vertices.length / 3); + var gridIndices = new Uint32Array(vertices.length / 3); - var interleaved = new CTM.InterleavedStream(gridIndices, 1); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + var interleaved = new CTM.InterleavedStream(gridIndices, 1); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); - CTM.restoreGridIndices(gridIndices, gridIndices.length); + CTM.restoreGridIndices(gridIndices, gridIndices.length); - return gridIndices; + return gridIndices; }; CTM.ReaderMG2.prototype.readIndices = function(stream, indices) { - stream.readInt32(); //magic "INDX" - stream.readInt32(); //packed size + stream.readInt32(); //magic "INDX" + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(indices, 3); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + var interleaved = new CTM.InterleavedStream(indices, 3); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); - CTM.restoreIndices(indices, indices.length); + CTM.restoreIndices(indices, indices.length); }; CTM.ReaderMG2.prototype.readNormals = function(stream, body) { - stream.readInt32(); //magic "NORM" - stream.readInt32(); //packed size + stream.readInt32(); //magic "NORM" + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(body.normals, 3); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + var interleaved = new CTM.InterleavedStream(body.normals, 3); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); - var smooth = CTM.calcSmoothNormals(body.indices, body.vertices); + var smooth = CTM.calcSmoothNormals(body.indices, body.vertices); - CTM.restoreNormals(body.normals, smooth, this.MG2Header.normalPrecision); + CTM.restoreNormals(body.normals, smooth, this.MG2Header.normalPrecision); }; CTM.ReaderMG2.prototype.readUVMaps = function(stream, uvMaps) { - var i = 0; - for (; i < uvMaps.length; ++ i) { - stream.readInt32(); //magic "TEXC" + var i = 0; + for (; i < uvMaps.length; ++ i) { + stream.readInt32(); //magic "TEXC" - uvMaps[i].name = stream.readString(); - uvMaps[i].filename = stream.readString(); + uvMaps[i].name = stream.readString(); + uvMaps[i].filename = stream.readString(); - var precision = stream.readFloat32(); + var precision = stream.readFloat32(); - stream.readInt32(); //packed size + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(uvMaps[i].uv, 2); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + var interleaved = new CTM.InterleavedStream(uvMaps[i].uv, 2); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); - CTM.restoreMap(uvMaps[i].uv, 2, precision); - } + CTM.restoreMap(uvMaps[i].uv, 2, precision); + } }; CTM.ReaderMG2.prototype.readAttrMaps = function(stream, attrMaps) { - var i = 0; - for (; i < attrMaps.length; ++ i) { - stream.readInt32(); //magic "ATTR" + var i = 0; + for (; i < attrMaps.length; ++ i) { + stream.readInt32(); //magic "ATTR" - attrMaps[i].name = stream.readString(); + attrMaps[i].name = stream.readString(); - var precision = stream.readFloat32(); + var precision = stream.readFloat32(); - stream.readInt32(); //packed size + stream.readInt32(); //packed size - var interleaved = new CTM.InterleavedStream(attrMaps[i].attr, 4); - LZMA.decompress(stream, stream, interleaved, interleaved.data.length); + var interleaved = new CTM.InterleavedStream(attrMaps[i].attr, 4); + LZMA.decompress(stream, stream, interleaved, interleaved.data.length); - CTM.restoreMap(attrMaps[i].attr, 4, precision); - } + CTM.restoreMap(attrMaps[i].attr, 4, precision); + } }; CTM.restoreIndices = function(indices, len) { - var i = 3; - if (len > 0) { - indices[2] += indices[0]; - indices[1] += indices[0]; - } - for (; i < len; i += 3) { - indices[i] += indices[i - 3]; + var i = 3; + if (len > 0) { + indices[2] += indices[0]; + indices[1] += indices[0]; + } + for (; i < len; i += 3) { + indices[i] += indices[i - 3]; - if (indices[i] === indices[i - 3]) { - indices[i + 1] += indices[i - 2]; - }else { - indices[i + 1] += indices[i]; - } + if (indices[i] === indices[i - 3]) { + indices[i + 1] += indices[i - 2]; + }else { + indices[i + 1] += indices[i]; + } - indices[i + 2] += indices[i]; - } + indices[i + 2] += indices[i]; + } }; CTM.restoreGridIndices = function(gridIndices, len) { - var i = 1; - for (; i < len; ++ i) { - gridIndices[i] += gridIndices[i - 1]; - } + var i = 1; + for (; i < len; ++ i) { + gridIndices[i] += gridIndices[i - 1]; + } }; CTM.restoreVertices = function(vertices, grid, gridIndices, precision) { - var gridIdx, delta, x, y, z, + var gridIdx, delta, x, y, z, intVertices = new Uint32Array(vertices.buffer, vertices.byteOffset, vertices.length), ydiv = grid.divx, zdiv = ydiv * grid.divy, prevGridIdx = 0x7fffffff, prevDelta = 0, i = 0, j = 0, len = gridIndices.length; - for (; i < len; j += 3) { - x = gridIdx = gridIndices[i ++]; + for (; i < len; j += 3) { + x = gridIdx = gridIndices[i ++]; - z = ~~(x / zdiv); - x -= ~~(z * zdiv); - y = ~~(x / ydiv); - x -= ~~(y * ydiv); + z = ~~(x / zdiv); + x -= ~~(z * zdiv); + y = ~~(x / ydiv); + x -= ~~(y * ydiv); - delta = intVertices[j]; - if (gridIdx === prevGridIdx) { - delta += prevDelta; - } + delta = intVertices[j]; + if (gridIdx === prevGridIdx) { + delta += prevDelta; + } - vertices[j] = grid.lowerBoundx + + vertices[j] = grid.lowerBoundx + x * grid.sizex + precision * delta; - vertices[j + 1] = grid.lowerBoundy + + vertices[j + 1] = grid.lowerBoundy + y * grid.sizey + precision * intVertices[j + 1]; - vertices[j + 2] = grid.lowerBoundz + + vertices[j + 2] = grid.lowerBoundz + z * grid.sizez + precision * intVertices[j + 2]; - prevGridIdx = gridIdx; - prevDelta = delta; - } + prevGridIdx = gridIdx; + prevDelta = delta; + } }; CTM.restoreNormals = function(normals, smooth, precision) { - var ro, phi, theta, sinPhi, + var ro, phi, theta, sinPhi, nx, ny, nz, by, bz, len, intNormals = new Uint32Array(normals.buffer, normals.byteOffset, normals.length), i = 0, k = normals.length, PI_DIV_2 = 3.141592653589793238462643 * 0.5; - for (; i < k; i += 3) { - ro = intNormals[i] * precision; - phi = intNormals[i + 1]; + for (; i < k; i += 3) { + ro = intNormals[i] * precision; + phi = intNormals[i + 1]; - if (phi === 0) { - normals[i] = smooth[i] * ro; - normals[i + 1] = smooth[i + 1] * ro; - normals[i + 2] = smooth[i + 2] * ro; - }else { + if (phi === 0) { + normals[i] = smooth[i] * ro; + normals[i + 1] = smooth[i + 1] * ro; + normals[i + 2] = smooth[i + 2] * ro; + }else { - if (phi <= 4) { - theta = (intNormals[i + 2] - 2) * PI_DIV_2; - }else { - theta = ( (intNormals[i + 2] * 4 / phi) - 2) * PI_DIV_2; - } + if (phi <= 4) { + theta = (intNormals[i + 2] - 2) * PI_DIV_2; + }else { + theta = ( (intNormals[i + 2] * 4 / phi) - 2) * PI_DIV_2; + } - phi *= precision * PI_DIV_2; - sinPhi = ro * Math.sin(phi); + phi *= precision * PI_DIV_2; + sinPhi = ro * Math.sin(phi); - nx = sinPhi * Math.cos(theta); - ny = sinPhi * Math.sin(theta); - nz = ro * Math.cos(phi); + nx = sinPhi * Math.cos(theta); + ny = sinPhi * Math.sin(theta); + nz = ro * Math.cos(phi); - bz = smooth[i + 1]; - by = smooth[i] - smooth[i + 2]; + bz = smooth[i + 1]; + by = smooth[i] - smooth[i + 2]; - len = Math.sqrt(2 * bz * bz + by * by); - if (len > 1e-20) { - by /= len; - bz /= len; - } + len = Math.sqrt(2 * bz * bz + by * by); + if (len > 1e-20) { + by /= len; + bz /= len; + } - normals[i] = smooth[i] * nz + + normals[i] = smooth[i] * nz + (smooth[i + 1] * bz - smooth[i + 2] * by) * ny - bz * nx; - normals[i + 1] = smooth[i + 1] * nz - + normals[i + 1] = smooth[i + 1] * nz - (smooth[i + 2] + smooth[i] ) * bz * ny + by * nx; - normals[i + 2] = smooth[i + 2] * nz + + normals[i + 2] = smooth[i + 2] * nz + (smooth[i] * by + smooth[i + 1] * bz) * ny + bz * nx; - } - } + } + } }; CTM.restoreMap = function(map, count, precision) { - var delta, value, + var delta, value, intMap = new Uint32Array(map.buffer, map.byteOffset, map.length), i = 0, j, len = map.length; - for (; i < count; ++ i) { - delta = 0; + for (; i < count; ++ i) { + delta = 0; - for (j = i; j < len; j += count) { - value = intMap[j]; + for (j = i; j < len; j += count) { + value = intMap[j]; - delta += value & 1 ? -( (value + 1) >> 1) : value >> 1; + delta += value & 1 ? -( (value + 1) >> 1) : value >> 1; - map[j] = delta * precision; - } - } + map[j] = delta * precision; + } + } }; CTM.calcSmoothNormals = function(indices, vertices) { - var smooth = new Float32Array(vertices.length), + var smooth = new Float32Array(vertices.length), indx, indy, indz, nx, ny, nz, v1x, v1y, v1z, v2x, v2y, v2z, len, i, k; - for (i = 0, k = indices.length; i < k;) { - indx = indices[i ++] * 3; - indy = indices[i ++] * 3; - indz = indices[i ++] * 3; - - v1x = vertices[indy] - vertices[indx]; - v2x = vertices[indz] - vertices[indx]; - v1y = vertices[indy + 1] - vertices[indx + 1]; - v2y = vertices[indz + 1] - vertices[indx + 1]; - v1z = vertices[indy + 2] - vertices[indx + 2]; - v2z = vertices[indz + 2] - vertices[indx + 2]; + for (i = 0, k = indices.length; i < k;) { + indx = indices[i ++] * 3; + indy = indices[i ++] * 3; + indz = indices[i ++] * 3; + + v1x = vertices[indy] - vertices[indx]; + v2x = vertices[indz] - vertices[indx]; + v1y = vertices[indy + 1] - vertices[indx + 1]; + v2y = vertices[indz + 1] - vertices[indx + 1]; + v1z = vertices[indy + 2] - vertices[indx + 2]; + v2z = vertices[indz + 2] - vertices[indx + 2]; - nx = v1y * v2z - v1z * v2y; - ny = v1z * v2x - v1x * v2z; - nz = v1x * v2y - v1y * v2x; + nx = v1y * v2z - v1z * v2y; + ny = v1z * v2x - v1x * v2z; + nz = v1x * v2y - v1y * v2x; - len = Math.sqrt(nx * nx + ny * ny + nz * nz); - if (len > 1e-10) { - nx /= len; - ny /= len; - nz /= len; - } + len = Math.sqrt(nx * nx + ny * ny + nz * nz); + if (len > 1e-10) { + nx /= len; + ny /= len; + nz /= len; + } - smooth[indx] += nx; - smooth[indx + 1] += ny; - smooth[indx + 2] += nz; - smooth[indy] += nx; - smooth[indy + 1] += ny; - smooth[indy + 2] += nz; - smooth[indz] += nx; - smooth[indz + 1] += ny; - smooth[indz + 2] += nz; - } - - for (i = 0, k = smooth.length; i < k; i += 3) { - len = Math.sqrt(smooth[i] * smooth[i] + + smooth[indx] += nx; + smooth[indx + 1] += ny; + smooth[indx + 2] += nz; + smooth[indy] += nx; + smooth[indy + 1] += ny; + smooth[indy + 2] += nz; + smooth[indz] += nx; + smooth[indz + 1] += ny; + smooth[indz + 2] += nz; + } + + for (i = 0, k = smooth.length; i < k; i += 3) { + len = Math.sqrt(smooth[i] * smooth[i] + smooth[i + 1] * smooth[i + 1] + smooth[i + 2] * smooth[i + 2]); - if (len > 1e-10) { - smooth[i] /= len; - smooth[i + 1] /= len; - smooth[i + 2] /= len; - } - } + if (len > 1e-10) { + smooth[i] /= len; + smooth[i + 1] /= len; + smooth[i + 2] /= len; + } + } - return smooth; + return smooth; }; CTM.isLittleEndian = (function() { - var buffer = new ArrayBuffer(2), + var buffer = new ArrayBuffer(2), bytes = new Uint8Array(buffer), ints = new Uint16Array(buffer); - bytes[0] = 1; + bytes[0] = 1; - return ints[0] === 1; + return ints[0] === 1; }()); CTM.InterleavedStream = function(data, count) { - this.data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); - this.offset = CTM.isLittleEndian ? 3 : 0; - this.count = count * 4; - this.len = this.data.length; + this.data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + this.offset = CTM.isLittleEndian ? 3 : 0; + this.count = count * 4; + this.len = this.data.length; }; CTM.InterleavedStream.prototype.writeByte = function(value) { - this.data[this.offset] = value; + this.data[this.offset] = value; - this.offset += this.count; - if (this.offset >= this.len) { + this.offset += this.count; + if (this.offset >= this.len) { - this.offset -= this.len - 4; - if (this.offset >= this.count) { + this.offset -= this.len - 4; + if (this.offset >= this.count) { - this.offset -= this.count + (CTM.isLittleEndian ? 1 : -1); - } - } + this.offset -= this.count + (CTM.isLittleEndian ? 1 : -1); + } + } }; CTM.Stream = function(data) { - this.data = data; - this.offset = 0; + this.data = data; + this.offset = 0; }; CTM.Stream.prototype.TWO_POW_MINUS23 = Math.pow(2, -23); @@ -599,63 +599,63 @@ CTM.Stream.prototype.TWO_POW_MINUS23 = Math.pow(2, -23); CTM.Stream.prototype.TWO_POW_MINUS126 = Math.pow(2, -126); CTM.Stream.prototype.readByte = function() { - return this.data[this.offset ++] & 0xff; + return this.data[this.offset ++] & 0xff; }; CTM.Stream.prototype.readInt32 = function() { - var i = this.readByte(); - i |= this.readByte() << 8; - i |= this.readByte() << 16; - return i | (this.readByte() << 24); + var i = this.readByte(); + i |= this.readByte() << 8; + i |= this.readByte() << 16; + return i | (this.readByte() << 24); }; CTM.Stream.prototype.readFloat32 = function() { - var m = this.readByte(); - m += this.readByte() << 8; + var m = this.readByte(); + m += this.readByte() << 8; - var b1 = this.readByte(); - var b2 = this.readByte(); + var b1 = this.readByte(); + var b2 = this.readByte(); - m += (b1 & 0x7f) << 16; - var e = ( (b2 & 0x7f) << 1) | ( (b1 & 0x80) >>> 7); - var s = b2 & 0x80 ? -1 : 1; + m += (b1 & 0x7f) << 16; + var e = ( (b2 & 0x7f) << 1) | ( (b1 & 0x80) >>> 7); + var s = b2 & 0x80 ? -1 : 1; - if (e === 255) { - return m !== 0 ? NaN : s * Infinity; - } - if (e > 0) { - return s * (1 + (m * this.TWO_POW_MINUS23) ) * Math.pow(2, e - 127); - } - if (m !== 0) { - return s * m * this.TWO_POW_MINUS126; - } - return s * 0; + if (e === 255) { + return m !== 0 ? NaN : s * Infinity; + } + if (e > 0) { + return s * (1 + (m * this.TWO_POW_MINUS23) ) * Math.pow(2, e - 127); + } + if (m !== 0) { + return s * m * this.TWO_POW_MINUS126; + } + return s * 0; }; CTM.Stream.prototype.readString = function() { - var len = this.readInt32(); + var len = this.readInt32(); - this.offset += len; + this.offset += len; - return String.fromCharCode.apply(null, this.data.subarray(this.offset - len, this.offset)); + return String.fromCharCode.apply(null, this.data.subarray(this.offset - len, this.offset)); }; CTM.Stream.prototype.readArrayInt32 = function(array) { - var i = 0, len = array.length; + var i = 0, len = array.length; - while (i < len) { - array[i ++] = this.readInt32(); - } + while (i < len) { + array[i ++] = this.readInt32(); + } - return array; + return array; }; CTM.Stream.prototype.readArrayFloat32 = function(array) { - var i = 0, len = array.length; + var i = 0, len = array.length; - while (i < len) { - array[i ++] = this.readFloat32(); - } + while (i < len) { + array[i ++] = this.readFloat32(); + } - return array; + return array; }; diff --git a/examples/js/loaders/ctm/lzma.js b/examples/js/loaders/ctm/lzma.js index e2e83dee80..9960f2592f 100644 --- a/examples/js/loaders/ctm/lzma.js +++ b/examples/js/loaders/ctm/lzma.js @@ -9,509 +9,509 @@ if ( typeof module === 'object' ) { } LZMA.OutWindow = function() { - this._windowSize = 0; + this._windowSize = 0; }; LZMA.OutWindow.prototype.create = function(windowSize) { - if ( (!this._buffer) || (this._windowSize !== windowSize) ) { - this._buffer = []; - } - this._windowSize = windowSize; - this._pos = 0; - this._streamPos = 0; + if ( (!this._buffer) || (this._windowSize !== windowSize) ) { + this._buffer = []; + } + this._windowSize = windowSize; + this._pos = 0; + this._streamPos = 0; }; LZMA.OutWindow.prototype.flush = function() { - var size = this._pos - this._streamPos; - if (size !== 0) { - while (size --) { - this._stream.writeByte(this._buffer[this._streamPos ++]); - } - if (this._pos >= this._windowSize) { - this._pos = 0; - } - this._streamPos = this._pos; - } + var size = this._pos - this._streamPos; + if (size !== 0) { + while (size --) { + this._stream.writeByte(this._buffer[this._streamPos ++]); + } + if (this._pos >= this._windowSize) { + this._pos = 0; + } + this._streamPos = this._pos; + } }; LZMA.OutWindow.prototype.releaseStream = function() { - this.flush(); - this._stream = null; + this.flush(); + this._stream = null; }; LZMA.OutWindow.prototype.setStream = function(stream) { - this.releaseStream(); - this._stream = stream; + this.releaseStream(); + this._stream = stream; }; LZMA.OutWindow.prototype.init = function(solid) { - if (!solid) { - this._streamPos = 0; - this._pos = 0; - } + if (!solid) { + this._streamPos = 0; + this._pos = 0; + } }; LZMA.OutWindow.prototype.copyBlock = function(distance, len) { - var pos = this._pos - distance - 1; - if (pos < 0) { - pos += this._windowSize; - } - while (len --) { - if (pos >= this._windowSize) { - pos = 0; - } - this._buffer[this._pos ++] = this._buffer[pos ++]; - if (this._pos >= this._windowSize) { - this.flush(); - } - } + var pos = this._pos - distance - 1; + if (pos < 0) { + pos += this._windowSize; + } + while (len --) { + if (pos >= this._windowSize) { + pos = 0; + } + this._buffer[this._pos ++] = this._buffer[pos ++]; + if (this._pos >= this._windowSize) { + this.flush(); + } + } }; LZMA.OutWindow.prototype.putByte = function(b) { - this._buffer[this._pos ++] = b; - if (this._pos >= this._windowSize) { - this.flush(); - } + this._buffer[this._pos ++] = b; + if (this._pos >= this._windowSize) { + this.flush(); + } }; LZMA.OutWindow.prototype.getByte = function(distance) { - var pos = this._pos - distance - 1; - if (pos < 0) { - pos += this._windowSize; - } - return this._buffer[pos]; + var pos = this._pos - distance - 1; + if (pos < 0) { + pos += this._windowSize; + } + return this._buffer[pos]; }; LZMA.RangeDecoder = function() { }; LZMA.RangeDecoder.prototype.setStream = function(stream) { - this._stream = stream; + this._stream = stream; }; LZMA.RangeDecoder.prototype.releaseStream = function() { - this._stream = null; + this._stream = null; }; LZMA.RangeDecoder.prototype.init = function() { - var i = 5; + var i = 5; - this._code = 0; - this._range = -1; + this._code = 0; + this._range = -1; - while (i --) { - this._code = (this._code << 8) | this._stream.readByte(); - } + while (i --) { + this._code = (this._code << 8) | this._stream.readByte(); + } }; LZMA.RangeDecoder.prototype.decodeDirectBits = function(numTotalBits) { - var result = 0, i = numTotalBits, t; + var result = 0, i = numTotalBits, t; - while (i --) { - this._range >>>= 1; - t = (this._code - this._range) >>> 31; - this._code -= this._range & (t - 1); - result = (result << 1) | (1 - t); + while (i --) { + this._range >>>= 1; + t = (this._code - this._range) >>> 31; + this._code -= this._range & (t - 1); + result = (result << 1) | (1 - t); - if ( (this._range & 0xff000000) === 0) { - this._code = (this._code << 8) | this._stream.readByte(); - this._range <<= 8; - } - } + if ( (this._range & 0xff000000) === 0) { + this._code = (this._code << 8) | this._stream.readByte(); + this._range <<= 8; + } + } - return result; + return result; }; LZMA.RangeDecoder.prototype.decodeBit = function(probs, index) { - var prob = probs[index], + var prob = probs[index], newBound = (this._range >>> 11) * prob; - if ( (this._code ^ 0x80000000) < (newBound ^ 0x80000000) ) { - this._range = newBound; - probs[index] += (2048 - prob) >>> 5; - if ( (this._range & 0xff000000) === 0) { - this._code = (this._code << 8) | this._stream.readByte(); - this._range <<= 8; - } - return 0; - } - - this._range -= newBound; - this._code -= newBound; - probs[index] -= prob >>> 5; - if ( (this._range & 0xff000000) === 0) { - this._code = (this._code << 8) | this._stream.readByte(); - this._range <<= 8; - } - return 1; + if ( (this._code ^ 0x80000000) < (newBound ^ 0x80000000) ) { + this._range = newBound; + probs[index] += (2048 - prob) >>> 5; + if ( (this._range & 0xff000000) === 0) { + this._code = (this._code << 8) | this._stream.readByte(); + this._range <<= 8; + } + return 0; + } + + this._range -= newBound; + this._code -= newBound; + probs[index] -= prob >>> 5; + if ( (this._range & 0xff000000) === 0) { + this._code = (this._code << 8) | this._stream.readByte(); + this._range <<= 8; + } + return 1; }; LZMA.initBitModels = function(probs, len) { - while (len --) { - probs[len] = 1024; - } + while (len --) { + probs[len] = 1024; + } }; LZMA.BitTreeDecoder = function(numBitLevels) { - this._models = []; - this._numBitLevels = numBitLevels; + this._models = []; + this._numBitLevels = numBitLevels; }; LZMA.BitTreeDecoder.prototype.init = function() { - LZMA.initBitModels(this._models, 1 << this._numBitLevels); + LZMA.initBitModels(this._models, 1 << this._numBitLevels); }; LZMA.BitTreeDecoder.prototype.decode = function(rangeDecoder) { - var m = 1, i = this._numBitLevels; + var m = 1, i = this._numBitLevels; - while (i --) { - m = (m << 1) | rangeDecoder.decodeBit(this._models, m); - } - return m - (1 << this._numBitLevels); + while (i --) { + m = (m << 1) | rangeDecoder.decodeBit(this._models, m); + } + return m - (1 << this._numBitLevels); }; LZMA.BitTreeDecoder.prototype.reverseDecode = function(rangeDecoder) { - var m = 1, symbol = 0, i = 0, bit; + var m = 1, symbol = 0, i = 0, bit; - for (; i < this._numBitLevels; ++ i) { - bit = rangeDecoder.decodeBit(this._models, m); - m = (m << 1) | bit; - symbol |= bit << i; - } - return symbol; + for (; i < this._numBitLevels; ++ i) { + bit = rangeDecoder.decodeBit(this._models, m); + m = (m << 1) | bit; + symbol |= bit << i; + } + return symbol; }; LZMA.reverseDecode2 = function(models, startIndex, rangeDecoder, numBitLevels) { - var m = 1, symbol = 0, i = 0, bit; + var m = 1, symbol = 0, i = 0, bit; - for (; i < numBitLevels; ++ i) { - bit = rangeDecoder.decodeBit(models, startIndex + m); - m = (m << 1) | bit; - symbol |= bit << i; - } - return symbol; + for (; i < numBitLevels; ++ i) { + bit = rangeDecoder.decodeBit(models, startIndex + m); + m = (m << 1) | bit; + symbol |= bit << i; + } + return symbol; }; LZMA.LenDecoder = function() { - this._choice = []; - this._lowCoder = []; - this._midCoder = []; - this._highCoder = new LZMA.BitTreeDecoder(8); - this._numPosStates = 0; + this._choice = []; + this._lowCoder = []; + this._midCoder = []; + this._highCoder = new LZMA.BitTreeDecoder(8); + this._numPosStates = 0; }; LZMA.LenDecoder.prototype.create = function(numPosStates) { - for (; this._numPosStates < numPosStates; ++ this._numPosStates) { - this._lowCoder[this._numPosStates] = new LZMA.BitTreeDecoder(3); - this._midCoder[this._numPosStates] = new LZMA.BitTreeDecoder(3); - } + for (; this._numPosStates < numPosStates; ++ this._numPosStates) { + this._lowCoder[this._numPosStates] = new LZMA.BitTreeDecoder(3); + this._midCoder[this._numPosStates] = new LZMA.BitTreeDecoder(3); + } }; LZMA.LenDecoder.prototype.init = function() { - var i = this._numPosStates; - LZMA.initBitModels(this._choice, 2); - while (i --) { - this._lowCoder[i].init(); - this._midCoder[i].init(); - } - this._highCoder.init(); + var i = this._numPosStates; + LZMA.initBitModels(this._choice, 2); + while (i --) { + this._lowCoder[i].init(); + this._midCoder[i].init(); + } + this._highCoder.init(); }; LZMA.LenDecoder.prototype.decode = function(rangeDecoder, posState) { - if (rangeDecoder.decodeBit(this._choice, 0) === 0) { - return this._lowCoder[posState].decode(rangeDecoder); - } - if (rangeDecoder.decodeBit(this._choice, 1) === 0) { - return 8 + this._midCoder[posState].decode(rangeDecoder); - } - return 16 + this._highCoder.decode(rangeDecoder); + if (rangeDecoder.decodeBit(this._choice, 0) === 0) { + return this._lowCoder[posState].decode(rangeDecoder); + } + if (rangeDecoder.decodeBit(this._choice, 1) === 0) { + return 8 + this._midCoder[posState].decode(rangeDecoder); + } + return 16 + this._highCoder.decode(rangeDecoder); }; LZMA.Decoder2 = function() { - this._decoders = []; + this._decoders = []; }; LZMA.Decoder2.prototype.init = function() { - LZMA.initBitModels(this._decoders, 0x300); + LZMA.initBitModels(this._decoders, 0x300); }; LZMA.Decoder2.prototype.decodeNormal = function(rangeDecoder) { - var symbol = 1; + var symbol = 1; - do { - symbol = (symbol << 1) | rangeDecoder.decodeBit(this._decoders, symbol); - }while (symbol < 0x100); + do { + symbol = (symbol << 1) | rangeDecoder.decodeBit(this._decoders, symbol); + }while (symbol < 0x100); - return symbol & 0xff; + return symbol & 0xff; }; LZMA.Decoder2.prototype.decodeWithMatchByte = function(rangeDecoder, matchByte) { - var symbol = 1, matchBit, bit; + var symbol = 1, matchBit, bit; - do { - matchBit = (matchByte >> 7) & 1; - matchByte <<= 1; - bit = rangeDecoder.decodeBit(this._decoders, ( (1 + matchBit) << 8) + symbol); - symbol = (symbol << 1) | bit; - if (matchBit !== bit) { - while (symbol < 0x100) { - symbol = (symbol << 1) | rangeDecoder.decodeBit(this._decoders, symbol); - } - break; - } - }while (symbol < 0x100); + do { + matchBit = (matchByte >> 7) & 1; + matchByte <<= 1; + bit = rangeDecoder.decodeBit(this._decoders, ( (1 + matchBit) << 8) + symbol); + symbol = (symbol << 1) | bit; + if (matchBit !== bit) { + while (symbol < 0x100) { + symbol = (symbol << 1) | rangeDecoder.decodeBit(this._decoders, symbol); + } + break; + } + }while (symbol < 0x100); - return symbol & 0xff; + return symbol & 0xff; }; LZMA.LiteralDecoder = function() { }; LZMA.LiteralDecoder.prototype.create = function(numPosBits, numPrevBits) { - var i; + var i; - if (this._coders + if (this._coders && (this._numPrevBits === numPrevBits) && (this._numPosBits === numPosBits) ) { - return; - } - this._numPosBits = numPosBits; - this._posMask = (1 << numPosBits) - 1; - this._numPrevBits = numPrevBits; + return; + } + this._numPosBits = numPosBits; + this._posMask = (1 << numPosBits) - 1; + this._numPrevBits = numPrevBits; - this._coders = []; + this._coders = []; - i = 1 << (this._numPrevBits + this._numPosBits); - while (i --) { - this._coders[i] = new LZMA.Decoder2(); - } + i = 1 << (this._numPrevBits + this._numPosBits); + while (i --) { + this._coders[i] = new LZMA.Decoder2(); + } }; LZMA.LiteralDecoder.prototype.init = function() { - var i = 1 << (this._numPrevBits + this._numPosBits); - while (i --) { - this._coders[i].init(); - } + var i = 1 << (this._numPrevBits + this._numPosBits); + while (i --) { + this._coders[i].init(); + } }; LZMA.LiteralDecoder.prototype.getDecoder = function(pos, prevByte) { - return this._coders[( (pos & this._posMask) << this._numPrevBits) + return this._coders[( (pos & this._posMask) << this._numPrevBits) + ( (prevByte & 0xff) >>> (8 - this._numPrevBits) )]; }; LZMA.Decoder = function() { - this._outWindow = new LZMA.OutWindow(); - this._rangeDecoder = new LZMA.RangeDecoder(); - this._isMatchDecoders = []; - this._isRepDecoders = []; - this._isRepG0Decoders = []; - this._isRepG1Decoders = []; - this._isRepG2Decoders = []; - this._isRep0LongDecoders = []; - this._posSlotDecoder = []; - this._posDecoders = []; - this._posAlignDecoder = new LZMA.BitTreeDecoder(4); - this._lenDecoder = new LZMA.LenDecoder(); - this._repLenDecoder = new LZMA.LenDecoder(); - this._literalDecoder = new LZMA.LiteralDecoder(); - this._dictionarySize = -1; - this._dictionarySizeCheck = -1; - - this._posSlotDecoder[0] = new LZMA.BitTreeDecoder(6); - this._posSlotDecoder[1] = new LZMA.BitTreeDecoder(6); - this._posSlotDecoder[2] = new LZMA.BitTreeDecoder(6); - this._posSlotDecoder[3] = new LZMA.BitTreeDecoder(6); + this._outWindow = new LZMA.OutWindow(); + this._rangeDecoder = new LZMA.RangeDecoder(); + this._isMatchDecoders = []; + this._isRepDecoders = []; + this._isRepG0Decoders = []; + this._isRepG1Decoders = []; + this._isRepG2Decoders = []; + this._isRep0LongDecoders = []; + this._posSlotDecoder = []; + this._posDecoders = []; + this._posAlignDecoder = new LZMA.BitTreeDecoder(4); + this._lenDecoder = new LZMA.LenDecoder(); + this._repLenDecoder = new LZMA.LenDecoder(); + this._literalDecoder = new LZMA.LiteralDecoder(); + this._dictionarySize = -1; + this._dictionarySizeCheck = -1; + + this._posSlotDecoder[0] = new LZMA.BitTreeDecoder(6); + this._posSlotDecoder[1] = new LZMA.BitTreeDecoder(6); + this._posSlotDecoder[2] = new LZMA.BitTreeDecoder(6); + this._posSlotDecoder[3] = new LZMA.BitTreeDecoder(6); }; LZMA.Decoder.prototype.setDictionarySize = function(dictionarySize) { - if (dictionarySize < 0) { - return false; - } - if (this._dictionarySize !== dictionarySize) { - this._dictionarySize = dictionarySize; - this._dictionarySizeCheck = Math.max(this._dictionarySize, 1); - this._outWindow.create( Math.max(this._dictionarySizeCheck, 4096) ); - } - return true; + if (dictionarySize < 0) { + return false; + } + if (this._dictionarySize !== dictionarySize) { + this._dictionarySize = dictionarySize; + this._dictionarySizeCheck = Math.max(this._dictionarySize, 1); + this._outWindow.create( Math.max(this._dictionarySizeCheck, 4096) ); + } + return true; }; LZMA.Decoder.prototype.setLcLpPb = function(lc, lp, pb) { - var numPosStates = 1 << pb; + var numPosStates = 1 << pb; - if (lc > 8 || lp > 4 || pb > 4) { - return false; - } + if (lc > 8 || lp > 4 || pb > 4) { + return false; + } - this._literalDecoder.create(lp, lc); + this._literalDecoder.create(lp, lc); - this._lenDecoder.create(numPosStates); - this._repLenDecoder.create(numPosStates); - this._posStateMask = numPosStates - 1; + this._lenDecoder.create(numPosStates); + this._repLenDecoder.create(numPosStates); + this._posStateMask = numPosStates - 1; - return true; + return true; }; LZMA.Decoder.prototype.init = function() { - var i = 4; + var i = 4; - this._outWindow.init(false); + this._outWindow.init(false); - LZMA.initBitModels(this._isMatchDecoders, 192); - LZMA.initBitModels(this._isRep0LongDecoders, 192); - LZMA.initBitModels(this._isRepDecoders, 12); - LZMA.initBitModels(this._isRepG0Decoders, 12); - LZMA.initBitModels(this._isRepG1Decoders, 12); - LZMA.initBitModels(this._isRepG2Decoders, 12); - LZMA.initBitModels(this._posDecoders, 114); + LZMA.initBitModels(this._isMatchDecoders, 192); + LZMA.initBitModels(this._isRep0LongDecoders, 192); + LZMA.initBitModels(this._isRepDecoders, 12); + LZMA.initBitModels(this._isRepG0Decoders, 12); + LZMA.initBitModels(this._isRepG1Decoders, 12); + LZMA.initBitModels(this._isRepG2Decoders, 12); + LZMA.initBitModels(this._posDecoders, 114); - this._literalDecoder.init(); + this._literalDecoder.init(); - while (i --) { - this._posSlotDecoder[i].init(); - } + while (i --) { + this._posSlotDecoder[i].init(); + } - this._lenDecoder.init(); - this._repLenDecoder.init(); - this._posAlignDecoder.init(); - this._rangeDecoder.init(); + this._lenDecoder.init(); + this._repLenDecoder.init(); + this._posAlignDecoder.init(); + this._rangeDecoder.init(); }; LZMA.Decoder.prototype.decode = function(inStream, outStream, outSize) { - var state = 0, rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0, nowPos64 = 0, prevByte = 0, + var state = 0, rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0, nowPos64 = 0, prevByte = 0, posState, decoder2, len, distance, posSlot, numDirectBits; - this._rangeDecoder.setStream(inStream); - this._outWindow.setStream(outStream); - - this.init(); - - while (outSize < 0 || nowPos64 < outSize) { - posState = nowPos64 & this._posStateMask; - - if (this._rangeDecoder.decodeBit(this._isMatchDecoders, (state << 4) + posState) === 0) { - decoder2 = this._literalDecoder.getDecoder(nowPos64 ++, prevByte); - - if (state >= 7) { - prevByte = decoder2.decodeWithMatchByte(this._rangeDecoder, this._outWindow.getByte(rep0) ); - }else { - prevByte = decoder2.decodeNormal(this._rangeDecoder); - } - this._outWindow.putByte(prevByte); - - state = state < 4 ? 0 : state - (state < 10 ? 3 : 6); - - }else { - - if (this._rangeDecoder.decodeBit(this._isRepDecoders, state) === 1) { - len = 0; - if (this._rangeDecoder.decodeBit(this._isRepG0Decoders, state) === 0) { - if (this._rangeDecoder.decodeBit(this._isRep0LongDecoders, (state << 4) + posState) === 0) { - state = state < 7 ? 9 : 11; - len = 1; - } - }else { - if (this._rangeDecoder.decodeBit(this._isRepG1Decoders, state) === 0) { - distance = rep1; - }else { - if (this._rangeDecoder.decodeBit(this._isRepG2Decoders, state) === 0) { - distance = rep2; - }else { - distance = rep3; - rep3 = rep2; - } - rep2 = rep1; - } - rep1 = rep0; - rep0 = distance; - } - if (len === 0) { - len = 2 + this._repLenDecoder.decode(this._rangeDecoder, posState); - state = state < 7 ? 8 : 11; - } - }else { - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - - len = 2 + this._lenDecoder.decode(this._rangeDecoder, posState); - state = state < 7 ? 7 : 10; - - posSlot = this._posSlotDecoder[len <= 5 ? len - 2 : 3].decode(this._rangeDecoder); - if (posSlot >= 4) { - - numDirectBits = (posSlot >> 1) - 1; - rep0 = (2 | (posSlot & 1) ) << numDirectBits; - - if (posSlot < 14) { - rep0 += LZMA.reverseDecode2(this._posDecoders, + this._rangeDecoder.setStream(inStream); + this._outWindow.setStream(outStream); + + this.init(); + + while (outSize < 0 || nowPos64 < outSize) { + posState = nowPos64 & this._posStateMask; + + if (this._rangeDecoder.decodeBit(this._isMatchDecoders, (state << 4) + posState) === 0) { + decoder2 = this._literalDecoder.getDecoder(nowPos64 ++, prevByte); + + if (state >= 7) { + prevByte = decoder2.decodeWithMatchByte(this._rangeDecoder, this._outWindow.getByte(rep0) ); + }else { + prevByte = decoder2.decodeNormal(this._rangeDecoder); + } + this._outWindow.putByte(prevByte); + + state = state < 4 ? 0 : state - (state < 10 ? 3 : 6); + + }else { + + if (this._rangeDecoder.decodeBit(this._isRepDecoders, state) === 1) { + len = 0; + if (this._rangeDecoder.decodeBit(this._isRepG0Decoders, state) === 0) { + if (this._rangeDecoder.decodeBit(this._isRep0LongDecoders, (state << 4) + posState) === 0) { + state = state < 7 ? 9 : 11; + len = 1; + } + }else { + if (this._rangeDecoder.decodeBit(this._isRepG1Decoders, state) === 0) { + distance = rep1; + }else { + if (this._rangeDecoder.decodeBit(this._isRepG2Decoders, state) === 0) { + distance = rep2; + }else { + distance = rep3; + rep3 = rep2; + } + rep2 = rep1; + } + rep1 = rep0; + rep0 = distance; + } + if (len === 0) { + len = 2 + this._repLenDecoder.decode(this._rangeDecoder, posState); + state = state < 7 ? 8 : 11; + } + }else { + rep3 = rep2; + rep2 = rep1; + rep1 = rep0; + + len = 2 + this._lenDecoder.decode(this._rangeDecoder, posState); + state = state < 7 ? 7 : 10; + + posSlot = this._posSlotDecoder[len <= 5 ? len - 2 : 3].decode(this._rangeDecoder); + if (posSlot >= 4) { + + numDirectBits = (posSlot >> 1) - 1; + rep0 = (2 | (posSlot & 1) ) << numDirectBits; + + if (posSlot < 14) { + rep0 += LZMA.reverseDecode2(this._posDecoders, rep0 - posSlot - 1, this._rangeDecoder, numDirectBits); - }else { - rep0 += this._rangeDecoder.decodeDirectBits(numDirectBits - 4) << 4; - rep0 += this._posAlignDecoder.reverseDecode(this._rangeDecoder); - if (rep0 < 0) { - if (rep0 === -1) { - break; - } - return false; - } - } - }else { - rep0 = posSlot; - } - } - - if (rep0 >= nowPos64 || rep0 >= this._dictionarySizeCheck) { - return false; - } - - this._outWindow.copyBlock(rep0, len); - nowPos64 += len; - prevByte = this._outWindow.getByte(0); - } - } - - this._outWindow.flush(); - this._outWindow.releaseStream(); - this._rangeDecoder.releaseStream(); - - return true; + }else { + rep0 += this._rangeDecoder.decodeDirectBits(numDirectBits - 4) << 4; + rep0 += this._posAlignDecoder.reverseDecode(this._rangeDecoder); + if (rep0 < 0) { + if (rep0 === -1) { + break; + } + return false; + } + } + }else { + rep0 = posSlot; + } + } + + if (rep0 >= nowPos64 || rep0 >= this._dictionarySizeCheck) { + return false; + } + + this._outWindow.copyBlock(rep0, len); + nowPos64 += len; + prevByte = this._outWindow.getByte(0); + } + } + + this._outWindow.flush(); + this._outWindow.releaseStream(); + this._rangeDecoder.releaseStream(); + + return true; }; LZMA.Decoder.prototype.setDecoderProperties = function(properties) { - var value, lc, lp, pb, dictionarySize; + var value, lc, lp, pb, dictionarySize; - if (properties.size < 5) { - return false; - } + if (properties.size < 5) { + return false; + } - value = properties.readByte(); - lc = value % 9; - value = ~~(value / 9); - lp = value % 5; - pb = ~~(value / 5); + value = properties.readByte(); + lc = value % 9; + value = ~~(value / 9); + lp = value % 5; + pb = ~~(value / 5); - if ( !this.setLcLpPb(lc, lp, pb) ) { - return false; - } + if ( !this.setLcLpPb(lc, lp, pb) ) { + return false; + } - dictionarySize = properties.readByte(); - dictionarySize |= properties.readByte() << 8; - dictionarySize |= properties.readByte() << 16; - dictionarySize += properties.readByte() * 16777216; + dictionarySize = properties.readByte(); + dictionarySize |= properties.readByte() << 8; + dictionarySize |= properties.readByte() << 16; + dictionarySize += properties.readByte() * 16777216; - return this.setDictionarySize(dictionarySize); + return this.setDictionarySize(dictionarySize); }; LZMA.decompress = function(properties, inStream, outStream, outSize) { - var decoder = new LZMA.Decoder(); + var decoder = new LZMA.Decoder(); - if ( !decoder.setDecoderProperties(properties) ) { - throw "Incorrect stream properties"; - } + if ( !decoder.setDecoderProperties(properties) ) { + throw "Incorrect stream properties"; + } - if ( !decoder.decode(inStream, outStream, outSize) ) { - throw "Error in data stream"; - } + if ( !decoder.decode(inStream, outStream, outSize) ) { + throw "Error in data stream"; + } - return true; + return true; }; diff --git a/examples/js/loaders/deprecated/SceneLoader.js b/examples/js/loaders/deprecated/SceneLoader.js index aa163f5ae9..93447f7a73 100644 --- a/examples/js/loaders/deprecated/SceneLoader.js +++ b/examples/js/loaders/deprecated/SceneLoader.js @@ -430,7 +430,7 @@ THREE.SceneLoader.prototype = { } else if ( objJSON.target ) { - camera.lookAt( new THREE.Vector3().fromArray( objJSON.target ) ); + camera.lookAt( new THREE.Vector3().fromArray( objJSON.target ) ); } diff --git a/examples/js/loaders/gltf/glTF-parser.js b/examples/js/loaders/gltf/glTF-parser.js index ed53d2a380..30476f7b29 100755 --- a/examples/js/loaders/gltf/glTF-parser.js +++ b/examples/js/loaders/gltf/glTF-parser.js @@ -49,35 +49,35 @@ */ var global = window; (function (root, factory) { - if (typeof exports === 'object') { + if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. - factory(module.exports); - } else if (typeof define === 'function' && define.amd) { + factory(module.exports); + } else if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([], function () { - return factory(root); - }); - } else { + define([], function () { + return factory(root); + }); + } else { // Browser globals - factory(root); - } + factory(root); + } }(this, function (root) { - "use strict"; + "use strict"; - var categoriesDepsOrder = [ "buffers", "bufferViews", "images", "videos", "samplers", "textures", "shaders", "programs", "techniques", "materials", "accessors", "meshes", "cameras", "lights", "skins", "nodes", "scenes", "animations" ]; + var categoriesDepsOrder = [ "buffers", "bufferViews", "images", "videos", "samplers", "textures", "shaders", "programs", "techniques", "materials", "accessors", "meshes", "cameras", "lights", "skins", "nodes", "scenes", "animations" ]; - var glTFParser = Object.create(Object.prototype, { + var glTFParser = Object.create(Object.prototype, { _rootDescription: { value: null, writable: true }, rootDescription: { set: function(value) { - this._rootDescription = value; + this._rootDescription = value; }, get: function() { - return this._rootDescription; + return this._rootDescription; } }, @@ -86,34 +86,34 @@ var global = window; //detect absolute path following the same protocol than window.location _isAbsolutePath: { value: function(path) { - var isAbsolutePathRegExp = new RegExp("^" + window.location.protocol, "i"); + var isAbsolutePathRegExp = new RegExp("^" + window.location.protocol, "i"); - return path.match(isAbsolutePathRegExp) ? true : false; + return path.match(isAbsolutePathRegExp) ? true : false; } }, resolvePathIfNeeded: { value: function(path) { - if (this._isAbsolutePath(path)) { - return path; - } + if (this._isAbsolutePath(path)) { + return path; + } - return this.baseURL + path; + return this.baseURL + path; } }, _resolvePathsForCategories: { value: function(categories) { - categories.forEach( function(category) { - var descriptions = this.json[category]; - if (descriptions) { - var descriptionKeys = Object.keys(descriptions); - descriptionKeys.forEach( function(descriptionKey) { - var description = descriptions[descriptionKey]; - description.path = this.resolvePathIfNeeded(description.path); - }, this); - } - }, this); + categories.forEach( function(category) { + var descriptions = this.json[category]; + if (descriptions) { + var descriptionKeys = Object.keys(descriptions); + descriptionKeys.forEach( function(descriptionKey) { + var description = descriptions[descriptionKey]; + description.path = this.resolvePathIfNeeded(description.path); + }, this); + } + }, this); } }, @@ -125,13 +125,13 @@ var global = window; json: { enumerable: true, get: function() { - return this._json; + return this._json; }, set: function(value) { - if (this._json !== value) { - this._json = value; - this._resolvePathsForCategories([ "buffers", "shaders", "images", "videos" ]); - } + if (this._json !== value) { + this._json = value; + this._resolvePathsForCategories([ "buffers", "shaders", "images", "videos" ]); + } } }, @@ -142,60 +142,60 @@ var global = window; getEntryDescription: { value: function (entryID, entryType) { - var entries = null; + var entries = null; - var category = entryType; - entries = this.rootDescription[category]; - if (!entries) { - console.log("ERROR:CANNOT find expected category named:" + category); - return null; - } + var category = entryType; + entries = this.rootDescription[category]; + if (!entries) { + console.log("ERROR:CANNOT find expected category named:" + category); + return null; + } - return entries ? entries[entryID] : null; + return entries ? entries[entryID] : null; } }, _stepToNextCategory: { value: function() { - this._state.categoryIndex = this.getNextCategoryIndex(this._state.categoryIndex + 1); - if (this._state.categoryIndex !== -1) { - this._state.categoryState.index = 0; - return true; - } + this._state.categoryIndex = this.getNextCategoryIndex(this._state.categoryIndex + 1); + if (this._state.categoryIndex !== -1) { + this._state.categoryState.index = 0; + return true; + } - return false; + return false; } }, _stepToNextDescription: { enumerable: false, value: function() { - var categoryState = this._state.categoryState; - var keys = categoryState.keys; - if (!keys) { - console.log("INCONSISTENCY ERROR"); - return false; - } - - categoryState.index ++; - categoryState.keys = null; - if (categoryState.index >= keys.length) { - return this._stepToNextCategory(); - } - return false; + var categoryState = this._state.categoryState; + var keys = categoryState.keys; + if (!keys) { + console.log("INCONSISTENCY ERROR"); + return false; + } + + categoryState.index ++; + categoryState.keys = null; + if (categoryState.index >= keys.length) { + return this._stepToNextCategory(); + } + return false; } }, hasCategory: { value: function(category) { - return this.rootDescription[category] ? true : false; + return this.rootDescription[category] ? true : false; } }, _handleState: { value: function() { - var methodForType = { + var methodForType = { "buffers" : this.handleBuffer, "bufferViews" : this.handleBufferView, "shaders" : this.handleShader, @@ -217,46 +217,46 @@ var global = window; }; - var success = true; - while (this._state.categoryIndex !== -1) { - var category = categoriesDepsOrder[this._state.categoryIndex]; - var categoryState = this._state.categoryState; - var keys = categoryState.keys; - if (!keys) { - categoryState.keys = keys = Object.keys(this.rootDescription[category]); - if (keys) { - if (keys.length == 0) { - this._stepToNextDescription(); - continue; - } - } - } - - var type = category; - var entryID = keys[categoryState.index]; - var description = this.getEntryDescription(entryID, type); - if (!description) { - if (this.handleError) { - this.handleError("INCONSISTENCY ERROR: no description found for entry " + entryID); - success = false; - break; - } - } else { - - if (methodForType[type]) { - if (methodForType[type].call(this, entryID, description, this._state.userInfo) === false) { - success = false; - break; - } - } - - this._stepToNextDescription(); - } - } - - if (this.handleLoadCompleted) { - this.handleLoadCompleted(success); - } + var success = true; + while (this._state.categoryIndex !== -1) { + var category = categoriesDepsOrder[this._state.categoryIndex]; + var categoryState = this._state.categoryState; + var keys = categoryState.keys; + if (!keys) { + categoryState.keys = keys = Object.keys(this.rootDescription[category]); + if (keys) { + if (keys.length == 0) { + this._stepToNextDescription(); + continue; + } + } + } + + var type = category; + var entryID = keys[categoryState.index]; + var description = this.getEntryDescription(entryID, type); + if (!description) { + if (this.handleError) { + this.handleError("INCONSISTENCY ERROR: no description found for entry " + entryID); + success = false; + break; + } + } else { + + if (methodForType[type]) { + if (methodForType[type].call(this, entryID, description, this._state.userInfo) === false) { + success = false; + break; + } + } + + this._stepToNextDescription(); + } + } + + if (this.handleLoadCompleted) { + this.handleLoadCompleted(success); + } } }, @@ -264,40 +264,40 @@ var global = window; _loadJSONIfNeeded: { enumerable: true, value: function(callback) { - var self = this; + var self = this; //FIXME: handle error - if (!this._json) { - var jsonPath = this._path; - var i = jsonPath.lastIndexOf("/"); - this.baseURL = (i !== 0) ? jsonPath.substring(0, i + 1) : ''; - var jsonfile = new XMLHttpRequest(); - jsonfile.open("GET", jsonPath, true); - jsonfile.addEventListener( 'load', function ( event ) { - self.json = JSON.parse(jsonfile.responseText); - if (callback) { - callback(self.json); - } - }, false ); - jsonfile.send(null); - } else { - if (callback) { - callback(this.json); - } - } + if (!this._json) { + var jsonPath = this._path; + var i = jsonPath.lastIndexOf("/"); + this.baseURL = (i !== 0) ? jsonPath.substring(0, i + 1) : ''; + var jsonfile = new XMLHttpRequest(); + jsonfile.open("GET", jsonPath, true); + jsonfile.addEventListener( 'load', function ( event ) { + self.json = JSON.parse(jsonfile.responseText); + if (callback) { + callback(self.json); + } + }, false ); + jsonfile.send(null); + } else { + if (callback) { + callback(this.json); + } + } } }, /* load JSON and assign it as description to the reader */ _buildLoader: { value: function(callback) { - var self = this; - function JSONReady(json) { - self.rootDescription = json; - if (callback) + var self = this; + function JSONReady(json) { + self.rootDescription = json; + if (callback) callback(this); - } + } - this._loadJSONIfNeeded(JSONReady); + this._loadJSONIfNeeded(JSONReady); } }, @@ -305,51 +305,51 @@ var global = window; _getEntryType: { value: function(entryID) { - var rootKeys = categoriesDepsOrder; - for (var i = 0 ; i < rootKeys.length ; i ++) { - var rootValues = this.rootDescription[rootKeys[i]]; - if (rootValues) { - return rootKeys[i]; - } - } - return null; + var rootKeys = categoriesDepsOrder; + for (var i = 0 ; i < rootKeys.length ; i ++) { + var rootValues = this.rootDescription[rootKeys[i]]; + if (rootValues) { + return rootKeys[i]; + } + } + return null; } }, getNextCategoryIndex: { value: function(currentIndex) { - for (var i = currentIndex ; i < categoriesDepsOrder.length ; i ++) { - if (this.hasCategory(categoriesDepsOrder[i])) { - return i; - } - } + for (var i = currentIndex ; i < categoriesDepsOrder.length ; i ++) { + if (this.hasCategory(categoriesDepsOrder[i])) { + return i; + } + } - return -1; + return -1; } }, load: { enumerable: true, value: function(userInfo, options) { - var self = this; - this._buildLoader(function loaderReady(reader) { - var startCategory = self.getNextCategoryIndex.call(self, 0); - if (startCategory !== -1) { - self._state = { "userInfo" : userInfo, + var self = this; + this._buildLoader(function loaderReady(reader) { + var startCategory = self.getNextCategoryIndex.call(self, 0); + if (startCategory !== -1) { + self._state = { "userInfo" : userInfo, "options" : options, "categoryIndex" : startCategory, "categoryState" : { "index" : "0" } }; - self._handleState(); - } - }); + self._handleState(); + } + }); } }, initWithPath: { value: function(path) { - this._path = path; - this._json = null; - return this; + this._path = path; + this._json = null; + return this; } }, @@ -359,30 +359,30 @@ var global = window; //to be invoked by subclass, so that ids can be ensured to not overlap loaderContext: { value: function() { - if (typeof this._knownURLs[this._path] === "undefined") { - this._knownURLs[this._path] = Object.keys(this._knownURLs).length; - } - return "__" + this._knownURLs[this._path]; + if (typeof this._knownURLs[this._path] === "undefined") { + this._knownURLs[this._path] = Object.keys(this._knownURLs).length; + } + return "__" + this._knownURLs[this._path]; } }, initWithJSON: { value: function(json, baseURL) { - this.json = json; - this.baseURL = baseURL; - if (!baseURL) { - console.log("WARNING: no base URL passed to Reader:initWithJSON"); - } - return this; + this.json = json; + this.baseURL = baseURL; + if (!baseURL) { + console.log("WARNING: no base URL passed to Reader:initWithJSON"); + } + return this; } } }); - if (root) { - root.glTFParser = glTFParser; - } + if (root) { + root.glTFParser = glTFParser; + } - return glTFParser; + return glTFParser; })); diff --git a/examples/js/loaders/gltf/glTFLoader.js b/examples/js/loaders/gltf/glTFLoader.js index 10d397f9dd..ff429405bf 100644 --- a/examples/js/loaders/gltf/glTFLoader.js +++ b/examples/js/loaders/gltf/glTFLoader.js @@ -4,16 +4,16 @@ THREE.glTFLoader = function (showStatus) { - this.meshesRequested = 0; - this.meshesLoaded = 0; - this.pendingMeshes = []; - this.animationsRequested = 0; - this.animationsLoaded = 0; - this.animations = []; - this.shadersRequested = 0; - this.shadersLoaded = 0; - this.shaders = {}; - THREE.Loader.call( this, showStatus ); + this.meshesRequested = 0; + this.meshesLoaded = 0; + this.pendingMeshes = []; + this.animationsRequested = 0; + this.animationsLoaded = 0; + this.animations = []; + this.shadersRequested = 0; + this.shadersLoaded = 0; + this.shaders = {}; + THREE.Loader.call( this, showStatus ); } THREE.glTFLoader.prototype = Object.create( THREE.Loader.prototype ); @@ -24,490 +24,490 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { var theLoader = this; // Utilities - function RgbArraytoHex(colorArray) { - if (!colorArray) return 0xFFFFFFFF; - var r = Math.floor(colorArray[0] * 255), + function RgbArraytoHex(colorArray) { + if (!colorArray) return 0xFFFFFFFF; + var r = Math.floor(colorArray[0] * 255), g = Math.floor(colorArray[1] * 255), b = Math.floor(colorArray[2] * 255), a = 255; - var color = (a << 24) + (r << 16) + (g << 8) + b; + var color = (a << 24) + (r << 16) + (g << 8) + b; - return color; - } + return color; + } - function convertAxisAngleToQuaternion(rotations, count) + function convertAxisAngleToQuaternion(rotations, count) { - var q = new THREE.Quaternion; - var axis = new THREE.Vector3; - var euler = new THREE.Vector3; + var q = new THREE.Quaternion; + var axis = new THREE.Vector3; + var euler = new THREE.Vector3; - var i; - for (i = 0; i < count; i ++) { - axis.set(rotations[i * 4], rotations[i * 4 + 1], + var i; + for (i = 0; i < count; i ++) { + axis.set(rotations[i * 4], rotations[i * 4 + 1], rotations[i * 4 + 2]).normalize(); - var angle = rotations[i * 4 + 3]; - q.setFromAxisAngle(axis, angle); - rotations[i * 4] = q.x; - rotations[i * 4 + 1] = q.y; - rotations[i * 4 + 2] = q.z; - rotations[i * 4 + 3] = q.w; - } - } + var angle = rotations[i * 4 + 3]; + q.setFromAxisAngle(axis, angle); + rotations[i * 4] = q.x; + rotations[i * 4 + 1] = q.y; + rotations[i * 4 + 2] = q.z; + rotations[i * 4 + 3] = q.w; + } + } - function componentsPerElementForGLType(glType) { - switch (glType) { - case WebGLRenderingContext.FLOAT : - case WebGLRenderingContext.UNSIGNED_BYTE : - case WebGLRenderingContext.UNSIGNED_SHORT : - return 1; - case WebGLRenderingContext.FLOAT_VEC2 : - return 2; - case WebGLRenderingContext.FLOAT_VEC3 : - return 3; - case WebGLRenderingContext.FLOAT_VEC4 : - return 4; - case WebGLRenderingContext.FLOAT_MAT4 : - return 16; - default: - return null; - } - } + function componentsPerElementForGLType(glType) { + switch (glType) { + case WebGLRenderingContext.FLOAT : + case WebGLRenderingContext.UNSIGNED_BYTE : + case WebGLRenderingContext.UNSIGNED_SHORT : + return 1; + case WebGLRenderingContext.FLOAT_VEC2 : + return 2; + case WebGLRenderingContext.FLOAT_VEC3 : + return 3; + case WebGLRenderingContext.FLOAT_VEC4 : + return 4; + case WebGLRenderingContext.FLOAT_MAT4 : + return 16; + default: + return null; + } + } - function LoadTexture(src) { - if (!src) { return null; } - return THREE.ImageUtils.loadTexture(src); - } + function LoadTexture(src) { + if (!src) { return null; } + return THREE.ImageUtils.loadTexture(src); + } // Geometry processing - var ClassicGeometry = function() { + var ClassicGeometry = function() { - this.geometry = new THREE.BufferGeometry; + this.geometry = new THREE.BufferGeometry; - this.totalAttributes = 0; - this.loadedAttributes = 0; - this.indicesLoaded = false; - this.finished = false; + this.totalAttributes = 0; + this.loadedAttributes = 0; + this.indicesLoaded = false; + this.finished = false; - this.onload = null; + this.onload = null; - this.uvs = null; - this.indexArray = null; - }; + this.uvs = null; + this.indexArray = null; + }; - ClassicGeometry.prototype.constructor = ClassicGeometry; + ClassicGeometry.prototype.constructor = ClassicGeometry; - ClassicGeometry.prototype.buildBufferGeometry = function() { + ClassicGeometry.prototype.buildBufferGeometry = function() { // Build indexed mesh - var geometry = this.geometry; + var geometry = this.geometry; - geometry.addAttribute( 'index', new THREE.BufferAttribute( this.indexArray, 1 ) ); - geometry.addDrawCall( 0, this.indexArray.length, 0 ); + geometry.addAttribute( 'index', new THREE.BufferAttribute( this.indexArray, 1 ) ); + geometry.addDrawCall( 0, this.indexArray.length, 0 ); - geometry.computeBoundingSphere(); - } + geometry.computeBoundingSphere(); + } - ClassicGeometry.prototype.checkFinished = function() { - if (this.indexArray && this.loadedAttributes === this.totalAttributes) { + ClassicGeometry.prototype.checkFinished = function() { + if (this.indexArray && this.loadedAttributes === this.totalAttributes) { - this.buildBufferGeometry(); + this.buildBufferGeometry(); - this.finished = true; + this.finished = true; - if (this.onload) { - this.onload(); - } - } - }; + if (this.onload) { + this.onload(); + } + } + }; // Delegate for processing index buffers - var IndicesDelegate = function() {}; + var IndicesDelegate = function() {}; - IndicesDelegate.prototype.handleError = function(errorCode, info) { + IndicesDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error - console.log("ERROR(IndicesDelegate):" + errorCode + ":" + info); - }; - - IndicesDelegate.prototype.convert = function(resource, ctx) { - return new Uint16Array(resource, 0, ctx.indices.count); - }; - - IndicesDelegate.prototype.resourceAvailable = function(glResource, ctx) { - var geometry = ctx.geometry; - geometry.indexArray = glResource; - geometry.checkFinished(); - return true; - }; - - var indicesDelegate = new IndicesDelegate(); - - var IndicesContext = function(indices, geometry) { - this.indices = indices; - this.geometry = geometry; - }; + console.log("ERROR(IndicesDelegate):" + errorCode + ":" + info); + }; + + IndicesDelegate.prototype.convert = function(resource, ctx) { + return new Uint16Array(resource, 0, ctx.indices.count); + }; + + IndicesDelegate.prototype.resourceAvailable = function(glResource, ctx) { + var geometry = ctx.geometry; + geometry.indexArray = glResource; + geometry.checkFinished(); + return true; + }; + + var indicesDelegate = new IndicesDelegate(); + + var IndicesContext = function(indices, geometry) { + this.indices = indices; + this.geometry = geometry; + }; // Delegate for processing vertex attribute buffers - var VertexAttributeDelegate = function() {}; + var VertexAttributeDelegate = function() {}; - VertexAttributeDelegate.prototype.handleError = function(errorCode, info) { + VertexAttributeDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error - console.log("ERROR(VertexAttributeDelegate):" + errorCode + ":" + info); - }; + console.log("ERROR(VertexAttributeDelegate):" + errorCode + ":" + info); + }; - VertexAttributeDelegate.prototype.convert = function(resource, ctx) { - return resource; - }; + VertexAttributeDelegate.prototype.convert = function(resource, ctx) { + return resource; + }; - VertexAttributeDelegate.prototype.arrayResourceAvailable = function(glResource, ctx) { - var geom = ctx.geometry; - var attribute = ctx.attribute; - var semantic = ctx.semantic; - var floatArray; - var i, l; + VertexAttributeDelegate.prototype.arrayResourceAvailable = function(glResource, ctx) { + var geom = ctx.geometry; + var attribute = ctx.attribute; + var semantic = ctx.semantic; + var floatArray; + var i, l; //FIXME: Float32 is assumed here, but should be checked. - if (semantic == "POSITION") { + if (semantic == "POSITION") { // TODO: Should be easy to take strides into account here - floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); - for (i = 0, l = floatArray.length; i < l; i += 3) { - geom.geometry.vertices.push( new THREE.Vector3( floatArray[i], floatArray[i + 1], floatArray[i + 2] ) ); - } - } else if (semantic == "NORMAL") { - geom.geometry.normals = []; - floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); - for (i = 0, l = floatArray.length; i < l; i += 3) { - geom.geometry.normals.push( new THREE.Vector3( floatArray[i], floatArray[i + 1], floatArray[i + 2] ) ); - } - } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) { - geom.uvs = []; - floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); - for (i = 0, l = floatArray.length; i < l; i += 2) { - geom.uvs.push( new THREE.Vector2( floatArray[i], 1.0 - floatArray[i + 1] ) ); - } - } + floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); + for (i = 0, l = floatArray.length; i < l; i += 3) { + geom.geometry.vertices.push( new THREE.Vector3( floatArray[i], floatArray[i + 1], floatArray[i + 2] ) ); + } + } else if (semantic == "NORMAL") { + geom.geometry.normals = []; + floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); + for (i = 0, l = floatArray.length; i < l; i += 3) { + geom.geometry.normals.push( new THREE.Vector3( floatArray[i], floatArray[i + 1], floatArray[i + 2] ) ); + } + } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) { + geom.uvs = []; + floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); + for (i = 0, l = floatArray.length; i < l; i += 2) { + geom.uvs.push( new THREE.Vector2( floatArray[i], 1.0 - floatArray[i + 1] ) ); + } + } else if (semantic == "WEIGHT") { - nComponents = componentsPerElementForGLType(attribute.type); - floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); - for (i = 0, l = floatArray.length; i < l; i += 4) { - geom.geometry.skinWeights.push( new THREE.Vector4( floatArray[i], floatArray[i + 1], floatArray[i + 2], floatArray[i + 3] ) ); - } + nComponents = componentsPerElementForGLType(attribute.type); + floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); + for (i = 0, l = floatArray.length; i < l; i += 4) { + geom.geometry.skinWeights.push( new THREE.Vector4( floatArray[i], floatArray[i + 1], floatArray[i + 2], floatArray[i + 3] ) ); + } } else if (semantic == "JOINT") { - nComponents = componentsPerElementForGLType(attribute.type); - floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); - for (i = 0, l = floatArray.length; i < l; i += 4) { - geom.geometry.skinIndices.push( new THREE.Vector4( floatArray[i], floatArray[i + 1], floatArray[i + 2], floatArray[i + 3] ) ); - } + nComponents = componentsPerElementForGLType(attribute.type); + floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); + for (i = 0, l = floatArray.length; i < l; i += 4) { + geom.geometry.skinIndices.push( new THREE.Vector4( floatArray[i], floatArray[i + 1], floatArray[i + 2], floatArray[i + 3] ) ); + } } - } + } - VertexAttributeDelegate.prototype.bufferResourceAvailable = function(glResource, ctx) { - var geom = ctx.geometry; - var attribute = ctx.attribute; - var semantic = ctx.semantic; - var floatArray; - var i, l; - var nComponents; + VertexAttributeDelegate.prototype.bufferResourceAvailable = function(glResource, ctx) { + var geom = ctx.geometry; + var attribute = ctx.attribute; + var semantic = ctx.semantic; + var floatArray; + var i, l; + var nComponents; //FIXME: Float32 is assumed here, but should be checked. - if (semantic == "POSITION") { + if (semantic == "POSITION") { // TODO: Should be easy to take strides into account here - floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); - geom.geometry.addAttribute( 'position', new THREE.BufferAttribute( floatArray, 3 ) ); - } else if (semantic == "NORMAL") { - floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); - geom.geometry.addAttribute( 'normal', new THREE.BufferAttribute( floatArray, 3 ) ); - } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) { + floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); + geom.geometry.addAttribute( 'position', new THREE.BufferAttribute( floatArray, 3 ) ); + } else if (semantic == "NORMAL") { + floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); + geom.geometry.addAttribute( 'normal', new THREE.BufferAttribute( floatArray, 3 ) ); + } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) { - nComponents = componentsPerElementForGLType(attribute.type); - floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); + nComponents = componentsPerElementForGLType(attribute.type); + floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); // N.B.: flip Y value... should we just set texture.flipY everywhere? - for (i = 0; i < floatArray.length / 2; i ++) { - floatArray[i * 2 + 1] = 1.0 - floatArray[i * 2 + 1]; - } - geom.geometry.addAttribute( 'uv', new THREE.BufferAttribute( floatArray, nComponents ) ); - } + for (i = 0; i < floatArray.length / 2; i ++) { + floatArray[i * 2 + 1] = 1.0 - floatArray[i * 2 + 1]; + } + geom.geometry.addAttribute( 'uv', new THREE.BufferAttribute( floatArray, nComponents ) ); + } else if (semantic == "WEIGHT") { - nComponents = componentsPerElementForGLType(attribute.type); - floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); - geom.geometry.addAttribute( 'skinWeight', new THREE.BufferAttribute( floatArray, nComponents ) ); + nComponents = componentsPerElementForGLType(attribute.type); + floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); + geom.geometry.addAttribute( 'skinWeight', new THREE.BufferAttribute( floatArray, nComponents ) ); } else if (semantic == "JOINT") { - nComponents = componentsPerElementForGLType(attribute.type); - floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); - geom.geometry.addAttribute( 'skinIndex', new THREE.BufferAttribute( floatArray, nComponents ) ); + nComponents = componentsPerElementForGLType(attribute.type); + floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); + geom.geometry.addAttribute( 'skinIndex', new THREE.BufferAttribute( floatArray, nComponents ) ); } - } + } - VertexAttributeDelegate.prototype.resourceAvailable = function(glResource, ctx) { + VertexAttributeDelegate.prototype.resourceAvailable = function(glResource, ctx) { - this.bufferResourceAvailable(glResource, ctx); + this.bufferResourceAvailable(glResource, ctx); - var geom = ctx.geometry; - geom.loadedAttributes ++; - geom.checkFinished(); - return true; - }; - - var vertexAttributeDelegate = new VertexAttributeDelegate(); - - var VertexAttributeContext = function(attribute, semantic, geometry) { - this.attribute = attribute; - this.semantic = semantic; - this.geometry = geometry; - }; - - var Mesh = function() { - this.primitives = []; - this.materialsPending = []; - this.loadedGeometry = 0; - this.onCompleteCallbacks = []; - }; - - Mesh.prototype.addPrimitive = function(geometry, material) { + var geom = ctx.geometry; + geom.loadedAttributes ++; + geom.checkFinished(); + return true; + }; + + var vertexAttributeDelegate = new VertexAttributeDelegate(); + + var VertexAttributeContext = function(attribute, semantic, geometry) { + this.attribute = attribute; + this.semantic = semantic; + this.geometry = geometry; + }; + + var Mesh = function() { + this.primitives = []; + this.materialsPending = []; + this.loadedGeometry = 0; + this.onCompleteCallbacks = []; + }; + + Mesh.prototype.addPrimitive = function(geometry, material) { - var self = this; - geometry.onload = function() { - self.loadedGeometry ++; - self.checkComplete(); - }; + var self = this; + geometry.onload = function() { + self.loadedGeometry ++; + self.checkComplete(); + }; - this.primitives.push({ + this.primitives.push({ geometry: geometry, material: material, mesh: null }); - }; - - Mesh.prototype.onComplete = function(callback) { - this.onCompleteCallbacks.push(callback); - this.checkComplete(); - }; - - Mesh.prototype.checkComplete = function() { - var self = this; - if (this.onCompleteCallbacks.length && this.primitives.length == this.loadedGeometry) { - this.onCompleteCallbacks.forEach(function(callback) { - callback(self); - }); - this.onCompleteCallbacks = []; - } - }; + }; + + Mesh.prototype.onComplete = function(callback) { + this.onCompleteCallbacks.push(callback); + this.checkComplete(); + }; + + Mesh.prototype.checkComplete = function() { + var self = this; + if (this.onCompleteCallbacks.length && this.primitives.length == this.loadedGeometry) { + this.onCompleteCallbacks.forEach(function(callback) { + callback(self); + }); + this.onCompleteCallbacks = []; + } + }; - Mesh.prototype.attachToNode = function(threeNode) { + Mesh.prototype.attachToNode = function(threeNode) { // Assumes that the geometry is complete - this.primitives.forEach(function(primitive) { + this.primitives.forEach(function(primitive) { /*if(!primitive.mesh) { primitive.mesh = new THREE.Mesh(primitive.geometry, primitive.material); }*/ - var material = primitive.material; - if (!(material instanceof THREE.Material)) { - material = theLoader.createShaderMaterial(material); - } - - var threeMesh = new THREE.Mesh(primitive.geometry.geometry, material); - threeMesh.castShadow = true; - threeNode.add(threeMesh); - }); - }; + var material = primitive.material; + if (!(material instanceof THREE.Material)) { + material = theLoader.createShaderMaterial(material); + } + + var threeMesh = new THREE.Mesh(primitive.geometry.geometry, material); + threeMesh.castShadow = true; + threeNode.add(threeMesh); + }); + }; // Delayed-loaded material - var Material = function(params) { - this.params = params; - }; + var Material = function(params) { + this.params = params; + }; // Delegate for processing animation parameter buffers - var AnimationParameterDelegate = function() {}; + var AnimationParameterDelegate = function() {}; - AnimationParameterDelegate.prototype.handleError = function(errorCode, info) { + AnimationParameterDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error - console.log("ERROR(AnimationParameterDelegate):" + errorCode + ":" + info); - }; - - AnimationParameterDelegate.prototype.convert = function(resource, ctx) { - var parameter = ctx.parameter; - - var glResource = null; - switch (parameter.type) { - case WebGLRenderingContext.FLOAT : - case WebGLRenderingContext.FLOAT_VEC2 : - case WebGLRenderingContext.FLOAT_VEC3 : - case WebGLRenderingContext.FLOAT_VEC4 : - glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type)); - break; - default: - break; - } + console.log("ERROR(AnimationParameterDelegate):" + errorCode + ":" + info); + }; + + AnimationParameterDelegate.prototype.convert = function(resource, ctx) { + var parameter = ctx.parameter; + + var glResource = null; + switch (parameter.type) { + case WebGLRenderingContext.FLOAT : + case WebGLRenderingContext.FLOAT_VEC2 : + case WebGLRenderingContext.FLOAT_VEC3 : + case WebGLRenderingContext.FLOAT_VEC4 : + glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type)); + break; + default: + break; + } - return glResource; - }; + return glResource; + }; - AnimationParameterDelegate.prototype.resourceAvailable = function(glResource, ctx) { - var animation = ctx.animation; - var parameter = ctx.parameter; - parameter.data = glResource; - animation.handleParameterLoaded(parameter); - return true; - }; + AnimationParameterDelegate.prototype.resourceAvailable = function(glResource, ctx) { + var animation = ctx.animation; + var parameter = ctx.parameter; + parameter.data = glResource; + animation.handleParameterLoaded(parameter); + return true; + }; - var animationParameterDelegate = new AnimationParameterDelegate(); + var animationParameterDelegate = new AnimationParameterDelegate(); - var AnimationParameterContext = function(parameter, animation) { - this.parameter = parameter; - this.animation = animation; - }; + var AnimationParameterContext = function(parameter, animation) { + this.parameter = parameter; + this.animation = animation; + }; // Animations - var Animation = function() { + var Animation = function() { // create Three.js keyframe here - this.totalParameters = 0; - this.loadedParameters = 0; - this.parameters = {}; - this.finishedLoading = false; - this.onload = null; + this.totalParameters = 0; + this.loadedParameters = 0; + this.parameters = {}; + this.finishedLoading = false; + this.onload = null; - }; + }; - Animation.prototype.constructor = Animation; + Animation.prototype.constructor = Animation; - Animation.prototype.handleParameterLoaded = function(parameter) { - this.parameters[parameter.name] = parameter; - this.loadedParameters ++; - this.checkFinished(); - }; + Animation.prototype.handleParameterLoaded = function(parameter) { + this.parameters[parameter.name] = parameter; + this.loadedParameters ++; + this.checkFinished(); + }; - Animation.prototype.checkFinished = function() { - if (this.loadedParameters === this.totalParameters) { + Animation.prototype.checkFinished = function() { + if (this.loadedParameters === this.totalParameters) { // Build animation - this.finishedLoading = true; + this.finishedLoading = true; - if (this.onload) { - this.onload(); - } - } - }; + if (this.onload) { + this.onload(); + } + } + }; // Delegate for processing inverse bind matrices buffer - var InverseBindMatricesDelegate = function() {}; + var InverseBindMatricesDelegate = function() {}; - InverseBindMatricesDelegate.prototype.handleError = function(errorCode, info) { + InverseBindMatricesDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error - console.log("ERROR(InverseBindMatricesDelegate):" + errorCode + ":" + info); - }; - - InverseBindMatricesDelegate.prototype.convert = function(resource, ctx) { - var parameter = ctx.parameter; - - var glResource = null; - switch (parameter.type) { - case WebGLRenderingContext.FLOAT_MAT4 : - glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type)); - break; - default: - break; - } + console.log("ERROR(InverseBindMatricesDelegate):" + errorCode + ":" + info); + }; + + InverseBindMatricesDelegate.prototype.convert = function(resource, ctx) { + var parameter = ctx.parameter; + + var glResource = null; + switch (parameter.type) { + case WebGLRenderingContext.FLOAT_MAT4 : + glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type)); + break; + default: + break; + } - return glResource; - }; + return glResource; + }; - InverseBindMatricesDelegate.prototype.resourceAvailable = function(glResource, ctx) { - var skin = ctx.skin; - skin.inverseBindMatrices = glResource; - return true; - }; + InverseBindMatricesDelegate.prototype.resourceAvailable = function(glResource, ctx) { + var skin = ctx.skin; + skin.inverseBindMatrices = glResource; + return true; + }; - var inverseBindMatricesDelegate = new InverseBindMatricesDelegate(); + var inverseBindMatricesDelegate = new InverseBindMatricesDelegate(); - var InverseBindMatricesContext = function(param, skin) { - this.parameter = param; - this.skin = skin; - }; + var InverseBindMatricesContext = function(param, skin) { + this.parameter = param; + this.skin = skin; + }; // Delegate for processing shaders from external files - var ShaderDelegate = function() {}; + var ShaderDelegate = function() {}; - ShaderDelegate.prototype.handleError = function(errorCode, info) { + ShaderDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error - console.log("ERROR(ShaderDelegate):" + errorCode + ":" + info); - }; + console.log("ERROR(ShaderDelegate):" + errorCode + ":" + info); + }; - ShaderDelegate.prototype.convert = function(resource, ctx) { - return resource; - } + ShaderDelegate.prototype.convert = function(resource, ctx) { + return resource; + } - ShaderDelegate.prototype.resourceAvailable = function(data, ctx) { - theLoader.shadersLoaded ++; - theLoader.shaders[ctx.id] = data; - return true; - }; - - var shaderDelegate = new ShaderDelegate(); - - var ShaderContext = function(id, path) { - this.id = id; - this.path = path; - }; + ShaderDelegate.prototype.resourceAvailable = function(data, ctx) { + theLoader.shadersLoaded ++; + theLoader.shaders[ctx.id] = data; + return true; + }; + + var shaderDelegate = new ShaderDelegate(); + + var ShaderContext = function(id, path) { + this.id = id; + this.path = path; + }; // Resource management - var ResourceEntry = function(entryID, object, description) { - this.entryID = entryID; - this.object = object; - this.description = description; - }; + var ResourceEntry = function(entryID, object, description) { + this.entryID = entryID; + this.object = object; + this.description = description; + }; - var Resources = function() { - this._entries = {}; - }; + var Resources = function() { + this._entries = {}; + }; - Resources.prototype.setEntry = function(entryID, object, description) { - if (!entryID) { - console.error("No EntryID provided, cannot store", description); - return; - } + Resources.prototype.setEntry = function(entryID, object, description) { + if (!entryID) { + console.error("No EntryID provided, cannot store", description); + return; + } - if (this._entries[entryID]) { - console.warn("entry[" + entryID + "] is being overwritten"); - } + if (this._entries[entryID]) { + console.warn("entry[" + entryID + "] is being overwritten"); + } - this._entries[entryID] = new ResourceEntry(entryID, object, description ); - }; + this._entries[entryID] = new ResourceEntry(entryID, object, description ); + }; - Resources.prototype.getEntry = function(entryID) { - return this._entries[entryID]; - }; + Resources.prototype.getEntry = function(entryID) { + return this._entries[entryID]; + }; - Resources.prototype.clearEntries = function() { - this._entries = {}; - }; + Resources.prototype.clearEntries = function() { + this._entries = {}; + }; - LoadDelegate = function() { + LoadDelegate = function() { } - LoadDelegate.prototype.loadCompleted = function(callback, obj) { - callback.call(Window, obj); - } + LoadDelegate.prototype.loadCompleted = function(callback, obj) { + callback.call(Window, obj); + } // Loader - var ThreeGLTFLoader = Object.create(glTFParser, { + var ThreeGLTFLoader = Object.create(glTFParser, { load: { enumerable: true, value: function(userInfo, options) { - this.resources = new Resources(); - this.cameras = []; - this.lights = []; - this.animations = []; - this.joints = {}; - this.skeltons = {}; - THREE.GLTFLoaderUtils.init(); - glTFParser.load.call(this, userInfo, options); + this.resources = new Resources(); + this.cameras = []; + this.lights = []; + this.animations = []; + this.joints = {}; + this.skeltons = {}; + THREE.GLTFLoaderUtils.init(); + glTFParser.load.call(this, userInfo, options); } }, @@ -533,73 +533,73 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { handleBuffer: { value: function(entryID, description, userInfo) { - this.resources.setEntry(entryID, null, description); - description.type = "ArrayBuffer"; - return true; + this.resources.setEntry(entryID, null, description); + description.type = "ArrayBuffer"; + return true; } }, handleBufferView: { value: function(entryID, description, userInfo) { - this.resources.setEntry(entryID, null, description); + this.resources.setEntry(entryID, null, description); - var buffer = this.resources.getEntry(description.buffer); - description.type = "ArrayBufferView"; + var buffer = this.resources.getEntry(description.buffer); + description.type = "ArrayBufferView"; - var bufferViewEntry = this.resources.getEntry(entryID); - bufferViewEntry.buffer = buffer; - return true; + var bufferViewEntry = this.resources.getEntry(entryID); + bufferViewEntry.buffer = buffer; + return true; } }, handleShader: { value: function(entryID, description, userInfo) { - this.resources.setEntry(entryID, null, description); - var shaderRequest = { + this.resources.setEntry(entryID, null, description); + var shaderRequest = { id : entryID, path : description.path, }; - var shaderContext = new ShaderContext(entryID, description.path); + var shaderContext = new ShaderContext(entryID, description.path); - theLoader.shadersRequested ++; - THREE.GLTFLoaderUtils.getFile(shaderRequest, shaderDelegate, shaderContext); + theLoader.shadersRequested ++; + THREE.GLTFLoaderUtils.getFile(shaderRequest, shaderDelegate, shaderContext); - return true; + return true; } }, handleProgram: { value: function(entryID, description, userInfo) { - this.resources.setEntry(entryID, null, description); - return true; + this.resources.setEntry(entryID, null, description); + return true; } }, handleTechnique: { value: function(entryID, description, userInfo) { - this.resources.setEntry(entryID, null, description); - return true; + this.resources.setEntry(entryID, null, description); + return true; } }, createShaderMaterial : { value: function(material) { - var fragmentShader = theLoader.shaders[material.params.fragmentShader]; - if (!fragmentShader) { - console.log("ERROR: Missing fragment shader definition:", material.params.fragmentShader); - return new THREE.MeshPhongMaterial; - } + var fragmentShader = theLoader.shaders[material.params.fragmentShader]; + if (!fragmentShader) { + console.log("ERROR: Missing fragment shader definition:", material.params.fragmentShader); + return new THREE.MeshPhongMaterial; + } - var vertexShader = theLoader.shaders[material.params.vertexShader]; - if (!fragmentShader) { - console.log("ERROR: Missing vertex shader definition:", material.params.vertexShader); - return new THREE.MeshPhongMaterial; - } + var vertexShader = theLoader.shaders[material.params.vertexShader]; + if (!fragmentShader) { + console.log("ERROR: Missing vertex shader definition:", material.params.vertexShader); + return new THREE.MeshPhongMaterial; + } - var uniforms = {}; - var shaderMaterial = new THREE.ShaderMaterial( { + var uniforms = {}; + var shaderMaterial = new THREE.ShaderMaterial( { fragmentShader: fragmentShader, vertexShader: vertexShader, @@ -607,195 +607,195 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { } ); - return new THREE.MeshPhongMaterial(material.params); + return new THREE.MeshPhongMaterial(material.params); } }, createShaderParams : { value: function(materialId, values, params, instanceProgram) { - var program = this.resources.getEntry(instanceProgram.program); + var program = this.resources.getEntry(instanceProgram.program); - if (program) { - params.fragmentShader = program.description.fragmentShader; - params.vertexShader = program.description.vertexShader; - params.attributes = instanceProgram.attributes; - params.uniforms = instanceProgram.uniforms; - } + if (program) { + params.fragmentShader = program.description.fragmentShader; + params.vertexShader = program.description.vertexShader; + params.attributes = instanceProgram.attributes; + params.uniforms = instanceProgram.uniforms; + } } }, threeJSMaterialType : { value: function(materialId, technique, values, params) { - var materialType = THREE.MeshPhongMaterial; - var defaultPass = null; - if (technique && technique.description && technique.description.passes) + var materialType = THREE.MeshPhongMaterial; + var defaultPass = null; + if (technique && technique.description && technique.description.passes) defaultPass = technique.description.passes.defaultPass; - if (defaultPass) { - if (defaultPass.details && defaultPass.details.commonProfile) { - var profile = technique.description.passes.defaultPass.details.commonProfile; - if (profile) + if (defaultPass) { + if (defaultPass.details && defaultPass.details.commonProfile) { + var profile = technique.description.passes.defaultPass.details.commonProfile; + if (profile) { - switch (profile.lightingModel) + switch (profile.lightingModel) { - case 'Blinn' : - case 'Phong' : - materialType = THREE.MeshPhongMaterial; - break; + case 'Blinn' : + case 'Phong' : + materialType = THREE.MeshPhongMaterial; + break; - case 'Lambert' : - materialType = THREE.MeshLambertMaterial; - break; + case 'Lambert' : + materialType = THREE.MeshLambertMaterial; + break; - default : - materialType = THREE.MeshBasicMaterial; - break; - } + default : + materialType = THREE.MeshBasicMaterial; + break; + } - if (profile.extras && profile.extras.doubleSided) + if (profile.extras && profile.extras.doubleSided) { - params.side = THREE.DoubleSide; - } - } - } + params.side = THREE.DoubleSide; + } + } + } else if (defaultPass.instanceProgram) { - var instanceProgram = defaultPass.instanceProgram; + var instanceProgram = defaultPass.instanceProgram; - this.createShaderParams(materialId, values, params, instanceProgram); + this.createShaderParams(materialId, values, params, instanceProgram); - var loadshaders = true; + var loadshaders = true; - if (loadshaders) { - materialType = Material; - } + if (loadshaders) { + materialType = Material; + } } - } + } - var texturePath = null; - var textureParams = null; - var diffuse = values.diffuse; - if (diffuse) + var texturePath = null; + var textureParams = null; + var diffuse = values.diffuse; + if (diffuse) { - var texture = diffuse; - if (texture) { - var textureEntry = this.resources.getEntry(texture); - if (textureEntry) { - { - var imageEntry = this.resources.getEntry(textureEntry.description.source); - if (imageEntry) { - texturePath = imageEntry.description.path; - } + var texture = diffuse; + if (texture) { + var textureEntry = this.resources.getEntry(texture); + if (textureEntry) { + { + var imageEntry = this.resources.getEntry(textureEntry.description.source); + if (imageEntry) { + texturePath = imageEntry.description.path; + } - var samplerEntry = this.resources.getEntry(textureEntry.description.sampler); - if (samplerEntry) { - textureParams = samplerEntry.description; - } - } - } - } - } - - var texture = LoadTexture(texturePath); - if (texture && textureParams) { + var samplerEntry = this.resources.getEntry(textureEntry.description.sampler); + if (samplerEntry) { + textureParams = samplerEntry.description; + } + } + } + } + } + + var texture = LoadTexture(texturePath); + if (texture && textureParams) { - if (textureParams.wrapS == WebGLRenderingContext.REPEAT) + if (textureParams.wrapS == WebGLRenderingContext.REPEAT) texture.wrapS = THREE.RepeatWrapping; - if (textureParams.wrapT == WebGLRenderingContext.REPEAT) + if (textureParams.wrapT == WebGLRenderingContext.REPEAT) texture.wrapT = THREE.RepeatWrapping; - if (textureParams.magFilter == WebGLRenderingContext.LINEAR) + if (textureParams.magFilter == WebGLRenderingContext.LINEAR) texture.magFilter = THREE.LinearFilter; // if (textureParams.minFilter == "LINEAR") // texture.minFilter = THREE.LinearFilter; - params.map = texture; - } + params.map = texture; + } - var envMapPath = null; - var envMapParams = null; - var reflective = values.reflective; - if (reflective) + var envMapPath = null; + var envMapParams = null; + var reflective = values.reflective; + if (reflective) { - var texture = reflective; - if (texture) { - var textureEntry = this.resources.getEntry(texture); - if (textureEntry) { - { - var imageEntry = this.resources.getEntry(textureEntry.description.source); - if (imageEntry) { - envMapPath = imageEntry.description.path; - } + var texture = reflective; + if (texture) { + var textureEntry = this.resources.getEntry(texture); + if (textureEntry) { + { + var imageEntry = this.resources.getEntry(textureEntry.description.source); + if (imageEntry) { + envMapPath = imageEntry.description.path; + } - var samplerEntry = this.resources.getEntry(textureEntry.description.sampler); - if (samplerEntry) { - envMapParams = samplerEntry.description; - } - } - } - } - } - - var texture = LoadTexture(envMapPath); - if (texture && envMapParams) { + var samplerEntry = this.resources.getEntry(textureEntry.description.sampler); + if (samplerEntry) { + envMapParams = samplerEntry.description; + } + } + } + } + } + + var texture = LoadTexture(envMapPath); + if (texture && envMapParams) { - if (envMapParams.wrapS == WebGLRenderingContext.REPEAT) + if (envMapParams.wrapS == WebGLRenderingContext.REPEAT) texture.wrapS = THREE.RepeatWrapping; - if (envMapParams.wrapT == WebGLRenderingContext.REPEAT) + if (envMapParams.wrapT == WebGLRenderingContext.REPEAT) texture.wrapT = THREE.RepeatWrapping; - if (envMapParams.magFilter == WebGLRenderingContext.LINEAR) + if (envMapParams.magFilter == WebGLRenderingContext.LINEAR) texture.magFilter = THREE.LinearFilter; // if (envMapParams.minFilter == WebGLRenderingContext.LINEAR) // texture.minFilter = THREE.LinearFilter; - params.envMap = texture; - } + params.envMap = texture; + } - var shininess = values.shininesss || values.shininess; // N.B.: typo in converter! - if (shininess) + var shininess = values.shininesss || values.shininess; // N.B.: typo in converter! + if (shininess) { - shininess = shininess; - } + shininess = shininess; + } - var diffuseColor = !texturePath ? diffuse : null; - var opacity = 1.0; - if (values.hasOwnProperty("transparency")) + var diffuseColor = !texturePath ? diffuse : null; + var opacity = 1.0; + if (values.hasOwnProperty("transparency")) { - var USE_A_ONE = true; // for now, hack because file format isn't telling us - opacity = USE_A_ONE ? values.transparency : (1.0 - values.transparency); - } + var USE_A_ONE = true; // for now, hack because file format isn't telling us + opacity = USE_A_ONE ? values.transparency : (1.0 - values.transparency); + } // if (diffuseColor) diffuseColor = [0, 1, 0]; - params.color = RgbArraytoHex(diffuseColor); - params.opacity = opacity; - params.transparent = opacity < 1.0; + params.color = RgbArraytoHex(diffuseColor); + params.opacity = opacity; + params.transparent = opacity < 1.0; // hack hack hack - if (texturePath && texturePath.toLowerCase().indexOf(".png") != -1) + if (texturePath && texturePath.toLowerCase().indexOf(".png") != -1) params.transparent = true; - if (!(shininess === undefined)) + if (!(shininess === undefined)) { - params.shininess = shininess; - } + params.shininess = shininess; + } - if (!(values.emission === undefined)) + if (!(values.emission === undefined)) { - params.emissive = RgbArraytoHex(values.emission); - } + params.emissive = RgbArraytoHex(values.emission); + } - if (!(values.specular === undefined)) + if (!(values.specular === undefined)) { - params.specular = RgbArraytoHex(values.specular); - } + params.specular = RgbArraytoHex(values.specular); + } - return materialType; + return materialType; } }, @@ -804,44 +804,44 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { value: function(entryID, description, userInfo) { //this should be rewritten using the meta datas that actually create the shader. //here we will infer what needs to be pass to Three.js by looking inside the technique parameters. - var technique = this.resources.getEntry(description.instanceTechnique.technique); - var materialParams = {}; - var values = description.instanceTechnique.values; + var technique = this.resources.getEntry(description.instanceTechnique.technique); + var materialParams = {}; + var values = description.instanceTechnique.values; - var materialType = this.threeJSMaterialType(entryID, technique, values, materialParams); + var materialType = this.threeJSMaterialType(entryID, technique, values, materialParams); - var material = new materialType(materialParams); + var material = new materialType(materialParams); - this.resources.setEntry(entryID, material, description); + this.resources.setEntry(entryID, material, description); - return true; + return true; } }, handleMesh: { value: function(entryID, description, userInfo) { - var mesh = new Mesh(); - this.resources.setEntry(entryID, mesh, description); - var primitivesDescription = description.primitives; - if (!primitivesDescription) { + var mesh = new Mesh(); + this.resources.setEntry(entryID, mesh, description); + var primitivesDescription = description.primitives; + if (!primitivesDescription) { //FIXME: not implemented in delegate - console.log("MISSING_PRIMITIVES for mesh:" + entryID); - return false; - } + console.log("MISSING_PRIMITIVES for mesh:" + entryID); + return false; + } - for (var i = 0 ; i < primitivesDescription.length ; i ++) { - var primitiveDescription = primitivesDescription[i]; + for (var i = 0 ; i < primitivesDescription.length ; i ++) { + var primitiveDescription = primitivesDescription[i]; - if (primitiveDescription.primitive === WebGLRenderingContext.TRIANGLES) { + if (primitiveDescription.primitive === WebGLRenderingContext.TRIANGLES) { - var geometry = new ClassicGeometry(); - var materialEntry = this.resources.getEntry(primitiveDescription.material); + var geometry = new ClassicGeometry(); + var materialEntry = this.resources.getEntry(primitiveDescription.material); - mesh.addPrimitive(geometry, materialEntry.object); + mesh.addPrimitive(geometry, materialEntry.object); - var indices = this.resources.getEntry(primitiveDescription.indices); - var bufferEntry = this.resources.getEntry(indices.description.bufferView); - var indicesObject = { + var indices = this.resources.getEntry(primitiveDescription.indices); + var bufferEntry = this.resources.getEntry(indices.description.bufferView); + var indicesObject = { bufferView : bufferEntry, byteOffset : indices.description.byteOffset, count : indices.description.count, @@ -849,36 +849,36 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { type : indices.description.type }; - var indicesContext = new IndicesContext(indicesObject, geometry); - var alreadyProcessedIndices = THREE.GLTFLoaderUtils.getBuffer(indicesObject, indicesDelegate, indicesContext); + var indicesContext = new IndicesContext(indicesObject, geometry); + var alreadyProcessedIndices = THREE.GLTFLoaderUtils.getBuffer(indicesObject, indicesDelegate, indicesContext); /*if(alreadyProcessedIndices) { indicesDelegate.resourceAvailable(alreadyProcessedIndices, indicesContext); }*/ // Load Vertex Attributes - var allAttributes = Object.keys(primitiveDescription.attributes); - allAttributes.forEach( function(semantic) { - geometry.totalAttributes ++; - - var attribute; - var attributeID = primitiveDescription.attributes[semantic]; - var attributeEntry = this.resources.getEntry(attributeID); - if (!attributeEntry) { + var allAttributes = Object.keys(primitiveDescription.attributes); + allAttributes.forEach( function(semantic) { + geometry.totalAttributes ++; + + var attribute; + var attributeID = primitiveDescription.attributes[semantic]; + var attributeEntry = this.resources.getEntry(attributeID); + if (!attributeEntry) { //let's just use an anonymous object for the attribute - attribute = description.attributes[attributeID]; - attribute.id = attributeID; - this.resources.setEntry(attributeID, attribute, attribute); + attribute = description.attributes[attributeID]; + attribute.id = attributeID; + this.resources.setEntry(attributeID, attribute, attribute); - var bufferEntry = this.resources.getEntry(attribute.bufferView); - attributeEntry = this.resources.getEntry(attributeID); + var bufferEntry = this.resources.getEntry(attribute.bufferView); + attributeEntry = this.resources.getEntry(attributeID); - } else { - attribute = attributeEntry.object; - attribute.id = attributeID; - var bufferEntry = this.resources.getEntry(attribute.bufferView); - } + } else { + attribute = attributeEntry.object; + attribute.id = attributeID; + var bufferEntry = this.resources.getEntry(attribute.bufferView); + } - var attributeObject = { + var attributeObject = { bufferView : bufferEntry, byteOffset : attribute.byteOffset, byteStride : attribute.byteStride, @@ -889,106 +889,106 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { id : attributeID }; - var attribContext = new VertexAttributeContext(attributeObject, semantic, geometry); + var attribContext = new VertexAttributeContext(attributeObject, semantic, geometry); - var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(attributeObject, vertexAttributeDelegate, attribContext); + var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(attributeObject, vertexAttributeDelegate, attribContext); /*if(alreadyProcessedAttribute) { vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext); }*/ - }, this); - } - } - return true; + }, this); + } + } + return true; } }, handleCamera: { value: function(entryID, description, userInfo) { - var camera; - if (description.type == "perspective") + var camera; + if (description.type == "perspective") { - var znear = description.perspective.znear; - var zfar = description.perspective.zfar; - var yfov = description.perspective.yfov; - var xfov = description.perspective.xfov; - var aspect_ratio = description.perspective.aspect_ratio; + var znear = description.perspective.znear; + var zfar = description.perspective.zfar; + var yfov = description.perspective.yfov; + var xfov = description.perspective.xfov; + var aspect_ratio = description.perspective.aspect_ratio; - if (!aspect_ratio) + if (!aspect_ratio) aspect_ratio = 1; - if (yfov === undefined) + if (yfov === undefined) { - if (xfov) + if (xfov) { // According to COLLADA spec... // aspect_ratio = xfov / yfov - yfov = xfov / aspect_ratio; - } + yfov = xfov / aspect_ratio; + } - } + } - if (yfov) + if (yfov) { - camera = new THREE.PerspectiveCamera(yfov, aspect_ratio, znear, zfar); - } - } + camera = new THREE.PerspectiveCamera(yfov, aspect_ratio, znear, zfar); + } + } else - { - camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, znear, zfar ); - } + { + camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, znear, zfar ); + } - if (camera) + if (camera) { - this.resources.setEntry(entryID, camera, description); - } + this.resources.setEntry(entryID, camera, description); + } - return true; + return true; } }, handleLight: { value: function(entryID, description, userInfo) { - var light = null; - var type = description.type; - if (type && description[type]) + var light = null; + var type = description.type; + if (type && description[type]) { - var lparams = description[type]; - var color = RgbArraytoHex(lparams.color); + var lparams = description[type]; + var color = RgbArraytoHex(lparams.color); - switch (type) { - case "directional" : - light = new THREE.DirectionalLight(color); - light.position.set(0, 0, 1); - break; + switch (type) { + case "directional" : + light = new THREE.DirectionalLight(color); + light.position.set(0, 0, 1); + break; - case "point" : - light = new THREE.PointLight(color); - break; + case "point" : + light = new THREE.PointLight(color); + break; - case "spot " : - light = new THREE.SpotLight(color); - light.position.set(0, 0, 1); - break; + case "spot " : + light = new THREE.SpotLight(color); + light.position.set(0, 0, 1); + break; - case "ambient" : - light = new THREE.AmbientLight(color); - break; - } - } + case "ambient" : + light = new THREE.AmbientLight(color); + break; + } + } - if (light) + if (light) { - this.resources.setEntry(entryID, light, description); - } + this.resources.setEntry(entryID, light, description); + } - return true; + return true; } }, addPendingMesh: { value: function(mesh, threeNode) { - theLoader.pendingMeshes.push({ + theLoader.pendingMeshes.push({ mesh: mesh, node: threeNode }); @@ -998,342 +998,342 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { handleNode: { value: function(entryID, description, userInfo) { - var threeNode = null; + var threeNode = null; if (description.jointId) { - threeNode = new THREE.Bone(); - threeNode.jointId = description.jointId; - this.joints[description.jointId] = entryID; + threeNode = new THREE.Bone(); + threeNode.jointId = description.jointId; + this.joints[description.jointId] = entryID; } else { - threeNode = new THREE.Object3D(); + threeNode = new THREE.Object3D(); } - threeNode.name = description.name; + threeNode.name = description.name; - this.resources.setEntry(entryID, threeNode, description); - - var m = description.matrix; - if (m) { - threeNode.applyMatrix(new THREE.Matrix4().fromArray( m )); - threeNode.matrixAutoUpdate = false; - threeNode.matrixWorldNeedsUpdate = true; - } - else { - var t = description.translation; - var r = description.rotation; - var s = description.scale; + this.resources.setEntry(entryID, threeNode, description); + + var m = description.matrix; + if (m) { + threeNode.applyMatrix(new THREE.Matrix4().fromArray( m )); + threeNode.matrixAutoUpdate = false; + threeNode.matrixWorldNeedsUpdate = true; + } + else { + var t = description.translation; + var r = description.rotation; + var s = description.scale; - var position = t ? new THREE.Vector3(t[0], t[1], t[2]) : + var position = t ? new THREE.Vector3(t[0], t[1], t[2]) : new THREE.Vector3; - if (r) { - convertAxisAngleToQuaternion(r, 1); - } - var rotation = r ? new THREE.Quaternion(r[0], r[1], r[2], r[3]) : + if (r) { + convertAxisAngleToQuaternion(r, 1); + } + var rotation = r ? new THREE.Quaternion(r[0], r[1], r[2], r[3]) : new THREE.Quaternion; - var scale = s ? new THREE.Vector3(s[0], s[1], s[2]) : + var scale = s ? new THREE.Vector3(s[0], s[1], s[2]) : new THREE.Vector3; - var matrix = new THREE.Matrix4; - matrix.compose(position, rotation, scale); - threeNode.matrixAutoUpdate = false; - threeNode.matrixWorldNeedsUpdate = true; - threeNode.applyMatrix(matrix); - } - - var self = this; + var matrix = new THREE.Matrix4; + matrix.compose(position, rotation, scale); + threeNode.matrixAutoUpdate = false; + threeNode.matrixWorldNeedsUpdate = true; + threeNode.applyMatrix(matrix); + } + + var self = this; // Iterate through all node meshes and attach the appropriate objects //FIXME: decision needs to be made between these 2 ways, probably meshes will be discarded. - var meshEntry; - if (description.mesh) { - meshEntry = this.resources.getEntry(description.mesh); - theLoader.meshesRequested ++; - meshEntry.object.onComplete(function(mesh) { - self.addPendingMesh(mesh, threeNode); - theLoader.meshesLoaded ++; - theLoader.checkComplete(); - }); - } - - if (description.meshes) { - description.meshes.forEach( function(meshID) { - meshEntry = this.resources.getEntry(meshID); - theLoader.meshesRequested ++; - meshEntry.object.onComplete(function(mesh) { - self.addPendingMesh(mesh, threeNode); - theLoader.meshesLoaded ++; - theLoader.checkComplete(); - }); - }, this); - } - - if (description.instanceSkin) { - - var skinEntry = this.resources.getEntry(description.instanceSkin.skin); + var meshEntry; + if (description.mesh) { + meshEntry = this.resources.getEntry(description.mesh); + theLoader.meshesRequested ++; + meshEntry.object.onComplete(function(mesh) { + self.addPendingMesh(mesh, threeNode); + theLoader.meshesLoaded ++; + theLoader.checkComplete(); + }); + } + + if (description.meshes) { + description.meshes.forEach( function(meshID) { + meshEntry = this.resources.getEntry(meshID); + theLoader.meshesRequested ++; + meshEntry.object.onComplete(function(mesh) { + self.addPendingMesh(mesh, threeNode); + theLoader.meshesLoaded ++; + theLoader.checkComplete(); + }); + }, this); + } + + if (description.instanceSkin) { + + var skinEntry = this.resources.getEntry(description.instanceSkin.skin); - if (skinEntry) { - - var skin = skinEntry.object; - description.instanceSkin.skin = skin; - threeNode.instanceSkin = description.instanceSkin; - - var sources = description.instanceSkin.sources; - skin.meshes = []; - sources.forEach( function(meshID) { - meshEntry = this.resources.getEntry(meshID); - theLoader.meshesRequested ++; - meshEntry.object.onComplete(function(mesh) { + if (skinEntry) { + + var skin = skinEntry.object; + description.instanceSkin.skin = skin; + threeNode.instanceSkin = description.instanceSkin; + + var sources = description.instanceSkin.sources; + skin.meshes = []; + sources.forEach( function(meshID) { + meshEntry = this.resources.getEntry(meshID); + theLoader.meshesRequested ++; + meshEntry.object.onComplete(function(mesh) { - skin.meshes.push(mesh); - theLoader.meshesLoaded ++; - theLoader.checkComplete(); - }); - }, this); + skin.meshes.push(mesh); + theLoader.meshesLoaded ++; + theLoader.checkComplete(); + }); + }, this); - } - } + } + } - if (description.camera) { - var cameraEntry = this.resources.getEntry(description.camera); - if (cameraEntry) { - threeNode.add(cameraEntry.object); - this.cameras.push(cameraEntry.object); - } - } - - if (description.light) { - var lightEntry = this.resources.getEntry(description.light); - if (lightEntry) { - threeNode.add(lightEntry.object); - this.lights.push(lightEntry.object); - } - } + if (description.camera) { + var cameraEntry = this.resources.getEntry(description.camera); + if (cameraEntry) { + threeNode.add(cameraEntry.object); + this.cameras.push(cameraEntry.object); + } + } + + if (description.light) { + var lightEntry = this.resources.getEntry(description.light); + if (lightEntry) { + threeNode.add(lightEntry.object); + this.lights.push(lightEntry.object); + } + } - return true; + return true; } }, buildNodeHirerachy: { value: function(nodeEntryId, parentThreeNode) { - var nodeEntry = this.resources.getEntry(nodeEntryId); - var threeNode = nodeEntry.object; - parentThreeNode.add(threeNode); - - var children = nodeEntry.description.children; - if (children) { - children.forEach( function(childID) { - this.buildNodeHirerachy(childID, threeNode); - }, this); - } - - return threeNode; + var nodeEntry = this.resources.getEntry(nodeEntryId); + var threeNode = nodeEntry.object; + parentThreeNode.add(threeNode); + + var children = nodeEntry.description.children; + if (children) { + children.forEach( function(childID) { + this.buildNodeHirerachy(childID, threeNode); + }, this); + } + + return threeNode; } }, buildSkin: { value: function(node) { - var skin = node.instanceSkin.skin; - if (skin) { - node.instanceSkin.skeletons.forEach(function(skeleton) { - var nodeEntry = this.resources.getEntry(skeleton); - if (nodeEntry) { + var skin = node.instanceSkin.skin; + if (skin) { + node.instanceSkin.skeletons.forEach(function(skeleton) { + var nodeEntry = this.resources.getEntry(skeleton); + if (nodeEntry) { - var rootSkeleton = nodeEntry.object; + var rootSkeleton = nodeEntry.object; - var dobones = true; + var dobones = true; - var i, len = skin.meshes.length; - for (i = 0; i < len; i ++) { - var mesh = skin.meshes[i]; - var threeMesh = null; - mesh.primitives.forEach(function(primitive) { + var i, len = skin.meshes.length; + for (i = 0; i < len; i ++) { + var mesh = skin.meshes[i]; + var threeMesh = null; + mesh.primitives.forEach(function(primitive) { - var material = primitive.material; - if (!(material instanceof THREE.Material)) { - material = this.createShaderMaterial(material); - } + var material = primitive.material; + if (!(material instanceof THREE.Material)) { + material = this.createShaderMaterial(material); + } - threeMesh = new THREE.SkinnedMesh(primitive.geometry.geometry, material, false); - threeMesh.add(rootSkeleton); + threeMesh = new THREE.SkinnedMesh(primitive.geometry.geometry, material, false); + threeMesh.add(rootSkeleton); - var geometry = primitive.geometry.geometry; - var j; - if (geometry.vertices) { - for ( j = 0; j < geometry.vertices.length; j ++ ) { - geometry.vertices[j].applyMatrix4( skin.bindShapeMatrix ); - } - } + var geometry = primitive.geometry.geometry; + var j; + if (geometry.vertices) { + for ( j = 0; j < geometry.vertices.length; j ++ ) { + geometry.vertices[j].applyMatrix4( skin.bindShapeMatrix ); + } + } else if (geometry.attributes.position) { - var a = geometry.attributes.position.array; - var v = new THREE.Vector3; + var a = geometry.attributes.position.array; + var v = new THREE.Vector3; for ( j = 0; j < a.length / 3; j ++ ) { - v.set(a[j * 3], a[j * 3 + 1], a[j * 3 + 2]); - v.applyMatrix4( skin.bindShapeMatrix ); - a[j * 3] = v.x; - a[j * 3 + 1] = v.y; - a[j * 3 + 2] = v.z; + v.set(a[j * 3], a[j * 3 + 1], a[j * 3 + 2]); + v.applyMatrix4( skin.bindShapeMatrix ); + a[j * 3] = v.x; + a[j * 3 + 1] = v.y; + a[j * 3 + 2] = v.z; } } - if (threeMesh && dobones) { + if (threeMesh && dobones) { - material.skinning = true; + material.skinning = true; - threeMesh.boneInverses = []; - var jointsIds = skin.jointsIds; - var bones = []; - var boneInverses = []; - var i, len = jointsIds.length; - for (i = 0; i < len; i ++) { - var jointId = jointsIds[i]; - var nodeForJoint = this.joints[jointId]; - var joint = this.resources.getEntry(nodeForJoint).object; - if (joint) { + threeMesh.boneInverses = []; + var jointsIds = skin.jointsIds; + var bones = []; + var boneInverses = []; + var i, len = jointsIds.length; + for (i = 0; i < len; i ++) { + var jointId = jointsIds[i]; + var nodeForJoint = this.joints[jointId]; + var joint = this.resources.getEntry(nodeForJoint).object; + if (joint) { - joint.skin = threeMesh; - bones.push(joint); + joint.skin = threeMesh; + bones.push(joint); - var m = skin.inverseBindMatrices; - var mat = new THREE.Matrix4().set( + var m = skin.inverseBindMatrices; + var mat = new THREE.Matrix4().set( m[i * 16 + 0], m[i * 16 + 4], m[i * 16 + 8], m[i * 16 + 12], m[i * 16 + 1], m[i * 16 + 5], m[i * 16 + 9], m[i * 16 + 13], m[i * 16 + 2], m[i * 16 + 6], m[i * 16 + 10], m[i * 16 + 14], m[i * 16 + 3], m[i * 16 + 7], m[i * 16 + 11], m[i * 16 + 15] ); - boneInverses.push(mat); + boneInverses.push(mat); - } else { - console.log("WARNING: jointId:" + jointId + " cannot be found in skeleton:" + skeleton); - } - } + } else { + console.log("WARNING: jointId:" + jointId + " cannot be found in skeleton:" + skeleton); + } + } - threeMesh.bind(new THREE.Skeleton(bones, boneInverses, false)); - } + threeMesh.bind(new THREE.Skeleton(bones, boneInverses, false)); + } - if (threeMesh) { - threeMesh.castShadow = true; - node.add(threeMesh); - } + if (threeMesh) { + threeMesh.castShadow = true; + node.add(threeMesh); + } - }, this); - } + }, this); + } - } + } - }, this); + }, this); - } + } } }, buildSkins: { value: function(node) { - if (node.instanceSkin) + if (node.instanceSkin) this.buildSkin(node); - var children = node.children; - if (children) { - children.forEach( function(child) { - this.buildSkins(child); - }, this); - } + var children = node.children; + if (children) { + children.forEach( function(child) { + this.buildSkins(child); + }, this); + } } }, createMeshAnimations : { value : function(root) { - this.buildSkins(root); + this.buildSkins(root); } }, handleScene: { value: function(entryID, description, userInfo) { - if (!description.nodes) { - console.log("ERROR: invalid file required nodes property is missing from scene"); - return false; - } + if (!description.nodes) { + console.log("ERROR: invalid file required nodes property is missing from scene"); + return false; + } - description.nodes.forEach( function(nodeUID) { - this.buildNodeHirerachy(nodeUID, userInfo.rootObj); - }, this); + description.nodes.forEach( function(nodeUID) { + this.buildNodeHirerachy(nodeUID, userInfo.rootObj); + }, this); - if (this.delegate) { - this.delegate.loadCompleted(userInfo.callback, userInfo.rootObj); - } + if (this.delegate) { + this.delegate.loadCompleted(userInfo.callback, userInfo.rootObj); + } - return true; + return true; } }, handleImage: { value: function(entryID, description, userInfo) { - this.resources.setEntry(entryID, null, description); - return true; + this.resources.setEntry(entryID, null, description); + return true; } }, addNodeAnimationChannel : { value : function(name, channel, interp) { - if (!this.nodeAnimationChannels) + if (!this.nodeAnimationChannels) this.nodeAnimationChannels = {}; - if (!this.nodeAnimationChannels[name]) { - this.nodeAnimationChannels[name] = []; - } + if (!this.nodeAnimationChannels[name]) { + this.nodeAnimationChannels[name] = []; + } - this.nodeAnimationChannels[name].push(interp); + this.nodeAnimationChannels[name].push(interp); }, }, createAnimations : { value : function() { - for (var name in this.nodeAnimationChannels) { - var nodeAnimationChannels = this.nodeAnimationChannels[name]; - var i, len = nodeAnimationChannels.length; + for (var name in this.nodeAnimationChannels) { + var nodeAnimationChannels = this.nodeAnimationChannels[name]; + var i, len = nodeAnimationChannels.length; //console.log(" animation channels for node " + name); //for (i = 0; i < len; i++) { // console.log(nodeAnimationChannels[i]); //} - var anim = new THREE.glTFAnimation(nodeAnimationChannels); - anim.name = "animation_" + name; - this.animations.push(anim); - } + var anim = new THREE.glTFAnimation(nodeAnimationChannels); + anim.name = "animation_" + name; + this.animations.push(anim); + } } }, buildAnimation: { value : function(animation) { - var interps = []; + var interps = []; var i, len = animation.channels.length; for (i = 0; i < len; i ++) { - var channel = animation.channels[i]; - var sampler = animation.samplers[channel.sampler]; - if (sampler) { + var channel = animation.channels[i]; + var sampler = animation.samplers[channel.sampler]; + if (sampler) { - var input = animation.parameters[sampler.input]; - if (input && input.data) { + var input = animation.parameters[sampler.input]; + if (input && input.data) { - var output = animation.parameters[sampler.output]; - if (output && output.data) { + var output = animation.parameters[sampler.output]; + if (output && output.data) { - var target = channel.target; - var node = this.resources.getEntry(target.id); - if (node) { + var target = channel.target; + var node = this.resources.getEntry(target.id); + if (node) { - var path = target.path; + var path = target.path; - if (path == "rotation") + if (path == "rotation") { - convertAxisAngleToQuaternion(output.data, output.count); - } + convertAxisAngleToQuaternion(output.data, output.count); + } - var interp = { + var interp = { keys : input.data, values : output.data, count : input.count, @@ -1342,12 +1342,12 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { type : sampler.interpolation }; - this.addNodeAnimationChannel(target.id, channel, interp); - interps.push(interp); - } - } - } - } + this.addNodeAnimationChannel(target.id, channel, interp); + interps.push(interp); + } + } + } + } } } }, @@ -1355,15 +1355,15 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { handleAnimation: { value: function(entryID, description, userInfo) { - var self = this; + var self = this; theLoader.animationsRequested ++; var animation = new Animation(); - animation.name = entryID; + animation.name = entryID; animation.onload = function() { // self.buildAnimation(animation); - theLoader.animationsLoaded ++; - theLoader.animations.push(animation); - theLoader.checkComplete(); + theLoader.animationsLoaded ++; + theLoader.animations.push(animation); + theLoader.checkComplete(); }; animation.channels = description.channels; @@ -1372,22 +1372,22 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { var parameters = description.parameters; if (!parameters) { //FIXME: not implemented in delegate - console.log("MISSING_PARAMETERS for animation:" + entryID); - return false; + console.log("MISSING_PARAMETERS for animation:" + entryID); + return false; } // Load parameter buffers - var params = Object.keys(parameters); - params.forEach( function(param) { + var params = Object.keys(parameters); + params.forEach( function(param) { - animation.totalParameters ++; - var parameter = parameters[param]; - var accessor = this.resources.getEntry(parameter); - if (!accessor) + animation.totalParameters ++; + var parameter = parameters[param]; + var accessor = this.resources.getEntry(parameter); + if (!accessor) debugger; - accessor = accessor.object; - var bufferView = this.resources.getEntry(accessor.bufferView); - var paramObject = { + accessor = accessor.object; + var bufferView = this.resources.getEntry(accessor.bufferView); + var paramObject = { bufferView : bufferView, byteOffset : accessor.byteOffset, count : accessor.count, @@ -1396,13 +1396,13 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { name : param }; - var paramContext = new AnimationParameterContext(paramObject, animation); + var paramContext = new AnimationParameterContext(paramObject, animation); - var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, animationParameterDelegate, paramContext); + var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, animationParameterDelegate, paramContext); /*if(alreadyProcessedAttribute) { vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext); }*/ - }, this); + }, this); return true; } @@ -1412,7 +1412,7 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { value: function(entryID, description, userInfo) { // Save attribute entry this.resources.setEntry(entryID, description, description); - return true; + return true; } }, @@ -1420,10 +1420,10 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { value: function(entryID, description, userInfo) { // Save skin entry - var skin = { + var skin = { }; - var m = description.bindShapeMatrix; + var m = description.bindShapeMatrix; skin.bindShapeMatrix = new THREE.Matrix4().fromArray( m ); skin.jointsIds = description.joints; @@ -1431,9 +1431,9 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { skin.inverseBindMatricesDescription = inverseBindMatricesDescription; skin.inverseBindMatricesDescription.id = entryID + "_inverseBindMatrices"; - var bufferEntry = this.resources.getEntry(inverseBindMatricesDescription.bufferView); + var bufferEntry = this.resources.getEntry(inverseBindMatricesDescription.bufferView); - var paramObject = { + var paramObject = { bufferView : bufferEntry, byteOffset : inverseBindMatricesDescription.byteOffset, count : inverseBindMatricesDescription.count, @@ -1444,13 +1444,13 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { var context = new InverseBindMatricesContext(paramObject, skin); - var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, inverseBindMatricesDelegate, context); + var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, inverseBindMatricesDelegate, context); var bufferView = this.resources.getEntry(skin.inverseBindMatricesDescription.bufferView); skin.inverseBindMatricesDescription.bufferView = bufferView.object; this.resources.setEntry(entryID, skin, description); - return true; + return true; } }, @@ -1458,7 +1458,7 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { value: function(entryID, description, userInfo) { // Save attribute entry this.resources.setEntry(entryID, description, description); - return true; + return true; } }, @@ -1466,15 +1466,15 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { value: function(entryID, description, userInfo) { // Save attribute entry this.resources.setEntry(entryID, null, description); - return true; + return true; } }, handleError: { value: function(msg) { - throw new Error(msg); - return true; + throw new Error(msg); + return true; } }, @@ -1486,10 +1486,10 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { delegate: { enumerable: true, get: function() { - return this._delegate; + return this._delegate; }, set: function(value) { - this._delegate = value; + this._delegate = value; } } }); @@ -1497,26 +1497,26 @@ THREE.glTFLoader.prototype.load = function( url, callback ) { // Loader - var Context = function(rootObj, callback) { - this.rootObj = rootObj; - this.callback = callback; - }; + var Context = function(rootObj, callback) { + this.rootObj = rootObj; + this.callback = callback; + }; - var rootObj = new THREE.Object3D(); + var rootObj = new THREE.Object3D(); - var self = this; + var self = this; - var loader = Object.create(ThreeGLTFLoader); - loader.initWithPath(url); - loader.load(new Context(rootObj, + var loader = Object.create(ThreeGLTFLoader); + loader.initWithPath(url); + loader.load(new Context(rootObj, function(obj) { }), null); - this.loader = loader; - this.callback = callback; - this.rootObj = rootObj; - return rootObj; + this.loader = loader; + this.callback = callback; + this.rootObj = rootObj; + return rootObj; } THREE.glTFLoader.prototype.callLoadedCallback = function() { diff --git a/examples/js/loaders/gltf/glTFLoaderUtils.js b/examples/js/loaders/gltf/glTFLoaderUtils.js index 961fdc946b..1d74148a53 100644 --- a/examples/js/loaders/gltf/glTFLoaderUtils.js +++ b/examples/js/loaders/gltf/glTFLoaderUtils.js @@ -26,8 +26,8 @@ THREE.GLTFLoaderUtils = Object.create(Object, { value: function() { this._streams = {}; this._streamsStatus = {}; - this._resources = {}; - this._resourcesStatus = {}; + this._resources = {}; + this._resourcesStatus = {}; } }, @@ -35,60 +35,60 @@ THREE.GLTFLoaderUtils = Object.create(Object, { _containsResource: { enumerable: false, value: function(resourceID) { - return this._resources[resourceID] ? true : false; + return this._resources[resourceID] ? true : false; } }, _storeResource: { enumerable: false, value: function(resourceID, resource) { - if (!resourceID) { - console.log("ERROR: entry does not contain id, cannot store"); - return; - } + if (!resourceID) { + console.log("ERROR: entry does not contain id, cannot store"); + return; + } - if (this._containsResource[resourceID]) { - console.log("WARNING: resource:" + resourceID + " is already stored, overriding"); - } + if (this._containsResource[resourceID]) { + console.log("WARNING: resource:" + resourceID + " is already stored, overriding"); + } - this._resources[resourceID] = resource; + this._resources[resourceID] = resource; } }, _getResource: { enumerable: false, value: function(resourceID) { - return this._resources[resourceID]; + return this._resources[resourceID]; } }, _loadStream: { value: function(path, type, delegate) { - var self = this; + var self = this; - if (!type) { - delegate.handleError(THREE.GLTFLoaderUtils.INVALID_TYPE, null); - return; - } + if (!type) { + delegate.handleError(THREE.GLTFLoaderUtils.INVALID_TYPE, null); + return; + } - if (!path) { - delegate.handleError(THREE.GLTFLoaderUtils.INVALID_PATH); - return; - } + if (!path) { + delegate.handleError(THREE.GLTFLoaderUtils.INVALID_PATH); + return; + } - var xhr = new XMLHttpRequest(); - xhr.open('GET', path, true); - xhr.responseType = (type === this.ARRAY_BUFFER) ? "arraybuffer" : "text"; + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, true); + xhr.responseType = (type === this.ARRAY_BUFFER) ? "arraybuffer" : "text"; //if this is not specified, 1 "big blob" scenes fails to load. - xhr.setRequestHeader("If-Modified-Since", "Sat, 01 Jan 1970 00:00:00 GMT"); - xhr.addEventListener( 'load', function ( event ) { - delegate.streamAvailable(path, xhr.response); - }, false ); - xhr.addEventListener( 'error', function ( event ) { - delegate.handleError(THREE.GLTFLoaderUtils.XMLHTTPREQUEST_STATUS_ERROR, xhr.status); - }, false ); - xhr.send(null); + xhr.setRequestHeader("If-Modified-Since", "Sat, 01 Jan 1970 00:00:00 GMT"); + xhr.addEventListener( 'load', function ( event ) { + delegate.streamAvailable(path, xhr.response); + }, false ); + xhr.addEventListener( 'error', function ( event ) { + delegate.handleError(THREE.GLTFLoaderUtils.XMLHTTPREQUEST_STATUS_ERROR, xhr.status); + }, false ); + xhr.send(null); } }, @@ -97,86 +97,86 @@ THREE.GLTFLoaderUtils = Object.create(Object, { _handleRequest: { value: function(request) { - var resourceStatus = this._resourcesStatus[request.id]; - if (resourceStatus) + var resourceStatus = this._resourcesStatus[request.id]; + if (resourceStatus) { - this._resourcesStatus[request.id] ++; - } + this._resourcesStatus[request.id] ++; + } else - { - this._resourcesStatus[request.id] = 1; - } + { + this._resourcesStatus[request.id] = 1; + } - var streamStatus = this._streamsStatus[request.path]; - if (streamStatus && streamStatus.status === "loading" ) + var streamStatus = this._streamsStatus[request.path]; + if (streamStatus && streamStatus.status === "loading" ) { - streamStatus.requests.push(request); - return; - } + streamStatus.requests.push(request); + return; + } - this._streamsStatus[request.path] = { status : "loading", requests : [ request ] }; + this._streamsStatus[request.path] = { status : "loading", requests : [ request ] }; - var self = this; - var processResourceDelegate = {}; - - processResourceDelegate.streamAvailable = function(path, res_) { - var streamStatus = self._streamsStatus[path]; - var requests = streamStatus.requests; - requests.forEach( function(req_) { - var subArray = res_.slice(req_.range[0], req_.range[1]); - var convertedResource = req_.delegate.convert(subArray, req_.ctx); - self._storeResource(req_.id, convertedResource); - req_.delegate.resourceAvailable(convertedResource, req_.ctx); - -- self._resourcesStatus[req_.id]; - - }, this); + var self = this; + var processResourceDelegate = {}; + + processResourceDelegate.streamAvailable = function(path, res_) { + var streamStatus = self._streamsStatus[path]; + var requests = streamStatus.requests; + requests.forEach( function(req_) { + var subArray = res_.slice(req_.range[0], req_.range[1]); + var convertedResource = req_.delegate.convert(subArray, req_.ctx); + self._storeResource(req_.id, convertedResource); + req_.delegate.resourceAvailable(convertedResource, req_.ctx); + -- self._resourcesStatus[req_.id]; + + }, this); - delete self._streamsStatus[path]; + delete self._streamsStatus[path]; - }; + }; - processResourceDelegate.handleError = function(errorCode, info) { - request.delegate.handleError(errorCode, info); - } + processResourceDelegate.handleError = function(errorCode, info) { + request.delegate.handleError(errorCode, info); + } - this._loadStream(request.path, request.type, processResourceDelegate); + this._loadStream(request.path, request.type, processResourceDelegate); } }, _elementSizeForGLType: { value: function(glType) { - switch (glType) { - case WebGLRenderingContext.FLOAT : - return Float32Array.BYTES_PER_ELEMENT; - case WebGLRenderingContext.UNSIGNED_BYTE : - return Uint8Array.BYTES_PER_ELEMENT; - case WebGLRenderingContext.UNSIGNED_SHORT : - return Uint16Array.BYTES_PER_ELEMENT; - case WebGLRenderingContext.FLOAT_VEC2 : - return Float32Array.BYTES_PER_ELEMENT * 2; - case WebGLRenderingContext.FLOAT_VEC3 : - return Float32Array.BYTES_PER_ELEMENT * 3; - case WebGLRenderingContext.FLOAT_VEC4 : - return Float32Array.BYTES_PER_ELEMENT * 4; - case WebGLRenderingContext.FLOAT_MAT3 : - return Float32Array.BYTES_PER_ELEMENT * 9; - case WebGLRenderingContext.FLOAT_MAT4 : - return Float32Array.BYTES_PER_ELEMENT * 16; - default: - return null; - } + switch (glType) { + case WebGLRenderingContext.FLOAT : + return Float32Array.BYTES_PER_ELEMENT; + case WebGLRenderingContext.UNSIGNED_BYTE : + return Uint8Array.BYTES_PER_ELEMENT; + case WebGLRenderingContext.UNSIGNED_SHORT : + return Uint16Array.BYTES_PER_ELEMENT; + case WebGLRenderingContext.FLOAT_VEC2 : + return Float32Array.BYTES_PER_ELEMENT * 2; + case WebGLRenderingContext.FLOAT_VEC3 : + return Float32Array.BYTES_PER_ELEMENT * 3; + case WebGLRenderingContext.FLOAT_VEC4 : + return Float32Array.BYTES_PER_ELEMENT * 4; + case WebGLRenderingContext.FLOAT_MAT3 : + return Float32Array.BYTES_PER_ELEMENT * 9; + case WebGLRenderingContext.FLOAT_MAT4 : + return Float32Array.BYTES_PER_ELEMENT * 16; + default: + return null; + } } }, _handleWrappedBufferViewResourceLoading: { value: function(wrappedBufferView, delegate, ctx) { - var bufferView = wrappedBufferView.bufferView; - var buffer = bufferView.buffer; - var byteOffset = wrappedBufferView.byteOffset + bufferView.description.byteOffset; - var range = [ byteOffset, (this._elementSizeForGLType(wrappedBufferView.type) * wrappedBufferView.count) + byteOffset ]; + var bufferView = wrappedBufferView.bufferView; + var buffer = bufferView.buffer; + var byteOffset = wrappedBufferView.byteOffset + bufferView.description.byteOffset; + var range = [ byteOffset, (this._elementSizeForGLType(wrappedBufferView.type) * wrappedBufferView.count) + byteOffset ]; - this._handleRequest({ "id" : wrappedBufferView.id, + this._handleRequest({ "id" : wrappedBufferView.id, "range" : range, "type" : buffer.description.type, "path" : buffer.description.path, @@ -189,14 +189,14 @@ THREE.GLTFLoaderUtils = Object.create(Object, { value: function(wrappedBufferView, delegate, ctx) { - var savedBuffer = this._getResource(wrappedBufferView.id); - if (savedBuffer) { - return savedBuffer; - } else { - this._handleWrappedBufferViewResourceLoading(wrappedBufferView, delegate, ctx); - } + var savedBuffer = this._getResource(wrappedBufferView.id); + if (savedBuffer) { + return savedBuffer; + } else { + this._handleWrappedBufferViewResourceLoading(wrappedBufferView, delegate, ctx); + } - return null; + return null; } }, @@ -204,17 +204,17 @@ THREE.GLTFLoaderUtils = Object.create(Object, { value: function(request, delegate, ctx) { - request.delegate = delegate; - request.ctx = ctx; + request.delegate = delegate; + request.ctx = ctx; - this._handleRequest({ "id" : request.id, + this._handleRequest({ "id" : request.id, "path" : request.path, "range" : [ 0 ], "type" : "text", "delegate" : delegate, "ctx" : ctx }, null); - return null; - } + return null; +} }, }); diff --git a/examples/js/renderers/SVGRenderer.js b/examples/js/renderers/SVGRenderer.js index 031a776c1a..544ddb7006 100644 --- a/examples/js/renderers/SVGRenderer.js +++ b/examples/js/renderers/SVGRenderer.js @@ -215,7 +215,7 @@ THREE.SVGRenderer = function () { var x = _vector3.x * _svgWidthHalf; var y = - _vector3.y * _svgHeightHalf; - var node = object.node; + var node = object.node; node.setAttribute( 'transform', 'translate(' + x + ',' + y + ')' ); _svg.appendChild( node ); diff --git a/examples/js/renderers/SoftwareRenderer.js b/examples/js/renderers/SoftwareRenderer.js index 53501eef0b..f26b2ef817 100644 --- a/examples/js/renderers/SoftwareRenderer.js +++ b/examples/js/renderers/SoftwareRenderer.js @@ -404,8 +404,8 @@ THREE.SoftwareRenderer = function ( parameters ) { + (material.palette[cIndex + 2] * tdata[tIndex + 2]); if (opaci < 250) { - var backColor = buffer[ colorOffset ] << 24 + buffer[ colorOffset + 1 ] << 16 + buffer[ colorOffset + 2 ] << 8; - foreColor = foreColor * opaci + backColor * (1 - opaci); + var backColor = buffer[ colorOffset ] << 24 + buffer[ colorOffset + 1 ] << 16 + buffer[ colorOffset + 2 ] << 8; + foreColor = foreColor * opaci + backColor * (1 - opaci); } buffer[ colorOffset ] = (foreColor & 0xff0000) >> 16; diff --git a/examples/js/utils/UVsDebug.js b/examples/js/utils/UVsDebug.js index d98f3e9ff4..6aa81e9cb1 100644 --- a/examples/js/utils/UVsDebug.js +++ b/examples/js/utils/UVsDebug.js @@ -16,104 +16,104 @@ THREE.UVsDebug = function( geometry, size ) { // handles wrapping of uv.x > 1 only - var abc = 'abcd'; + var abc = 'abcd'; - var uv, u, ax, ay; - var i, il, j, jl; - var vnum; + var uv, u, ax, ay; + var i, il, j, jl; + var vnum; - var a = new THREE.Vector2(); - var b = new THREE.Vector2(); + var a = new THREE.Vector2(); + var b = new THREE.Vector2(); - var faces = geometry.faces; - var uvs = geometry.faceVertexUvs[ 0 ]; + var faces = geometry.faces; + var uvs = geometry.faceVertexUvs[ 0 ]; - var canvas = document.createElement( 'canvas' ); - var width = size || 1024; // power of 2 required for wrapping - var height = size || 1024; - canvas.width = width; - canvas.height = height; + var canvas = document.createElement( 'canvas' ); + var width = size || 1024; // power of 2 required for wrapping + var height = size || 1024; + canvas.width = width; + canvas.height = height; - var ctx = canvas.getContext( '2d' ); - ctx.lineWidth = 2; - ctx.strokeStyle = 'rgba( 0, 0, 0, 1.0 )'; - ctx.textAlign = 'center'; + var ctx = canvas.getContext( '2d' ); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba( 0, 0, 0, 1.0 )'; + ctx.textAlign = 'center'; // paint background white - ctx.fillStyle = 'rgba( 255, 255, 255, 1.0 )'; - ctx.fillRect( 0, 0, width, height ); + ctx.fillStyle = 'rgba( 255, 255, 255, 1.0 )'; + ctx.fillRect( 0, 0, width, height ); - for ( i = 0, il = uvs.length; i < il; i ++ ) { + for ( i = 0, il = uvs.length; i < il; i ++ ) { - uv = uvs[ i ]; + uv = uvs[ i ]; // draw lines - ctx.beginPath(); + ctx.beginPath(); - a.set( 0, 0 ); + a.set( 0, 0 ); - for ( j = 0, jl = uv.length; j < jl; j ++ ) { + for ( j = 0, jl = uv.length; j < jl; j ++ ) { - u = uv[ j ]; + u = uv[ j ]; - a.x += u.x; - a.y += u.y; + a.x += u.x; + a.y += u.y; - if ( j == 0 ) { + if ( j == 0 ) { - ctx.moveTo( u.x * width, ( 1 - u.y ) * height ); + ctx.moveTo( u.x * width, ( 1 - u.y ) * height ); - } else { + } else { - ctx.lineTo( u.x * width, ( 1 - u.y ) * height ); + ctx.lineTo( u.x * width, ( 1 - u.y ) * height ); - } + } - } + } - ctx.closePath(); - ctx.stroke(); + ctx.closePath(); + ctx.stroke(); - a.divideScalar( jl ); + a.divideScalar( jl ); // label the face number - ctx.font = "12pt Arial bold"; - ctx.fillStyle = 'rgba( 0, 0, 0, 1.0 )'; - ctx.fillText( i, a.x * width, ( 1 - a.y ) * height ); + ctx.font = "12pt Arial bold"; + ctx.fillStyle = 'rgba( 0, 0, 0, 1.0 )'; + ctx.fillText( i, a.x * width, ( 1 - a.y ) * height ); - if ( a.x > 0.95 ) { // wrap x // 0.95 is arbitrary + if ( a.x > 0.95 ) { // wrap x // 0.95 is arbitrary - ctx.fillText( i, ( a.x % 1 ) * width, ( 1 - a.y ) * height ); + ctx.fillText( i, ( a.x % 1 ) * width, ( 1 - a.y ) * height ); - } + } - ctx.font = "8pt Arial bold"; - ctx.fillStyle = 'rgba( 0, 0, 0, 1.0 )'; + ctx.font = "8pt Arial bold"; + ctx.fillStyle = 'rgba( 0, 0, 0, 1.0 )'; // label uv edge orders - for ( j = 0, jl = uv.length; j < jl; j ++ ) { + for ( j = 0, jl = uv.length; j < jl; j ++ ) { - u = uv[ j ]; - b.addVectors( a, u ).divideScalar( 2 ); + u = uv[ j ]; + b.addVectors( a, u ).divideScalar( 2 ); - vnum = faces[ i ][ abc[ j ] ]; - ctx.fillText( abc[ j ] + vnum, b.x * width, ( 1 - b.y ) * height ); + vnum = faces[ i ][ abc[ j ] ]; + ctx.fillText( abc[ j ] + vnum, b.x * width, ( 1 - b.y ) * height ); - if ( b.x > 0.95 ) { // wrap x + if ( b.x > 0.95 ) { // wrap x - ctx.fillText( abc[ j ] + vnum, ( b.x % 1 ) * width, ( 1 - b.y ) * height ); + ctx.fillText( abc[ j ] + vnum, ( b.x % 1 ) * width, ( 1 - b.y ) * height ); - } + } - } + } - } + } - return canvas; + return canvas; } diff --git a/examples/js/wip/benchmark/Geometry4.js b/examples/js/wip/benchmark/Geometry4.js index b9b055abaa..b93f057484 100644 --- a/examples/js/wip/benchmark/Geometry4.js +++ b/examples/js/wip/benchmark/Geometry4.js @@ -1,18 +1,18 @@ THREE.Geometry4 = function ( size ) { - THREE.BufferGeometry.call( this ); + THREE.BufferGeometry.call( this ); - var verticesBuffer = new ArrayBuffer( size * 3 * 4 ); - var normalsBuffer = new ArrayBuffer( size * 3 * 4 ); - var uvsBuffer = new ArrayBuffer( size * 2 * 4 ); + var verticesBuffer = new ArrayBuffer( size * 3 * 4 ); + var normalsBuffer = new ArrayBuffer( size * 3 * 4 ); + var uvsBuffer = new ArrayBuffer( size * 2 * 4 ); - this.attributes[ 'position' ] = { array: new Float32Array( verticesBuffer, 0, size * 3 ), itemSize: 3 }; - this.attributes[ 'normal' ] = { array: new Float32Array( normalsBuffer, 0, size * 3 ), itemSize: 3 }; - this.attributes[ 'uv' ] = { array: new Float32Array( uvsBuffer, 0, size * 2 ), itemSize: 2 }; + this.attributes[ 'position' ] = { array: new Float32Array( verticesBuffer, 0, size * 3 ), itemSize: 3 }; + this.attributes[ 'normal' ] = { array: new Float32Array( normalsBuffer, 0, size * 3 ), itemSize: 3 }; + this.attributes[ 'uv' ] = { array: new Float32Array( uvsBuffer, 0, size * 2 ), itemSize: 2 }; - this.vertices = new THREE.VectorArrayProxy( this.attributes[ 'position' ] ); - this.normals = new THREE.VectorArrayProxy( this.attributes[ 'normal' ] ); - this.uvs = new THREE.VectorArrayProxy( this.attributes[ 'uv' ] ); + this.vertices = new THREE.VectorArrayProxy( this.attributes[ 'position' ] ); + this.normals = new THREE.VectorArrayProxy( this.attributes[ 'normal' ] ); + this.uvs = new THREE.VectorArrayProxy( this.attributes[ 'uv' ] ); }; THREE.Geometry4.prototype = Object.create( THREE.BufferGeometry.prototype ); @@ -22,16 +22,16 @@ THREE.VectorArrayProxy = function(attribute) { // Acts as a proxy for an array of vectors, by setting up accessors which return THREE.Vector*Proxy objects - this.attribute = attribute; + this.attribute = attribute; - for (var i = 0, l = this.attribute.array.length / this.attribute.itemSize; i < l; i ++) { + for (var i = 0, l = this.attribute.array.length / this.attribute.itemSize; i < l; i ++) { - Object.defineProperty(this, i, { + Object.defineProperty(this, i, { get: (function(i) { return function() { return this.getValue(i); }})(i), set: (function(i) { return function(v) { return this.setValue(i, v); }})(i), }); - } + } } @@ -39,23 +39,23 @@ THREE.VectorArrayProxy.prototype.getValue = function(i) { // Allocates a new THREE.Vector2Proxy or THREE.Vector3Proxy depending on the itemSize of our attribute - var subarray = this.attribute.array.subarray(i * this.attribute.itemSize, (i + 1) * this.attribute.itemSize); + var subarray = this.attribute.array.subarray(i * this.attribute.itemSize, (i + 1) * this.attribute.itemSize); - switch (this.attribute.itemSize) { + switch (this.attribute.itemSize) { - case 2: - return new THREE.Vector2Proxy(subarray); + case 2: + return new THREE.Vector2Proxy(subarray); - case 3: - return new THREE.Vector3Proxy(subarray); + case 3: + return new THREE.Vector3Proxy(subarray); - } + } } THREE.VectorArrayProxy.prototype.setValue = function(i, v) { - var vec = this[i]; - vec.copy(v); + var vec = this[i]; + vec.copy(v); } @@ -63,7 +63,7 @@ THREE.VectorArrayProxy.prototype.setValue = function(i, v) { THREE.Vector2Proxy = function(subarray) { - this.subarray = subarray; + this.subarray = subarray; } THREE.Vector2Proxy.prototype = Object.create( THREE.Vector2.prototype ); @@ -74,7 +74,7 @@ Object.defineProperty(THREE.Vector2Proxy.prototype, 'y', { get: function() { ret THREE.Vector3Proxy = function(subarray) { - this.subarray = subarray; + this.subarray = subarray; } THREE.Vector3Proxy.prototype = Object.create( THREE.Vector3.prototype ); diff --git a/src/extras/FontUtils.js b/src/extras/FontUtils.js index b3f1e56db8..244cc2b04b 100644 --- a/src/extras/FontUtils.js +++ b/src/extras/FontUtils.js @@ -182,11 +182,11 @@ THREE.FontUtils = { 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; + break; case 'b': diff --git a/src/extras/core/Curve.js b/src/extras/core/Curve.js index 5183b2b2a4..a40e940f5b 100644 --- a/src/extras/core/Curve.js +++ b/src/extras/core/Curve.js @@ -212,17 +212,17 @@ THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) { // we could get finer grain at lengths, or use simple interpolatation between two points var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; + var lengthAfter = arcLengths[ i + 1 ]; - var segmentLength = lengthAfter - lengthBefore; + var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; // add that fractional amount to t - var t = ( i + segmentFraction ) / ( il - 1 ); + var t = ( i + segmentFraction ) / ( il - 1 ); return t; diff --git a/src/extras/core/Path.js b/src/extras/core/Path.js index 50917c87b9..c56c3ea7e8 100644 --- a/src/extras/core/Path.js +++ b/src/extras/core/Path.js @@ -375,7 +375,7 @@ THREE.Path.prototype.getPoints = function( divisions, closedPath ) { //console.log(points); - break; + break; case THREE.PathActions.ELLIPSE: @@ -413,7 +413,7 @@ THREE.Path.prototype.getPoints = function( divisions, closedPath ) { //console.log(points); - break; + break; } // end switch diff --git a/src/extras/geometries/ExtrudeGeometry.js b/src/extras/geometries/ExtrudeGeometry.js index e1e11c7ad1..207e7f60b6 100644 --- a/src/extras/geometries/ExtrudeGeometry.js +++ b/src/extras/geometries/ExtrudeGeometry.js @@ -605,7 +605,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { var uvs = uvgen.generateTopUV( scope, a, b, c ); - scope.faceVertexUvs[ 0 ].push( uvs ); + scope.faceVertexUvs[ 0 ].push( uvs ); } @@ -616,13 +616,13 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { c += shapesOffset; d += shapesOffset; - scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) ); - scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) ); + scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) ); + scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) ); - var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); + var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); + scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); + scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); } diff --git a/src/loaders/CompressedTextureLoader.js b/src/loaders/CompressedTextureLoader.js index 3ef59092fb..6eece36665 100644 --- a/src/loaders/CompressedTextureLoader.js +++ b/src/loaders/CompressedTextureLoader.js @@ -49,7 +49,7 @@ THREE.CompressedTextureLoader.prototype = { if ( loaded === 6 ) { - if (texDatas.mipmapCount == 1) + if (texDatas.mipmapCount == 1) texture.minFilter = THREE.LinearFilter; texture.format = texDatas.format; diff --git a/src/loaders/JSONLoader.js b/src/loaders/JSONLoader.js index ad45150a73..de58c9c5ab 100644 --- a/src/loaders/JSONLoader.js +++ b/src/loaders/JSONLoader.js @@ -461,7 +461,7 @@ THREE.JSONLoader.prototype.parse = function ( json, texturePath ) { if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - THREE.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + + THREE.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); } diff --git a/src/math/Matrix4.js b/src/math/Matrix4.js index 47068850e7..45a35fb81f 100644 --- a/src/math/Matrix4.js +++ b/src/math/Matrix4.js @@ -92,15 +92,15 @@ THREE.Matrix4.prototype = { extractBasis: function ( xAxis, yAxis, zAxis ) { - var te = this.elements; + var te = this.elements; xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] ); yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] ); zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] ); - return this; + return this; - }, + }, makeBasis: function ( xAxis, yAxis, zAxis ) { @@ -111,7 +111,7 @@ THREE.Matrix4.prototype = { 0, 0, 0, 1 ); - return this; + return this; }, diff --git a/src/math/Sphere.js b/src/math/Sphere.js index 0f47f548f7..52cff009c9 100644 --- a/src/math/Sphere.js +++ b/src/math/Sphere.js @@ -52,7 +52,7 @@ THREE.Sphere.prototype = { return this; - }; + }; }(), diff --git a/src/math/Vector2.js b/src/math/Vector2.js index bfb3841e68..d9fba42184 100644 --- a/src/math/Vector2.js +++ b/src/math/Vector2.js @@ -371,9 +371,9 @@ THREE.Vector2.prototype = { lerpVectors: function ( v1, v2, alpha ) { - this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - return this; + return this; }, @@ -408,14 +408,14 @@ THREE.Vector2.prototype = { fromAttribute: function ( attribute, index, offset ) { - if ( offset === undefined ) offset = 0; + if ( offset === undefined ) offset = 0; - index = index * attribute.itemSize + offset; + index = index * attribute.itemSize + offset; - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; - return this; + return this; }, diff --git a/src/math/Vector3.js b/src/math/Vector3.js index 409c515951..464a635f5c 100644 --- a/src/math/Vector3.js +++ b/src/math/Vector3.js @@ -599,9 +599,9 @@ THREE.Vector3.prototype = { lerpVectors: function ( v1, v2, alpha ) { - this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - return this; + return this; }, @@ -819,15 +819,15 @@ THREE.Vector3.prototype = { fromAttribute: function ( attribute, index, offset ) { - if ( offset === undefined ) offset = 0; + if ( offset === undefined ) offset = 0; - index = index * attribute.itemSize + offset; + index = index * attribute.itemSize + offset; - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; - return this; + return this; }, diff --git a/src/math/Vector4.js b/src/math/Vector4.js index aac65abb7f..d27e9ebc9e 100644 --- a/src/math/Vector4.js +++ b/src/math/Vector4.js @@ -507,45 +507,45 @@ THREE.Vector4.prototype = { floor: function () { - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); - return this; + return this; }, ceil: function () { - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); - return this; + return this; }, round: function () { - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + this.w = Math.round( this.w ); - return this; + return this; }, roundToZero: function () { - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - return this; + return this; }, @@ -617,9 +617,9 @@ THREE.Vector4.prototype = { lerpVectors: function ( v1, v2, alpha ) { - this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - return this; + return this; }, @@ -658,16 +658,16 @@ THREE.Vector4.prototype = { fromAttribute: function ( attribute, index, offset ) { - if ( offset === undefined ) offset = 0; + if ( offset === undefined ) offset = 0; - index = index * attribute.itemSize + offset; + index = index * attribute.itemSize + offset; - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; - this.w = attribute.array[ index + 3 ]; + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; + this.w = attribute.array[ index + 3 ]; - return this; + return this; }, diff --git a/src/renderers/WebGLRenderer.js b/src/renderers/WebGLRenderer.js index c6f7033656..47ff43d4d9 100644 --- a/src/renderers/WebGLRenderer.js +++ b/src/renderers/WebGLRenderer.js @@ -6155,49 +6155,49 @@ THREE.WebGLRenderer = function ( parameters ) { this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) { - if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) { + if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - } + } - if ( renderTarget.__webglFramebuffer ) { + if ( renderTarget.__webglFramebuffer ) { - if ( renderTarget.format !== THREE.RGBAFormat ) { + if ( renderTarget.format !== THREE.RGBAFormat ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' ); - return; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' ); + return; - } + } - var restore = false; + var restore = false; - if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) { + if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer ); - restore = true; + restore = true; - } + } - if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { + if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { - _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer ); + _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer ); - } else { + } else { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); - } + } - if ( restore ) { + if ( restore ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); - } + } - } + } }; -- GitLab