GLTFLoader.js 82 KB

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