GLTF2Loader.js 67 KB

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