GLTF2Loader.js 50 KB

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