GLTFLoader.js 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295
  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.GLTFLoader = ( function () {
  9. function GLTFLoader( manager ) {
  10. THREE.Loader.call( this, manager );
  11. this.dracoLoader = null;
  12. this.ddsLoader = null;
  13. }
  14. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  15. constructor: GLTFLoader,
  16. load: function ( url, onLoad, onProgress, onError ) {
  17. var scope = this;
  18. var resourcePath;
  19. if ( this.resourcePath !== '' ) {
  20. resourcePath = this.resourcePath;
  21. } else if ( this.path !== '' ) {
  22. resourcePath = this.path;
  23. } else {
  24. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  25. }
  26. // Tells the LoadingManager to track an extra item, which resolves after
  27. // the model is fully loaded. This means the count of items loaded will
  28. // be incorrect, but ensures manager.onLoad() does not fire early.
  29. scope.manager.itemStart( url );
  30. var _onError = function ( e ) {
  31. if ( onError ) {
  32. onError( e );
  33. } else {
  34. console.error( e );
  35. }
  36. scope.manager.itemError( url );
  37. scope.manager.itemEnd( url );
  38. };
  39. var loader = new THREE.FileLoader( scope.manager );
  40. loader.setPath( this.path );
  41. loader.setResponseType( 'arraybuffer' );
  42. if ( scope.crossOrigin === 'use-credentials' ) {
  43. loader.setWithCredentials( true );
  44. }
  45. loader.load( url, function ( data ) {
  46. try {
  47. scope.parse( data, resourcePath, function ( gltf ) {
  48. onLoad( gltf );
  49. scope.manager.itemEnd( url );
  50. }, _onError );
  51. } catch ( e ) {
  52. _onError( e );
  53. }
  54. }, onProgress, _onError );
  55. },
  56. setDRACOLoader: function ( dracoLoader ) {
  57. this.dracoLoader = dracoLoader;
  58. return this;
  59. },
  60. setDDSLoader: function ( ddsLoader ) {
  61. this.ddsLoader = ddsLoader;
  62. return this;
  63. },
  64. parse: function ( data, path, onLoad, onError ) {
  65. var content;
  66. var extensions = {};
  67. if ( typeof data === 'string' ) {
  68. content = data;
  69. } else {
  70. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  71. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  72. try {
  73. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  74. } catch ( error ) {
  75. if ( onError ) onError( error );
  76. return;
  77. }
  78. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  79. } else {
  80. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  81. }
  82. }
  83. var json = JSON.parse( content );
  84. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  85. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  86. return;
  87. }
  88. if ( json.extensionsUsed ) {
  89. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  90. var extensionName = json.extensionsUsed[ i ];
  91. var extensionsRequired = json.extensionsRequired || [];
  92. switch ( extensionName ) {
  93. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  94. extensions[ extensionName ] = new GLTFLightsExtension( json );
  95. break;
  96. case EXTENSIONS.KHR_MATERIALS_CLEARCOAT:
  97. extensions[ extensionName ] = new GLTFMaterialsClearcoatExtension();
  98. break;
  99. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  100. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  101. break;
  102. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  103. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  104. break;
  105. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  106. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  107. break;
  108. case EXTENSIONS.MSFT_TEXTURE_DDS:
  109. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  110. break;
  111. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  112. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  113. break;
  114. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  115. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  116. break;
  117. default:
  118. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  119. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  120. }
  121. }
  122. }
  123. }
  124. var parser = new GLTFParser( json, extensions, {
  125. path: path || this.resourcePath || '',
  126. crossOrigin: this.crossOrigin,
  127. manager: this.manager
  128. } );
  129. parser.parse( onLoad, onError );
  130. }
  131. } );
  132. /* GLTFREGISTRY */
  133. function GLTFRegistry() {
  134. var objects = {};
  135. return {
  136. get: function ( key ) {
  137. return objects[ key ];
  138. },
  139. add: function ( key, object ) {
  140. objects[ key ] = object;
  141. },
  142. remove: function ( key ) {
  143. delete objects[ key ];
  144. },
  145. removeAll: function () {
  146. objects = {};
  147. }
  148. };
  149. }
  150. /*********************************/
  151. /********** EXTENSIONS ***********/
  152. /*********************************/
  153. var EXTENSIONS = {
  154. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  155. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  156. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  157. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  158. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  159. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  160. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  161. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  162. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  163. };
  164. /**
  165. * DDS Texture Extension
  166. *
  167. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  168. *
  169. */
  170. function GLTFTextureDDSExtension( ddsLoader ) {
  171. if ( ! ddsLoader ) {
  172. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  173. }
  174. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  175. this.ddsLoader = ddsLoader;
  176. }
  177. /**
  178. * Punctual Lights Extension
  179. *
  180. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  181. */
  182. function GLTFLightsExtension( json ) {
  183. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  184. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  185. this.lightDefs = extension.lights || [];
  186. }
  187. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  188. var lightDef = this.lightDefs[ lightIndex ];
  189. var lightNode;
  190. var color = new THREE.Color( 0xffffff );
  191. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  192. var range = lightDef.range !== undefined ? lightDef.range : 0;
  193. switch ( lightDef.type ) {
  194. case 'directional':
  195. lightNode = new THREE.DirectionalLight( color );
  196. lightNode.target.position.set( 0, 0, - 1 );
  197. lightNode.add( lightNode.target );
  198. break;
  199. case 'point':
  200. lightNode = new THREE.PointLight( color );
  201. lightNode.distance = range;
  202. break;
  203. case 'spot':
  204. lightNode = new THREE.SpotLight( color );
  205. lightNode.distance = range;
  206. // Handle spotlight properties.
  207. lightDef.spot = lightDef.spot || {};
  208. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  209. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  210. lightNode.angle = lightDef.spot.outerConeAngle;
  211. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  212. lightNode.target.position.set( 0, 0, - 1 );
  213. lightNode.add( lightNode.target );
  214. break;
  215. default:
  216. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  217. }
  218. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  219. // here, because node-level parsing will only override position if explicitly specified.
  220. lightNode.position.set( 0, 0, 0 );
  221. lightNode.decay = 2;
  222. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  223. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  224. return Promise.resolve( lightNode );
  225. };
  226. /**
  227. * Unlit Materials Extension
  228. *
  229. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  230. */
  231. function GLTFMaterialsUnlitExtension() {
  232. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  233. }
  234. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  235. return THREE.MeshBasicMaterial;
  236. };
  237. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  238. var pending = [];
  239. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  240. materialParams.opacity = 1.0;
  241. var metallicRoughness = materialDef.pbrMetallicRoughness;
  242. if ( metallicRoughness ) {
  243. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  244. var array = metallicRoughness.baseColorFactor;
  245. materialParams.color.fromArray( array );
  246. materialParams.opacity = array[ 3 ];
  247. }
  248. if ( metallicRoughness.baseColorTexture !== undefined ) {
  249. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  250. }
  251. }
  252. return Promise.all( pending );
  253. };
  254. /**
  255. * Clearcoat Materials Extension
  256. *
  257. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  258. */
  259. function GLTFMaterialsClearcoatExtension() {
  260. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  261. }
  262. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function () {
  263. return THREE.MeshPhysicalMaterial;
  264. };
  265. GLTFMaterialsClearcoatExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  266. var pending = [];
  267. var extension = materialDef.extensions[ this.name ];
  268. if ( extension.clearcoatFactor !== undefined ) {
  269. materialParams.clearcoat = extension.clearcoatFactor;
  270. }
  271. if ( extension.clearcoatTexture !== undefined ) {
  272. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  273. }
  274. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  275. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  276. }
  277. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  278. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  279. }
  280. if ( extension.clearcoatNormalTexture !== undefined ) {
  281. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  282. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  283. var scale = extension.clearcoatNormalTexture.scale;
  284. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, scale );
  285. }
  286. }
  287. return Promise.all( pending );
  288. };
  289. /* BINARY EXTENSION */
  290. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  291. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  292. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  293. function GLTFBinaryExtension( data ) {
  294. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  295. this.content = null;
  296. this.body = null;
  297. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  298. this.header = {
  299. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  300. version: headerView.getUint32( 4, true ),
  301. length: headerView.getUint32( 8, true )
  302. };
  303. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  304. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  305. } else if ( this.header.version < 2.0 ) {
  306. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  307. }
  308. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  309. var chunkIndex = 0;
  310. while ( chunkIndex < chunkView.byteLength ) {
  311. var chunkLength = chunkView.getUint32( chunkIndex, true );
  312. chunkIndex += 4;
  313. var chunkType = chunkView.getUint32( chunkIndex, true );
  314. chunkIndex += 4;
  315. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  316. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  317. this.content = THREE.LoaderUtils.decodeText( contentArray );
  318. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  319. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  320. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  321. }
  322. // Clients must ignore chunks with unknown types.
  323. chunkIndex += chunkLength;
  324. }
  325. if ( this.content === null ) {
  326. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  327. }
  328. }
  329. /**
  330. * DRACO Mesh Compression Extension
  331. *
  332. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  333. */
  334. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  335. if ( ! dracoLoader ) {
  336. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  337. }
  338. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  339. this.json = json;
  340. this.dracoLoader = dracoLoader;
  341. this.dracoLoader.preload();
  342. }
  343. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  344. var json = this.json;
  345. var dracoLoader = this.dracoLoader;
  346. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  347. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  348. var threeAttributeMap = {};
  349. var attributeNormalizedMap = {};
  350. var attributeTypeMap = {};
  351. for ( var attributeName in gltfAttributeMap ) {
  352. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  353. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  354. }
  355. for ( attributeName in primitive.attributes ) {
  356. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  357. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  358. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  359. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  360. attributeTypeMap[ threeAttributeName ] = componentType;
  361. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  362. }
  363. }
  364. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  365. return new Promise( function ( resolve ) {
  366. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  367. for ( var attributeName in geometry.attributes ) {
  368. var attribute = geometry.attributes[ attributeName ];
  369. var normalized = attributeNormalizedMap[ attributeName ];
  370. if ( normalized !== undefined ) attribute.normalized = normalized;
  371. }
  372. resolve( geometry );
  373. }, threeAttributeMap, attributeTypeMap );
  374. } );
  375. } );
  376. };
  377. /**
  378. * Texture Transform Extension
  379. *
  380. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  381. */
  382. function GLTFTextureTransformExtension() {
  383. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  384. }
  385. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  386. texture = texture.clone();
  387. if ( transform.offset !== undefined ) {
  388. texture.offset.fromArray( transform.offset );
  389. }
  390. if ( transform.rotation !== undefined ) {
  391. texture.rotation = transform.rotation;
  392. }
  393. if ( transform.scale !== undefined ) {
  394. texture.repeat.fromArray( transform.scale );
  395. }
  396. if ( transform.texCoord !== undefined ) {
  397. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  398. }
  399. texture.needsUpdate = true;
  400. return texture;
  401. };
  402. /**
  403. * Specular-Glossiness Extension
  404. *
  405. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  406. */
  407. /**
  408. * A sub class of THREE.StandardMaterial with some of the functionality
  409. * changed via the `onBeforeCompile` callback
  410. * @pailhead
  411. */
  412. function GLTFMeshStandardSGMaterial( params ) {
  413. THREE.MeshStandardMaterial.call( this );
  414. this.isGLTFSpecularGlossinessMaterial = true;
  415. //various chunks that need replacing
  416. var specularMapParsFragmentChunk = [
  417. '#ifdef USE_SPECULARMAP',
  418. ' uniform sampler2D specularMap;',
  419. '#endif'
  420. ].join( '\n' );
  421. var glossinessMapParsFragmentChunk = [
  422. '#ifdef USE_GLOSSINESSMAP',
  423. ' uniform sampler2D glossinessMap;',
  424. '#endif'
  425. ].join( '\n' );
  426. var specularMapFragmentChunk = [
  427. 'vec3 specularFactor = specular;',
  428. '#ifdef USE_SPECULARMAP',
  429. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  430. ' texelSpecular = sRGBToLinear( texelSpecular );',
  431. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  432. ' specularFactor *= texelSpecular.rgb;',
  433. '#endif'
  434. ].join( '\n' );
  435. var glossinessMapFragmentChunk = [
  436. 'float glossinessFactor = glossiness;',
  437. '#ifdef USE_GLOSSINESSMAP',
  438. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  439. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  440. ' glossinessFactor *= texelGlossiness.a;',
  441. '#endif'
  442. ].join( '\n' );
  443. var lightPhysicalFragmentChunk = [
  444. 'PhysicalMaterial material;',
  445. 'material.diffuseColor = diffuseColor.rgb;',
  446. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  447. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  448. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 );// 0.0525 corresponds to the base mip of a 256 cubemap.',
  449. 'material.specularRoughness += geometryRoughness;',
  450. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  451. 'material.specularColor = specularFactor.rgb;',
  452. ].join( '\n' );
  453. var uniforms = {
  454. specular: { value: new THREE.Color().setHex( 0xffffff ) },
  455. glossiness: { value: 1 },
  456. specularMap: { value: null },
  457. glossinessMap: { value: null }
  458. };
  459. this._extraUniforms = uniforms;
  460. // please see #14031 or #13198 for an alternate approach
  461. this.onBeforeCompile = function ( shader ) {
  462. for ( var uniformName in uniforms ) {
  463. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  464. }
  465. shader.fragmentShader = shader.fragmentShader.replace( 'uniform float roughness;', 'uniform vec3 specular;' );
  466. shader.fragmentShader = shader.fragmentShader.replace( 'uniform float metalness;', 'uniform float glossiness;' );
  467. shader.fragmentShader = shader.fragmentShader.replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk );
  468. shader.fragmentShader = shader.fragmentShader.replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk );
  469. shader.fragmentShader = shader.fragmentShader.replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk );
  470. shader.fragmentShader = shader.fragmentShader.replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk );
  471. shader.fragmentShader = shader.fragmentShader.replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  472. };
  473. /*eslint-disable*/
  474. Object.defineProperties(
  475. this,
  476. {
  477. specular: {
  478. get: function () { return uniforms.specular.value; },
  479. set: function ( v ) { uniforms.specular.value = v; }
  480. },
  481. specularMap: {
  482. get: function () { return uniforms.specularMap.value; },
  483. set: function ( v ) { uniforms.specularMap.value = v; }
  484. },
  485. glossiness: {
  486. get: function () { return uniforms.glossiness.value; },
  487. set: function ( v ) { uniforms.glossiness.value = v; }
  488. },
  489. glossinessMap: {
  490. get: function () { return uniforms.glossinessMap.value; },
  491. set: function ( v ) {
  492. uniforms.glossinessMap.value = v;
  493. //how about something like this - @pailhead
  494. if ( v ) {
  495. this.defines.USE_GLOSSINESSMAP = '';
  496. // set USE_ROUGHNESSMAP to enable vUv
  497. this.defines.USE_ROUGHNESSMAP = '';
  498. } else {
  499. delete this.defines.USE_ROUGHNESSMAP;
  500. delete this.defines.USE_GLOSSINESSMAP;
  501. }
  502. }
  503. }
  504. }
  505. );
  506. /*eslint-enable*/
  507. delete this.metalness;
  508. delete this.roughness;
  509. delete this.metalnessMap;
  510. delete this.roughnessMap;
  511. this.setValues( params );
  512. }
  513. GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  514. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  515. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  516. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  517. this.specularMap = source.specularMap;
  518. this.specular.copy( source.specular );
  519. this.glossinessMap = source.glossinessMap;
  520. this.glossiness = source.glossiness;
  521. delete this.metalness;
  522. delete this.roughness;
  523. delete this.metalnessMap;
  524. delete this.roughnessMap;
  525. return this;
  526. };
  527. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  528. return {
  529. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  530. specularGlossinessParams: [
  531. 'color',
  532. 'map',
  533. 'lightMap',
  534. 'lightMapIntensity',
  535. 'aoMap',
  536. 'aoMapIntensity',
  537. 'emissive',
  538. 'emissiveIntensity',
  539. 'emissiveMap',
  540. 'bumpMap',
  541. 'bumpScale',
  542. 'normalMap',
  543. 'normalMapType',
  544. 'displacementMap',
  545. 'displacementScale',
  546. 'displacementBias',
  547. 'specularMap',
  548. 'specular',
  549. 'glossinessMap',
  550. 'glossiness',
  551. 'alphaMap',
  552. 'envMap',
  553. 'envMapIntensity',
  554. 'refractionRatio',
  555. ],
  556. getMaterialType: function () {
  557. return GLTFMeshStandardSGMaterial;
  558. },
  559. extendParams: function ( materialParams, materialDef, parser ) {
  560. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  561. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  562. materialParams.opacity = 1.0;
  563. var pending = [];
  564. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  565. var array = pbrSpecularGlossiness.diffuseFactor;
  566. materialParams.color.fromArray( array );
  567. materialParams.opacity = array[ 3 ];
  568. }
  569. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  570. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  571. }
  572. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  573. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  574. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  575. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  576. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  577. }
  578. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  579. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  580. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  581. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  582. }
  583. return Promise.all( pending );
  584. },
  585. createMaterial: function ( materialParams ) {
  586. var material = new GLTFMeshStandardSGMaterial( materialParams );
  587. material.fog = true;
  588. material.color = materialParams.color;
  589. material.map = materialParams.map === undefined ? null : materialParams.map;
  590. material.lightMap = null;
  591. material.lightMapIntensity = 1.0;
  592. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  593. material.aoMapIntensity = 1.0;
  594. material.emissive = materialParams.emissive;
  595. material.emissiveIntensity = 1.0;
  596. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  597. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  598. material.bumpScale = 1;
  599. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  600. material.normalMapType = THREE.TangentSpaceNormalMap;
  601. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  602. material.displacementMap = null;
  603. material.displacementScale = 1;
  604. material.displacementBias = 0;
  605. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  606. material.specular = materialParams.specular;
  607. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  608. material.glossiness = materialParams.glossiness;
  609. material.alphaMap = null;
  610. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  611. material.envMapIntensity = 1.0;
  612. material.refractionRatio = 0.98;
  613. return material;
  614. },
  615. };
  616. }
  617. /**
  618. * Mesh Quantization Extension
  619. *
  620. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  621. */
  622. function GLTFMeshQuantizationExtension() {
  623. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  624. }
  625. /*********************************/
  626. /********** INTERPOLATION ********/
  627. /*********************************/
  628. // Spline Interpolation
  629. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  630. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  631. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  632. }
  633. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  634. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  635. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  636. // Copies a sample value to the result buffer. See description of glTF
  637. // CUBICSPLINE values layout in interpolate_() function below.
  638. var result = this.resultBuffer,
  639. values = this.sampleValues,
  640. valueSize = this.valueSize,
  641. offset = index * valueSize * 3 + valueSize;
  642. for ( var i = 0; i !== valueSize; i ++ ) {
  643. result[ i ] = values[ offset + i ];
  644. }
  645. return result;
  646. };
  647. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  648. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  649. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  650. var result = this.resultBuffer;
  651. var values = this.sampleValues;
  652. var stride = this.valueSize;
  653. var stride2 = stride * 2;
  654. var stride3 = stride * 3;
  655. var td = t1 - t0;
  656. var p = ( t - t0 ) / td;
  657. var pp = p * p;
  658. var ppp = pp * p;
  659. var offset1 = i1 * stride3;
  660. var offset0 = offset1 - stride3;
  661. var s2 = - 2 * ppp + 3 * pp;
  662. var s3 = ppp - pp;
  663. var s0 = 1 - s2;
  664. var s1 = s3 - pp + p;
  665. // Layout of keyframe output values for CUBICSPLINE animations:
  666. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  667. for ( var i = 0; i !== stride; i ++ ) {
  668. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  669. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  670. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  671. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  672. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  673. }
  674. return result;
  675. };
  676. /*********************************/
  677. /********** INTERNALS ************/
  678. /*********************************/
  679. /* CONSTANTS */
  680. var WEBGL_CONSTANTS = {
  681. FLOAT: 5126,
  682. //FLOAT_MAT2: 35674,
  683. FLOAT_MAT3: 35675,
  684. FLOAT_MAT4: 35676,
  685. FLOAT_VEC2: 35664,
  686. FLOAT_VEC3: 35665,
  687. FLOAT_VEC4: 35666,
  688. LINEAR: 9729,
  689. REPEAT: 10497,
  690. SAMPLER_2D: 35678,
  691. POINTS: 0,
  692. LINES: 1,
  693. LINE_LOOP: 2,
  694. LINE_STRIP: 3,
  695. TRIANGLES: 4,
  696. TRIANGLE_STRIP: 5,
  697. TRIANGLE_FAN: 6,
  698. UNSIGNED_BYTE: 5121,
  699. UNSIGNED_SHORT: 5123
  700. };
  701. var WEBGL_COMPONENT_TYPES = {
  702. 5120: Int8Array,
  703. 5121: Uint8Array,
  704. 5122: Int16Array,
  705. 5123: Uint16Array,
  706. 5125: Uint32Array,
  707. 5126: Float32Array
  708. };
  709. var WEBGL_FILTERS = {
  710. 9728: THREE.NearestFilter,
  711. 9729: THREE.LinearFilter,
  712. 9984: THREE.NearestMipmapNearestFilter,
  713. 9985: THREE.LinearMipmapNearestFilter,
  714. 9986: THREE.NearestMipmapLinearFilter,
  715. 9987: THREE.LinearMipmapLinearFilter
  716. };
  717. var WEBGL_WRAPPINGS = {
  718. 33071: THREE.ClampToEdgeWrapping,
  719. 33648: THREE.MirroredRepeatWrapping,
  720. 10497: THREE.RepeatWrapping
  721. };
  722. var WEBGL_TYPE_SIZES = {
  723. 'SCALAR': 1,
  724. 'VEC2': 2,
  725. 'VEC3': 3,
  726. 'VEC4': 4,
  727. 'MAT2': 4,
  728. 'MAT3': 9,
  729. 'MAT4': 16
  730. };
  731. var ATTRIBUTES = {
  732. POSITION: 'position',
  733. NORMAL: 'normal',
  734. TANGENT: 'tangent',
  735. TEXCOORD_0: 'uv',
  736. TEXCOORD_1: 'uv2',
  737. COLOR_0: 'color',
  738. WEIGHTS_0: 'skinWeight',
  739. JOINTS_0: 'skinIndex',
  740. };
  741. var PATH_PROPERTIES = {
  742. scale: 'scale',
  743. translation: 'position',
  744. rotation: 'quaternion',
  745. weights: 'morphTargetInfluences'
  746. };
  747. var INTERPOLATION = {
  748. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  749. // keyframe track will be initialized with a default interpolation type, then modified.
  750. LINEAR: THREE.InterpolateLinear,
  751. STEP: THREE.InterpolateDiscrete
  752. };
  753. var ALPHA_MODES = {
  754. OPAQUE: 'OPAQUE',
  755. MASK: 'MASK',
  756. BLEND: 'BLEND'
  757. };
  758. var MIME_TYPE_FORMATS = {
  759. 'image/png': THREE.RGBAFormat,
  760. 'image/jpeg': THREE.RGBFormat
  761. };
  762. /* UTILITY FUNCTIONS */
  763. function resolveURL( url, path ) {
  764. // Invalid URL
  765. if ( typeof url !== 'string' || url === '' ) return '';
  766. // Host Relative URL
  767. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  768. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  769. }
  770. // Absolute URL http://,https://,//
  771. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  772. // Data URI
  773. if ( /^data:.*,.*$/i.test( url ) ) return url;
  774. // Blob URL
  775. if ( /^blob:.*$/i.test( url ) ) return url;
  776. // Relative URL
  777. return path + url;
  778. }
  779. /**
  780. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  781. */
  782. function createDefaultMaterial( cache ) {
  783. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  784. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  785. color: 0xFFFFFF,
  786. emissive: 0x000000,
  787. metalness: 1,
  788. roughness: 1,
  789. transparent: false,
  790. depthTest: true,
  791. side: THREE.FrontSide
  792. } );
  793. }
  794. return cache[ 'DefaultMaterial' ];
  795. }
  796. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  797. // Add unknown glTF extensions to an object's userData.
  798. for ( var name in objectDef.extensions ) {
  799. if ( knownExtensions[ name ] === undefined ) {
  800. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  801. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  802. }
  803. }
  804. }
  805. /**
  806. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  807. * @param {GLTF.definition} gltfDef
  808. */
  809. function assignExtrasToUserData( object, gltfDef ) {
  810. if ( gltfDef.extras !== undefined ) {
  811. if ( typeof gltfDef.extras === 'object' ) {
  812. Object.assign( object.userData, gltfDef.extras );
  813. } else {
  814. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  815. }
  816. }
  817. }
  818. /**
  819. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  820. *
  821. * @param {THREE.BufferGeometry} geometry
  822. * @param {Array<GLTF.Target>} targets
  823. * @param {GLTFParser} parser
  824. * @return {Promise<THREE.BufferGeometry>}
  825. */
  826. function addMorphTargets( geometry, targets, parser ) {
  827. var hasMorphPosition = false;
  828. var hasMorphNormal = false;
  829. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  830. var target = targets[ i ];
  831. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  832. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  833. if ( hasMorphPosition && hasMorphNormal ) break;
  834. }
  835. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  836. var pendingPositionAccessors = [];
  837. var pendingNormalAccessors = [];
  838. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  839. var target = targets[ i ];
  840. if ( hasMorphPosition ) {
  841. var pendingAccessor = target.POSITION !== undefined
  842. ? parser.getDependency( 'accessor', target.POSITION )
  843. : geometry.attributes.position;
  844. pendingPositionAccessors.push( pendingAccessor );
  845. }
  846. if ( hasMorphNormal ) {
  847. var pendingAccessor = target.NORMAL !== undefined
  848. ? parser.getDependency( 'accessor', target.NORMAL )
  849. : geometry.attributes.normal;
  850. pendingNormalAccessors.push( pendingAccessor );
  851. }
  852. }
  853. return Promise.all( [
  854. Promise.all( pendingPositionAccessors ),
  855. Promise.all( pendingNormalAccessors )
  856. ] ).then( function ( accessors ) {
  857. var morphPositions = accessors[ 0 ];
  858. var morphNormals = accessors[ 1 ];
  859. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  860. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  861. geometry.morphTargetsRelative = true;
  862. return geometry;
  863. } );
  864. }
  865. /**
  866. * @param {THREE.Mesh} mesh
  867. * @param {GLTF.Mesh} meshDef
  868. */
  869. function updateMorphTargets( mesh, meshDef ) {
  870. mesh.updateMorphTargets();
  871. if ( meshDef.weights !== undefined ) {
  872. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  873. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  874. }
  875. }
  876. // .extras has user-defined data, so check that .extras.targetNames is an array.
  877. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  878. var targetNames = meshDef.extras.targetNames;
  879. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  880. mesh.morphTargetDictionary = {};
  881. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  882. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  883. }
  884. } else {
  885. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  886. }
  887. }
  888. }
  889. function createPrimitiveKey( primitiveDef ) {
  890. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  891. var geometryKey;
  892. if ( dracoExtension ) {
  893. geometryKey = 'draco:' + dracoExtension.bufferView
  894. + ':' + dracoExtension.indices
  895. + ':' + createAttributesKey( dracoExtension.attributes );
  896. } else {
  897. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  898. }
  899. return geometryKey;
  900. }
  901. function createAttributesKey( attributes ) {
  902. var attributesKey = '';
  903. var keys = Object.keys( attributes ).sort();
  904. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  905. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  906. }
  907. return attributesKey;
  908. }
  909. /* GLTF PARSER */
  910. function GLTFParser( json, extensions, options ) {
  911. this.json = json || {};
  912. this.extensions = extensions || {};
  913. this.options = options || {};
  914. // loader object cache
  915. this.cache = new GLTFRegistry();
  916. // associations between Three.js objects and glTF elements
  917. this.associations = new Map();
  918. // BufferGeometry caching
  919. this.primitiveCache = {};
  920. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  921. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  922. this.fileLoader = new THREE.FileLoader( this.options.manager );
  923. this.fileLoader.setResponseType( 'arraybuffer' );
  924. if ( this.options.crossOrigin === 'use-credentials' ) {
  925. this.fileLoader.setWithCredentials( true );
  926. }
  927. }
  928. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  929. var parser = this;
  930. var json = this.json;
  931. var extensions = this.extensions;
  932. // Clear the loader cache
  933. this.cache.removeAll();
  934. // Mark the special nodes/meshes in json for efficient parse
  935. this.markDefs();
  936. Promise.all( [
  937. this.getDependencies( 'scene' ),
  938. this.getDependencies( 'animation' ),
  939. this.getDependencies( 'camera' ),
  940. ] ).then( function ( dependencies ) {
  941. var result = {
  942. scene: dependencies[ 0 ][ json.scene || 0 ],
  943. scenes: dependencies[ 0 ],
  944. animations: dependencies[ 1 ],
  945. cameras: dependencies[ 2 ],
  946. asset: json.asset,
  947. parser: parser,
  948. userData: {}
  949. };
  950. addUnknownExtensionsToUserData( extensions, result, json );
  951. assignExtrasToUserData( result, json );
  952. onLoad( result );
  953. } ).catch( onError );
  954. };
  955. /**
  956. * Marks the special nodes/meshes in json for efficient parse.
  957. */
  958. GLTFParser.prototype.markDefs = function () {
  959. var nodeDefs = this.json.nodes || [];
  960. var skinDefs = this.json.skins || [];
  961. var meshDefs = this.json.meshes || [];
  962. var meshReferences = {};
  963. var meshUses = {};
  964. // Nothing in the node definition indicates whether it is a Bone or an
  965. // Object3D. Use the skins' joint references to mark bones.
  966. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  967. var joints = skinDefs[ skinIndex ].joints;
  968. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  969. nodeDefs[ joints[ i ] ].isBone = true;
  970. }
  971. }
  972. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  973. // avoid having more than one THREE.Mesh with the same name, count
  974. // references and rename instances below.
  975. //
  976. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  977. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  978. var nodeDef = nodeDefs[ nodeIndex ];
  979. if ( nodeDef.mesh !== undefined ) {
  980. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  981. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  982. }
  983. meshReferences[ nodeDef.mesh ] ++;
  984. // Nothing in the mesh definition indicates whether it is
  985. // a SkinnedMesh or Mesh. Use the node's mesh reference
  986. // to mark SkinnedMesh if node has skin.
  987. if ( nodeDef.skin !== undefined ) {
  988. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  989. }
  990. }
  991. }
  992. this.json.meshReferences = meshReferences;
  993. this.json.meshUses = meshUses;
  994. };
  995. /**
  996. * Requests the specified dependency asynchronously, with caching.
  997. * @param {string} type
  998. * @param {number} index
  999. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  1000. */
  1001. GLTFParser.prototype.getDependency = function ( type, index ) {
  1002. var cacheKey = type + ':' + index;
  1003. var dependency = this.cache.get( cacheKey );
  1004. if ( ! dependency ) {
  1005. switch ( type ) {
  1006. case 'scene':
  1007. dependency = this.loadScene( index );
  1008. break;
  1009. case 'node':
  1010. dependency = this.loadNode( index );
  1011. break;
  1012. case 'mesh':
  1013. dependency = this.loadMesh( index );
  1014. break;
  1015. case 'accessor':
  1016. dependency = this.loadAccessor( index );
  1017. break;
  1018. case 'bufferView':
  1019. dependency = this.loadBufferView( index );
  1020. break;
  1021. case 'buffer':
  1022. dependency = this.loadBuffer( index );
  1023. break;
  1024. case 'material':
  1025. dependency = this.loadMaterial( index );
  1026. break;
  1027. case 'texture':
  1028. dependency = this.loadTexture( index );
  1029. break;
  1030. case 'skin':
  1031. dependency = this.loadSkin( index );
  1032. break;
  1033. case 'animation':
  1034. dependency = this.loadAnimation( index );
  1035. break;
  1036. case 'camera':
  1037. dependency = this.loadCamera( index );
  1038. break;
  1039. case 'light':
  1040. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  1041. break;
  1042. default:
  1043. throw new Error( 'Unknown type: ' + type );
  1044. }
  1045. this.cache.add( cacheKey, dependency );
  1046. }
  1047. return dependency;
  1048. };
  1049. /**
  1050. * Requests all dependencies of the specified type asynchronously, with caching.
  1051. * @param {string} type
  1052. * @return {Promise<Array<Object>>}
  1053. */
  1054. GLTFParser.prototype.getDependencies = function ( type ) {
  1055. var dependencies = this.cache.get( type );
  1056. if ( ! dependencies ) {
  1057. var parser = this;
  1058. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1059. dependencies = Promise.all( defs.map( function ( def, index ) {
  1060. return parser.getDependency( type, index );
  1061. } ) );
  1062. this.cache.add( type, dependencies );
  1063. }
  1064. return dependencies;
  1065. };
  1066. /**
  1067. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1068. * @param {number} bufferIndex
  1069. * @return {Promise<ArrayBuffer>}
  1070. */
  1071. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1072. var bufferDef = this.json.buffers[ bufferIndex ];
  1073. var loader = this.fileLoader;
  1074. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1075. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1076. }
  1077. // If present, GLB container is required to be the first buffer.
  1078. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1079. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1080. }
  1081. var options = this.options;
  1082. return new Promise( function ( resolve, reject ) {
  1083. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1084. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1085. } );
  1086. } );
  1087. };
  1088. /**
  1089. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1090. * @param {number} bufferViewIndex
  1091. * @return {Promise<ArrayBuffer>}
  1092. */
  1093. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1094. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1095. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1096. var byteLength = bufferViewDef.byteLength || 0;
  1097. var byteOffset = bufferViewDef.byteOffset || 0;
  1098. return buffer.slice( byteOffset, byteOffset + byteLength );
  1099. } );
  1100. };
  1101. /**
  1102. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1103. * @param {number} accessorIndex
  1104. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  1105. */
  1106. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1107. var parser = this;
  1108. var json = this.json;
  1109. var accessorDef = this.json.accessors[ accessorIndex ];
  1110. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1111. // Ignore empty accessors, which may be used to declare runtime
  1112. // information about attributes coming from another source (e.g. Draco
  1113. // compression extension).
  1114. return Promise.resolve( null );
  1115. }
  1116. var pendingBufferViews = [];
  1117. if ( accessorDef.bufferView !== undefined ) {
  1118. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1119. } else {
  1120. pendingBufferViews.push( null );
  1121. }
  1122. if ( accessorDef.sparse !== undefined ) {
  1123. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1124. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1125. }
  1126. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1127. var bufferView = bufferViews[ 0 ];
  1128. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1129. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1130. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1131. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1132. var itemBytes = elementBytes * itemSize;
  1133. var byteOffset = accessorDef.byteOffset || 0;
  1134. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  1135. var normalized = accessorDef.normalized === true;
  1136. var array, bufferAttribute;
  1137. // The buffer is not interleaved if the stride is the item size in bytes.
  1138. if ( byteStride && byteStride !== itemBytes ) {
  1139. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  1140. // This makes sure that IBA.count reflects accessor.count properly
  1141. var ibSlice = Math.floor( byteOffset / byteStride );
  1142. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  1143. var ib = parser.cache.get( ibCacheKey );
  1144. if ( ! ib ) {
  1145. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  1146. // Integer parameters to IB/IBA are in array elements, not bytes.
  1147. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1148. parser.cache.add( ibCacheKey, ib );
  1149. }
  1150. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  1151. } else {
  1152. if ( bufferView === null ) {
  1153. array = new TypedArray( accessorDef.count * itemSize );
  1154. } else {
  1155. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1156. }
  1157. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1158. }
  1159. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1160. if ( accessorDef.sparse !== undefined ) {
  1161. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1162. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1163. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1164. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1165. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1166. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1167. if ( bufferView !== null ) {
  1168. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1169. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  1170. }
  1171. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1172. var index = sparseIndices[ i ];
  1173. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1174. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1175. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1176. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1177. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1178. }
  1179. }
  1180. return bufferAttribute;
  1181. } );
  1182. };
  1183. /**
  1184. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1185. * @param {number} textureIndex
  1186. * @return {Promise<THREE.Texture>}
  1187. */
  1188. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1189. var parser = this;
  1190. var json = this.json;
  1191. var options = this.options;
  1192. var textureLoader = this.textureLoader;
  1193. var URL = self.URL || self.webkitURL;
  1194. var textureDef = json.textures[ textureIndex ];
  1195. var textureExtensions = textureDef.extensions || {};
  1196. var source;
  1197. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  1198. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  1199. } else {
  1200. source = json.images[ textureDef.source ];
  1201. }
  1202. var sourceURI = source.uri;
  1203. var isObjectURL = false;
  1204. if ( source.bufferView !== undefined ) {
  1205. // Load binary image data from bufferView, if provided.
  1206. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1207. isObjectURL = true;
  1208. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1209. sourceURI = URL.createObjectURL( blob );
  1210. return sourceURI;
  1211. } );
  1212. }
  1213. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1214. // Load Texture resource.
  1215. var loader = options.manager.getHandler( sourceURI );
  1216. if ( ! loader ) {
  1217. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  1218. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  1219. : textureLoader;
  1220. }
  1221. return new Promise( function ( resolve, reject ) {
  1222. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1223. } );
  1224. } ).then( function ( texture ) {
  1225. // Clean up resources and configure Texture.
  1226. if ( isObjectURL === true ) {
  1227. URL.revokeObjectURL( sourceURI );
  1228. }
  1229. texture.flipY = false;
  1230. if ( textureDef.name ) texture.name = textureDef.name;
  1231. // Ignore unknown mime types, like DDS files.
  1232. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  1233. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  1234. }
  1235. var samplers = json.samplers || {};
  1236. var sampler = samplers[ textureDef.sampler ] || {};
  1237. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1238. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  1239. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1240. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1241. parser.associations.set( texture, {
  1242. type: 'textures',
  1243. index: textureIndex
  1244. } );
  1245. return texture;
  1246. } );
  1247. };
  1248. /**
  1249. * Asynchronously assigns a texture to the given material parameters.
  1250. * @param {Object} materialParams
  1251. * @param {string} mapName
  1252. * @param {Object} mapDef
  1253. * @return {Promise}
  1254. */
  1255. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  1256. var parser = this;
  1257. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  1258. if ( ! texture.isCompressedTexture ) {
  1259. switch ( mapName ) {
  1260. case 'aoMap':
  1261. case 'emissiveMap':
  1262. case 'metalnessMap':
  1263. case 'normalMap':
  1264. case 'roughnessMap':
  1265. texture.format = THREE.RGBFormat;
  1266. break;
  1267. }
  1268. }
  1269. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  1270. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  1271. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  1272. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  1273. }
  1274. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  1275. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  1276. if ( transform ) {
  1277. var gltfReference = this.associations.get( texture );
  1278. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  1279. this.associations.set( texture, gltfReference );
  1280. }
  1281. }
  1282. materialParams[ mapName ] = texture;
  1283. } );
  1284. };
  1285. /**
  1286. * Assigns final material to a Mesh, Line, or Points instance. The instance
  1287. * already has a material (generated from the glTF material options alone)
  1288. * but reuse of the same glTF material may require multiple threejs materials
  1289. * to accomodate different primitive types, defines, etc. New materials will
  1290. * be created if necessary, and reused from a cache.
  1291. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  1292. */
  1293. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  1294. var geometry = mesh.geometry;
  1295. var material = mesh.material;
  1296. var useVertexTangents = geometry.attributes.tangent !== undefined;
  1297. var useVertexColors = geometry.attributes.color !== undefined;
  1298. var useFlatShading = geometry.attributes.normal === undefined;
  1299. var useSkinning = mesh.isSkinnedMesh === true;
  1300. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  1301. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  1302. if ( mesh.isPoints ) {
  1303. var cacheKey = 'PointsMaterial:' + material.uuid;
  1304. var pointsMaterial = this.cache.get( cacheKey );
  1305. if ( ! pointsMaterial ) {
  1306. pointsMaterial = new THREE.PointsMaterial();
  1307. THREE.Material.prototype.copy.call( pointsMaterial, material );
  1308. pointsMaterial.color.copy( material.color );
  1309. pointsMaterial.map = material.map;
  1310. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  1311. this.cache.add( cacheKey, pointsMaterial );
  1312. }
  1313. material = pointsMaterial;
  1314. } else if ( mesh.isLine ) {
  1315. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1316. var lineMaterial = this.cache.get( cacheKey );
  1317. if ( ! lineMaterial ) {
  1318. lineMaterial = new THREE.LineBasicMaterial();
  1319. THREE.Material.prototype.copy.call( lineMaterial, material );
  1320. lineMaterial.color.copy( material.color );
  1321. this.cache.add( cacheKey, lineMaterial );
  1322. }
  1323. material = lineMaterial;
  1324. }
  1325. // Clone the material if it will be modified
  1326. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1327. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  1328. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  1329. if ( useSkinning ) cacheKey += 'skinning:';
  1330. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  1331. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  1332. if ( useFlatShading ) cacheKey += 'flat-shading:';
  1333. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  1334. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  1335. var cachedMaterial = this.cache.get( cacheKey );
  1336. if ( ! cachedMaterial ) {
  1337. cachedMaterial = material.clone();
  1338. if ( useSkinning ) cachedMaterial.skinning = true;
  1339. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  1340. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  1341. if ( useFlatShading ) cachedMaterial.flatShading = true;
  1342. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  1343. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  1344. this.cache.add( cacheKey, cachedMaterial );
  1345. this.associations.set( cachedMaterial, this.associations.get( material ) );
  1346. }
  1347. material = cachedMaterial;
  1348. }
  1349. // workarounds for mesh and geometry
  1350. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  1351. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  1352. }
  1353. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  1354. if ( material.normalScale && ! useVertexTangents ) {
  1355. material.normalScale.y = - material.normalScale.y;
  1356. }
  1357. if ( material.clearcoatNormalScale && ! useVertexTangents ) {
  1358. material.clearcoatNormalScale.y = - material.clearcoatNormalScale.y;
  1359. }
  1360. mesh.material = material;
  1361. };
  1362. /**
  1363. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1364. * @param {number} materialIndex
  1365. * @return {Promise<THREE.Material>}
  1366. */
  1367. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1368. var parser = this;
  1369. var json = this.json;
  1370. var extensions = this.extensions;
  1371. var materialDef = json.materials[ materialIndex ];
  1372. var materialType;
  1373. var materialParams = {};
  1374. var materialExtensions = materialDef.extensions || {};
  1375. var pending = [];
  1376. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1377. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1378. materialType = sgExtension.getMaterialType();
  1379. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1380. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  1381. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  1382. materialType = kmuExtension.getMaterialType();
  1383. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  1384. } else {
  1385. // Specification:
  1386. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1387. materialType = THREE.MeshStandardMaterial;
  1388. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  1389. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1390. materialParams.opacity = 1.0;
  1391. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1392. var array = metallicRoughness.baseColorFactor;
  1393. materialParams.color.fromArray( array );
  1394. materialParams.opacity = array[ 3 ];
  1395. }
  1396. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1397. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  1398. }
  1399. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1400. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1401. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1402. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1403. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1404. }
  1405. }
  1406. if ( materialDef.doubleSided === true ) {
  1407. materialParams.side = THREE.DoubleSide;
  1408. }
  1409. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1410. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1411. materialParams.transparent = true;
  1412. // See: https://github.com/mrdoob/three.js/issues/17706
  1413. materialParams.depthWrite = false;
  1414. } else {
  1415. materialParams.transparent = false;
  1416. if ( alphaMode === ALPHA_MODES.MASK ) {
  1417. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1418. }
  1419. }
  1420. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1421. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  1422. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1423. if ( materialDef.normalTexture.scale !== undefined ) {
  1424. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1425. }
  1426. }
  1427. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1428. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  1429. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1430. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1431. }
  1432. }
  1433. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1434. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1435. }
  1436. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1437. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  1438. }
  1439. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_CLEARCOAT ] ) {
  1440. var clearcoatExtension = extensions[ EXTENSIONS.KHR_MATERIALS_CLEARCOAT ];
  1441. materialType = clearcoatExtension.getMaterialType();
  1442. pending.push( clearcoatExtension.extendParams( materialParams, { extensions: materialExtensions }, parser ) );
  1443. }
  1444. return Promise.all( pending ).then( function () {
  1445. var material;
  1446. if ( materialType === GLTFMeshStandardSGMaterial ) {
  1447. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1448. } else {
  1449. material = new materialType( materialParams );
  1450. }
  1451. if ( materialDef.name ) material.name = materialDef.name;
  1452. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  1453. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1454. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1455. assignExtrasToUserData( material, materialDef );
  1456. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  1457. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  1458. return material;
  1459. } );
  1460. };
  1461. /**
  1462. * @param {THREE.BufferGeometry} geometry
  1463. * @param {GLTF.Primitive} primitiveDef
  1464. * @param {GLTFParser} parser
  1465. */
  1466. function computeBounds( geometry, primitiveDef, parser ) {
  1467. var attributes = primitiveDef.attributes;
  1468. var box = new THREE.Box3();
  1469. if ( attributes.POSITION !== undefined ) {
  1470. var accessor = parser.json.accessors[ attributes.POSITION ];
  1471. var min = accessor.min;
  1472. var max = accessor.max;
  1473. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1474. if ( min !== undefined && max !== undefined ) {
  1475. box.set(
  1476. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  1477. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  1478. } else {
  1479. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1480. return;
  1481. }
  1482. } else {
  1483. return;
  1484. }
  1485. var targets = primitiveDef.targets;
  1486. if ( targets !== undefined ) {
  1487. var maxDisplacement = new THREE.Vector3();
  1488. var vector = new THREE.Vector3();
  1489. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1490. var target = targets[ i ];
  1491. if ( target.POSITION !== undefined ) {
  1492. var accessor = parser.json.accessors[ target.POSITION ];
  1493. var min = accessor.min;
  1494. var max = accessor.max;
  1495. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1496. if ( min !== undefined && max !== undefined ) {
  1497. // we need to get max of absolute components because target weight is [-1,1]
  1498. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  1499. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  1500. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  1501. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  1502. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  1503. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  1504. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  1505. maxDisplacement.max( vector );
  1506. } else {
  1507. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1508. }
  1509. }
  1510. }
  1511. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  1512. box.expandByVector( maxDisplacement );
  1513. }
  1514. geometry.boundingBox = box;
  1515. var sphere = new THREE.Sphere();
  1516. box.getCenter( sphere.center );
  1517. sphere.radius = box.min.distanceTo( box.max ) / 2;
  1518. geometry.boundingSphere = sphere;
  1519. }
  1520. /**
  1521. * @param {THREE.BufferGeometry} geometry
  1522. * @param {GLTF.Primitive} primitiveDef
  1523. * @param {GLTFParser} parser
  1524. * @return {Promise<THREE.BufferGeometry>}
  1525. */
  1526. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  1527. var attributes = primitiveDef.attributes;
  1528. var pending = [];
  1529. function assignAttributeAccessor( accessorIndex, attributeName ) {
  1530. return parser.getDependency( 'accessor', accessorIndex )
  1531. .then( function ( accessor ) {
  1532. geometry.setAttribute( attributeName, accessor );
  1533. } );
  1534. }
  1535. for ( var gltfAttributeName in attributes ) {
  1536. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  1537. // Skip attributes already provided by e.g. Draco extension.
  1538. if ( threeAttributeName in geometry.attributes ) continue;
  1539. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  1540. }
  1541. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  1542. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  1543. geometry.setIndex( accessor );
  1544. } );
  1545. pending.push( accessor );
  1546. }
  1547. assignExtrasToUserData( geometry, primitiveDef );
  1548. computeBounds( geometry, primitiveDef, parser );
  1549. return Promise.all( pending ).then( function () {
  1550. return primitiveDef.targets !== undefined
  1551. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  1552. : geometry;
  1553. } );
  1554. }
  1555. /**
  1556. * @param {THREE.BufferGeometry} geometry
  1557. * @param {Number} drawMode
  1558. * @return {THREE.BufferGeometry}
  1559. */
  1560. function toTrianglesDrawMode( geometry, drawMode ) {
  1561. var index = geometry.getIndex();
  1562. // generate index if not present
  1563. if ( index === null ) {
  1564. var indices = [];
  1565. var position = geometry.getAttribute( 'position' );
  1566. if ( position !== undefined ) {
  1567. for ( var i = 0; i < position.count; i ++ ) {
  1568. indices.push( i );
  1569. }
  1570. geometry.setIndex( indices );
  1571. index = geometry.getIndex();
  1572. } else {
  1573. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  1574. return geometry;
  1575. }
  1576. }
  1577. //
  1578. var numberOfTriangles = index.count - 2;
  1579. var newIndices = [];
  1580. if ( drawMode === THREE.TriangleFanDrawMode ) {
  1581. // gl.TRIANGLE_FAN
  1582. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  1583. newIndices.push( index.getX( 0 ) );
  1584. newIndices.push( index.getX( i ) );
  1585. newIndices.push( index.getX( i + 1 ) );
  1586. }
  1587. } else {
  1588. // gl.TRIANGLE_STRIP
  1589. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  1590. if ( i % 2 === 0 ) {
  1591. newIndices.push( index.getX( i ) );
  1592. newIndices.push( index.getX( i + 1 ) );
  1593. newIndices.push( index.getX( i + 2 ) );
  1594. } else {
  1595. newIndices.push( index.getX( i + 2 ) );
  1596. newIndices.push( index.getX( i + 1 ) );
  1597. newIndices.push( index.getX( i ) );
  1598. }
  1599. }
  1600. }
  1601. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  1602. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  1603. }
  1604. // build final geometry
  1605. var newGeometry = geometry.clone();
  1606. newGeometry.setIndex( newIndices );
  1607. return newGeometry;
  1608. }
  1609. /**
  1610. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1611. *
  1612. * Creates BufferGeometries from primitives.
  1613. *
  1614. * @param {Array<GLTF.Primitive>} primitives
  1615. * @return {Promise<Array<THREE.BufferGeometry>>}
  1616. */
  1617. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1618. var parser = this;
  1619. var extensions = this.extensions;
  1620. var cache = this.primitiveCache;
  1621. function createDracoPrimitive( primitive ) {
  1622. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1623. .decodePrimitive( primitive, parser )
  1624. .then( function ( geometry ) {
  1625. return addPrimitiveAttributes( geometry, primitive, parser );
  1626. } );
  1627. }
  1628. var pending = [];
  1629. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1630. var primitive = primitives[ i ];
  1631. var cacheKey = createPrimitiveKey( primitive );
  1632. // See if we've already created this geometry
  1633. var cached = cache[ cacheKey ];
  1634. if ( cached ) {
  1635. // Use the cached geometry if it exists
  1636. pending.push( cached.promise );
  1637. } else {
  1638. var geometryPromise;
  1639. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1640. // Use DRACO geometry if available
  1641. geometryPromise = createDracoPrimitive( primitive );
  1642. } else {
  1643. // Otherwise create a new geometry
  1644. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  1645. }
  1646. // Cache this geometry
  1647. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  1648. pending.push( geometryPromise );
  1649. }
  1650. }
  1651. return Promise.all( pending );
  1652. };
  1653. /**
  1654. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1655. * @param {number} meshIndex
  1656. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1657. */
  1658. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1659. var parser = this;
  1660. var json = this.json;
  1661. var meshDef = json.meshes[ meshIndex ];
  1662. var primitives = meshDef.primitives;
  1663. var pending = [];
  1664. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1665. var material = primitives[ i ].material === undefined
  1666. ? createDefaultMaterial( this.cache )
  1667. : this.getDependency( 'material', primitives[ i ].material );
  1668. pending.push( material );
  1669. }
  1670. pending.push( parser.loadGeometries( primitives ) );
  1671. return Promise.all( pending ).then( function ( results ) {
  1672. var materials = results.slice( 0, results.length - 1 );
  1673. var geometries = results[ results.length - 1 ];
  1674. var meshes = [];
  1675. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  1676. var geometry = geometries[ i ];
  1677. var primitive = primitives[ i ];
  1678. // 1. create Mesh
  1679. var mesh;
  1680. var material = materials[ i ];
  1681. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1682. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1683. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1684. primitive.mode === undefined ) {
  1685. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  1686. mesh = meshDef.isSkinnedMesh === true
  1687. ? new THREE.SkinnedMesh( geometry, material )
  1688. : new THREE.Mesh( geometry, material );
  1689. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  1690. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  1691. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  1692. mesh.normalizeSkinWeights();
  1693. }
  1694. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1695. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  1696. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1697. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  1698. }
  1699. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1700. mesh = new THREE.LineSegments( geometry, material );
  1701. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1702. mesh = new THREE.Line( geometry, material );
  1703. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1704. mesh = new THREE.LineLoop( geometry, material );
  1705. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1706. mesh = new THREE.Points( geometry, material );
  1707. } else {
  1708. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1709. }
  1710. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  1711. updateMorphTargets( mesh, meshDef );
  1712. }
  1713. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1714. if ( geometries.length > 1 ) mesh.name += '_' + i;
  1715. assignExtrasToUserData( mesh, meshDef );
  1716. parser.assignFinalMaterial( mesh );
  1717. meshes.push( mesh );
  1718. }
  1719. if ( meshes.length === 1 ) {
  1720. return meshes[ 0 ];
  1721. }
  1722. var group = new THREE.Group();
  1723. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1724. group.add( meshes[ i ] );
  1725. }
  1726. return group;
  1727. } );
  1728. };
  1729. /**
  1730. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1731. * @param {number} cameraIndex
  1732. * @return {Promise<THREE.Camera>}
  1733. */
  1734. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1735. var camera;
  1736. var cameraDef = this.json.cameras[ cameraIndex ];
  1737. var params = cameraDef[ cameraDef.type ];
  1738. if ( ! params ) {
  1739. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1740. return;
  1741. }
  1742. if ( cameraDef.type === 'perspective' ) {
  1743. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  1744. } else if ( cameraDef.type === 'orthographic' ) {
  1745. camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  1746. }
  1747. if ( cameraDef.name ) camera.name = cameraDef.name;
  1748. assignExtrasToUserData( camera, cameraDef );
  1749. return Promise.resolve( camera );
  1750. };
  1751. /**
  1752. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1753. * @param {number} skinIndex
  1754. * @return {Promise<Object>}
  1755. */
  1756. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1757. var skinDef = this.json.skins[ skinIndex ];
  1758. var skinEntry = { joints: skinDef.joints };
  1759. if ( skinDef.inverseBindMatrices === undefined ) {
  1760. return Promise.resolve( skinEntry );
  1761. }
  1762. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1763. skinEntry.inverseBindMatrices = accessor;
  1764. return skinEntry;
  1765. } );
  1766. };
  1767. /**
  1768. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1769. * @param {number} animationIndex
  1770. * @return {Promise<THREE.AnimationClip>}
  1771. */
  1772. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1773. var json = this.json;
  1774. var animationDef = json.animations[ animationIndex ];
  1775. var pendingNodes = [];
  1776. var pendingInputAccessors = [];
  1777. var pendingOutputAccessors = [];
  1778. var pendingSamplers = [];
  1779. var pendingTargets = [];
  1780. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1781. var channel = animationDef.channels[ i ];
  1782. var sampler = animationDef.samplers[ channel.sampler ];
  1783. var target = channel.target;
  1784. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1785. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1786. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1787. pendingNodes.push( this.getDependency( 'node', name ) );
  1788. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  1789. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  1790. pendingSamplers.push( sampler );
  1791. pendingTargets.push( target );
  1792. }
  1793. return Promise.all( [
  1794. Promise.all( pendingNodes ),
  1795. Promise.all( pendingInputAccessors ),
  1796. Promise.all( pendingOutputAccessors ),
  1797. Promise.all( pendingSamplers ),
  1798. Promise.all( pendingTargets )
  1799. ] ).then( function ( dependencies ) {
  1800. var nodes = dependencies[ 0 ];
  1801. var inputAccessors = dependencies[ 1 ];
  1802. var outputAccessors = dependencies[ 2 ];
  1803. var samplers = dependencies[ 3 ];
  1804. var targets = dependencies[ 4 ];
  1805. var tracks = [];
  1806. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  1807. var node = nodes[ i ];
  1808. var inputAccessor = inputAccessors[ i ];
  1809. var outputAccessor = outputAccessors[ i ];
  1810. var sampler = samplers[ i ];
  1811. var target = targets[ i ];
  1812. if ( node === undefined ) continue;
  1813. node.updateMatrix();
  1814. node.matrixAutoUpdate = true;
  1815. var TypedKeyframeTrack;
  1816. switch ( PATH_PROPERTIES[ target.path ] ) {
  1817. case PATH_PROPERTIES.weights:
  1818. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1819. break;
  1820. case PATH_PROPERTIES.rotation:
  1821. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1822. break;
  1823. case PATH_PROPERTIES.position:
  1824. case PATH_PROPERTIES.scale:
  1825. default:
  1826. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1827. break;
  1828. }
  1829. var targetName = node.name ? node.name : node.uuid;
  1830. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1831. var targetNames = [];
  1832. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1833. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  1834. node.traverse( function ( object ) {
  1835. if ( object.isMesh === true && object.morphTargetInfluences ) {
  1836. targetNames.push( object.name ? object.name : object.uuid );
  1837. }
  1838. } );
  1839. } else {
  1840. targetNames.push( targetName );
  1841. }
  1842. var outputArray = outputAccessor.array;
  1843. if ( outputAccessor.normalized ) {
  1844. var scale;
  1845. if ( outputArray.constructor === Int8Array ) {
  1846. scale = 1 / 127;
  1847. } else if ( outputArray.constructor === Uint8Array ) {
  1848. scale = 1 / 255;
  1849. } else if ( outputArray.constructor == Int16Array ) {
  1850. scale = 1 / 32767;
  1851. } else if ( outputArray.constructor === Uint16Array ) {
  1852. scale = 1 / 65535;
  1853. } else {
  1854. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  1855. }
  1856. var scaled = new Float32Array( outputArray.length );
  1857. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  1858. scaled[ j ] = outputArray[ j ] * scale;
  1859. }
  1860. outputArray = scaled;
  1861. }
  1862. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1863. var track = new TypedKeyframeTrack(
  1864. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1865. inputAccessor.array,
  1866. outputArray,
  1867. interpolation
  1868. );
  1869. // Override interpolation with custom factory method.
  1870. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  1871. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  1872. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  1873. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  1874. // must be divided by three to get the interpolant's sampleSize argument.
  1875. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  1876. };
  1877. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  1878. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  1879. }
  1880. tracks.push( track );
  1881. }
  1882. }
  1883. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  1884. return new THREE.AnimationClip( name, undefined, tracks );
  1885. } );
  1886. };
  1887. /**
  1888. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  1889. * @param {number} nodeIndex
  1890. * @return {Promise<THREE.Object3D>}
  1891. */
  1892. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  1893. var json = this.json;
  1894. var extensions = this.extensions;
  1895. var parser = this;
  1896. var meshReferences = json.meshReferences;
  1897. var meshUses = json.meshUses;
  1898. var nodeDef = json.nodes[ nodeIndex ];
  1899. return ( function () {
  1900. var pending = [];
  1901. if ( nodeDef.mesh !== undefined ) {
  1902. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  1903. var node;
  1904. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1905. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  1906. node = mesh.clone();
  1907. node.name += '_instance_' + instanceNum;
  1908. } else {
  1909. node = mesh;
  1910. }
  1911. // if weights are provided on the node, override weights on the mesh.
  1912. if ( nodeDef.weights !== undefined ) {
  1913. node.traverse( function ( o ) {
  1914. if ( ! o.isMesh ) return;
  1915. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  1916. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  1917. }
  1918. } );
  1919. }
  1920. return node;
  1921. } ) );
  1922. }
  1923. if ( nodeDef.camera !== undefined ) {
  1924. pending.push( parser.getDependency( 'camera', nodeDef.camera ) );
  1925. }
  1926. if ( nodeDef.extensions
  1927. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  1928. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  1929. pending.push( parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ) );
  1930. }
  1931. return Promise.all( pending );
  1932. }() ).then( function ( objects ) {
  1933. var node;
  1934. // .isBone isn't in glTF spec. See .markDefs
  1935. if ( nodeDef.isBone === true ) {
  1936. node = new THREE.Bone();
  1937. } else if ( objects.length > 1 ) {
  1938. node = new THREE.Group();
  1939. } else if ( objects.length === 1 ) {
  1940. node = objects[ 0 ];
  1941. } else {
  1942. node = new THREE.Object3D();
  1943. }
  1944. if ( node !== objects[ 0 ] ) {
  1945. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  1946. node.add( objects[ i ] );
  1947. }
  1948. }
  1949. if ( nodeDef.name ) {
  1950. node.userData.name = nodeDef.name;
  1951. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  1952. }
  1953. assignExtrasToUserData( node, nodeDef );
  1954. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  1955. if ( nodeDef.matrix !== undefined ) {
  1956. var matrix = new THREE.Matrix4();
  1957. matrix.fromArray( nodeDef.matrix );
  1958. node.applyMatrix4( matrix );
  1959. } else {
  1960. if ( nodeDef.translation !== undefined ) {
  1961. node.position.fromArray( nodeDef.translation );
  1962. }
  1963. if ( nodeDef.rotation !== undefined ) {
  1964. node.quaternion.fromArray( nodeDef.rotation );
  1965. }
  1966. if ( nodeDef.scale !== undefined ) {
  1967. node.scale.fromArray( nodeDef.scale );
  1968. }
  1969. }
  1970. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  1971. return node;
  1972. } );
  1973. };
  1974. /**
  1975. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  1976. * @param {number} sceneIndex
  1977. * @return {Promise<THREE.Group>}
  1978. */
  1979. GLTFParser.prototype.loadScene = function () {
  1980. // scene node hierachy builder
  1981. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  1982. var nodeDef = json.nodes[ nodeId ];
  1983. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  1984. if ( nodeDef.skin === undefined ) return node;
  1985. // build skeleton here as well
  1986. var skinEntry;
  1987. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  1988. skinEntry = skin;
  1989. var pendingJoints = [];
  1990. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  1991. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  1992. }
  1993. return Promise.all( pendingJoints );
  1994. } ).then( function ( jointNodes ) {
  1995. node.traverse( function ( mesh ) {
  1996. if ( ! mesh.isMesh ) return;
  1997. var bones = [];
  1998. var boneInverses = [];
  1999. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  2000. var jointNode = jointNodes[ j ];
  2001. if ( jointNode ) {
  2002. bones.push( jointNode );
  2003. var mat = new THREE.Matrix4();
  2004. if ( skinEntry.inverseBindMatrices !== undefined ) {
  2005. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  2006. }
  2007. boneInverses.push( mat );
  2008. } else {
  2009. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  2010. }
  2011. }
  2012. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  2013. } );
  2014. return node;
  2015. } );
  2016. } ).then( function ( node ) {
  2017. // build node hierachy
  2018. parentObject.add( node );
  2019. var pending = [];
  2020. if ( nodeDef.children ) {
  2021. var children = nodeDef.children;
  2022. for ( var i = 0, il = children.length; i < il; i ++ ) {
  2023. var child = children[ i ];
  2024. pending.push( buildNodeHierachy( child, node, json, parser ) );
  2025. }
  2026. }
  2027. return Promise.all( pending );
  2028. } );
  2029. }
  2030. return function loadScene( sceneIndex ) {
  2031. var json = this.json;
  2032. var extensions = this.extensions;
  2033. var sceneDef = this.json.scenes[ sceneIndex ];
  2034. var parser = this;
  2035. // Loader returns Group, not Scene.
  2036. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  2037. var scene = new THREE.Group();
  2038. if ( sceneDef.name ) scene.name = sceneDef.name;
  2039. assignExtrasToUserData( scene, sceneDef );
  2040. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  2041. var nodeIds = sceneDef.nodes || [];
  2042. var pending = [];
  2043. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  2044. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  2045. }
  2046. return Promise.all( pending ).then( function () {
  2047. return scene;
  2048. } );
  2049. };
  2050. }();
  2051. return GLTFLoader;
  2052. } )();