GLTFLoader.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757
  1. /**
  2. * @author Rich Tibbett / https://github.com/richtr
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author Tony Parisi / http://www.tonyparisi.com/
  5. */
  6. (function() {
  7. THREE.GLTFLoader = function( manager ) {
  8. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9. this.parser = GLTFParser;
  10. };
  11. THREE.GLTFLoader.prototype = {
  12. constructor: THREE.GLTFLoader,
  13. load: function( url, onLoad, onProgress, onError ) {
  14. var scope = this;
  15. var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
  16. var loader = new THREE.FileLoader( scope.manager );
  17. loader.load( url, function( text ) {
  18. scope.parse( JSON.parse( text ), onLoad, path );
  19. }, onProgress, onError );
  20. },
  21. setCrossOrigin: function( value ) {
  22. this.crossOrigin = value;
  23. },
  24. setPath: function( value ) {
  25. this.path = value;
  26. },
  27. parse: function( json, callback, path ) {
  28. console.time( 'GLTFLoader' );
  29. var glTFParser = new this.parser( json, {
  30. path: path || this.path,
  31. crossOrigin: !!this.crossOrigin
  32. });
  33. glTFParser.parse( function( scene, cameras, animations ) {
  34. console.timeEnd( 'GLTFLoader' );
  35. var glTF = {
  36. "scene": scene,
  37. "cameras": cameras,
  38. "animations": animations
  39. };
  40. callback( glTF );
  41. });
  42. // Developers should use `callback` argument for async notification on
  43. // completion to prevent side effects.
  44. // Function return is kept only for backward-compatability purposes.
  45. return {
  46. get scene() {
  47. console.warn( "Synchronous glTF object access is deprecated." +
  48. " Use the asynchronous 'callback' argument instead." );
  49. return scene;
  50. },
  51. set scene( value ) {
  52. console.warn( "Synchronous glTF object access is deprecated." +
  53. " Use the asynchronous 'callback' argument instead." );
  54. scene = value;
  55. }
  56. };
  57. }
  58. };
  59. /* GLTFREGISTRY */
  60. var GLTFRegistry = function() {
  61. var objects = {};
  62. return {
  63. get : function( key ) {
  64. return objects[ key ];
  65. },
  66. add : function( key, object ) {
  67. objects[ key ] = object;
  68. },
  69. remove: function( key ) {
  70. delete objects[ key ];
  71. },
  72. removeAll: function() {
  73. objects = {};
  74. },
  75. update : function( scene, camera ) {
  76. _each( objects, function( object ) {
  77. if ( object.update ) {
  78. object.update( scene, camera );
  79. }
  80. });
  81. }
  82. };
  83. };
  84. /* GLTFSHADERS */
  85. THREE.GLTFLoader.Shaders = new GLTFRegistry();
  86. /* GLTFSHADER */
  87. var GLTFShader = function( targetNode, allNodes ) {
  88. this.boundUniforms = {};
  89. // bind each uniform to its source node
  90. _each(targetNode.material.uniforms, function(uniform, uniformId) {
  91. if (uniform.semantic) {
  92. var sourceNodeRef = uniform.node;
  93. var sourceNode = targetNode;
  94. if ( sourceNodeRef ) {
  95. sourceNode = allNodes[ sourceNodeRef ];
  96. }
  97. this.boundUniforms[ uniformId ] = {
  98. semantic: uniform.semantic,
  99. sourceNode: sourceNode,
  100. targetNode: targetNode,
  101. uniform: uniform
  102. };
  103. }
  104. }.bind( this ));
  105. this._m4 = new THREE.Matrix4();
  106. };
  107. // Update - update all the uniform values
  108. GLTFShader.prototype.update = function( scene, camera ) {
  109. // update scene graph
  110. scene.updateMatrixWorld();
  111. // update camera matrices and frustum
  112. camera.updateMatrixWorld();
  113. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  114. _each( this.boundUniforms, function( boundUniform ) {
  115. switch (boundUniform.semantic) {
  116. case "MODELVIEW":
  117. var m4 = boundUniform.uniform.value;
  118. m4.multiplyMatrices(camera.matrixWorldInverse,
  119. boundUniform.sourceNode.matrixWorld);
  120. break;
  121. case "MODELVIEWINVERSETRANSPOSE":
  122. var m3 = boundUniform.uniform.value;
  123. this._m4.multiplyMatrices(camera.matrixWorldInverse,
  124. boundUniform.sourceNode.matrixWorld);
  125. m3.getNormalMatrix(this._m4);
  126. break;
  127. case "PROJECTION":
  128. var m4 = boundUniform.uniform.value;
  129. m4.copy(camera.projectionMatrix);
  130. break;
  131. case "JOINTMATRIX":
  132. var m4v = boundUniform.uniform.value;
  133. for (var mi = 0; mi < m4v.length; mi++) {
  134. // So it goes like this:
  135. // SkinnedMesh world matrix is already baked into MODELVIEW;
  136. // ransform joints to local space,
  137. // then transform using joint's inverse
  138. m4v[mi]
  139. .getInverse(boundUniform.sourceNode.matrixWorld)
  140. .multiply(boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld)
  141. .multiply(boundUniform.targetNode.skeleton.boneInverses[mi]);
  142. }
  143. break;
  144. default :
  145. console.warn("Unhandled shader semantic: " + boundUniform.semantic);
  146. break;
  147. }
  148. }.bind( this ));
  149. };
  150. /* GLTFANIMATION */
  151. THREE.GLTFLoader.Animations = new GLTFRegistry();
  152. // Construction/initialization
  153. var GLTFAnimation = function( interps ) {
  154. this.running = false;
  155. this.loop = false;
  156. this.duration = 0;
  157. this.startTime = 0;
  158. this.interps = [];
  159. this.uuid = THREE.Math.generateUUID();
  160. if ( interps ) {
  161. this.createInterpolators( interps );
  162. }
  163. };
  164. GLTFAnimation.prototype.createInterpolators = function( interps ) {
  165. for ( var i = 0, len = interps.length; i < len; i ++ ) {
  166. var interp = new GLTFInterpolator( interps[ i ] );
  167. this.interps.push( interp );
  168. this.duration = Math.max( this.duration, interp.duration );
  169. }
  170. };
  171. // Start/stop
  172. GLTFAnimation.prototype.play = function() {
  173. if ( this.running )
  174. return;
  175. this.startTime = Date.now();
  176. this.running = true;
  177. THREE.GLTFLoader.Animations.add( this.uuid, this );
  178. };
  179. GLTFAnimation.prototype.stop = function() {
  180. this.running = false;
  181. THREE.GLTFLoader.Animations.remove( this.uuid );
  182. };
  183. // Update - drive key frame evaluation
  184. GLTFAnimation.prototype.update = function() {
  185. if ( !this.running )
  186. return;
  187. var now = Date.now();
  188. var deltat = ( now - this.startTime ) / 1000;
  189. var t = deltat % this.duration;
  190. var nCycles = Math.floor( deltat / this.duration );
  191. if ( nCycles >= 1 && ! this.loop ) {
  192. this.running = false;
  193. _each( this.interps, function( _, i ) {
  194. this.interps[ i ].interp( this.duration );
  195. }.bind( this ));
  196. this.stop();
  197. } else {
  198. _each( this.interps, function( _, i ) {
  199. this.interps[ i ].interp( t );
  200. }.bind( this ));
  201. }
  202. };
  203. /* GLTFINTERPOLATOR */
  204. var GLTFInterpolator = function( param ) {
  205. this.keys = param.keys;
  206. this.values = param.values;
  207. this.count = param.count;
  208. this.type = param.type;
  209. this.path = param.path;
  210. this.isRot = false;
  211. var node = param.target;
  212. node.updateMatrix();
  213. node.matrixAutoUpdate = true;
  214. this.targetNode = node;
  215. switch ( param.path ) {
  216. case "translation" :
  217. this.target = node.position;
  218. this.originalValue = node.position.clone();
  219. break;
  220. case "rotation" :
  221. this.target = node.quaternion;
  222. this.originalValue = node.quaternion.clone();
  223. this.isRot = true;
  224. break;
  225. case "scale" :
  226. this.target = node.scale;
  227. this.originalValue = node.scale.clone();
  228. break;
  229. }
  230. this.duration = this.keys[ this.count - 1 ];
  231. this.vec1 = new THREE.Vector3();
  232. this.vec2 = new THREE.Vector3();
  233. this.vec3 = new THREE.Vector3();
  234. this.quat1 = new THREE.Quaternion();
  235. this.quat2 = new THREE.Quaternion();
  236. this.quat3 = new THREE.Quaternion();
  237. };
  238. //Interpolation and tweening methods
  239. GLTFInterpolator.prototype.interp = function( t ) {
  240. if ( t == this.keys[ 0 ] ) {
  241. if ( this.isRot ) {
  242. this.quat3.fromArray( this.values );
  243. } else {
  244. this.vec3.fromArray( this.values );
  245. }
  246. } else if ( t < this.keys[ 0 ] ) {
  247. if ( this.isRot ) {
  248. this.quat1.copy( this.originalValue );
  249. this.quat2.fromArray( this.values );
  250. THREE.Quaternion.slerp( this.quat1, this.quat2, this.quat3, t / this.keys[ 0 ] );
  251. } else {
  252. this.vec3.copy( this.originalValue );
  253. this.vec2.fromArray( this.values );
  254. this.vec3.lerp( this.vec2, t / this.keys[ 0 ] );
  255. }
  256. } else if ( t >= this.keys[ this.count - 1 ] ) {
  257. if ( this.isRot ) {
  258. this.quat3.fromArray( this.values, ( this.count - 1 ) * 4 );
  259. } else {
  260. this.vec3.fromArray( this.values, ( this.count - 1 ) * 3 );
  261. }
  262. } else {
  263. for ( var i = 0; i < this.count - 1; i ++ ) {
  264. var key1 = this.keys[ i ];
  265. var key2 = this.keys[ i + 1 ];
  266. if ( t >= key1 && t <= key2 ) {
  267. if ( this.isRot ) {
  268. this.quat1.fromArray( this.values, i * 4 );
  269. this.quat2.fromArray( this.values, ( i + 1 ) * 4 );
  270. THREE.Quaternion.slerp( this.quat1, this.quat2, this.quat3, ( t - key1 ) / ( key2 - key1 ) );
  271. } else {
  272. this.vec3.fromArray( this.values, i * 3 );
  273. this.vec2.fromArray( this.values, ( i + 1 ) * 3 );
  274. this.vec3.lerp( this.vec2, ( t - key1 ) / ( key2 - key1 ) );
  275. }
  276. }
  277. }
  278. }
  279. if ( this.target ) {
  280. if ( this.isRot ) {
  281. this.target.copy( this.quat3 );
  282. } else {
  283. this.target.copy( this.vec3 );
  284. }
  285. }
  286. };
  287. /*********************************/
  288. /********** INTERNALS ************/
  289. /*********************************/
  290. /* CONSTANTS */
  291. var WEBGL_CONSTANTS = {
  292. FLOAT: 5126,
  293. //FLOAT_MAT2: 35674,
  294. FLOAT_MAT3: 35675,
  295. FLOAT_MAT4: 35676,
  296. FLOAT_VEC2: 35664,
  297. FLOAT_VEC3: 35665,
  298. FLOAT_VEC4: 35666,
  299. LINEAR: 9729,
  300. REPEAT: 10497,
  301. SAMPLER_2D: 35678,
  302. TRIANGLES: 4,
  303. UNSIGNED_BYTE: 5121,
  304. UNSIGNED_SHORT: 5123,
  305. VERTEX_SHADER: 35633,
  306. FRAGMENT_SHADER: 35632
  307. };
  308. var WEBGL_TYPE = {
  309. 5126: Number,
  310. //35674: THREE.Matrix2,
  311. 35675: THREE.Matrix3,
  312. 35676: THREE.Matrix4,
  313. 35664: THREE.Vector2,
  314. 35665: THREE.Vector3,
  315. 35666: THREE.Vector4,
  316. 35678: THREE.Texture
  317. };
  318. var WEBGL_COMPONENT_TYPES = {
  319. 5120: Int8Array,
  320. 5121: Uint8Array,
  321. 5122: Int16Array,
  322. 5123: Uint16Array,
  323. 5125: Uint32Array,
  324. 5126: Float32Array
  325. };
  326. var WEBGL_FILTERS = {
  327. 9728: THREE.NearestFilter,
  328. 9729: THREE.LinearFilter,
  329. 9984: THREE.NearestMipMapNearestFilter,
  330. 9985: THREE.LinearMipMapNearestFilter,
  331. 9986: THREE.NearestMipMapLinearFilter,
  332. 9987: THREE.LinearMipMapLinearFilter
  333. };
  334. var WEBGL_WRAPPINGS = {
  335. 33071: THREE.ClampToEdgeWrapping,
  336. 33648: THREE.MirroredRepeatWrapping,
  337. 10497: THREE.RepeatWrapping
  338. };
  339. var WEBGL_TYPE_SIZES = {
  340. 'SCALAR': 1,
  341. 'VEC2': 2,
  342. 'VEC3': 3,
  343. 'VEC4': 4,
  344. 'MAT2': 4,
  345. 'MAT3': 9,
  346. 'MAT4': 16
  347. };
  348. /* UTILITY FUNCTIONS */
  349. var _each = function( object, callback, thisObj ) {
  350. if ( !object ) {
  351. return Promise.resolve();
  352. }
  353. var results;
  354. var fns = [];
  355. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  356. results = [];
  357. var length = object.length;
  358. for ( var idx = 0; idx < length; idx ++ ) {
  359. var value = callback.call( thisObj || this, object[ idx ], idx );
  360. if ( value ) {
  361. fns.push( value );
  362. if ( value instanceof Promise ) {
  363. value.then( function( key, value ) {
  364. results[ idx ] = value;
  365. }.bind( this, key ));
  366. } else {
  367. results[ idx ] = value;
  368. }
  369. }
  370. }
  371. } else {
  372. results = {};
  373. for ( var key in object ) {
  374. if ( object.hasOwnProperty( key ) ) {
  375. var value = callback.call( thisObj || this, object[ key ], key );
  376. if ( value ) {
  377. fns.push( value );
  378. if ( value instanceof Promise ) {
  379. value.then( function( key, value ) {
  380. results[ key ] = value;
  381. }.bind( this, key ));
  382. } else {
  383. results[ key ] = value;
  384. }
  385. }
  386. }
  387. }
  388. }
  389. return Promise.all( fns ).then( function() {
  390. return results;
  391. });
  392. };
  393. var resolveURL = function( url, path ) {
  394. // Invalid URL
  395. if ( typeof url !== 'string' || url === '' )
  396. return '';
  397. // Absolute URL
  398. if ( /^https?:\/\//i.test( url ) ) {
  399. return url;
  400. }
  401. // Data URI
  402. if ( /^data:.*,.*$/i.test( url ) ) {
  403. return url;
  404. }
  405. // Relative URL
  406. return (path || '') + url;
  407. };
  408. // Three.js seems too dependent on attribute names so globally
  409. // replace those in the shader code
  410. var replaceTHREEShaderAttributes = function( shaderText, technique ) {
  411. // Expected technique attributes
  412. var attributes = {};
  413. _each( technique.attributes, function( pname, attributeId ) {
  414. var param = technique.parameters[ pname ];
  415. var atype = param.type;
  416. var semantic = param.semantic;
  417. attributes[ attributeId ] = {
  418. type : atype,
  419. semantic : semantic
  420. };
  421. });
  422. // Figure out which attributes to change in technique
  423. var shaderParams = technique.parameters;
  424. var shaderAttributes = technique.attributes;
  425. var params = {};
  426. _each( attributes, function( _, attributeId ) {
  427. var pname = shaderAttributes[ attributeId ];
  428. var shaderParam = shaderParams[ pname ];
  429. var semantic = shaderParam.semantic;
  430. if ( semantic ) {
  431. params[ attributeId ] = shaderParam;
  432. }
  433. });
  434. _each( params, function( param, pname ) {
  435. var semantic = param.semantic;
  436. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  437. switch ( semantic ) {
  438. case "POSITION":
  439. shaderText = shaderText.replace( regEx, 'position' );
  440. break;
  441. case "NORMAL":
  442. shaderText = shaderText.replace( regEx, 'normal' );
  443. break;
  444. case 'TEXCOORD_0':
  445. case 'TEXCOORD0':
  446. case 'TEXCOORD':
  447. shaderText = shaderText.replace( regEx, 'uv' );
  448. break;
  449. case "WEIGHT":
  450. shaderText = shaderText.replace(regEx, 'skinWeight');
  451. break;
  452. case "JOINT":
  453. shaderText = shaderText.replace(regEx, 'skinIndex');
  454. break;
  455. }
  456. });
  457. return shaderText;
  458. };
  459. // Deferred constructor for RawShaderMaterial types
  460. var DeferredShaderMaterial = function( params ) {
  461. this.isDeferredShaderMaterial = true;
  462. this.params = params;
  463. };
  464. DeferredShaderMaterial.prototype.create = function() {
  465. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  466. _each( this.params.uniforms, function( originalUniform, uniformId ) {
  467. if ( originalUniform.value instanceof THREE.Texture ) {
  468. uniforms[ uniformId ].value = originalUniform.value;
  469. uniforms[ uniformId ].value.needsUpdate = true;
  470. }
  471. uniforms[ uniformId ].semantic = originalUniform.semantic;
  472. uniforms[ uniformId ].node = originalUniform.node;
  473. });
  474. this.params.uniforms = uniforms;
  475. return new THREE.RawShaderMaterial( this.params );
  476. };
  477. /* GLTF PARSER */
  478. var GLTFParser = function(json, options) {
  479. this.json = json || {};
  480. this.options = options || {};
  481. // loader object cache
  482. this.cache = new GLTFRegistry();
  483. };
  484. GLTFParser.prototype._withDependencies = function( dependencies ) {
  485. var _dependencies = {};
  486. for ( var i = 0; i < dependencies.length; i ++ ) {
  487. var dependency = dependencies[ i ];
  488. var fnName = "load" + dependency.charAt(0).toUpperCase() + dependency.slice(1);
  489. var cached = this.cache.get( dependency );
  490. if ( cached !== undefined ) {
  491. _dependencies[ dependency ] = cached;
  492. } else if ( this[ fnName ] ) {
  493. var fn = this[ fnName ]();
  494. this.cache.add( dependency, fn );
  495. _dependencies[ dependency ] = fn;
  496. }
  497. }
  498. return _each( _dependencies, function( dependency, dependencyId ) {
  499. return dependency;
  500. });
  501. };
  502. GLTFParser.prototype.parse = function( callback ) {
  503. // Clear the loader cache
  504. this.cache.removeAll();
  505. // Fire the callback on complete
  506. this._withDependencies([
  507. "scenes",
  508. "cameras",
  509. "animations"
  510. ]).then(function( dependencies ) {
  511. var scene = dependencies.scenes[ this.json.scene ];
  512. var cameras = [];
  513. _each( dependencies.cameras, function( camera ) {
  514. cameras.push( camera );
  515. });
  516. var animations = [];
  517. _each( dependencies.animations, function( animation ) {
  518. animations.push( animation );
  519. });
  520. callback( scene, cameras, animations );
  521. }.bind( this ));
  522. };
  523. GLTFParser.prototype.loadShaders = function() {
  524. return _each( this.json.shaders, function( shader, shaderId ) {
  525. return new Promise( function( resolve ) {
  526. var loader = new THREE.FileLoader();
  527. loader.responseType = 'text';
  528. loader.load( resolveURL( shader.uri, this.options.path ), function( shaderText ) {
  529. resolve( shaderText );
  530. });
  531. }.bind( this ));
  532. }.bind( this ));
  533. };
  534. GLTFParser.prototype.loadBuffers = function() {
  535. return _each( this.json.buffers, function( buffer, bufferId ) {
  536. if ( buffer.type === 'arraybuffer' ) {
  537. return new Promise( function( resolve ) {
  538. var loader = new THREE.FileLoader();
  539. loader.responseType = 'arraybuffer';
  540. loader.load( resolveURL( buffer.uri, this.options.path ), function( buffer ) {
  541. resolve( buffer );
  542. } );
  543. }.bind( this ));
  544. }
  545. }.bind( this ));
  546. };
  547. GLTFParser.prototype.loadBufferViews = function() {
  548. return this._withDependencies([
  549. "buffers"
  550. ]).then( function( dependencies ) {
  551. return _each( this.json.bufferViews, function( bufferView, bufferViewId ) {
  552. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  553. return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + bufferView.byteLength );
  554. });
  555. }.bind( this ));
  556. };
  557. GLTFParser.prototype.loadAccessors = function() {
  558. return this._withDependencies([
  559. "bufferViews"
  560. ]).then( function( dependencies ) {
  561. return _each( this.json.accessors, function( accessor, accessorId ) {
  562. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  563. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  564. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  565. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  566. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  567. var itemBytes = elementBytes * itemSize;
  568. // The buffer is not interleaved if the stride is the item size in bytes.
  569. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  570. // Use the full buffer if it's interleaved.
  571. var array = new TypedArray( arraybuffer );
  572. // Integer parameters to IB/IBA are in array elements, not bytes.
  573. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  574. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  575. } else {
  576. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  577. return new THREE.BufferAttribute( array, itemSize );
  578. }
  579. });
  580. }.bind( this ));
  581. };
  582. GLTFParser.prototype.loadTextures = function() {
  583. return _each( this.json.textures, function( texture, textureId ) {
  584. if ( texture.source ) {
  585. return new Promise( function( resolve ) {
  586. var source = this.json.images[ texture.source ];
  587. var textureLoader = THREE.Loader.Handlers.get( source.uri );
  588. if ( textureLoader === null ) {
  589. textureLoader = new THREE.TextureLoader();
  590. }
  591. textureLoader.crossOrigin = this.options.crossOrigin || false;
  592. textureLoader.load( resolveURL( source.uri, this.options.path ), function( _texture ) {
  593. _texture.flipY = false;
  594. if ( texture.sampler ) {
  595. var sampler = this.json.samplers[ texture.sampler ];
  596. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ];
  597. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ];
  598. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ];
  599. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ];
  600. }
  601. resolve( _texture );
  602. }.bind( this ));
  603. }.bind( this ));
  604. }
  605. }.bind( this ));
  606. };
  607. GLTFParser.prototype.loadMaterials = function() {
  608. return this._withDependencies([
  609. "shaders",
  610. "textures"
  611. ]).then( function( dependencies ) {
  612. return _each( this.json.materials, function( material, materialId ) {
  613. var materialType;
  614. var materialValues = {};
  615. var materialParams = {};
  616. var khr_material;
  617. if ( material.extensions && material.extensions.KHR_materials_common ) {
  618. khr_material = material.extensions.KHR_materials_common;
  619. } else if ( this.json.extensions && this.json.extensions.KHR_materials_common ) {
  620. khr_material = this.json.extensions.KHR_materials_common;
  621. }
  622. if ( khr_material ) {
  623. switch ( khr_material.technique )
  624. {
  625. case 'BLINN' :
  626. case 'PHONG' :
  627. materialType = THREE.MeshPhongMaterial;
  628. break;
  629. case 'LAMBERT' :
  630. materialType = THREE.MeshLambertMaterial;
  631. break;
  632. case 'CONSTANT' :
  633. default :
  634. materialType = THREE.MeshBasicMaterial;
  635. break;
  636. }
  637. _each( khr_material.values, function( value, prop ) {
  638. materialValues[ prop ] = value;
  639. });
  640. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  641. materialParams.side = THREE.DoubleSide;
  642. }
  643. if ( khr_material.transparent || materialValues.transparent ) {
  644. materialParams.transparent = true;
  645. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  646. }
  647. } else if ( material.technique === undefined ) {
  648. materialType = THREE.MeshPhongMaterial;
  649. _each( material.values, function( value, prop ) {
  650. materialValues[ prop ] = value;
  651. });
  652. } else {
  653. materialType = DeferredShaderMaterial;
  654. var technique = this.json.techniques[ material.technique ];
  655. materialParams.uniforms = {};
  656. var program = this.json.programs[ technique.program ];
  657. if ( program ) {
  658. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  659. if ( ! materialParams.fragmentShader ) {
  660. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  661. materialType = THREE.MeshPhongMaterial;
  662. }
  663. var vertexShader = dependencies.shaders[ program.vertexShader ];
  664. if ( ! vertexShader ) {
  665. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  666. materialType = THREE.MeshPhongMaterial;
  667. }
  668. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  669. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  670. var uniforms = technique.uniforms;
  671. _each( uniforms, function( pname, uniformId ) {
  672. var shaderParam = technique.parameters[ pname ];
  673. var ptype = shaderParam.type;
  674. if ( WEBGL_TYPE[ ptype ] ) {
  675. var pcount = shaderParam.count;
  676. var value = material.values[ pname ];
  677. var uvalue = new WEBGL_TYPE[ ptype ]();
  678. var usemantic = shaderParam.semantic;
  679. var unode = shaderParam.node;
  680. switch ( ptype ) {
  681. case WEBGL_CONSTANTS.FLOAT:
  682. uvalue = shaderParam.value;
  683. if ( pname == "transparency" ) {
  684. materialParams.transparent = true;
  685. }
  686. if ( value !== undefined ) {
  687. uvalue = value;
  688. }
  689. break;
  690. case WEBGL_CONSTANTS.FLOAT_VEC2:
  691. case WEBGL_CONSTANTS.FLOAT_VEC3:
  692. case WEBGL_CONSTANTS.FLOAT_VEC4:
  693. case WEBGL_CONSTANTS.FLOAT_MAT3:
  694. if ( shaderParam && shaderParam.value ) {
  695. uvalue.fromArray( shaderParam.value );
  696. }
  697. if ( value ) {
  698. uvalue.fromArray( value );
  699. }
  700. break;
  701. case WEBGL_CONSTANTS.FLOAT_MAT2:
  702. // what to do?
  703. console.warn("FLOAT_MAT2 is not a supported uniform type");
  704. break;
  705. case WEBGL_CONSTANTS.FLOAT_MAT4:
  706. if ( pcount ) {
  707. uvalue = new Array( pcount );
  708. for ( var mi = 0; mi < pcount; mi ++ ) {
  709. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  710. }
  711. if ( shaderParam && shaderParam.value ) {
  712. var m4v = shaderParam.value;
  713. uvalue.fromArray( m4v );
  714. }
  715. if ( value ) {
  716. uvalue.fromArray( value );
  717. }
  718. } else {
  719. if ( shaderParam && shaderParam.value ) {
  720. var m4 = shaderParam.value;
  721. uvalue.fromArray( m4 );
  722. }
  723. if ( value ) {
  724. uvalue.fromArray( value );
  725. }
  726. }
  727. break;
  728. case WEBGL_CONSTANTS.SAMPLER_2D:
  729. uvalue = value ? dependencies.textures[ value ] : null;
  730. break;
  731. }
  732. materialParams.uniforms[ uniformId ] = {
  733. value: uvalue,
  734. semantic: usemantic,
  735. node: unode
  736. };
  737. } else {
  738. throw new Error( "Unknown shader uniform param type: " + ptype );
  739. }
  740. });
  741. }
  742. }
  743. if ( Array.isArray( materialValues.diffuse ) ) {
  744. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  745. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  746. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  747. }
  748. delete materialParams.diffuse;
  749. if ( typeof( materialValues.reflective ) === 'string' ) {
  750. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  751. }
  752. if ( typeof( materialValues.bump ) === 'string' ) {
  753. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  754. }
  755. if ( Array.isArray( materialValues.emission ) ) {
  756. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  757. }
  758. if ( Array.isArray( materialValues.specular ) ) {
  759. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  760. }
  761. if ( materialValues.shininess !== undefined ) {
  762. materialParams.shininess = materialValues.shininess;
  763. }
  764. var _material = new materialType( materialParams );
  765. _material.name = material.name;
  766. return _material;
  767. }.bind( this ));
  768. }.bind( this ));
  769. };
  770. GLTFParser.prototype.loadMeshes = function() {
  771. return this._withDependencies([
  772. "accessors",
  773. "materials"
  774. ]).then( function( dependencies ) {
  775. return _each( this.json.meshes, function( mesh, meshId ) {
  776. var group = new THREE.Object3D();
  777. group.name = mesh.name;
  778. var primitives = mesh.primitives;
  779. _each( primitives, function( primitive ) {
  780. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  781. var geometry = new THREE.BufferGeometry();
  782. var attributes = primitive.attributes;
  783. _each( attributes, function( attributeEntry, attributeId ) {
  784. if ( !attributeEntry ) {
  785. return;
  786. }
  787. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  788. switch ( attributeId ) {
  789. case 'POSITION':
  790. geometry.addAttribute( 'position', bufferAttribute );
  791. break;
  792. case 'NORMAL':
  793. geometry.addAttribute( 'normal', bufferAttribute );
  794. break;
  795. case 'TEXCOORD_0':
  796. case 'TEXCOORD0':
  797. case 'TEXCOORD':
  798. geometry.addAttribute( 'uv', bufferAttribute );
  799. break;
  800. case 'WEIGHT':
  801. geometry.addAttribute( 'skinWeight', bufferAttribute );
  802. break;
  803. case 'JOINT':
  804. geometry.addAttribute( 'skinIndex', bufferAttribute );
  805. break;
  806. }
  807. });
  808. if ( primitive.indices ) {
  809. var indexArray = dependencies.accessors[ primitive.indices ];
  810. geometry.setIndex( indexArray );
  811. var offset = {
  812. start: 0,
  813. index: 0,
  814. count: indexArray.count
  815. };
  816. geometry.groups.push( offset );
  817. geometry.computeBoundingSphere();
  818. }
  819. var material = dependencies.materials[ primitive.material ];
  820. var meshNode = new THREE.Mesh( geometry, material );
  821. meshNode.castShadow = true;
  822. group.add( meshNode );
  823. } else {
  824. console.warn("Non-triangular primitives are not supported");
  825. }
  826. });
  827. return group;
  828. });
  829. }.bind( this ));
  830. };
  831. GLTFParser.prototype.loadCameras = function() {
  832. return _each( this.json.cameras, function( camera, cameraId ) {
  833. if ( camera.type == "perspective" && camera.perspective ) {
  834. var yfov = camera.perspective.yfov;
  835. var xfov = camera.perspective.xfov;
  836. var aspect_ratio = camera.perspective.aspect_ratio || 1;
  837. // According to COLLADA spec...
  838. // aspect_ratio = xfov / yfov
  839. xfov = ( xfov === undefined && yfov ) ? yfov * aspect_ratio : xfov;
  840. // According to COLLADA spec...
  841. // aspect_ratio = xfov / yfov
  842. // yfov = ( yfov === undefined && xfov ) ? xfov / aspect_ratio : yfov;
  843. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspect_ratio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  844. _camera.name = camera.name;
  845. return _camera;
  846. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  847. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  848. _camera.name = camera.name;
  849. return _camera;
  850. }
  851. }.bind( this ));
  852. };
  853. GLTFParser.prototype.loadSkins = function() {
  854. return this._withDependencies([
  855. "accessors"
  856. ]).then( function( dependencies ) {
  857. return _each( this.json.skins, function( skin, skinId ) {
  858. var _skin = {
  859. bindShapeMatrix: new THREE.Matrix4().fromArray( skin.bindShapeMatrix ),
  860. jointNames: skin.jointNames,
  861. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  862. };
  863. return _skin;
  864. });
  865. }.bind( this ));
  866. };
  867. GLTFParser.prototype.loadAnimations = function() {
  868. return this._withDependencies([
  869. "accessors",
  870. "nodes"
  871. ]).then( function( dependencies ) {
  872. return _each( this.json.animations, function( animation, animationId ) {
  873. var interps = [];
  874. _each( animation.channels, function( channel ) {
  875. var sampler = animation.samplers[ channel.sampler ];
  876. if (sampler && animation.parameters) {
  877. var target = channel.target;
  878. var name = target.id;
  879. var input = animation.parameters[sampler.input];
  880. var output = animation.parameters[sampler.output];
  881. var inputAccessor = dependencies.accessors[ input ];
  882. var outputAccessor = dependencies.accessors[ output ];
  883. var node = dependencies.nodes[ name ];
  884. if ( node ) {
  885. var interp = {
  886. keys : inputAccessor.array,
  887. values : outputAccessor.array,
  888. count : inputAccessor.count,
  889. target : node,
  890. path : target.path,
  891. type : sampler.interpolation
  892. };
  893. interps.push( interp );
  894. }
  895. }
  896. });
  897. var _animation = new GLTFAnimation(interps);
  898. _animation.name = "animation_" + animationId;
  899. return _animation;
  900. });
  901. }.bind( this ));
  902. };
  903. GLTFParser.prototype.loadNodes = function() {
  904. return _each( this.json.nodes, function( node, nodeId ) {
  905. var matrix = new THREE.Matrix4();
  906. var _node;
  907. if ( node.jointName ) {
  908. _node = new THREE.Bone();
  909. _node.jointName = node.jointName;
  910. } else {
  911. _node = new THREE.Object3D()
  912. }
  913. _node.name = node.name;
  914. _node.matrixAutoUpdate = false;
  915. if ( node.matrix !== undefined ) {
  916. matrix.fromArray( node.matrix );
  917. _node.applyMatrix( matrix );
  918. } else {
  919. if ( node.translation !== undefined ) {
  920. _node.position.fromArray( node.translation );
  921. }
  922. if ( node.rotation !== undefined ) {
  923. _node.quaternion.fromArray( node.rotation );
  924. }
  925. if ( node.scale !== undefined ) {
  926. _node.scale.fromArray( node.scale );
  927. }
  928. }
  929. return _node;
  930. }.bind( this )).then( function( __nodes ) {
  931. return this._withDependencies([
  932. "meshes",
  933. "skins",
  934. "cameras",
  935. "extensions"
  936. ]).then( function( dependencies ) {
  937. return _each( __nodes, function( _node, nodeId ) {
  938. var node = this.json.nodes[ nodeId ];
  939. if ( node.meshes !== undefined ) {
  940. _each( node.meshes, function( meshId ) {
  941. var group = dependencies.meshes[ meshId ];
  942. _each( group.children, function( mesh ) {
  943. // clone Mesh to add to _node
  944. var originalMaterial = mesh.material;
  945. var originalGeometry = mesh.geometry;
  946. var material;
  947. if(originalMaterial.isDeferredShaderMaterial) {
  948. originalMaterial = material = originalMaterial.create();
  949. } else {
  950. material = originalMaterial;
  951. }
  952. mesh = new THREE.Mesh( originalGeometry, material );
  953. mesh.castShadow = true;
  954. var skinEntry;
  955. if ( node.skin ) {
  956. skinEntry = dependencies.skins[ node.skin ];
  957. }
  958. // Replace Mesh with SkinnedMesh in library
  959. if (skinEntry) {
  960. var geometry = originalGeometry;
  961. var material = originalMaterial;
  962. material.skinning = true;
  963. mesh = new THREE.SkinnedMesh( geometry, material, false );
  964. mesh.castShadow = true;
  965. var bones = [];
  966. var boneInverses = [];
  967. _each( skinEntry.jointNames, function( jointId, i ) {
  968. var jointNode = __nodes[ jointId ];
  969. if ( jointNode ) {
  970. jointNode.skin = mesh;
  971. bones.push(jointNode);
  972. var m = skinEntry.inverseBindMatrices.array;
  973. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  974. boneInverses.push(mat);
  975. } else {
  976. console.warn( "WARNING: joint: ''" + jointId + "' could not be found" );
  977. }
  978. });
  979. mesh.bind( new THREE.Skeleton( bones, boneInverses, false ), skinEntry.bindShapeMatrix );
  980. }
  981. _node.add( mesh );
  982. });
  983. });
  984. }
  985. if ( node.camera !== undefined ) {
  986. var camera = dependencies.cameras[ node.camera ];
  987. _node.add( camera );
  988. }
  989. if (node.extensions && node.extensions.KHR_materials_common
  990. && node.extensions.KHR_materials_common.light) {
  991. var light = dependencies.extensions.KHR_materials_common.lights[ node.extensions.KHR_materials_common.light ];
  992. _node.add(light);
  993. }
  994. return _node;
  995. }.bind( this ));
  996. }.bind( this ));
  997. }.bind( this ));
  998. };
  999. GLTFParser.prototype.loadExtensions = function() {
  1000. return _each( this.json.extensions, function( extension, extensionId ) {
  1001. switch ( extensionId ) {
  1002. case "KHR_materials_common":
  1003. var extensionNode = {
  1004. lights: {}
  1005. };
  1006. var lights = extension.lights;
  1007. _each( lights, function( light, lightID ) {
  1008. var lightNode;
  1009. var lightParams = light[light.type];
  1010. var color = new THREE.Color().fromArray( lightParams.color );
  1011. switch ( light.type ) {
  1012. case "directional":
  1013. lightNode = new THREE.DirectionalLight( color );
  1014. lightNode.position.set( 0, 0, 1 );
  1015. break;
  1016. case "point":
  1017. lightNode = new THREE.PointLight( color );
  1018. break;
  1019. case "spot ":
  1020. lightNode = new THREE.SpotLight( color );
  1021. lightNode.position.set( 0, 0, 1 );
  1022. break;
  1023. case "ambient":
  1024. lightNode = new THREE.AmbientLight( color );
  1025. break;
  1026. }
  1027. if ( lightNode ) {
  1028. extensionNode.lights[ lightID ] = lightNode;
  1029. }
  1030. });
  1031. return extensionNode;
  1032. break;
  1033. }
  1034. }.bind( this ));
  1035. };
  1036. GLTFParser.prototype.loadScenes = function() {
  1037. // scene node hierachy builder
  1038. var buildNodeHierachy = function( nodeId, parentObject, allNodes ) {
  1039. var _node = allNodes[ nodeId ];
  1040. parentObject.add( _node );
  1041. var node = this.json.nodes[ nodeId ];
  1042. if ( node.children ) {
  1043. _each( node.children, function( child ) {
  1044. buildNodeHierachy( child, _node, allNodes );
  1045. });
  1046. }
  1047. }.bind( this );
  1048. return this._withDependencies([
  1049. "nodes"
  1050. ]).then( function( dependencies ) {
  1051. return _each( this.json.scenes, function( scene, sceneId ) {
  1052. var _scene = new THREE.Scene();
  1053. _scene.name = scene.name;
  1054. _each( scene.nodes, function( nodeId ) {
  1055. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1056. });
  1057. _scene.traverse( function( child ) {
  1058. // Register raw material meshes with GLTFLoader.Shaders
  1059. if (child.material && child.material.isRawShaderMaterial) {
  1060. var xshader = new GLTFShader( child, dependencies.nodes );
  1061. THREE.GLTFLoader.Shaders.add( child.uuid, xshader );
  1062. }
  1063. });
  1064. return _scene;
  1065. });
  1066. }.bind( this ));
  1067. };
  1068. })();