glTFLoader.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. /**
  2. * @author Tony Parisi / http://www.tonyparisi.com/
  3. */
  4. THREE.glTFLoader = function (showStatus) {
  5. this.meshesRequested = 0;
  6. this.meshesLoaded = 0;
  7. this.pendingMeshes = [];
  8. this.animationsRequested = 0;
  9. this.animationsLoaded = 0;
  10. this.animations = [];
  11. this.shadersRequested = 0;
  12. this.shadersLoaded = 0;
  13. this.shaders = {};
  14. THREE.Loader.call( this, showStatus );
  15. }
  16. THREE.glTFLoader.prototype = Object.create( THREE.Loader.prototype );
  17. THREE.glTFLoader.prototype.constructor = THREE.glTFLoader;
  18. THREE.glTFLoader.prototype.load = function( url, callback ) {
  19. var theLoader = this;
  20. // Utilities
  21. function RgbArraytoHex(colorArray) {
  22. if(!colorArray) return 0xFFFFFFFF;
  23. var r = Math.floor(colorArray[0] * 255),
  24. g = Math.floor(colorArray[1] * 255),
  25. b = Math.floor(colorArray[2] * 255),
  26. a = 255;
  27. var color = (a << 24) + (r << 16) + (g << 8) + b;
  28. return color;
  29. }
  30. function convertAxisAngleToQuaternion(rotations, count)
  31. {
  32. var q = new THREE.Quaternion;
  33. var axis = new THREE.Vector3;
  34. var euler = new THREE.Vector3;
  35. var i;
  36. for (i = 0; i < count; i++) {
  37. axis.set(rotations[i * 4], rotations[i * 4 + 1],
  38. rotations[i * 4 + 2]).normalize();
  39. var angle = rotations[i * 4 + 3];
  40. q.setFromAxisAngle(axis, angle);
  41. rotations[i * 4] = q.x;
  42. rotations[i * 4 + 1] = q.y;
  43. rotations[i * 4 + 2] = q.z;
  44. rotations[i * 4 + 3] = q.w;
  45. }
  46. }
  47. function componentsPerElementForGLType(glType) {
  48. switch (glType) {
  49. case WebGLRenderingContext.FLOAT :
  50. case WebGLRenderingContext.UNSIGNED_BYTE :
  51. case WebGLRenderingContext.UNSIGNED_SHORT :
  52. return 1;
  53. case WebGLRenderingContext.FLOAT_VEC2 :
  54. return 2;
  55. case WebGLRenderingContext.FLOAT_VEC3 :
  56. return 3;
  57. case WebGLRenderingContext.FLOAT_VEC4 :
  58. return 4;
  59. case WebGLRenderingContext.FLOAT_MAT4 :
  60. return 16;
  61. default:
  62. return null;
  63. }
  64. }
  65. function LoadTexture(src) {
  66. if(!src) { return null; }
  67. return THREE.ImageUtils.loadTexture(src);
  68. }
  69. // Geometry processing
  70. var ClassicGeometry = function() {
  71. this.geometry = new THREE.BufferGeometry;
  72. this.totalAttributes = 0;
  73. this.loadedAttributes = 0;
  74. this.indicesLoaded = false;
  75. this.finished = false;
  76. this.onload = null;
  77. this.uvs = null;
  78. this.indexArray = null;
  79. };
  80. ClassicGeometry.prototype.constructor = ClassicGeometry;
  81. ClassicGeometry.prototype.buildBufferGeometry = function() {
  82. // Build indexed mesh
  83. var geometry = this.geometry;
  84. geometry.addAttribute( 'index', new THREE.BufferAttribute( this.indexArray, 1 ) );
  85. geometry.addDrawCall( 0, this.indexArray.length, 0 );
  86. geometry.computeBoundingSphere();
  87. }
  88. ClassicGeometry.prototype.checkFinished = function() {
  89. if(this.indexArray && this.loadedAttributes === this.totalAttributes) {
  90. this.buildBufferGeometry();
  91. this.finished = true;
  92. if(this.onload) {
  93. this.onload();
  94. }
  95. }
  96. };
  97. // Delegate for processing index buffers
  98. var IndicesDelegate = function() {};
  99. IndicesDelegate.prototype.handleError = function(errorCode, info) {
  100. // FIXME: report error
  101. console.log("ERROR(IndicesDelegate):"+errorCode+":"+info);
  102. };
  103. IndicesDelegate.prototype.convert = function(resource, ctx) {
  104. return new Uint16Array(resource, 0, ctx.indices.count);
  105. };
  106. IndicesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  107. var geometry = ctx.geometry;
  108. geometry.indexArray = glResource;
  109. geometry.checkFinished();
  110. return true;
  111. };
  112. var indicesDelegate = new IndicesDelegate();
  113. var IndicesContext = function(indices, geometry) {
  114. this.indices = indices;
  115. this.geometry = geometry;
  116. };
  117. // Delegate for processing vertex attribute buffers
  118. var VertexAttributeDelegate = function() {};
  119. VertexAttributeDelegate.prototype.handleError = function(errorCode, info) {
  120. // FIXME: report error
  121. console.log("ERROR(VertexAttributeDelegate):"+errorCode+":"+info);
  122. };
  123. VertexAttributeDelegate.prototype.convert = function(resource, ctx) {
  124. return resource;
  125. };
  126. VertexAttributeDelegate.prototype.arrayResourceAvailable = function(glResource, ctx) {
  127. var geom = ctx.geometry;
  128. var attribute = ctx.attribute;
  129. var semantic = ctx.semantic;
  130. var floatArray;
  131. var i, l;
  132. //FIXME: Float32 is assumed here, but should be checked.
  133. if(semantic == "POSITION") {
  134. // TODO: Should be easy to take strides into account here
  135. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  136. for(i = 0, l = floatArray.length; i < l; i += 3) {
  137. geom.geometry.vertices.push( new THREE.Vector3( floatArray[i], floatArray[i+1], floatArray[i+2] ) );
  138. }
  139. } else if(semantic == "NORMAL") {
  140. geom.geometry.normals = [];
  141. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  142. for(i = 0, l = floatArray.length; i < l; i += 3) {
  143. geom.geometry.normals.push( new THREE.Vector3( floatArray[i], floatArray[i+1], floatArray[i+2] ) );
  144. }
  145. } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) {
  146. geom.uvs = [];
  147. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  148. for(i = 0, l = floatArray.length; i < l; i += 2) {
  149. geom.uvs.push( new THREE.Vector2( floatArray[i], 1.0 - floatArray[i+1] ) );
  150. }
  151. }
  152. else if (semantic == "WEIGHT") {
  153. nComponents = componentsPerElementForGLType(attribute.type);
  154. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  155. for(i = 0, l = floatArray.length; i < l; i += 4) {
  156. geom.geometry.skinWeights.push( new THREE.Vector4( floatArray[i], floatArray[i+1], floatArray[i+2], floatArray[i+3] ) );
  157. }
  158. }
  159. else if (semantic == "JOINT") {
  160. nComponents = componentsPerElementForGLType(attribute.type);
  161. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  162. for(i = 0, l = floatArray.length; i < l; i += 4) {
  163. geom.geometry.skinIndices.push( new THREE.Vector4( floatArray[i], floatArray[i+1], floatArray[i+2], floatArray[i+3] ) );
  164. }
  165. }
  166. }
  167. VertexAttributeDelegate.prototype.bufferResourceAvailable = function(glResource, ctx) {
  168. var geom = ctx.geometry;
  169. var attribute = ctx.attribute;
  170. var semantic = ctx.semantic;
  171. var floatArray;
  172. var i, l;
  173. var nComponents;
  174. //FIXME: Float32 is assumed here, but should be checked.
  175. if(semantic == "POSITION") {
  176. // TODO: Should be easy to take strides into account here
  177. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  178. geom.geometry.addAttribute( 'position', new THREE.BufferAttribute( floatArray, 3 ) );
  179. } else if(semantic == "NORMAL") {
  180. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  181. geom.geometry.addAttribute( 'normal', new THREE.BufferAttribute( floatArray, 3 ) );
  182. } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) {
  183. nComponents = componentsPerElementForGLType(attribute.type);
  184. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  185. // N.B.: flip Y value... should we just set texture.flipY everywhere?
  186. for (i = 0; i < floatArray.length / 2; i++) {
  187. floatArray[i*2+1] = 1.0 - floatArray[i*2+1];
  188. }
  189. geom.geometry.addAttribute( 'uv', new THREE.BufferAttribute( floatArray, nComponents ) );
  190. }
  191. else if (semantic == "WEIGHT") {
  192. nComponents = componentsPerElementForGLType(attribute.type);
  193. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  194. geom.geometry.addAttribute( 'skinWeight', new THREE.BufferAttribute( floatArray, nComponents ) );
  195. }
  196. else if (semantic == "JOINT") {
  197. nComponents = componentsPerElementForGLType(attribute.type);
  198. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  199. geom.geometry.addAttribute( 'skinIndex', new THREE.BufferAttribute( floatArray, nComponents ) );
  200. }
  201. }
  202. VertexAttributeDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  203. this.bufferResourceAvailable(glResource, ctx);
  204. var geom = ctx.geometry;
  205. geom.loadedAttributes++;
  206. geom.checkFinished();
  207. return true;
  208. };
  209. var vertexAttributeDelegate = new VertexAttributeDelegate();
  210. var VertexAttributeContext = function(attribute, semantic, geometry) {
  211. this.attribute = attribute;
  212. this.semantic = semantic;
  213. this.geometry = geometry;
  214. };
  215. var Mesh = function() {
  216. this.primitives = [];
  217. this.materialsPending = [];
  218. this.loadedGeometry = 0;
  219. this.onCompleteCallbacks = [];
  220. };
  221. Mesh.prototype.addPrimitive = function(geometry, material) {
  222. var self = this;
  223. geometry.onload = function() {
  224. self.loadedGeometry++;
  225. self.checkComplete();
  226. };
  227. this.primitives.push({
  228. geometry: geometry,
  229. material: material,
  230. mesh: null
  231. });
  232. };
  233. Mesh.prototype.onComplete = function(callback) {
  234. this.onCompleteCallbacks.push(callback);
  235. this.checkComplete();
  236. };
  237. Mesh.prototype.checkComplete = function() {
  238. var self = this;
  239. if(this.onCompleteCallbacks.length && this.primitives.length == this.loadedGeometry) {
  240. this.onCompleteCallbacks.forEach(function(callback) {
  241. callback(self);
  242. });
  243. this.onCompleteCallbacks = [];
  244. }
  245. };
  246. Mesh.prototype.attachToNode = function(threeNode) {
  247. // Assumes that the geometry is complete
  248. this.primitives.forEach(function(primitive) {
  249. /*if(!primitive.mesh) {
  250. primitive.mesh = new THREE.Mesh(primitive.geometry, primitive.material);
  251. }*/
  252. var material = primitive.material;
  253. if (!(material instanceof THREE.Material)) {
  254. material = theLoader.createShaderMaterial(material);
  255. }
  256. var threeMesh = new THREE.Mesh(primitive.geometry.geometry, material);
  257. threeMesh.castShadow = true;
  258. threeNode.add(threeMesh);
  259. });
  260. };
  261. // Delayed-loaded material
  262. var Material = function(params) {
  263. this.params = params;
  264. };
  265. // Delegate for processing animation parameter buffers
  266. var AnimationParameterDelegate = function() {};
  267. AnimationParameterDelegate.prototype.handleError = function(errorCode, info) {
  268. // FIXME: report error
  269. console.log("ERROR(AnimationParameterDelegate):"+errorCode+":"+info);
  270. };
  271. AnimationParameterDelegate.prototype.convert = function(resource, ctx) {
  272. var parameter = ctx.parameter;
  273. var glResource = null;
  274. switch (parameter.type) {
  275. case WebGLRenderingContext.FLOAT :
  276. case WebGLRenderingContext.FLOAT_VEC2 :
  277. case WebGLRenderingContext.FLOAT_VEC3 :
  278. case WebGLRenderingContext.FLOAT_VEC4 :
  279. glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
  280. break;
  281. default:
  282. break;
  283. }
  284. return glResource;
  285. };
  286. AnimationParameterDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  287. var animation = ctx.animation;
  288. var parameter = ctx.parameter;
  289. parameter.data = glResource;
  290. animation.handleParameterLoaded(parameter);
  291. return true;
  292. };
  293. var animationParameterDelegate = new AnimationParameterDelegate();
  294. var AnimationParameterContext = function(parameter, animation) {
  295. this.parameter = parameter;
  296. this.animation = animation;
  297. };
  298. // Animations
  299. var Animation = function() {
  300. // create Three.js keyframe here
  301. this.totalParameters = 0;
  302. this.loadedParameters = 0;
  303. this.parameters = {};
  304. this.finishedLoading = false;
  305. this.onload = null;
  306. };
  307. Animation.prototype.constructor = Animation;
  308. Animation.prototype.handleParameterLoaded = function(parameter) {
  309. this.parameters[parameter.name] = parameter;
  310. this.loadedParameters++;
  311. this.checkFinished();
  312. };
  313. Animation.prototype.checkFinished = function() {
  314. if(this.loadedParameters === this.totalParameters) {
  315. // Build animation
  316. this.finishedLoading = true;
  317. if (this.onload) {
  318. this.onload();
  319. }
  320. }
  321. };
  322. // Delegate for processing inverse bind matrices buffer
  323. var InverseBindMatricesDelegate = function() {};
  324. InverseBindMatricesDelegate.prototype.handleError = function(errorCode, info) {
  325. // FIXME: report error
  326. console.log("ERROR(InverseBindMatricesDelegate):"+errorCode+":"+info);
  327. };
  328. InverseBindMatricesDelegate.prototype.convert = function(resource, ctx) {
  329. var parameter = ctx.parameter;
  330. var glResource = null;
  331. switch (parameter.type) {
  332. case WebGLRenderingContext.FLOAT_MAT4 :
  333. glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
  334. break;
  335. default:
  336. break;
  337. }
  338. return glResource;
  339. };
  340. InverseBindMatricesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  341. var skin = ctx.skin;
  342. skin.inverseBindMatrices = glResource;
  343. return true;
  344. };
  345. var inverseBindMatricesDelegate = new InverseBindMatricesDelegate();
  346. var InverseBindMatricesContext = function(param, skin) {
  347. this.parameter = param;
  348. this.skin = skin;
  349. };
  350. // Delegate for processing shaders from external files
  351. var ShaderDelegate = function() {};
  352. ShaderDelegate.prototype.handleError = function(errorCode, info) {
  353. // FIXME: report error
  354. console.log("ERROR(ShaderDelegate):"+errorCode+":"+info);
  355. };
  356. ShaderDelegate.prototype.convert = function(resource, ctx) {
  357. return resource;
  358. }
  359. ShaderDelegate.prototype.resourceAvailable = function(data, ctx) {
  360. theLoader.shadersLoaded++;
  361. theLoader.shaders[ctx.id] = data;
  362. return true;
  363. };
  364. var shaderDelegate = new ShaderDelegate();
  365. var ShaderContext = function(id, path) {
  366. this.id = id;
  367. this.path = path;
  368. };
  369. // Resource management
  370. var ResourceEntry = function(entryID, object, description) {
  371. this.entryID = entryID;
  372. this.object = object;
  373. this.description = description;
  374. };
  375. var Resources = function() {
  376. this._entries = {};
  377. };
  378. Resources.prototype.setEntry = function(entryID, object, description) {
  379. if (!entryID) {
  380. console.error("No EntryID provided, cannot store", description);
  381. return;
  382. }
  383. if (this._entries[entryID]) {
  384. console.warn("entry["+entryID+"] is being overwritten");
  385. }
  386. this._entries[entryID] = new ResourceEntry(entryID, object, description );
  387. };
  388. Resources.prototype.getEntry = function(entryID) {
  389. return this._entries[entryID];
  390. };
  391. Resources.prototype.clearEntries = function() {
  392. this._entries = {};
  393. };
  394. LoadDelegate = function() {
  395. }
  396. LoadDelegate.prototype.loadCompleted = function(callback, obj) {
  397. callback.call(Window, obj);
  398. }
  399. // Loader
  400. var ThreeGLTFLoader = Object.create(glTFParser, {
  401. load: {
  402. enumerable: true,
  403. value: function(userInfo, options) {
  404. this.resources = new Resources();
  405. this.cameras = [];
  406. this.lights = [];
  407. this.animations = [];
  408. this.joints = {};
  409. this.skeltons = {};
  410. THREE.GLTFLoaderUtils.init();
  411. glTFParser.load.call(this, userInfo, options);
  412. }
  413. },
  414. cameras: {
  415. enumerable: true,
  416. writable: true,
  417. value : []
  418. },
  419. lights: {
  420. enumerable: true,
  421. writable: true,
  422. value : []
  423. },
  424. animations: {
  425. enumerable: true,
  426. writable: true,
  427. value : []
  428. },
  429. // Implement WebGLTFLoader handlers
  430. handleBuffer: {
  431. value: function(entryID, description, userInfo) {
  432. this.resources.setEntry(entryID, null, description);
  433. description.type = "ArrayBuffer";
  434. return true;
  435. }
  436. },
  437. handleBufferView: {
  438. value: function(entryID, description, userInfo) {
  439. this.resources.setEntry(entryID, null, description);
  440. var buffer = this.resources.getEntry(description.buffer);
  441. description.type = "ArrayBufferView";
  442. var bufferViewEntry = this.resources.getEntry(entryID);
  443. bufferViewEntry.buffer = buffer;
  444. return true;
  445. }
  446. },
  447. handleShader: {
  448. value: function(entryID, description, userInfo) {
  449. this.resources.setEntry(entryID, null, description);
  450. var shaderRequest = {
  451. id : entryID,
  452. path : description.path,
  453. };
  454. var shaderContext = new ShaderContext(entryID, description.path);
  455. theLoader.shadersRequested++;
  456. THREE.GLTFLoaderUtils.getFile(shaderRequest, shaderDelegate, shaderContext);
  457. return true;
  458. }
  459. },
  460. handleProgram: {
  461. value: function(entryID, description, userInfo) {
  462. this.resources.setEntry(entryID, null, description);
  463. return true;
  464. }
  465. },
  466. handleTechnique: {
  467. value: function(entryID, description, userInfo) {
  468. this.resources.setEntry(entryID, null, description);
  469. return true;
  470. }
  471. },
  472. createShaderMaterial : {
  473. value: function(material) {
  474. var fragmentShader = theLoader.shaders[material.params.fragmentShader];
  475. if (!fragmentShader) {
  476. console.log("ERROR: Missing fragment shader definition:", material.params.fragmentShader);
  477. return new THREE.MeshPhongMaterial;
  478. }
  479. var vertexShader = theLoader.shaders[material.params.vertexShader];
  480. if (!fragmentShader) {
  481. console.log("ERROR: Missing vertex shader definition:", material.params.vertexShader);
  482. return new THREE.MeshPhongMaterial;
  483. }
  484. var uniforms = {};
  485. var shaderMaterial = new THREE.ShaderMaterial( {
  486. fragmentShader: fragmentShader,
  487. vertexShader: vertexShader,
  488. uniforms: uniforms,
  489. } );
  490. return new THREE.MeshPhongMaterial(material.params);
  491. }
  492. },
  493. createShaderParams : {
  494. value: function(materialId, values, params, instanceProgram) {
  495. var program = this.resources.getEntry(instanceProgram.program);
  496. if (program) {
  497. params.fragmentShader = program.description.fragmentShader;
  498. params.vertexShader = program.description.vertexShader;
  499. params.attributes = instanceProgram.attributes;
  500. params.uniforms = instanceProgram.uniforms;
  501. }
  502. }
  503. },
  504. threeJSMaterialType : {
  505. value: function(materialId, technique, values, params) {
  506. var materialType = THREE.MeshPhongMaterial;
  507. var defaultPass = null;
  508. if (technique && technique.description && technique.description.passes)
  509. defaultPass = technique.description.passes.defaultPass;
  510. if (defaultPass) {
  511. if (defaultPass.details && defaultPass.details.commonProfile) {
  512. var profile = technique.description.passes.defaultPass.details.commonProfile;
  513. if (profile)
  514. {
  515. switch (profile.lightingModel)
  516. {
  517. case 'Blinn' :
  518. case 'Phong' :
  519. materialType = THREE.MeshPhongMaterial;
  520. break;
  521. case 'Lambert' :
  522. materialType = THREE.MeshLambertMaterial;
  523. break;
  524. default :
  525. materialType = THREE.MeshBasicMaterial;
  526. break;
  527. }
  528. if (profile.extras && profile.extras.doubleSided)
  529. {
  530. params.side = THREE.DoubleSide;
  531. }
  532. }
  533. }
  534. else if (defaultPass.instanceProgram) {
  535. var instanceProgram = defaultPass.instanceProgram;
  536. this.createShaderParams(materialId, values, params, instanceProgram);
  537. var loadshaders = true;
  538. if (loadshaders) {
  539. materialType = Material;
  540. }
  541. }
  542. }
  543. var texturePath = null;
  544. var textureParams = null;
  545. var diffuse = values.diffuse;
  546. if (diffuse)
  547. {
  548. var texture = diffuse;
  549. if (texture) {
  550. var textureEntry = this.resources.getEntry(texture);
  551. if (textureEntry) {
  552. {
  553. var imageEntry = this.resources.getEntry(textureEntry.description.source);
  554. if (imageEntry) {
  555. texturePath = imageEntry.description.path;
  556. }
  557. var samplerEntry = this.resources.getEntry(textureEntry.description.sampler);
  558. if (samplerEntry) {
  559. textureParams = samplerEntry.description;
  560. }
  561. }
  562. }
  563. }
  564. }
  565. var texture = LoadTexture(texturePath);
  566. if (texture && textureParams) {
  567. if (textureParams.wrapS == WebGLRenderingContext.REPEAT)
  568. texture.wrapS = THREE.RepeatWrapping;
  569. if (textureParams.wrapT == WebGLRenderingContext.REPEAT)
  570. texture.wrapT = THREE.RepeatWrapping;
  571. if (textureParams.magFilter == WebGLRenderingContext.LINEAR)
  572. texture.magFilter = THREE.LinearFilter;
  573. // if (textureParams.minFilter == "LINEAR")
  574. // texture.minFilter = THREE.LinearFilter;
  575. params.map = texture;
  576. }
  577. var envMapPath = null;
  578. var envMapParams = null;
  579. var reflective = values.reflective;
  580. if (reflective)
  581. {
  582. var texture = reflective;
  583. if (texture) {
  584. var textureEntry = this.resources.getEntry(texture);
  585. if (textureEntry) {
  586. {
  587. var imageEntry = this.resources.getEntry(textureEntry.description.source);
  588. if (imageEntry) {
  589. envMapPath = imageEntry.description.path;
  590. }
  591. var samplerEntry = this.resources.getEntry(textureEntry.description.sampler);
  592. if (samplerEntry) {
  593. envMapParams = samplerEntry.description;
  594. }
  595. }
  596. }
  597. }
  598. }
  599. var texture = LoadTexture(envMapPath);
  600. if (texture && envMapParams) {
  601. if (envMapParams.wrapS == WebGLRenderingContext.REPEAT)
  602. texture.wrapS = THREE.RepeatWrapping;
  603. if (envMapParams.wrapT == WebGLRenderingContext.REPEAT)
  604. texture.wrapT = THREE.RepeatWrapping;
  605. if (envMapParams.magFilter == WebGLRenderingContext.LINEAR)
  606. texture.magFilter = THREE.LinearFilter;
  607. // if (envMapParams.minFilter == WebGLRenderingContext.LINEAR)
  608. // texture.minFilter = THREE.LinearFilter;
  609. params.envMap = texture;
  610. }
  611. var shininess = values.shininesss || values.shininess; // N.B.: typo in converter!
  612. if (shininess)
  613. {
  614. shininess = shininess;
  615. }
  616. var diffuseColor = !texturePath ? diffuse : null;
  617. var opacity = 1.0;
  618. if (values.hasOwnProperty("transparency"))
  619. {
  620. var USE_A_ONE = true; // for now, hack because file format isn't telling us
  621. opacity = USE_A_ONE ? values.transparency : (1.0 - values.transparency);
  622. }
  623. // if (diffuseColor) diffuseColor = [0, 1, 0];
  624. params.color = RgbArraytoHex(diffuseColor);
  625. params.opacity = opacity;
  626. params.transparent = opacity < 1.0;
  627. // hack hack hack
  628. if (texturePath && texturePath.toLowerCase().indexOf(".png") != -1)
  629. params.transparent = true;
  630. if (!(shininess === undefined))
  631. {
  632. params.shininess = shininess;
  633. }
  634. if (!(values.ambient === undefined) && !(typeof(values.ambient) == 'string'))
  635. {
  636. params.ambient = RgbArraytoHex(values.ambient);
  637. }
  638. if (!(values.emission === undefined))
  639. {
  640. params.emissive = RgbArraytoHex(values.emission);
  641. }
  642. if (!(values.specular === undefined))
  643. {
  644. params.specular = RgbArraytoHex(values.specular);
  645. }
  646. return materialType;
  647. }
  648. },
  649. handleMaterial: {
  650. value: function(entryID, description, userInfo) {
  651. //this should be rewritten using the meta datas that actually create the shader.
  652. //here we will infer what needs to be pass to Three.js by looking inside the technique parameters.
  653. var technique = this.resources.getEntry(description.instanceTechnique.technique);
  654. var materialParams = {};
  655. var values = description.instanceTechnique.values;
  656. var materialType = this.threeJSMaterialType(entryID, technique, values, materialParams);
  657. var material = new materialType(materialParams);
  658. this.resources.setEntry(entryID, material, description);
  659. return true;
  660. }
  661. },
  662. handleMesh: {
  663. value: function(entryID, description, userInfo) {
  664. var mesh = new Mesh();
  665. this.resources.setEntry(entryID, mesh, description);
  666. var primitivesDescription = description.primitives;
  667. if (!primitivesDescription) {
  668. //FIXME: not implemented in delegate
  669. console.log("MISSING_PRIMITIVES for mesh:"+ entryID);
  670. return false;
  671. }
  672. for (var i = 0 ; i < primitivesDescription.length ; i++) {
  673. var primitiveDescription = primitivesDescription[i];
  674. if (primitiveDescription.primitive === WebGLRenderingContext.TRIANGLES) {
  675. var geometry = new ClassicGeometry();
  676. var materialEntry = this.resources.getEntry(primitiveDescription.material);
  677. mesh.addPrimitive(geometry, materialEntry.object);
  678. var indices = this.resources.getEntry(primitiveDescription.indices);
  679. var bufferEntry = this.resources.getEntry(indices.description.bufferView);
  680. var indicesObject = {
  681. bufferView : bufferEntry,
  682. byteOffset : indices.description.byteOffset,
  683. count : indices.description.count,
  684. id : indices.entryID,
  685. type : indices.description.type
  686. };
  687. var indicesContext = new IndicesContext(indicesObject, geometry);
  688. var alreadyProcessedIndices = THREE.GLTFLoaderUtils.getBuffer(indicesObject, indicesDelegate, indicesContext);
  689. /*if(alreadyProcessedIndices) {
  690. indicesDelegate.resourceAvailable(alreadyProcessedIndices, indicesContext);
  691. }*/
  692. // Load Vertex Attributes
  693. var allAttributes = Object.keys(primitiveDescription.attributes);
  694. allAttributes.forEach( function(semantic) {
  695. geometry.totalAttributes++;
  696. var attribute;
  697. var attributeID = primitiveDescription.attributes[semantic];
  698. var attributeEntry = this.resources.getEntry(attributeID);
  699. if (!attributeEntry) {
  700. //let's just use an anonymous object for the attribute
  701. attribute = description.attributes[attributeID];
  702. attribute.id = attributeID;
  703. this.resources.setEntry(attributeID, attribute, attribute);
  704. var bufferEntry = this.resources.getEntry(attribute.bufferView);
  705. attributeEntry = this.resources.getEntry(attributeID);
  706. } else {
  707. attribute = attributeEntry.object;
  708. attribute.id = attributeID;
  709. var bufferEntry = this.resources.getEntry(attribute.bufferView);
  710. }
  711. var attributeObject = {
  712. bufferView : bufferEntry,
  713. byteOffset : attribute.byteOffset,
  714. byteStride : attribute.byteStride,
  715. count : attribute.count,
  716. max : attribute.max,
  717. min : attribute.min,
  718. type : attribute.type,
  719. id : attributeID
  720. };
  721. var attribContext = new VertexAttributeContext(attributeObject, semantic, geometry);
  722. var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(attributeObject, vertexAttributeDelegate, attribContext);
  723. /*if(alreadyProcessedAttribute) {
  724. vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
  725. }*/
  726. }, this);
  727. }
  728. }
  729. return true;
  730. }
  731. },
  732. handleCamera: {
  733. value: function(entryID, description, userInfo) {
  734. var camera;
  735. if (description.type == "perspective")
  736. {
  737. var znear = description.perspective.znear;
  738. var zfar = description.perspective.zfar;
  739. var yfov = description.perspective.yfov;
  740. var xfov = description.perspective.xfov;
  741. var aspect_ratio = description.perspective.aspect_ratio;
  742. if (!aspect_ratio)
  743. aspect_ratio = 1;
  744. if (yfov === undefined)
  745. {
  746. if (xfov)
  747. {
  748. // According to COLLADA spec...
  749. // aspect_ratio = xfov / yfov
  750. yfov = xfov / aspect_ratio;
  751. }
  752. }
  753. if (yfov)
  754. {
  755. camera = new THREE.PerspectiveCamera(yfov, aspect_ratio, znear, zfar);
  756. }
  757. }
  758. else
  759. {
  760. camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, znear, zfar );
  761. }
  762. if (camera)
  763. {
  764. this.resources.setEntry(entryID, camera, description);
  765. }
  766. return true;
  767. }
  768. },
  769. handleLight: {
  770. value: function(entryID, description, userInfo) {
  771. var light = null;
  772. var type = description.type;
  773. if (type && description[type])
  774. {
  775. var lparams = description[type];
  776. var color = RgbArraytoHex(lparams.color);
  777. switch (type) {
  778. case "directional" :
  779. light = new THREE.DirectionalLight(color);
  780. light.position.set(0, 0, 1);
  781. break;
  782. case "point" :
  783. light = new THREE.PointLight(color);
  784. break;
  785. case "spot " :
  786. light = new THREE.SpotLight(color);
  787. light.position.set(0, 0, 1);
  788. break;
  789. case "ambient" :
  790. light = new THREE.AmbientLight(color);
  791. break;
  792. }
  793. }
  794. if (light)
  795. {
  796. this.resources.setEntry(entryID, light, description);
  797. }
  798. return true;
  799. }
  800. },
  801. addPendingMesh: {
  802. value: function(mesh, threeNode) {
  803. theLoader.pendingMeshes.push({
  804. mesh: mesh,
  805. node: threeNode
  806. });
  807. }
  808. },
  809. handleNode: {
  810. value: function(entryID, description, userInfo) {
  811. var threeNode = null;
  812. if (description.jointId) {
  813. threeNode = new THREE.Bone();
  814. threeNode.jointId = description.jointId;
  815. this.joints[description.jointId] = entryID;
  816. }
  817. else {
  818. threeNode = new THREE.Object3D();
  819. }
  820. threeNode.name = description.name;
  821. this.resources.setEntry(entryID, threeNode, description);
  822. var m = description.matrix;
  823. if(m) {
  824. threeNode.applyMatrix(new THREE.Matrix4().fromArray( m ));
  825. threeNode.matrixAutoUpdate = false;
  826. threeNode.matrixWorldNeedsUpdate = true;
  827. }
  828. else {
  829. var t = description.translation;
  830. var r = description.rotation;
  831. var s = description.scale;
  832. var position = t ? new THREE.Vector3(t[0], t[1], t[2]) :
  833. new THREE.Vector3;
  834. if (r) {
  835. convertAxisAngleToQuaternion(r, 1);
  836. }
  837. var rotation = r ? new THREE.Quaternion(r[0], r[1], r[2], r[3]) :
  838. new THREE.Quaternion;
  839. var scale = s ? new THREE.Vector3(s[0], s[1], s[2]) :
  840. new THREE.Vector3;
  841. var matrix = new THREE.Matrix4;
  842. matrix.compose(position, rotation, scale);
  843. threeNode.matrixAutoUpdate = false;
  844. threeNode.matrixWorldNeedsUpdate = true;
  845. threeNode.applyMatrix(matrix);
  846. }
  847. var self = this;
  848. // Iterate through all node meshes and attach the appropriate objects
  849. //FIXME: decision needs to be made between these 2 ways, probably meshes will be discarded.
  850. var meshEntry;
  851. if (description.mesh) {
  852. meshEntry = this.resources.getEntry(description.mesh);
  853. theLoader.meshesRequested++;
  854. meshEntry.object.onComplete(function(mesh) {
  855. self.addPendingMesh(mesh, threeNode);
  856. theLoader.meshesLoaded++;
  857. theLoader.checkComplete();
  858. });
  859. }
  860. if (description.meshes) {
  861. description.meshes.forEach( function(meshID) {
  862. meshEntry = this.resources.getEntry(meshID);
  863. theLoader.meshesRequested++;
  864. meshEntry.object.onComplete(function(mesh) {
  865. self.addPendingMesh(mesh, threeNode);
  866. theLoader.meshesLoaded++;
  867. theLoader.checkComplete();
  868. });
  869. }, this);
  870. }
  871. if (description.instanceSkin) {
  872. var skinEntry = this.resources.getEntry(description.instanceSkin.skin);
  873. if (skinEntry) {
  874. var skin = skinEntry.object;
  875. description.instanceSkin.skin = skin;
  876. threeNode.instanceSkin = description.instanceSkin;
  877. var sources = description.instanceSkin.sources;
  878. skin.meshes = [];
  879. sources.forEach( function(meshID) {
  880. meshEntry = this.resources.getEntry(meshID);
  881. theLoader.meshesRequested++;
  882. meshEntry.object.onComplete(function(mesh) {
  883. skin.meshes.push(mesh);
  884. theLoader.meshesLoaded++;
  885. theLoader.checkComplete();
  886. });
  887. }, this);
  888. }
  889. }
  890. if (description.camera) {
  891. var cameraEntry = this.resources.getEntry(description.camera);
  892. if (cameraEntry) {
  893. threeNode.add(cameraEntry.object);
  894. this.cameras.push(cameraEntry.object);
  895. }
  896. }
  897. if (description.light) {
  898. var lightEntry = this.resources.getEntry(description.light);
  899. if (lightEntry) {
  900. threeNode.add(lightEntry.object);
  901. this.lights.push(lightEntry.object);
  902. }
  903. }
  904. return true;
  905. }
  906. },
  907. buildNodeHirerachy: {
  908. value: function(nodeEntryId, parentThreeNode) {
  909. var nodeEntry = this.resources.getEntry(nodeEntryId);
  910. var threeNode = nodeEntry.object;
  911. parentThreeNode.add(threeNode);
  912. var children = nodeEntry.description.children;
  913. if (children) {
  914. children.forEach( function(childID) {
  915. this.buildNodeHirerachy(childID, threeNode);
  916. }, this);
  917. }
  918. return threeNode;
  919. }
  920. },
  921. buildSkin: {
  922. value: function(node) {
  923. var skin = node.instanceSkin.skin;
  924. if (skin) {
  925. node.instanceSkin.skeletons.forEach(function(skeleton) {
  926. var nodeEntry = this.resources.getEntry(skeleton);
  927. if (nodeEntry) {
  928. var rootSkeleton = nodeEntry.object;
  929. var dobones = true;
  930. var i, len = skin.meshes.length;
  931. for (i = 0; i < len; i++) {
  932. var mesh = skin.meshes[i];
  933. var threeMesh = null;
  934. mesh.primitives.forEach(function(primitive) {
  935. var material = primitive.material;
  936. if (!(material instanceof THREE.Material)) {
  937. material = this.createShaderMaterial(material);
  938. }
  939. threeMesh = new THREE.SkinnedMesh(primitive.geometry.geometry, material, false);
  940. threeMesh.add(rootSkeleton);
  941. var geometry = primitive.geometry.geometry;
  942. var j;
  943. if (geometry.vertices) {
  944. for ( j = 0; j < geometry.vertices.length; j ++ ) {
  945. geometry.vertices[j].applyMatrix4( skin.bindShapeMatrix );
  946. }
  947. }
  948. else if (geometry.attributes.position) {
  949. var a = geometry.attributes.position.array;
  950. var v = new THREE.Vector3;
  951. for ( j = 0; j < a.length / 3; j++ ) {
  952. v.set(a[j * 3], a[j * 3 + 1], a[j * 3 + 2]);
  953. v.applyMatrix4( skin.bindShapeMatrix );
  954. a[j * 3] = v.x;
  955. a[j * 3 + 1] = v.y;
  956. a[j * 3 + 2] = v.z;
  957. }
  958. }
  959. if (threeMesh && dobones) {
  960. material.skinning = true;
  961. threeMesh.boneInverses = [];
  962. var jointsIds = skin.jointsIds;
  963. var bones = [];
  964. var boneInverses = [];
  965. var i, len = jointsIds.length;
  966. for (i = 0; i < len; i++) {
  967. var jointId = jointsIds[i];
  968. var nodeForJoint = this.joints[jointId];
  969. var joint = this.resources.getEntry(nodeForJoint).object;
  970. if (joint) {
  971. joint.skin = threeMesh;
  972. bones.push(joint);
  973. var m = skin.inverseBindMatrices;
  974. var mat = new THREE.Matrix4().set(
  975. m[i * 16 + 0], m[i * 16 + 4], m[i * 16 + 8], m[i * 16 + 12],
  976. m[i * 16 + 1], m[i * 16 + 5], m[i * 16 + 9], m[i * 16 + 13],
  977. m[i * 16 + 2], m[i * 16 + 6], m[i * 16 + 10], m[i * 16 + 14],
  978. m[i * 16 + 3], m[i * 16 + 7], m[i * 16 + 11], m[i * 16 + 15]
  979. );
  980. boneInverses.push(mat);
  981. } else {
  982. console.log("WARNING: jointId:"+jointId+" cannot be found in skeleton:"+skeleton);
  983. }
  984. }
  985. threeMesh.bind(new THREE.Skeleton(bones, boneInverses, false));
  986. }
  987. if (threeMesh) {
  988. threeMesh.castShadow = true;
  989. node.add(threeMesh);
  990. }
  991. }, this);
  992. }
  993. }
  994. }, this);
  995. }
  996. }
  997. },
  998. buildSkins: {
  999. value: function(node) {
  1000. if (node.instanceSkin)
  1001. this.buildSkin(node);
  1002. var children = node.children;
  1003. if (children) {
  1004. children.forEach( function(child) {
  1005. this.buildSkins(child);
  1006. }, this);
  1007. }
  1008. }
  1009. },
  1010. createMeshAnimations : {
  1011. value : function(root) {
  1012. this.buildSkins(root);
  1013. }
  1014. },
  1015. handleScene: {
  1016. value: function(entryID, description, userInfo) {
  1017. if (!description.nodes) {
  1018. console.log("ERROR: invalid file required nodes property is missing from scene");
  1019. return false;
  1020. }
  1021. description.nodes.forEach( function(nodeUID) {
  1022. this.buildNodeHirerachy(nodeUID, userInfo.rootObj);
  1023. }, this);
  1024. if (this.delegate) {
  1025. this.delegate.loadCompleted(userInfo.callback, userInfo.rootObj);
  1026. }
  1027. return true;
  1028. }
  1029. },
  1030. handleImage: {
  1031. value: function(entryID, description, userInfo) {
  1032. this.resources.setEntry(entryID, null, description);
  1033. return true;
  1034. }
  1035. },
  1036. addNodeAnimationChannel : {
  1037. value : function(name, channel, interp) {
  1038. if (!this.nodeAnimationChannels)
  1039. this.nodeAnimationChannels = {};
  1040. if (!this.nodeAnimationChannels[name]) {
  1041. this.nodeAnimationChannels[name] = [];
  1042. }
  1043. this.nodeAnimationChannels[name].push(interp);
  1044. },
  1045. },
  1046. createAnimations : {
  1047. value : function() {
  1048. for (var name in this.nodeAnimationChannels) {
  1049. var nodeAnimationChannels = this.nodeAnimationChannels[name];
  1050. var i, len = nodeAnimationChannels.length;
  1051. //console.log(" animation channels for node " + name);
  1052. //for (i = 0; i < len; i++) {
  1053. // console.log(nodeAnimationChannels[i]);
  1054. //}
  1055. var anim = new THREE.glTFAnimation(nodeAnimationChannels);
  1056. anim.name = "animation_" + name;
  1057. this.animations.push(anim);
  1058. }
  1059. }
  1060. },
  1061. buildAnimation: {
  1062. value : function(animation) {
  1063. var interps = [];
  1064. var i, len = animation.channels.length;
  1065. for (i = 0; i < len; i++) {
  1066. var channel = animation.channels[i];
  1067. var sampler = animation.samplers[channel.sampler];
  1068. if (sampler) {
  1069. var input = animation.parameters[sampler.input];
  1070. if (input && input.data) {
  1071. var output = animation.parameters[sampler.output];
  1072. if (output && output.data) {
  1073. var target = channel.target;
  1074. var node = this.resources.getEntry(target.id);
  1075. if (node) {
  1076. var path = target.path;
  1077. if (path == "rotation")
  1078. {
  1079. convertAxisAngleToQuaternion(output.data, output.count);
  1080. }
  1081. var interp = {
  1082. keys : input.data,
  1083. values : output.data,
  1084. count : input.count,
  1085. target : node.object,
  1086. path : path,
  1087. type : sampler.interpolation
  1088. };
  1089. this.addNodeAnimationChannel(target.id, channel, interp);
  1090. interps.push(interp);
  1091. }
  1092. }
  1093. }
  1094. }
  1095. }
  1096. }
  1097. },
  1098. handleAnimation: {
  1099. value: function(entryID, description, userInfo) {
  1100. var self = this;
  1101. theLoader.animationsRequested++;
  1102. var animation = new Animation();
  1103. animation.name = entryID;
  1104. animation.onload = function() {
  1105. // self.buildAnimation(animation);
  1106. theLoader.animationsLoaded++;
  1107. theLoader.animations.push(animation);
  1108. theLoader.checkComplete();
  1109. };
  1110. animation.channels = description.channels;
  1111. animation.samplers = description.samplers;
  1112. this.resources.setEntry(entryID, animation, description);
  1113. var parameters = description.parameters;
  1114. if (!parameters) {
  1115. //FIXME: not implemented in delegate
  1116. console.log("MISSING_PARAMETERS for animation:"+ entryID);
  1117. return false;
  1118. }
  1119. // Load parameter buffers
  1120. var params = Object.keys(parameters);
  1121. params.forEach( function(param) {
  1122. animation.totalParameters++;
  1123. var parameter = parameters[param];
  1124. var accessor = this.resources.getEntry(parameter);
  1125. if (!accessor)
  1126. debugger;
  1127. accessor = accessor.object;
  1128. var bufferView = this.resources.getEntry(accessor.bufferView);
  1129. var paramObject = {
  1130. bufferView : bufferView,
  1131. byteOffset : accessor.byteOffset,
  1132. count : accessor.count,
  1133. type : accessor.type,
  1134. id : accessor.bufferView,
  1135. name : param
  1136. };
  1137. var paramContext = new AnimationParameterContext(paramObject, animation);
  1138. var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, animationParameterDelegate, paramContext);
  1139. /*if(alreadyProcessedAttribute) {
  1140. vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
  1141. }*/
  1142. }, this);
  1143. return true;
  1144. }
  1145. },
  1146. handleAccessor: {
  1147. value: function(entryID, description, userInfo) {
  1148. // Save attribute entry
  1149. this.resources.setEntry(entryID, description, description);
  1150. return true;
  1151. }
  1152. },
  1153. handleSkin: {
  1154. value: function(entryID, description, userInfo) {
  1155. // Save skin entry
  1156. var skin = {
  1157. };
  1158. var m = description.bindShapeMatrix;
  1159. skin.bindShapeMatrix = new THREE.Matrix4().fromArray( m );
  1160. skin.jointsIds = description.joints;
  1161. var inverseBindMatricesDescription = description.inverseBindMatrices;
  1162. skin.inverseBindMatricesDescription = inverseBindMatricesDescription;
  1163. skin.inverseBindMatricesDescription.id = entryID + "_inverseBindMatrices";
  1164. var bufferEntry = this.resources.getEntry(inverseBindMatricesDescription.bufferView);
  1165. var paramObject = {
  1166. bufferView : bufferEntry,
  1167. byteOffset : inverseBindMatricesDescription.byteOffset,
  1168. count : inverseBindMatricesDescription.count,
  1169. type : inverseBindMatricesDescription.type,
  1170. id : inverseBindMatricesDescription.bufferView,
  1171. name : skin.inverseBindMatricesDescription.id
  1172. };
  1173. var context = new InverseBindMatricesContext(paramObject, skin);
  1174. var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, inverseBindMatricesDelegate, context);
  1175. var bufferView = this.resources.getEntry(skin.inverseBindMatricesDescription.bufferView);
  1176. skin.inverseBindMatricesDescription.bufferView =
  1177. bufferView.object;
  1178. this.resources.setEntry(entryID, skin, description);
  1179. return true;
  1180. }
  1181. },
  1182. handleSampler: {
  1183. value: function(entryID, description, userInfo) {
  1184. // Save attribute entry
  1185. this.resources.setEntry(entryID, description, description);
  1186. return true;
  1187. }
  1188. },
  1189. handleTexture: {
  1190. value: function(entryID, description, userInfo) {
  1191. // Save attribute entry
  1192. this.resources.setEntry(entryID, null, description);
  1193. return true;
  1194. }
  1195. },
  1196. handleError: {
  1197. value: function(msg) {
  1198. throw new Error(msg);
  1199. return true;
  1200. }
  1201. },
  1202. _delegate: {
  1203. value: new LoadDelegate,
  1204. writable: true
  1205. },
  1206. delegate: {
  1207. enumerable: true,
  1208. get: function() {
  1209. return this._delegate;
  1210. },
  1211. set: function(value) {
  1212. this._delegate = value;
  1213. }
  1214. }
  1215. });
  1216. // Loader
  1217. var Context = function(rootObj, callback) {
  1218. this.rootObj = rootObj;
  1219. this.callback = callback;
  1220. };
  1221. var rootObj = new THREE.Object3D();
  1222. var self = this;
  1223. var loader = Object.create(ThreeGLTFLoader);
  1224. loader.initWithPath(url);
  1225. loader.load(new Context(rootObj,
  1226. function(obj) {
  1227. }),
  1228. null);
  1229. this.loader = loader;
  1230. this.callback = callback;
  1231. this.rootObj = rootObj;
  1232. return rootObj;
  1233. }
  1234. THREE.glTFLoader.prototype.callLoadedCallback = function() {
  1235. var result = {
  1236. scene : this.rootObj,
  1237. cameras : this.loader.cameras,
  1238. animations : this.loader.animations,
  1239. };
  1240. this.callback(result);
  1241. }
  1242. THREE.glTFLoader.prototype.checkComplete = function() {
  1243. if (this.meshesLoaded == this.meshesRequested
  1244. && this.shadersLoaded == this.shadersRequested
  1245. && this.animationsLoaded == this.animationsRequested)
  1246. {
  1247. for (var i = 0; i < this.pendingMeshes.length; i++) {
  1248. var pending = this.pendingMeshes[i];
  1249. pending.mesh.attachToNode(pending.node);
  1250. }
  1251. for (var i = 0; i < this.animationsLoaded; i++) {
  1252. var animation = this.animations[i];
  1253. this.loader.buildAnimation(animation);
  1254. }
  1255. this.loader.createAnimations();
  1256. this.loader.createMeshAnimations(this.rootObj);
  1257. this.callLoadedCallback();
  1258. }
  1259. }