index.js 57 KB

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