GLTFExporter.js 53 KB

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