GLTFLoader.js 81 KB

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