GLTFLoader.js 85 KB

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