GLTFExporter.js 53 KB

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