GLTFExporter.js 53 KB

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