GLTFLoader.js 82 KB

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