GLTF2Loader.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956
  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. TRIANGLES: 4,
  720. LINES: 1,
  721. UNSIGNED_BYTE: 5121,
  722. UNSIGNED_SHORT: 5123,
  723. VERTEX_SHADER: 35633,
  724. FRAGMENT_SHADER: 35632
  725. };
  726. var WEBGL_TYPE = {
  727. 5126: Number,
  728. //35674: THREE.Matrix2,
  729. 35675: THREE.Matrix3,
  730. 35676: THREE.Matrix4,
  731. 35664: THREE.Vector2,
  732. 35665: THREE.Vector3,
  733. 35666: THREE.Vector4,
  734. 35678: THREE.Texture
  735. };
  736. var WEBGL_COMPONENT_TYPES = {
  737. 5120: Int8Array,
  738. 5121: Uint8Array,
  739. 5122: Int16Array,
  740. 5123: Uint16Array,
  741. 5125: Uint32Array,
  742. 5126: Float32Array
  743. };
  744. var WEBGL_FILTERS = {
  745. 9728: THREE.NearestFilter,
  746. 9729: THREE.LinearFilter,
  747. 9984: THREE.NearestMipMapNearestFilter,
  748. 9985: THREE.LinearMipMapNearestFilter,
  749. 9986: THREE.NearestMipMapLinearFilter,
  750. 9987: THREE.LinearMipMapLinearFilter
  751. };
  752. var WEBGL_WRAPPINGS = {
  753. 33071: THREE.ClampToEdgeWrapping,
  754. 33648: THREE.MirroredRepeatWrapping,
  755. 10497: THREE.RepeatWrapping
  756. };
  757. var WEBGL_TEXTURE_FORMATS = {
  758. 6406: THREE.AlphaFormat,
  759. 6407: THREE.RGBFormat,
  760. 6408: THREE.RGBAFormat,
  761. 6409: THREE.LuminanceFormat,
  762. 6410: THREE.LuminanceAlphaFormat
  763. };
  764. var WEBGL_TEXTURE_DATATYPES = {
  765. 5121: THREE.UnsignedByteType,
  766. 32819: THREE.UnsignedShort4444Type,
  767. 32820: THREE.UnsignedShort5551Type,
  768. 33635: THREE.UnsignedShort565Type
  769. };
  770. var WEBGL_SIDES = {
  771. 1028: THREE.BackSide, // Culling front
  772. 1029: THREE.FrontSide // Culling back
  773. //1032: THREE.NoSide // Culling front and back, what to do?
  774. };
  775. var WEBGL_DEPTH_FUNCS = {
  776. 512: THREE.NeverDepth,
  777. 513: THREE.LessDepth,
  778. 514: THREE.EqualDepth,
  779. 515: THREE.LessEqualDepth,
  780. 516: THREE.GreaterEqualDepth,
  781. 517: THREE.NotEqualDepth,
  782. 518: THREE.GreaterEqualDepth,
  783. 519: THREE.AlwaysDepth
  784. };
  785. var WEBGL_BLEND_EQUATIONS = {
  786. 32774: THREE.AddEquation,
  787. 32778: THREE.SubtractEquation,
  788. 32779: THREE.ReverseSubtractEquation
  789. };
  790. var WEBGL_BLEND_FUNCS = {
  791. 0: THREE.ZeroFactor,
  792. 1: THREE.OneFactor,
  793. 768: THREE.SrcColorFactor,
  794. 769: THREE.OneMinusSrcColorFactor,
  795. 770: THREE.SrcAlphaFactor,
  796. 771: THREE.OneMinusSrcAlphaFactor,
  797. 772: THREE.DstAlphaFactor,
  798. 773: THREE.OneMinusDstAlphaFactor,
  799. 774: THREE.DstColorFactor,
  800. 775: THREE.OneMinusDstColorFactor,
  801. 776: THREE.SrcAlphaSaturateFactor
  802. // The followings are not supported by Three.js yet
  803. //32769: CONSTANT_COLOR,
  804. //32770: ONE_MINUS_CONSTANT_COLOR,
  805. //32771: CONSTANT_ALPHA,
  806. //32772: ONE_MINUS_CONSTANT_COLOR
  807. };
  808. var WEBGL_TYPE_SIZES = {
  809. 'SCALAR': 1,
  810. 'VEC2': 2,
  811. 'VEC3': 3,
  812. 'VEC4': 4,
  813. 'MAT2': 4,
  814. 'MAT3': 9,
  815. 'MAT4': 16
  816. };
  817. var PATH_PROPERTIES = {
  818. scale: 'scale',
  819. translation: 'position',
  820. rotation: 'quaternion',
  821. weights: 'morphTargetInfluences'
  822. };
  823. var INTERPOLATION = {
  824. CATMULLROMSPLINE: THREE.InterpolateSmooth,
  825. CUBICSPLINE: THREE.InterpolateSmooth,
  826. LINEAR: THREE.InterpolateLinear,
  827. STEP: THREE.InterpolateDiscrete
  828. };
  829. var STATES_ENABLES = {
  830. 2884: 'CULL_FACE',
  831. 2929: 'DEPTH_TEST',
  832. 3042: 'BLEND',
  833. 3089: 'SCISSOR_TEST',
  834. 32823: 'POLYGON_OFFSET_FILL',
  835. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  836. };
  837. var ALPHA_MODES = {
  838. OPAQUE: 'OPAQUE',
  839. MASK: 'MASK',
  840. BLEND: 'BLEND'
  841. };
  842. /* UTILITY FUNCTIONS */
  843. function _each( object, callback, thisObj ) {
  844. if ( !object ) {
  845. return Promise.resolve();
  846. }
  847. var results;
  848. var fns = [];
  849. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  850. results = [];
  851. var length = object.length;
  852. for ( var idx = 0; idx < length; idx ++ ) {
  853. var value = callback.call( thisObj || this, object[ idx ], idx );
  854. if ( value ) {
  855. fns.push( value );
  856. if ( value instanceof Promise ) {
  857. value.then( function( key, value ) {
  858. results[ key ] = value;
  859. }.bind( this, idx ));
  860. } else {
  861. results[ idx ] = value;
  862. }
  863. }
  864. }
  865. } else {
  866. results = {};
  867. for ( var key in object ) {
  868. if ( object.hasOwnProperty( key ) ) {
  869. var value = callback.call( thisObj || this, object[ key ], key );
  870. if ( value ) {
  871. fns.push( value );
  872. if ( value instanceof Promise ) {
  873. value.then( function( key, value ) {
  874. results[ key ] = value;
  875. }.bind( this, key ));
  876. } else {
  877. results[ key ] = value;
  878. }
  879. }
  880. }
  881. }
  882. }
  883. return Promise.all( fns ).then( function() {
  884. return results;
  885. });
  886. }
  887. function resolveURL( url, path ) {
  888. // Invalid URL
  889. if ( typeof url !== 'string' || url === '' )
  890. return '';
  891. // Absolute URL http://,https://,//
  892. if ( /^(https?:)?\/\//i.test( url ) ) {
  893. return url;
  894. }
  895. // Data URI
  896. if ( /^data:.*,.*$/i.test( url ) ) {
  897. return url;
  898. }
  899. // Blob URL
  900. if ( /^blob:.*$/i.test( url ) ) {
  901. return url;
  902. }
  903. // Relative URL
  904. return ( path || '' ) + url;
  905. }
  906. function convertUint8ArrayToString( array ) {
  907. if ( window.TextDecoder !== undefined ) {
  908. return new TextDecoder().decode( array );
  909. }
  910. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  911. // throws a "maximum call stack size exceeded" error for large arrays.
  912. var s = '';
  913. for ( var i = 0, il = array.length; i < il; i ++ ) {
  914. s += String.fromCharCode( array[ i ] );
  915. }
  916. return s;
  917. }
  918. // Three.js seems too dependent on attribute names so globally
  919. // replace those in the shader code
  920. function replaceTHREEShaderAttributes( shaderText, technique ) {
  921. // Expected technique attributes
  922. var attributes = {};
  923. for ( var attributeId in technique.attributes ) {
  924. var pname = technique.attributes[ attributeId ];
  925. var param = technique.parameters[ pname ];
  926. var atype = param.type;
  927. var semantic = param.semantic;
  928. attributes[ attributeId ] = {
  929. type: atype,
  930. semantic: semantic
  931. };
  932. }
  933. // Figure out which attributes to change in technique
  934. var shaderParams = technique.parameters;
  935. var shaderAttributes = technique.attributes;
  936. var params = {};
  937. for ( var attributeId in attributes ) {
  938. var pname = shaderAttributes[ attributeId ];
  939. var shaderParam = shaderParams[ pname ];
  940. var semantic = shaderParam.semantic;
  941. if ( semantic ) {
  942. params[ attributeId ] = shaderParam;
  943. }
  944. }
  945. for ( var pname in params ) {
  946. var param = params[ pname ];
  947. var semantic = param.semantic;
  948. var regEx = new RegExp( '\\b' + pname + '\\b', 'g' );
  949. switch ( semantic ) {
  950. case 'POSITION':
  951. shaderText = shaderText.replace( regEx, 'position' );
  952. break;
  953. case 'NORMAL':
  954. shaderText = shaderText.replace( regEx, 'normal' );
  955. break;
  956. case 'TEXCOORD_0':
  957. case 'TEXCOORD0':
  958. case 'TEXCOORD':
  959. shaderText = shaderText.replace( regEx, 'uv' );
  960. break;
  961. case 'TEXCOORD_1':
  962. shaderText = shaderText.replace( regEx, 'uv2' );
  963. break;
  964. case 'COLOR_0':
  965. case 'COLOR0':
  966. case 'COLOR':
  967. shaderText = shaderText.replace( regEx, 'color' );
  968. break;
  969. case 'WEIGHTS_0':
  970. case 'WEIGHT': // WEIGHT semantic deprecated.
  971. shaderText = shaderText.replace( regEx, 'skinWeight' );
  972. break;
  973. case 'JOINTS_0':
  974. case 'JOINT': // JOINT semantic deprecated.
  975. shaderText = shaderText.replace( regEx, 'skinIndex' );
  976. break;
  977. }
  978. }
  979. return shaderText;
  980. }
  981. /**
  982. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  983. */
  984. function createDefaultMaterial() {
  985. return new THREE.MeshStandardMaterial( {
  986. color: 0xFFFFFF,
  987. emissive: 0x000000,
  988. metalness: 1,
  989. roughness: 1,
  990. transparent: false,
  991. depthTest: true,
  992. side: THREE.FrontSide
  993. } );
  994. }
  995. /**
  996. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  997. * @param {THREE.Mesh} mesh
  998. * @param {GLTF.Mesh} meshDef
  999. * @param {GLTF.Primitive} primitiveDef
  1000. * @param {Object} dependencies
  1001. */
  1002. function addMorphTargets ( mesh, meshDef, primitiveDef, dependencies ) {
  1003. var geometry = mesh.geometry;
  1004. var material = mesh.material;
  1005. var targets = primitiveDef.targets;
  1006. var morphAttributes = geometry.morphAttributes;
  1007. morphAttributes.position = [];
  1008. morphAttributes.normal = [];
  1009. material.morphTargets = true;
  1010. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1011. var target = targets[ i ];
  1012. var attributeName = 'morphTarget' + i;
  1013. var positionAttribute, normalAttribute;
  1014. if ( target.POSITION !== undefined ) {
  1015. // Three.js morph formula is
  1016. // position
  1017. // + weight0 * ( morphTarget0 - position )
  1018. // + weight1 * ( morphTarget1 - position )
  1019. // ...
  1020. // while the glTF one is
  1021. // position
  1022. // + weight0 * morphTarget0
  1023. // + weight1 * morphTarget1
  1024. // ...
  1025. // then adding position to morphTarget.
  1026. // So morphTarget value will depend on mesh's position, then cloning attribute
  1027. // for the case if attribute is shared among two or more meshes.
  1028. positionAttribute = dependencies.accessors[ target.POSITION ].clone();
  1029. var position = geometry.attributes.position;
  1030. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  1031. positionAttribute.setXYZ(
  1032. j,
  1033. positionAttribute.getX( j ) + position.getX( j ),
  1034. positionAttribute.getY( j ) + position.getY( j ),
  1035. positionAttribute.getZ( j ) + position.getZ( j )
  1036. );
  1037. }
  1038. } else {
  1039. // Copying the original position not to affect the final position.
  1040. // See the formula above.
  1041. positionAttribute = geometry.attributes.position.clone();
  1042. }
  1043. if ( target.NORMAL !== undefined ) {
  1044. material.morphNormals = true;
  1045. // see target.POSITION's comment
  1046. normalAttribute = dependencies.accessors[ target.NORMAL ].clone();
  1047. var normal = geometry.attributes.normal;
  1048. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  1049. normalAttribute.setXYZ(
  1050. j,
  1051. normalAttribute.getX( j ) + normal.getX( j ),
  1052. normalAttribute.getY( j ) + normal.getY( j ),
  1053. normalAttribute.getZ( j ) + normal.getZ( j )
  1054. );
  1055. }
  1056. } else {
  1057. normalAttribute = geometry.attributes.normal.clone();
  1058. }
  1059. if ( target.TANGENT !== undefined ) {
  1060. // TODO: implement
  1061. }
  1062. positionAttribute.name = attributeName;
  1063. normalAttribute.name = attributeName;
  1064. morphAttributes.position.push( positionAttribute );
  1065. morphAttributes.normal.push( normalAttribute );
  1066. }
  1067. mesh.updateMorphTargets();
  1068. if ( meshDef.weights !== undefined ) {
  1069. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  1070. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  1071. }
  1072. }
  1073. }
  1074. // Deferred constructor for RawShaderMaterial types
  1075. function DeferredShaderMaterial( params ) {
  1076. this.isDeferredShaderMaterial = true;
  1077. this.params = params;
  1078. }
  1079. DeferredShaderMaterial.prototype.create = function () {
  1080. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  1081. for ( var uniformId in this.params.uniforms ) {
  1082. var originalUniform = this.params.uniforms[ uniformId ];
  1083. if ( originalUniform.value instanceof THREE.Texture ) {
  1084. uniforms[ uniformId ].value = originalUniform.value;
  1085. uniforms[ uniformId ].value.needsUpdate = true;
  1086. }
  1087. uniforms[ uniformId ].semantic = originalUniform.semantic;
  1088. uniforms[ uniformId ].node = originalUniform.node;
  1089. }
  1090. this.params.uniforms = uniforms;
  1091. return new THREE.RawShaderMaterial( this.params );
  1092. };
  1093. /* GLTF PARSER */
  1094. function GLTFParser( json, extensions, options ) {
  1095. this.json = json || {};
  1096. this.extensions = extensions || {};
  1097. this.options = options || {};
  1098. // loader object cache
  1099. this.cache = new GLTFRegistry();
  1100. }
  1101. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  1102. var _dependencies = {};
  1103. for ( var i = 0; i < dependencies.length; i ++ ) {
  1104. var dependency = dependencies[ i ];
  1105. var fnName = 'load' + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  1106. var cached = this.cache.get( dependency );
  1107. if ( cached !== undefined ) {
  1108. _dependencies[ dependency ] = cached;
  1109. } else if ( this[ fnName ] ) {
  1110. var fn = this[ fnName ]();
  1111. this.cache.add( dependency, fn );
  1112. _dependencies[ dependency ] = fn;
  1113. }
  1114. }
  1115. return _each( _dependencies, function ( dependency ) {
  1116. return dependency;
  1117. } );
  1118. };
  1119. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  1120. var json = this.json;
  1121. // Clear the loader cache
  1122. this.cache.removeAll();
  1123. // Fire the callback on complete
  1124. this._withDependencies( [
  1125. 'scenes',
  1126. 'cameras',
  1127. 'animations'
  1128. ] ).then( function ( dependencies ) {
  1129. var scenes = [];
  1130. for ( var name in dependencies.scenes ) {
  1131. scenes.push( dependencies.scenes[ name ] );
  1132. }
  1133. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  1134. var cameras = [];
  1135. for ( var name in dependencies.cameras ) {
  1136. var camera = dependencies.cameras[ name ];
  1137. cameras.push( camera );
  1138. }
  1139. var animations = [];
  1140. for ( var name in dependencies.animations ) {
  1141. animations.push( dependencies.animations[ name ] );
  1142. }
  1143. onLoad( scene, scenes, cameras, animations );
  1144. } ).catch( onError );
  1145. };
  1146. GLTFParser.prototype.loadShaders = function () {
  1147. var json = this.json;
  1148. var options = this.options;
  1149. var extensions = this.extensions;
  1150. return this._withDependencies( [
  1151. 'bufferViews'
  1152. ] ).then( function ( dependencies ) {
  1153. var shaders = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] !== undefined ? extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].shaders : json.shaders;
  1154. if ( shaders === undefined ) shaders = {};
  1155. return _each( shaders, function ( shader ) {
  1156. if ( shader.bufferView !== undefined ) {
  1157. var bufferView = dependencies.bufferViews[ shader.bufferView ];
  1158. var array = new Uint8Array( bufferView );
  1159. return convertUint8ArrayToString( array );
  1160. }
  1161. return new Promise( function ( resolve ) {
  1162. var loader = new THREE.FileLoader();
  1163. loader.setResponseType( 'text' );
  1164. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  1165. resolve( shaderText );
  1166. } );
  1167. } );
  1168. } );
  1169. } );
  1170. };
  1171. GLTFParser.prototype.loadBuffers = function () {
  1172. var json = this.json;
  1173. var extensions = this.extensions;
  1174. var options = this.options;
  1175. return _each( json.buffers, function ( buffer, name ) {
  1176. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  1177. // If present, GLB container is required to be the first buffer.
  1178. if ( buffer.uri === undefined && name === 0 ) {
  1179. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  1180. }
  1181. return new Promise( function ( resolve ) {
  1182. var loader = new THREE.FileLoader();
  1183. loader.setResponseType( 'arraybuffer' );
  1184. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  1185. resolve( buffer );
  1186. } );
  1187. } );
  1188. } else {
  1189. console.warn( 'THREE.GLTF2Loader: %s buffer type is not supported.', buffer.type );
  1190. }
  1191. } );
  1192. };
  1193. GLTFParser.prototype.loadBufferViews = function () {
  1194. var json = this.json;
  1195. return this._withDependencies( [
  1196. 'buffers'
  1197. ] ).then( function ( dependencies ) {
  1198. return _each( json.bufferViews, function ( bufferView ) {
  1199. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  1200. var byteLength = bufferView.byteLength || 0;
  1201. var byteOffset = bufferView.byteOffset || 0;
  1202. return arraybuffer.slice( byteOffset, byteOffset + byteLength );
  1203. } );
  1204. } );
  1205. };
  1206. GLTFParser.prototype.loadAccessors = function () {
  1207. var json = this.json;
  1208. return this._withDependencies( [
  1209. 'bufferViews'
  1210. ] ).then( function ( dependencies ) {
  1211. return _each( json.accessors, function ( accessor ) {
  1212. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  1213. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  1214. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  1215. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1216. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1217. var itemBytes = elementBytes * itemSize;
  1218. var byteStride = json.bufferViews[ accessor.bufferView ].byteStride;
  1219. var array;
  1220. // The buffer is not interleaved if the stride is the item size in bytes.
  1221. if ( byteStride && byteStride !== itemBytes ) {
  1222. // Use the full buffer if it's interleaved.
  1223. array = new TypedArray( arraybuffer );
  1224. // Integer parameters to IB/IBA are in array elements, not bytes.
  1225. var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1226. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  1227. } else {
  1228. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  1229. return new THREE.BufferAttribute( array, itemSize );
  1230. }
  1231. } );
  1232. } );
  1233. };
  1234. GLTFParser.prototype.loadTextures = function () {
  1235. var json = this.json;
  1236. var options = this.options;
  1237. return this._withDependencies( [
  1238. 'bufferViews'
  1239. ] ).then( function ( dependencies ) {
  1240. return _each( json.textures, function ( texture ) {
  1241. if ( texture.source !== undefined ) {
  1242. return new Promise( function ( resolve ) {
  1243. var source = json.images[ texture.source ];
  1244. var sourceUri = source.uri;
  1245. var urlCreator;
  1246. if ( source.bufferView !== undefined ) {
  1247. var bufferView = dependencies.bufferViews[ source.bufferView ];
  1248. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1249. urlCreator = window.URL || window.webkitURL;
  1250. sourceUri = urlCreator.createObjectURL( blob );
  1251. }
  1252. var textureLoader = THREE.Loader.Handlers.get( sourceUri );
  1253. if ( textureLoader === null ) {
  1254. textureLoader = new THREE.TextureLoader();
  1255. }
  1256. textureLoader.setCrossOrigin( options.crossOrigin );
  1257. textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
  1258. if ( urlCreator !== undefined ) {
  1259. urlCreator.revokeObjectURL( sourceUri );
  1260. }
  1261. _texture.flipY = false;
  1262. if ( texture.name !== undefined ) _texture.name = texture.name;
  1263. _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat;
  1264. if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {
  1265. console.warn( 'THREE.GLTF2Loader: Three.js does not support texture internalFormat which is different from texture format. ' +
  1266. 'internalFormat will be forced to be the same value as format.' );
  1267. }
  1268. _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;
  1269. var samplers = json.samplers || {};
  1270. var sampler = samplers[ texture.sampler ] || {};
  1271. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1272. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  1273. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1274. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1275. resolve( _texture );
  1276. }, undefined, function () {
  1277. resolve();
  1278. } );
  1279. } );
  1280. }
  1281. } );
  1282. } );
  1283. };
  1284. GLTFParser.prototype.loadMaterials = function () {
  1285. var json = this.json;
  1286. var extensions = this.extensions;
  1287. return this._withDependencies( [
  1288. 'shaders',
  1289. 'textures'
  1290. ] ).then( function ( dependencies ) {
  1291. return _each( json.materials, function ( material ) {
  1292. var materialType;
  1293. var materialParams = {};
  1294. var materialExtensions = material.extensions || {};
  1295. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  1296. materialType = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].getMaterialType( material );
  1297. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].extendParams( materialParams, material, dependencies );
  1298. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1299. materialType = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].getMaterialType( material );
  1300. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].extendParams( materialParams, material, dependencies );
  1301. } else if ( materialExtensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] ) {
  1302. materialType = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].getMaterialType( material );
  1303. extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].extendParams( materialParams, material, dependencies );
  1304. } else if ( material.pbrMetallicRoughness !== undefined ) {
  1305. // Specification:
  1306. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1307. materialType = THREE.MeshStandardMaterial;
  1308. var metallicRoughness = material.pbrMetallicRoughness;
  1309. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1310. materialParams.opacity = 1.0;
  1311. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1312. var array = metallicRoughness.baseColorFactor;
  1313. materialParams.color.fromArray( array );
  1314. materialParams.opacity = array[ 3 ];
  1315. }
  1316. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1317. materialParams.map = dependencies.textures[ metallicRoughness.baseColorTexture.index ];
  1318. }
  1319. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1320. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1321. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1322. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  1323. materialParams.metalnessMap = dependencies.textures[ textureIndex ];
  1324. materialParams.roughnessMap = dependencies.textures[ textureIndex ];
  1325. }
  1326. } else {
  1327. materialType = THREE.MeshPhongMaterial;
  1328. }
  1329. if ( material.doubleSided === true ) {
  1330. materialParams.side = THREE.DoubleSide;
  1331. }
  1332. var alphaMode = material.alphaMode || ALPHA_MODES.OPAQUE;
  1333. if ( alphaMode !== ALPHA_MODES.OPAQUE ) {
  1334. materialParams.transparent = true;
  1335. } else {
  1336. materialParams.transparent = false;
  1337. }
  1338. if ( material.normalTexture !== undefined ) {
  1339. materialParams.normalMap = dependencies.textures[ material.normalTexture.index ];
  1340. }
  1341. if ( material.occlusionTexture !== undefined ) {
  1342. materialParams.aoMap = dependencies.textures[ material.occlusionTexture.index ];
  1343. }
  1344. if ( material.emissiveFactor !== undefined ) {
  1345. if ( materialType === THREE.MeshBasicMaterial ) {
  1346. materialParams.color = new THREE.Color().fromArray( material.emissiveFactor );
  1347. } else {
  1348. materialParams.emissive = new THREE.Color().fromArray( material.emissiveFactor );
  1349. }
  1350. }
  1351. if ( material.emissiveTexture !== undefined ) {
  1352. if ( materialType === THREE.MeshBasicMaterial ) {
  1353. materialParams.map = dependencies.textures[ material.emissiveTexture.index ];
  1354. } else {
  1355. materialParams.emissiveMap = dependencies.textures[ material.emissiveTexture.index ];
  1356. }
  1357. }
  1358. var _material;
  1359. if ( materialType === THREE.ShaderMaterial ) {
  1360. _material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1361. } else {
  1362. _material = new materialType( materialParams );
  1363. }
  1364. if ( material.name !== undefined ) _material.name = material.name;
  1365. // Normal map textures use OpenGL conventions:
  1366. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  1367. _material.normalScale.x = -1;
  1368. _material.userData = material.extras;
  1369. return _material;
  1370. } );
  1371. } );
  1372. };
  1373. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1374. return this._withDependencies( [
  1375. 'accessors',
  1376. 'bufferViews',
  1377. ] ).then( function ( dependencies ) {
  1378. return _each( primitives, function ( primitive ) {
  1379. var geometry = new THREE.BufferGeometry();
  1380. var attributes = primitive.attributes;
  1381. for ( var attributeId in attributes ) {
  1382. var attributeEntry = attributes[ attributeId ];
  1383. if ( attributeEntry === undefined ) return;
  1384. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1385. switch ( attributeId ) {
  1386. case 'POSITION':
  1387. geometry.addAttribute( 'position', bufferAttribute );
  1388. break;
  1389. case 'NORMAL':
  1390. geometry.addAttribute( 'normal', bufferAttribute );
  1391. break;
  1392. case 'TEXCOORD_0':
  1393. case 'TEXCOORD0':
  1394. case 'TEXCOORD':
  1395. geometry.addAttribute( 'uv', bufferAttribute );
  1396. break;
  1397. case 'TEXCOORD_1':
  1398. geometry.addAttribute( 'uv2', bufferAttribute );
  1399. break;
  1400. case 'COLOR_0':
  1401. case 'COLOR0':
  1402. case 'COLOR':
  1403. geometry.addAttribute( 'color', bufferAttribute );
  1404. break;
  1405. case 'WEIGHTS_0':
  1406. case 'WEIGHT': // WEIGHT semantic deprecated.
  1407. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1408. break;
  1409. case 'JOINTS_0':
  1410. case 'JOINT': // JOINT semantic deprecated.
  1411. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1412. break;
  1413. }
  1414. }
  1415. if ( primitive.indices !== undefined ) {
  1416. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1417. }
  1418. return geometry;
  1419. } );
  1420. } );
  1421. };
  1422. /**
  1423. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1424. */
  1425. GLTFParser.prototype.loadMeshes = function () {
  1426. var scope = this;
  1427. var json = this.json;
  1428. return this._withDependencies( [
  1429. 'accessors',
  1430. 'materials'
  1431. ] ).then( function ( dependencies ) {
  1432. return _each( json.meshes, function ( meshDef ) {
  1433. var group = new THREE.Group();
  1434. if ( meshDef.name !== undefined ) group.name = meshDef.name;
  1435. if ( meshDef.extras ) group.userData = meshDef.extras;
  1436. var primitives = meshDef.primitives || [];
  1437. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  1438. for ( var name in primitives ) {
  1439. var primitive = primitives[ name ];
  1440. var geometry = geometries[ name ];
  1441. var material = primitive.material === undefined
  1442. ? createDefaultMaterial()
  1443. : dependencies.materials[ primitive.material ];
  1444. if ( material.aoMap
  1445. && geometry.attributes.uv2 === undefined
  1446. && geometry.attributes.uv !== undefined ) {
  1447. console.log( 'THREE.GLTF2Loader: Duplicating UVs to support aoMap.' );
  1448. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1449. }
  1450. if ( geometry.attributes.color !== undefined ) {
  1451. material.vertexColors = THREE.VertexColors;
  1452. material.needsUpdate = true;
  1453. }
  1454. if ( geometry.attributes.normal === undefined ) {
  1455. if ( material.flatShading !== undefined ) {
  1456. material.flatShading = true;
  1457. } else {
  1458. // TODO: Remove this backwards-compatibility fix after r87 release.
  1459. material.shading = THREE.FlatShading;
  1460. }
  1461. }
  1462. var mesh;
  1463. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  1464. mesh = new THREE.Mesh( geometry, material );
  1465. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1466. mesh = new THREE.LineSegments( geometry, material );
  1467. } else {
  1468. throw new Error( 'THREE.GLTF2Loader: Only TRIANGLE and LINE primitives are supported.' );
  1469. }
  1470. mesh.name = group.name + '_' + name;
  1471. if ( primitive.targets !== undefined ) {
  1472. addMorphTargets( mesh, meshDef, primitive, dependencies );
  1473. }
  1474. if ( primitive.extras ) mesh.userData = primitive.extras;
  1475. group.add( mesh );
  1476. }
  1477. return group;
  1478. } );
  1479. } );
  1480. } );
  1481. };
  1482. /**
  1483. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1484. */
  1485. GLTFParser.prototype.loadCameras = function () {
  1486. var json = this.json;
  1487. return _each( json.cameras, function ( camera ) {
  1488. var _camera;
  1489. var params = camera[ camera.type ];
  1490. if ( !params ) {
  1491. console.warn( 'THREE.GLTF2Loader: Missing camera parameters.' );
  1492. return;
  1493. }
  1494. if ( camera.type === 'perspective' ) {
  1495. var aspectRatio = params.aspectRatio || 1;
  1496. var xfov = params.yfov * aspectRatio;
  1497. _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
  1498. } else if ( camera.type === 'orthographic' ) {
  1499. _camera = new THREE.OrthographicCamera( params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar );
  1500. }
  1501. if ( camera.name !== undefined ) _camera.name = camera.name;
  1502. if ( camera.extras ) _camera.userData = camera.extras;
  1503. return _camera;
  1504. } );
  1505. };
  1506. GLTFParser.prototype.loadSkins = function () {
  1507. var json = this.json;
  1508. return this._withDependencies( [
  1509. 'accessors'
  1510. ] ).then( function ( dependencies ) {
  1511. return _each( json.skins, function ( skin ) {
  1512. var _skin = {
  1513. joints: skin.joints,
  1514. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1515. };
  1516. return _skin;
  1517. } );
  1518. } );
  1519. };
  1520. GLTFParser.prototype.loadAnimations = function () {
  1521. var json = this.json;
  1522. return this._withDependencies( [
  1523. 'accessors',
  1524. 'nodes'
  1525. ] ).then( function ( dependencies ) {
  1526. return _each( json.animations, function ( animation, animationId ) {
  1527. var tracks = [];
  1528. for ( var channelId in animation.channels ) {
  1529. var channel = animation.channels[ channelId ];
  1530. var sampler = animation.samplers[ channel.sampler ];
  1531. if ( sampler ) {
  1532. var target = channel.target;
  1533. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1534. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1535. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1536. var inputAccessor = dependencies.accessors[ input ];
  1537. var outputAccessor = dependencies.accessors[ output ];
  1538. var node = dependencies.nodes[ name ];
  1539. if ( node ) {
  1540. node.updateMatrix();
  1541. node.matrixAutoUpdate = true;
  1542. var TypedKeyframeTrack;
  1543. switch ( PATH_PROPERTIES[ target.path ] ) {
  1544. case PATH_PROPERTIES.weights:
  1545. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1546. break;
  1547. case PATH_PROPERTIES.rotation:
  1548. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1549. break;
  1550. case PATH_PROPERTIES.position:
  1551. case PATH_PROPERTIES.scale:
  1552. default:
  1553. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1554. break;
  1555. }
  1556. var targetName = node.name ? node.name : node.uuid;
  1557. if ( sampler.interpolation === 'CATMULLROMSPLINE' ) {
  1558. console.warn( 'THREE.GLTF2Loader: CATMULLROMSPLINE interpolation is not supported. Using CUBICSPLINE instead.' );
  1559. }
  1560. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1561. var targetNames = [];
  1562. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1563. // node should be THREE.Group here but
  1564. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1565. // the property of a mesh object under node.
  1566. // So finding targets here.
  1567. node.traverse( function ( object ) {
  1568. if ( object.isMesh === true && object.material.morphTargets === true ) {
  1569. targetNames.push( object.name ? object.name : object.uuid );
  1570. }
  1571. } );
  1572. } else {
  1573. targetNames.push( targetName );
  1574. }
  1575. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1576. // buffers before creating a truncated copy to keep. Because buffers may
  1577. // be reused by other tracks, make copies here.
  1578. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  1579. tracks.push( new TypedKeyframeTrack(
  1580. targetNames[ i ] + '.' + PATH_PROPERTIES[ target.path ],
  1581. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1582. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1583. interpolation
  1584. ) );
  1585. }
  1586. }
  1587. }
  1588. }
  1589. var name = animation.name !== undefined ? animation.name : 'animation_' + animationId;
  1590. return new THREE.AnimationClip( name, undefined, tracks );
  1591. } );
  1592. } );
  1593. };
  1594. GLTFParser.prototype.loadNodes = function () {
  1595. var json = this.json;
  1596. var extensions = this.extensions;
  1597. var scope = this;
  1598. var nodes = json.nodes || [];
  1599. var skins = json.skins || [];
  1600. // Nothing in the node definition indicates whether it is a Bone or an
  1601. // Object3D. Use the skins' joint references to mark bones.
  1602. skins.forEach( function ( skin ) {
  1603. skin.joints.forEach( function ( id ) {
  1604. nodes[ id ].isBone = true;
  1605. } );
  1606. } );
  1607. return _each( json.nodes, function ( node ) {
  1608. var matrix = new THREE.Matrix4();
  1609. var _node = node.isBone === true ? new THREE.Bone() : new THREE.Object3D();
  1610. if ( node.name !== undefined ) {
  1611. _node.name = THREE.PropertyBinding.sanitizeNodeName( node.name );
  1612. }
  1613. if ( node.extras ) _node.userData = node.extras;
  1614. if ( node.matrix !== undefined ) {
  1615. matrix.fromArray( node.matrix );
  1616. _node.applyMatrix( matrix );
  1617. } else {
  1618. if ( node.translation !== undefined ) {
  1619. _node.position.fromArray( node.translation );
  1620. }
  1621. if ( node.rotation !== undefined ) {
  1622. _node.quaternion.fromArray( node.rotation );
  1623. }
  1624. if ( node.scale !== undefined ) {
  1625. _node.scale.fromArray( node.scale );
  1626. }
  1627. }
  1628. return _node;
  1629. } ).then( function ( __nodes ) {
  1630. return scope._withDependencies( [
  1631. 'meshes',
  1632. 'skins',
  1633. 'cameras'
  1634. ] ).then( function ( dependencies ) {
  1635. return _each( __nodes, function ( _node, nodeId ) {
  1636. var node = json.nodes[ nodeId ];
  1637. var meshes;
  1638. if ( node.mesh !== undefined) {
  1639. meshes = [ node.mesh ];
  1640. } else if ( node.meshes !== undefined ) {
  1641. console.warn( 'THREE.GLTF2Loader: Legacy glTF file detected. Nodes may have no more than one mesh.' );
  1642. meshes = node.meshes;
  1643. }
  1644. if ( meshes !== undefined ) {
  1645. for ( var meshId in meshes ) {
  1646. var mesh = meshes[ meshId ];
  1647. var group = dependencies.meshes[ mesh ];
  1648. if ( group === undefined ) {
  1649. console.warn( 'THREE.GLTF2Loader: Could not find node "' + mesh + '".' );
  1650. continue;
  1651. }
  1652. // do not clone children as they will be replaced anyway
  1653. var clonedgroup = group.clone( false );
  1654. for ( var childrenId in group.children ) {
  1655. var child = group.children[ childrenId ];
  1656. // clone Mesh to add to _node
  1657. var originalMaterial = child.material;
  1658. var originalGeometry = child.geometry;
  1659. var originalInfluences = child.morphTargetInfluences;
  1660. var originalUserData = child.userData;
  1661. var originalName = child.name;
  1662. var material;
  1663. if ( originalMaterial.isDeferredShaderMaterial ) {
  1664. originalMaterial = material = originalMaterial.create();
  1665. } else {
  1666. material = originalMaterial;
  1667. }
  1668. switch ( child.type ) {
  1669. case 'LineSegments':
  1670. child = new THREE.LineSegments( originalGeometry, material );
  1671. break;
  1672. case 'LineLoop':
  1673. child = new THREE.LineLoop( originalGeometry, material );
  1674. break;
  1675. case 'Line':
  1676. child = new THREE.Line( originalGeometry, material );
  1677. break;
  1678. default:
  1679. child = new THREE.Mesh( originalGeometry, material );
  1680. }
  1681. child.castShadow = true;
  1682. child.morphTargetInfluences = originalInfluences;
  1683. child.userData = originalUserData;
  1684. child.name = originalName;
  1685. var skinEntry;
  1686. if ( node.skin !== undefined ) {
  1687. skinEntry = dependencies.skins[ node.skin ];
  1688. }
  1689. // Replace Mesh with SkinnedMesh in library
  1690. if ( skinEntry ) {
  1691. var geometry = originalGeometry;
  1692. material = originalMaterial;
  1693. material.skinning = true;
  1694. child = new THREE.SkinnedMesh( geometry, material );
  1695. child.castShadow = true;
  1696. child.userData = originalUserData;
  1697. child.name = originalName;
  1698. var bones = [];
  1699. var boneInverses = [];
  1700. for ( var i = 0, l = skinEntry.joints.length; i < l; i ++ ) {
  1701. var jointId = skinEntry.joints[ i ];
  1702. var jointNode = __nodes[ jointId ];
  1703. if ( jointNode ) {
  1704. bones.push( jointNode );
  1705. var m = skinEntry.inverseBindMatrices.array;
  1706. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  1707. boneInverses.push( mat );
  1708. } else {
  1709. console.warn( 'THREE.GLTF2Loader: Joint "%s" could not be found.', jointId );
  1710. }
  1711. }
  1712. child.bind( new THREE.Skeleton( bones, boneInverses ), child.matrixWorld );
  1713. }
  1714. clonedgroup.add( child );
  1715. }
  1716. _node.add( clonedgroup );
  1717. }
  1718. }
  1719. if ( node.camera !== undefined ) {
  1720. var camera = dependencies.cameras[ node.camera ];
  1721. _node.add( camera );
  1722. }
  1723. if ( node.extensions
  1724. && node.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1725. && node.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1726. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1727. _node.add( lights[ node.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1728. }
  1729. return _node;
  1730. } );
  1731. } );
  1732. } );
  1733. };
  1734. GLTFParser.prototype.loadScenes = function () {
  1735. var json = this.json;
  1736. var extensions = this.extensions;
  1737. // scene node hierachy builder
  1738. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1739. var _node = allNodes[ nodeId ];
  1740. parentObject.add( _node );
  1741. var node = json.nodes[ nodeId ];
  1742. if ( node.children ) {
  1743. var children = node.children;
  1744. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1745. var child = children[ i ];
  1746. buildNodeHierachy( child, _node, allNodes );
  1747. }
  1748. }
  1749. }
  1750. return this._withDependencies( [
  1751. 'nodes'
  1752. ] ).then( function ( dependencies ) {
  1753. return _each( json.scenes, function ( scene ) {
  1754. var _scene = new THREE.Scene();
  1755. if ( scene.name !== undefined ) _scene.name = scene.name;
  1756. if ( scene.extras ) _scene.userData = scene.extras;
  1757. var nodes = scene.nodes || [];
  1758. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1759. var nodeId = nodes[ i ];
  1760. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1761. }
  1762. _scene.traverse( function ( child ) {
  1763. // Register raw material meshes with GLTF2Loader.Shaders
  1764. if ( child.material && child.material.isRawShaderMaterial ) {
  1765. child.gltfShader = new GLTFShader( child, dependencies.nodes );
  1766. child.onBeforeRender = function(renderer, scene, camera){
  1767. this.gltfShader.update(scene, camera);
  1768. };
  1769. }
  1770. // for Specular-Glossiness.
  1771. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial ) {
  1772. child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1773. }
  1774. } );
  1775. // Ambient lighting, if present, is always attached to the scene root.
  1776. if ( scene.extensions
  1777. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1778. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1779. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1780. _scene.add( lights[ scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1781. }
  1782. return _scene;
  1783. } );
  1784. } );
  1785. };
  1786. return GLTF2Loader;
  1787. } )();