GLTFExporter.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232
  1. /**
  2. * @author fernandojsg / http://fernandojsg.com
  3. * @author Don McCurdy / https://www.donmccurdy.com
  4. * @author Takahiro / https://github.com/takahirox
  5. */
  6. //------------------------------------------------------------------------------
  7. // Constants
  8. //------------------------------------------------------------------------------
  9. var WEBGL_CONSTANTS = {
  10. POINTS: 0x0000,
  11. LINES: 0x0001,
  12. LINE_LOOP: 0x0002,
  13. LINE_STRIP: 0x0003,
  14. TRIANGLES: 0x0004,
  15. TRIANGLE_STRIP: 0x0005,
  16. TRIANGLE_FAN: 0x0006,
  17. UNSIGNED_BYTE: 0x1401,
  18. UNSIGNED_SHORT: 0x1403,
  19. FLOAT: 0x1406,
  20. UNSIGNED_INT: 0x1405,
  21. ARRAY_BUFFER: 0x8892,
  22. ELEMENT_ARRAY_BUFFER: 0x8893,
  23. NEAREST: 0x2600,
  24. LINEAR: 0x2601,
  25. NEAREST_MIPMAP_NEAREST: 0x2700,
  26. LINEAR_MIPMAP_NEAREST: 0x2701,
  27. NEAREST_MIPMAP_LINEAR: 0x2702,
  28. LINEAR_MIPMAP_LINEAR: 0x2703,
  29. CLAMP_TO_EDGE: 33071,
  30. MIRRORED_REPEAT: 33648,
  31. REPEAT: 10497
  32. };
  33. var THREE_TO_WEBGL = {};
  34. THREE_TO_WEBGL[ THREE.NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
  35. THREE_TO_WEBGL[ THREE.NearestMipMapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
  36. THREE_TO_WEBGL[ THREE.NearestMipMapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
  37. THREE_TO_WEBGL[ THREE.LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
  38. THREE_TO_WEBGL[ THREE.LinearMipMapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
  39. THREE_TO_WEBGL[ THREE.LinearMipMapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
  40. THREE_TO_WEBGL[ THREE.ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
  41. THREE_TO_WEBGL[ THREE.RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
  42. THREE_TO_WEBGL[ THREE.MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
  43. var PATH_PROPERTIES = {
  44. scale: 'scale',
  45. position: 'translation',
  46. quaternion: 'rotation',
  47. morphTargetInfluences: 'weights'
  48. };
  49. //------------------------------------------------------------------------------
  50. // GLTF Exporter
  51. //------------------------------------------------------------------------------
  52. THREE.GLTFExporter = function () {};
  53. THREE.GLTFExporter.prototype = {
  54. constructor: THREE.GLTFExporter,
  55. /**
  56. * Parse scenes and generate GLTF output
  57. * @param {THREE.Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  58. * @param {Function} onDone Callback on completed
  59. * @param {Object} options options
  60. */
  61. parse: function ( input, onDone, options ) {
  62. var DEFAULT_OPTIONS = {
  63. binary: false,
  64. trs: false,
  65. onlyVisible: true,
  66. truncateDrawRange: true,
  67. embedImages: true,
  68. animations: [],
  69. forceIndices: false,
  70. forcePowerOfTwoTextures: false,
  71. includeCustomExtensions: false
  72. };
  73. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  74. if ( options.animations.length > 0 ) {
  75. // Only TRS properties, and not matrices, may be targeted by animation.
  76. options.trs = true;
  77. }
  78. var outputJSON = {
  79. asset: {
  80. version: "2.0",
  81. generator: "THREE.GLTFExporter"
  82. }
  83. };
  84. var byteOffset = 0;
  85. var buffers = [];
  86. var pending = [];
  87. var nodeMap = new Map();
  88. var skins = [];
  89. var extensionsUsed = {};
  90. var cachedData = {
  91. meshes: new Map(),
  92. attributes: new Map(),
  93. attributesNormalized: new Map(),
  94. materials: new Map(),
  95. textures: new Map(),
  96. images: new Map()
  97. };
  98. var cachedCanvas;
  99. /**
  100. * Compare two arrays
  101. */
  102. /**
  103. * Compare two arrays
  104. * @param {Array} array1 Array 1 to compare
  105. * @param {Array} array2 Array 2 to compare
  106. * @return {Boolean} Returns true if both arrays are equal
  107. */
  108. function equalArray( array1, array2 ) {
  109. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  110. return element === array2[ index ];
  111. } );
  112. }
  113. /**
  114. * Converts a string to an ArrayBuffer.
  115. * @param {string} text
  116. * @return {ArrayBuffer}
  117. */
  118. function stringToArrayBuffer( text ) {
  119. if ( window.TextEncoder !== undefined ) {
  120. return new TextEncoder().encode( text ).buffer;
  121. }
  122. var array = new Uint8Array( new ArrayBuffer( text.length ) );
  123. for ( var i = 0, il = text.length; i < il; i ++ ) {
  124. var value = text.charCodeAt( i );
  125. // Replacing multi-byte character with space(0x20).
  126. array[ i ] = value > 0xFF ? 0x20 : value;
  127. }
  128. return array.buffer;
  129. }
  130. /**
  131. * Get the min and max vectors from the given attribute
  132. * @param {THREE.BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
  133. * @param {Integer} start
  134. * @param {Integer} count
  135. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  136. */
  137. function getMinMax( attribute, start, count ) {
  138. var output = {
  139. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  140. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  141. };
  142. for ( var i = start; i < start + count; i ++ ) {
  143. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  144. var value = attribute.array[ i * attribute.itemSize + a ];
  145. output.min[ a ] = Math.min( output.min[ a ], value );
  146. output.max[ a ] = Math.max( output.max[ a ], value );
  147. }
  148. }
  149. return output;
  150. }
  151. /**
  152. * Checks if image size is POT.
  153. *
  154. * @param {Image} image The image to be checked.
  155. * @returns {Boolean} Returns true if image size is POT.
  156. *
  157. */
  158. function isPowerOfTwo( image ) {
  159. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  160. }
  161. /**
  162. * Checks if normal attribute values are normalized.
  163. *
  164. * @param {THREE.BufferAttribute} normal
  165. * @returns {Boolean}
  166. *
  167. */
  168. function isNormalizedNormalAttribute( normal ) {
  169. if ( cachedData.attributesNormalized.has( normal ) ) {
  170. return false;
  171. }
  172. var v = new THREE.Vector3();
  173. for ( var i = 0, il = normal.count; i < il; i ++ ) {
  174. // 0.0005 is from glTF-validator
  175. if ( Math.abs( v.fromArray( normal.array, i * 3 ).length() - 1.0 ) > 0.0005 ) return false;
  176. }
  177. return true;
  178. }
  179. /**
  180. * Creates normalized normal buffer attribute.
  181. *
  182. * @param {THREE.BufferAttribute} normal
  183. * @returns {THREE.BufferAttribute}
  184. *
  185. */
  186. function createNormalizedNormalAttribute( normal ) {
  187. if ( cachedData.attributesNormalized.has( normal ) ) {
  188. return cachedData.attributesNormalized.get( normal );
  189. }
  190. var attribute = normal.clone();
  191. var v = new THREE.Vector3();
  192. for ( var i = 0, il = attribute.count; i < il; i ++ ) {
  193. v.fromArray( attribute.array, i * 3 );
  194. if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
  195. // if values can't be normalized set (1, 0, 0)
  196. v.setX( 1.0 );
  197. } else {
  198. v.normalize();
  199. }
  200. v.toArray( attribute.array, i * 3 );
  201. }
  202. cachedData.attributesNormalized.set( normal, attribute );
  203. return attribute;
  204. }
  205. /**
  206. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  207. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  208. *
  209. * @param {Integer} bufferSize The size the original buffer.
  210. * @returns {Integer} new buffer size with required padding.
  211. *
  212. */
  213. function getPaddedBufferSize( bufferSize ) {
  214. return Math.ceil( bufferSize / 4 ) * 4;
  215. }
  216. /**
  217. * Returns a buffer aligned to 4-byte boundary.
  218. *
  219. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  220. * @param {Integer} paddingByte (Optional)
  221. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  222. */
  223. function getPaddedArrayBuffer( arrayBuffer, paddingByte ) {
  224. paddingByte = paddingByte || 0;
  225. var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  226. if ( paddedLength !== arrayBuffer.byteLength ) {
  227. var array = new Uint8Array( paddedLength );
  228. array.set( new Uint8Array( arrayBuffer ) );
  229. if ( paddingByte !== 0 ) {
  230. for ( var i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
  231. array[ i ] = paddingByte;
  232. }
  233. }
  234. return array.buffer;
  235. }
  236. return arrayBuffer;
  237. }
  238. /**
  239. * Serializes a userData.
  240. *
  241. * @param {THREE.Object3D|THREE.Material} object
  242. * @param {Object} gltfProperty
  243. */
  244. function serializeUserData( object, gltfProperty ) {
  245. if ( Object.keys( object.userData ).length === 0 ) {
  246. return;
  247. }
  248. try {
  249. var json = JSON.parse( JSON.stringify( object.userData ) );
  250. if ( options.includeCustomExtensions && json.gltfExtensions ) {
  251. if ( gltfProperty.extensions === undefined ) {
  252. gltfProperty.extensions = {};
  253. }
  254. for ( var extensionName in json.gltfExtensions ) {
  255. gltfProperty.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
  256. extensionsUsed[ extensionName ] = true;
  257. }
  258. delete json.gltfExtensions;
  259. }
  260. if ( Object.keys( json ).length > 0 ) {
  261. gltfProperty.extras = json;
  262. }
  263. } catch ( error ) {
  264. console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
  265. 'won\'t be serialized because of JSON.stringify error - ' + error.message );
  266. }
  267. }
  268. /**
  269. * Applies a texture transform, if present, to the map definition. Requires
  270. * the KHR_texture_transform extension.
  271. */
  272. function applyTextureTransform( mapDef, texture ) {
  273. var didTransform = false;
  274. var transformDef = {};
  275. if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
  276. transformDef.offset = texture.offset.toArray();
  277. didTransform = true;
  278. }
  279. if ( texture.rotation !== 0 ) {
  280. transformDef.rotation = texture.rotation;
  281. didTransform = true;
  282. }
  283. if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
  284. transformDef.scale = texture.repeat.toArray();
  285. didTransform = true;
  286. }
  287. if ( didTransform ) {
  288. mapDef.extensions = mapDef.extensions || {};
  289. mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
  290. extensionsUsed[ 'KHR_texture_transform' ] = true;
  291. }
  292. }
  293. /**
  294. * Process a buffer to append to the default one.
  295. * @param {ArrayBuffer} buffer
  296. * @return {Integer}
  297. */
  298. function processBuffer( buffer ) {
  299. if ( ! outputJSON.buffers ) {
  300. outputJSON.buffers = [ { byteLength: 0 } ];
  301. }
  302. // All buffers are merged before export.
  303. buffers.push( buffer );
  304. return 0;
  305. }
  306. /**
  307. * Process and generate a BufferView
  308. * @param {THREE.BufferAttribute} attribute
  309. * @param {number} componentType
  310. * @param {number} start
  311. * @param {number} count
  312. * @param {number} target (Optional) Target usage of the BufferView
  313. * @return {Object}
  314. */
  315. function processBufferView( attribute, componentType, start, count, target ) {
  316. if ( ! outputJSON.bufferViews ) {
  317. outputJSON.bufferViews = [];
  318. }
  319. // Create a new dataview and dump the attribute's array into it
  320. var componentSize;
  321. if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  322. componentSize = 1;
  323. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  324. componentSize = 2;
  325. } else {
  326. componentSize = 4;
  327. }
  328. var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
  329. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  330. var offset = 0;
  331. for ( var i = start; i < start + count; i ++ ) {
  332. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  333. // @TODO Fails on InterleavedBufferAttribute, and could probably be
  334. // optimized for normal BufferAttribute.
  335. var value = attribute.array[ i * attribute.itemSize + a ];
  336. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  337. dataView.setFloat32( offset, value, true );
  338. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  339. dataView.setUint32( offset, value, true );
  340. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  341. dataView.setUint16( offset, value, true );
  342. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  343. dataView.setUint8( offset, value );
  344. }
  345. offset += componentSize;
  346. }
  347. }
  348. var gltfBufferView = {
  349. buffer: processBuffer( dataView.buffer ),
  350. byteOffset: byteOffset,
  351. byteLength: byteLength
  352. };
  353. if ( target !== undefined ) gltfBufferView.target = target;
  354. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  355. // Only define byteStride for vertex attributes.
  356. gltfBufferView.byteStride = attribute.itemSize * componentSize;
  357. }
  358. byteOffset += byteLength;
  359. outputJSON.bufferViews.push( gltfBufferView );
  360. // @TODO Merge bufferViews where possible.
  361. var output = {
  362. id: outputJSON.bufferViews.length - 1,
  363. byteLength: 0
  364. };
  365. return output;
  366. }
  367. /**
  368. * Process and generate a BufferView from an image Blob.
  369. * @param {Blob} blob
  370. * @return {Promise<Integer>}
  371. */
  372. function processBufferViewImage( blob ) {
  373. if ( ! outputJSON.bufferViews ) {
  374. outputJSON.bufferViews = [];
  375. }
  376. return new Promise( function ( resolve ) {
  377. var reader = new window.FileReader();
  378. reader.readAsArrayBuffer( blob );
  379. reader.onloadend = function () {
  380. var buffer = getPaddedArrayBuffer( reader.result );
  381. var bufferView = {
  382. buffer: processBuffer( buffer ),
  383. byteOffset: byteOffset,
  384. byteLength: buffer.byteLength
  385. };
  386. byteOffset += buffer.byteLength;
  387. outputJSON.bufferViews.push( bufferView );
  388. resolve( outputJSON.bufferViews.length - 1 );
  389. };
  390. } );
  391. }
  392. /**
  393. * Process attribute to generate an accessor
  394. * @param {THREE.BufferAttribute} attribute Attribute to process
  395. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  396. * @param {Integer} start (Optional)
  397. * @param {Integer} count (Optional)
  398. * @return {Integer} Index of the processed accessor on the "accessors" array
  399. */
  400. function processAccessor( attribute, geometry, start, count ) {
  401. var types = {
  402. 1: 'SCALAR',
  403. 2: 'VEC2',
  404. 3: 'VEC3',
  405. 4: 'VEC4',
  406. 16: 'MAT4'
  407. };
  408. var componentType;
  409. // Detect the component type of the attribute array (float, uint or ushort)
  410. if ( attribute.array.constructor === Float32Array ) {
  411. componentType = WEBGL_CONSTANTS.FLOAT;
  412. } else if ( attribute.array.constructor === Uint32Array ) {
  413. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  414. } else if ( attribute.array.constructor === Uint16Array ) {
  415. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  416. } else if ( attribute.array.constructor === Uint8Array ) {
  417. componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
  418. } else {
  419. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  420. }
  421. if ( start === undefined ) start = 0;
  422. if ( count === undefined ) count = attribute.count;
  423. // @TODO Indexed buffer geometry with drawRange not supported yet
  424. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  425. var end = start + count;
  426. var end2 = geometry.drawRange.count === Infinity
  427. ? attribute.count
  428. : geometry.drawRange.start + geometry.drawRange.count;
  429. start = Math.max( start, geometry.drawRange.start );
  430. count = Math.min( end, end2 ) - start;
  431. if ( count < 0 ) count = 0;
  432. }
  433. // Skip creating an accessor if the attribute doesn't have data to export
  434. if ( count === 0 ) {
  435. return null;
  436. }
  437. var minMax = getMinMax( attribute, start, count );
  438. var bufferViewTarget;
  439. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  440. // animation samplers, target must not be set.
  441. if ( geometry !== undefined ) {
  442. bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
  443. }
  444. var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
  445. var gltfAccessor = {
  446. bufferView: bufferView.id,
  447. byteOffset: bufferView.byteOffset,
  448. componentType: componentType,
  449. count: count,
  450. max: minMax.max,
  451. min: minMax.min,
  452. type: types[ attribute.itemSize ]
  453. };
  454. if ( ! outputJSON.accessors ) {
  455. outputJSON.accessors = [];
  456. }
  457. outputJSON.accessors.push( gltfAccessor );
  458. return outputJSON.accessors.length - 1;
  459. }
  460. /**
  461. * Process image
  462. * @param {Image} image to process
  463. * @param {Integer} format of the image (e.g. THREE.RGBFormat, THREE.RGBAFormat etc)
  464. * @param {Boolean} flipY before writing out the image
  465. * @return {Integer} Index of the processed texture in the "images" array
  466. */
  467. function processImage( image, format, flipY ) {
  468. if ( ! cachedData.images.has( image ) ) {
  469. cachedData.images.set( image, {} );
  470. }
  471. var cachedImages = cachedData.images.get( image );
  472. var mimeType = format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
  473. var key = mimeType + ":flipY/" + flipY.toString();
  474. if ( cachedImages[ key ] !== undefined ) {
  475. return cachedImages[ key ];
  476. }
  477. if ( ! outputJSON.images ) {
  478. outputJSON.images = [];
  479. }
  480. var gltfImage = { mimeType: mimeType };
  481. if ( options.embedImages ) {
  482. var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  483. canvas.width = image.width;
  484. canvas.height = image.height;
  485. if ( options.forcePowerOfTwoTextures && ! isPowerOfTwo( image ) ) {
  486. console.warn( 'GLTFExporter: Resized non-power-of-two image.', image );
  487. canvas.width = THREE.Math.floorPowerOfTwo( canvas.width );
  488. canvas.height = THREE.Math.floorPowerOfTwo( canvas.height );
  489. }
  490. var ctx = canvas.getContext( '2d' );
  491. if ( flipY === true ) {
  492. ctx.translate( 0, canvas.height );
  493. ctx.scale( 1, - 1 );
  494. }
  495. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  496. if ( options.binary === true ) {
  497. pending.push( new Promise( function ( resolve ) {
  498. canvas.toBlob( function ( blob ) {
  499. processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
  500. gltfImage.bufferView = bufferViewIndex;
  501. resolve();
  502. } );
  503. }, mimeType );
  504. } ) );
  505. } else {
  506. gltfImage.uri = canvas.toDataURL( mimeType );
  507. }
  508. } else {
  509. gltfImage.uri = image.src;
  510. }
  511. outputJSON.images.push( gltfImage );
  512. var index = outputJSON.images.length - 1;
  513. cachedImages[ key ] = index;
  514. return index;
  515. }
  516. /**
  517. * Process sampler
  518. * @param {Texture} map Texture to process
  519. * @return {Integer} Index of the processed texture in the "samplers" array
  520. */
  521. function processSampler( map ) {
  522. if ( ! outputJSON.samplers ) {
  523. outputJSON.samplers = [];
  524. }
  525. var gltfSampler = {
  526. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  527. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  528. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  529. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  530. };
  531. outputJSON.samplers.push( gltfSampler );
  532. return outputJSON.samplers.length - 1;
  533. }
  534. /**
  535. * Process texture
  536. * @param {Texture} map Map to process
  537. * @return {Integer} Index of the processed texture in the "textures" array
  538. */
  539. function processTexture( map ) {
  540. if ( cachedData.textures.has( map ) ) {
  541. return cachedData.textures.get( map );
  542. }
  543. if ( ! outputJSON.textures ) {
  544. outputJSON.textures = [];
  545. }
  546. var gltfTexture = {
  547. sampler: processSampler( map ),
  548. source: processImage( map.image, map.format, map.flipY )
  549. };
  550. outputJSON.textures.push( gltfTexture );
  551. var index = outputJSON.textures.length - 1;
  552. cachedData.textures.set( map, index );
  553. return index;
  554. }
  555. /**
  556. * Process material
  557. * @param {THREE.Material} material Material to process
  558. * @return {Integer} Index of the processed material in the "materials" array
  559. */
  560. function processMaterial( material ) {
  561. if ( cachedData.materials.has( material ) ) {
  562. return cachedData.materials.get( material );
  563. }
  564. if ( ! outputJSON.materials ) {
  565. outputJSON.materials = [];
  566. }
  567. if ( material.isShaderMaterial ) {
  568. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  569. return null;
  570. }
  571. // @QUESTION Should we avoid including any attribute that has the default value?
  572. var gltfMaterial = {
  573. pbrMetallicRoughness: {}
  574. };
  575. if ( material.isMeshBasicMaterial ) {
  576. gltfMaterial.extensions = { KHR_materials_unlit: {} };
  577. extensionsUsed[ 'KHR_materials_unlit' ] = true;
  578. } else if ( ! material.isMeshStandardMaterial ) {
  579. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  580. }
  581. // pbrMetallicRoughness.baseColorFactor
  582. var color = material.color.toArray().concat( [ material.opacity ] );
  583. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  584. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  585. }
  586. if ( material.isMeshStandardMaterial ) {
  587. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  588. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  589. } else if ( material.isMeshBasicMaterial ) {
  590. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.0;
  591. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.9;
  592. } else {
  593. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  594. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  595. }
  596. // pbrMetallicRoughness.metallicRoughnessTexture
  597. if ( material.metalnessMap || material.roughnessMap ) {
  598. if ( material.metalnessMap === material.roughnessMap ) {
  599. var metalRoughMapDef = { index: processTexture( material.metalnessMap ) };
  600. applyTextureTransform( metalRoughMapDef, material.metalnessMap );
  601. gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  602. } else {
  603. console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
  604. }
  605. }
  606. // pbrMetallicRoughness.baseColorTexture
  607. if ( material.map ) {
  608. var baseColorMapDef = { index: processTexture( material.map ) };
  609. applyTextureTransform( baseColorMapDef, material.map );
  610. gltfMaterial.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  611. }
  612. if ( material.isMeshBasicMaterial ||
  613. material.isLineBasicMaterial ||
  614. material.isPointsMaterial ) {
  615. } else {
  616. // emissiveFactor
  617. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  618. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  619. gltfMaterial.emissiveFactor = emissive;
  620. }
  621. // emissiveTexture
  622. if ( material.emissiveMap ) {
  623. var emissiveMapDef = { index: processTexture( material.emissiveMap ) };
  624. applyTextureTransform( emissiveMapDef, material.emissiveMap );
  625. gltfMaterial.emissiveTexture = emissiveMapDef;
  626. }
  627. }
  628. // normalTexture
  629. if ( material.normalMap ) {
  630. var normalMapDef = { index: processTexture( material.normalMap ) };
  631. if ( material.normalScale.x !== - 1 ) {
  632. if ( material.normalScale.x !== material.normalScale.y ) {
  633. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  634. }
  635. normalMapDef.scale = material.normalScale.x;
  636. }
  637. applyTextureTransform( normalMapDef, material.normalMap );
  638. gltfMaterial.normalTexture = normalMapDef;
  639. }
  640. // occlusionTexture
  641. if ( material.aoMap ) {
  642. var occlusionMapDef = {
  643. index: processTexture( material.aoMap ),
  644. texCoord: 1
  645. };
  646. if ( material.aoMapIntensity !== 1.0 ) {
  647. occlusionMapDef.strength = material.aoMapIntensity;
  648. }
  649. applyTextureTransform( occlusionMapDef, material.aoMap );
  650. gltfMaterial.occlusionTexture = occlusionMapDef;
  651. }
  652. // alphaMode
  653. if ( material.transparent || material.alphaTest > 0.0 ) {
  654. gltfMaterial.alphaMode = material.opacity < 1.0 ? 'BLEND' : 'MASK';
  655. // Write alphaCutoff if it's non-zero and different from the default (0.5).
  656. if ( material.alphaTest > 0.0 && material.alphaTest !== 0.5 ) {
  657. gltfMaterial.alphaCutoff = material.alphaTest;
  658. }
  659. }
  660. // doubleSided
  661. if ( material.side === THREE.DoubleSide ) {
  662. gltfMaterial.doubleSided = true;
  663. }
  664. if ( material.name !== '' ) {
  665. gltfMaterial.name = material.name;
  666. }
  667. serializeUserData( material, gltfMaterial );
  668. outputJSON.materials.push( gltfMaterial );
  669. var index = outputJSON.materials.length - 1;
  670. cachedData.materials.set( material, index );
  671. return index;
  672. }
  673. /**
  674. * Process mesh
  675. * @param {THREE.Mesh} mesh Mesh to process
  676. * @return {Integer} Index of the processed mesh in the "meshes" array
  677. */
  678. function processMesh( mesh ) {
  679. var cacheKey = mesh.geometry.uuid + ':' + mesh.material.uuid;
  680. if ( cachedData.meshes.has( cacheKey ) ) {
  681. return cachedData.meshes.get( cacheKey );
  682. }
  683. var geometry = mesh.geometry;
  684. var mode;
  685. // Use the correct mode
  686. if ( mesh.isLineSegments ) {
  687. mode = WEBGL_CONSTANTS.LINES;
  688. } else if ( mesh.isLineLoop ) {
  689. mode = WEBGL_CONSTANTS.LINE_LOOP;
  690. } else if ( mesh.isLine ) {
  691. mode = WEBGL_CONSTANTS.LINE_STRIP;
  692. } else if ( mesh.isPoints ) {
  693. mode = WEBGL_CONSTANTS.POINTS;
  694. } else {
  695. if ( ! geometry.isBufferGeometry ) {
  696. console.warn( 'GLTFExporter: Exporting THREE.Geometry will increase file size. Use THREE.BufferGeometry instead.' );
  697. var geometryTemp = new THREE.BufferGeometry();
  698. geometryTemp.fromGeometry( geometry );
  699. geometry = geometryTemp;
  700. }
  701. if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {
  702. console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
  703. mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
  704. } else if ( mesh.drawMode === THREE.TriangleStripDrawMode ) {
  705. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
  706. } else {
  707. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  708. }
  709. }
  710. var gltfMesh = {};
  711. var attributes = {};
  712. var primitives = [];
  713. var targets = [];
  714. // Conversion between attributes names in threejs and gltf spec
  715. var nameConversion = {
  716. uv: 'TEXCOORD_0',
  717. uv2: 'TEXCOORD_1',
  718. color: 'COLOR_0',
  719. skinWeight: 'WEIGHTS_0',
  720. skinIndex: 'JOINTS_0'
  721. };
  722. var originalNormal = geometry.getAttribute( 'normal' );
  723. if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) {
  724. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  725. geometry.addAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) );
  726. }
  727. // @QUESTION Detect if .vertexColors = THREE.VertexColors?
  728. // For every attribute create an accessor
  729. var modifiedAttribute = null;
  730. for ( var attributeName in geometry.attributes ) {
  731. // Ignore morph target attributes, which are exported later.
  732. if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
  733. var attribute = geometry.attributes[ attributeName ];
  734. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  735. // Prefix all geometry attributes except the ones specifically
  736. // listed in the spec; non-spec attributes are considered custom.
  737. var validVertexAttributes =
  738. /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  739. if ( ! validVertexAttributes.test( attributeName ) ) {
  740. attributeName = '_' + attributeName;
  741. }
  742. if ( cachedData.attributes.has( attribute ) ) {
  743. attributes[ attributeName ] = cachedData.attributes.get( attribute );
  744. continue;
  745. }
  746. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  747. modifiedAttribute = null;
  748. var array = attribute.array;
  749. if ( attributeName === 'JOINTS_0' &&
  750. ! ( array instanceof Uint16Array ) &&
  751. ! ( array instanceof Uint8Array ) ) {
  752. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  753. modifiedAttribute = new THREE.BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  754. }
  755. var accessor = processAccessor( modifiedAttribute || attribute, geometry );
  756. if ( accessor !== null ) {
  757. attributes[ attributeName ] = accessor;
  758. cachedData.attributes.set( attribute, accessor );
  759. }
  760. }
  761. if ( originalNormal !== undefined ) geometry.addAttribute( 'normal', originalNormal );
  762. // Skip if no exportable attributes found
  763. if ( Object.keys( attributes ).length === 0 ) {
  764. return null;
  765. }
  766. // Morph targets
  767. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  768. var weights = [];
  769. var targetNames = [];
  770. var reverseDictionary = {};
  771. if ( mesh.morphTargetDictionary !== undefined ) {
  772. for ( var key in mesh.morphTargetDictionary ) {
  773. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  774. }
  775. }
  776. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  777. var target = {};
  778. var warned = false;
  779. for ( var attributeName in geometry.morphAttributes ) {
  780. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  781. // Three.js doesn't support TANGENT yet.
  782. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  783. if ( ! warned ) {
  784. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  785. warned = true;
  786. }
  787. continue;
  788. }
  789. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  790. var gltfAttributeName = attributeName.toUpperCase();
  791. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  792. //
  793. // glTF 2.0 Specification:
  794. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  795. var baseAttribute = geometry.attributes[ attributeName ];
  796. if ( cachedData.attributes.has( attribute ) ) {
  797. target[ gltfAttributeName ] = cachedData.attributes.get( attribute );
  798. continue;
  799. }
  800. // Clones attribute not to override
  801. var relativeAttribute = attribute.clone();
  802. for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {
  803. relativeAttribute.setXYZ(
  804. j,
  805. attribute.getX( j ) - baseAttribute.getX( j ),
  806. attribute.getY( j ) - baseAttribute.getY( j ),
  807. attribute.getZ( j ) - baseAttribute.getZ( j )
  808. );
  809. }
  810. target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry );
  811. cachedData.attributes.set( baseAttribute, target[ gltfAttributeName ] );
  812. }
  813. targets.push( target );
  814. weights.push( mesh.morphTargetInfluences[ i ] );
  815. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  816. }
  817. gltfMesh.weights = weights;
  818. if ( targetNames.length > 0 ) {
  819. gltfMesh.extras = {};
  820. gltfMesh.extras.targetNames = targetNames;
  821. }
  822. }
  823. var forceIndices = options.forceIndices;
  824. var isMultiMaterial = Array.isArray( mesh.material );
  825. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  826. if ( ! forceIndices && geometry.index === null && isMultiMaterial ) {
  827. // temporal workaround.
  828. console.warn( 'THREE.GLTFExporter: Creating index for non-indexed multi-material mesh.' );
  829. forceIndices = true;
  830. }
  831. var didForceIndices = false;
  832. if ( geometry.index === null && forceIndices ) {
  833. var indices = [];
  834. for ( var i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
  835. indices[ i ] = i;
  836. }
  837. geometry.setIndex( indices );
  838. didForceIndices = true;
  839. }
  840. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  841. var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  842. for ( var i = 0, il = groups.length; i < il; i ++ ) {
  843. var primitive = {
  844. mode: mode,
  845. attributes: attributes,
  846. };
  847. serializeUserData( geometry, primitive );
  848. if ( targets.length > 0 ) primitive.targets = targets;
  849. if ( geometry.index !== null ) {
  850. if ( cachedData.attributes.has( geometry.index ) ) {
  851. primitive.indices = cachedData.attributes.get( geometry.index );
  852. } else {
  853. primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  854. cachedData.attributes.set( geometry.index, primitive.indices );
  855. }
  856. if ( primitive.indices === null ) delete primitive.indices;
  857. }
  858. var material = processMaterial( materials[ groups[ i ].materialIndex ] );
  859. if ( material !== null ) {
  860. primitive.material = material;
  861. }
  862. primitives.push( primitive );
  863. }
  864. if ( didForceIndices ) {
  865. geometry.setIndex( null );
  866. }
  867. gltfMesh.primitives = primitives;
  868. if ( ! outputJSON.meshes ) {
  869. outputJSON.meshes = [];
  870. }
  871. outputJSON.meshes.push( gltfMesh );
  872. var index = outputJSON.meshes.length - 1;
  873. cachedData.meshes.set( cacheKey, index );
  874. return index;
  875. }
  876. /**
  877. * Process camera
  878. * @param {THREE.Camera} camera Camera to process
  879. * @return {Integer} Index of the processed mesh in the "camera" array
  880. */
  881. function processCamera( camera ) {
  882. if ( ! outputJSON.cameras ) {
  883. outputJSON.cameras = [];
  884. }
  885. var isOrtho = camera.isOrthographicCamera;
  886. var gltfCamera = {
  887. type: isOrtho ? 'orthographic' : 'perspective'
  888. };
  889. if ( isOrtho ) {
  890. gltfCamera.orthographic = {
  891. xmag: camera.right * 2,
  892. ymag: camera.top * 2,
  893. zfar: camera.far <= 0 ? 0.001 : camera.far,
  894. znear: camera.near < 0 ? 0 : camera.near
  895. };
  896. } else {
  897. gltfCamera.perspective = {
  898. aspectRatio: camera.aspect,
  899. yfov: THREE.Math.degToRad( camera.fov ),
  900. zfar: camera.far <= 0 ? 0.001 : camera.far,
  901. znear: camera.near < 0 ? 0 : camera.near
  902. };
  903. }
  904. if ( camera.name !== '' ) {
  905. gltfCamera.name = camera.type;
  906. }
  907. outputJSON.cameras.push( gltfCamera );
  908. return outputJSON.cameras.length - 1;
  909. }
  910. /**
  911. * Creates glTF animation entry from AnimationClip object.
  912. *
  913. * Status:
  914. * - Only properties listed in PATH_PROPERTIES may be animated.
  915. *
  916. * @param {THREE.AnimationClip} clip
  917. * @param {THREE.Object3D} root
  918. * @return {number}
  919. */
  920. function processAnimation( clip, root ) {
  921. if ( ! outputJSON.animations ) {
  922. outputJSON.animations = [];
  923. }
  924. clip = THREE.GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  925. var tracks = clip.tracks;
  926. var channels = [];
  927. var samplers = [];
  928. for ( var i = 0; i < tracks.length; ++ i ) {
  929. var track = tracks[ i ];
  930. var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  931. var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  932. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  933. if ( trackBinding.objectName === 'bones' ) {
  934. if ( trackNode.isSkinnedMesh === true ) {
  935. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  936. } else {
  937. trackNode = undefined;
  938. }
  939. }
  940. if ( ! trackNode || ! trackProperty ) {
  941. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  942. return null;
  943. }
  944. var inputItemSize = 1;
  945. var outputItemSize = track.values.length / track.times.length;
  946. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  947. outputItemSize /= trackNode.morphTargetInfluences.length;
  948. }
  949. var interpolation;
  950. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  951. // Detecting glTF cubic spline interpolant by checking factory method's special property
  952. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  953. // valid value from .getInterpolation().
  954. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  955. interpolation = 'CUBICSPLINE';
  956. // itemSize of CUBICSPLINE keyframe is 9
  957. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  958. // but needs to be stored as VEC3 so dividing by 3 here.
  959. outputItemSize /= 3;
  960. } else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {
  961. interpolation = 'STEP';
  962. } else {
  963. interpolation = 'LINEAR';
  964. }
  965. samplers.push( {
  966. input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  967. output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  968. interpolation: interpolation
  969. } );
  970. channels.push( {
  971. sampler: samplers.length - 1,
  972. target: {
  973. node: nodeMap.get( trackNode ),
  974. path: trackProperty
  975. }
  976. } );
  977. }
  978. outputJSON.animations.push( {
  979. name: clip.name || 'clip_' + outputJSON.animations.length,
  980. samplers: samplers,
  981. channels: channels
  982. } );
  983. return outputJSON.animations.length - 1;
  984. }
  985. function processSkin( object ) {
  986. var node = outputJSON.nodes[ nodeMap.get( object ) ];
  987. var skeleton = object.skeleton;
  988. var rootJoint = object.skeleton.bones[ 0 ];
  989. if ( rootJoint === undefined ) return null;
  990. var joints = [];
  991. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  992. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  993. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  994. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  995. }
  996. if ( outputJSON.skins === undefined ) {
  997. outputJSON.skins = [];
  998. }
  999. outputJSON.skins.push( {
  1000. inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  1001. joints: joints,
  1002. skeleton: nodeMap.get( rootJoint )
  1003. } );
  1004. var skinIndex = node.skin = outputJSON.skins.length - 1;
  1005. return skinIndex;
  1006. }
  1007. function processLight( light ) {
  1008. var lightDef = {};
  1009. if ( light.name ) lightDef.name = light.name;
  1010. lightDef.color = light.color.toArray();
  1011. lightDef.intensity = light.intensity;
  1012. if ( light.isDirectionalLight ) {
  1013. lightDef.type = 'directional';
  1014. } else if ( light.isPointLight ) {
  1015. lightDef.type = 'point';
  1016. if ( light.distance > 0 ) lightDef.range = light.distance;
  1017. } else if ( light.isSpotLight ) {
  1018. lightDef.type = 'spot';
  1019. if ( light.distance > 0 ) lightDef.range = light.distance;
  1020. lightDef.spot = {};
  1021. lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
  1022. lightDef.spot.outerConeAngle = light.angle;
  1023. }
  1024. if ( light.decay !== undefined && light.decay !== 2 ) {
  1025. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
  1026. + 'and expects light.decay=2.' );
  1027. }
  1028. if ( light.target
  1029. && ( light.target.parent !== light
  1030. || light.target.position.x !== 0
  1031. || light.target.position.y !== 0
  1032. || light.target.position.z !== - 1 ) ) {
  1033. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
  1034. + 'make light.target a child of the light with position 0,0,-1.' );
  1035. }
  1036. var lights = outputJSON.extensions[ 'KHR_lights_punctual' ].lights;
  1037. lights.push( lightDef );
  1038. return lights.length - 1;
  1039. }
  1040. /**
  1041. * Process Object3D node
  1042. * @param {THREE.Object3D} node Object3D to processNode
  1043. * @return {Integer} Index of the node in the nodes list
  1044. */
  1045. function processNode( object ) {
  1046. if ( ! outputJSON.nodes ) {
  1047. outputJSON.nodes = [];
  1048. }
  1049. var gltfNode = {};
  1050. if ( options.trs ) {
  1051. var rotation = object.quaternion.toArray();
  1052. var position = object.position.toArray();
  1053. var scale = object.scale.toArray();
  1054. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1055. gltfNode.rotation = rotation;
  1056. }
  1057. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1058. gltfNode.translation = position;
  1059. }
  1060. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1061. gltfNode.scale = scale;
  1062. }
  1063. } else {
  1064. object.updateMatrix();
  1065. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  1066. gltfNode.matrix = object.matrix.elements;
  1067. }
  1068. }
  1069. // We don't export empty strings name because it represents no-name in Three.js.
  1070. if ( object.name !== '' ) {
  1071. gltfNode.name = String( object.name );
  1072. }
  1073. serializeUserData( object, gltfNode );
  1074. if ( object.isMesh || object.isLine || object.isPoints ) {
  1075. var mesh = processMesh( object );
  1076. if ( mesh !== null ) {
  1077. gltfNode.mesh = mesh;
  1078. }
  1079. } else if ( object.isCamera ) {
  1080. gltfNode.camera = processCamera( object );
  1081. } else if ( object.isDirectionalLight || object.isPointLight || object.isSpotLight ) {
  1082. if ( ! extensionsUsed[ 'KHR_lights_punctual' ] ) {
  1083. outputJSON.extensions = outputJSON.extensions || {};
  1084. outputJSON.extensions[ 'KHR_lights_punctual' ] = { lights: [] };
  1085. extensionsUsed[ 'KHR_lights_punctual' ] = true;
  1086. }
  1087. gltfNode.extensions = gltfNode.extensions || {};
  1088. gltfNode.extensions[ 'KHR_lights_punctual' ] = { light: processLight( object ) };
  1089. } else if ( object.isLight ) {
  1090. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', object );
  1091. return null;
  1092. }
  1093. if ( object.isSkinnedMesh ) {
  1094. skins.push( object );
  1095. }
  1096. if ( object.children.length > 0 ) {
  1097. var children = [];
  1098. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  1099. var child = object.children[ i ];
  1100. if ( child.visible || options.onlyVisible === false ) {
  1101. var node = processNode( child );
  1102. if ( node !== null ) {
  1103. children.push( node );
  1104. }
  1105. }
  1106. }
  1107. if ( children.length > 0 ) {
  1108. gltfNode.children = children;
  1109. }
  1110. }
  1111. outputJSON.nodes.push( gltfNode );
  1112. var nodeIndex = outputJSON.nodes.length - 1;
  1113. nodeMap.set( object, nodeIndex );
  1114. return nodeIndex;
  1115. }
  1116. /**
  1117. * Process Scene
  1118. * @param {THREE.Scene} node Scene to process
  1119. */
  1120. function processScene( scene ) {
  1121. if ( ! outputJSON.scenes ) {
  1122. outputJSON.scenes = [];
  1123. outputJSON.scene = 0;
  1124. }
  1125. var gltfScene = {
  1126. nodes: []
  1127. };
  1128. if ( scene.name !== '' ) {
  1129. gltfScene.name = scene.name;
  1130. }
  1131. if ( scene.userData && Object.keys( scene.userData ).length > 0 ) {
  1132. gltfScene.extras = serializeUserData( scene );
  1133. }
  1134. outputJSON.scenes.push( gltfScene );
  1135. var nodes = [];
  1136. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  1137. var child = scene.children[ i ];
  1138. if ( child.visible || options.onlyVisible === false ) {
  1139. var node = processNode( child );
  1140. if ( node !== null ) {
  1141. nodes.push( node );
  1142. }
  1143. }
  1144. }
  1145. if ( nodes.length > 0 ) {
  1146. gltfScene.nodes = nodes;
  1147. }
  1148. serializeUserData( scene, gltfScene );
  1149. }
  1150. /**
  1151. * Creates a THREE.Scene to hold a list of objects and parse it
  1152. * @param {Array} objects List of objects to process
  1153. */
  1154. function processObjects( objects ) {
  1155. var scene = new THREE.Scene();
  1156. scene.name = 'AuxScene';
  1157. for ( var i = 0; i < objects.length; i ++ ) {
  1158. // We push directly to children instead of calling `add` to prevent
  1159. // modify the .parent and break its original scene and hierarchy
  1160. scene.children.push( objects[ i ] );
  1161. }
  1162. processScene( scene );
  1163. }
  1164. function processInput( input ) {
  1165. input = input instanceof Array ? input : [ input ];
  1166. var objectsWithoutScene = [];
  1167. for ( var i = 0; i < input.length; i ++ ) {
  1168. if ( input[ i ] instanceof THREE.Scene ) {
  1169. processScene( input[ i ] );
  1170. } else {
  1171. objectsWithoutScene.push( input[ i ] );
  1172. }
  1173. }
  1174. if ( objectsWithoutScene.length > 0 ) {
  1175. processObjects( objectsWithoutScene );
  1176. }
  1177. for ( var i = 0; i < skins.length; ++ i ) {
  1178. processSkin( skins[ i ] );
  1179. }
  1180. for ( var i = 0; i < options.animations.length; ++ i ) {
  1181. processAnimation( options.animations[ i ], input[ 0 ] );
  1182. }
  1183. }
  1184. processInput( input );
  1185. Promise.all( pending ).then( function () {
  1186. // Merge buffers.
  1187. var blob = new Blob( buffers, { type: 'application/octet-stream' } );
  1188. // Declare extensions.
  1189. var extensionsUsedList = Object.keys( extensionsUsed );
  1190. if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList;
  1191. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  1192. // Update bytelength of the single buffer.
  1193. outputJSON.buffers[ 0 ].byteLength = blob.size;
  1194. var reader = new window.FileReader();
  1195. if ( options.binary === true ) {
  1196. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  1197. var GLB_HEADER_BYTES = 12;
  1198. var GLB_HEADER_MAGIC = 0x46546C67;
  1199. var GLB_VERSION = 2;
  1200. var GLB_CHUNK_PREFIX_BYTES = 8;
  1201. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  1202. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  1203. reader.readAsArrayBuffer( blob );
  1204. reader.onloadend = function () {
  1205. // Binary chunk.
  1206. var binaryChunk = getPaddedArrayBuffer( reader.result );
  1207. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1208. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  1209. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  1210. // JSON chunk.
  1211. var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 );
  1212. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1213. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  1214. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  1215. // GLB header.
  1216. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  1217. var headerView = new DataView( header );
  1218. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  1219. headerView.setUint32( 4, GLB_VERSION, true );
  1220. var totalByteLength = GLB_HEADER_BYTES
  1221. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  1222. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  1223. headerView.setUint32( 8, totalByteLength, true );
  1224. var glbBlob = new Blob( [
  1225. header,
  1226. jsonChunkPrefix,
  1227. jsonChunk,
  1228. binaryChunkPrefix,
  1229. binaryChunk
  1230. ], { type: 'application/octet-stream' } );
  1231. var glbReader = new window.FileReader();
  1232. glbReader.readAsArrayBuffer( glbBlob );
  1233. glbReader.onloadend = function () {
  1234. onDone( glbReader.result );
  1235. };
  1236. };
  1237. } else {
  1238. reader.readAsDataURL( blob );
  1239. reader.onloadend = function () {
  1240. var base64data = reader.result;
  1241. outputJSON.buffers[ 0 ].uri = base64data;
  1242. onDone( outputJSON );
  1243. };
  1244. }
  1245. } else {
  1246. onDone( outputJSON );
  1247. }
  1248. } );
  1249. }
  1250. };
  1251. THREE.GLTFExporter.Utils = {
  1252. insertKeyframe: function ( track, time ) {
  1253. var tolerance = 0.001; // 1ms
  1254. var valueSize = track.getValueSize();
  1255. var times = new track.TimeBufferType( track.times.length + 1 );
  1256. var values = new track.ValueBufferType( track.values.length + valueSize );
  1257. var interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  1258. var index;
  1259. if ( track.times.length === 0 ) {
  1260. times[ 0 ] = time;
  1261. for ( var i = 0; i < valueSize; i ++ ) {
  1262. values[ i ] = 0;
  1263. }
  1264. index = 0;
  1265. } else if ( time < track.times[ 0 ] ) {
  1266. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  1267. times[ 0 ] = time;
  1268. times.set( track.times, 1 );
  1269. values.set( interpolant.evaluate( time ), 0 );
  1270. values.set( track.values, valueSize );
  1271. index = 0;
  1272. } else if ( time > track.times[ track.times.length - 1 ] ) {
  1273. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  1274. return track.times.length - 1;
  1275. }
  1276. times[ times.length - 1 ] = time;
  1277. times.set( track.times, 0 );
  1278. values.set( track.values, 0 );
  1279. values.set( interpolant.evaluate( time ), track.values.length );
  1280. index = times.length - 1;
  1281. } else {
  1282. for ( var i = 0; i < track.times.length; i ++ ) {
  1283. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  1284. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  1285. times.set( track.times.slice( 0, i + 1 ), 0 );
  1286. times[ i + 1 ] = time;
  1287. times.set( track.times.slice( i + 1 ), i + 2 );
  1288. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  1289. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  1290. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  1291. index = i + 1;
  1292. break;
  1293. }
  1294. }
  1295. }
  1296. track.times = times;
  1297. track.values = values;
  1298. return index;
  1299. },
  1300. mergeMorphTargetTracks: function ( clip, root ) {
  1301. var tracks = [];
  1302. var mergedTracks = {};
  1303. var sourceTracks = clip.tracks;
  1304. for ( var i = 0; i < sourceTracks.length; ++ i ) {
  1305. var sourceTrack = sourceTracks[ i ];
  1306. var sourceTrackBinding = THREE.PropertyBinding.parseTrackName( sourceTrack.name );
  1307. var sourceTrackNode = THREE.PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  1308. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  1309. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  1310. tracks.push( sourceTrack );
  1311. continue;
  1312. }
  1313. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
  1314. && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  1315. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  1316. // This should never happen, because glTF morph target animations
  1317. // affect all targets already.
  1318. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  1319. }
  1320. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  1321. sourceTrack = sourceTrack.clone();
  1322. sourceTrack.setInterpolation( THREE.InterpolateLinear );
  1323. }
  1324. var targetCount = sourceTrackNode.morphTargetInfluences.length;
  1325. var targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  1326. if ( targetIndex === undefined ) {
  1327. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  1328. }
  1329. var mergedTrack;
  1330. // If this is the first time we've seen this object, create a new
  1331. // track to store merged keyframe data for each morph target.
  1332. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  1333. mergedTrack = sourceTrack.clone();
  1334. var values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  1335. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1336. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  1337. }
  1338. mergedTrack.name = '.morphTargetInfluences';
  1339. mergedTrack.values = values;
  1340. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  1341. tracks.push( mergedTrack );
  1342. continue;
  1343. }
  1344. var mergedKeyframeIndex = 0;
  1345. var sourceKeyframeIndex = 0;
  1346. var sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  1347. mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
  1348. // For every existing keyframe of the merged track, write a (possibly
  1349. // interpolated) value from the source track.
  1350. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1351. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  1352. }
  1353. // For every existing keyframe of the source track, write a (possibly
  1354. // new) keyframe to the merged track. Values from the previous loop may
  1355. // be written again, but keyframes are de-duplicated.
  1356. for ( var j = 0; j < sourceTrack.times.length; j ++ ) {
  1357. var keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  1358. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  1359. }
  1360. }
  1361. clip.tracks = tracks;
  1362. return clip;
  1363. }
  1364. };