GLTFExporter.js 53 KB

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