GLTFExporter.js 52 KB

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