GLTFLoader.js 79 KB

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