GLTFExporter.js 52 KB

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