GLTFLoader.js 79 KB

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