glTFLoader.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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.emission === undefined))
  635. {
  636. params.emissive = RgbArraytoHex(values.emission);
  637. }
  638. if (!(values.specular === undefined))
  639. {
  640. params.specular = RgbArraytoHex(values.specular);
  641. }
  642. return materialType;
  643. }
  644. },
  645. handleMaterial: {
  646. value: function(entryID, description, userInfo) {
  647. //this should be rewritten using the meta datas that actually create the shader.
  648. //here we will infer what needs to be pass to Three.js by looking inside the technique parameters.
  649. var technique = this.resources.getEntry(description.instanceTechnique.technique);
  650. var materialParams = {};
  651. var values = description.instanceTechnique.values;
  652. var materialType = this.threeJSMaterialType(entryID, technique, values, materialParams);
  653. var material = new materialType(materialParams);
  654. this.resources.setEntry(entryID, material, description);
  655. return true;
  656. }
  657. },
  658. handleMesh: {
  659. value: function(entryID, description, userInfo) {
  660. var mesh = new Mesh();
  661. this.resources.setEntry(entryID, mesh, description);
  662. var primitivesDescription = description.primitives;
  663. if (!primitivesDescription) {
  664. //FIXME: not implemented in delegate
  665. console.log("MISSING_PRIMITIVES for mesh:" + entryID);
  666. return false;
  667. }
  668. for (var i = 0 ; i < primitivesDescription.length ; i ++) {
  669. var primitiveDescription = primitivesDescription[i];
  670. if (primitiveDescription.primitive === WebGLRenderingContext.TRIANGLES) {
  671. var geometry = new ClassicGeometry();
  672. var materialEntry = this.resources.getEntry(primitiveDescription.material);
  673. mesh.addPrimitive(geometry, materialEntry.object);
  674. var indices = this.resources.getEntry(primitiveDescription.indices);
  675. var bufferEntry = this.resources.getEntry(indices.description.bufferView);
  676. var indicesObject = {
  677. bufferView : bufferEntry,
  678. byteOffset : indices.description.byteOffset,
  679. count : indices.description.count,
  680. id : indices.entryID,
  681. type : indices.description.type
  682. };
  683. var indicesContext = new IndicesContext(indicesObject, geometry);
  684. var alreadyProcessedIndices = THREE.GLTFLoaderUtils.getBuffer(indicesObject, indicesDelegate, indicesContext);
  685. /*if(alreadyProcessedIndices) {
  686. indicesDelegate.resourceAvailable(alreadyProcessedIndices, indicesContext);
  687. }*/
  688. // Load Vertex Attributes
  689. var allAttributes = Object.keys(primitiveDescription.attributes);
  690. allAttributes.forEach( function(semantic) {
  691. geometry.totalAttributes ++;
  692. var attribute;
  693. var attributeID = primitiveDescription.attributes[semantic];
  694. var attributeEntry = this.resources.getEntry(attributeID);
  695. if (!attributeEntry) {
  696. //let's just use an anonymous object for the attribute
  697. attribute = description.attributes[attributeID];
  698. attribute.id = attributeID;
  699. this.resources.setEntry(attributeID, attribute, attribute);
  700. var bufferEntry = this.resources.getEntry(attribute.bufferView);
  701. attributeEntry = this.resources.getEntry(attributeID);
  702. } else {
  703. attribute = attributeEntry.object;
  704. attribute.id = attributeID;
  705. var bufferEntry = this.resources.getEntry(attribute.bufferView);
  706. }
  707. var attributeObject = {
  708. bufferView : bufferEntry,
  709. byteOffset : attribute.byteOffset,
  710. byteStride : attribute.byteStride,
  711. count : attribute.count,
  712. max : attribute.max,
  713. min : attribute.min,
  714. type : attribute.type,
  715. id : attributeID
  716. };
  717. var attribContext = new VertexAttributeContext(attributeObject, semantic, geometry);
  718. var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(attributeObject, vertexAttributeDelegate, attribContext);
  719. /*if(alreadyProcessedAttribute) {
  720. vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
  721. }*/
  722. }, this);
  723. }
  724. }
  725. return true;
  726. }
  727. },
  728. handleCamera: {
  729. value: function(entryID, description, userInfo) {
  730. var camera;
  731. if (description.type == "perspective")
  732. {
  733. var znear = description.perspective.znear;
  734. var zfar = description.perspective.zfar;
  735. var yfov = description.perspective.yfov;
  736. var xfov = description.perspective.xfov;
  737. var aspect_ratio = description.perspective.aspect_ratio;
  738. if (!aspect_ratio)
  739. aspect_ratio = 1;
  740. if (yfov === undefined)
  741. {
  742. if (xfov)
  743. {
  744. // According to COLLADA spec...
  745. // aspect_ratio = xfov / yfov
  746. yfov = xfov / aspect_ratio;
  747. }
  748. }
  749. if (yfov)
  750. {
  751. camera = new THREE.PerspectiveCamera(yfov, aspect_ratio, znear, zfar);
  752. }
  753. }
  754. else
  755. {
  756. camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, znear, zfar );
  757. }
  758. if (camera)
  759. {
  760. this.resources.setEntry(entryID, camera, description);
  761. }
  762. return true;
  763. }
  764. },
  765. handleLight: {
  766. value: function(entryID, description, userInfo) {
  767. var light = null;
  768. var type = description.type;
  769. if (type && description[type])
  770. {
  771. var lparams = description[type];
  772. var color = RgbArraytoHex(lparams.color);
  773. switch (type) {
  774. case "directional" :
  775. light = new THREE.DirectionalLight(color);
  776. light.position.set(0, 0, 1);
  777. break;
  778. case "point" :
  779. light = new THREE.PointLight(color);
  780. break;
  781. case "spot " :
  782. light = new THREE.SpotLight(color);
  783. light.position.set(0, 0, 1);
  784. break;
  785. case "ambient" :
  786. light = new THREE.AmbientLight(color);
  787. break;
  788. }
  789. }
  790. if (light)
  791. {
  792. this.resources.setEntry(entryID, light, description);
  793. }
  794. return true;
  795. }
  796. },
  797. addPendingMesh: {
  798. value: function(mesh, threeNode) {
  799. theLoader.pendingMeshes.push({
  800. mesh: mesh,
  801. node: threeNode
  802. });
  803. }
  804. },
  805. handleNode: {
  806. value: function(entryID, description, userInfo) {
  807. var threeNode = null;
  808. if (description.jointId) {
  809. threeNode = new THREE.Bone();
  810. threeNode.jointId = description.jointId;
  811. this.joints[description.jointId] = entryID;
  812. }
  813. else {
  814. threeNode = new THREE.Object3D();
  815. }
  816. threeNode.name = description.name;
  817. this.resources.setEntry(entryID, threeNode, description);
  818. var m = description.matrix;
  819. if (m) {
  820. threeNode.applyMatrix(new THREE.Matrix4().fromArray( m ));
  821. threeNode.matrixAutoUpdate = false;
  822. threeNode.matrixWorldNeedsUpdate = true;
  823. }
  824. else {
  825. var t = description.translation;
  826. var r = description.rotation;
  827. var s = description.scale;
  828. var position = t ? new THREE.Vector3(t[0], t[1], t[2]) :
  829. new THREE.Vector3;
  830. if (r) {
  831. convertAxisAngleToQuaternion(r, 1);
  832. }
  833. var rotation = r ? new THREE.Quaternion(r[0], r[1], r[2], r[3]) :
  834. new THREE.Quaternion;
  835. var scale = s ? new THREE.Vector3(s[0], s[1], s[2]) :
  836. new THREE.Vector3;
  837. var matrix = new THREE.Matrix4;
  838. matrix.compose(position, rotation, scale);
  839. threeNode.matrixAutoUpdate = false;
  840. threeNode.matrixWorldNeedsUpdate = true;
  841. threeNode.applyMatrix(matrix);
  842. }
  843. var self = this;
  844. // Iterate through all node meshes and attach the appropriate objects
  845. //FIXME: decision needs to be made between these 2 ways, probably meshes will be discarded.
  846. var meshEntry;
  847. if (description.mesh) {
  848. meshEntry = this.resources.getEntry(description.mesh);
  849. theLoader.meshesRequested ++;
  850. meshEntry.object.onComplete(function(mesh) {
  851. self.addPendingMesh(mesh, threeNode);
  852. theLoader.meshesLoaded ++;
  853. theLoader.checkComplete();
  854. });
  855. }
  856. if (description.meshes) {
  857. description.meshes.forEach( function(meshID) {
  858. meshEntry = this.resources.getEntry(meshID);
  859. theLoader.meshesRequested ++;
  860. meshEntry.object.onComplete(function(mesh) {
  861. self.addPendingMesh(mesh, threeNode);
  862. theLoader.meshesLoaded ++;
  863. theLoader.checkComplete();
  864. });
  865. }, this);
  866. }
  867. if (description.instanceSkin) {
  868. var skinEntry = this.resources.getEntry(description.instanceSkin.skin);
  869. if (skinEntry) {
  870. var skin = skinEntry.object;
  871. description.instanceSkin.skin = skin;
  872. threeNode.instanceSkin = description.instanceSkin;
  873. var sources = description.instanceSkin.sources;
  874. skin.meshes = [];
  875. sources.forEach( function(meshID) {
  876. meshEntry = this.resources.getEntry(meshID);
  877. theLoader.meshesRequested ++;
  878. meshEntry.object.onComplete(function(mesh) {
  879. skin.meshes.push(mesh);
  880. theLoader.meshesLoaded ++;
  881. theLoader.checkComplete();
  882. });
  883. }, this);
  884. }
  885. }
  886. if (description.camera) {
  887. var cameraEntry = this.resources.getEntry(description.camera);
  888. if (cameraEntry) {
  889. threeNode.add(cameraEntry.object);
  890. this.cameras.push(cameraEntry.object);
  891. }
  892. }
  893. if (description.light) {
  894. var lightEntry = this.resources.getEntry(description.light);
  895. if (lightEntry) {
  896. threeNode.add(lightEntry.object);
  897. this.lights.push(lightEntry.object);
  898. }
  899. }
  900. return true;
  901. }
  902. },
  903. buildNodeHirerachy: {
  904. value: function(nodeEntryId, parentThreeNode) {
  905. var nodeEntry = this.resources.getEntry(nodeEntryId);
  906. var threeNode = nodeEntry.object;
  907. parentThreeNode.add(threeNode);
  908. var children = nodeEntry.description.children;
  909. if (children) {
  910. children.forEach( function(childID) {
  911. this.buildNodeHirerachy(childID, threeNode);
  912. }, this);
  913. }
  914. return threeNode;
  915. }
  916. },
  917. buildSkin: {
  918. value: function(node) {
  919. var skin = node.instanceSkin.skin;
  920. if (skin) {
  921. node.instanceSkin.skeletons.forEach(function(skeleton) {
  922. var nodeEntry = this.resources.getEntry(skeleton);
  923. if (nodeEntry) {
  924. var rootSkeleton = nodeEntry.object;
  925. var dobones = true;
  926. var i, len = skin.meshes.length;
  927. for (i = 0; i < len; i ++) {
  928. var mesh = skin.meshes[i];
  929. var threeMesh = null;
  930. mesh.primitives.forEach(function(primitive) {
  931. var material = primitive.material;
  932. if (!(material instanceof THREE.Material)) {
  933. material = this.createShaderMaterial(material);
  934. }
  935. threeMesh = new THREE.SkinnedMesh(primitive.geometry.geometry, material, false);
  936. threeMesh.add(rootSkeleton);
  937. var geometry = primitive.geometry.geometry;
  938. var j;
  939. if (geometry.vertices) {
  940. for ( j = 0; j < geometry.vertices.length; j ++ ) {
  941. geometry.vertices[j].applyMatrix4( skin.bindShapeMatrix );
  942. }
  943. }
  944. else if (geometry.attributes.position) {
  945. var a = geometry.attributes.position.array;
  946. var v = new THREE.Vector3;
  947. for ( j = 0; j < a.length / 3; j ++ ) {
  948. v.set(a[j * 3], a[j * 3 + 1], a[j * 3 + 2]);
  949. v.applyMatrix4( skin.bindShapeMatrix );
  950. a[j * 3] = v.x;
  951. a[j * 3 + 1] = v.y;
  952. a[j * 3 + 2] = v.z;
  953. }
  954. }
  955. if (threeMesh && dobones) {
  956. material.skinning = true;
  957. threeMesh.boneInverses = [];
  958. var jointsIds = skin.jointsIds;
  959. var bones = [];
  960. var boneInverses = [];
  961. var i, len = jointsIds.length;
  962. for (i = 0; i < len; i ++) {
  963. var jointId = jointsIds[i];
  964. var nodeForJoint = this.joints[jointId];
  965. var joint = this.resources.getEntry(nodeForJoint).object;
  966. if (joint) {
  967. joint.skin = threeMesh;
  968. bones.push(joint);
  969. var m = skin.inverseBindMatrices;
  970. var mat = new THREE.Matrix4().set(
  971. m[i * 16 + 0], m[i * 16 + 4], m[i * 16 + 8], m[i * 16 + 12],
  972. m[i * 16 + 1], m[i * 16 + 5], m[i * 16 + 9], m[i * 16 + 13],
  973. m[i * 16 + 2], m[i * 16 + 6], m[i * 16 + 10], m[i * 16 + 14],
  974. m[i * 16 + 3], m[i * 16 + 7], m[i * 16 + 11], m[i * 16 + 15]
  975. );
  976. boneInverses.push(mat);
  977. } else {
  978. console.log("WARNING: jointId:" + jointId + " cannot be found in skeleton:" + skeleton);
  979. }
  980. }
  981. threeMesh.bind(new THREE.Skeleton(bones, boneInverses, false));
  982. }
  983. if (threeMesh) {
  984. threeMesh.castShadow = true;
  985. node.add(threeMesh);
  986. }
  987. }, this);
  988. }
  989. }
  990. }, this);
  991. }
  992. }
  993. },
  994. buildSkins: {
  995. value: function(node) {
  996. if (node.instanceSkin)
  997. this.buildSkin(node);
  998. var children = node.children;
  999. if (children) {
  1000. children.forEach( function(child) {
  1001. this.buildSkins(child);
  1002. }, this);
  1003. }
  1004. }
  1005. },
  1006. createMeshAnimations : {
  1007. value : function(root) {
  1008. this.buildSkins(root);
  1009. }
  1010. },
  1011. handleScene: {
  1012. value: function(entryID, description, userInfo) {
  1013. if (!description.nodes) {
  1014. console.log("ERROR: invalid file required nodes property is missing from scene");
  1015. return false;
  1016. }
  1017. description.nodes.forEach( function(nodeUID) {
  1018. this.buildNodeHirerachy(nodeUID, userInfo.rootObj);
  1019. }, this);
  1020. if (this.delegate) {
  1021. this.delegate.loadCompleted(userInfo.callback, userInfo.rootObj);
  1022. }
  1023. return true;
  1024. }
  1025. },
  1026. handleImage: {
  1027. value: function(entryID, description, userInfo) {
  1028. this.resources.setEntry(entryID, null, description);
  1029. return true;
  1030. }
  1031. },
  1032. addNodeAnimationChannel : {
  1033. value : function(name, channel, interp) {
  1034. if (!this.nodeAnimationChannels)
  1035. this.nodeAnimationChannels = {};
  1036. if (!this.nodeAnimationChannels[name]) {
  1037. this.nodeAnimationChannels[name] = [];
  1038. }
  1039. this.nodeAnimationChannels[name].push(interp);
  1040. },
  1041. },
  1042. createAnimations : {
  1043. value : function() {
  1044. for (var name in this.nodeAnimationChannels) {
  1045. var nodeAnimationChannels = this.nodeAnimationChannels[name];
  1046. var i, len = nodeAnimationChannels.length;
  1047. //console.log(" animation channels for node " + name);
  1048. //for (i = 0; i < len; i++) {
  1049. // console.log(nodeAnimationChannels[i]);
  1050. //}
  1051. var anim = new THREE.glTFAnimation(nodeAnimationChannels);
  1052. anim.name = "animation_" + name;
  1053. this.animations.push(anim);
  1054. }
  1055. }
  1056. },
  1057. buildAnimation: {
  1058. value : function(animation) {
  1059. var interps = [];
  1060. var i, len = animation.channels.length;
  1061. for (i = 0; i < len; i ++) {
  1062. var channel = animation.channels[i];
  1063. var sampler = animation.samplers[channel.sampler];
  1064. if (sampler) {
  1065. var input = animation.parameters[sampler.input];
  1066. if (input && input.data) {
  1067. var output = animation.parameters[sampler.output];
  1068. if (output && output.data) {
  1069. var target = channel.target;
  1070. var node = this.resources.getEntry(target.id);
  1071. if (node) {
  1072. var path = target.path;
  1073. if (path == "rotation")
  1074. {
  1075. convertAxisAngleToQuaternion(output.data, output.count);
  1076. }
  1077. var interp = {
  1078. keys : input.data,
  1079. values : output.data,
  1080. count : input.count,
  1081. target : node.object,
  1082. path : path,
  1083. type : sampler.interpolation
  1084. };
  1085. this.addNodeAnimationChannel(target.id, channel, interp);
  1086. interps.push(interp);
  1087. }
  1088. }
  1089. }
  1090. }
  1091. }
  1092. }
  1093. },
  1094. handleAnimation: {
  1095. value: function(entryID, description, userInfo) {
  1096. var self = this;
  1097. theLoader.animationsRequested ++;
  1098. var animation = new Animation();
  1099. animation.name = entryID;
  1100. animation.onload = function() {
  1101. // self.buildAnimation(animation);
  1102. theLoader.animationsLoaded ++;
  1103. theLoader.animations.push(animation);
  1104. theLoader.checkComplete();
  1105. };
  1106. animation.channels = description.channels;
  1107. animation.samplers = description.samplers;
  1108. this.resources.setEntry(entryID, animation, description);
  1109. var parameters = description.parameters;
  1110. if (!parameters) {
  1111. //FIXME: not implemented in delegate
  1112. console.log("MISSING_PARAMETERS for animation:" + entryID);
  1113. return false;
  1114. }
  1115. // Load parameter buffers
  1116. var params = Object.keys(parameters);
  1117. params.forEach( function(param) {
  1118. animation.totalParameters ++;
  1119. var parameter = parameters[param];
  1120. var accessor = this.resources.getEntry(parameter);
  1121. if (!accessor)
  1122. debugger;
  1123. accessor = accessor.object;
  1124. var bufferView = this.resources.getEntry(accessor.bufferView);
  1125. var paramObject = {
  1126. bufferView : bufferView,
  1127. byteOffset : accessor.byteOffset,
  1128. count : accessor.count,
  1129. type : accessor.type,
  1130. id : accessor.bufferView,
  1131. name : param
  1132. };
  1133. var paramContext = new AnimationParameterContext(paramObject, animation);
  1134. var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, animationParameterDelegate, paramContext);
  1135. /*if(alreadyProcessedAttribute) {
  1136. vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
  1137. }*/
  1138. }, this);
  1139. return true;
  1140. }
  1141. },
  1142. handleAccessor: {
  1143. value: function(entryID, description, userInfo) {
  1144. // Save attribute entry
  1145. this.resources.setEntry(entryID, description, description);
  1146. return true;
  1147. }
  1148. },
  1149. handleSkin: {
  1150. value: function(entryID, description, userInfo) {
  1151. // Save skin entry
  1152. var skin = {
  1153. };
  1154. var m = description.bindShapeMatrix;
  1155. skin.bindShapeMatrix = new THREE.Matrix4().fromArray( m );
  1156. skin.jointsIds = description.joints;
  1157. var inverseBindMatricesDescription = description.inverseBindMatrices;
  1158. skin.inverseBindMatricesDescription = inverseBindMatricesDescription;
  1159. skin.inverseBindMatricesDescription.id = entryID + "_inverseBindMatrices";
  1160. var bufferEntry = this.resources.getEntry(inverseBindMatricesDescription.bufferView);
  1161. var paramObject = {
  1162. bufferView : bufferEntry,
  1163. byteOffset : inverseBindMatricesDescription.byteOffset,
  1164. count : inverseBindMatricesDescription.count,
  1165. type : inverseBindMatricesDescription.type,
  1166. id : inverseBindMatricesDescription.bufferView,
  1167. name : skin.inverseBindMatricesDescription.id
  1168. };
  1169. var context = new InverseBindMatricesContext(paramObject, skin);
  1170. var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, inverseBindMatricesDelegate, context);
  1171. var bufferView = this.resources.getEntry(skin.inverseBindMatricesDescription.bufferView);
  1172. skin.inverseBindMatricesDescription.bufferView =
  1173. bufferView.object;
  1174. this.resources.setEntry(entryID, skin, description);
  1175. return true;
  1176. }
  1177. },
  1178. handleSampler: {
  1179. value: function(entryID, description, userInfo) {
  1180. // Save attribute entry
  1181. this.resources.setEntry(entryID, description, description);
  1182. return true;
  1183. }
  1184. },
  1185. handleTexture: {
  1186. value: function(entryID, description, userInfo) {
  1187. // Save attribute entry
  1188. this.resources.setEntry(entryID, null, description);
  1189. return true;
  1190. }
  1191. },
  1192. handleError: {
  1193. value: function(msg) {
  1194. throw new Error(msg);
  1195. return true;
  1196. }
  1197. },
  1198. _delegate: {
  1199. value: new LoadDelegate,
  1200. writable: true
  1201. },
  1202. delegate: {
  1203. enumerable: true,
  1204. get: function() {
  1205. return this._delegate;
  1206. },
  1207. set: function(value) {
  1208. this._delegate = value;
  1209. }
  1210. }
  1211. });
  1212. // Loader
  1213. var Context = function(rootObj, callback) {
  1214. this.rootObj = rootObj;
  1215. this.callback = callback;
  1216. };
  1217. var rootObj = new THREE.Object3D();
  1218. var self = this;
  1219. var loader = Object.create(ThreeGLTFLoader);
  1220. loader.initWithPath(url);
  1221. loader.load(new Context(rootObj,
  1222. function(obj) {
  1223. }),
  1224. null);
  1225. this.loader = loader;
  1226. this.callback = callback;
  1227. this.rootObj = rootObj;
  1228. return rootObj;
  1229. }
  1230. THREE.glTFLoader.prototype.callLoadedCallback = function() {
  1231. var result = {
  1232. scene : this.rootObj,
  1233. cameras : this.loader.cameras,
  1234. animations : this.loader.animations,
  1235. };
  1236. this.callback(result);
  1237. }
  1238. THREE.glTFLoader.prototype.checkComplete = function() {
  1239. if (this.meshesLoaded == this.meshesRequested
  1240. && this.shadersLoaded == this.shadersRequested
  1241. && this.animationsLoaded == this.animationsRequested)
  1242. {
  1243. for (var i = 0; i < this.pendingMeshes.length; i ++) {
  1244. var pending = this.pendingMeshes[i];
  1245. pending.mesh.attachToNode(pending.node);
  1246. }
  1247. for (var i = 0; i < this.animationsLoaded; i ++) {
  1248. var animation = this.animations[i];
  1249. this.loader.buildAnimation(animation);
  1250. }
  1251. this.loader.createAnimations();
  1252. this.loader.createMeshAnimations(this.rootObj);
  1253. this.callLoadedCallback();
  1254. }
  1255. }