GLTFExporter.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327
  1. //------------------------------------------------------------------------------
  2. // Constants
  3. //------------------------------------------------------------------------------
  4. var WEBGL_CONSTANTS = {
  5. POINTS: 0x0000,
  6. LINES: 0x0001,
  7. LINE_LOOP: 0x0002,
  8. LINE_STRIP: 0x0003,
  9. TRIANGLES: 0x0004,
  10. TRIANGLE_STRIP: 0x0005,
  11. TRIANGLE_FAN: 0x0006,
  12. UNSIGNED_BYTE: 0x1401,
  13. UNSIGNED_SHORT: 0x1403,
  14. FLOAT: 0x1406,
  15. UNSIGNED_INT: 0x1405,
  16. ARRAY_BUFFER: 0x8892,
  17. ELEMENT_ARRAY_BUFFER: 0x8893,
  18. NEAREST: 0x2600,
  19. LINEAR: 0x2601,
  20. NEAREST_MIPMAP_NEAREST: 0x2700,
  21. LINEAR_MIPMAP_NEAREST: 0x2701,
  22. NEAREST_MIPMAP_LINEAR: 0x2702,
  23. LINEAR_MIPMAP_LINEAR: 0x2703,
  24. CLAMP_TO_EDGE: 33071,
  25. MIRRORED_REPEAT: 33648,
  26. REPEAT: 10497
  27. };
  28. var identityArray = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ];
  29. var THREE_TO_WEBGL = {};
  30. THREE_TO_WEBGL[ THREE.NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
  31. THREE_TO_WEBGL[ THREE.NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
  32. THREE_TO_WEBGL[ THREE.NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
  33. THREE_TO_WEBGL[ THREE.LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
  34. THREE_TO_WEBGL[ THREE.LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
  35. THREE_TO_WEBGL[ THREE.LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
  36. THREE_TO_WEBGL[ THREE.ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
  37. THREE_TO_WEBGL[ THREE.RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
  38. THREE_TO_WEBGL[ THREE.MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
  39. var PATH_PROPERTIES = {
  40. scale: 'scale',
  41. position: 'translation',
  42. quaternion: 'rotation',
  43. morphTargetInfluences: 'weights'
  44. };
  45. //------------------------------------------------------------------------------
  46. // GLTF Exporter
  47. //------------------------------------------------------------------------------
  48. THREE.GLTFExporter = function () {};
  49. THREE.GLTFExporter.prototype = {
  50. constructor: THREE.GLTFExporter,
  51. /**
  52. * Parse scenes and generate GLTF output
  53. * @param {THREE.Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  54. * @param {Function} onDone Callback on completed
  55. * @param {Object} options options
  56. */
  57. parse: function ( input, onDone, options ) {
  58. var DEFAULT_OPTIONS = {
  59. binary: false,
  60. trs: false,
  61. onlyVisible: true,
  62. truncateDrawRange: true,
  63. embedImages: true,
  64. maxTextureSize: Infinity,
  65. animations: [],
  66. includeCustomExtensions: false
  67. };
  68. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  69. if ( options.animations.length > 0 ) {
  70. // Only TRS properties, and not matrices, may be targeted by animation.
  71. options.trs = true;
  72. }
  73. var outputJSON = {
  74. asset: {
  75. version: '2.0',
  76. generator: 'THREE.GLTFExporter'
  77. }
  78. };
  79. var byteOffset = 0;
  80. var buffers = [];
  81. var pending = [];
  82. var nodeMap = new Map();
  83. var skins = [];
  84. var extensionsUsed = {};
  85. var cachedData = {
  86. meshes: new Map(),
  87. attributes: new Map(),
  88. attributesNormalized: new Map(),
  89. materials: new Map(),
  90. textures: new Map(),
  91. images: new Map()
  92. };
  93. var cachedCanvas;
  94. var uids = new Map();
  95. var uid = 0;
  96. /**
  97. * Assign and return a temporal unique id for an object
  98. * especially which doesn't have .uuid
  99. * @param {Object} object
  100. * @return {Integer}
  101. */
  102. function getUID( object ) {
  103. if ( ! uids.has( object ) ) uids.set( object, uid ++ );
  104. return uids.get( object );
  105. }
  106. /**
  107. * Compare two arrays
  108. * @param {Array} array1 Array 1 to compare
  109. * @param {Array} array2 Array 2 to compare
  110. * @return {Boolean} Returns true if both arrays are equal
  111. */
  112. function equalArray( array1, array2 ) {
  113. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  114. return element === array2[ index ];
  115. } );
  116. }
  117. /**
  118. * Is identity matrix
  119. *
  120. * @param {THREE.Matrix4} matrix
  121. * @returns {Boolean} Returns true, if parameter is identity matrix
  122. */
  123. function isIdentityMatrix( matrix ) {
  124. return equalArray( matrix.elements, identityArray );
  125. }
  126. /**
  127. * Converts a string to an ArrayBuffer.
  128. * @param {string} text
  129. * @return {ArrayBuffer}
  130. */
  131. function stringToArrayBuffer( text ) {
  132. if ( window.TextEncoder !== undefined ) {
  133. return new TextEncoder().encode( text ).buffer;
  134. }
  135. var array = new Uint8Array( new ArrayBuffer( text.length ) );
  136. for ( var i = 0, il = text.length; i < il; i ++ ) {
  137. var value = text.charCodeAt( i );
  138. // Replacing multi-byte character with space(0x20).
  139. array[ i ] = value > 0xFF ? 0x20 : value;
  140. }
  141. return array.buffer;
  142. }
  143. /**
  144. * Get the min and max vectors from the given attribute
  145. * @param {THREE.BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
  146. * @param {Integer} start
  147. * @param {Integer} count
  148. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  149. */
  150. function getMinMax( attribute, start, count ) {
  151. var output = {
  152. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  153. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  154. };
  155. for ( var i = start; i < start + count; i ++ ) {
  156. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  157. var value;
  158. if ( attribute.itemSize > 4 ) {
  159. // no support for interleaved data for itemSize > 4
  160. value = attribute.array[ i * attribute.itemSize + a ];
  161. } else {
  162. if ( a === 0 ) value = attribute.getX( i );
  163. else if ( a === 1 ) value = attribute.getY( i );
  164. else if ( a === 2 ) value = attribute.getZ( i );
  165. else if ( a === 3 ) value = attribute.getW( i );
  166. }
  167. output.min[ a ] = Math.min( output.min[ a ], value );
  168. output.max[ a ] = Math.max( output.max[ a ], value );
  169. }
  170. }
  171. return output;
  172. }
  173. /**
  174. * Checks if normal attribute values are normalized.
  175. *
  176. * @param {THREE.BufferAttribute} normal
  177. * @returns {Boolean}
  178. *
  179. */
  180. function isNormalizedNormalAttribute( normal ) {
  181. if ( cachedData.attributesNormalized.has( normal ) ) {
  182. return false;
  183. }
  184. var v = new THREE.Vector3();
  185. for ( var i = 0, il = normal.count; i < il; i ++ ) {
  186. // 0.0005 is from glTF-validator
  187. if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false;
  188. }
  189. return true;
  190. }
  191. /**
  192. * Creates normalized normal buffer attribute.
  193. *
  194. * @param {THREE.BufferAttribute} normal
  195. * @returns {THREE.BufferAttribute}
  196. *
  197. */
  198. function createNormalizedNormalAttribute( normal ) {
  199. if ( cachedData.attributesNormalized.has( normal ) ) {
  200. return cachedData.attributesNormalized.get( normal );
  201. }
  202. var attribute = normal.clone();
  203. var v = new THREE.Vector3();
  204. for ( var i = 0, il = attribute.count; i < il; i ++ ) {
  205. v.fromBufferAttribute( attribute, i );
  206. if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
  207. // if values can't be normalized set (1, 0, 0)
  208. v.setX( 1.0 );
  209. } else {
  210. v.normalize();
  211. }
  212. attribute.setXYZ( i, v.x, v.y, v.z );
  213. }
  214. cachedData.attributesNormalized.set( normal, attribute );
  215. return attribute;
  216. }
  217. /**
  218. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  219. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  220. *
  221. * @param {Integer} bufferSize The size the original buffer.
  222. * @returns {Integer} new buffer size with required padding.
  223. *
  224. */
  225. function getPaddedBufferSize( bufferSize ) {
  226. return Math.ceil( bufferSize / 4 ) * 4;
  227. }
  228. /**
  229. * Returns a buffer aligned to 4-byte boundary.
  230. *
  231. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  232. * @param {Integer} paddingByte (Optional)
  233. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  234. */
  235. function getPaddedArrayBuffer( arrayBuffer, paddingByte ) {
  236. paddingByte = paddingByte || 0;
  237. var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  238. if ( paddedLength !== arrayBuffer.byteLength ) {
  239. var array = new Uint8Array( paddedLength );
  240. array.set( new Uint8Array( arrayBuffer ) );
  241. if ( paddingByte !== 0 ) {
  242. for ( var i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
  243. array[ i ] = paddingByte;
  244. }
  245. }
  246. return array.buffer;
  247. }
  248. return arrayBuffer;
  249. }
  250. /**
  251. * Serializes a userData.
  252. *
  253. * @param {THREE.Object3D|THREE.Material} object
  254. * @param {Object} gltfProperty
  255. */
  256. function serializeUserData( object, gltfProperty ) {
  257. if ( Object.keys( object.userData ).length === 0 ) {
  258. return;
  259. }
  260. try {
  261. var json = JSON.parse( JSON.stringify( object.userData ) );
  262. if ( options.includeCustomExtensions && json.gltfExtensions ) {
  263. if ( gltfProperty.extensions === undefined ) {
  264. gltfProperty.extensions = {};
  265. }
  266. for ( var extensionName in json.gltfExtensions ) {
  267. gltfProperty.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
  268. extensionsUsed[ extensionName ] = true;
  269. }
  270. delete json.gltfExtensions;
  271. }
  272. if ( Object.keys( json ).length > 0 ) {
  273. gltfProperty.extras = json;
  274. }
  275. } catch ( error ) {
  276. console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
  277. 'won\'t be serialized because of JSON.stringify error - ' + error.message );
  278. }
  279. }
  280. /**
  281. * Applies a texture transform, if present, to the map definition. Requires
  282. * the KHR_texture_transform extension.
  283. */
  284. function applyTextureTransform( mapDef, texture ) {
  285. var didTransform = false;
  286. var transformDef = {};
  287. if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
  288. transformDef.offset = texture.offset.toArray();
  289. didTransform = true;
  290. }
  291. if ( texture.rotation !== 0 ) {
  292. transformDef.rotation = texture.rotation;
  293. didTransform = true;
  294. }
  295. if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
  296. transformDef.scale = texture.repeat.toArray();
  297. didTransform = true;
  298. }
  299. if ( didTransform ) {
  300. mapDef.extensions = mapDef.extensions || {};
  301. mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
  302. extensionsUsed[ 'KHR_texture_transform' ] = true;
  303. }
  304. }
  305. /**
  306. * Process a buffer to append to the default one.
  307. * @param {ArrayBuffer} buffer
  308. * @return {Integer}
  309. */
  310. function processBuffer( buffer ) {
  311. if ( ! outputJSON.buffers ) {
  312. outputJSON.buffers = [ { byteLength: 0 } ];
  313. }
  314. // All buffers are merged before export.
  315. buffers.push( buffer );
  316. return 0;
  317. }
  318. /**
  319. * Process and generate a BufferView
  320. * @param {THREE.BufferAttribute} attribute
  321. * @param {number} componentType
  322. * @param {number} start
  323. * @param {number} count
  324. * @param {number} target (Optional) Target usage of the BufferView
  325. * @return {Object}
  326. */
  327. function processBufferView( attribute, componentType, start, count, target ) {
  328. if ( ! outputJSON.bufferViews ) {
  329. outputJSON.bufferViews = [];
  330. }
  331. // Create a new dataview and dump the attribute's array into it
  332. var componentSize;
  333. if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  334. componentSize = 1;
  335. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  336. componentSize = 2;
  337. } else {
  338. componentSize = 4;
  339. }
  340. var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
  341. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  342. var offset = 0;
  343. for ( var i = start; i < start + count; i ++ ) {
  344. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  345. var value;
  346. if ( attribute.itemSize > 4 ) {
  347. // no support for interleaved data for itemSize > 4
  348. value = attribute.array[ i * attribute.itemSize + a ];
  349. } else {
  350. if ( a === 0 ) value = attribute.getX( i );
  351. else if ( a === 1 ) value = attribute.getY( i );
  352. else if ( a === 2 ) value = attribute.getZ( i );
  353. else if ( a === 3 ) value = attribute.getW( i );
  354. }
  355. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  356. dataView.setFloat32( offset, value, true );
  357. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  358. dataView.setUint32( offset, value, true );
  359. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  360. dataView.setUint16( offset, value, true );
  361. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  362. dataView.setUint8( offset, value );
  363. }
  364. offset += componentSize;
  365. }
  366. }
  367. var gltfBufferView = {
  368. buffer: processBuffer( dataView.buffer ),
  369. byteOffset: byteOffset,
  370. byteLength: byteLength
  371. };
  372. if ( target !== undefined ) gltfBufferView.target = target;
  373. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  374. // Only define byteStride for vertex attributes.
  375. gltfBufferView.byteStride = attribute.itemSize * componentSize;
  376. }
  377. byteOffset += byteLength;
  378. outputJSON.bufferViews.push( gltfBufferView );
  379. // @TODO Merge bufferViews where possible.
  380. var output = {
  381. id: outputJSON.bufferViews.length - 1,
  382. byteLength: 0
  383. };
  384. return output;
  385. }
  386. /**
  387. * Process and generate a BufferView from an image Blob.
  388. * @param {Blob} blob
  389. * @return {Promise<Integer>}
  390. */
  391. function processBufferViewImage( blob ) {
  392. if ( ! outputJSON.bufferViews ) {
  393. outputJSON.bufferViews = [];
  394. }
  395. return new Promise( function ( resolve ) {
  396. var reader = new window.FileReader();
  397. reader.readAsArrayBuffer( blob );
  398. reader.onloadend = function () {
  399. var buffer = getPaddedArrayBuffer( reader.result );
  400. var bufferView = {
  401. buffer: processBuffer( buffer ),
  402. byteOffset: byteOffset,
  403. byteLength: buffer.byteLength
  404. };
  405. byteOffset += buffer.byteLength;
  406. outputJSON.bufferViews.push( bufferView );
  407. resolve( outputJSON.bufferViews.length - 1 );
  408. };
  409. } );
  410. }
  411. /**
  412. * Process attribute to generate an accessor
  413. * @param {THREE.BufferAttribute} attribute Attribute to process
  414. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  415. * @param {Integer} start (Optional)
  416. * @param {Integer} count (Optional)
  417. * @return {Integer} Index of the processed accessor on the "accessors" array
  418. */
  419. function processAccessor( attribute, geometry, start, count ) {
  420. var types = {
  421. 1: 'SCALAR',
  422. 2: 'VEC2',
  423. 3: 'VEC3',
  424. 4: 'VEC4',
  425. 16: 'MAT4'
  426. };
  427. var componentType;
  428. // Detect the component type of the attribute array (float, uint or ushort)
  429. if ( attribute.array.constructor === Float32Array ) {
  430. componentType = WEBGL_CONSTANTS.FLOAT;
  431. } else if ( attribute.array.constructor === Uint32Array ) {
  432. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  433. } else if ( attribute.array.constructor === Uint16Array ) {
  434. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  435. } else if ( attribute.array.constructor === Uint8Array ) {
  436. componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
  437. } else {
  438. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  439. }
  440. if ( start === undefined ) start = 0;
  441. if ( count === undefined ) count = attribute.count;
  442. // @TODO Indexed buffer geometry with drawRange not supported yet
  443. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  444. var end = start + count;
  445. var end2 = geometry.drawRange.count === Infinity
  446. ? attribute.count
  447. : geometry.drawRange.start + geometry.drawRange.count;
  448. start = Math.max( start, geometry.drawRange.start );
  449. count = Math.min( end, end2 ) - start;
  450. if ( count < 0 ) count = 0;
  451. }
  452. // Skip creating an accessor if the attribute doesn't have data to export
  453. if ( count === 0 ) {
  454. return null;
  455. }
  456. var minMax = getMinMax( attribute, start, count );
  457. var bufferViewTarget;
  458. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  459. // animation samplers, target must not be set.
  460. if ( geometry !== undefined ) {
  461. bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
  462. }
  463. var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
  464. var gltfAccessor = {
  465. bufferView: bufferView.id,
  466. byteOffset: bufferView.byteOffset,
  467. componentType: componentType,
  468. count: count,
  469. max: minMax.max,
  470. min: minMax.min,
  471. type: types[ attribute.itemSize ]
  472. };
  473. if ( attribute.normalized === true ) {
  474. gltfAccessor.normalized = true;
  475. }
  476. if ( ! outputJSON.accessors ) {
  477. outputJSON.accessors = [];
  478. }
  479. outputJSON.accessors.push( gltfAccessor );
  480. return outputJSON.accessors.length - 1;
  481. }
  482. /**
  483. * Process image
  484. * @param {Image} image to process
  485. * @param {Integer} format of the image (e.g. THREE.RGBFormat, THREE.RGBAFormat etc)
  486. * @param {Boolean} flipY before writing out the image
  487. * @return {Integer} Index of the processed texture in the "images" array
  488. */
  489. function processImage( image, format, flipY ) {
  490. if ( ! cachedData.images.has( image ) ) {
  491. cachedData.images.set( image, {} );
  492. }
  493. var cachedImages = cachedData.images.get( image );
  494. var mimeType = format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
  495. var key = mimeType + ':flipY/' + flipY.toString();
  496. if ( cachedImages[ key ] !== undefined ) {
  497. return cachedImages[ key ];
  498. }
  499. if ( ! outputJSON.images ) {
  500. outputJSON.images = [];
  501. }
  502. var gltfImage = { mimeType: mimeType };
  503. if ( options.embedImages ) {
  504. var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  505. canvas.width = Math.min( image.width, options.maxTextureSize );
  506. canvas.height = Math.min( image.height, options.maxTextureSize );
  507. var ctx = canvas.getContext( '2d' );
  508. if ( flipY === true ) {
  509. ctx.translate( 0, canvas.height );
  510. ctx.scale( 1, - 1 );
  511. }
  512. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  513. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  514. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  515. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  516. } else {
  517. if ( format !== THREE.RGBAFormat && format !== THREE.RGBFormat ) {
  518. console.error( 'GLTFExporter: Only RGB and RGBA formats are supported.' );
  519. }
  520. if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
  521. console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
  522. }
  523. let data = image.data;
  524. if ( format === THREE.RGBFormat ) {
  525. data = new Uint8ClampedArray( image.height * image.width * 4 );
  526. for ( var i = 0, j = 0; i < data.length; i += 4, j += 3 ) {
  527. data[ i + 0 ] = image.data[ j + 0 ];
  528. data[ i + 1 ] = image.data[ j + 1 ];
  529. data[ i + 2 ] = image.data[ j + 2 ];
  530. data[ i + 3 ] = 255;
  531. }
  532. }
  533. ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
  534. }
  535. if ( options.binary === true ) {
  536. pending.push( new Promise( function ( resolve ) {
  537. canvas.toBlob( function ( blob ) {
  538. processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
  539. gltfImage.bufferView = bufferViewIndex;
  540. resolve();
  541. } );
  542. }, mimeType );
  543. } ) );
  544. } else {
  545. gltfImage.uri = canvas.toDataURL( mimeType );
  546. }
  547. } else {
  548. gltfImage.uri = image.src;
  549. }
  550. outputJSON.images.push( gltfImage );
  551. var index = outputJSON.images.length - 1;
  552. cachedImages[ key ] = index;
  553. return index;
  554. }
  555. /**
  556. * Process sampler
  557. * @param {Texture} map Texture to process
  558. * @return {Integer} Index of the processed texture in the "samplers" array
  559. */
  560. function processSampler( map ) {
  561. if ( ! outputJSON.samplers ) {
  562. outputJSON.samplers = [];
  563. }
  564. var gltfSampler = {
  565. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  566. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  567. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  568. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  569. };
  570. outputJSON.samplers.push( gltfSampler );
  571. return outputJSON.samplers.length - 1;
  572. }
  573. /**
  574. * Process texture
  575. * @param {Texture} map Map to process
  576. * @return {Integer} Index of the processed texture in the "textures" array
  577. */
  578. function processTexture( map ) {
  579. if ( cachedData.textures.has( map ) ) {
  580. return cachedData.textures.get( map );
  581. }
  582. if ( ! outputJSON.textures ) {
  583. outputJSON.textures = [];
  584. }
  585. var gltfTexture = {
  586. sampler: processSampler( map ),
  587. source: processImage( map.image, map.format, map.flipY )
  588. };
  589. if ( map.name ) {
  590. gltfTexture.name = map.name;
  591. }
  592. outputJSON.textures.push( gltfTexture );
  593. var index = outputJSON.textures.length - 1;
  594. cachedData.textures.set( map, index );
  595. return index;
  596. }
  597. /**
  598. * Process material
  599. * @param {THREE.Material} material Material to process
  600. * @return {Integer} Index of the processed material in the "materials" array
  601. */
  602. function processMaterial( material ) {
  603. if ( cachedData.materials.has( material ) ) {
  604. return cachedData.materials.get( material );
  605. }
  606. if ( material.isShaderMaterial ) {
  607. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  608. return null;
  609. }
  610. if ( ! outputJSON.materials ) {
  611. outputJSON.materials = [];
  612. }
  613. // @QUESTION Should we avoid including any attribute that has the default value?
  614. var gltfMaterial = {
  615. pbrMetallicRoughness: {}
  616. };
  617. if ( material.isMeshBasicMaterial ) {
  618. gltfMaterial.extensions = { KHR_materials_unlit: {} };
  619. extensionsUsed[ 'KHR_materials_unlit' ] = true;
  620. } else if ( material.isGLTFSpecularGlossinessMaterial ) {
  621. gltfMaterial.extensions = { KHR_materials_pbrSpecularGlossiness: {} };
  622. extensionsUsed[ 'KHR_materials_pbrSpecularGlossiness' ] = true;
  623. } else if ( ! material.isMeshStandardMaterial ) {
  624. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  625. }
  626. // pbrMetallicRoughness.baseColorFactor
  627. var color = material.color.toArray().concat( [ material.opacity ] );
  628. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  629. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  630. }
  631. if ( material.isMeshStandardMaterial ) {
  632. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  633. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  634. } else if ( material.isMeshBasicMaterial ) {
  635. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.0;
  636. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.9;
  637. } else {
  638. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  639. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  640. }
  641. // pbrSpecularGlossiness diffuse, specular and glossiness factor
  642. if ( material.isGLTFSpecularGlossinessMaterial ) {
  643. if ( gltfMaterial.pbrMetallicRoughness.baseColorFactor ) {
  644. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseFactor = gltfMaterial.pbrMetallicRoughness.baseColorFactor;
  645. }
  646. var specularFactor = [ 1, 1, 1 ];
  647. material.specular.toArray( specularFactor, 0 );
  648. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularFactor = specularFactor;
  649. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.glossinessFactor = material.glossiness;
  650. }
  651. // pbrMetallicRoughness.metallicRoughnessTexture
  652. if ( material.metalnessMap || material.roughnessMap ) {
  653. if ( material.metalnessMap === material.roughnessMap ) {
  654. var metalRoughMapDef = { index: processTexture( material.metalnessMap ) };
  655. applyTextureTransform( metalRoughMapDef, material.metalnessMap );
  656. gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  657. } else {
  658. console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
  659. }
  660. }
  661. // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
  662. if ( material.map ) {
  663. var baseColorMapDef = { index: processTexture( material.map ) };
  664. applyTextureTransform( baseColorMapDef, material.map );
  665. if ( material.isGLTFSpecularGlossinessMaterial ) {
  666. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseTexture = baseColorMapDef;
  667. }
  668. gltfMaterial.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  669. }
  670. // pbrSpecularGlossiness specular map
  671. if ( material.isGLTFSpecularGlossinessMaterial && material.specularMap ) {
  672. var specularMapDef = { index: processTexture( material.specularMap ) };
  673. applyTextureTransform( specularMapDef, material.specularMap );
  674. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularGlossinessTexture = specularMapDef;
  675. }
  676. if ( material.emissive ) {
  677. // emissiveFactor
  678. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  679. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  680. gltfMaterial.emissiveFactor = emissive;
  681. }
  682. // emissiveTexture
  683. if ( material.emissiveMap ) {
  684. var emissiveMapDef = { index: processTexture( material.emissiveMap ) };
  685. applyTextureTransform( emissiveMapDef, material.emissiveMap );
  686. gltfMaterial.emissiveTexture = emissiveMapDef;
  687. }
  688. }
  689. // normalTexture
  690. if ( material.normalMap ) {
  691. var normalMapDef = { index: processTexture( material.normalMap ) };
  692. if ( material.normalScale && material.normalScale.x !== - 1 ) {
  693. if ( material.normalScale.x !== material.normalScale.y ) {
  694. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  695. }
  696. normalMapDef.scale = material.normalScale.x;
  697. }
  698. applyTextureTransform( normalMapDef, material.normalMap );
  699. gltfMaterial.normalTexture = normalMapDef;
  700. }
  701. // occlusionTexture
  702. if ( material.aoMap ) {
  703. var occlusionMapDef = {
  704. index: processTexture( material.aoMap ),
  705. texCoord: 1
  706. };
  707. if ( material.aoMapIntensity !== 1.0 ) {
  708. occlusionMapDef.strength = material.aoMapIntensity;
  709. }
  710. applyTextureTransform( occlusionMapDef, material.aoMap );
  711. gltfMaterial.occlusionTexture = occlusionMapDef;
  712. }
  713. // alphaMode
  714. if ( material.transparent ) {
  715. gltfMaterial.alphaMode = 'BLEND';
  716. } else {
  717. if ( material.alphaTest > 0.0 ) {
  718. gltfMaterial.alphaMode = 'MASK';
  719. gltfMaterial.alphaCutoff = material.alphaTest;
  720. }
  721. }
  722. // doubleSided
  723. if ( material.side === THREE.DoubleSide ) {
  724. gltfMaterial.doubleSided = true;
  725. }
  726. if ( material.name !== '' ) {
  727. gltfMaterial.name = material.name;
  728. }
  729. serializeUserData( material, gltfMaterial );
  730. outputJSON.materials.push( gltfMaterial );
  731. var index = outputJSON.materials.length - 1;
  732. cachedData.materials.set( material, index );
  733. return index;
  734. }
  735. /**
  736. * Process mesh
  737. * @param {THREE.Mesh} mesh Mesh to process
  738. * @return {Integer} Index of the processed mesh in the "meshes" array
  739. */
  740. function processMesh( mesh ) {
  741. var meshCacheKeyParts = [ mesh.geometry.uuid ];
  742. if ( Array.isArray( mesh.material ) ) {
  743. for ( var i = 0, l = mesh.material.length; i < l; i ++ ) {
  744. meshCacheKeyParts.push( mesh.material[ i ].uuid );
  745. }
  746. } else {
  747. meshCacheKeyParts.push( mesh.material.uuid );
  748. }
  749. var meshCacheKey = meshCacheKeyParts.join( ':' );
  750. if ( cachedData.meshes.has( meshCacheKey ) ) {
  751. return cachedData.meshes.get( meshCacheKey );
  752. }
  753. var geometry = mesh.geometry;
  754. var mode;
  755. // Use the correct mode
  756. if ( mesh.isLineSegments ) {
  757. mode = WEBGL_CONSTANTS.LINES;
  758. } else if ( mesh.isLineLoop ) {
  759. mode = WEBGL_CONSTANTS.LINE_LOOP;
  760. } else if ( mesh.isLine ) {
  761. mode = WEBGL_CONSTANTS.LINE_STRIP;
  762. } else if ( mesh.isPoints ) {
  763. mode = WEBGL_CONSTANTS.POINTS;
  764. } else {
  765. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  766. }
  767. if ( geometry.isBufferGeometry !== true ) {
  768. throw new Error( 'THREE.GLTFExporter: Geometry is not of type THREE.BufferGeometry.' );
  769. }
  770. var gltfMesh = {};
  771. var attributes = {};
  772. var primitives = [];
  773. var targets = [];
  774. // Conversion between attributes names in threejs and gltf spec
  775. var nameConversion = {
  776. uv: 'TEXCOORD_0',
  777. uv2: 'TEXCOORD_1',
  778. color: 'COLOR_0',
  779. skinWeight: 'WEIGHTS_0',
  780. skinIndex: 'JOINTS_0'
  781. };
  782. var originalNormal = geometry.getAttribute( 'normal' );
  783. if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) {
  784. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  785. geometry.setAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) );
  786. }
  787. // @QUESTION Detect if .vertexColors = true?
  788. // For every attribute create an accessor
  789. var modifiedAttribute = null;
  790. for ( var attributeName in geometry.attributes ) {
  791. // Ignore morph target attributes, which are exported later.
  792. if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
  793. var attribute = geometry.attributes[ attributeName ];
  794. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  795. // Prefix all geometry attributes except the ones specifically
  796. // listed in the spec; non-spec attributes are considered custom.
  797. var validVertexAttributes =
  798. /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  799. if ( ! validVertexAttributes.test( attributeName ) ) {
  800. attributeName = '_' + attributeName;
  801. }
  802. if ( cachedData.attributes.has( getUID( attribute ) ) ) {
  803. attributes[ attributeName ] = cachedData.attributes.get( getUID( attribute ) );
  804. continue;
  805. }
  806. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  807. modifiedAttribute = null;
  808. var array = attribute.array;
  809. if ( attributeName === 'JOINTS_0' &&
  810. ! ( array instanceof Uint16Array ) &&
  811. ! ( array instanceof Uint8Array ) ) {
  812. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  813. modifiedAttribute = new THREE.BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  814. }
  815. var accessor = processAccessor( modifiedAttribute || attribute, geometry );
  816. if ( accessor !== null ) {
  817. attributes[ attributeName ] = accessor;
  818. cachedData.attributes.set( getUID( attribute ), accessor );
  819. }
  820. }
  821. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
  822. // Skip if no exportable attributes found
  823. if ( Object.keys( attributes ).length === 0 ) {
  824. return null;
  825. }
  826. // Morph targets
  827. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  828. var weights = [];
  829. var targetNames = [];
  830. var reverseDictionary = {};
  831. if ( mesh.morphTargetDictionary !== undefined ) {
  832. for ( var key in mesh.morphTargetDictionary ) {
  833. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  834. }
  835. }
  836. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  837. var target = {};
  838. var warned = false;
  839. for ( var attributeName in geometry.morphAttributes ) {
  840. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  841. // Three.js doesn't support TANGENT yet.
  842. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  843. if ( ! warned ) {
  844. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  845. warned = true;
  846. }
  847. continue;
  848. }
  849. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  850. var gltfAttributeName = attributeName.toUpperCase();
  851. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  852. //
  853. // glTF 2.0 Specification:
  854. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  855. var baseAttribute = geometry.attributes[ attributeName ];
  856. if ( cachedData.attributes.has( getUID( attribute ) ) ) {
  857. target[ gltfAttributeName ] = cachedData.attributes.get( getUID( attribute ) );
  858. continue;
  859. }
  860. // Clones attribute not to override
  861. var relativeAttribute = attribute.clone();
  862. if ( ! geometry.morphTargetsRelative ) {
  863. for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {
  864. relativeAttribute.setXYZ(
  865. j,
  866. attribute.getX( j ) - baseAttribute.getX( j ),
  867. attribute.getY( j ) - baseAttribute.getY( j ),
  868. attribute.getZ( j ) - baseAttribute.getZ( j )
  869. );
  870. }
  871. }
  872. target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry );
  873. cachedData.attributes.set( getUID( baseAttribute ), target[ gltfAttributeName ] );
  874. }
  875. targets.push( target );
  876. weights.push( mesh.morphTargetInfluences[ i ] );
  877. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  878. }
  879. gltfMesh.weights = weights;
  880. if ( targetNames.length > 0 ) {
  881. gltfMesh.extras = {};
  882. gltfMesh.extras.targetNames = targetNames;
  883. }
  884. }
  885. var isMultiMaterial = Array.isArray( mesh.material );
  886. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  887. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  888. var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  889. for ( var i = 0, il = groups.length; i < il; i ++ ) {
  890. var primitive = {
  891. mode: mode,
  892. attributes: attributes,
  893. };
  894. serializeUserData( geometry, primitive );
  895. if ( targets.length > 0 ) primitive.targets = targets;
  896. if ( geometry.index !== null ) {
  897. var cacheKey = getUID( geometry.index );
  898. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  899. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  900. }
  901. if ( cachedData.attributes.has( cacheKey ) ) {
  902. primitive.indices = cachedData.attributes.get( cacheKey );
  903. } else {
  904. primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  905. cachedData.attributes.set( cacheKey, primitive.indices );
  906. }
  907. if ( primitive.indices === null ) delete primitive.indices;
  908. }
  909. var material = processMaterial( materials[ groups[ i ].materialIndex ] );
  910. if ( material !== null ) {
  911. primitive.material = material;
  912. }
  913. primitives.push( primitive );
  914. }
  915. gltfMesh.primitives = primitives;
  916. if ( ! outputJSON.meshes ) {
  917. outputJSON.meshes = [];
  918. }
  919. outputJSON.meshes.push( gltfMesh );
  920. var index = outputJSON.meshes.length - 1;
  921. cachedData.meshes.set( meshCacheKey, index );
  922. return index;
  923. }
  924. /**
  925. * Process camera
  926. * @param {THREE.Camera} camera Camera to process
  927. * @return {Integer} Index of the processed mesh in the "camera" array
  928. */
  929. function processCamera( camera ) {
  930. if ( ! outputJSON.cameras ) {
  931. outputJSON.cameras = [];
  932. }
  933. var isOrtho = camera.isOrthographicCamera;
  934. var gltfCamera = {
  935. type: isOrtho ? 'orthographic' : 'perspective'
  936. };
  937. if ( isOrtho ) {
  938. gltfCamera.orthographic = {
  939. xmag: camera.right * 2,
  940. ymag: camera.top * 2,
  941. zfar: camera.far <= 0 ? 0.001 : camera.far,
  942. znear: camera.near < 0 ? 0 : camera.near
  943. };
  944. } else {
  945. gltfCamera.perspective = {
  946. aspectRatio: camera.aspect,
  947. yfov: THREE.MathUtils.degToRad( camera.fov ),
  948. zfar: camera.far <= 0 ? 0.001 : camera.far,
  949. znear: camera.near < 0 ? 0 : camera.near
  950. };
  951. }
  952. if ( camera.name !== '' ) {
  953. gltfCamera.name = camera.type;
  954. }
  955. outputJSON.cameras.push( gltfCamera );
  956. return outputJSON.cameras.length - 1;
  957. }
  958. /**
  959. * Creates glTF animation entry from AnimationClip object.
  960. *
  961. * Status:
  962. * - Only properties listed in PATH_PROPERTIES may be animated.
  963. *
  964. * @param {THREE.AnimationClip} clip
  965. * @param {THREE.Object3D} root
  966. * @return {number}
  967. */
  968. function processAnimation( clip, root ) {
  969. if ( ! outputJSON.animations ) {
  970. outputJSON.animations = [];
  971. }
  972. clip = THREE.GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  973. var tracks = clip.tracks;
  974. var channels = [];
  975. var samplers = [];
  976. for ( var i = 0; i < tracks.length; ++ i ) {
  977. var track = tracks[ i ];
  978. var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  979. var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  980. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  981. if ( trackBinding.objectName === 'bones' ) {
  982. if ( trackNode.isSkinnedMesh === true ) {
  983. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  984. } else {
  985. trackNode = undefined;
  986. }
  987. }
  988. if ( ! trackNode || ! trackProperty ) {
  989. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  990. return null;
  991. }
  992. var inputItemSize = 1;
  993. var outputItemSize = track.values.length / track.times.length;
  994. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  995. outputItemSize /= trackNode.morphTargetInfluences.length;
  996. }
  997. var interpolation;
  998. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  999. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1000. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1001. // valid value from .getInterpolation().
  1002. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1003. interpolation = 'CUBICSPLINE';
  1004. // itemSize of CUBICSPLINE keyframe is 9
  1005. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1006. // but needs to be stored as VEC3 so dividing by 3 here.
  1007. outputItemSize /= 3;
  1008. } else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {
  1009. interpolation = 'STEP';
  1010. } else {
  1011. interpolation = 'LINEAR';
  1012. }
  1013. samplers.push( {
  1014. input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  1015. output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  1016. interpolation: interpolation
  1017. } );
  1018. channels.push( {
  1019. sampler: samplers.length - 1,
  1020. target: {
  1021. node: nodeMap.get( trackNode ),
  1022. path: trackProperty
  1023. }
  1024. } );
  1025. }
  1026. outputJSON.animations.push( {
  1027. name: clip.name || 'clip_' + outputJSON.animations.length,
  1028. samplers: samplers,
  1029. channels: channels
  1030. } );
  1031. return outputJSON.animations.length - 1;
  1032. }
  1033. function processSkin( object ) {
  1034. var node = outputJSON.nodes[ nodeMap.get( object ) ];
  1035. var skeleton = object.skeleton;
  1036. if ( skeleton === undefined ) return null;
  1037. var rootJoint = object.skeleton.bones[ 0 ];
  1038. if ( rootJoint === undefined ) return null;
  1039. var joints = [];
  1040. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1041. var temporaryBoneInverse = new THREE.Matrix4();
  1042. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  1043. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1044. temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
  1045. temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
  1046. }
  1047. if ( outputJSON.skins === undefined ) {
  1048. outputJSON.skins = [];
  1049. }
  1050. outputJSON.skins.push( {
  1051. inverseBindMatrices: processAccessor( new THREE.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 ( isIdentityMatrix( object.matrix ) === false ) {
  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 {THREE.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 THREE.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 THREE.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 THREE.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. THREE.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 = THREE.PropertyBinding.parseTrackName( sourceTrack.name );
  1356. var sourceTrackNode = THREE.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( THREE.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. };