LegacyGLTFLoader.js 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334
  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. */
  7. import {
  8. AddEquation,
  9. AlphaFormat,
  10. AlwaysDepth,
  11. AmbientLight,
  12. AnimationClip,
  13. AnimationUtils,
  14. BackSide,
  15. Bone,
  16. BufferAttribute,
  17. BufferGeometry,
  18. ClampToEdgeWrapping,
  19. Color,
  20. CustomBlending,
  21. DefaultLoadingManager,
  22. DirectionalLight,
  23. DoubleSide,
  24. DstAlphaFactor,
  25. DstColorFactor,
  26. EqualDepth,
  27. FileLoader,
  28. FrontSide,
  29. GreaterEqualDepth,
  30. Group,
  31. InterleavedBuffer,
  32. InterleavedBufferAttribute,
  33. InterpolateDiscrete,
  34. InterpolateLinear,
  35. LessDepth,
  36. LessEqualDepth,
  37. Line,
  38. LineLoop,
  39. LineSegments,
  40. LinearFilter,
  41. LinearMipmapLinearFilter,
  42. LinearMipmapNearestFilter,
  43. Loader,
  44. LoaderUtils,
  45. LuminanceAlphaFormat,
  46. LuminanceFormat,
  47. Math as _Math,
  48. Matrix3,
  49. Matrix4,
  50. Mesh,
  51. MeshBasicMaterial,
  52. MeshLambertMaterial,
  53. MeshPhongMaterial,
  54. MirroredRepeatWrapping,
  55. NearestFilter,
  56. NearestMipmapLinearFilter,
  57. NearestMipmapNearestFilter,
  58. NeverDepth,
  59. NoBlending,
  60. NotEqualDepth,
  61. Object3D,
  62. OneFactor,
  63. OneMinusDstAlphaFactor,
  64. OneMinusDstColorFactor,
  65. OneMinusSrcAlphaFactor,
  66. OneMinusSrcColorFactor,
  67. OrthographicCamera,
  68. PerspectiveCamera,
  69. PointLight,
  70. QuaternionKeyframeTrack,
  71. RGBAFormat,
  72. RGBFormat,
  73. RawShaderMaterial,
  74. RepeatWrapping,
  75. ReverseSubtractEquation,
  76. Scene,
  77. Skeleton,
  78. SkinnedMesh,
  79. SpotLight,
  80. SrcAlphaFactor,
  81. SrcAlphaSaturateFactor,
  82. SrcColorFactor,
  83. SubtractEquation,
  84. Texture,
  85. TextureLoader,
  86. UniformsUtils,
  87. UnsignedByteType,
  88. UnsignedShort4444Type,
  89. UnsignedShort5551Type,
  90. UnsignedShort565Type,
  91. Vector2,
  92. Vector3,
  93. Vector4,
  94. VectorKeyframeTrack,
  95. ZeroFactor
  96. } from "../../../../build/three.module.js";
  97. var LegacyGLTFLoader = ( function () {
  98. function LegacyGLTFLoader( manager ) {
  99. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  100. }
  101. LegacyGLTFLoader.prototype = {
  102. constructor: LegacyGLTFLoader,
  103. crossOrigin: 'anonymous',
  104. load: function ( url, onLoad, onProgress, onError ) {
  105. var scope = this;
  106. var resourcePath;
  107. if ( this.resourcePath !== undefined ) {
  108. resourcePath = this.resourcePath;
  109. } else if ( this.path !== undefined ) {
  110. resourcePath = this.path;
  111. } else {
  112. resourcePath = LoaderUtils.extractUrlBase( url );
  113. }
  114. var loader = new FileLoader( scope.manager );
  115. loader.setPath( this.path );
  116. loader.setResponseType( 'arraybuffer' );
  117. loader.load( url, function ( data ) {
  118. scope.parse( data, resourcePath, onLoad );
  119. }, onProgress, onError );
  120. },
  121. setCrossOrigin: function ( value ) {
  122. this.crossOrigin = value;
  123. return this;
  124. },
  125. setPath: function ( value ) {
  126. this.path = value;
  127. },
  128. setResourcePath: function ( value ) {
  129. this.resourcePath = value;
  130. return this;
  131. },
  132. parse: function ( data, path, callback ) {
  133. var content;
  134. var extensions = {};
  135. var magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  136. if ( magic === BINARY_EXTENSION_HEADER_DEFAULTS.magic ) {
  137. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  138. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  139. } else {
  140. content = LoaderUtils.decodeText( new Uint8Array( data ) );
  141. }
  142. var json = JSON.parse( content );
  143. if ( json.extensionsUsed && json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  144. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  145. }
  146. var parser = new GLTFParser( json, extensions, {
  147. crossOrigin: this.crossOrigin,
  148. manager: this.manager,
  149. path: path || this.resourcePath || ''
  150. } );
  151. parser.parse( function ( scene, scenes, cameras, animations ) {
  152. var glTF = {
  153. "scene": scene,
  154. "scenes": scenes,
  155. "cameras": cameras,
  156. "animations": animations
  157. };
  158. callback( glTF );
  159. } );
  160. }
  161. };
  162. /* GLTFREGISTRY */
  163. function GLTFRegistry() {
  164. var objects = {};
  165. return {
  166. get: function ( key ) {
  167. return objects[ key ];
  168. },
  169. add: function ( key, object ) {
  170. objects[ key ] = object;
  171. },
  172. remove: function ( key ) {
  173. delete objects[ key ];
  174. },
  175. removeAll: function () {
  176. objects = {};
  177. },
  178. update: function ( scene, camera ) {
  179. for ( var name in objects ) {
  180. var object = objects[ name ];
  181. if ( object.update ) {
  182. object.update( scene, camera );
  183. }
  184. }
  185. }
  186. };
  187. }
  188. /* GLTFSHADERS */
  189. LegacyGLTFLoader.Shaders = {
  190. update: function () {
  191. console.warn( 'THREE.LegacyGLTFLoader.Shaders has been deprecated, and now updates automatically.' );
  192. }
  193. };
  194. /* GLTFSHADER */
  195. function GLTFShader( targetNode, allNodes ) {
  196. var boundUniforms = {};
  197. // bind each uniform to its source node
  198. var uniforms = targetNode.material.uniforms;
  199. for ( var uniformId in uniforms ) {
  200. var uniform = uniforms[ uniformId ];
  201. if ( uniform.semantic ) {
  202. var sourceNodeRef = uniform.node;
  203. var sourceNode = targetNode;
  204. if ( sourceNodeRef ) {
  205. sourceNode = allNodes[ sourceNodeRef ];
  206. }
  207. boundUniforms[ uniformId ] = {
  208. semantic: uniform.semantic,
  209. sourceNode: sourceNode,
  210. targetNode: targetNode,
  211. uniform: uniform
  212. };
  213. }
  214. }
  215. this.boundUniforms = boundUniforms;
  216. this._m4 = new Matrix4();
  217. }
  218. // Update - update all the uniform values
  219. GLTFShader.prototype.update = function ( scene, camera ) {
  220. var boundUniforms = this.boundUniforms;
  221. for ( var name in boundUniforms ) {
  222. var boundUniform = boundUniforms[ name ];
  223. switch ( boundUniform.semantic ) {
  224. case "MODELVIEW":
  225. var m4 = boundUniform.uniform.value;
  226. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  227. break;
  228. case "MODELVIEWINVERSETRANSPOSE":
  229. var m3 = boundUniform.uniform.value;
  230. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  231. m3.getNormalMatrix( this._m4 );
  232. break;
  233. case "PROJECTION":
  234. var m4 = boundUniform.uniform.value;
  235. m4.copy( camera.projectionMatrix );
  236. break;
  237. case "JOINTMATRIX":
  238. var m4v = boundUniform.uniform.value;
  239. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  240. // So it goes like this:
  241. // SkinnedMesh world matrix is already baked into MODELVIEW;
  242. // transform joints to local space,
  243. // then transform using joint's inverse
  244. m4v[ mi ]
  245. .getInverse( boundUniform.sourceNode.matrixWorld )
  246. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  247. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
  248. .multiply( boundUniform.targetNode.bindMatrix );
  249. }
  250. break;
  251. default :
  252. console.warn( "Unhandled shader semantic: " + boundUniform.semantic );
  253. break;
  254. }
  255. }
  256. };
  257. /* ANIMATION */
  258. LegacyGLTFLoader.Animations = {
  259. update: function () {
  260. console.warn( 'THREE.LegacyGLTFLoader.Animation has been deprecated. Use THREE.AnimationMixer instead.' );
  261. }
  262. };
  263. /*********************************/
  264. /********** EXTENSIONS ***********/
  265. /*********************************/
  266. var EXTENSIONS = {
  267. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  268. KHR_MATERIALS_COMMON: 'KHR_materials_common'
  269. };
  270. /* MATERIALS COMMON EXTENSION */
  271. function GLTFMaterialsCommonExtension( json ) {
  272. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  273. this.lights = {};
  274. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) || {};
  275. var lights = extension.lights || {};
  276. for ( var lightId in lights ) {
  277. var light = lights[ lightId ];
  278. var lightNode;
  279. var lightParams = light[ light.type ];
  280. var color = new Color().fromArray( lightParams.color );
  281. switch ( light.type ) {
  282. case "directional":
  283. lightNode = new DirectionalLight( color );
  284. lightNode.position.set( 0, 0, 1 );
  285. break;
  286. case "point":
  287. lightNode = new PointLight( color );
  288. break;
  289. case "spot":
  290. lightNode = new SpotLight( color );
  291. lightNode.position.set( 0, 0, 1 );
  292. break;
  293. case "ambient":
  294. lightNode = new AmbientLight( color );
  295. break;
  296. }
  297. if ( lightNode ) {
  298. this.lights[ lightId ] = lightNode;
  299. }
  300. }
  301. }
  302. /* BINARY EXTENSION */
  303. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  304. var BINARY_EXTENSION_HEADER_DEFAULTS = { magic: 'glTF', version: 1, contentFormat: 0 };
  305. var BINARY_EXTENSION_HEADER_LENGTH = 20;
  306. function GLTFBinaryExtension( data ) {
  307. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  308. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  309. var header = {
  310. magic: LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  311. version: headerView.getUint32( 4, true ),
  312. length: headerView.getUint32( 8, true ),
  313. contentLength: headerView.getUint32( 12, true ),
  314. contentFormat: headerView.getUint32( 16, true )
  315. };
  316. for ( var key in BINARY_EXTENSION_HEADER_DEFAULTS ) {
  317. var value = BINARY_EXTENSION_HEADER_DEFAULTS[ key ];
  318. if ( header[ key ] !== value ) {
  319. throw new Error( 'Unsupported glTF-Binary header: Expected "%s" to be "%s".', key, value );
  320. }
  321. }
  322. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH, header.contentLength );
  323. this.header = header;
  324. this.content = LoaderUtils.decodeText( contentArray );
  325. this.body = data.slice( BINARY_EXTENSION_HEADER_LENGTH + header.contentLength, header.length );
  326. }
  327. GLTFBinaryExtension.prototype.loadShader = function ( shader, bufferViews ) {
  328. var bufferView = bufferViews[ shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].bufferView ];
  329. var array = new Uint8Array( bufferView );
  330. return LoaderUtils.decodeText( array );
  331. };
  332. /*********************************/
  333. /********** INTERNALS ************/
  334. /*********************************/
  335. /* CONSTANTS */
  336. var WEBGL_CONSTANTS = {
  337. FLOAT: 5126,
  338. //FLOAT_MAT2: 35674,
  339. FLOAT_MAT3: 35675,
  340. FLOAT_MAT4: 35676,
  341. FLOAT_VEC2: 35664,
  342. FLOAT_VEC3: 35665,
  343. FLOAT_VEC4: 35666,
  344. LINEAR: 9729,
  345. REPEAT: 10497,
  346. SAMPLER_2D: 35678,
  347. TRIANGLES: 4,
  348. LINES: 1,
  349. UNSIGNED_BYTE: 5121,
  350. UNSIGNED_SHORT: 5123,
  351. VERTEX_SHADER: 35633,
  352. FRAGMENT_SHADER: 35632
  353. };
  354. var WEBGL_TYPE = {
  355. 5126: Number,
  356. //35674: Matrix2,
  357. 35675: Matrix3,
  358. 35676: Matrix4,
  359. 35664: Vector2,
  360. 35665: Vector3,
  361. 35666: Vector4,
  362. 35678: Texture
  363. };
  364. var WEBGL_COMPONENT_TYPES = {
  365. 5120: Int8Array,
  366. 5121: Uint8Array,
  367. 5122: Int16Array,
  368. 5123: Uint16Array,
  369. 5125: Uint32Array,
  370. 5126: Float32Array
  371. };
  372. var WEBGL_FILTERS = {
  373. 9728: NearestFilter,
  374. 9729: LinearFilter,
  375. 9984: NearestMipmapNearestFilter,
  376. 9985: LinearMipmapNearestFilter,
  377. 9986: NearestMipmapLinearFilter,
  378. 9987: LinearMipmapLinearFilter
  379. };
  380. var WEBGL_WRAPPINGS = {
  381. 33071: ClampToEdgeWrapping,
  382. 33648: MirroredRepeatWrapping,
  383. 10497: RepeatWrapping
  384. };
  385. var WEBGL_TEXTURE_FORMATS = {
  386. 6406: AlphaFormat,
  387. 6407: RGBFormat,
  388. 6408: RGBAFormat,
  389. 6409: LuminanceFormat,
  390. 6410: LuminanceAlphaFormat
  391. };
  392. var WEBGL_TEXTURE_DATATYPES = {
  393. 5121: UnsignedByteType,
  394. 32819: UnsignedShort4444Type,
  395. 32820: UnsignedShort5551Type,
  396. 33635: UnsignedShort565Type
  397. };
  398. var WEBGL_SIDES = {
  399. 1028: BackSide, // Culling front
  400. 1029: FrontSide // Culling back
  401. //1032: NoSide // Culling front and back, what to do?
  402. };
  403. var WEBGL_DEPTH_FUNCS = {
  404. 512: NeverDepth,
  405. 513: LessDepth,
  406. 514: EqualDepth,
  407. 515: LessEqualDepth,
  408. 516: GreaterEqualDepth,
  409. 517: NotEqualDepth,
  410. 518: GreaterEqualDepth,
  411. 519: AlwaysDepth
  412. };
  413. var WEBGL_BLEND_EQUATIONS = {
  414. 32774: AddEquation,
  415. 32778: SubtractEquation,
  416. 32779: ReverseSubtractEquation
  417. };
  418. var WEBGL_BLEND_FUNCS = {
  419. 0: ZeroFactor,
  420. 1: OneFactor,
  421. 768: SrcColorFactor,
  422. 769: OneMinusSrcColorFactor,
  423. 770: SrcAlphaFactor,
  424. 771: OneMinusSrcAlphaFactor,
  425. 772: DstAlphaFactor,
  426. 773: OneMinusDstAlphaFactor,
  427. 774: DstColorFactor,
  428. 775: OneMinusDstColorFactor,
  429. 776: SrcAlphaSaturateFactor
  430. // The followings are not supported by Three.js yet
  431. //32769: CONSTANT_COLOR,
  432. //32770: ONE_MINUS_CONSTANT_COLOR,
  433. //32771: CONSTANT_ALPHA,
  434. //32772: ONE_MINUS_CONSTANT_COLOR
  435. };
  436. var WEBGL_TYPE_SIZES = {
  437. 'SCALAR': 1,
  438. 'VEC2': 2,
  439. 'VEC3': 3,
  440. 'VEC4': 4,
  441. 'MAT2': 4,
  442. 'MAT3': 9,
  443. 'MAT4': 16
  444. };
  445. var PATH_PROPERTIES = {
  446. scale: 'scale',
  447. translation: 'position',
  448. rotation: 'quaternion'
  449. };
  450. var INTERPOLATION = {
  451. LINEAR: InterpolateLinear,
  452. STEP: InterpolateDiscrete
  453. };
  454. var STATES_ENABLES = {
  455. 2884: 'CULL_FACE',
  456. 2929: 'DEPTH_TEST',
  457. 3042: 'BLEND',
  458. 3089: 'SCISSOR_TEST',
  459. 32823: 'POLYGON_OFFSET_FILL',
  460. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  461. };
  462. /* UTILITY FUNCTIONS */
  463. function _each( object, callback, thisObj ) {
  464. if ( ! object ) {
  465. return Promise.resolve();
  466. }
  467. var results;
  468. var fns = [];
  469. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  470. results = [];
  471. var length = object.length;
  472. for ( var idx = 0; idx < length; idx ++ ) {
  473. var value = callback.call( thisObj || this, object[ idx ], idx );
  474. if ( value ) {
  475. fns.push( value );
  476. if ( value instanceof Promise ) {
  477. value.then( function ( key, value ) {
  478. results[ key ] = value;
  479. }.bind( this, idx ) );
  480. } else {
  481. results[ idx ] = value;
  482. }
  483. }
  484. }
  485. } else {
  486. results = {};
  487. for ( var key in object ) {
  488. if ( object.hasOwnProperty( key ) ) {
  489. var value = callback.call( thisObj || this, object[ key ], key );
  490. if ( value ) {
  491. fns.push( value );
  492. if ( value instanceof Promise ) {
  493. value.then( function ( key, value ) {
  494. results[ key ] = value;
  495. }.bind( this, key ) );
  496. } else {
  497. results[ key ] = value;
  498. }
  499. }
  500. }
  501. }
  502. }
  503. return Promise.all( fns ).then( function () {
  504. return results;
  505. } );
  506. }
  507. function resolveURL( url, path ) {
  508. // Invalid URL
  509. if ( typeof url !== 'string' || url === '' )
  510. return '';
  511. // Absolute URL http://,https://,//
  512. if ( /^(https?:)?\/\//i.test( url ) ) {
  513. return url;
  514. }
  515. // Data URI
  516. if ( /^data:.*,.*$/i.test( url ) ) {
  517. return url;
  518. }
  519. // Blob URL
  520. if ( /^blob:.*$/i.test( url ) ) {
  521. return url;
  522. }
  523. // Relative URL
  524. return ( path || '' ) + url;
  525. }
  526. // Three.js seems too dependent on attribute names so globally
  527. // replace those in the shader code
  528. function replaceTHREEShaderAttributes( shaderText, technique ) {
  529. // Expected technique attributes
  530. var attributes = {};
  531. for ( var attributeId in technique.attributes ) {
  532. var pname = technique.attributes[ attributeId ];
  533. var param = technique.parameters[ pname ];
  534. var atype = param.type;
  535. var semantic = param.semantic;
  536. attributes[ attributeId ] = {
  537. type: atype,
  538. semantic: semantic
  539. };
  540. }
  541. // Figure out which attributes to change in technique
  542. var shaderParams = technique.parameters;
  543. var shaderAttributes = technique.attributes;
  544. var params = {};
  545. for ( var attributeId in attributes ) {
  546. var pname = shaderAttributes[ attributeId ];
  547. var shaderParam = shaderParams[ pname ];
  548. var semantic = shaderParam.semantic;
  549. if ( semantic ) {
  550. params[ attributeId ] = shaderParam;
  551. }
  552. }
  553. for ( var pname in params ) {
  554. var param = params[ pname ];
  555. var semantic = param.semantic;
  556. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  557. switch ( semantic ) {
  558. case "POSITION":
  559. shaderText = shaderText.replace( regEx, 'position' );
  560. break;
  561. case "NORMAL":
  562. shaderText = shaderText.replace( regEx, 'normal' );
  563. break;
  564. case 'TEXCOORD_0':
  565. case 'TEXCOORD0':
  566. case 'TEXCOORD':
  567. shaderText = shaderText.replace( regEx, 'uv' );
  568. break;
  569. case 'TEXCOORD_1':
  570. shaderText = shaderText.replace( regEx, 'uv2' );
  571. break;
  572. case 'COLOR_0':
  573. case 'COLOR0':
  574. case 'COLOR':
  575. shaderText = shaderText.replace( regEx, 'color' );
  576. break;
  577. case "WEIGHT":
  578. shaderText = shaderText.replace( regEx, 'skinWeight' );
  579. break;
  580. case "JOINT":
  581. shaderText = shaderText.replace( regEx, 'skinIndex' );
  582. break;
  583. }
  584. }
  585. return shaderText;
  586. }
  587. function createDefaultMaterial() {
  588. return new MeshPhongMaterial( {
  589. color: 0x00000,
  590. emissive: 0x888888,
  591. specular: 0x000000,
  592. shininess: 0,
  593. transparent: false,
  594. depthTest: true,
  595. side: FrontSide
  596. } );
  597. }
  598. // Deferred constructor for RawShaderMaterial types
  599. function DeferredShaderMaterial( params ) {
  600. this.isDeferredShaderMaterial = true;
  601. this.params = params;
  602. }
  603. DeferredShaderMaterial.prototype.create = function () {
  604. var uniforms = UniformsUtils.clone( this.params.uniforms );
  605. for ( var uniformId in this.params.uniforms ) {
  606. var originalUniform = this.params.uniforms[ uniformId ];
  607. if ( originalUniform.value instanceof Texture ) {
  608. uniforms[ uniformId ].value = originalUniform.value;
  609. uniforms[ uniformId ].value.needsUpdate = true;
  610. }
  611. uniforms[ uniformId ].semantic = originalUniform.semantic;
  612. uniforms[ uniformId ].node = originalUniform.node;
  613. }
  614. this.params.uniforms = uniforms;
  615. return new RawShaderMaterial( this.params );
  616. };
  617. /* GLTF PARSER */
  618. function GLTFParser( json, extensions, options ) {
  619. this.json = json || {};
  620. this.extensions = extensions || {};
  621. this.options = options || {};
  622. // loader object cache
  623. this.cache = new GLTFRegistry();
  624. }
  625. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  626. var _dependencies = {};
  627. for ( var i = 0; i < dependencies.length; i ++ ) {
  628. var dependency = dependencies[ i ];
  629. var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  630. var cached = this.cache.get( dependency );
  631. if ( cached !== undefined ) {
  632. _dependencies[ dependency ] = cached;
  633. } else if ( this[ fnName ] ) {
  634. var fn = this[ fnName ]();
  635. this.cache.add( dependency, fn );
  636. _dependencies[ dependency ] = fn;
  637. }
  638. }
  639. return _each( _dependencies, function ( dependency ) {
  640. return dependency;
  641. } );
  642. };
  643. GLTFParser.prototype.parse = function ( callback ) {
  644. var json = this.json;
  645. // Clear the loader cache
  646. this.cache.removeAll();
  647. // Fire the callback on complete
  648. this._withDependencies( [
  649. "scenes",
  650. "cameras",
  651. "animations"
  652. ] ).then( function ( dependencies ) {
  653. var scenes = [];
  654. for ( var name in dependencies.scenes ) {
  655. scenes.push( dependencies.scenes[ name ] );
  656. }
  657. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  658. var cameras = [];
  659. for ( var name in dependencies.cameras ) {
  660. var camera = dependencies.cameras[ name ];
  661. cameras.push( camera );
  662. }
  663. var animations = [];
  664. for ( var name in dependencies.animations ) {
  665. animations.push( dependencies.animations[ name ] );
  666. }
  667. callback( scene, scenes, cameras, animations );
  668. } );
  669. };
  670. GLTFParser.prototype.loadShaders = function () {
  671. var json = this.json;
  672. var extensions = this.extensions;
  673. var options = this.options;
  674. return this._withDependencies( [
  675. "bufferViews"
  676. ] ).then( function ( dependencies ) {
  677. return _each( json.shaders, function ( shader ) {
  678. if ( shader.extensions && shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  679. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadShader( shader, dependencies.bufferViews );
  680. }
  681. return new Promise( function ( resolve ) {
  682. var loader = new FileLoader( options.manager );
  683. loader.setResponseType( 'text' );
  684. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  685. resolve( shaderText );
  686. } );
  687. } );
  688. } );
  689. } );
  690. };
  691. GLTFParser.prototype.loadBuffers = function () {
  692. var json = this.json;
  693. var extensions = this.extensions;
  694. var options = this.options;
  695. return _each( json.buffers, function ( buffer, name ) {
  696. if ( name === BINARY_EXTENSION_BUFFER_NAME ) {
  697. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  698. }
  699. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  700. return new Promise( function ( resolve ) {
  701. var loader = new FileLoader( options.manager );
  702. loader.setResponseType( 'arraybuffer' );
  703. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  704. resolve( buffer );
  705. } );
  706. } );
  707. } else {
  708. console.warn( 'THREE.LegacyGLTFLoader: ' + buffer.type + ' buffer type is not supported' );
  709. }
  710. } );
  711. };
  712. GLTFParser.prototype.loadBufferViews = function () {
  713. var json = this.json;
  714. return this._withDependencies( [
  715. "buffers"
  716. ] ).then( function ( dependencies ) {
  717. return _each( json.bufferViews, function ( bufferView ) {
  718. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  719. var byteLength = bufferView.byteLength !== undefined ? bufferView.byteLength : 0;
  720. return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + byteLength );
  721. } );
  722. } );
  723. };
  724. GLTFParser.prototype.loadAccessors = function () {
  725. var json = this.json;
  726. return this._withDependencies( [
  727. "bufferViews"
  728. ] ).then( function ( dependencies ) {
  729. return _each( json.accessors, function ( accessor ) {
  730. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  731. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  732. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  733. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  734. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  735. var itemBytes = elementBytes * itemSize;
  736. // The buffer is not interleaved if the stride is the item size in bytes.
  737. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  738. // Use the full buffer if it's interleaved.
  739. var array = new TypedArray( arraybuffer );
  740. // Integer parameters to IB/IBA are in array elements, not bytes.
  741. var ib = new InterleavedBuffer( array, accessor.byteStride / elementBytes );
  742. return new InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  743. } else {
  744. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  745. return new BufferAttribute( array, itemSize );
  746. }
  747. } );
  748. } );
  749. };
  750. GLTFParser.prototype.loadTextures = function () {
  751. var json = this.json;
  752. var options = this.options;
  753. return this._withDependencies( [
  754. "bufferViews"
  755. ] ).then( function ( dependencies ) {
  756. return _each( json.textures, function ( texture ) {
  757. if ( texture.source ) {
  758. return new Promise( function ( resolve ) {
  759. var source = json.images[ texture.source ];
  760. var sourceUri = source.uri;
  761. var isObjectURL = false;
  762. if ( source.extensions && source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  763. var metadata = source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ];
  764. var bufferView = dependencies.bufferViews[ metadata.bufferView ];
  765. var blob = new Blob( [ bufferView ], { type: metadata.mimeType } );
  766. sourceUri = URL.createObjectURL( blob );
  767. isObjectURL = true;
  768. }
  769. var textureLoader = Loader.Handlers.get( sourceUri );
  770. if ( textureLoader === null ) {
  771. textureLoader = new TextureLoader( options.manager );
  772. }
  773. textureLoader.setCrossOrigin( options.crossOrigin );
  774. textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
  775. if ( isObjectURL ) URL.revokeObjectURL( sourceUri );
  776. _texture.flipY = false;
  777. if ( texture.name !== undefined ) _texture.name = texture.name;
  778. _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : RGBAFormat;
  779. if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {
  780. console.warn( 'THREE.LegacyGLTFLoader: Three.js doesn\'t support texture internalFormat which is different from texture format. ' +
  781. 'internalFormat will be forced to be the same value as format.' );
  782. }
  783. _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : UnsignedByteType;
  784. if ( texture.sampler ) {
  785. var sampler = json.samplers[ texture.sampler ];
  786. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;
  787. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || NearestMipmapLinearFilter;
  788. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;
  789. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;
  790. }
  791. resolve( _texture );
  792. }, undefined, function () {
  793. if ( isObjectURL ) URL.revokeObjectURL( sourceUri );
  794. resolve();
  795. } );
  796. } );
  797. }
  798. } );
  799. } );
  800. };
  801. GLTFParser.prototype.loadMaterials = function () {
  802. var json = this.json;
  803. return this._withDependencies( [
  804. "shaders",
  805. "textures"
  806. ] ).then( function ( dependencies ) {
  807. return _each( json.materials, function ( material ) {
  808. var materialType;
  809. var materialValues = {};
  810. var materialParams = {};
  811. var khr_material;
  812. if ( material.extensions && material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  813. khr_material = material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  814. }
  815. if ( khr_material ) {
  816. // don't copy over unused values to avoid material warning spam
  817. var keys = [ 'ambient', 'emission', 'transparent', 'transparency', 'doubleSided' ];
  818. switch ( khr_material.technique ) {
  819. case 'BLINN' :
  820. case 'PHONG' :
  821. materialType = MeshPhongMaterial;
  822. keys.push( 'diffuse', 'specular', 'shininess' );
  823. break;
  824. case 'LAMBERT' :
  825. materialType = MeshLambertMaterial;
  826. keys.push( 'diffuse' );
  827. break;
  828. case 'CONSTANT' :
  829. default :
  830. materialType = MeshBasicMaterial;
  831. break;
  832. }
  833. keys.forEach( function ( v ) {
  834. if ( khr_material.values[ v ] !== undefined ) materialValues[ v ] = khr_material.values[ v ];
  835. } );
  836. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  837. materialParams.side = DoubleSide;
  838. }
  839. if ( khr_material.transparent || materialValues.transparent ) {
  840. materialParams.transparent = true;
  841. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  842. }
  843. } else if ( material.technique === undefined ) {
  844. materialType = MeshPhongMaterial;
  845. Object.assign( materialValues, material.values );
  846. } else {
  847. materialType = DeferredShaderMaterial;
  848. var technique = json.techniques[ material.technique ];
  849. materialParams.uniforms = {};
  850. var program = json.programs[ technique.program ];
  851. if ( program ) {
  852. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  853. if ( ! materialParams.fragmentShader ) {
  854. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  855. materialType = MeshPhongMaterial;
  856. }
  857. var vertexShader = dependencies.shaders[ program.vertexShader ];
  858. if ( ! vertexShader ) {
  859. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  860. materialType = MeshPhongMaterial;
  861. }
  862. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  863. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  864. var uniforms = technique.uniforms;
  865. for ( var uniformId in uniforms ) {
  866. var pname = uniforms[ uniformId ];
  867. var shaderParam = technique.parameters[ pname ];
  868. var ptype = shaderParam.type;
  869. if ( WEBGL_TYPE[ ptype ] ) {
  870. var pcount = shaderParam.count;
  871. var value;
  872. if ( material.values !== undefined ) value = material.values[ pname ];
  873. var uvalue = new WEBGL_TYPE[ ptype ]();
  874. var usemantic = shaderParam.semantic;
  875. var unode = shaderParam.node;
  876. switch ( ptype ) {
  877. case WEBGL_CONSTANTS.FLOAT:
  878. uvalue = shaderParam.value;
  879. if ( pname == "transparency" ) {
  880. materialParams.transparent = true;
  881. }
  882. if ( value !== undefined ) {
  883. uvalue = value;
  884. }
  885. break;
  886. case WEBGL_CONSTANTS.FLOAT_VEC2:
  887. case WEBGL_CONSTANTS.FLOAT_VEC3:
  888. case WEBGL_CONSTANTS.FLOAT_VEC4:
  889. case WEBGL_CONSTANTS.FLOAT_MAT3:
  890. if ( shaderParam && shaderParam.value ) {
  891. uvalue.fromArray( shaderParam.value );
  892. }
  893. if ( value ) {
  894. uvalue.fromArray( value );
  895. }
  896. break;
  897. case WEBGL_CONSTANTS.FLOAT_MAT2:
  898. // what to do?
  899. console.warn( "FLOAT_MAT2 is not a supported uniform type" );
  900. break;
  901. case WEBGL_CONSTANTS.FLOAT_MAT4:
  902. if ( pcount ) {
  903. uvalue = new Array( pcount );
  904. for ( var mi = 0; mi < pcount; mi ++ ) {
  905. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  906. }
  907. if ( shaderParam && shaderParam.value ) {
  908. var m4v = shaderParam.value;
  909. uvalue.fromArray( m4v );
  910. }
  911. if ( value ) {
  912. uvalue.fromArray( value );
  913. }
  914. } else {
  915. if ( shaderParam && shaderParam.value ) {
  916. var m4 = shaderParam.value;
  917. uvalue.fromArray( m4 );
  918. }
  919. if ( value ) {
  920. uvalue.fromArray( value );
  921. }
  922. }
  923. break;
  924. case WEBGL_CONSTANTS.SAMPLER_2D:
  925. if ( value !== undefined ) {
  926. uvalue = dependencies.textures[ value ];
  927. } else if ( shaderParam.value !== undefined ) {
  928. uvalue = dependencies.textures[ shaderParam.value ];
  929. } else {
  930. uvalue = null;
  931. }
  932. break;
  933. }
  934. materialParams.uniforms[ uniformId ] = {
  935. value: uvalue,
  936. semantic: usemantic,
  937. node: unode
  938. };
  939. } else {
  940. throw new Error( "Unknown shader uniform param type: " + ptype );
  941. }
  942. }
  943. var states = technique.states || {};
  944. var enables = states.enable || [];
  945. var functions = states.functions || {};
  946. var enableCullFace = false;
  947. var enableDepthTest = false;
  948. var enableBlend = false;
  949. for ( var i = 0, il = enables.length; i < il; i ++ ) {
  950. var enable = enables[ i ];
  951. switch ( STATES_ENABLES[ enable ] ) {
  952. case 'CULL_FACE':
  953. enableCullFace = true;
  954. break;
  955. case 'DEPTH_TEST':
  956. enableDepthTest = true;
  957. break;
  958. case 'BLEND':
  959. enableBlend = true;
  960. break;
  961. // TODO: implement
  962. case 'SCISSOR_TEST':
  963. case 'POLYGON_OFFSET_FILL':
  964. case 'SAMPLE_ALPHA_TO_COVERAGE':
  965. break;
  966. default:
  967. throw new Error( "Unknown technique.states.enable: " + enable );
  968. }
  969. }
  970. if ( enableCullFace ) {
  971. materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : FrontSide;
  972. } else {
  973. materialParams.side = DoubleSide;
  974. }
  975. materialParams.depthTest = enableDepthTest;
  976. materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : LessDepth;
  977. materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true;
  978. materialParams.blending = enableBlend ? CustomBlending : NoBlending;
  979. materialParams.transparent = enableBlend;
  980. var blendEquationSeparate = functions.blendEquationSeparate;
  981. if ( blendEquationSeparate !== undefined ) {
  982. materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ];
  983. materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ];
  984. } else {
  985. materialParams.blendEquation = AddEquation;
  986. materialParams.blendEquationAlpha = AddEquation;
  987. }
  988. var blendFuncSeparate = functions.blendFuncSeparate;
  989. if ( blendFuncSeparate !== undefined ) {
  990. materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ];
  991. materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ];
  992. materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ];
  993. materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ];
  994. } else {
  995. materialParams.blendSrc = OneFactor;
  996. materialParams.blendDst = ZeroFactor;
  997. materialParams.blendSrcAlpha = OneFactor;
  998. materialParams.blendDstAlpha = ZeroFactor;
  999. }
  1000. }
  1001. }
  1002. if ( Array.isArray( materialValues.diffuse ) ) {
  1003. materialParams.color = new Color().fromArray( materialValues.diffuse );
  1004. } else if ( typeof ( materialValues.diffuse ) === 'string' ) {
  1005. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  1006. }
  1007. delete materialParams.diffuse;
  1008. if ( typeof ( materialValues.reflective ) === 'string' ) {
  1009. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  1010. }
  1011. if ( typeof ( materialValues.bump ) === 'string' ) {
  1012. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  1013. }
  1014. if ( Array.isArray( materialValues.emission ) ) {
  1015. if ( materialType === MeshBasicMaterial ) {
  1016. materialParams.color = new Color().fromArray( materialValues.emission );
  1017. } else {
  1018. materialParams.emissive = new Color().fromArray( materialValues.emission );
  1019. }
  1020. } else if ( typeof ( materialValues.emission ) === 'string' ) {
  1021. if ( materialType === MeshBasicMaterial ) {
  1022. materialParams.map = dependencies.textures[ materialValues.emission ];
  1023. } else {
  1024. materialParams.emissiveMap = dependencies.textures[ materialValues.emission ];
  1025. }
  1026. }
  1027. if ( Array.isArray( materialValues.specular ) ) {
  1028. materialParams.specular = new Color().fromArray( materialValues.specular );
  1029. } else if ( typeof ( materialValues.specular ) === 'string' ) {
  1030. materialParams.specularMap = dependencies.textures[ materialValues.specular ];
  1031. }
  1032. if ( materialValues.shininess !== undefined ) {
  1033. materialParams.shininess = materialValues.shininess;
  1034. }
  1035. var _material = new materialType( materialParams );
  1036. if ( material.name !== undefined ) _material.name = material.name;
  1037. return _material;
  1038. } );
  1039. } );
  1040. };
  1041. GLTFParser.prototype.loadMeshes = function () {
  1042. var json = this.json;
  1043. return this._withDependencies( [
  1044. "accessors",
  1045. "materials"
  1046. ] ).then( function ( dependencies ) {
  1047. return _each( json.meshes, function ( mesh ) {
  1048. var group = new Group();
  1049. if ( mesh.name !== undefined ) group.name = mesh.name;
  1050. if ( mesh.extras ) group.userData = mesh.extras;
  1051. var primitives = mesh.primitives || [];
  1052. for ( var name in primitives ) {
  1053. var primitive = primitives[ name ];
  1054. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  1055. var geometry = new BufferGeometry();
  1056. var attributes = primitive.attributes;
  1057. for ( var attributeId in attributes ) {
  1058. var attributeEntry = attributes[ attributeId ];
  1059. if ( ! attributeEntry ) return;
  1060. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1061. switch ( attributeId ) {
  1062. case 'POSITION':
  1063. geometry.addAttribute( 'position', bufferAttribute );
  1064. break;
  1065. case 'NORMAL':
  1066. geometry.addAttribute( 'normal', bufferAttribute );
  1067. break;
  1068. case 'TEXCOORD_0':
  1069. case 'TEXCOORD0':
  1070. case 'TEXCOORD':
  1071. geometry.addAttribute( 'uv', bufferAttribute );
  1072. break;
  1073. case 'TEXCOORD_1':
  1074. geometry.addAttribute( 'uv2', bufferAttribute );
  1075. break;
  1076. case 'COLOR_0':
  1077. case 'COLOR0':
  1078. case 'COLOR':
  1079. geometry.addAttribute( 'color', bufferAttribute );
  1080. break;
  1081. case 'WEIGHT':
  1082. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1083. break;
  1084. case 'JOINT':
  1085. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1086. break;
  1087. default:
  1088. if ( ! primitive.material ) break;
  1089. var material = json.materials[ primitive.material ];
  1090. if ( ! material.technique ) break;
  1091. var parameters = json.techniques[ material.technique ].parameters || {};
  1092. for ( var attributeName in parameters ) {
  1093. if ( parameters[ attributeName ][ 'semantic' ] === attributeId ) {
  1094. geometry.addAttribute( attributeName, bufferAttribute );
  1095. }
  1096. }
  1097. }
  1098. }
  1099. if ( primitive.indices ) {
  1100. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1101. }
  1102. var material = dependencies.materials !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial();
  1103. var meshNode = new Mesh( geometry, material );
  1104. meshNode.castShadow = true;
  1105. meshNode.name = ( name === "0" ? group.name : group.name + name );
  1106. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1107. group.add( meshNode );
  1108. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1109. var geometry = new BufferGeometry();
  1110. var attributes = primitive.attributes;
  1111. for ( var attributeId in attributes ) {
  1112. var attributeEntry = attributes[ attributeId ];
  1113. if ( ! attributeEntry ) return;
  1114. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1115. switch ( attributeId ) {
  1116. case 'POSITION':
  1117. geometry.addAttribute( 'position', bufferAttribute );
  1118. break;
  1119. case 'COLOR_0':
  1120. case 'COLOR0':
  1121. case 'COLOR':
  1122. geometry.addAttribute( 'color', bufferAttribute );
  1123. break;
  1124. }
  1125. }
  1126. var material = dependencies.materials[ primitive.material ];
  1127. var meshNode;
  1128. if ( primitive.indices ) {
  1129. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1130. meshNode = new LineSegments( geometry, material );
  1131. } else {
  1132. meshNode = new Line( geometry, material );
  1133. }
  1134. meshNode.name = ( name === "0" ? group.name : group.name + name );
  1135. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1136. group.add( meshNode );
  1137. } else {
  1138. console.warn( "Only triangular and line primitives are supported" );
  1139. }
  1140. }
  1141. return group;
  1142. } );
  1143. } );
  1144. };
  1145. GLTFParser.prototype.loadCameras = function () {
  1146. var json = this.json;
  1147. return _each( json.cameras, function ( camera ) {
  1148. if ( camera.type == "perspective" && camera.perspective ) {
  1149. var yfov = camera.perspective.yfov;
  1150. var aspectRatio = camera.perspective.aspectRatio !== undefined ? camera.perspective.aspectRatio : 1;
  1151. // According to COLLADA spec...
  1152. // aspectRatio = xfov / yfov
  1153. var xfov = yfov * aspectRatio;
  1154. var _camera = new PerspectiveCamera( _Math.radToDeg( xfov ), aspectRatio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  1155. if ( camera.name !== undefined ) _camera.name = camera.name;
  1156. if ( camera.extras ) _camera.userData = camera.extras;
  1157. return _camera;
  1158. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  1159. var _camera = new OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  1160. if ( camera.name !== undefined ) _camera.name = camera.name;
  1161. if ( camera.extras ) _camera.userData = camera.extras;
  1162. return _camera;
  1163. }
  1164. } );
  1165. };
  1166. GLTFParser.prototype.loadSkins = function () {
  1167. var json = this.json;
  1168. return this._withDependencies( [
  1169. "accessors"
  1170. ] ).then( function ( dependencies ) {
  1171. return _each( json.skins, function ( skin ) {
  1172. var bindShapeMatrix = new Matrix4();
  1173. if ( skin.bindShapeMatrix !== undefined ) bindShapeMatrix.fromArray( skin.bindShapeMatrix );
  1174. var _skin = {
  1175. bindShapeMatrix: bindShapeMatrix,
  1176. jointNames: skin.jointNames,
  1177. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1178. };
  1179. return _skin;
  1180. } );
  1181. } );
  1182. };
  1183. GLTFParser.prototype.loadAnimations = function () {
  1184. var json = this.json;
  1185. return this._withDependencies( [
  1186. "accessors",
  1187. "nodes"
  1188. ] ).then( function ( dependencies ) {
  1189. return _each( json.animations, function ( animation, animationId ) {
  1190. var tracks = [];
  1191. for ( var channelId in animation.channels ) {
  1192. var channel = animation.channels[ channelId ];
  1193. var sampler = animation.samplers[ channel.sampler ];
  1194. if ( sampler ) {
  1195. var target = channel.target;
  1196. var name = target.id;
  1197. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1198. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1199. var inputAccessor = dependencies.accessors[ input ];
  1200. var outputAccessor = dependencies.accessors[ output ];
  1201. var node = dependencies.nodes[ name ];
  1202. if ( node ) {
  1203. node.updateMatrix();
  1204. node.matrixAutoUpdate = true;
  1205. var TypedKeyframeTrack = PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.rotation
  1206. ? QuaternionKeyframeTrack
  1207. : VectorKeyframeTrack;
  1208. var targetName = node.name ? node.name : node.uuid;
  1209. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear;
  1210. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1211. // buffers before creating a truncated copy to keep. Because buffers may
  1212. // be reused by other tracks, make copies here.
  1213. tracks.push( new TypedKeyframeTrack(
  1214. targetName + '.' + PATH_PROPERTIES[ target.path ],
  1215. AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1216. AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1217. interpolation
  1218. ) );
  1219. }
  1220. }
  1221. }
  1222. var name = animation.name !== undefined ? animation.name : "animation_" + animationId;
  1223. return new AnimationClip( name, undefined, tracks );
  1224. } );
  1225. } );
  1226. };
  1227. GLTFParser.prototype.loadNodes = function () {
  1228. var json = this.json;
  1229. var extensions = this.extensions;
  1230. var scope = this;
  1231. return _each( json.nodes, function ( node ) {
  1232. var matrix = new Matrix4();
  1233. var _node;
  1234. if ( node.jointName ) {
  1235. _node = new Bone();
  1236. _node.name = node.name !== undefined ? node.name : node.jointName;
  1237. _node.jointName = node.jointName;
  1238. } else {
  1239. _node = new Object3D();
  1240. if ( node.name !== undefined ) _node.name = node.name;
  1241. }
  1242. if ( node.extras ) _node.userData = node.extras;
  1243. if ( node.matrix !== undefined ) {
  1244. matrix.fromArray( node.matrix );
  1245. _node.applyMatrix( matrix );
  1246. } else {
  1247. if ( node.translation !== undefined ) {
  1248. _node.position.fromArray( node.translation );
  1249. }
  1250. if ( node.rotation !== undefined ) {
  1251. _node.quaternion.fromArray( node.rotation );
  1252. }
  1253. if ( node.scale !== undefined ) {
  1254. _node.scale.fromArray( node.scale );
  1255. }
  1256. }
  1257. return _node;
  1258. } ).then( function ( __nodes ) {
  1259. return scope._withDependencies( [
  1260. "meshes",
  1261. "skins",
  1262. "cameras"
  1263. ] ).then( function ( dependencies ) {
  1264. return _each( __nodes, function ( _node, nodeId ) {
  1265. var node = json.nodes[ nodeId ];
  1266. if ( node.meshes !== undefined ) {
  1267. for ( var meshId in node.meshes ) {
  1268. var mesh = node.meshes[ meshId ];
  1269. var group = dependencies.meshes[ mesh ];
  1270. if ( group === undefined ) {
  1271. console.warn( 'LegacyGLTFLoader: Couldn\'t find node "' + mesh + '".' );
  1272. continue;
  1273. }
  1274. for ( var childrenId in group.children ) {
  1275. var child = group.children[ childrenId ];
  1276. // clone Mesh to add to _node
  1277. var originalMaterial = child.material;
  1278. var originalGeometry = child.geometry;
  1279. var originalUserData = child.userData;
  1280. var originalName = child.name;
  1281. var material;
  1282. if ( originalMaterial.isDeferredShaderMaterial ) {
  1283. originalMaterial = material = originalMaterial.create();
  1284. } else {
  1285. material = originalMaterial;
  1286. }
  1287. switch ( child.type ) {
  1288. case 'LineSegments':
  1289. child = new LineSegments( originalGeometry, material );
  1290. break;
  1291. case 'LineLoop':
  1292. child = new LineLoop( originalGeometry, material );
  1293. break;
  1294. case 'Line':
  1295. child = new Line( originalGeometry, material );
  1296. break;
  1297. default:
  1298. child = new Mesh( originalGeometry, material );
  1299. }
  1300. child.castShadow = true;
  1301. child.userData = originalUserData;
  1302. child.name = originalName;
  1303. var skinEntry;
  1304. if ( node.skin ) {
  1305. skinEntry = dependencies.skins[ node.skin ];
  1306. }
  1307. // Replace Mesh with SkinnedMesh in library
  1308. if ( skinEntry ) {
  1309. var getJointNode = function ( jointId ) {
  1310. var keys = Object.keys( __nodes );
  1311. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  1312. var n = __nodes[ keys[ i ] ];
  1313. if ( n.jointName === jointId ) return n;
  1314. }
  1315. return null;
  1316. };
  1317. var geometry = originalGeometry;
  1318. var material = originalMaterial;
  1319. material.skinning = true;
  1320. child = new SkinnedMesh( geometry, material );
  1321. child.castShadow = true;
  1322. child.userData = originalUserData;
  1323. child.name = originalName;
  1324. var bones = [];
  1325. var boneInverses = [];
  1326. for ( var i = 0, l = skinEntry.jointNames.length; i < l; i ++ ) {
  1327. var jointId = skinEntry.jointNames[ i ];
  1328. var jointNode = getJointNode( jointId );
  1329. if ( jointNode ) {
  1330. bones.push( jointNode );
  1331. var m = skinEntry.inverseBindMatrices.array;
  1332. var mat = new Matrix4().fromArray( m, i * 16 );
  1333. boneInverses.push( mat );
  1334. } else {
  1335. console.warn( "WARNING: joint: '" + jointId + "' could not be found" );
  1336. }
  1337. }
  1338. child.bind( new Skeleton( bones, boneInverses ), skinEntry.bindShapeMatrix );
  1339. var buildBoneGraph = function ( parentJson, parentObject, property ) {
  1340. var children = parentJson[ property ];
  1341. if ( children === undefined ) return;
  1342. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1343. var nodeId = children[ i ];
  1344. var bone = __nodes[ nodeId ];
  1345. var boneJson = json.nodes[ nodeId ];
  1346. if ( bone !== undefined && bone.isBone === true && boneJson !== undefined ) {
  1347. parentObject.add( bone );
  1348. buildBoneGraph( boneJson, bone, 'children' );
  1349. }
  1350. }
  1351. };
  1352. buildBoneGraph( node, child, 'skeletons' );
  1353. }
  1354. _node.add( child );
  1355. }
  1356. }
  1357. }
  1358. if ( node.camera !== undefined ) {
  1359. var camera = dependencies.cameras[ node.camera ];
  1360. _node.add( camera );
  1361. }
  1362. if ( node.extensions
  1363. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ]
  1364. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ) {
  1365. var extensionLights = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].lights;
  1366. var light = extensionLights[ node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ];
  1367. _node.add( light );
  1368. }
  1369. return _node;
  1370. } );
  1371. } );
  1372. } );
  1373. };
  1374. GLTFParser.prototype.loadScenes = function () {
  1375. var json = this.json;
  1376. // scene node hierachy builder
  1377. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1378. var _node = allNodes[ nodeId ];
  1379. parentObject.add( _node );
  1380. var node = json.nodes[ nodeId ];
  1381. if ( node.children ) {
  1382. var children = node.children;
  1383. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1384. var child = children[ i ];
  1385. buildNodeHierachy( child, _node, allNodes );
  1386. }
  1387. }
  1388. }
  1389. return this._withDependencies( [
  1390. "nodes"
  1391. ] ).then( function ( dependencies ) {
  1392. return _each( json.scenes, function ( scene ) {
  1393. var _scene = new Scene();
  1394. if ( scene.name !== undefined ) _scene.name = scene.name;
  1395. if ( scene.extras ) _scene.userData = scene.extras;
  1396. var nodes = scene.nodes || [];
  1397. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1398. var nodeId = nodes[ i ];
  1399. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1400. }
  1401. _scene.traverse( function ( child ) {
  1402. // Register raw material meshes with LegacyGLTFLoader.Shaders
  1403. if ( child.material && child.material.isRawShaderMaterial ) {
  1404. child.gltfShader = new GLTFShader( child, dependencies.nodes );
  1405. child.onBeforeRender = function ( renderer, scene, camera ) {
  1406. this.gltfShader.update( scene, camera );
  1407. };
  1408. }
  1409. } );
  1410. return _scene;
  1411. } );
  1412. } );
  1413. };
  1414. return LegacyGLTFLoader;
  1415. } )();
  1416. export { LegacyGLTFLoader };