GLTFExporter.js 52 KB

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