LegacyGLTFLoader.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  1. /**
  2. * @author Rich Tibbett / https://github.com/richtr
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author Tony Parisi / http://www.tonyparisi.com/
  5. * @author Takahiro / https://github.com/takahirox
  6. */
  7. THREE.LegacyGLTFLoader = ( function () {
  8. function LegacyGLTFLoader( manager ) {
  9. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10. }
  11. LegacyGLTFLoader.prototype = {
  12. constructor: LegacyGLTFLoader,
  13. crossOrigin: 'anonymous',
  14. load: function ( url, onLoad, onProgress, onError ) {
  15. var scope = this;
  16. var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.LoaderUtils.extractUrlBase( url );
  17. var loader = new THREE.FileLoader( scope.manager );
  18. loader.setResponseType( 'arraybuffer' );
  19. loader.load( url, function ( data ) {
  20. scope.parse( data, path, onLoad );
  21. }, onProgress, onError );
  22. },
  23. setCrossOrigin: function ( value ) {
  24. this.crossOrigin = value;
  25. return this;
  26. },
  27. setPath: function ( value ) {
  28. this.path = value;
  29. },
  30. parse: function ( data, path, callback ) {
  31. var content;
  32. var extensions = {};
  33. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  34. if ( magic === BINARY_EXTENSION_HEADER_DEFAULTS.magic ) {
  35. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  36. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  37. } else {
  38. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  39. }
  40. var json = JSON.parse( content );
  41. if ( json.extensionsUsed && json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  42. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  43. }
  44. var parser = new GLTFParser( json, extensions, {
  45. crossOrigin: this.crossOrigin,
  46. manager: this.manager,
  47. path: path || this.path
  48. } );
  49. parser.parse( function ( scene, scenes, cameras, animations ) {
  50. var glTF = {
  51. "scene": scene,
  52. "scenes": scenes,
  53. "cameras": cameras,
  54. "animations": animations
  55. };
  56. callback( glTF );
  57. } );
  58. }
  59. };
  60. /* GLTFREGISTRY */
  61. function GLTFRegistry() {
  62. var objects = {};
  63. return {
  64. get: function ( key ) {
  65. return objects[ key ];
  66. },
  67. add: function ( key, object ) {
  68. objects[ key ] = object;
  69. },
  70. remove: function ( key ) {
  71. delete objects[ key ];
  72. },
  73. removeAll: function () {
  74. objects = {};
  75. },
  76. update: function ( scene, camera ) {
  77. for ( var name in objects ) {
  78. var object = objects[ name ];
  79. if ( object.update ) {
  80. object.update( scene, camera );
  81. }
  82. }
  83. }
  84. };
  85. }
  86. /* GLTFSHADERS */
  87. LegacyGLTFLoader.Shaders = {
  88. update: function () {
  89. console.warn( 'THREE.LegacyGLTFLoader.Shaders has been deprecated, and now updates automatically.' );
  90. }
  91. };
  92. /* GLTFSHADER */
  93. function GLTFShader( targetNode, allNodes ) {
  94. var boundUniforms = {};
  95. // bind each uniform to its source node
  96. var uniforms = targetNode.material.uniforms;
  97. for ( var uniformId in uniforms ) {
  98. var uniform = uniforms[ uniformId ];
  99. if ( uniform.semantic ) {
  100. var sourceNodeRef = uniform.node;
  101. var sourceNode = targetNode;
  102. if ( sourceNodeRef ) {
  103. sourceNode = allNodes[ sourceNodeRef ];
  104. }
  105. boundUniforms[ uniformId ] = {
  106. semantic: uniform.semantic,
  107. sourceNode: sourceNode,
  108. targetNode: targetNode,
  109. uniform: uniform
  110. };
  111. }
  112. }
  113. this.boundUniforms = boundUniforms;
  114. this._m4 = new THREE.Matrix4();
  115. }
  116. // Update - update all the uniform values
  117. GLTFShader.prototype.update = function ( scene, camera ) {
  118. var boundUniforms = this.boundUniforms;
  119. for ( var name in boundUniforms ) {
  120. var boundUniform = boundUniforms[ name ];
  121. switch ( boundUniform.semantic ) {
  122. case "MODELVIEW":
  123. var m4 = boundUniform.uniform.value;
  124. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  125. break;
  126. case "MODELVIEWINVERSETRANSPOSE":
  127. var m3 = boundUniform.uniform.value;
  128. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  129. m3.getNormalMatrix( this._m4 );
  130. break;
  131. case "PROJECTION":
  132. var m4 = boundUniform.uniform.value;
  133. m4.copy( camera.projectionMatrix );
  134. break;
  135. case "JOINTMATRIX":
  136. var m4v = boundUniform.uniform.value;
  137. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  138. // So it goes like this:
  139. // SkinnedMesh world matrix is already baked into MODELVIEW;
  140. // transform joints to local space,
  141. // then transform using joint's inverse
  142. m4v[ mi ]
  143. .getInverse( boundUniform.sourceNode.matrixWorld )
  144. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  145. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
  146. .multiply( boundUniform.targetNode.bindMatrix );
  147. }
  148. break;
  149. default :
  150. console.warn( "Unhandled shader semantic: " + boundUniform.semantic );
  151. break;
  152. }
  153. }
  154. };
  155. /* ANIMATION */
  156. LegacyGLTFLoader.Animations = {
  157. update: function () {
  158. console.warn( 'THREE.LegacyGLTFLoader.Animation has been deprecated. Use THREE.AnimationMixer instead.' );
  159. }
  160. };
  161. /*********************************/
  162. /********** EXTENSIONS ***********/
  163. /*********************************/
  164. var EXTENSIONS = {
  165. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  166. KHR_MATERIALS_COMMON: 'KHR_materials_common'
  167. };
  168. /* MATERIALS COMMON EXTENSION */
  169. function GLTFMaterialsCommonExtension( json ) {
  170. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  171. this.lights = {};
  172. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) || {};
  173. var lights = extension.lights || {};
  174. for ( var lightId in lights ) {
  175. var light = lights[ lightId ];
  176. var lightNode;
  177. var lightParams = light[ light.type ];
  178. var color = new THREE.Color().fromArray( lightParams.color );
  179. switch ( light.type ) {
  180. case "directional":
  181. lightNode = new THREE.DirectionalLight( color );
  182. lightNode.position.set( 0, 0, 1 );
  183. break;
  184. case "point":
  185. lightNode = new THREE.PointLight( color );
  186. break;
  187. case "spot":
  188. lightNode = new THREE.SpotLight( color );
  189. lightNode.position.set( 0, 0, 1 );
  190. break;
  191. case "ambient":
  192. lightNode = new THREE.AmbientLight( color );
  193. break;
  194. }
  195. if ( lightNode ) {
  196. this.lights[ lightId ] = lightNode;
  197. }
  198. }
  199. }
  200. /* BINARY EXTENSION */
  201. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  202. var BINARY_EXTENSION_HEADER_DEFAULTS = { magic: 'glTF', version: 1, contentFormat: 0 };
  203. var BINARY_EXTENSION_HEADER_LENGTH = 20;
  204. function GLTFBinaryExtension( data ) {
  205. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  206. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  207. var header = {
  208. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  209. version: headerView.getUint32( 4, true ),
  210. length: headerView.getUint32( 8, true ),
  211. contentLength: headerView.getUint32( 12, true ),
  212. contentFormat: headerView.getUint32( 16, true )
  213. };
  214. for ( var key in BINARY_EXTENSION_HEADER_DEFAULTS ) {
  215. var value = BINARY_EXTENSION_HEADER_DEFAULTS[ key ];
  216. if ( header[ key ] !== value ) {
  217. throw new Error( 'Unsupported glTF-Binary header: Expected "%s" to be "%s".', key, value );
  218. }
  219. }
  220. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH, header.contentLength );
  221. this.header = header;
  222. this.content = THREE.LoaderUtils.decodeText( contentArray );
  223. this.body = data.slice( BINARY_EXTENSION_HEADER_LENGTH + header.contentLength, header.length );
  224. }
  225. GLTFBinaryExtension.prototype.loadShader = function ( shader, bufferViews ) {
  226. var bufferView = bufferViews[ shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].bufferView ];
  227. var array = new Uint8Array( bufferView );
  228. return THREE.LoaderUtils.decodeText( array );
  229. };
  230. /*********************************/
  231. /********** INTERNALS ************/
  232. /*********************************/
  233. /* CONSTANTS */
  234. var WEBGL_CONSTANTS = {
  235. FLOAT: 5126,
  236. //FLOAT_MAT2: 35674,
  237. FLOAT_MAT3: 35675,
  238. FLOAT_MAT4: 35676,
  239. FLOAT_VEC2: 35664,
  240. FLOAT_VEC3: 35665,
  241. FLOAT_VEC4: 35666,
  242. LINEAR: 9729,
  243. REPEAT: 10497,
  244. SAMPLER_2D: 35678,
  245. TRIANGLES: 4,
  246. LINES: 1,
  247. UNSIGNED_BYTE: 5121,
  248. UNSIGNED_SHORT: 5123,
  249. VERTEX_SHADER: 35633,
  250. FRAGMENT_SHADER: 35632
  251. };
  252. var WEBGL_TYPE = {
  253. 5126: Number,
  254. //35674: THREE.Matrix2,
  255. 35675: THREE.Matrix3,
  256. 35676: THREE.Matrix4,
  257. 35664: THREE.Vector2,
  258. 35665: THREE.Vector3,
  259. 35666: THREE.Vector4,
  260. 35678: THREE.Texture
  261. };
  262. var WEBGL_COMPONENT_TYPES = {
  263. 5120: Int8Array,
  264. 5121: Uint8Array,
  265. 5122: Int16Array,
  266. 5123: Uint16Array,
  267. 5125: Uint32Array,
  268. 5126: Float32Array
  269. };
  270. var WEBGL_FILTERS = {
  271. 9728: THREE.NearestFilter,
  272. 9729: THREE.LinearFilter,
  273. 9984: THREE.NearestMipMapNearestFilter,
  274. 9985: THREE.LinearMipMapNearestFilter,
  275. 9986: THREE.NearestMipMapLinearFilter,
  276. 9987: THREE.LinearMipMapLinearFilter
  277. };
  278. var WEBGL_WRAPPINGS = {
  279. 33071: THREE.ClampToEdgeWrapping,
  280. 33648: THREE.MirroredRepeatWrapping,
  281. 10497: THREE.RepeatWrapping
  282. };
  283. var WEBGL_TEXTURE_FORMATS = {
  284. 6406: THREE.AlphaFormat,
  285. 6407: THREE.RGBFormat,
  286. 6408: THREE.RGBAFormat,
  287. 6409: THREE.LuminanceFormat,
  288. 6410: THREE.LuminanceAlphaFormat
  289. };
  290. var WEBGL_TEXTURE_DATATYPES = {
  291. 5121: THREE.UnsignedByteType,
  292. 32819: THREE.UnsignedShort4444Type,
  293. 32820: THREE.UnsignedShort5551Type,
  294. 33635: THREE.UnsignedShort565Type
  295. };
  296. var WEBGL_SIDES = {
  297. 1028: THREE.BackSide, // Culling front
  298. 1029: THREE.FrontSide // Culling back
  299. //1032: THREE.NoSide // Culling front and back, what to do?
  300. };
  301. var WEBGL_DEPTH_FUNCS = {
  302. 512: THREE.NeverDepth,
  303. 513: THREE.LessDepth,
  304. 514: THREE.EqualDepth,
  305. 515: THREE.LessEqualDepth,
  306. 516: THREE.GreaterEqualDepth,
  307. 517: THREE.NotEqualDepth,
  308. 518: THREE.GreaterEqualDepth,
  309. 519: THREE.AlwaysDepth
  310. };
  311. var WEBGL_BLEND_EQUATIONS = {
  312. 32774: THREE.AddEquation,
  313. 32778: THREE.SubtractEquation,
  314. 32779: THREE.ReverseSubtractEquation
  315. };
  316. var WEBGL_BLEND_FUNCS = {
  317. 0: THREE.ZeroFactor,
  318. 1: THREE.OneFactor,
  319. 768: THREE.SrcColorFactor,
  320. 769: THREE.OneMinusSrcColorFactor,
  321. 770: THREE.SrcAlphaFactor,
  322. 771: THREE.OneMinusSrcAlphaFactor,
  323. 772: THREE.DstAlphaFactor,
  324. 773: THREE.OneMinusDstAlphaFactor,
  325. 774: THREE.DstColorFactor,
  326. 775: THREE.OneMinusDstColorFactor,
  327. 776: THREE.SrcAlphaSaturateFactor
  328. // The followings are not supported by Three.js yet
  329. //32769: CONSTANT_COLOR,
  330. //32770: ONE_MINUS_CONSTANT_COLOR,
  331. //32771: CONSTANT_ALPHA,
  332. //32772: ONE_MINUS_CONSTANT_COLOR
  333. };
  334. var WEBGL_TYPE_SIZES = {
  335. 'SCALAR': 1,
  336. 'VEC2': 2,
  337. 'VEC3': 3,
  338. 'VEC4': 4,
  339. 'MAT2': 4,
  340. 'MAT3': 9,
  341. 'MAT4': 16
  342. };
  343. var PATH_PROPERTIES = {
  344. scale: 'scale',
  345. translation: 'position',
  346. rotation: 'quaternion'
  347. };
  348. var INTERPOLATION = {
  349. LINEAR: THREE.InterpolateLinear,
  350. STEP: THREE.InterpolateDiscrete
  351. };
  352. var STATES_ENABLES = {
  353. 2884: 'CULL_FACE',
  354. 2929: 'DEPTH_TEST',
  355. 3042: 'BLEND',
  356. 3089: 'SCISSOR_TEST',
  357. 32823: 'POLYGON_OFFSET_FILL',
  358. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  359. };
  360. /* UTILITY FUNCTIONS */
  361. function _each( object, callback, thisObj ) {
  362. if ( !object ) {
  363. return Promise.resolve();
  364. }
  365. var results;
  366. var fns = [];
  367. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  368. results = [];
  369. var length = object.length;
  370. for ( var idx = 0; idx < length; idx ++ ) {
  371. var value = callback.call( thisObj || this, object[ idx ], idx );
  372. if ( value ) {
  373. fns.push( value );
  374. if ( value instanceof Promise ) {
  375. value.then( function( key, value ) {
  376. results[ key ] = value;
  377. }.bind( this, idx ));
  378. } else {
  379. results[ idx ] = value;
  380. }
  381. }
  382. }
  383. } else {
  384. results = {};
  385. for ( var key in object ) {
  386. if ( object.hasOwnProperty( key ) ) {
  387. var value = callback.call( thisObj || this, object[ key ], key );
  388. if ( value ) {
  389. fns.push( value );
  390. if ( value instanceof Promise ) {
  391. value.then( function( key, value ) {
  392. results[ key ] = value;
  393. }.bind( this, key ));
  394. } else {
  395. results[ key ] = value;
  396. }
  397. }
  398. }
  399. }
  400. }
  401. return Promise.all( fns ).then( function() {
  402. return results;
  403. });
  404. }
  405. function resolveURL( url, path ) {
  406. // Invalid URL
  407. if ( typeof url !== 'string' || url === '' )
  408. return '';
  409. // Absolute URL http://,https://,//
  410. if ( /^(https?:)?\/\//i.test( url ) ) {
  411. return url;
  412. }
  413. // Data URI
  414. if ( /^data:.*,.*$/i.test( url ) ) {
  415. return url;
  416. }
  417. // Blob URL
  418. if ( /^blob:.*$/i.test( url ) ) {
  419. return url;
  420. }
  421. // Relative URL
  422. return ( path || '' ) + url;
  423. }
  424. // Three.js seems too dependent on attribute names so globally
  425. // replace those in the shader code
  426. function replaceTHREEShaderAttributes( shaderText, technique ) {
  427. // Expected technique attributes
  428. var attributes = {};
  429. for ( var attributeId in technique.attributes ) {
  430. var pname = technique.attributes[ attributeId ];
  431. var param = technique.parameters[ pname ];
  432. var atype = param.type;
  433. var semantic = param.semantic;
  434. attributes[ attributeId ] = {
  435. type: atype,
  436. semantic: semantic
  437. };
  438. }
  439. // Figure out which attributes to change in technique
  440. var shaderParams = technique.parameters;
  441. var shaderAttributes = technique.attributes;
  442. var params = {};
  443. for ( var attributeId in attributes ) {
  444. var pname = shaderAttributes[ attributeId ];
  445. var shaderParam = shaderParams[ pname ];
  446. var semantic = shaderParam.semantic;
  447. if ( semantic ) {
  448. params[ attributeId ] = shaderParam;
  449. }
  450. }
  451. for ( var pname in params ) {
  452. var param = params[ pname ];
  453. var semantic = param.semantic;
  454. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  455. switch ( semantic ) {
  456. case "POSITION":
  457. shaderText = shaderText.replace( regEx, 'position' );
  458. break;
  459. case "NORMAL":
  460. shaderText = shaderText.replace( regEx, 'normal' );
  461. break;
  462. case 'TEXCOORD_0':
  463. case 'TEXCOORD0':
  464. case 'TEXCOORD':
  465. shaderText = shaderText.replace( regEx, 'uv' );
  466. break;
  467. case 'TEXCOORD_1':
  468. shaderText = shaderText.replace( regEx, 'uv2' );
  469. break;
  470. case 'COLOR_0':
  471. case 'COLOR0':
  472. case 'COLOR':
  473. shaderText = shaderText.replace( regEx, 'color' );
  474. break;
  475. case "WEIGHT":
  476. shaderText = shaderText.replace( regEx, 'skinWeight' );
  477. break;
  478. case "JOINT":
  479. shaderText = shaderText.replace( regEx, 'skinIndex' );
  480. break;
  481. }
  482. }
  483. return shaderText;
  484. }
  485. function createDefaultMaterial() {
  486. return new THREE.MeshPhongMaterial( {
  487. color: 0x00000,
  488. emissive: 0x888888,
  489. specular: 0x000000,
  490. shininess: 0,
  491. transparent: false,
  492. depthTest: true,
  493. side: THREE.FrontSide
  494. } );
  495. }
  496. // Deferred constructor for RawShaderMaterial types
  497. function DeferredShaderMaterial( params ) {
  498. this.isDeferredShaderMaterial = true;
  499. this.params = params;
  500. }
  501. DeferredShaderMaterial.prototype.create = function () {
  502. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  503. for ( var uniformId in this.params.uniforms ) {
  504. var originalUniform = this.params.uniforms[ uniformId ];
  505. if ( originalUniform.value instanceof THREE.Texture ) {
  506. uniforms[ uniformId ].value = originalUniform.value;
  507. uniforms[ uniformId ].value.needsUpdate = true;
  508. }
  509. uniforms[ uniformId ].semantic = originalUniform.semantic;
  510. uniforms[ uniformId ].node = originalUniform.node;
  511. }
  512. this.params.uniforms = uniforms;
  513. return new THREE.RawShaderMaterial( this.params );
  514. };
  515. /* GLTF PARSER */
  516. function GLTFParser( json, extensions, options ) {
  517. this.json = json || {};
  518. this.extensions = extensions || {};
  519. this.options = options || {};
  520. // loader object cache
  521. this.cache = new GLTFRegistry();
  522. }
  523. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  524. var _dependencies = {};
  525. for ( var i = 0; i < dependencies.length; i ++ ) {
  526. var dependency = dependencies[ i ];
  527. var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  528. var cached = this.cache.get( dependency );
  529. if ( cached !== undefined ) {
  530. _dependencies[ dependency ] = cached;
  531. } else if ( this[ fnName ] ) {
  532. var fn = this[ fnName ]();
  533. this.cache.add( dependency, fn );
  534. _dependencies[ dependency ] = fn;
  535. }
  536. }
  537. return _each( _dependencies, function ( dependency ) {
  538. return dependency;
  539. } );
  540. };
  541. GLTFParser.prototype.parse = function ( callback ) {
  542. var json = this.json;
  543. // Clear the loader cache
  544. this.cache.removeAll();
  545. // Fire the callback on complete
  546. this._withDependencies( [
  547. "scenes",
  548. "cameras",
  549. "animations"
  550. ] ).then( function ( dependencies ) {
  551. var scenes = [];
  552. for ( var name in dependencies.scenes ) {
  553. scenes.push( dependencies.scenes[ name ] );
  554. }
  555. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  556. var cameras = [];
  557. for ( var name in dependencies.cameras ) {
  558. var camera = dependencies.cameras[ name ];
  559. cameras.push( camera );
  560. }
  561. var animations = [];
  562. for ( var name in dependencies.animations ) {
  563. animations.push( dependencies.animations[ name ] );
  564. }
  565. callback( scene, scenes, cameras, animations );
  566. } );
  567. };
  568. GLTFParser.prototype.loadShaders = function () {
  569. var json = this.json;
  570. var extensions = this.extensions;
  571. var options = this.options;
  572. return this._withDependencies( [
  573. "bufferViews"
  574. ] ).then( function ( dependencies ) {
  575. return _each( json.shaders, function ( shader ) {
  576. if ( shader.extensions && shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  577. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadShader( shader, dependencies.bufferViews );
  578. }
  579. return new Promise( function ( resolve ) {
  580. var loader = new THREE.FileLoader( options.manager );
  581. loader.setResponseType( 'text' );
  582. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  583. resolve( shaderText );
  584. } );
  585. } );
  586. } );
  587. } );
  588. };
  589. GLTFParser.prototype.loadBuffers = function () {
  590. var json = this.json;
  591. var extensions = this.extensions;
  592. var options = this.options;
  593. return _each( json.buffers, function ( buffer, name ) {
  594. if ( name === BINARY_EXTENSION_BUFFER_NAME ) {
  595. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  596. }
  597. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  598. return new Promise( function ( resolve ) {
  599. var loader = new THREE.FileLoader( options.manager );
  600. loader.setResponseType( 'arraybuffer' );
  601. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  602. resolve( buffer );
  603. } );
  604. } );
  605. } else {
  606. console.warn( 'THREE.LegacyGLTFLoader: ' + buffer.type + ' buffer type is not supported' );
  607. }
  608. } );
  609. };
  610. GLTFParser.prototype.loadBufferViews = function () {
  611. var json = this.json;
  612. return this._withDependencies( [
  613. "buffers"
  614. ] ).then( function ( dependencies ) {
  615. return _each( json.bufferViews, function ( bufferView ) {
  616. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  617. var byteLength = bufferView.byteLength !== undefined ? bufferView.byteLength : 0;
  618. return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + byteLength );
  619. } );
  620. } );
  621. };
  622. GLTFParser.prototype.loadAccessors = function () {
  623. var json = this.json;
  624. return this._withDependencies( [
  625. "bufferViews"
  626. ] ).then( function ( dependencies ) {
  627. return _each( json.accessors, function ( accessor ) {
  628. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  629. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  630. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  631. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  632. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  633. var itemBytes = elementBytes * itemSize;
  634. // The buffer is not interleaved if the stride is the item size in bytes.
  635. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  636. // Use the full buffer if it's interleaved.
  637. var array = new TypedArray( arraybuffer );
  638. // Integer parameters to IB/IBA are in array elements, not bytes.
  639. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  640. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  641. } else {
  642. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  643. return new THREE.BufferAttribute( array, itemSize );
  644. }
  645. } );
  646. } );
  647. };
  648. GLTFParser.prototype.loadTextures = function () {
  649. var json = this.json;
  650. var extensions = this.extensions;
  651. var options = this.options;
  652. return this._withDependencies( [
  653. "bufferViews"
  654. ] ).then( function ( dependencies ) {
  655. return _each( json.textures, function ( texture ) {
  656. if ( texture.source ) {
  657. return new Promise( function ( resolve ) {
  658. var source = json.images[ texture.source ];
  659. var sourceUri = source.uri;
  660. var isObjectURL = false;
  661. if ( source.extensions && source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  662. var metadata = source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ];
  663. var bufferView = dependencies.bufferViews[ metadata.bufferView ];
  664. var blob = new Blob( [ bufferView ], { type: metadata.mimeType } );
  665. sourceUri = URL.createObjectURL( blob );
  666. isObjectURL = true;
  667. }
  668. var textureLoader = THREE.Loader.Handlers.get( sourceUri );
  669. if ( textureLoader === null ) {
  670. textureLoader = new THREE.TextureLoader( options.manager );
  671. }
  672. textureLoader.setCrossOrigin( options.crossOrigin );
  673. textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
  674. if ( isObjectURL ) URL.revokeObjectURL( sourceUri );
  675. _texture.flipY = false;
  676. if ( texture.name !== undefined ) _texture.name = texture.name;
  677. _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat;
  678. if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {
  679. console.warn( 'THREE.LegacyGLTFLoader: Three.js doesn\'t support texture internalFormat which is different from texture format. ' +
  680. 'internalFormat will be forced to be the same value as format.' );
  681. }
  682. _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;
  683. if ( texture.sampler ) {
  684. var sampler = json.samplers[ texture.sampler ];
  685. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  686. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.NearestMipMapLinearFilter;
  687. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  688. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  689. }
  690. resolve( _texture );
  691. }, undefined, function () {
  692. if ( isObjectURL ) URL.revokeObjectURL( sourceUri );
  693. resolve();
  694. } );
  695. } );
  696. }
  697. } );
  698. } );
  699. };
  700. GLTFParser.prototype.loadMaterials = function () {
  701. var json = this.json;
  702. return this._withDependencies( [
  703. "shaders",
  704. "textures"
  705. ] ).then( function ( dependencies ) {
  706. return _each( json.materials, function ( material ) {
  707. var materialType;
  708. var materialValues = {};
  709. var materialParams = {};
  710. var khr_material;
  711. if ( material.extensions && material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  712. khr_material = material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  713. }
  714. if ( khr_material ) {
  715. // don't copy over unused values to avoid material warning spam
  716. var keys = [ 'ambient', 'emission', 'transparent', 'transparency', 'doubleSided' ];
  717. switch ( khr_material.technique ) {
  718. case 'BLINN' :
  719. case 'PHONG' :
  720. materialType = THREE.MeshPhongMaterial;
  721. keys.push( 'diffuse', 'specular', 'shininess' );
  722. break;
  723. case 'LAMBERT' :
  724. materialType = THREE.MeshLambertMaterial;
  725. keys.push( 'diffuse' );
  726. break;
  727. case 'CONSTANT' :
  728. default :
  729. materialType = THREE.MeshBasicMaterial;
  730. break;
  731. }
  732. keys.forEach( function( v ) {
  733. if ( khr_material.values[ v ] !== undefined ) materialValues[ v ] = khr_material.values[ v ];
  734. } );
  735. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  736. materialParams.side = THREE.DoubleSide;
  737. }
  738. if ( khr_material.transparent || materialValues.transparent ) {
  739. materialParams.transparent = true;
  740. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  741. }
  742. } else if ( material.technique === undefined ) {
  743. materialType = THREE.MeshPhongMaterial;
  744. Object.assign( materialValues, material.values );
  745. } else {
  746. materialType = DeferredShaderMaterial;
  747. var technique = json.techniques[ material.technique ];
  748. materialParams.uniforms = {};
  749. var program = json.programs[ technique.program ];
  750. if ( program ) {
  751. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  752. if ( ! materialParams.fragmentShader ) {
  753. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  754. materialType = THREE.MeshPhongMaterial;
  755. }
  756. var vertexShader = dependencies.shaders[ program.vertexShader ];
  757. if ( ! vertexShader ) {
  758. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  759. materialType = THREE.MeshPhongMaterial;
  760. }
  761. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  762. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  763. var uniforms = technique.uniforms;
  764. for ( var uniformId in uniforms ) {
  765. var pname = uniforms[ uniformId ];
  766. var shaderParam = technique.parameters[ pname ];
  767. var ptype = shaderParam.type;
  768. if ( WEBGL_TYPE[ ptype ] ) {
  769. var pcount = shaderParam.count;
  770. var value;
  771. if ( material.values !== undefined ) value = material.values[ pname ];
  772. var uvalue = new WEBGL_TYPE[ ptype ]();
  773. var usemantic = shaderParam.semantic;
  774. var unode = shaderParam.node;
  775. switch ( ptype ) {
  776. case WEBGL_CONSTANTS.FLOAT:
  777. uvalue = shaderParam.value;
  778. if ( pname == "transparency" ) {
  779. materialParams.transparent = true;
  780. }
  781. if ( value !== undefined ) {
  782. uvalue = value;
  783. }
  784. break;
  785. case WEBGL_CONSTANTS.FLOAT_VEC2:
  786. case WEBGL_CONSTANTS.FLOAT_VEC3:
  787. case WEBGL_CONSTANTS.FLOAT_VEC4:
  788. case WEBGL_CONSTANTS.FLOAT_MAT3:
  789. if ( shaderParam && shaderParam.value ) {
  790. uvalue.fromArray( shaderParam.value );
  791. }
  792. if ( value ) {
  793. uvalue.fromArray( value );
  794. }
  795. break;
  796. case WEBGL_CONSTANTS.FLOAT_MAT2:
  797. // what to do?
  798. console.warn( "FLOAT_MAT2 is not a supported uniform type" );
  799. break;
  800. case WEBGL_CONSTANTS.FLOAT_MAT4:
  801. if ( pcount ) {
  802. uvalue = new Array( pcount );
  803. for ( var mi = 0; mi < pcount; mi ++ ) {
  804. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  805. }
  806. if ( shaderParam && shaderParam.value ) {
  807. var m4v = shaderParam.value;
  808. uvalue.fromArray( m4v );
  809. }
  810. if ( value ) {
  811. uvalue.fromArray( value );
  812. }
  813. } else {
  814. if ( shaderParam && shaderParam.value ) {
  815. var m4 = shaderParam.value;
  816. uvalue.fromArray( m4 );
  817. }
  818. if ( value ) {
  819. uvalue.fromArray( value );
  820. }
  821. }
  822. break;
  823. case WEBGL_CONSTANTS.SAMPLER_2D:
  824. if ( value !== undefined ) {
  825. uvalue = dependencies.textures[ value ];
  826. } else if ( shaderParam.value !== undefined ) {
  827. uvalue = dependencies.textures[ shaderParam.value ];
  828. } else {
  829. uvalue = null;
  830. }
  831. break;
  832. }
  833. materialParams.uniforms[ uniformId ] = {
  834. value: uvalue,
  835. semantic: usemantic,
  836. node: unode
  837. };
  838. } else {
  839. throw new Error( "Unknown shader uniform param type: " + ptype );
  840. }
  841. }
  842. var states = technique.states || {};
  843. var enables = states.enable || [];
  844. var functions = states.functions || {};
  845. var enableCullFace = false;
  846. var enableDepthTest = false;
  847. var enableBlend = false;
  848. for ( var i = 0, il = enables.length; i < il; i ++ ) {
  849. var enable = enables[ i ];
  850. switch ( STATES_ENABLES[ enable ] ) {
  851. case 'CULL_FACE':
  852. enableCullFace = true;
  853. break;
  854. case 'DEPTH_TEST':
  855. enableDepthTest = true;
  856. break;
  857. case 'BLEND':
  858. enableBlend = true;
  859. break;
  860. // TODO: implement
  861. case 'SCISSOR_TEST':
  862. case 'POLYGON_OFFSET_FILL':
  863. case 'SAMPLE_ALPHA_TO_COVERAGE':
  864. break;
  865. default:
  866. throw new Error( "Unknown technique.states.enable: " + enable );
  867. }
  868. }
  869. if ( enableCullFace ) {
  870. materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : THREE.FrontSide;
  871. } else {
  872. materialParams.side = THREE.DoubleSide;
  873. }
  874. materialParams.depthTest = enableDepthTest;
  875. materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : THREE.LessDepth;
  876. materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true;
  877. materialParams.blending = enableBlend ? THREE.CustomBlending : THREE.NoBlending;
  878. materialParams.transparent = enableBlend;
  879. var blendEquationSeparate = functions.blendEquationSeparate;
  880. if ( blendEquationSeparate !== undefined ) {
  881. materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ];
  882. materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ];
  883. } else {
  884. materialParams.blendEquation = THREE.AddEquation;
  885. materialParams.blendEquationAlpha = THREE.AddEquation;
  886. }
  887. var blendFuncSeparate = functions.blendFuncSeparate;
  888. if ( blendFuncSeparate !== undefined ) {
  889. materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ];
  890. materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ];
  891. materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ];
  892. materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ];
  893. } else {
  894. materialParams.blendSrc = THREE.OneFactor;
  895. materialParams.blendDst = THREE.ZeroFactor;
  896. materialParams.blendSrcAlpha = THREE.OneFactor;
  897. materialParams.blendDstAlpha = THREE.ZeroFactor;
  898. }
  899. }
  900. }
  901. if ( Array.isArray( materialValues.diffuse ) ) {
  902. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  903. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  904. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  905. }
  906. delete materialParams.diffuse;
  907. if ( typeof( materialValues.reflective ) === 'string' ) {
  908. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  909. }
  910. if ( typeof( materialValues.bump ) === 'string' ) {
  911. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  912. }
  913. if ( Array.isArray( materialValues.emission ) ) {
  914. if ( materialType === THREE.MeshBasicMaterial ) {
  915. materialParams.color = new THREE.Color().fromArray( materialValues.emission );
  916. } else {
  917. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  918. }
  919. } else if ( typeof( materialValues.emission ) === 'string' ) {
  920. if ( materialType === THREE.MeshBasicMaterial ) {
  921. materialParams.map = dependencies.textures[ materialValues.emission ];
  922. } else {
  923. materialParams.emissiveMap = dependencies.textures[ materialValues.emission ];
  924. }
  925. }
  926. if ( Array.isArray( materialValues.specular ) ) {
  927. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  928. } else if ( typeof( materialValues.specular ) === 'string' ) {
  929. materialParams.specularMap = dependencies.textures[ materialValues.specular ];
  930. }
  931. if ( materialValues.shininess !== undefined ) {
  932. materialParams.shininess = materialValues.shininess;
  933. }
  934. var _material = new materialType( materialParams );
  935. if ( material.name !== undefined ) _material.name = material.name;
  936. return _material;
  937. } );
  938. } );
  939. };
  940. GLTFParser.prototype.loadMeshes = function () {
  941. var json = this.json;
  942. return this._withDependencies( [
  943. "accessors",
  944. "materials"
  945. ] ).then( function ( dependencies ) {
  946. return _each( json.meshes, function ( mesh ) {
  947. var group = new THREE.Group();
  948. if ( mesh.name !== undefined ) group.name = mesh.name;
  949. if ( mesh.extras ) group.userData = mesh.extras;
  950. var primitives = mesh.primitives || [];
  951. for ( var name in primitives ) {
  952. var primitive = primitives[ name ];
  953. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  954. var geometry = new THREE.BufferGeometry();
  955. var attributes = primitive.attributes;
  956. for ( var attributeId in attributes ) {
  957. var attributeEntry = attributes[ attributeId ];
  958. if ( ! attributeEntry ) return;
  959. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  960. switch ( attributeId ) {
  961. case 'POSITION':
  962. geometry.addAttribute( 'position', bufferAttribute );
  963. break;
  964. case 'NORMAL':
  965. geometry.addAttribute( 'normal', bufferAttribute );
  966. break;
  967. case 'TEXCOORD_0':
  968. case 'TEXCOORD0':
  969. case 'TEXCOORD':
  970. geometry.addAttribute( 'uv', bufferAttribute );
  971. break;
  972. case 'TEXCOORD_1':
  973. geometry.addAttribute( 'uv2', bufferAttribute );
  974. break;
  975. case 'COLOR_0':
  976. case 'COLOR0':
  977. case 'COLOR':
  978. geometry.addAttribute( 'color', bufferAttribute );
  979. break;
  980. case 'WEIGHT':
  981. geometry.addAttribute( 'skinWeight', bufferAttribute );
  982. break;
  983. case 'JOINT':
  984. geometry.addAttribute( 'skinIndex', bufferAttribute );
  985. break;
  986. default:
  987. if ( ! primitive.material ) break;
  988. var material = json.materials[ primitive.material ];
  989. if ( ! material.technique ) break;
  990. var parameters = json.techniques[ material.technique ].parameters || {};
  991. for( var attributeName in parameters ) {
  992. if ( parameters [ attributeName ][ 'semantic' ] === attributeId ) {
  993. geometry.addAttribute( attributeName, bufferAttribute );
  994. }
  995. }
  996. }
  997. }
  998. if ( primitive.indices ) {
  999. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1000. }
  1001. var material = dependencies.materials !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial();
  1002. var meshNode = new THREE.Mesh( geometry, material );
  1003. meshNode.castShadow = true;
  1004. meshNode.name = ( name === "0" ? group.name : group.name + name );
  1005. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1006. group.add( meshNode );
  1007. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1008. var geometry = new THREE.BufferGeometry();
  1009. var attributes = primitive.attributes;
  1010. for ( var attributeId in attributes ) {
  1011. var attributeEntry = attributes[ attributeId ];
  1012. if ( ! attributeEntry ) return;
  1013. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1014. switch ( attributeId ) {
  1015. case 'POSITION':
  1016. geometry.addAttribute( 'position', bufferAttribute );
  1017. break;
  1018. case 'COLOR_0':
  1019. case 'COLOR0':
  1020. case 'COLOR':
  1021. geometry.addAttribute( 'color', bufferAttribute );
  1022. break;
  1023. }
  1024. }
  1025. var material = dependencies.materials[ primitive.material ];
  1026. var meshNode;
  1027. if ( primitive.indices ) {
  1028. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1029. meshNode = new THREE.LineSegments( geometry, material );
  1030. } else {
  1031. meshNode = new THREE.Line( geometry, material );
  1032. }
  1033. meshNode.name = ( name === "0" ? group.name : group.name + name );
  1034. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1035. group.add( meshNode );
  1036. } else {
  1037. console.warn( "Only triangular and line primitives are supported" );
  1038. }
  1039. }
  1040. return group;
  1041. } );
  1042. } );
  1043. };
  1044. GLTFParser.prototype.loadCameras = function () {
  1045. var json = this.json;
  1046. return _each( json.cameras, function ( camera ) {
  1047. if ( camera.type == "perspective" && camera.perspective ) {
  1048. var yfov = camera.perspective.yfov;
  1049. var aspectRatio = camera.perspective.aspectRatio !== undefined ? camera.perspective.aspectRatio : 1;
  1050. // According to COLLADA spec...
  1051. // aspectRatio = xfov / yfov
  1052. var xfov = yfov * aspectRatio;
  1053. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  1054. if ( camera.name !== undefined ) _camera.name = camera.name;
  1055. if ( camera.extras ) _camera.userData = camera.extras;
  1056. return _camera;
  1057. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  1058. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  1059. if ( camera.name !== undefined ) _camera.name = camera.name;
  1060. if ( camera.extras ) _camera.userData = camera.extras;
  1061. return _camera;
  1062. }
  1063. } );
  1064. };
  1065. GLTFParser.prototype.loadSkins = function () {
  1066. var json = this.json;
  1067. return this._withDependencies( [
  1068. "accessors"
  1069. ] ).then( function ( dependencies ) {
  1070. return _each( json.skins, function ( skin ) {
  1071. var bindShapeMatrix = new THREE.Matrix4();
  1072. if ( skin.bindShapeMatrix !== undefined ) bindShapeMatrix.fromArray( skin.bindShapeMatrix );
  1073. var _skin = {
  1074. bindShapeMatrix: bindShapeMatrix,
  1075. jointNames: skin.jointNames,
  1076. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1077. };
  1078. return _skin;
  1079. } );
  1080. } );
  1081. };
  1082. GLTFParser.prototype.loadAnimations = function () {
  1083. var json = this.json;
  1084. return this._withDependencies( [
  1085. "accessors",
  1086. "nodes"
  1087. ] ).then( function ( dependencies ) {
  1088. return _each( json.animations, function ( animation, animationId ) {
  1089. var tracks = [];
  1090. for ( var channelId in animation.channels ) {
  1091. var channel = animation.channels[ channelId ];
  1092. var sampler = animation.samplers[ channel.sampler ];
  1093. if ( sampler ) {
  1094. var target = channel.target;
  1095. var name = target.id;
  1096. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1097. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1098. var inputAccessor = dependencies.accessors[ input ];
  1099. var outputAccessor = dependencies.accessors[ output ];
  1100. var node = dependencies.nodes[ name ];
  1101. if ( node ) {
  1102. node.updateMatrix();
  1103. node.matrixAutoUpdate = true;
  1104. var TypedKeyframeTrack = PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.rotation
  1105. ? THREE.QuaternionKeyframeTrack
  1106. : THREE.VectorKeyframeTrack;
  1107. var targetName = node.name ? node.name : node.uuid;
  1108. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1109. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1110. // buffers before creating a truncated copy to keep. Because buffers may
  1111. // be reused by other tracks, make copies here.
  1112. tracks.push( new TypedKeyframeTrack(
  1113. targetName + '.' + PATH_PROPERTIES[ target.path ],
  1114. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1115. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1116. interpolation
  1117. ) );
  1118. }
  1119. }
  1120. }
  1121. var name = animation.name !== undefined ? animation.name : "animation_" + animationId;
  1122. return new THREE.AnimationClip( name, undefined, tracks );
  1123. } );
  1124. } );
  1125. };
  1126. GLTFParser.prototype.loadNodes = function () {
  1127. var json = this.json;
  1128. var extensions = this.extensions;
  1129. var scope = this;
  1130. return _each( json.nodes, function ( node ) {
  1131. var matrix = new THREE.Matrix4();
  1132. var _node;
  1133. if ( node.jointName ) {
  1134. _node = new THREE.Bone();
  1135. _node.name = node.name !== undefined ? node.name : node.jointName;
  1136. _node.jointName = node.jointName;
  1137. } else {
  1138. _node = new THREE.Object3D();
  1139. if ( node.name !== undefined ) _node.name = node.name;
  1140. }
  1141. if ( node.extras ) _node.userData = node.extras;
  1142. if ( node.matrix !== undefined ) {
  1143. matrix.fromArray( node.matrix );
  1144. _node.applyMatrix( matrix );
  1145. } else {
  1146. if ( node.translation !== undefined ) {
  1147. _node.position.fromArray( node.translation );
  1148. }
  1149. if ( node.rotation !== undefined ) {
  1150. _node.quaternion.fromArray( node.rotation );
  1151. }
  1152. if ( node.scale !== undefined ) {
  1153. _node.scale.fromArray( node.scale );
  1154. }
  1155. }
  1156. return _node;
  1157. } ).then( function ( __nodes ) {
  1158. return scope._withDependencies( [
  1159. "meshes",
  1160. "skins",
  1161. "cameras"
  1162. ] ).then( function ( dependencies ) {
  1163. return _each( __nodes, function ( _node, nodeId ) {
  1164. var node = json.nodes[ nodeId ];
  1165. if ( node.meshes !== undefined ) {
  1166. for ( var meshId in node.meshes ) {
  1167. var mesh = node.meshes[ meshId ];
  1168. var group = dependencies.meshes[ mesh ];
  1169. if ( group === undefined ) {
  1170. console.warn( 'LegacyGLTFLoader: Couldn\'t find node "' + mesh + '".' );
  1171. continue;
  1172. }
  1173. for ( var childrenId in group.children ) {
  1174. var child = group.children[ childrenId ];
  1175. // clone Mesh to add to _node
  1176. var originalMaterial = child.material;
  1177. var originalGeometry = child.geometry;
  1178. var originalUserData = child.userData;
  1179. var originalName = child.name;
  1180. var material;
  1181. if ( originalMaterial.isDeferredShaderMaterial ) {
  1182. originalMaterial = material = originalMaterial.create();
  1183. } else {
  1184. material = originalMaterial;
  1185. }
  1186. switch ( child.type ) {
  1187. case 'LineSegments':
  1188. child = new THREE.LineSegments( originalGeometry, material );
  1189. break;
  1190. case 'LineLoop':
  1191. child = new THREE.LineLoop( originalGeometry, material );
  1192. break;
  1193. case 'Line':
  1194. child = new THREE.Line( originalGeometry, material );
  1195. break;
  1196. default:
  1197. child = new THREE.Mesh( originalGeometry, material );
  1198. }
  1199. child.castShadow = true;
  1200. child.userData = originalUserData;
  1201. child.name = originalName;
  1202. var skinEntry;
  1203. if ( node.skin ) {
  1204. skinEntry = dependencies.skins[ node.skin ];
  1205. }
  1206. // Replace Mesh with SkinnedMesh in library
  1207. if ( skinEntry ) {
  1208. var getJointNode = function ( jointId ) {
  1209. var keys = Object.keys( __nodes );
  1210. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  1211. var n = __nodes[ keys[ i ] ];
  1212. if ( n.jointName === jointId ) return n;
  1213. }
  1214. return null;
  1215. };
  1216. var geometry = originalGeometry;
  1217. var material = originalMaterial;
  1218. material.skinning = true;
  1219. child = new THREE.SkinnedMesh( geometry, material );
  1220. child.castShadow = true;
  1221. child.userData = originalUserData;
  1222. child.name = originalName;
  1223. var bones = [];
  1224. var boneInverses = [];
  1225. for ( var i = 0, l = skinEntry.jointNames.length; i < l; i ++ ) {
  1226. var jointId = skinEntry.jointNames[ i ];
  1227. var jointNode = getJointNode( jointId );
  1228. if ( jointNode ) {
  1229. bones.push( jointNode );
  1230. var m = skinEntry.inverseBindMatrices.array;
  1231. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  1232. boneInverses.push( mat );
  1233. } else {
  1234. console.warn( "WARNING: joint: '" + jointId + "' could not be found" );
  1235. }
  1236. }
  1237. child.bind( new THREE.Skeleton( bones, boneInverses ), skinEntry.bindShapeMatrix );
  1238. var buildBoneGraph = function ( parentJson, parentObject, property ) {
  1239. var children = parentJson[ property ];
  1240. if ( children === undefined ) return;
  1241. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1242. var nodeId = children[ i ];
  1243. var bone = __nodes[ nodeId ];
  1244. var boneJson = json.nodes[ nodeId ];
  1245. if ( bone !== undefined && bone.isBone === true && boneJson !== undefined ) {
  1246. parentObject.add( bone );
  1247. buildBoneGraph( boneJson, bone, 'children' );
  1248. }
  1249. }
  1250. };
  1251. buildBoneGraph( node, child, 'skeletons' );
  1252. }
  1253. _node.add( child );
  1254. }
  1255. }
  1256. }
  1257. if ( node.camera !== undefined ) {
  1258. var camera = dependencies.cameras[ node.camera ];
  1259. _node.add( camera );
  1260. }
  1261. if ( node.extensions
  1262. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ]
  1263. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ) {
  1264. var extensionLights = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].lights;
  1265. var light = extensionLights[ node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ];
  1266. _node.add( light );
  1267. }
  1268. return _node;
  1269. } );
  1270. } );
  1271. } );
  1272. };
  1273. GLTFParser.prototype.loadScenes = function () {
  1274. var json = this.json;
  1275. // scene node hierachy builder
  1276. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1277. var _node = allNodes[ nodeId ];
  1278. parentObject.add( _node );
  1279. var node = json.nodes[ nodeId ];
  1280. if ( node.children ) {
  1281. var children = node.children;
  1282. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1283. var child = children[ i ];
  1284. buildNodeHierachy( child, _node, allNodes );
  1285. }
  1286. }
  1287. }
  1288. return this._withDependencies( [
  1289. "nodes"
  1290. ] ).then( function ( dependencies ) {
  1291. return _each( json.scenes, function ( scene ) {
  1292. var _scene = new THREE.Scene();
  1293. if ( scene.name !== undefined ) _scene.name = scene.name;
  1294. if ( scene.extras ) _scene.userData = scene.extras;
  1295. var nodes = scene.nodes || [];
  1296. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1297. var nodeId = nodes[ i ];
  1298. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1299. }
  1300. _scene.traverse( function ( child ) {
  1301. // Register raw material meshes with LegacyGLTFLoader.Shaders
  1302. if ( child.material && child.material.isRawShaderMaterial ) {
  1303. child.gltfShader = new GLTFShader( child, dependencies.nodes );
  1304. child.onBeforeRender = function(renderer, scene, camera){
  1305. this.gltfShader.update(scene, camera);
  1306. };
  1307. }
  1308. } );
  1309. return _scene;
  1310. } );
  1311. } );
  1312. };
  1313. return LegacyGLTFLoader;
  1314. } )();