babylon.glTF2Serializer.js 92 KB

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