GLTFExporter.js 52 KB

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