GLTFExporter.js 52 KB

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