GLTFExporter.js 52 KB

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