GLTFLoader.js 79 KB

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