GLTFLoader.js 85 KB

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