GLTFExporter.js 53 KB

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