2
0

GLTFExporter.js 53 KB

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