GLTFLoader.js 82 KB

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