GLTFLoader.js 81 KB

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