GLTFLoader.js 85 KB

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