LegacyGLTFLoader.js 47 KB

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