GLTFExporter.js 52 KB

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