babylon.glTF2Serializer.js 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. ;
  5. /**
  6. * Class for generating glTF data from a Babylon scene.
  7. */
  8. var GLTF2Export = /** @class */ (function () {
  9. function GLTF2Export() {
  10. }
  11. /**
  12. * Exports the geometry of the scene to .gltf file format.
  13. * @param scene - Babylon scene with scene hierarchy information.
  14. * @param filePrefix - File prefix to use when generating the glTF file.
  15. * @param options - Exporter options.
  16. * @returns - Returns an object with a .gltf file and associates texture names
  17. * as keys and their data and paths as values.
  18. */
  19. GLTF2Export.GLTF = function (scene, filePrefix, options) {
  20. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  21. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  22. if (scene.isReady) {
  23. return gltfGenerator._generateGLTF(glTFPrefix);
  24. }
  25. else {
  26. throw new Error("glTF Serializer: Scene is not ready!");
  27. }
  28. };
  29. /**
  30. * Exports the geometry of the scene to .glb file format.
  31. * @param scene - Babylon scene with scene hierarchy information.
  32. * @param filePrefix - File prefix to use when generating glb file.
  33. * @param options - Exporter options.
  34. * @returns - Returns an object with a .glb filename as key and data as value
  35. */
  36. GLTF2Export.GLB = function (scene, filePrefix, options) {
  37. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  38. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  39. if (scene.isReady) {
  40. return gltfGenerator._generateGLB(glTFPrefix);
  41. }
  42. else {
  43. throw new Error("glTF Serializer: Scene is not ready!");
  44. }
  45. };
  46. return GLTF2Export;
  47. }());
  48. BABYLON.GLTF2Export = GLTF2Export;
  49. })(BABYLON || (BABYLON = {}));
  50. //# sourceMappingURL=babylon.glTFSerializer.js.map
  51. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  52. /**
  53. * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally.
  54. * @hidden - capitalization of GLTF2 module.
  55. */
  56. var BABYLON;
  57. (function (BABYLON) {
  58. var GLTF2;
  59. (function (GLTF2) {
  60. /**
  61. * Converts Babylon Scene into glTF 2.0.
  62. * @hidden
  63. */
  64. var _Exporter = /** @class */ (function () {
  65. /**
  66. * Creates a glTF Exporter instance, which can accept optional exporter options.
  67. * @param babylonScene - Babylon scene object
  68. * @param options - Options to modify the behavior of the exporter.
  69. */
  70. function _Exporter(babylonScene, options) {
  71. this.asset = { generator: "BabylonJS", version: "2.0" };
  72. this.babylonScene = babylonScene;
  73. this.bufferViews = new Array();
  74. this.accessors = new Array();
  75. this.meshes = new Array();
  76. this.scenes = new Array();
  77. this.nodes = new Array();
  78. this.images = new Array();
  79. this.materials = new Array();
  80. this.textures = new Array();
  81. this.imageData = {};
  82. this.convertToRightHandedSystem = this.babylonScene.useRightHandedSystem ? false : true;
  83. if (options) {
  84. this.options = options;
  85. }
  86. }
  87. /**
  88. * Creates a buffer view based on teh supplied arguments
  89. * @param bufferIndex - index value of the specified buffer
  90. * @param byteOffset - byte offset value
  91. * @param byteLength - byte length of the bufferView
  92. * @param byteStride - byte distance between conequential elements.
  93. * @param name - name of the buffer view
  94. * @returns - bufferView for glTF
  95. */
  96. _Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  97. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  98. if (byteOffset) {
  99. bufferview.byteOffset = byteOffset;
  100. }
  101. if (name) {
  102. bufferview.name = name;
  103. }
  104. if (byteStride) {
  105. bufferview.byteStride = byteStride;
  106. }
  107. return bufferview;
  108. };
  109. /**
  110. * Creates an accessor based on the supplied arguments
  111. * @param bufferviewIndex - The index of the bufferview referenced by this accessor.
  112. * @param name - The name of the accessor.
  113. * @param type - The type of the accessor.
  114. * @param componentType - The datatype of components in the attribute.
  115. * @param count - The number of attributes referenced by this accessor.
  116. * @param byteOffset - The offset relative to the start of the bufferView in bytes.
  117. * @param min - Minimum value of each component in this attribute.
  118. * @param max - Maximum value of each component in this attribute.
  119. * @returns - accessor for glTF
  120. */
  121. _Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  122. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  123. if (min) {
  124. accessor.min = min;
  125. }
  126. if (max) {
  127. accessor.max = max;
  128. }
  129. if (byteOffset) {
  130. accessor.byteOffset = byteOffset;
  131. }
  132. return accessor;
  133. };
  134. /**
  135. * Calculates the minimum and maximum values of an array of position floats.
  136. * @param positions - Positions array of a mesh.
  137. * @param vertexStart - Starting vertex offset to calculate min and max values.
  138. * @param vertexCount - Number of vertices to check for min and max values.
  139. * @returns - min number array and max number array.
  140. */
  141. _Exporter.prototype.calculateMinMaxPositions = function (positions, vertexStart, vertexCount) {
  142. var min = [Infinity, Infinity, Infinity];
  143. var max = [-Infinity, -Infinity, -Infinity];
  144. var positionStrideSize = 3;
  145. var end = vertexStart + vertexCount;
  146. if (vertexCount) {
  147. for (var i = vertexStart; i < end; ++i) {
  148. var indexOffset = positionStrideSize * i;
  149. var position = BABYLON.Vector3.FromArray(positions, indexOffset);
  150. var vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(position).asArray() : position.asArray();
  151. for (var j = 0; j < positionStrideSize; ++j) {
  152. var num = vector[j];
  153. if (num < min[j]) {
  154. min[j] = num;
  155. }
  156. if (num > max[j]) {
  157. max[j] = num;
  158. }
  159. ++indexOffset;
  160. }
  161. }
  162. }
  163. return { min: min, max: max };
  164. };
  165. /**
  166. * Converts a vector3 array to right-handed.
  167. * @param vector - vector3 Array to convert to right-handed.
  168. * @returns - right-handed Vector3 array.
  169. */
  170. _Exporter.GetRightHandedVector3 = function (vector) {
  171. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  172. };
  173. /**
  174. * Converts a vector4 array to right-handed.
  175. * @param vector - vector4 Array to convert to right-handed.
  176. * @returns - right-handed vector4 array.
  177. */
  178. _Exporter.GetRightHandedVector4 = function (vector) {
  179. return new BABYLON.Vector4(vector.x, vector.y, -vector.z, -vector.w);
  180. };
  181. /**
  182. * Converts a quaternion to right-handed.
  183. * @param quaternion - Source quaternion to convert to right-handed.
  184. */
  185. _Exporter.GetRightHandedQuaternion = function (quaternion) {
  186. return new BABYLON.Quaternion(-quaternion.x, -quaternion.y, quaternion.z, quaternion.w);
  187. };
  188. /**
  189. * Writes mesh attribute data to a data buffer.
  190. * Returns the bytelength of the data.
  191. * @param vertexBufferKind - Indicates what kind of vertex data is being passed in.
  192. * @param meshAttributeArray - Array containing the attribute data.
  193. * @param byteOffset - The offset to start counting bytes from.
  194. * @param dataBuffer - The buffer to write the binary data to.
  195. * @returns - Byte length of the attribute data.
  196. */
  197. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, byteOffset, dataBuffer) {
  198. var byteOff = byteOffset;
  199. var stride = BABYLON.VertexBuffer.DeduceStride(vertexBufferKind);
  200. var end = meshAttributeArray.length / stride;
  201. var byteLength = 0;
  202. for (var k = 0; k < end; ++k) {
  203. var index = k * stride;
  204. var vector = [];
  205. if (vertexBufferKind === BABYLON.VertexBuffer.PositionKind || vertexBufferKind === BABYLON.VertexBuffer.NormalKind) {
  206. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  207. vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(vertexData).asArray() : vertexData.asArray();
  208. }
  209. else if (vertexBufferKind === BABYLON.VertexBuffer.TangentKind || vertexBufferKind === BABYLON.VertexBuffer.ColorKind) {
  210. var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
  211. vector = (this.convertToRightHandedSystem && !(vertexBufferKind === BABYLON.VertexBuffer.ColorKind)) ? _Exporter.GetRightHandedVector4(vertexData).asArray() : vertexData.asArray();
  212. }
  213. else if (vertexBufferKind === BABYLON.VertexBuffer.UVKind || vertexBufferKind === BABYLON.VertexBuffer.UV2Kind) {
  214. vector = [meshAttributeArray[index], meshAttributeArray[index + 1]];
  215. }
  216. else {
  217. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  218. }
  219. for (var i = 0; i < vector.length; ++i) {
  220. dataBuffer.setFloat32(byteOff, vector[i], true);
  221. byteOff += 4;
  222. }
  223. }
  224. byteLength = meshAttributeArray.length * 4;
  225. return byteLength;
  226. };
  227. /**
  228. * Generates glTF json data
  229. * @param shouldUseGlb - Indicates whether the json should be written for a glb file.
  230. * @param glTFPrefix - Text to use when prefixing a glTF file.
  231. * @param prettyPrint - Indicates whether the json file should be pretty printed (true) or not (false).
  232. * @returns - json data as string
  233. */
  234. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  235. var buffer = { byteLength: this.totalByteLength };
  236. var glTF = {
  237. asset: this.asset
  238. };
  239. if (buffer.byteLength) {
  240. glTF.buffers = [buffer];
  241. }
  242. if (this.nodes && this.nodes.length) {
  243. glTF.nodes = this.nodes;
  244. }
  245. if (this.meshes && this.meshes.length) {
  246. glTF.meshes = this.meshes;
  247. }
  248. if (this.scenes && this.scenes.length) {
  249. glTF.scenes = this.scenes;
  250. glTF.scene = 0;
  251. }
  252. if (this.bufferViews && this.bufferViews.length) {
  253. glTF.bufferViews = this.bufferViews;
  254. }
  255. if (this.accessors && this.accessors.length) {
  256. glTF.accessors = this.accessors;
  257. }
  258. if (this.materials && this.materials.length) {
  259. glTF.materials = this.materials;
  260. }
  261. if (this.textures && this.textures.length) {
  262. glTF.textures = this.textures;
  263. }
  264. if (this.images && this.images.length) {
  265. if (!shouldUseGlb) {
  266. glTF.images = this.images;
  267. }
  268. else {
  269. glTF.images = [];
  270. // Replace uri with bufferview and mime type for glb
  271. var imageLength = this.images.length;
  272. var byteOffset = this.totalByteLength;
  273. for (var i = 0; i < imageLength; ++i) {
  274. var image = this.images[i];
  275. if (image.uri) {
  276. var imageData = this.imageData[image.uri];
  277. var imageName = image.uri.split('.')[0] + " image";
  278. var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  279. byteOffset += imageData.data.buffer.byteLength;
  280. this.bufferViews.push(bufferView);
  281. image.bufferView = this.bufferViews.length - 1;
  282. image.name = imageName;
  283. image.mimeType = imageData.mimeType;
  284. image.uri = undefined;
  285. glTF.images.push(image);
  286. }
  287. }
  288. buffer.byteLength = byteOffset;
  289. }
  290. }
  291. if (!shouldUseGlb) {
  292. buffer.uri = glTFPrefix + ".bin";
  293. }
  294. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  295. return jsonText;
  296. };
  297. /**
  298. * Generates data for .gltf and .bin files based on the glTF prefix string
  299. * @param glTFPrefix - Text to use when prefixing a glTF file.
  300. * @returns - GLTFData with glTF file data.
  301. */
  302. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  303. var binaryBuffer = this.generateBinary();
  304. var jsonText = this.generateJSON(false, glTFPrefix, true);
  305. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  306. var glTFFileName = glTFPrefix + '.gltf';
  307. var glTFBinFile = glTFPrefix + '.bin';
  308. var container = new BABYLON._GLTFData();
  309. container.glTFFiles[glTFFileName] = jsonText;
  310. container.glTFFiles[glTFBinFile] = bin;
  311. if (this.imageData) {
  312. for (var image in this.imageData) {
  313. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  314. }
  315. }
  316. return container;
  317. };
  318. /**
  319. * Creates a binary buffer for glTF
  320. * @returns - array buffer for binary data
  321. */
  322. _Exporter.prototype.generateBinary = function () {
  323. var byteOffset = 0;
  324. byteOffset = this.createScene(this.babylonScene, byteOffset);
  325. return this.binaryBuffer;
  326. };
  327. /**
  328. * Pads the number to a multiple of 4
  329. * @param num - number to pad
  330. * @returns - padded number
  331. */
  332. _Exporter.prototype._getPadding = function (num) {
  333. var remainder = num % 4;
  334. var padding = remainder === 0 ? remainder : 4 - remainder;
  335. return padding;
  336. };
  337. /**
  338. * Generates a glb file from the json and binary data.
  339. * Returns an object with the glb file name as the key and data as the value.
  340. * @param glTFPrefix
  341. * @returns - object with glb filename as key and data as value
  342. */
  343. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  344. var binaryBuffer = this.generateBinary();
  345. var jsonText = this.generateJSON(true);
  346. var glbFileName = glTFPrefix + '.glb';
  347. var headerLength = 12;
  348. var chunkLengthPrefix = 8;
  349. var jsonLength = jsonText.length;
  350. var imageByteLength = 0;
  351. for (var key in this.imageData) {
  352. imageByteLength += this.imageData[key].data.byteLength;
  353. }
  354. var jsonPadding = this._getPadding(jsonLength);
  355. var binPadding = this._getPadding(binaryBuffer.byteLength);
  356. var imagePadding = this._getPadding(imageByteLength);
  357. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  358. //header
  359. var headerBuffer = new ArrayBuffer(headerLength);
  360. var headerBufferView = new DataView(headerBuffer);
  361. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  362. headerBufferView.setUint32(4, 2, true); // version
  363. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  364. //json chunk
  365. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  366. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  367. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  368. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  369. //json chunk bytes
  370. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  371. for (var i = 0; i < jsonLength; ++i) {
  372. jsonData[i] = jsonText.charCodeAt(i);
  373. }
  374. //json padding
  375. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  376. for (var i = 0; i < jsonPadding; ++i) {
  377. jsonPaddingView[i] = 0x20;
  378. }
  379. //binary chunk
  380. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  381. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  382. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  383. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  384. // binary padding
  385. var binPaddingBuffer = new ArrayBuffer(binPadding);
  386. var binPaddingView = new Uint8Array(binPaddingBuffer);
  387. for (var i = 0; i < binPadding; ++i) {
  388. binPaddingView[i] = 0;
  389. }
  390. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  391. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  392. for (var i = 0; i < imagePadding; ++i) {
  393. imagePaddingView[i] = 0;
  394. }
  395. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  396. // binary data
  397. for (var key in this.imageData) {
  398. glbData.push(this.imageData[key].data.buffer);
  399. }
  400. glbData.push(binPaddingBuffer);
  401. glbData.push(imagePaddingBuffer);
  402. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  403. var container = new BABYLON._GLTFData();
  404. container.glTFFiles[glbFileName] = glbFile;
  405. return container;
  406. };
  407. /**
  408. * Sets the TRS for each node
  409. * @param node - glTF Node for storing the transformation data.
  410. * @param babylonMesh - Babylon mesh used as the source for the transformation data.
  411. */
  412. _Exporter.prototype.setNodeTransformation = function (node, babylonMesh) {
  413. if (!babylonMesh.position.equalsToFloats(0, 0, 0)) {
  414. node.translation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(babylonMesh.position).asArray() : babylonMesh.position.asArray();
  415. }
  416. if (!babylonMesh.scaling.equalsToFloats(1, 1, 1)) {
  417. node.scale = babylonMesh.scaling.asArray();
  418. }
  419. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  420. if (babylonMesh.rotationQuaternion) {
  421. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  422. }
  423. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  424. node.rotation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedQuaternion(rotationQuaternion).asArray() : rotationQuaternion.asArray();
  425. }
  426. };
  427. /**
  428. * Creates a bufferview based on the vertices type for the Babylon mesh
  429. * @param kind - Indicates the type of vertices data.
  430. * @param babylonMesh - The Babylon mesh to get the vertices data from.
  431. * @param byteOffset - The offset from the buffer to start indexing from.
  432. * @param dataBuffer - The buffer to write the bufferview data to.
  433. * @returns bytelength of the bufferview data.
  434. */
  435. _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, byteOffset, dataBuffer) {
  436. var bufferMesh = null;
  437. var byteLength = 0;
  438. if (babylonMesh instanceof BABYLON.Mesh) {
  439. bufferMesh = babylonMesh;
  440. }
  441. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  442. bufferMesh = babylonMesh.sourceMesh;
  443. }
  444. if (bufferMesh) {
  445. var vertexData = bufferMesh.getVerticesData(kind);
  446. if (vertexData) {
  447. if (dataBuffer && vertexData) { // write data to buffer
  448. byteLength = this.writeAttributeData(kind, vertexData, byteOffset, dataBuffer);
  449. byteOffset += byteLength;
  450. }
  451. else {
  452. byteLength = vertexData.length * 4;
  453. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, kind + " - " + bufferMesh.name);
  454. byteOffset += byteLength;
  455. this.bufferViews.push(bufferView);
  456. }
  457. }
  458. }
  459. return byteLength;
  460. };
  461. /**
  462. * Sets data for the primitive attributes of each submesh
  463. * @param mesh - glTF Mesh object to store the primitive attribute information.
  464. * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
  465. * @param byteOffset - The offset in bytes of the buffer data.
  466. * @param dataBuffer - Buffer to write the attribute data to.
  467. * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
  468. */
  469. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, dataBuffer) {
  470. var bufferMesh = null;
  471. if (babylonMesh instanceof BABYLON.Mesh) {
  472. bufferMesh = babylonMesh;
  473. }
  474. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  475. bufferMesh = babylonMesh.sourceMesh;
  476. }
  477. var attributeData = [
  478. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */ },
  479. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */ },
  480. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */ },
  481. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */ },
  482. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */ },
  483. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */ },
  484. ];
  485. var indexBufferViewIndex = null;
  486. if (bufferMesh) {
  487. // For each BabylonMesh, create bufferviews for each 'kind'
  488. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  489. var attribute = attributeData_1[_i];
  490. var attributeKind = attribute.kind;
  491. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  492. byteOffset += this.createBufferViewKind(attributeKind, babylonMesh, byteOffset, dataBuffer);
  493. attribute.bufferViewIndex = this.bufferViews.length - 1;
  494. }
  495. }
  496. if (bufferMesh.getTotalIndices()) {
  497. var indices = bufferMesh.getIndices();
  498. if (indices) {
  499. if (dataBuffer) {
  500. var end = indices.length;
  501. var byteOff = byteOffset;
  502. for (var k = 0; k < end; ++k) {
  503. dataBuffer.setUint32(byteOff, indices[k], true);
  504. byteOff += 4;
  505. }
  506. byteOffset = byteOff;
  507. }
  508. else {
  509. var byteLength = indices.length * 4;
  510. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
  511. byteOffset += byteLength;
  512. this.bufferViews.push(bufferView);
  513. indexBufferViewIndex = this.bufferViews.length - 1;
  514. }
  515. }
  516. }
  517. if (babylonMesh.subMeshes) {
  518. var uvCoordsPresent = false;
  519. // go through all mesh primitives (submeshes)
  520. for (var _a = 0, _b = babylonMesh.subMeshes; _a < _b.length; _a++) {
  521. var submesh = _b[_a];
  522. var meshPrimitive = { attributes: {} };
  523. // Create a bufferview storing all the positions
  524. if (!dataBuffer) {
  525. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  526. var attribute = attributeData_2[_c];
  527. var attributeKind = attribute.kind;
  528. var vertexData = bufferMesh.getVerticesData(attributeKind);
  529. if (vertexData) {
  530. var stride = BABYLON.VertexBuffer.DeduceStride(attributeKind);
  531. var minMax = void 0;
  532. var min = null;
  533. var max = null;
  534. var bufferViewIndex = attribute.bufferViewIndex;
  535. if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
  536. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  537. minMax = this.calculateMinMaxPositions(vertexData, 0, vertexData.length / stride);
  538. min = minMax.min;
  539. max = minMax.max;
  540. }
  541. var accessor = this.createAccessor(bufferViewIndex, attributeKind + " - " + babylonMesh.name, attribute.accessorType, 5126 /* FLOAT */, vertexData.length / stride, 0, min, max);
  542. this.accessors.push(accessor);
  543. switch (attributeKind) {
  544. case BABYLON.VertexBuffer.PositionKind: {
  545. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  546. break;
  547. }
  548. case BABYLON.VertexBuffer.NormalKind: {
  549. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  550. break;
  551. }
  552. case BABYLON.VertexBuffer.ColorKind: {
  553. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  554. break;
  555. }
  556. case BABYLON.VertexBuffer.TangentKind: {
  557. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  558. break;
  559. }
  560. case BABYLON.VertexBuffer.UVKind: {
  561. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  562. uvCoordsPresent = true;
  563. break;
  564. }
  565. case BABYLON.VertexBuffer.UV2Kind: {
  566. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  567. uvCoordsPresent = true;
  568. break;
  569. }
  570. default: {
  571. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  572. }
  573. }
  574. }
  575. }
  576. }
  577. if (indexBufferViewIndex) {
  578. // Create accessor
  579. var accessor = this.createAccessor(indexBufferViewIndex, "indices - " + babylonMesh.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  580. this.accessors.push(accessor);
  581. meshPrimitive.indices = this.accessors.length - 1;
  582. }
  583. }
  584. if (bufferMesh.material) {
  585. var materialIndex = null;
  586. if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial || bufferMesh.material instanceof BABYLON.PBRMaterial) {
  587. materialIndex = babylonMesh.getScene().materials.indexOf(bufferMesh.material);
  588. }
  589. else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
  590. var babylonMultiMaterial = bufferMesh.material;
  591. var material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
  592. if (material) {
  593. materialIndex = babylonMesh.getScene().materials.indexOf(material);
  594. }
  595. }
  596. else {
  597. BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
  598. }
  599. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  600. if (uvCoordsPresent || !GLTF2._GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
  601. meshPrimitive.material = materialIndex;
  602. }
  603. else {
  604. // If no texture coordinate information is present, make a copy of the material without the textures to be glTF compliant.
  605. var newMat = GLTF2._GLTFMaterial._StripTexturesFromMaterial(this.materials[materialIndex]);
  606. this.materials.push(newMat);
  607. meshPrimitive.material = this.materials.length - 1;
  608. }
  609. }
  610. }
  611. mesh.primitives.push(meshPrimitive);
  612. }
  613. }
  614. }
  615. return byteOffset;
  616. };
  617. /**
  618. * Creates a glTF scene based on the array of meshes.
  619. * Returns the the total byte offset.
  620. * @param babylonScene - Babylon scene to get the mesh data from.
  621. * @param byteOffset - Offset to start from in bytes.
  622. * @returns bytelength + byteoffset
  623. */
  624. _Exporter.prototype.createScene = function (babylonScene, byteOffset) {
  625. if (babylonScene.meshes.length) {
  626. var babylonMeshes = babylonScene.meshes;
  627. var scene = { nodes: new Array() };
  628. GLTF2._GLTFMaterial._ConvertMaterialsToGLTF(babylonScene.materials, "image/png" /* PNG */, this.images, this.textures, this.materials, this.imageData, true);
  629. var result = this.createNodeMap(babylonScene, byteOffset);
  630. this.nodeMap = result.nodeMap;
  631. this.totalByteLength = result.byteOffset;
  632. this.binaryBuffer = new ArrayBuffer(this.totalByteLength);
  633. var dataBuffer = new DataView(this.binaryBuffer);
  634. for (var i = 0; i < babylonMeshes.length; ++i) {
  635. var babylonMesh = babylonMeshes[i];
  636. // Build Hierarchy with the node map.
  637. var glTFNodeIndex = this.nodeMap[babylonMesh.uniqueId];
  638. var glTFNode = this.nodes[glTFNodeIndex];
  639. if (!babylonMesh.parent) {
  640. if (this.options &&
  641. this.options.shouldExportMesh != undefined &&
  642. !this.options.shouldExportMesh(babylonMesh)) {
  643. BABYLON.Tools.Log("Omitting " + babylonMesh.name + " from scene.");
  644. }
  645. else {
  646. scene.nodes.push(glTFNodeIndex);
  647. }
  648. }
  649. var directDescendents = babylonMesh.getDescendants(true);
  650. if (!glTFNode.children && directDescendents && directDescendents.length) {
  651. glTFNode.children = [];
  652. for (var _i = 0, directDescendents_1 = directDescendents; _i < directDescendents_1.length; _i++) {
  653. var descendent = directDescendents_1[_i];
  654. glTFNode.children.push(this.nodeMap[descendent.uniqueId]);
  655. }
  656. }
  657. var mesh = { primitives: new Array() };
  658. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  659. }
  660. this.scenes.push(scene);
  661. }
  662. return byteOffset;
  663. };
  664. /**
  665. * Creates a mapping of Node unique id to node index
  666. * @param scene - Babylon Scene.
  667. * @param byteOffset - The initial byte offset.
  668. * @returns - Node mapping of unique id to index.
  669. */
  670. _Exporter.prototype.createNodeMap = function (scene, byteOffset) {
  671. var nodeMap = {};
  672. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  673. var babylonMesh = _a[_i];
  674. var result = this.createNode(babylonMesh, byteOffset, null);
  675. this.nodes.push(result.node);
  676. nodeMap[babylonMesh.uniqueId] = this.nodes.length - 1;
  677. byteOffset = result.byteOffset;
  678. }
  679. return { nodeMap: nodeMap, byteOffset: byteOffset };
  680. };
  681. /**
  682. * Creates a glTF node from a Babylon mesh.
  683. * @param babylonMesh - Source Babylon mesh.
  684. * @param byteOffset - The initial byte offset.
  685. * @param dataBuffer - Buffer for storing geometry data.
  686. * @returns - Object containing an INode and byteoffset.
  687. */
  688. _Exporter.prototype.createNode = function (babylonMesh, byteOffset, dataBuffer) {
  689. // create node to hold translation/rotation/scale and the mesh
  690. var node = {};
  691. if (babylonMesh.name) {
  692. node.name = babylonMesh.name;
  693. }
  694. // Set transformation
  695. this.setNodeTransformation(node, babylonMesh);
  696. // create mesh
  697. var mesh = { primitives: new Array() };
  698. mesh.primitives = [];
  699. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  700. if (mesh.primitives.length) {
  701. this.meshes.push(mesh);
  702. node.mesh = this.meshes.length - 1;
  703. }
  704. return { node: node, byteOffset: byteOffset };
  705. };
  706. return _Exporter;
  707. }());
  708. GLTF2._Exporter = _Exporter;
  709. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  710. })(BABYLON || (BABYLON = {}));
  711. //# sourceMappingURL=babylon.glTFExporter.js.map
  712. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  713. var BABYLON;
  714. (function (BABYLON) {
  715. /**
  716. * Class for holding and downloading glTF file data
  717. */
  718. var _GLTFData = /** @class */ (function () {
  719. /**
  720. * Initializes the glTF file object.
  721. */
  722. function _GLTFData() {
  723. this.glTFFiles = {};
  724. }
  725. /**
  726. * Downloads the glTF data as files based on their names and data.
  727. */
  728. _GLTFData.prototype.downloadFiles = function () {
  729. /**
  730. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  731. * @param str - Source string.
  732. * @param suffix - Suffix to search for in the source string.
  733. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  734. */
  735. function endsWith(str, suffix) {
  736. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  737. }
  738. for (var key in this.glTFFiles) {
  739. var link = document.createElement('a');
  740. document.body.appendChild(link);
  741. link.setAttribute("type", "hidden");
  742. link.download = key;
  743. var blob = this.glTFFiles[key];
  744. var mimeType = void 0;
  745. if (endsWith(key, ".glb")) {
  746. mimeType = { type: "model/gltf-binary" };
  747. }
  748. else if (endsWith(key, ".bin")) {
  749. mimeType = { type: "application/octet-stream" };
  750. }
  751. else if (endsWith(key, ".gltf")) {
  752. mimeType = { type: "model/gltf+json" };
  753. }
  754. else if (endsWith(key, ".jpeg" || ".jpg")) {
  755. mimeType = { type: "image/jpeg" /* JPEG */ };
  756. }
  757. else if (endsWith(key, ".png")) {
  758. mimeType = { type: "image/png" /* PNG */ };
  759. }
  760. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  761. link.click();
  762. }
  763. };
  764. return _GLTFData;
  765. }());
  766. BABYLON._GLTFData = _GLTFData;
  767. })(BABYLON || (BABYLON = {}));
  768. //# sourceMappingURL=babylon.glTFData.js.map
  769. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  770. var BABYLON;
  771. (function (BABYLON) {
  772. var GLTF2;
  773. (function (GLTF2) {
  774. /**
  775. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  776. * @hidden
  777. */
  778. var _GLTFMaterial = /** @class */ (function () {
  779. function _GLTFMaterial() {
  780. }
  781. /**
  782. * Specifies if two colors are approximately equal in value.
  783. * @param color1 - first color to compare to.
  784. * @param color2 - second color to compare to.
  785. * @param epsilon - threshold value
  786. */
  787. _GLTFMaterial.FuzzyEquals = function (color1, color2, epsilon) {
  788. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  789. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  790. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  791. };
  792. /**
  793. * Gets the materials from a Babylon scene and converts them to glTF materials.
  794. * @param scene - babylonjs scene.
  795. * @param mimeType - texture mime type.
  796. * @param images - array of images.
  797. * @param textures - array of textures.
  798. * @param materials - array of materials.
  799. * @param imageData - mapping of texture names to base64 textures
  800. * @param hasTextureCoords - specifies if texture coordinates are present on the material.
  801. */
  802. _GLTFMaterial._ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  803. for (var i = 0; i < babylonMaterials.length; ++i) {
  804. var babylonMaterial = babylonMaterials[i];
  805. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  806. _GLTFMaterial._ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  807. }
  808. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  809. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  810. }
  811. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  812. _GLTFMaterial._ConvertPBRMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  813. }
  814. else {
  815. throw new Error("Unsupported material type: " + babylonMaterial.name);
  816. }
  817. }
  818. };
  819. /**
  820. * Makes a copy of the glTF material without the texture parameters.
  821. * @param originalMaterial - original glTF material.
  822. * @returns glTF material without texture parameters
  823. */
  824. _GLTFMaterial._StripTexturesFromMaterial = function (originalMaterial) {
  825. var newMaterial = {};
  826. if (originalMaterial) {
  827. newMaterial.name = originalMaterial.name;
  828. newMaterial.doubleSided = originalMaterial.doubleSided;
  829. newMaterial.alphaMode = originalMaterial.alphaMode;
  830. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  831. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  832. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  833. if (originalPBRMetallicRoughness) {
  834. newMaterial.pbrMetallicRoughness = {};
  835. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  836. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  837. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  838. }
  839. }
  840. return newMaterial;
  841. };
  842. /**
  843. * Specifies if the material has any texture parameters present.
  844. * @param material - glTF Material.
  845. * @returns boolean specifying if texture parameters are present
  846. */
  847. _GLTFMaterial._HasTexturesPresent = function (material) {
  848. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  849. return true;
  850. }
  851. var pbrMat = material.pbrMetallicRoughness;
  852. if (pbrMat) {
  853. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  854. return true;
  855. }
  856. }
  857. return false;
  858. };
  859. /**
  860. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  861. * @param babylonStandardMaterial
  862. * @returns - glTF Metallic Roughness Material representation
  863. */
  864. _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  865. var P0 = new BABYLON.Vector2(0, 1);
  866. var P1 = new BABYLON.Vector2(0, 0.1);
  867. var P2 = new BABYLON.Vector2(0, 0.1);
  868. var P3 = new BABYLON.Vector2(1300, 0.1);
  869. /**
  870. * Given the control points, solve for x based on a given t for a cubic bezier curve.
  871. * @param t - a value between 0 and 1.
  872. * @param p0 - first control point.
  873. * @param p1 - second control point.
  874. * @param p2 - third control point.
  875. * @param p3 - fourth control point.
  876. * @returns - number result of cubic bezier curve at the specified t.
  877. */
  878. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  879. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  880. 3 * (1 - t) * (1 - t) * t * p1 +
  881. 3 * (1 - t) * t * t * p2 +
  882. t * t * t * p3);
  883. }
  884. /**
  885. * Evaluates a specified specular power value to determine the appropriate roughness value,
  886. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  887. * and roughness on the ordinant axis (y-axis).
  888. * @param specularPower - specular power of standard material.
  889. * @returns - Number representing the roughness value.
  890. */
  891. function _solveForRoughness(specularPower) {
  892. var t = Math.pow(specularPower / P3.x, 0.333333);
  893. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  894. }
  895. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  896. var opacity = babylonStandardMaterial.alpha;
  897. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this._maxSpecularPower);
  898. var roughness = _solveForRoughness(specularPower);
  899. var glTFPbrMetallicRoughness = {
  900. baseColorFactor: [
  901. diffuse.r,
  902. diffuse.g,
  903. diffuse.b,
  904. opacity
  905. ],
  906. metallicFactor: 0,
  907. roughnessFactor: roughness,
  908. };
  909. return glTFPbrMetallicRoughness;
  910. };
  911. /**
  912. * Computes the metallic factor
  913. * @param diffuse - diffused value
  914. * @param specular - specular value
  915. * @param oneMinusSpecularStrength - one minus the specular strength
  916. * @returns - metallic value
  917. */
  918. _GLTFMaterial._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  919. if (specular < _GLTFMaterial._dielectricSpecular.r) {
  920. _GLTFMaterial._dielectricSpecular;
  921. return 0;
  922. }
  923. var a = _GLTFMaterial._dielectricSpecular.r;
  924. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial._dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial._dielectricSpecular.r;
  925. var c = _GLTFMaterial._dielectricSpecular.r - specular;
  926. var D = b * b - 4.0 * a * c;
  927. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  928. };
  929. /**
  930. * Gets the glTF alpha mode from the Babylon Material
  931. * @param babylonMaterial - Babylon Material
  932. * @returns - The Babylon alpha mode value
  933. */
  934. _GLTFMaterial._GetAlphaMode = function (babylonMaterial) {
  935. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  936. var babylonStandardMaterial = babylonMaterial;
  937. if ((babylonStandardMaterial.alpha != 1.0) ||
  938. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  939. (babylonStandardMaterial.opacityTexture != null)) {
  940. return "BLEND" /* BLEND */;
  941. }
  942. else {
  943. return "OPAQUE" /* OPAQUE */;
  944. }
  945. }
  946. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  947. var babylonPBRMetallicRoughness = babylonMaterial;
  948. switch (babylonPBRMetallicRoughness.transparencyMode) {
  949. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  950. return "OPAQUE" /* OPAQUE */;
  951. }
  952. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  953. return "BLEND" /* BLEND */;
  954. }
  955. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  956. return "MASK" /* MASK */;
  957. }
  958. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  959. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  960. return "BLEND" /* BLEND */;
  961. }
  962. default: {
  963. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  964. }
  965. }
  966. }
  967. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  968. var babylonPBRMaterial = babylonMaterial;
  969. switch (babylonPBRMaterial.transparencyMode) {
  970. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  971. return "OPAQUE" /* OPAQUE */;
  972. }
  973. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  974. return "BLEND" /* BLEND */;
  975. }
  976. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  977. return "MASK" /* MASK */;
  978. }
  979. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  980. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  981. return "BLEND" /* BLEND */;
  982. }
  983. default: {
  984. throw new Error("Unsupported alpha mode " + babylonPBRMaterial.transparencyMode);
  985. }
  986. }
  987. }
  988. else {
  989. throw new Error("Unsupported Babylon material type");
  990. }
  991. };
  992. /**
  993. * Converts a Babylon Standard Material to a glTF Material.
  994. * @param babylonStandardMaterial - BJS Standard Material.
  995. * @param mimeType - mime type to use for the textures.
  996. * @param images - array of glTF image interfaces.
  997. * @param textures - array of glTF texture interfaces.
  998. * @param materials - array of glTF material interfaces.
  999. * @param imageData - map of image file name to data.
  1000. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1001. */
  1002. _GLTFMaterial._ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1003. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Standard Material is currently not fully supported/implemented in glTF serializer");
  1004. var glTFPbrMetallicRoughness = _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1005. var glTFMaterial = { name: babylonStandardMaterial.name };
  1006. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1007. if (!babylonStandardMaterial.twoSidedLighting) {
  1008. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1009. }
  1010. glTFMaterial.doubleSided = true;
  1011. }
  1012. if (hasTextureCoords) {
  1013. if (babylonStandardMaterial.diffuseTexture) {
  1014. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
  1015. if (glTFTexture != null) {
  1016. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1017. }
  1018. }
  1019. if (babylonStandardMaterial.bumpTexture) {
  1020. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
  1021. if (glTFTexture) {
  1022. glTFMaterial.normalTexture = glTFTexture;
  1023. }
  1024. }
  1025. if (babylonStandardMaterial.emissiveTexture) {
  1026. var glTFEmissiveTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1027. if (glTFEmissiveTexture) {
  1028. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1029. }
  1030. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1031. }
  1032. if (babylonStandardMaterial.ambientTexture) {
  1033. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
  1034. if (glTFTexture) {
  1035. var occlusionTexture = {
  1036. index: glTFTexture.index
  1037. };
  1038. glTFMaterial.occlusionTexture = occlusionTexture;
  1039. occlusionTexture.strength = 1.0;
  1040. }
  1041. }
  1042. }
  1043. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1044. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1045. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1046. }
  1047. else {
  1048. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1049. }
  1050. }
  1051. if (babylonStandardMaterial.emissiveColor && !this.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1052. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1053. }
  1054. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1055. materials.push(glTFMaterial);
  1056. };
  1057. /**
  1058. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1059. * @param babylonPBRMetalRoughMaterial - BJS PBR Metallic Roughness Material.
  1060. * @param mimeType - mime type to use for the textures.
  1061. * @param images - array of glTF image interfaces.
  1062. * @param textures - array of glTF texture interfaces.
  1063. * @param materials - array of glTF material interfaces.
  1064. * @param imageData - map of image file name to data.
  1065. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1066. */
  1067. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1068. var glTFPbrMetallicRoughness = {};
  1069. if (babylonPBRMetalRoughMaterial.baseColor) {
  1070. glTFPbrMetallicRoughness.baseColorFactor = [
  1071. babylonPBRMetalRoughMaterial.baseColor.r,
  1072. babylonPBRMetalRoughMaterial.baseColor.g,
  1073. babylonPBRMetalRoughMaterial.baseColor.b,
  1074. babylonPBRMetalRoughMaterial.alpha
  1075. ];
  1076. }
  1077. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1078. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1079. }
  1080. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1081. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1082. }
  1083. var glTFMaterial = {
  1084. name: babylonPBRMetalRoughMaterial.name
  1085. };
  1086. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1087. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1088. }
  1089. if (hasTextureCoords) {
  1090. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1091. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
  1092. if (glTFTexture != null) {
  1093. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1094. }
  1095. }
  1096. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1097. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
  1098. if (glTFTexture) {
  1099. glTFMaterial.normalTexture = glTFTexture;
  1100. }
  1101. }
  1102. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1103. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
  1104. if (glTFTexture) {
  1105. glTFMaterial.occlusionTexture = glTFTexture;
  1106. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1107. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1108. }
  1109. }
  1110. }
  1111. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1112. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1113. if (glTFTexture != null) {
  1114. glTFMaterial.emissiveTexture = glTFTexture;
  1115. }
  1116. }
  1117. }
  1118. if (this.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1119. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1120. }
  1121. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1122. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMetalRoughMaterial);
  1123. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1124. glTFMaterial.alphaMode = alphaMode;
  1125. if (alphaMode === "BLEND" /* BLEND */) {
  1126. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1127. }
  1128. }
  1129. }
  1130. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1131. materials.push(glTFMaterial);
  1132. };
  1133. /**
  1134. * Converts an image typed array buffer to a base64 image.
  1135. * @param buffer - typed array buffer.
  1136. * @param width - width of the image.
  1137. * @param height - height of the image.
  1138. * @param mimeType - mimetype of the image.
  1139. * @returns - base64 image string.
  1140. */
  1141. _GLTFMaterial._CreateBase64FromCanvas = function (buffer, width, height, mimeType) {
  1142. var imageCanvas = document.createElement('canvas');
  1143. imageCanvas.id = "WriteCanvas";
  1144. var ctx = imageCanvas.getContext('2d');
  1145. imageCanvas.width = width;
  1146. imageCanvas.height = height;
  1147. var imgData = ctx.createImageData(width, height);
  1148. imgData.data.set(buffer);
  1149. ctx.putImageData(imgData, 0, 0);
  1150. return imageCanvas.toDataURL(mimeType);
  1151. };
  1152. /**
  1153. * Generates a white texture based on the specified width and height.
  1154. * @param width - width of the texture in pixels.
  1155. * @param height - height of the texture in pixels.
  1156. * @param scene - babylonjs scene.
  1157. * @returns - white texture.
  1158. */
  1159. _GLTFMaterial._CreateWhiteTexture = function (width, height, scene) {
  1160. var data = new Uint8Array(width * height * 4);
  1161. for (var i = 0; i < data.length; ++i) {
  1162. data[i] = 255;
  1163. }
  1164. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1165. return rawTexture;
  1166. };
  1167. /**
  1168. * Resizes the two source textures to the same dimensions. If a texture is null, a default white texture is generated. If both textures are null, returns null.
  1169. * @param texture1 - first texture to resize.
  1170. * @param texture2 - second texture to resize.
  1171. * @param scene - babylonjs scene.
  1172. * @returns resized textures or null.
  1173. */
  1174. _GLTFMaterial._ResizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1175. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1176. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1177. var resizedTexture1;
  1178. var resizedTexture2;
  1179. if (texture1Size.width < texture2Size.width) {
  1180. if (texture1) {
  1181. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1182. }
  1183. else {
  1184. resizedTexture1 = this._CreateWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1185. }
  1186. resizedTexture2 = texture2;
  1187. }
  1188. else if (texture1Size.width > texture2Size.width) {
  1189. if (texture2) {
  1190. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1191. }
  1192. else {
  1193. resizedTexture2 = this._CreateWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1194. }
  1195. resizedTexture1 = texture1;
  1196. }
  1197. else {
  1198. resizedTexture1 = texture1;
  1199. resizedTexture2 = texture2;
  1200. }
  1201. return {
  1202. "texture1": resizedTexture1,
  1203. "texture2": resizedTexture2
  1204. };
  1205. };
  1206. /**
  1207. * Convert Specular Glossiness Textures to Metallic Roughness.
  1208. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1209. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1210. * @param diffuseTexture - texture used to store diffuse information.
  1211. * @param specularGlossinessTexture - texture used to store specular and glossiness information.
  1212. * @param factors - specular glossiness material factors.
  1213. * @param mimeType - the mime type to use for the texture.
  1214. * @returns pbr metallic roughness interface or null.
  1215. */
  1216. _GLTFMaterial._ConvertSpecularGlossinessTexturesToMetallicRoughness = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1217. if (!(diffuseTexture || specularGlossinessTexture)) {
  1218. return null;
  1219. }
  1220. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture.getScene();
  1221. if (!scene) {
  1222. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  1223. }
  1224. var resizedTextures = this._ResizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  1225. var diffuseSize = resizedTextures.texture1.getSize();
  1226. var diffuseBuffer;
  1227. var specularGlossinessBuffer;
  1228. var width = diffuseSize.width;
  1229. var height = diffuseSize.height;
  1230. var pixels = (resizedTextures.texture1.readPixels());
  1231. if (pixels instanceof Uint8Array) {
  1232. diffuseBuffer = (resizedTextures.texture1.readPixels());
  1233. }
  1234. else {
  1235. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture1.name);
  1236. }
  1237. pixels = resizedTextures.texture2.readPixels();
  1238. if (pixels instanceof Uint8Array) {
  1239. specularGlossinessBuffer = (resizedTextures.texture2.readPixels());
  1240. }
  1241. else {
  1242. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture2.name);
  1243. }
  1244. var byteLength = specularGlossinessBuffer.byteLength;
  1245. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  1246. var baseColorBuffer = new Uint8Array(byteLength);
  1247. var strideSize = 4;
  1248. var maxBaseColor = BABYLON.Color3.Black();
  1249. var maxMetallic = 0;
  1250. var maxRoughness = 0;
  1251. for (var h = 0; h < height; ++h) {
  1252. for (var w = 0; w < width; ++w) {
  1253. var offset = (width * h + w) * strideSize;
  1254. var diffuseColor = BABYLON.Color3.FromInts(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  1255. var specularColor = BABYLON.Color3.FromInts(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  1256. var glossiness = (specularGlossinessBuffer[offset + 3] / 255) * factors.glossiness;
  1257. var specularGlossiness = {
  1258. diffuseColor: diffuseColor,
  1259. specularColor: specularColor,
  1260. glossiness: glossiness
  1261. };
  1262. var metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  1263. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  1264. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  1265. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  1266. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  1267. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  1268. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  1269. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  1270. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  1271. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] : 255;
  1272. metallicRoughnessBuffer[offset] = 0;
  1273. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  1274. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  1275. metallicRoughnessBuffer[offset + 3] = 255;
  1276. }
  1277. }
  1278. // Retrieves the metallic roughness factors from the maximum texture values.
  1279. var metallicRoughnessFactors = {
  1280. baseColor: maxBaseColor,
  1281. metallic: maxMetallic,
  1282. roughness: maxRoughness
  1283. };
  1284. var writeOutMetallicRoughnessTexture = false;
  1285. var writeOutBaseColorTexture = false;
  1286. for (var h = 0; h < height; ++h) {
  1287. for (var w = 0; w < width; ++w) {
  1288. var destinationOffset = (width * h + w) * strideSize;
  1289. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors.baseColor.r > this._epsilon ? metallicRoughnessFactors.baseColor.r : 1;
  1290. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors.baseColor.g > this._epsilon ? metallicRoughnessFactors.baseColor.g : 1;
  1291. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors.baseColor.b > this._epsilon ? metallicRoughnessFactors.baseColor.b : 1;
  1292. var linearBaseColorPixel = BABYLON.Color3.FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  1293. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  1294. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  1295. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  1296. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  1297. if (!this.FuzzyEquals(sRGBBaseColorPixel, BABYLON.Color3.White(), this._epsilon)) {
  1298. writeOutBaseColorTexture = true;
  1299. }
  1300. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors.roughness > this._epsilon ? metallicRoughnessFactors.roughness : 1;
  1301. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors.metallic > this._epsilon ? metallicRoughnessFactors.metallic : 1;
  1302. var metallicRoughnessPixel = BABYLON.Color3.FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  1303. if (!this.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), this._epsilon)) {
  1304. writeOutMetallicRoughnessTexture = true;
  1305. }
  1306. }
  1307. }
  1308. if (writeOutMetallicRoughnessTexture) {
  1309. var metallicRoughnessBase64 = this._CreateBase64FromCanvas(metallicRoughnessBuffer, width, height, mimeType);
  1310. metallicRoughnessFactors.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  1311. }
  1312. if (writeOutBaseColorTexture) {
  1313. var baseColorBase64 = this._CreateBase64FromCanvas(baseColorBuffer, width, height, mimeType);
  1314. metallicRoughnessFactors.baseColorTextureBase64 = baseColorBase64;
  1315. }
  1316. return metallicRoughnessFactors;
  1317. };
  1318. /**
  1319. * Converts specular glossiness material properties to metallic roughness.
  1320. * @param specularGlossiness - interface with specular glossiness material properties.
  1321. * @returns - interface with metallic roughness material properties.
  1322. */
  1323. _GLTFMaterial._ConvertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  1324. var diffusePerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.diffuseColor);
  1325. var specularPerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.specularColor);
  1326. var oneMinusSpecularStrength = 1 - _GLTFMaterial._GetMaxComponent(specularGlossiness.specularColor);
  1327. var metallic = _GLTFMaterial._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1328. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - this._dielectricSpecular.r) / Math.max(1 - metallic, this._epsilon));
  1329. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(this._dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this._epsilon));
  1330. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1331. baseColor = baseColor.clampToRef(0, 1, baseColor);
  1332. var metallicRoughness = {
  1333. baseColor: baseColor,
  1334. metallic: metallic,
  1335. roughness: 1 - specularGlossiness.glossiness
  1336. };
  1337. return metallicRoughness;
  1338. };
  1339. /**
  1340. * Calculates the surface reflectance, independent of lighting conditions.
  1341. * @param color - Color source to calculate brightness from.
  1342. * @returns number representing the perceived brightness, or zero if color is undefined.
  1343. */
  1344. _GLTFMaterial._GetPerceivedBrightness = function (color) {
  1345. if (color) {
  1346. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1347. }
  1348. return 0;
  1349. };
  1350. /**
  1351. * Returns the maximum color component value.
  1352. * @param color
  1353. * @returns maximum color component value, or zero if color is null or undefined.
  1354. */
  1355. _GLTFMaterial._GetMaxComponent = function (color) {
  1356. if (color) {
  1357. return Math.max(color.r, Math.max(color.g, color.b));
  1358. }
  1359. return 0;
  1360. };
  1361. /**
  1362. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors.
  1363. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1364. * @param mimeType - mime type to use for the textures.
  1365. * @param images - array of glTF image interfaces.
  1366. * @param textures - array of glTF texture interfaces.
  1367. * @param glTFPbrMetallicRoughness - glTF PBR Metallic Roughness interface.
  1368. * @param imageData - map of image file name to data.
  1369. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1370. * @returns - glTF PBR Metallic Roughness factors.
  1371. */
  1372. _GLTFMaterial._ConvertMetalRoughFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1373. var metallicRoughness = {
  1374. baseColor: babylonPBRMaterial.albedoColor,
  1375. metallic: babylonPBRMaterial.metallic,
  1376. roughness: babylonPBRMaterial.roughness
  1377. };
  1378. if (hasTextureCoords) {
  1379. if (babylonPBRMaterial.albedoTexture) {
  1380. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.albedoTexture, mimeType, images, textures, imageData);
  1381. if (glTFTexture) {
  1382. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1383. }
  1384. }
  1385. if (babylonPBRMaterial.metallicTexture) {
  1386. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.metallicTexture, mimeType, images, textures, imageData);
  1387. if (glTFTexture != null) {
  1388. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  1389. }
  1390. }
  1391. }
  1392. return metallicRoughness;
  1393. };
  1394. /**
  1395. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors.
  1396. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1397. * @param mimeType - mime type to use for the textures.
  1398. * @param images - array of glTF image interfaces.
  1399. * @param textures - array of glTF texture interfaces.
  1400. * @param glTFPbrMetallicRoughness - glTF PBR Metallic Roughness interface.
  1401. * @param imageData - map of image file name to data.
  1402. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1403. * @returns - glTF PBR Metallic Roughness factors.
  1404. */
  1405. _GLTFMaterial._ConvertSpecGlossFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1406. var specGloss = {
  1407. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  1408. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  1409. glossiness: babylonPBRMaterial.microSurface || 1,
  1410. };
  1411. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  1412. throw new Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture currently not supported");
  1413. }
  1414. var metallicRoughnessFactors = this._ConvertSpecularGlossinessTexturesToMetallicRoughness(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType);
  1415. if (!metallicRoughnessFactors) {
  1416. metallicRoughnessFactors = this._ConvertSpecularGlossinessToMetallicRoughness(specGloss);
  1417. }
  1418. else {
  1419. if (hasTextureCoords) {
  1420. if (metallicRoughnessFactors.baseColorTextureBase64) {
  1421. var glTFBaseColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1422. if (glTFBaseColorTexture != null) {
  1423. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  1424. }
  1425. }
  1426. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  1427. var glTFMRColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1428. if (glTFMRColorTexture != null) {
  1429. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  1430. }
  1431. }
  1432. }
  1433. }
  1434. return metallicRoughnessFactors;
  1435. };
  1436. /**
  1437. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1438. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1439. * @param mimeType - mime type to use for the textures.
  1440. * @param images - array of glTF image interfaces.
  1441. * @param textures - array of glTF texture interfaces.
  1442. * @param materials - array of glTF material interfaces.
  1443. * @param imageData - map of image file name to data.
  1444. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1445. */
  1446. _GLTFMaterial._ConvertPBRMaterial = function (babylonPBRMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1447. var glTFPbrMetallicRoughness = {};
  1448. var metallicRoughness;
  1449. var glTFMaterial = {
  1450. name: babylonPBRMaterial.name
  1451. };
  1452. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  1453. if (useMetallicRoughness) {
  1454. metallicRoughness = this._ConvertMetalRoughFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  1455. }
  1456. else {
  1457. metallicRoughness = this._ConvertSpecGlossFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  1458. }
  1459. if (!(this.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), this._epsilon) && babylonPBRMaterial.alpha >= this._epsilon)) {
  1460. glTFPbrMetallicRoughness.baseColorFactor = [
  1461. metallicRoughness.baseColor.r,
  1462. metallicRoughness.baseColor.g,
  1463. metallicRoughness.baseColor.b,
  1464. babylonPBRMaterial.alpha
  1465. ];
  1466. }
  1467. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  1468. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  1469. }
  1470. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  1471. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  1472. }
  1473. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  1474. if (!babylonPBRMaterial.twoSidedLighting) {
  1475. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1476. }
  1477. glTFMaterial.doubleSided = true;
  1478. }
  1479. if (hasTextureCoords) {
  1480. if (babylonPBRMaterial.bumpTexture) {
  1481. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.bumpTexture, mimeType, images, textures, imageData);
  1482. if (glTFTexture) {
  1483. glTFMaterial.normalTexture = glTFTexture;
  1484. }
  1485. }
  1486. if (babylonPBRMaterial.ambientTexture) {
  1487. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.ambientTexture, mimeType, images, textures, imageData);
  1488. if (glTFTexture) {
  1489. var occlusionTexture = {
  1490. index: glTFTexture.index
  1491. };
  1492. glTFMaterial.occlusionTexture = occlusionTexture;
  1493. if (babylonPBRMaterial.ambientTextureStrength) {
  1494. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  1495. }
  1496. }
  1497. }
  1498. if (babylonPBRMaterial.emissiveTexture) {
  1499. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1500. if (glTFTexture != null) {
  1501. glTFMaterial.emissiveTexture = glTFTexture;
  1502. }
  1503. }
  1504. }
  1505. if (!this.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1506. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  1507. }
  1508. if (babylonPBRMaterial.transparencyMode != null) {
  1509. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMaterial);
  1510. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1511. glTFMaterial.alphaMode = alphaMode;
  1512. if (alphaMode === "BLEND" /* BLEND */) {
  1513. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  1514. }
  1515. }
  1516. }
  1517. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1518. materials.push(glTFMaterial);
  1519. };
  1520. /**
  1521. * Extracts a texture from a Babylon texture into file data and glTF data.
  1522. * @param babylonTexture - Babylon texture to extract.
  1523. * @param mimeType - Mime Type of the babylonTexture.
  1524. * @param images - Array of glTF images.
  1525. * @param textures - Array of glTF textures.
  1526. * @param imageData - map of image file name and data.
  1527. * @return - glTF texture info, or null if the texture format is not supported.
  1528. */
  1529. _GLTFMaterial._ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
  1530. var textureName = "texture_" + (textures.length - 1).toString();
  1531. var textureData = babylonTexture.getInternalTexture();
  1532. if (textureData != null) {
  1533. textureName = textureData.url || textureName;
  1534. }
  1535. textureName = BABYLON.Tools.GetFilename(textureName);
  1536. var baseFile = textureName.split('.')[0];
  1537. var extension = "";
  1538. if (mimeType === "image/jpeg" /* JPEG */) {
  1539. extension = ".jpg";
  1540. }
  1541. else if (mimeType === "image/png" /* PNG */) {
  1542. extension = ".png";
  1543. }
  1544. else {
  1545. throw new Error("Unsupported mime type " + mimeType);
  1546. }
  1547. textureName = baseFile + extension;
  1548. var pixels = babylonTexture.readPixels();
  1549. var size = babylonTexture.getSize();
  1550. var base64Data = this._CreateBase64FromCanvas(pixels, size.width, size.height, mimeType);
  1551. return this._GetTextureInfoFromBase64(base64Data, textureName, mimeType, images, textures, imageData);
  1552. };
  1553. /**
  1554. * Builds a texture from base64 string.
  1555. * @param base64Texture - base64 texture string.
  1556. * @param textureName - Name to use for the texture.
  1557. * @param mimeType - image mime type for the texture.
  1558. * @param images - array of images.
  1559. * @param textures - array of textures.
  1560. * @param imageData - map of image data.
  1561. * @returns - glTF texture info, or null if the texture format is not supported.
  1562. */
  1563. _GLTFMaterial._GetTextureInfoFromBase64 = function (base64Texture, textureName, mimeType, images, textures, imageData) {
  1564. var textureInfo = null;
  1565. var glTFTexture = {
  1566. source: images.length
  1567. };
  1568. var binStr = atob(base64Texture.split(',')[1]);
  1569. var arr = new Uint8Array(binStr.length);
  1570. for (var i = 0; i < binStr.length; ++i) {
  1571. arr[i] = binStr.charCodeAt(i);
  1572. }
  1573. var imageValues = { data: arr, mimeType: mimeType };
  1574. imageData[textureName] = imageValues;
  1575. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  1576. var glTFImage = {
  1577. uri: textureName
  1578. };
  1579. var foundIndex = -1;
  1580. for (var i = 0; i < images.length; ++i) {
  1581. if (images[i].uri === textureName) {
  1582. foundIndex = i;
  1583. break;
  1584. }
  1585. }
  1586. if (foundIndex === -1) {
  1587. images.push(glTFImage);
  1588. glTFTexture.source = images.length - 1;
  1589. textures.push({
  1590. source: images.length - 1
  1591. });
  1592. textureInfo = {
  1593. index: images.length - 1
  1594. };
  1595. }
  1596. else {
  1597. glTFTexture.source = foundIndex;
  1598. textureInfo = {
  1599. index: foundIndex
  1600. };
  1601. }
  1602. }
  1603. return textureInfo;
  1604. };
  1605. /**
  1606. * Represents the dielectric specular values for R, G and B.
  1607. */
  1608. _GLTFMaterial._dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1609. /**
  1610. * Allows the maximum specular power to be defined for material calculations.
  1611. */
  1612. _GLTFMaterial._maxSpecularPower = 1024;
  1613. /**
  1614. * Numeric tolerance value
  1615. */
  1616. _GLTFMaterial._epsilon = 1e-6;
  1617. return _GLTFMaterial;
  1618. }());
  1619. GLTF2._GLTFMaterial = _GLTFMaterial;
  1620. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1621. })(BABYLON || (BABYLON = {}));
  1622. //# sourceMappingURL=babylon.glTFMaterial.js.map