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