GLTFExporter.js 52 KB

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