GLTF2Loader.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901
  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 ) {
  41. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) {
  42. extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json );
  43. }
  44. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  45. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  46. }
  47. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {
  48. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  49. }
  50. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_TECHNIQUE_WEBGL ) >= 0 ) {
  51. extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] = new GLTFTechniqueWebglExtension( json );
  52. }
  53. }
  54. console.time( 'GLTF2Loader' );
  55. var parser = new GLTFParser( json, extensions, {
  56. path: path || this.path,
  57. crossOrigin: this.crossOrigin
  58. } );
  59. parser.parse( function ( scene, scenes, cameras, animations ) {
  60. console.timeEnd( 'GLTF2Loader' );
  61. var glTF = {
  62. scene: scene,
  63. scenes: scenes,
  64. cameras: cameras,
  65. animations: animations
  66. };
  67. callback( glTF );
  68. } );
  69. }
  70. };
  71. /* GLTFREGISTRY */
  72. function GLTFRegistry() {
  73. var objects = {};
  74. return {
  75. get: function ( key ) {
  76. return objects[ key ];
  77. },
  78. add: function ( key, object ) {
  79. objects[ key ] = object;
  80. },
  81. remove: function ( key ) {
  82. delete objects[ key ];
  83. },
  84. removeAll: function () {
  85. objects = {};
  86. },
  87. update: function ( scene, camera ) {
  88. for ( var name in objects ) {
  89. var object = objects[ name ];
  90. if ( object.update ) {
  91. object.update( scene, camera );
  92. }
  93. }
  94. }
  95. };
  96. }
  97. /* GLTFSHADER */
  98. function GLTFShader( targetNode, allNodes ) {
  99. var boundUniforms = {};
  100. // bind each uniform to its source node
  101. var uniforms = targetNode.material.uniforms;
  102. for ( var uniformId in uniforms ) {
  103. var uniform = uniforms[ uniformId ];
  104. if ( uniform.semantic ) {
  105. var sourceNodeRef = uniform.node;
  106. var sourceNode = targetNode;
  107. if ( sourceNodeRef ) {
  108. sourceNode = allNodes[ sourceNodeRef ];
  109. }
  110. boundUniforms[ uniformId ] = {
  111. semantic: uniform.semantic,
  112. sourceNode: sourceNode,
  113. targetNode: targetNode,
  114. uniform: uniform
  115. };
  116. }
  117. }
  118. this.boundUniforms = boundUniforms;
  119. this._m4 = new THREE.Matrix4();
  120. }
  121. // Update - update all the uniform values
  122. GLTFShader.prototype.update = function ( scene, camera ) {
  123. var boundUniforms = this.boundUniforms;
  124. for ( var name in boundUniforms ) {
  125. var boundUniform = boundUniforms[ name ];
  126. switch ( boundUniform.semantic ) {
  127. case 'MODELVIEW':
  128. var m4 = boundUniform.uniform.value;
  129. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  130. break;
  131. case 'MODELVIEWINVERSETRANSPOSE':
  132. var m3 = boundUniform.uniform.value;
  133. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  134. m3.getNormalMatrix( this._m4 );
  135. break;
  136. case 'PROJECTION':
  137. var m4 = boundUniform.uniform.value;
  138. m4.copy( camera.projectionMatrix );
  139. break;
  140. case 'JOINTMATRIX':
  141. var m4v = boundUniform.uniform.value;
  142. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  143. // So it goes like this:
  144. // SkinnedMesh world matrix is already baked into MODELVIEW;
  145. // transform joints to local space,
  146. // then transform using joint's inverse
  147. m4v[ mi ]
  148. .getInverse( boundUniform.sourceNode.matrixWorld )
  149. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  150. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
  151. .multiply( boundUniform.targetNode.bindMatrix );
  152. }
  153. break;
  154. default :
  155. console.warn( 'THREE.GLTF2Loader: Unhandled shader semantic: ' + boundUniform.semantic );
  156. break;
  157. }
  158. }
  159. };
  160. /*********************************/
  161. /********** EXTENSIONS ***********/
  162. /*********************************/
  163. var EXTENSIONS = {
  164. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  165. KHR_LIGHTS: 'KHR_lights',
  166. KHR_MATERIALS_COMMON: 'KHR_materials_common',
  167. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  168. KHR_TECHNIQUE_WEBGL: 'KHR_technique_webgl',
  169. };
  170. /**
  171. * Lights Extension
  172. *
  173. * Specification: PENDING
  174. */
  175. function GLTFLightsExtension( json ) {
  176. this.name = EXTENSIONS.KHR_LIGHTS;
  177. this.lights = {};
  178. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {};
  179. var lights = extension.lights || {};
  180. for ( var lightId in lights ) {
  181. var light = lights[ lightId ];
  182. var lightNode;
  183. var color = new THREE.Color().fromArray( light.color );
  184. switch ( light.type ) {
  185. case 'directional':
  186. lightNode = new THREE.DirectionalLight( color );
  187. lightNode.position.set( 0, 0, 1 );
  188. break;
  189. case 'point':
  190. lightNode = new THREE.PointLight( color );
  191. break;
  192. case 'spot':
  193. lightNode = new THREE.SpotLight( color );
  194. lightNode.position.set( 0, 0, 1 );
  195. break;
  196. case 'ambient':
  197. lightNode = new THREE.AmbientLight( color );
  198. break;
  199. }
  200. if ( lightNode ) {
  201. if ( light.constantAttenuation !== undefined ) {
  202. lightNode.intensity = light.constantAttenuation;
  203. }
  204. if ( light.linearAttenuation !== undefined ) {
  205. lightNode.distance = 1 / light.linearAttenuation;
  206. }
  207. if ( light.quadraticAttenuation !== undefined ) {
  208. lightNode.decay = light.quadraticAttenuation;
  209. }
  210. if ( light.fallOffAngle !== undefined ) {
  211. lightNode.angle = light.fallOffAngle;
  212. }
  213. if ( light.fallOffExponent !== undefined ) {
  214. console.warn( 'THREE.GLTF2Loader:: light.fallOffExponent not currently supported.' );
  215. }
  216. lightNode.name = light.name || ( 'light_' + lightId );
  217. this.lights[ lightId ] = lightNode;
  218. }
  219. }
  220. }
  221. /**
  222. * Common Materials Extension
  223. *
  224. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_common
  225. */
  226. function GLTFMaterialsCommonExtension( json ) {
  227. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  228. }
  229. GLTFMaterialsCommonExtension.prototype.getMaterialType = function ( material ) {
  230. var khrMaterial = material.extensions[ this.name ];
  231. switch ( khrMaterial.type ) {
  232. case 'commonBlinn' :
  233. case 'commonPhong' :
  234. return THREE.MeshPhongMaterial;
  235. case 'commonLambert' :
  236. return THREE.MeshLambertMaterial;
  237. case 'commonConstant' :
  238. default :
  239. return THREE.MeshBasicMaterial;
  240. }
  241. };
  242. GLTFMaterialsCommonExtension.prototype.extendParams = function ( materialParams, material, dependencies ) {
  243. var khrMaterial = material.extensions[ this.name ];
  244. var keys = [];
  245. // TODO: Currently ignored: 'ambientFactor', 'ambientTexture'
  246. switch ( khrMaterial.type ) {
  247. case 'commonBlinn' :
  248. case 'commonPhong' :
  249. keys.push( 'diffuseFactor', 'diffuseTexture', 'specularFactor', 'specularTexture', 'shininessFactor' );
  250. break;
  251. case 'commonLambert' :
  252. keys.push( 'diffuseFactor', 'diffuseTexture' );
  253. break;
  254. case 'commonConstant' :
  255. default :
  256. break;
  257. }
  258. var materialValues = {};
  259. keys.forEach( function( v ) {
  260. if ( khrMaterial[ v ] !== undefined ) materialValues[ v ] = khrMaterial[ v ];
  261. } );
  262. if ( materialValues.diffuseFactor !== undefined ) {
  263. materialParams.color = new THREE.Color().fromArray( materialValues.diffuseFactor );
  264. materialParams.opacity = materialValues.diffuseFactor[ 3 ];
  265. }
  266. if ( materialValues.diffuseTexture !== undefined ) {
  267. materialParams.map = dependencies.textures[ materialValues.diffuseTexture.index ];
  268. }
  269. if ( materialValues.specularFactor !== undefined ) {
  270. materialParams.specular = new THREE.Color().fromArray( materialValues.specularFactor );
  271. }
  272. if ( materialValues.specularTexture !== undefined ) {
  273. materialParams.specularMap = dependencies.textures[ materialValues.specularTexture.index ];
  274. }
  275. if ( materialValues.shininessFactor !== undefined ) {
  276. materialParams.shininess = materialValues.shininessFactor;
  277. }
  278. };
  279. /* BINARY EXTENSION */
  280. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  281. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  282. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  283. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  284. function GLTFBinaryExtension( data ) {
  285. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  286. this.content = null;
  287. this.body = null;
  288. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  289. this.header = {
  290. magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
  291. version: headerView.getUint32( 4, true ),
  292. length: headerView.getUint32( 8, true )
  293. };
  294. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  295. throw new Error( 'THREE.GLTF2Loader: Unsupported glTF-Binary header.' );
  296. } else if ( this.header.version < 2.0 ) {
  297. throw new Error( 'THREE.GLTF2Loader: Legacy binary file detected. Use GLTFLoader instead.' );
  298. }
  299. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  300. var chunkIndex = 0;
  301. while ( chunkIndex < chunkView.byteLength ) {
  302. var chunkLength = chunkView.getUint32( chunkIndex, true );
  303. chunkIndex += 4;
  304. var chunkType = chunkView.getUint32( chunkIndex, true );
  305. chunkIndex += 4;
  306. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  307. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  308. this.content = convertUint8ArrayToString( contentArray );
  309. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  310. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  311. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  312. }
  313. // Clients must ignore chunks with unknown types.
  314. chunkIndex += chunkLength;
  315. }
  316. if ( this.content === null ) {
  317. throw new Error( 'THREE.GLTF2Loader: JSON content not found.' );
  318. }
  319. }
  320. /**
  321. * WebGL Technique Extension
  322. *
  323. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_technique_webgl
  324. */
  325. function GLTFTechniqueWebglExtension( json ) {
  326. this.name = EXTENSIONS.KHR_TECHNIQUE_WEBGL;
  327. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] ) || {};
  328. this.techniques = extension.techniques || {};
  329. this.programs = extension.programs || {};
  330. this.shaders = extension.shaders || {};
  331. }
  332. GLTFTechniqueWebglExtension.prototype.getMaterialType = function () {
  333. return DeferredShaderMaterial;
  334. };
  335. GLTFTechniqueWebglExtension.prototype.extendParams = function ( materialParams, material, dependencies ) {
  336. var extension = material[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ];
  337. var technique = dependencies.techniques[ extension.technique ];
  338. materialParams.uniforms = {};
  339. var program = dependencies.programs[ technique.program ];
  340. if ( program === undefined ) {
  341. return;
  342. }
  343. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  344. if ( ! materialParams.fragmentShader ) {
  345. throw new Error( 'THREE.GLTF2Loader: Missing fragment shader definition: ', program.fragmentShader );
  346. }
  347. var vertexShader = dependencies.shaders[ program.vertexShader ];
  348. if ( ! vertexShader ) {
  349. throw new Error( 'THREE.GLTF2Loader: Missing vertex shader definition: ', program.vertexShader );
  350. }
  351. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  352. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  353. var uniforms = technique.uniforms;
  354. for ( var uniformId in uniforms ) {
  355. var pname = uniforms[ uniformId ];
  356. var shaderParam = technique.parameters[ pname ];
  357. var ptype = shaderParam.type;
  358. if ( WEBGL_TYPE[ ptype ] ) {
  359. var pcount = shaderParam.count;
  360. var value;
  361. if ( material.values !== undefined ) value = material.values[ pname ];
  362. var uvalue = new WEBGL_TYPE[ ptype ]();
  363. var usemantic = shaderParam.semantic;
  364. var unode = shaderParam.node;
  365. switch ( ptype ) {
  366. case WEBGL_CONSTANTS.FLOAT:
  367. uvalue = shaderParam.value;
  368. if ( pname === 'transparency' ) {
  369. materialParams.transparent = true;
  370. }
  371. if ( value !== undefined ) {
  372. uvalue = value;
  373. }
  374. break;
  375. case WEBGL_CONSTANTS.FLOAT_VEC2:
  376. case WEBGL_CONSTANTS.FLOAT_VEC3:
  377. case WEBGL_CONSTANTS.FLOAT_VEC4:
  378. case WEBGL_CONSTANTS.FLOAT_MAT3:
  379. if ( shaderParam && shaderParam.value ) {
  380. uvalue.fromArray( shaderParam.value );
  381. }
  382. if ( value ) {
  383. uvalue.fromArray( value );
  384. }
  385. break;
  386. case WEBGL_CONSTANTS.FLOAT_MAT2:
  387. // what to do?
  388. console.warn( 'THREE.GLTF2Loader: FLOAT_MAT2 is not a supported uniform type.' );
  389. break;
  390. case WEBGL_CONSTANTS.FLOAT_MAT4:
  391. if ( pcount ) {
  392. uvalue = new Array( pcount );
  393. for ( var mi = 0; mi < pcount; mi ++ ) {
  394. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  395. }
  396. if ( shaderParam && shaderParam.value ) {
  397. var m4v = shaderParam.value;
  398. uvalue.fromArray( m4v );
  399. }
  400. if ( value ) {
  401. uvalue.fromArray( value );
  402. }
  403. } else {
  404. if ( shaderParam && shaderParam.value ) {
  405. var m4 = shaderParam.value;
  406. uvalue.fromArray( m4 );
  407. }
  408. if ( value ) {
  409. uvalue.fromArray( value );
  410. }
  411. }
  412. break;
  413. case WEBGL_CONSTANTS.SAMPLER_2D:
  414. if ( value !== undefined ) {
  415. uvalue = dependencies.textures[ value ];
  416. } else if ( shaderParam.value !== undefined ) {
  417. uvalue = dependencies.textures[ shaderParam.value ];
  418. } else {
  419. uvalue = null;
  420. }
  421. break;
  422. }
  423. materialParams.uniforms[ uniformId ] = {
  424. value: uvalue,
  425. semantic: usemantic,
  426. node: unode
  427. };
  428. } else {
  429. throw new Error( 'THREE.GLTF2Loader: Unknown shader uniform param type: ' + ptype );
  430. }
  431. }
  432. var states = technique.states || {};
  433. var enables = states.enable || [];
  434. var functions = states.functions || {};
  435. var enableCullFace = false;
  436. var enableDepthTest = false;
  437. var enableBlend = false;
  438. for ( var i = 0, il = enables.length; i < il; i ++ ) {
  439. var enable = enables[ i ];
  440. switch ( STATES_ENABLES[ enable ] ) {
  441. case 'CULL_FACE':
  442. enableCullFace = true;
  443. break;
  444. case 'DEPTH_TEST':
  445. enableDepthTest = true;
  446. break;
  447. case 'BLEND':
  448. enableBlend = true;
  449. break;
  450. // TODO: implement
  451. case 'SCISSOR_TEST':
  452. case 'POLYGON_OFFSET_FILL':
  453. case 'SAMPLE_ALPHA_TO_COVERAGE':
  454. break;
  455. default:
  456. throw new Error( 'THREE.GLTF2Loader: Unknown technique.states.enable: ' + enable );
  457. }
  458. }
  459. if ( enableCullFace ) {
  460. materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : THREE.FrontSide;
  461. } else {
  462. materialParams.side = THREE.DoubleSide;
  463. }
  464. materialParams.depthTest = enableDepthTest;
  465. materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : THREE.LessDepth;
  466. materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true;
  467. materialParams.blending = enableBlend ? THREE.CustomBlending : THREE.NoBlending;
  468. materialParams.transparent = enableBlend;
  469. var blendEquationSeparate = functions.blendEquationSeparate;
  470. if ( blendEquationSeparate !== undefined ) {
  471. materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ];
  472. materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ];
  473. } else {
  474. materialParams.blendEquation = THREE.AddEquation;
  475. materialParams.blendEquationAlpha = THREE.AddEquation;
  476. }
  477. var blendFuncSeparate = functions.blendFuncSeparate;
  478. if ( blendFuncSeparate !== undefined ) {
  479. materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ];
  480. materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ];
  481. materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ];
  482. materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ];
  483. } else {
  484. materialParams.blendSrc = THREE.OneFactor;
  485. materialParams.blendDst = THREE.ZeroFactor;
  486. materialParams.blendSrcAlpha = THREE.OneFactor;
  487. materialParams.blendDstAlpha = THREE.ZeroFactor;
  488. }
  489. };
  490. /**
  491. * Specular-Glossiness Extension
  492. *
  493. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  494. */
  495. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  496. return {
  497. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  498. getMaterialType: function () {
  499. return THREE.ShaderMaterial;
  500. },
  501. extendParams: function ( params, material, dependencies ) {
  502. // specification
  503. // https://github.com/sbtron/glTF/tree/KHRpbrSpecGloss/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  504. var pbrSpecularGlossiness = material.extensions[ this.name ];
  505. var shader = THREE.ShaderLib[ 'standard' ];
  506. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  507. var specularMapParsFragmentChunk = [
  508. '#ifdef USE_SPECULARMAP',
  509. ' uniform sampler2D specularMap;',
  510. '#endif'
  511. ].join( '\n' );
  512. var glossinessMapParsFragmentChunk = [
  513. '#ifdef USE_GLOSSINESSMAP',
  514. ' uniform sampler2D glossinessMap;',
  515. '#endif'
  516. ].join( '\n' );
  517. var specularMapFragmentChunk = [
  518. 'vec3 specularFactor = specular;',
  519. '#ifdef USE_SPECULARMAP',
  520. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  521. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  522. ' specularFactor *= texelSpecular.rgb;',
  523. '#endif'
  524. ].join( '\n' );
  525. var glossinessMapFragmentChunk = [
  526. 'float glossinessFactor = glossiness;',
  527. '#ifdef USE_GLOSSINESSMAP',
  528. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  529. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  530. ' glossinessFactor *= texelGlossiness.a;',
  531. '#endif'
  532. ].join( '\n' );
  533. var lightPhysicalFragmentChunk = [
  534. 'PhysicalMaterial material;',
  535. 'material.diffuseColor = diffuseColor.rgb;',
  536. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  537. 'material.specularColor = specularFactor.rgb;',
  538. ].join( '\n' );
  539. var fragmentShader = shader.fragmentShader
  540. .replace( '#include <specularmap_fragment>', '' )
  541. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  542. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  543. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  544. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  545. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  546. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  547. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  548. delete uniforms.roughness;
  549. delete uniforms.metalness;
  550. delete uniforms.roughnessMap;
  551. delete uniforms.metalnessMap;
  552. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  553. uniforms.glossiness = { value: 0.5 };
  554. uniforms.specularMap = { value: null };
  555. uniforms.glossinessMap = { value: null };
  556. params.vertexShader = shader.vertexShader;
  557. params.fragmentShader = fragmentShader;
  558. params.uniforms = uniforms;
  559. params.defines = { 'STANDARD': '' };
  560. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  561. params.opacity = 1.0;
  562. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  563. var array = pbrSpecularGlossiness.diffuseFactor;
  564. params.color.fromArray( array );
  565. params.opacity = array[ 3 ];
  566. }
  567. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  568. params.map = dependencies.textures[ pbrSpecularGlossiness.diffuseTexture.index ];
  569. }
  570. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  571. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  572. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  573. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  574. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  575. }
  576. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  577. params.glossinessMap = dependencies.textures[ pbrSpecularGlossiness.specularGlossinessTexture.index ];
  578. params.specularMap = dependencies.textures[ pbrSpecularGlossiness.specularGlossinessTexture.index ];
  579. }
  580. },
  581. createMaterial: function ( params ) {
  582. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  583. var material = new THREE.ShaderMaterial( {
  584. defines: params.defines,
  585. vertexShader: params.vertexShader,
  586. fragmentShader: params.fragmentShader,
  587. uniforms: params.uniforms,
  588. fog: true,
  589. lights: true,
  590. opacity: params.opacity,
  591. transparent: params.transparent
  592. } );
  593. material.color = params.color;
  594. material.map = params.map === undefined ? null : params.map;
  595. material.lightMap = null;
  596. material.lightMapIntensity = 1.0;
  597. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  598. material.aoMapIntensity = 1.0;
  599. material.emissive = params.emissive;
  600. material.emissiveIntensity = 1.0;
  601. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  602. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  603. material.bumpScale = 1;
  604. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  605. material.normalScale = new THREE.Vector2( 1, 1 );
  606. material.displacementMap = null;
  607. material.displacementScale = 1;
  608. material.displacementBias = 0;
  609. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  610. material.specular = params.specular;
  611. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  612. material.glossiness = params.glossiness;
  613. material.alphaMap = null;
  614. material.envMap = params.envMap === undefined ? null : params.envMap;
  615. material.envMapIntensity = 1.0;
  616. material.refractionRatio = 0.98;
  617. material.extensions.derivatives = true;
  618. return material;
  619. },
  620. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  621. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  622. var uniforms = material.uniforms;
  623. var defines = material.defines;
  624. uniforms.opacity.value = material.opacity;
  625. uniforms.diffuse.value.copy( material.color );
  626. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  627. uniforms.map.value = material.map;
  628. uniforms.specularMap.value = material.specularMap;
  629. uniforms.alphaMap.value = material.alphaMap;
  630. uniforms.lightMap.value = material.lightMap;
  631. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  632. uniforms.aoMap.value = material.aoMap;
  633. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  634. // uv repeat and offset setting priorities
  635. // 1. color map
  636. // 2. specular map
  637. // 3. normal map
  638. // 4. bump map
  639. // 5. alpha map
  640. // 6. emissive map
  641. var uvScaleMap;
  642. if ( material.map ) {
  643. uvScaleMap = material.map;
  644. } else if ( material.specularMap ) {
  645. uvScaleMap = material.specularMap;
  646. } else if ( material.displacementMap ) {
  647. uvScaleMap = material.displacementMap;
  648. } else if ( material.normalMap ) {
  649. uvScaleMap = material.normalMap;
  650. } else if ( material.bumpMap ) {
  651. uvScaleMap = material.bumpMap;
  652. } else if ( material.glossinessMap ) {
  653. uvScaleMap = material.glossinessMap;
  654. } else if ( material.alphaMap ) {
  655. uvScaleMap = material.alphaMap;
  656. } else if ( material.emissiveMap ) {
  657. uvScaleMap = material.emissiveMap;
  658. }
  659. if ( uvScaleMap !== undefined ) {
  660. // backwards compatibility
  661. if ( uvScaleMap.isWebGLRenderTarget ) {
  662. uvScaleMap = uvScaleMap.texture;
  663. }
  664. var offset = uvScaleMap.offset;
  665. var repeat = uvScaleMap.repeat;
  666. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  667. }
  668. uniforms.envMap.value = material.envMap;
  669. uniforms.envMapIntensity.value = material.envMapIntensity;
  670. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? -1 : 1;
  671. uniforms.refractionRatio.value = material.refractionRatio;
  672. uniforms.specular.value.copy( material.specular );
  673. uniforms.glossiness.value = material.glossiness;
  674. uniforms.glossinessMap.value = material.glossinessMap;
  675. uniforms.emissiveMap.value = material.emissiveMap;
  676. uniforms.bumpMap.value = material.bumpMap;
  677. uniforms.normalMap.value = material.normalMap;
  678. uniforms.displacementMap.value = material.displacementMap;
  679. uniforms.displacementScale.value = material.displacementScale;
  680. uniforms.displacementBias.value = material.displacementBias;
  681. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  682. defines.USE_GLOSSINESSMAP = '';
  683. // set USE_ROUGHNESSMAP to enable vUv
  684. defines.USE_ROUGHNESSMAP = ''
  685. }
  686. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  687. delete defines.USE_GLOSSINESSMAP;
  688. delete defines.USE_ROUGHNESSMAP;
  689. }
  690. }
  691. };
  692. }
  693. /*********************************/
  694. /********** INTERNALS ************/
  695. /*********************************/
  696. /* CONSTANTS */
  697. var WEBGL_CONSTANTS = {
  698. FLOAT: 5126,
  699. //FLOAT_MAT2: 35674,
  700. FLOAT_MAT3: 35675,
  701. FLOAT_MAT4: 35676,
  702. FLOAT_VEC2: 35664,
  703. FLOAT_VEC3: 35665,
  704. FLOAT_VEC4: 35666,
  705. LINEAR: 9729,
  706. REPEAT: 10497,
  707. SAMPLER_2D: 35678,
  708. TRIANGLES: 4,
  709. LINES: 1,
  710. UNSIGNED_BYTE: 5121,
  711. UNSIGNED_SHORT: 5123,
  712. VERTEX_SHADER: 35633,
  713. FRAGMENT_SHADER: 35632
  714. };
  715. var WEBGL_TYPE = {
  716. 5126: Number,
  717. //35674: THREE.Matrix2,
  718. 35675: THREE.Matrix3,
  719. 35676: THREE.Matrix4,
  720. 35664: THREE.Vector2,
  721. 35665: THREE.Vector3,
  722. 35666: THREE.Vector4,
  723. 35678: THREE.Texture
  724. };
  725. var WEBGL_COMPONENT_TYPES = {
  726. 5120: Int8Array,
  727. 5121: Uint8Array,
  728. 5122: Int16Array,
  729. 5123: Uint16Array,
  730. 5125: Uint32Array,
  731. 5126: Float32Array
  732. };
  733. var WEBGL_FILTERS = {
  734. 9728: THREE.NearestFilter,
  735. 9729: THREE.LinearFilter,
  736. 9984: THREE.NearestMipMapNearestFilter,
  737. 9985: THREE.LinearMipMapNearestFilter,
  738. 9986: THREE.NearestMipMapLinearFilter,
  739. 9987: THREE.LinearMipMapLinearFilter
  740. };
  741. var WEBGL_WRAPPINGS = {
  742. 33071: THREE.ClampToEdgeWrapping,
  743. 33648: THREE.MirroredRepeatWrapping,
  744. 10497: THREE.RepeatWrapping
  745. };
  746. var WEBGL_TEXTURE_FORMATS = {
  747. 6406: THREE.AlphaFormat,
  748. 6407: THREE.RGBFormat,
  749. 6408: THREE.RGBAFormat,
  750. 6409: THREE.LuminanceFormat,
  751. 6410: THREE.LuminanceAlphaFormat
  752. };
  753. var WEBGL_TEXTURE_DATATYPES = {
  754. 5121: THREE.UnsignedByteType,
  755. 32819: THREE.UnsignedShort4444Type,
  756. 32820: THREE.UnsignedShort5551Type,
  757. 33635: THREE.UnsignedShort565Type
  758. };
  759. var WEBGL_SIDES = {
  760. 1028: THREE.BackSide, // Culling front
  761. 1029: THREE.FrontSide // Culling back
  762. //1032: THREE.NoSide // Culling front and back, what to do?
  763. };
  764. var WEBGL_DEPTH_FUNCS = {
  765. 512: THREE.NeverDepth,
  766. 513: THREE.LessDepth,
  767. 514: THREE.EqualDepth,
  768. 515: THREE.LessEqualDepth,
  769. 516: THREE.GreaterEqualDepth,
  770. 517: THREE.NotEqualDepth,
  771. 518: THREE.GreaterEqualDepth,
  772. 519: THREE.AlwaysDepth
  773. };
  774. var WEBGL_BLEND_EQUATIONS = {
  775. 32774: THREE.AddEquation,
  776. 32778: THREE.SubtractEquation,
  777. 32779: THREE.ReverseSubtractEquation
  778. };
  779. var WEBGL_BLEND_FUNCS = {
  780. 0: THREE.ZeroFactor,
  781. 1: THREE.OneFactor,
  782. 768: THREE.SrcColorFactor,
  783. 769: THREE.OneMinusSrcColorFactor,
  784. 770: THREE.SrcAlphaFactor,
  785. 771: THREE.OneMinusSrcAlphaFactor,
  786. 772: THREE.DstAlphaFactor,
  787. 773: THREE.OneMinusDstAlphaFactor,
  788. 774: THREE.DstColorFactor,
  789. 775: THREE.OneMinusDstColorFactor,
  790. 776: THREE.SrcAlphaSaturateFactor
  791. // The followings are not supported by Three.js yet
  792. //32769: CONSTANT_COLOR,
  793. //32770: ONE_MINUS_CONSTANT_COLOR,
  794. //32771: CONSTANT_ALPHA,
  795. //32772: ONE_MINUS_CONSTANT_COLOR
  796. };
  797. var WEBGL_TYPE_SIZES = {
  798. 'SCALAR': 1,
  799. 'VEC2': 2,
  800. 'VEC3': 3,
  801. 'VEC4': 4,
  802. 'MAT2': 4,
  803. 'MAT3': 9,
  804. 'MAT4': 16
  805. };
  806. var PATH_PROPERTIES = {
  807. scale: 'scale',
  808. translation: 'position',
  809. rotation: 'quaternion',
  810. weights: 'morphTargetInfluences'
  811. };
  812. var INTERPOLATION = {
  813. LINEAR: THREE.InterpolateLinear,
  814. STEP: THREE.InterpolateDiscrete
  815. };
  816. var STATES_ENABLES = {
  817. 2884: 'CULL_FACE',
  818. 2929: 'DEPTH_TEST',
  819. 3042: 'BLEND',
  820. 3089: 'SCISSOR_TEST',
  821. 32823: 'POLYGON_OFFSET_FILL',
  822. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  823. };
  824. var ALPHA_MODES = {
  825. OPAQUE: 'OPAQUE',
  826. MASK: 'MASK',
  827. BLEND: 'BLEND'
  828. };
  829. /* UTILITY FUNCTIONS */
  830. function _each( object, callback, thisObj ) {
  831. if ( !object ) {
  832. return Promise.resolve();
  833. }
  834. var results;
  835. var fns = [];
  836. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  837. results = [];
  838. var length = object.length;
  839. for ( var idx = 0; idx < length; idx ++ ) {
  840. var value = callback.call( thisObj || this, object[ idx ], idx );
  841. if ( value ) {
  842. fns.push( value );
  843. if ( value instanceof Promise ) {
  844. value.then( function( key, value ) {
  845. results[ key ] = value;
  846. }.bind( this, idx ));
  847. } else {
  848. results[ idx ] = value;
  849. }
  850. }
  851. }
  852. } else {
  853. results = {};
  854. for ( var key in object ) {
  855. if ( object.hasOwnProperty( key ) ) {
  856. var value = callback.call( thisObj || this, object[ key ], key );
  857. if ( value ) {
  858. fns.push( value );
  859. if ( value instanceof Promise ) {
  860. value.then( function( key, value ) {
  861. results[ key ] = value;
  862. }.bind( this, key ));
  863. } else {
  864. results[ key ] = value;
  865. }
  866. }
  867. }
  868. }
  869. }
  870. return Promise.all( fns ).then( function() {
  871. return results;
  872. });
  873. }
  874. function resolveURL( url, path ) {
  875. // Invalid URL
  876. if ( typeof url !== 'string' || url === '' )
  877. return '';
  878. // Absolute URL http://,https://,//
  879. if ( /^(https?:)?\/\//i.test( url ) ) {
  880. return url;
  881. }
  882. // Data URI
  883. if ( /^data:.*,.*$/i.test( url ) ) {
  884. return url;
  885. }
  886. // Blob URL
  887. if ( /^blob:.*$/i.test( url ) ) {
  888. return url;
  889. }
  890. // Relative URL
  891. return ( path || '' ) + url;
  892. }
  893. function convertUint8ArrayToString( array ) {
  894. if ( window.TextDecoder !== undefined ) {
  895. return new TextDecoder().decode( array );
  896. }
  897. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  898. // throws a "maximum call stack size exceeded" error for large arrays.
  899. var s = '';
  900. for ( var i = 0, il = array.length; i < il; i ++ ) {
  901. s += String.fromCharCode( array[ i ] );
  902. }
  903. return s;
  904. }
  905. // Three.js seems too dependent on attribute names so globally
  906. // replace those in the shader code
  907. function replaceTHREEShaderAttributes( shaderText, technique ) {
  908. // Expected technique attributes
  909. var attributes = {};
  910. for ( var attributeId in technique.attributes ) {
  911. var pname = technique.attributes[ attributeId ];
  912. var param = technique.parameters[ pname ];
  913. var atype = param.type;
  914. var semantic = param.semantic;
  915. attributes[ attributeId ] = {
  916. type: atype,
  917. semantic: semantic
  918. };
  919. }
  920. // Figure out which attributes to change in technique
  921. var shaderParams = technique.parameters;
  922. var shaderAttributes = technique.attributes;
  923. var params = {};
  924. for ( var attributeId in attributes ) {
  925. var pname = shaderAttributes[ attributeId ];
  926. var shaderParam = shaderParams[ pname ];
  927. var semantic = shaderParam.semantic;
  928. if ( semantic ) {
  929. params[ attributeId ] = shaderParam;
  930. }
  931. }
  932. for ( var pname in params ) {
  933. var param = params[ pname ];
  934. var semantic = param.semantic;
  935. var regEx = new RegExp( '\\b' + pname + '\\b', 'g' );
  936. switch ( semantic ) {
  937. case 'POSITION':
  938. shaderText = shaderText.replace( regEx, 'position' );
  939. break;
  940. case 'NORMAL':
  941. shaderText = shaderText.replace( regEx, 'normal' );
  942. break;
  943. case 'TEXCOORD_0':
  944. case 'TEXCOORD0':
  945. case 'TEXCOORD':
  946. shaderText = shaderText.replace( regEx, 'uv' );
  947. break;
  948. case 'TEXCOORD_1':
  949. shaderText = shaderText.replace( regEx, 'uv2' );
  950. break;
  951. case 'COLOR_0':
  952. case 'COLOR0':
  953. case 'COLOR':
  954. shaderText = shaderText.replace( regEx, 'color' );
  955. break;
  956. case 'WEIGHTS_0':
  957. case 'WEIGHT': // WEIGHT semantic deprecated.
  958. shaderText = shaderText.replace( regEx, 'skinWeight' );
  959. break;
  960. case 'JOINTS_0':
  961. case 'JOINT': // JOINT semantic deprecated.
  962. shaderText = shaderText.replace( regEx, 'skinIndex' );
  963. break;
  964. }
  965. }
  966. return shaderText;
  967. }
  968. /**
  969. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  970. */
  971. function createDefaultMaterial() {
  972. return new THREE.MeshStandardMaterial( {
  973. color: 0xFFFFFF,
  974. emissive: 0x000000,
  975. metalness: 1,
  976. roughness: 1,
  977. transparent: false,
  978. depthTest: true,
  979. side: THREE.FrontSide
  980. } );
  981. }
  982. // Deferred constructor for RawShaderMaterial types
  983. function DeferredShaderMaterial( params ) {
  984. this.isDeferredShaderMaterial = true;
  985. this.params = params;
  986. }
  987. DeferredShaderMaterial.prototype.create = function () {
  988. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  989. for ( var uniformId in this.params.uniforms ) {
  990. var originalUniform = this.params.uniforms[ uniformId ];
  991. if ( originalUniform.value instanceof THREE.Texture ) {
  992. uniforms[ uniformId ].value = originalUniform.value;
  993. uniforms[ uniformId ].value.needsUpdate = true;
  994. }
  995. uniforms[ uniformId ].semantic = originalUniform.semantic;
  996. uniforms[ uniformId ].node = originalUniform.node;
  997. }
  998. this.params.uniforms = uniforms;
  999. return new THREE.RawShaderMaterial( this.params );
  1000. };
  1001. /* GLTF PARSER */
  1002. function GLTFParser( json, extensions, options ) {
  1003. this.json = json || {};
  1004. this.extensions = extensions || {};
  1005. this.options = options || {};
  1006. // loader object cache
  1007. this.cache = new GLTFRegistry();
  1008. }
  1009. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  1010. var _dependencies = {};
  1011. for ( var i = 0; i < dependencies.length; i ++ ) {
  1012. var dependency = dependencies[ i ];
  1013. var fnName = 'load' + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  1014. var cached = this.cache.get( dependency );
  1015. if ( cached !== undefined ) {
  1016. _dependencies[ dependency ] = cached;
  1017. } else if ( this[ fnName ] ) {
  1018. var fn = this[ fnName ]();
  1019. this.cache.add( dependency, fn );
  1020. _dependencies[ dependency ] = fn;
  1021. }
  1022. }
  1023. return _each( _dependencies, function ( dependency ) {
  1024. return dependency;
  1025. } );
  1026. };
  1027. GLTFParser.prototype.parse = function ( callback ) {
  1028. var json = this.json;
  1029. // Clear the loader cache
  1030. this.cache.removeAll();
  1031. // Fire the callback on complete
  1032. this._withDependencies( [
  1033. 'scenes',
  1034. 'cameras',
  1035. 'animations'
  1036. ] ).then( function ( dependencies ) {
  1037. var scenes = [];
  1038. for ( var name in dependencies.scenes ) {
  1039. scenes.push( dependencies.scenes[ name ] );
  1040. }
  1041. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  1042. var cameras = [];
  1043. for ( var name in dependencies.cameras ) {
  1044. var camera = dependencies.cameras[ name ];
  1045. cameras.push( camera );
  1046. }
  1047. var animations = [];
  1048. for ( var name in dependencies.animations ) {
  1049. animations.push( dependencies.animations[ name ] );
  1050. }
  1051. callback( scene, scenes, cameras, animations );
  1052. } );
  1053. };
  1054. GLTFParser.prototype.loadShaders = function () {
  1055. var json = this.json;
  1056. var options = this.options;
  1057. var extensions = this.extensions;
  1058. return this._withDependencies( [
  1059. 'bufferViews'
  1060. ] ).then( function ( dependencies ) {
  1061. var shaders = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] !== undefined ? extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].shaders : json.shaders;
  1062. if ( shaders === undefined ) shaders = {};
  1063. return _each( shaders, function ( shader ) {
  1064. if ( shader.bufferView !== undefined ) {
  1065. var bufferView = dependencies.bufferViews[ shader.bufferView ];
  1066. var array = new Uint8Array( bufferView );
  1067. return convertUint8ArrayToString( array );
  1068. }
  1069. return new Promise( function ( resolve ) {
  1070. var loader = new THREE.FileLoader();
  1071. loader.setResponseType( 'text' );
  1072. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  1073. resolve( shaderText );
  1074. } );
  1075. } );
  1076. } );
  1077. } );
  1078. };
  1079. GLTFParser.prototype.loadBuffers = function () {
  1080. var json = this.json;
  1081. var extensions = this.extensions;
  1082. var options = this.options;
  1083. return _each( json.buffers, function ( buffer, name ) {
  1084. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  1085. // If present, GLB container is required to be the first buffer.
  1086. if ( buffer.uri === undefined && name === 0 ) {
  1087. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  1088. }
  1089. return new Promise( function ( resolve ) {
  1090. var loader = new THREE.FileLoader();
  1091. loader.setResponseType( 'arraybuffer' );
  1092. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  1093. resolve( buffer );
  1094. } );
  1095. } );
  1096. } else {
  1097. console.warn( 'THREE.GLTF2Loader: %s buffer type is not supported.', buffer.type );
  1098. }
  1099. } );
  1100. };
  1101. GLTFParser.prototype.loadBufferViews = function () {
  1102. var json = this.json;
  1103. return this._withDependencies( [
  1104. 'buffers'
  1105. ] ).then( function ( dependencies ) {
  1106. return _each( json.bufferViews, function ( bufferView ) {
  1107. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  1108. var byteLength = bufferView.byteLength || 0;
  1109. var byteOffset = bufferView.byteOffset || 0;
  1110. return arraybuffer.slice( byteOffset, byteOffset + byteLength );
  1111. } );
  1112. } );
  1113. };
  1114. GLTFParser.prototype.loadAccessors = function () {
  1115. var json = this.json;
  1116. return this._withDependencies( [
  1117. 'bufferViews'
  1118. ] ).then( function ( dependencies ) {
  1119. return _each( json.accessors, function ( accessor ) {
  1120. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  1121. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  1122. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  1123. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1124. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1125. var itemBytes = elementBytes * itemSize;
  1126. var byteStride = json.bufferViews[ accessor.bufferView ].byteStride;
  1127. var array;
  1128. // The buffer is not interleaved if the stride is the item size in bytes.
  1129. if ( byteStride && byteStride !== itemBytes ) {
  1130. // Use the full buffer if it's interleaved.
  1131. array = new TypedArray( arraybuffer );
  1132. // Integer parameters to IB/IBA are in array elements, not bytes.
  1133. var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1134. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  1135. } else {
  1136. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  1137. return new THREE.BufferAttribute( array, itemSize );
  1138. }
  1139. } );
  1140. } );
  1141. };
  1142. GLTFParser.prototype.loadTextures = function () {
  1143. var json = this.json;
  1144. var options = this.options;
  1145. return this._withDependencies( [
  1146. 'bufferViews'
  1147. ] ).then( function ( dependencies ) {
  1148. return _each( json.textures, function ( texture ) {
  1149. if ( texture.source !== undefined ) {
  1150. return new Promise( function ( resolve ) {
  1151. var source = json.images[ texture.source ];
  1152. var sourceUri = source.uri;
  1153. var urlCreator;
  1154. if ( source.bufferView !== undefined ) {
  1155. var bufferView = dependencies.bufferViews[ source.bufferView ];
  1156. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1157. urlCreator = window.URL || window.webkitURL;
  1158. sourceUri = urlCreator.createObjectURL( blob );
  1159. }
  1160. var textureLoader = THREE.Loader.Handlers.get( sourceUri );
  1161. if ( textureLoader === null ) {
  1162. textureLoader = new THREE.TextureLoader();
  1163. }
  1164. textureLoader.setCrossOrigin( options.crossOrigin );
  1165. textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
  1166. if ( urlCreator !== undefined ) {
  1167. urlCreator.revokeObjectURL( sourceUri );
  1168. }
  1169. _texture.flipY = false;
  1170. if ( texture.name !== undefined ) _texture.name = texture.name;
  1171. _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat;
  1172. if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {
  1173. console.warn( 'THREE.GLTF2Loader: Three.js does not support texture internalFormat which is different from texture format. ' +
  1174. 'internalFormat will be forced to be the same value as format.' );
  1175. }
  1176. _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;
  1177. var samplers = json.samplers || {};
  1178. var sampler = samplers[ texture.sampler ] || {};
  1179. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1180. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  1181. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1182. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1183. resolve( _texture );
  1184. }, undefined, function () {
  1185. resolve();
  1186. } );
  1187. } );
  1188. }
  1189. } );
  1190. } );
  1191. };
  1192. GLTFParser.prototype.loadMaterials = function () {
  1193. var json = this.json;
  1194. var extensions = this.extensions;
  1195. return this._withDependencies( [
  1196. 'shaders',
  1197. 'textures'
  1198. ] ).then( function ( dependencies ) {
  1199. return _each( json.materials, function ( material ) {
  1200. var materialType;
  1201. var materialParams = {};
  1202. var materialExtensions = material.extensions || {};
  1203. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  1204. materialType = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].getMaterialType( material );
  1205. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].extendParams( materialParams, material, dependencies );
  1206. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1207. materialType = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].getMaterialType( material );
  1208. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].extendParams( materialParams, material, dependencies );
  1209. } else if ( materialExtensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] ) {
  1210. materialType = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].getMaterialType( material );
  1211. extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].extendParams( materialParams, material, dependencies );
  1212. } else if ( material.pbrMetallicRoughness !== undefined ) {
  1213. // Specification:
  1214. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1215. materialType = THREE.MeshStandardMaterial;
  1216. var metallicRoughness = material.pbrMetallicRoughness;
  1217. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1218. materialParams.opacity = 1.0;
  1219. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1220. var array = metallicRoughness.baseColorFactor;
  1221. materialParams.color.fromArray( array );
  1222. materialParams.opacity = array[ 3 ];
  1223. }
  1224. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1225. materialParams.map = dependencies.textures[ metallicRoughness.baseColorTexture.index ];
  1226. }
  1227. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1228. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1229. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1230. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  1231. materialParams.metalnessMap = dependencies.textures[ textureIndex ];
  1232. materialParams.roughnessMap = dependencies.textures[ textureIndex ];
  1233. }
  1234. } else {
  1235. materialType = THREE.MeshPhongMaterial;
  1236. }
  1237. if ( material.doubleSided === true ) {
  1238. materialParams.side = THREE.DoubleSide;
  1239. }
  1240. var alphaMode = material.alphaMode || ALPHA_MODES.OPAQUE;
  1241. if ( alphaMode !== ALPHA_MODES.OPAQUE ) {
  1242. materialParams.transparent = true;
  1243. } else {
  1244. materialParams.transparent = false;
  1245. }
  1246. if ( material.normalTexture !== undefined ) {
  1247. materialParams.normalMap = dependencies.textures[ material.normalTexture.index ];
  1248. }
  1249. if ( material.occlusionTexture !== undefined ) {
  1250. materialParams.aoMap = dependencies.textures[ material.occlusionTexture.index ];
  1251. }
  1252. if ( material.emissiveFactor !== undefined ) {
  1253. if ( materialType === THREE.MeshBasicMaterial ) {
  1254. materialParams.color = new THREE.Color().fromArray( material.emissiveFactor );
  1255. } else {
  1256. materialParams.emissive = new THREE.Color().fromArray( material.emissiveFactor );
  1257. }
  1258. }
  1259. if ( material.emissiveTexture !== undefined ) {
  1260. if ( materialType === THREE.MeshBasicMaterial ) {
  1261. materialParams.map = dependencies.textures[ material.emissiveTexture.index ];
  1262. } else {
  1263. materialParams.emissiveMap = dependencies.textures[ material.emissiveTexture.index ];
  1264. }
  1265. }
  1266. var _material;
  1267. if ( materialType === THREE.ShaderMaterial ) {
  1268. _material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1269. } else {
  1270. _material = new materialType( materialParams );
  1271. }
  1272. if ( material.name !== undefined ) _material.name = material.name;
  1273. return _material;
  1274. } );
  1275. } );
  1276. };
  1277. GLTFParser.prototype.loadMeshes = function () {
  1278. var json = this.json;
  1279. return this._withDependencies( [
  1280. 'accessors',
  1281. 'materials'
  1282. ] ).then( function ( dependencies ) {
  1283. return _each( json.meshes, function ( mesh ) {
  1284. var group = new THREE.Group();
  1285. if ( mesh.name !== undefined ) group.name = mesh.name;
  1286. if ( mesh.extras ) group.userData = mesh.extras;
  1287. var primitives = mesh.primitives || [];
  1288. for ( var name in primitives ) {
  1289. var primitive = primitives[ name ];
  1290. var material = primitive.material !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial();
  1291. var geometry;
  1292. var meshNode;
  1293. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  1294. geometry = new THREE.BufferGeometry();
  1295. var attributes = primitive.attributes;
  1296. for ( var attributeId in attributes ) {
  1297. var attributeEntry = attributes[ attributeId ];
  1298. if ( attributeEntry === undefined ) return;
  1299. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1300. switch ( attributeId ) {
  1301. case 'POSITION':
  1302. geometry.addAttribute( 'position', bufferAttribute );
  1303. break;
  1304. case 'NORMAL':
  1305. geometry.addAttribute( 'normal', bufferAttribute );
  1306. break;
  1307. case 'TEXCOORD_0':
  1308. case 'TEXCOORD0':
  1309. case 'TEXCOORD':
  1310. geometry.addAttribute( 'uv', bufferAttribute );
  1311. break;
  1312. case 'TEXCOORD_1':
  1313. geometry.addAttribute( 'uv2', bufferAttribute );
  1314. break;
  1315. case 'COLOR_0':
  1316. case 'COLOR0':
  1317. case 'COLOR':
  1318. geometry.addAttribute( 'color', bufferAttribute );
  1319. break;
  1320. case 'WEIGHTS_0':
  1321. case 'WEIGHT': // WEIGHT semantic deprecated.
  1322. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1323. break;
  1324. case 'JOINTS_0':
  1325. case 'JOINT': // JOINT semantic deprecated.
  1326. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1327. break;
  1328. }
  1329. }
  1330. if ( primitive.indices !== undefined ) {
  1331. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1332. }
  1333. if ( material.aoMap
  1334. && geometry.attributes.uv2 === undefined
  1335. && geometry.attributes.uv !== undefined ) {
  1336. console.log( 'THREE.GLTF2Loader: Duplicating UVs to support aoMap.' );
  1337. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1338. }
  1339. meshNode = new THREE.Mesh( geometry, material );
  1340. meshNode.castShadow = true;
  1341. if ( primitive.targets !== undefined ) {
  1342. var targets = primitive.targets;
  1343. var morphAttributes = geometry.morphAttributes;
  1344. morphAttributes.position = [];
  1345. morphAttributes.normal = [];
  1346. material.morphTargets = true;
  1347. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1348. var target = targets[ i ];
  1349. var attributeName = 'morphTarget' + i;
  1350. var positionAttribute, normalAttribute;
  1351. if ( target.POSITION !== undefined ) {
  1352. // Three.js morph formula is
  1353. // position
  1354. // + weight0 * ( morphTarget0 - position )
  1355. // + weight1 * ( morphTarget1 - position )
  1356. // ...
  1357. // while the glTF one is
  1358. // position
  1359. // + weight0 * morphTarget0
  1360. // + weight1 * morphTarget1
  1361. // ...
  1362. // then adding position to morphTarget.
  1363. // So morphTarget value will depend on mesh's position, then cloning attribute
  1364. // for the case if attribute is shared among two or more meshes.
  1365. positionAttribute = dependencies.accessors[ target.POSITION ].clone();
  1366. var position = geometry.attributes.position;
  1367. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  1368. positionAttribute.setXYZ(
  1369. j,
  1370. positionAttribute.getX( j ) + position.getX( j ),
  1371. positionAttribute.getY( j ) + position.getY( j ),
  1372. positionAttribute.getZ( j ) + position.getZ( j )
  1373. );
  1374. }
  1375. } else if ( geometry.attributes.position ) {
  1376. // Copying the original position not to affect the final position.
  1377. // See the formula above.
  1378. positionAttribute = geometry.attributes.position.clone();
  1379. }
  1380. if ( target.NORMAL !== undefined ) {
  1381. material.morphNormals = true;
  1382. // see target.POSITION's comment
  1383. normalAttribute = dependencies.accessors[ target.NORMAL ].clone();
  1384. var normal = geometry.attributes.normal;
  1385. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  1386. normalAttribute.setXYZ(
  1387. j,
  1388. normalAttribute.getX( j ) + normal.getX( j ),
  1389. normalAttribute.getY( j ) + normal.getY( j ),
  1390. normalAttribute.getZ( j ) + normal.getZ( j )
  1391. );
  1392. }
  1393. } else if ( geometry.attributes.normal ) {
  1394. normalAttribute = geometry.attributes.normal.clone();
  1395. }
  1396. // TODO: implement
  1397. if ( target.TANGENT !== undefined ) {
  1398. }
  1399. if ( positionAttribute ) {
  1400. positionAttribute.name = attributeName;
  1401. morphAttributes.position.push( positionAttribute );
  1402. }
  1403. if ( normalAttribute ) {
  1404. normalAttribute.name = attributeName;
  1405. morphAttributes.normal.push( normalAttribute );
  1406. }
  1407. }
  1408. meshNode.updateMorphTargets();
  1409. if ( mesh.weights !== undefined ) {
  1410. for ( var i = 0, il = mesh.weights.length; i < il; i ++ ) {
  1411. meshNode.morphTargetInfluences[ i ] = mesh.weights[ i ];
  1412. }
  1413. }
  1414. }
  1415. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1416. geometry = new THREE.BufferGeometry();
  1417. var attributes = primitive.attributes;
  1418. for ( var attributeId in attributes ) {
  1419. var attributeEntry = attributes[ attributeId ];
  1420. if ( ! attributeEntry ) return;
  1421. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1422. switch ( attributeId ) {
  1423. case 'POSITION':
  1424. geometry.addAttribute( 'position', bufferAttribute );
  1425. break;
  1426. case 'COLOR_0':
  1427. case 'COLOR0':
  1428. case 'COLOR':
  1429. geometry.addAttribute( 'color', bufferAttribute );
  1430. break;
  1431. }
  1432. }
  1433. if ( primitive.indices !== undefined ) {
  1434. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1435. }
  1436. meshNode = new THREE.LineSegments( geometry, material );
  1437. } else {
  1438. throw new Error( 'THREE.GLTF2Loader: Only triangular and line primitives are supported.' );
  1439. }
  1440. if ( geometry.attributes.color !== undefined ) {
  1441. material.vertexColors = THREE.VertexColors;
  1442. material.needsUpdate = true;
  1443. }
  1444. meshNode.name = group.name + '_' + name;
  1445. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1446. group.add( meshNode );
  1447. }
  1448. return group;
  1449. } );
  1450. } );
  1451. };
  1452. /**
  1453. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1454. */
  1455. GLTFParser.prototype.loadCameras = function () {
  1456. var json = this.json;
  1457. return _each( json.cameras, function ( camera ) {
  1458. var _camera;
  1459. var params = camera[ camera.type ];
  1460. if ( !params ) {
  1461. console.warn( 'THREE.GLTF2Loader: Missing camera parameters.' );
  1462. return;
  1463. }
  1464. if ( camera.type === 'perspective' ) {
  1465. var aspectRatio = params.aspectRatio || 1;
  1466. var xfov = params.yfov * aspectRatio;
  1467. _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
  1468. } else if ( camera.type === 'orthographic' ) {
  1469. _camera = new THREE.OrthographicCamera( params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar );
  1470. }
  1471. if ( camera.name !== undefined ) _camera.name = camera.name;
  1472. if ( camera.extras ) _camera.userData = camera.extras;
  1473. return _camera;
  1474. } );
  1475. };
  1476. GLTFParser.prototype.loadSkins = function () {
  1477. var json = this.json;
  1478. return this._withDependencies( [
  1479. 'accessors'
  1480. ] ).then( function ( dependencies ) {
  1481. return _each( json.skins, function ( skin ) {
  1482. var _skin = {
  1483. joints: skin.joints,
  1484. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1485. };
  1486. return _skin;
  1487. } );
  1488. } );
  1489. };
  1490. GLTFParser.prototype.loadAnimations = function () {
  1491. var json = this.json;
  1492. return this._withDependencies( [
  1493. 'accessors',
  1494. 'nodes'
  1495. ] ).then( function ( dependencies ) {
  1496. return _each( json.animations, function ( animation, animationId ) {
  1497. var tracks = [];
  1498. for ( var channelId in animation.channels ) {
  1499. var channel = animation.channels[ channelId ];
  1500. var sampler = animation.samplers[ channel.sampler ];
  1501. if ( sampler ) {
  1502. var target = channel.target;
  1503. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1504. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1505. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1506. var inputAccessor = dependencies.accessors[ input ];
  1507. var outputAccessor = dependencies.accessors[ output ];
  1508. var node = dependencies.nodes[ name ];
  1509. if ( node ) {
  1510. node.updateMatrix();
  1511. node.matrixAutoUpdate = true;
  1512. var TypedKeyframeTrack;
  1513. switch ( PATH_PROPERTIES[ target.path ] ) {
  1514. case PATH_PROPERTIES.weights:
  1515. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1516. break;
  1517. case PATH_PROPERTIES.rotation:
  1518. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1519. break;
  1520. case PATH_PROPERTIES.position:
  1521. case PATH_PROPERTIES.scale:
  1522. default:
  1523. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1524. break;
  1525. }
  1526. var targetName = node.name ? node.name : node.uuid;
  1527. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1528. var targetNames = [];
  1529. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1530. // node should be THREE.Group here but
  1531. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1532. // the property of a mesh object under node.
  1533. // So finding targets here.
  1534. node.traverse( function ( object ) {
  1535. if ( object.isMesh === true && object.material.morphTargets === true ) {
  1536. targetNames.push( object.name ? object.name : object.uuid );
  1537. }
  1538. } );
  1539. } else {
  1540. targetNames.push( targetName );
  1541. }
  1542. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1543. // buffers before creating a truncated copy to keep. Because buffers may
  1544. // be reused by other tracks, make copies here.
  1545. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  1546. tracks.push( new TypedKeyframeTrack(
  1547. targetNames[ i ] + '.' + PATH_PROPERTIES[ target.path ],
  1548. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1549. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1550. interpolation
  1551. ) );
  1552. }
  1553. }
  1554. }
  1555. }
  1556. var name = animation.name !== undefined ? animation.name : 'animation_' + animationId;
  1557. return new THREE.AnimationClip( name, undefined, tracks );
  1558. } );
  1559. } );
  1560. };
  1561. GLTFParser.prototype.loadNodes = function () {
  1562. var json = this.json;
  1563. var extensions = this.extensions;
  1564. var scope = this;
  1565. var nodes = json.nodes || [];
  1566. var skins = json.skins || [];
  1567. // Nothing in the node definition indicates whether it is a Bone or an
  1568. // Object3D. Use the skins' joint references to mark bones.
  1569. skins.forEach( function ( skin ) {
  1570. skin.joints.forEach( function ( id ) {
  1571. nodes[ id ].isBone = true;
  1572. } );
  1573. } );
  1574. return _each( json.nodes, function ( node ) {
  1575. var matrix = new THREE.Matrix4();
  1576. var _node = node.isBone === true ? new THREE.Bone() : new THREE.Object3D();
  1577. if ( node.name !== undefined ) {
  1578. _node.name = THREE.PropertyBinding.sanitizeNodeName( node.name );
  1579. }
  1580. if ( node.extras ) _node.userData = node.extras;
  1581. if ( node.matrix !== undefined ) {
  1582. matrix.fromArray( node.matrix );
  1583. _node.applyMatrix( matrix );
  1584. } else {
  1585. if ( node.translation !== undefined ) {
  1586. _node.position.fromArray( node.translation );
  1587. }
  1588. if ( node.rotation !== undefined ) {
  1589. _node.quaternion.fromArray( node.rotation );
  1590. }
  1591. if ( node.scale !== undefined ) {
  1592. _node.scale.fromArray( node.scale );
  1593. }
  1594. }
  1595. return _node;
  1596. } ).then( function ( __nodes ) {
  1597. return scope._withDependencies( [
  1598. 'meshes',
  1599. 'skins',
  1600. 'cameras'
  1601. ] ).then( function ( dependencies ) {
  1602. return _each( __nodes, function ( _node, nodeId ) {
  1603. var node = json.nodes[ nodeId ];
  1604. var meshes;
  1605. if ( node.mesh !== undefined) {
  1606. meshes = [ node.mesh ];
  1607. } else if ( node.meshes !== undefined ) {
  1608. console.warn( 'THREE.GLTF2Loader: Legacy glTF file detected. Nodes may have no more than one mesh.' );
  1609. meshes = node.meshes;
  1610. }
  1611. if ( meshes !== undefined ) {
  1612. for ( var meshId in meshes ) {
  1613. var mesh = meshes[ meshId ];
  1614. var group = dependencies.meshes[ mesh ];
  1615. if ( group === undefined ) {
  1616. console.warn( 'THREE.GLTF2Loader: Could not find node "' + mesh + '".' );
  1617. continue;
  1618. }
  1619. //do not clone children as they will be replaced anyway
  1620. var clonedgroup = group.clone( false );
  1621. for ( var childrenId in group.children ) {
  1622. var child = group.children[ childrenId ];
  1623. // clone Mesh to add to _node
  1624. var originalMaterial = child.material;
  1625. var originalGeometry = child.geometry;
  1626. var originalInfluences = child.morphTargetInfluences;
  1627. var originalUserData = child.userData;
  1628. var originalName = child.name;
  1629. var material;
  1630. if ( originalMaterial.isDeferredShaderMaterial ) {
  1631. originalMaterial = material = originalMaterial.create();
  1632. } else {
  1633. material = originalMaterial;
  1634. }
  1635. switch ( child.type ) {
  1636. case 'LineSegments':
  1637. child = new THREE.LineSegments( originalGeometry, material );
  1638. break;
  1639. case 'LineLoop':
  1640. child = new THREE.LineLoop( originalGeometry, material );
  1641. break;
  1642. case 'Line':
  1643. child = new THREE.Line( originalGeometry, material );
  1644. break;
  1645. default:
  1646. child = new THREE.Mesh( originalGeometry, material );
  1647. }
  1648. child.castShadow = true;
  1649. child.morphTargetInfluences = originalInfluences;
  1650. child.userData = originalUserData;
  1651. child.name = originalName;
  1652. var skinEntry;
  1653. if ( node.skin !== undefined ) {
  1654. skinEntry = dependencies.skins[ node.skin ];
  1655. }
  1656. // Replace Mesh with SkinnedMesh in library
  1657. if ( skinEntry ) {
  1658. var geometry = originalGeometry;
  1659. material = originalMaterial;
  1660. material.skinning = true;
  1661. child = new THREE.SkinnedMesh( geometry, material );
  1662. child.castShadow = true;
  1663. child.userData = originalUserData;
  1664. child.name = originalName;
  1665. var bones = [];
  1666. var boneInverses = [];
  1667. for ( var i = 0, l = skinEntry.joints.length; i < l; i ++ ) {
  1668. var jointId = skinEntry.joints[ i ];
  1669. var jointNode = __nodes[ jointId ];
  1670. if ( jointNode ) {
  1671. bones.push( jointNode );
  1672. var m = skinEntry.inverseBindMatrices.array;
  1673. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  1674. boneInverses.push( mat );
  1675. } else {
  1676. console.warn( 'THREE.GLTF2Loader: Joint "%s" could not be found.', jointId );
  1677. }
  1678. }
  1679. child.bind( new THREE.Skeleton( bones, boneInverses ), child.matrixWorld );
  1680. }
  1681. clonedgroup.add(child);
  1682. }
  1683. _node.add( clonedgroup );
  1684. }
  1685. }
  1686. if ( node.camera !== undefined ) {
  1687. var camera = dependencies.cameras[ node.camera ];
  1688. _node.add( camera );
  1689. }
  1690. if ( node.extensions
  1691. && node.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1692. && node.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1693. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1694. _node.add( lights[ node.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1695. }
  1696. return _node;
  1697. } );
  1698. } );
  1699. } );
  1700. };
  1701. GLTFParser.prototype.loadScenes = function () {
  1702. var json = this.json;
  1703. var extensions = this.extensions;
  1704. // scene node hierachy builder
  1705. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1706. var _node = allNodes[ nodeId ];
  1707. parentObject.add( _node );
  1708. var node = json.nodes[ nodeId ];
  1709. if ( node.children ) {
  1710. var children = node.children;
  1711. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1712. var child = children[ i ];
  1713. buildNodeHierachy( child, _node, allNodes );
  1714. }
  1715. }
  1716. }
  1717. return this._withDependencies( [
  1718. 'nodes'
  1719. ] ).then( function ( dependencies ) {
  1720. return _each( json.scenes, function ( scene ) {
  1721. var _scene = new THREE.Scene();
  1722. if ( scene.name !== undefined ) _scene.name = scene.name;
  1723. if ( scene.extras ) _scene.userData = scene.extras;
  1724. var nodes = scene.nodes || [];
  1725. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1726. var nodeId = nodes[ i ];
  1727. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1728. }
  1729. _scene.traverse( function ( child ) {
  1730. // Register raw material meshes with GLTF2Loader.Shaders
  1731. if ( child.material && child.material.isRawShaderMaterial ) {
  1732. child.gltfShader = new GLTFShader( child, dependencies.nodes );
  1733. child.onBeforeRender = function(renderer, scene, camera){
  1734. this.gltfShader.update(scene, camera);
  1735. };
  1736. }
  1737. // for Specular-Glossiness.
  1738. if ( child.material && child.material.type === 'ShaderMaterial' ) {
  1739. child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1740. }
  1741. } );
  1742. // Ambient lighting, if present, is always attached to the scene root.
  1743. if ( scene.extensions
  1744. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1745. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1746. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1747. _scene.add( lights[ scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1748. }
  1749. return _scene;
  1750. } );
  1751. } );
  1752. };
  1753. return GLTF2Loader;
  1754. } )();