123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314 |
- var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
- var babylonDependency = (globalObject && globalObject.BABYLON) || BABYLON || (typeof require !== 'undefined' && require("babylonjs"));
- var BABYLON = babylonDependency;
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
-
- var BABYLON;
- (function (BABYLON) {
- var OBJExport = /** @class */ (function () {
- function OBJExport() {
- }
- //Exports the geometrys of a Mesh array in .OBJ file format (text)
- OBJExport.OBJ = function (mesh, materials, matlibname, globalposition) {
- var output = [];
- var v = 1;
- if (materials) {
- if (!matlibname) {
- matlibname = 'mat';
- }
- output.push("mtllib " + matlibname + ".mtl");
- }
- for (var j = 0; j < mesh.length; j++) {
- output.push("g object" + j);
- output.push("o object_" + j);
- //Uses the position of the item in the scene, to the file (this back to normal in the end)
- var lastMatrix = null;
- if (globalposition) {
- var newMatrix = BABYLON.Matrix.Translation(mesh[j].position.x, mesh[j].position.y, mesh[j].position.z);
- lastMatrix = BABYLON.Matrix.Translation(-(mesh[j].position.x), -(mesh[j].position.y), -(mesh[j].position.z));
- mesh[j].bakeTransformIntoVertices(newMatrix);
- }
- //TODO: submeshes (groups)
- //TODO: smoothing groups (s 1, s off);
- if (materials) {
- var mat = mesh[j].material;
- if (mat) {
- output.push("usemtl " + mat.id);
- }
- }
- var g = mesh[j].geometry;
- if (!g) {
- continue;
- }
- var trunkVerts = g.getVerticesData('position');
- var trunkNormals = g.getVerticesData('normal');
- var trunkUV = g.getVerticesData('uv');
- var trunkFaces = g.getIndices();
- var curV = 0;
- if (!trunkVerts || !trunkNormals || !trunkUV || !trunkFaces) {
- continue;
- }
- for (var i = 0; i < trunkVerts.length; i += 3) {
- output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]);
- curV++;
- }
- for (i = 0; i < trunkNormals.length; i += 3) {
- output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]);
- }
- for (i = 0; i < trunkUV.length; i += 2) {
- output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]);
- }
- for (i = 0; i < trunkFaces.length; i += 3) {
- output.push("f " + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) +
- " " + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) +
- " " + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v));
- }
- //back de previous matrix, to not change the original mesh in the scene
- if (globalposition && lastMatrix) {
- mesh[j].bakeTransformIntoVertices(lastMatrix);
- }
- v += curV;
- }
- var text = output.join("\n");
- return (text);
- };
- //Exports the material(s) of a mesh in .MTL file format (text)
- //TODO: Export the materials of mesh array
- OBJExport.MTL = function (mesh) {
- var output = [];
- var m = mesh.material;
- output.push("newmtl mat1");
- output.push(" Ns " + m.specularPower.toFixed(4));
- output.push(" Ni 1.5000");
- output.push(" d " + m.alpha.toFixed(4));
- output.push(" Tr 0.0000");
- output.push(" Tf 1.0000 1.0000 1.0000");
- output.push(" illum 2");
- output.push(" Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4));
- output.push(" Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4));
- output.push(" Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4));
- output.push(" Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4));
- //TODO: uv scale, offset, wrap
- //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures?
- var uvscale = "";
- if (m.ambientTexture) {
- output.push(" map_Ka " + uvscale + m.ambientTexture.name);
- }
- if (m.diffuseTexture) {
- output.push(" map_Kd " + uvscale + m.diffuseTexture.name);
- //TODO: alpha testing, opacity in diffuse texture alpha channel (diffuseTexture.hasAlpha -> map_d)
- }
- if (m.specularTexture) {
- output.push(" map_Ks " + uvscale + m.specularTexture.name);
- /* TODO: glossiness = specular highlight component is in alpha channel of specularTexture. (???)
- if (m.useGlossinessFromSpecularMapAlpha) {
- output.push(" map_Ns "+uvscale + m.specularTexture.name);
- }
- */
- }
- /* TODO: emissive texture not in .MAT format (???)
- if (m.emissiveTexture) {
- output.push(" map_d "+uvscale+m.emissiveTexture.name);
- }
- */
- if (m.bumpTexture) {
- output.push(" map_bump -imfchan z " + uvscale + m.bumpTexture.name);
- }
- if (m.opacityTexture) {
- output.push(" map_d " + uvscale + m.opacityTexture.name);
- }
- var text = output.join("\n");
- return (text);
- };
- return OBJExport;
- }());
- BABYLON.OBJExport = OBJExport;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.objSerializer.js.map
- var BABYLON;
- (function (BABYLON) {
- ;
- /**
- * Class for generating glTF data from a Babylon scene.
- */
- var GLTF2Export = /** @class */ (function () {
- function GLTF2Export() {
- }
- /**
- * Exports the geometry of the scene to .gltf file format.
- * @param scene - Babylon scene with scene hierarchy information.
- * @param filePrefix - File prefix to use when generating the glTF file.
- * @param options - Exporter options.
- * @returns - Returns an object with a .gltf file and associates texture names
- * as keys and their data and paths as values.
- */
- GLTF2Export.GLTF = function (scene, filePrefix, options) {
- var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
- var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
- if (scene.isReady) {
- return gltfGenerator._generateGLTF(glTFPrefix);
- }
- else {
- throw new Error("glTF Serializer: Scene is not ready!");
- }
- };
- /**
- * Exports the geometry of the scene to .glb file format.
- * @param scene - Babylon scene with scene hierarchy information.
- * @param filePrefix - File prefix to use when generating glb file.
- * @param options - Exporter options.
- * @returns - Returns an object with a .glb filename as key and data as value
- */
- GLTF2Export.GLB = function (scene, filePrefix, options) {
- var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
- var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
- if (scene.isReady) {
- return gltfGenerator._generateGLB(glTFPrefix);
- }
- else {
- throw new Error("glTF Serializer: Scene is not ready!");
- }
- };
- return GLTF2Export;
- }());
- BABYLON.GLTF2Export = GLTF2Export;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.glTFSerializer.js.map
- /**
- * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally.
- * @ignore - capitalization of GLTF2 module.
- */
- var BABYLON;
- (function (BABYLON) {
- var GLTF2;
- (function (GLTF2) {
- /**
- * Converts Babylon Scene into glTF 2.0.
- */
- var _Exporter = /** @class */ (function () {
- /**
- * Creates a glTF Exporter instance, which can accept optional exporter options.
- * @param babylonScene - Babylon scene object
- * @param options - Options to modify the behavior of the exporter.
- */
- function _Exporter(babylonScene, options) {
- this.asset = { generator: "BabylonJS", version: "2.0" };
- this.babylonScene = babylonScene;
- this.bufferViews = new Array();
- this.accessors = new Array();
- this.meshes = new Array();
- this.scenes = new Array();
- this.nodes = new Array();
- this.images = new Array();
- this.materials = new Array();
- this.textures = new Array();
- this.imageData = {};
- this.convertToRightHandedSystem = !this.babylonScene.useRightHandedSystem;
- if (options) {
- this.options = options;
- }
- }
- /**
- * Creates a buffer view based on teh supplied arguments
- * @param bufferIndex - index value of the specified buffer
- * @param byteOffset - byte offset value
- * @param byteLength - byte length of the bufferView
- * @param byteStride - byte distance between conequential elements.
- * @param name - name of the buffer view
- * @returns - bufferView for glTF
- */
- _Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
- var bufferview = { buffer: bufferIndex, byteLength: byteLength };
- if (byteOffset) {
- bufferview.byteOffset = byteOffset;
- }
- if (name) {
- bufferview.name = name;
- }
- if (byteStride) {
- bufferview.byteStride = byteStride;
- }
- return bufferview;
- };
- /**
- * Creates an accessor based on the supplied arguments
- * @param bufferviewIndex - The index of the bufferview referenced by this accessor.
- * @param name - The name of the accessor.
- * @param type - The type of the accessor.
- * @param componentType - The datatype of components in the attribute.
- * @param count - The number of attributes referenced by this accessor.
- * @param byteOffset - The offset relative to the start of the bufferView in bytes.
- * @param min - Minimum value of each component in this attribute.
- * @param max - Maximum value of each component in this attribute.
- * @returns - accessor for glTF
- */
- _Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
- var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
- if (min) {
- accessor.min = min;
- }
- if (max) {
- accessor.max = max;
- }
- if (byteOffset) {
- accessor.byteOffset = byteOffset;
- }
- return accessor;
- };
- /**
- * Calculates the minimum and maximum values of an array of position floats.
- * @param positions - Positions array of a mesh.
- * @param vertexStart - Starting vertex offset to calculate min and max values.
- * @param vertexCount - Number of vertices to check for min and max values.
- * @returns - min number array and max number array.
- */
- _Exporter.prototype.calculateMinMaxPositions = function (positions, vertexStart, vertexCount) {
- var min = [Infinity, Infinity, Infinity];
- var max = [-Infinity, -Infinity, -Infinity];
- var positionStrideSize = 3;
- var end = vertexStart + vertexCount;
- if (vertexCount) {
- for (var i = vertexStart; i < end; ++i) {
- var indexOffset = positionStrideSize * i;
- var position = BABYLON.Vector3.FromArray(positions, indexOffset);
- var vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(position).asArray() : position.asArray();
- for (var j = 0; j < positionStrideSize; ++j) {
- var num = vector[j];
- if (num < min[j]) {
- min[j] = num;
- }
- if (num > max[j]) {
- max[j] = num;
- }
- ++indexOffset;
- }
- }
- }
- return { min: min, max: max };
- };
- /**
- * Converts a vector3 array to right-handed.
- * @param vector - vector3 Array to convert to right-handed.
- * @returns - right-handed Vector3 array.
- */
- _Exporter.GetRightHandedVector3 = function (vector) {
- return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
- };
- /**
- * Converts a vector4 array to right-handed.
- * @param vector - vector4 Array to convert to right-handed.
- * @returns - right-handed vector4 array.
- */
- _Exporter.GetRightHandedVector4 = function (vector) {
- return new BABYLON.Vector4(vector.x, vector.y, -vector.z, -vector.w);
- };
- /**
- * Converts a quaternion to right-handed.
- * @param quaternion - Source quaternion to convert to right-handed.
- */
- _Exporter.GetRightHandedQuaternion = function (quaternion) {
- return new BABYLON.Quaternion(-quaternion.x, -quaternion.y, quaternion.z, quaternion.w);
- };
- /**
- * Writes mesh attribute data to a data buffer.
- * Returns the bytelength of the data.
- * @param vertexBufferKind - Indicates what kind of vertex data is being passed in.
- * @param meshAttributeArray - Array containing the attribute data.
- * @param strideSize - Represents the offset between consecutive attributes
- * @param byteOffset - The offset to start counting bytes from.
- * @param dataBuffer - The buffer to write the binary data to.
- * @returns - Byte length of the attribute data.
- */
- _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, strideSize, vertexBufferOffset, byteOffset, dataBuffer) {
- var byteOff = byteOffset;
- var end = meshAttributeArray.length / strideSize;
- var byteLength = 0;
- for (var k = 0; k < end; ++k) {
- var index = k * strideSize;
- var vector = [];
- if (vertexBufferKind === BABYLON.VertexBuffer.PositionKind || vertexBufferKind === BABYLON.VertexBuffer.NormalKind) {
- var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
- vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(vertexData).asArray() : vertexData.asArray();
- }
- else if (vertexBufferKind === BABYLON.VertexBuffer.TangentKind || vertexBufferKind === BABYLON.VertexBuffer.ColorKind) {
- var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
- vector = (this.convertToRightHandedSystem && !(vertexBufferKind === BABYLON.VertexBuffer.ColorKind)) ? _Exporter.GetRightHandedVector4(vertexData).asArray() : vertexData.asArray();
- }
- else if (vertexBufferKind === BABYLON.VertexBuffer.UVKind || vertexBufferKind === BABYLON.VertexBuffer.UV2Kind) {
- vector = [meshAttributeArray[index], meshAttributeArray[index + 1]];
- }
- else {
- BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
- }
- for (var i = 0; i < vector.length; ++i) {
- dataBuffer.setFloat32(byteOff, vector[i], true);
- byteOff += 4;
- }
- }
- byteLength = meshAttributeArray.length * 4;
- return byteLength;
- };
- /**
- * Generates glTF json data
- * @param shouldUseGlb - Indicates whether the json should be written for a glb file.
- * @param glTFPrefix - Text to use when prefixing a glTF file.
- * @param prettyPrint - Indicates whether the json file should be pretty printed (true) or not (false).
- * @returns - json data as string
- */
- _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
- var buffer = { byteLength: this.totalByteLength };
- var glTF = {
- asset: this.asset
- };
- if (buffer.byteLength) {
- glTF.buffers = [buffer];
- }
- if (this.nodes && this.nodes.length) {
- glTF.nodes = this.nodes;
- }
- if (this.meshes && this.meshes.length) {
- glTF.meshes = this.meshes;
- }
- if (this.scenes && this.scenes.length) {
- glTF.scenes = this.scenes;
- glTF.scene = 0;
- }
- if (this.bufferViews && this.bufferViews.length) {
- glTF.bufferViews = this.bufferViews;
- }
- if (this.accessors && this.accessors.length) {
- glTF.accessors = this.accessors;
- }
- if (this.materials && this.materials.length) {
- glTF.materials = this.materials;
- }
- if (this.textures && this.textures.length) {
- glTF.textures = this.textures;
- }
- if (this.images && this.images.length) {
- if (!shouldUseGlb) {
- glTF.images = this.images;
- }
- else {
- glTF.images = [];
- // Replace uri with bufferview and mime type for glb
- var imageLength = this.images.length;
- var byteOffset = this.totalByteLength;
- for (var i = 0; i < imageLength; ++i) {
- var image = this.images[i];
- if (image.uri) {
- var imageData = this.imageData[image.uri];
- var imageName = image.uri.split('.')[0] + " image";
- var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
- byteOffset += imageData.data.buffer.byteLength;
- this.bufferViews.push(bufferView);
- image.bufferView = this.bufferViews.length - 1;
- image.name = imageName;
- image.mimeType = imageData.mimeType;
- image.uri = undefined;
- glTF.images.push(image);
- }
- }
- buffer.byteLength = byteOffset;
- }
- }
- if (!shouldUseGlb) {
- buffer.uri = glTFPrefix + ".bin";
- }
- var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
- return jsonText;
- };
- /**
- * Generates data for .gltf and .bin files based on the glTF prefix string
- * @param glTFPrefix - Text to use when prefixing a glTF file.
- * @returns - GLTFData with glTF file data.
- */
- _Exporter.prototype._generateGLTF = function (glTFPrefix) {
- var binaryBuffer = this.generateBinary();
- var jsonText = this.generateJSON(false, glTFPrefix, true);
- var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
- var glTFFileName = glTFPrefix + '.gltf';
- var glTFBinFile = glTFPrefix + '.bin';
- var container = new BABYLON._GLTFData();
- container.glTFFiles[glTFFileName] = jsonText;
- container.glTFFiles[glTFBinFile] = bin;
- if (this.imageData) {
- for (var image in this.imageData) {
- container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
- }
- }
- return container;
- };
- /**
- * Creates a binary buffer for glTF
- * @returns - array buffer for binary data
- */
- _Exporter.prototype.generateBinary = function () {
- var byteOffset = 0;
- byteOffset = this.createScene(this.babylonScene, byteOffset);
- return this.binaryBuffer;
- };
- /**
- * Pads the number to a multiple of 4
- * @param num - number to pad
- * @returns - padded number
- */
- _Exporter.prototype._getPadding = function (num) {
- var remainder = num % 4;
- var padding = remainder === 0 ? remainder : 4 - remainder;
- return padding;
- };
- /**
- * Generates a glb file from the json and binary data.
- * Returns an object with the glb file name as the key and data as the value.
- * @param glTFPrefix
- * @returns - object with glb filename as key and data as value
- */
- _Exporter.prototype._generateGLB = function (glTFPrefix) {
- var binaryBuffer = this.generateBinary();
- var jsonText = this.generateJSON(true);
- var glbFileName = glTFPrefix + '.glb';
- var headerLength = 12;
- var chunkLengthPrefix = 8;
- var jsonLength = jsonText.length;
- var imageByteLength = 0;
- for (var key in this.imageData) {
- imageByteLength += this.imageData[key].data.byteLength;
- }
- var jsonPadding = this._getPadding(jsonLength);
- var binPadding = this._getPadding(binaryBuffer.byteLength);
- var imagePadding = this._getPadding(imageByteLength);
- var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
- //header
- var headerBuffer = new ArrayBuffer(headerLength);
- var headerBufferView = new DataView(headerBuffer);
- headerBufferView.setUint32(0, 0x46546C67, true); //glTF
- headerBufferView.setUint32(4, 2, true); // version
- headerBufferView.setUint32(8, byteLength, true); // total bytes in file
- //json chunk
- var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
- var jsonChunkBufferView = new DataView(jsonChunkBuffer);
- jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
- jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
- //json chunk bytes
- var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
- for (var i = 0; i < jsonLength; ++i) {
- jsonData[i] = jsonText.charCodeAt(i);
- }
- //json padding
- var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
- for (var i = 0; i < jsonPadding; ++i) {
- jsonPaddingView[i] = 0x20;
- }
- //binary chunk
- var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
- var binaryChunkBufferView = new DataView(binaryChunkBuffer);
- binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
- binaryChunkBufferView.setUint32(4, 0x004E4942, true);
- // binary padding
- var binPaddingBuffer = new ArrayBuffer(binPadding);
- var binPaddingView = new Uint8Array(binPaddingBuffer);
- for (var i = 0; i < binPadding; ++i) {
- binPaddingView[i] = 0;
- }
- var imagePaddingBuffer = new ArrayBuffer(imagePadding);
- var imagePaddingView = new Uint8Array(imagePaddingBuffer);
- for (var i = 0; i < imagePadding; ++i) {
- imagePaddingView[i] = 0;
- }
- var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
- // binary data
- for (var key in this.imageData) {
- glbData.push(this.imageData[key].data.buffer);
- }
- glbData.push(binPaddingBuffer);
- glbData.push(imagePaddingBuffer);
- var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
- var container = new BABYLON._GLTFData();
- container.glTFFiles[glbFileName] = glbFile;
- return container;
- };
- /**
- * Sets the TRS for each node
- * @param node - glTF Node for storing the transformation data.
- * @param babylonMesh - Babylon mesh used as the source for the transformation data.
- */
- _Exporter.prototype.setNodeTransformation = function (node, babylonMesh) {
- if (!(babylonMesh.position.x === 0 && babylonMesh.position.y === 0 && babylonMesh.position.z === 0)) {
- node.translation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(babylonMesh.position).asArray() : babylonMesh.position.asArray();
- }
- if (!(babylonMesh.scaling.x === 1 && babylonMesh.scaling.y === 1 && babylonMesh.scaling.z === 1)) {
- node.scale = babylonMesh.scaling.asArray();
- }
- var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
- if (babylonMesh.rotationQuaternion) {
- rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
- }
- if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
- node.rotation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedQuaternion(rotationQuaternion).asArray() : rotationQuaternion.asArray();
- }
- };
- /**
- * Creates a bufferview based on the vertices type for the Babylon mesh
- * @param kind - Indicates the type of vertices data.
- * @param babylonMesh - The Babylon mesh to get the vertices data from.
- * @param byteOffset - The offset from the buffer to start indexing from.
- * @param dataBuffer - The buffer to write the bufferview data to.
- * @returns bytelength of the bufferview data.
- */
- _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, byteOffset, dataBuffer) {
- var bufferMesh = null;
- var byteLength = 0;
- if (babylonMesh instanceof BABYLON.Mesh) {
- bufferMesh = babylonMesh;
- }
- else if (babylonMesh instanceof BABYLON.InstancedMesh) {
- bufferMesh = babylonMesh.sourceMesh;
- }
- if (bufferMesh) {
- var vertexBuffer = null;
- var vertexBufferOffset = null;
- var vertexData = null;
- var vertexStrideSize = null;
- if (bufferMesh.isVerticesDataPresent(kind)) {
- vertexBuffer = bufferMesh.getVertexBuffer(kind);
- if (vertexBuffer) {
- vertexBufferOffset = vertexBuffer.getOffset();
- vertexData = vertexBuffer.getData();
- if (vertexData) {
- vertexStrideSize = vertexBuffer.getStrideSize();
- if (dataBuffer && vertexData) {
- byteLength = this.writeAttributeData(kind, vertexData, vertexStrideSize, vertexBufferOffset, byteOffset, dataBuffer);
- byteOffset += byteLength;
- }
- else {
- byteLength = vertexData.length * 4;
- var bufferView = this.createBufferView(0, byteOffset, byteLength, vertexStrideSize * 4, kind + " - " + bufferMesh.name);
- byteOffset += byteLength;
- this.bufferViews.push(bufferView);
- }
- }
- }
- }
- }
- return byteLength;
- };
- /**
- * Sets data for the primitive attributes of each submesh
- * @param mesh - glTF Mesh object to store the primitive attribute information.
- * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
- * @param byteOffset - The offset in bytes of the buffer data.
- * @param dataBuffer - Buffer to write the attribute data to.
- * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
- */
- _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, dataBuffer) {
- var bufferMesh = null;
- if (babylonMesh instanceof BABYLON.Mesh) {
- bufferMesh = babylonMesh;
- }
- else if (babylonMesh instanceof BABYLON.InstancedMesh) {
- bufferMesh = babylonMesh.sourceMesh;
- }
- var attributeData = [
- { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */ },
- { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */ },
- { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */ },
- { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */ },
- { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */ },
- { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */ },
- ];
- var indexBufferViewIndex = null;
- if (bufferMesh) {
- // For each BabylonMesh, create bufferviews for each 'kind'
- for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
- var attribute = attributeData_1[_i];
- var attributeKind = attribute.kind;
- if (bufferMesh.isVerticesDataPresent(attributeKind)) {
- byteOffset += this.createBufferViewKind(attributeKind, babylonMesh, byteOffset, dataBuffer);
- attribute.bufferViewIndex = this.bufferViews.length - 1;
- }
- }
- if (bufferMesh.getTotalIndices()) {
- var indices = bufferMesh.getIndices();
- if (indices) {
- if (dataBuffer) {
- var end = indices.length;
- var byteOff = byteOffset;
- for (var k = 0; k < end; ++k) {
- dataBuffer.setUint32(byteOff, indices[k], true);
- byteOff += 4;
- }
- byteOffset = byteOff;
- }
- else {
- var byteLength = indices.length * 4;
- var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
- byteOffset += byteLength;
- this.bufferViews.push(bufferView);
- indexBufferViewIndex = this.bufferViews.length - 1;
- }
- }
- }
- if (babylonMesh.subMeshes) {
- // go through all mesh primitives (submeshes)
- for (var _a = 0, _b = babylonMesh.subMeshes; _a < _b.length; _a++) {
- var submesh = _b[_a];
- var meshPrimitive = { attributes: {} };
- // Create a bufferview storing all the positions
- if (!dataBuffer) {
- for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
- var attribute = attributeData_2[_c];
- var attributeKind = attribute.kind;
- if (bufferMesh.isVerticesDataPresent(attributeKind)) {
- var vertexBuffer = bufferMesh.getVertexBuffer(attributeKind);
- if (vertexBuffer) {
- var bufferData = vertexBuffer.getData();
- if (bufferData) {
- var strideSize = vertexBuffer.getStrideSize();
- var minMax = void 0;
- var min = null;
- var max = null;
- var bufferViewIndex = attribute.bufferViewIndex;
- if (bufferViewIndex != undefined) {
- if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
- minMax = this.calculateMinMaxPositions(bufferData, 0, bufferData.length / strideSize);
- min = minMax.min;
- max = minMax.max;
- }
- var accessor = this.createAccessor(bufferViewIndex, attributeKind + " - " + babylonMesh.name, attribute.accessorType, 5126 /* FLOAT */, bufferData.length / strideSize, 0, min, max);
- this.accessors.push(accessor);
- switch (attributeKind) {
- case BABYLON.VertexBuffer.PositionKind: {
- meshPrimitive.attributes.POSITION = this.accessors.length - 1;
- break;
- }
- case BABYLON.VertexBuffer.NormalKind: {
- meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
- break;
- }
- case BABYLON.VertexBuffer.ColorKind: {
- meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
- break;
- }
- case BABYLON.VertexBuffer.TangentKind: {
- meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
- break;
- }
- case BABYLON.VertexBuffer.UVKind: {
- meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
- break;
- }
- case BABYLON.VertexBuffer.UV2Kind: {
- meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
- break;
- }
- default: {
- BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
- }
- }
- }
- }
- }
- }
- }
- if (indexBufferViewIndex) {
- // Create accessor
- var accessor = this.createAccessor(indexBufferViewIndex, "indices - " + babylonMesh.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
- this.accessors.push(accessor);
- meshPrimitive.indices = this.accessors.length - 1;
- }
- }
- if (bufferMesh.material) {
- if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial) {
- var materialIndex = babylonMesh.getScene().materials.indexOf(bufferMesh.material);
- meshPrimitive.material = materialIndex;
- }
- else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
- var babylonMultiMaterial = bufferMesh.material;
- var material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
- if (material) {
- var materialIndex = babylonMesh.getScene().materials.indexOf(material);
- meshPrimitive.material = materialIndex;
- }
- }
- else {
- BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
- }
- }
- mesh.primitives.push(meshPrimitive);
- }
- }
- }
- return byteOffset;
- };
- /**
- * Creates a glTF scene based on the array of meshes.
- * Returns the the total byte offset.
- * @param babylonScene - Babylon scene to get the mesh data from.
- * @param byteOffset - Offset to start from in bytes.
- * @returns bytelength + byteoffset
- */
- _Exporter.prototype.createScene = function (babylonScene, byteOffset) {
- if (babylonScene.meshes.length) {
- var babylonMeshes = babylonScene.meshes;
- var scene = { nodes: new Array() };
- GLTF2._GLTFMaterial.ConvertMaterialsToGLTF(babylonScene.materials, "image/jpeg" /* JPEG */, this.images, this.textures, this.materials, this.imageData, true);
- var result = this.createNodeMap(babylonScene, byteOffset);
- this.nodeMap = result.nodeMap;
- this.totalByteLength = result.byteOffset;
- this.binaryBuffer = new ArrayBuffer(this.totalByteLength);
- var dataBuffer = new DataView(this.binaryBuffer);
- for (var i = 0; i < babylonMeshes.length; ++i) {
- if (this.options &&
- this.options.shouldExportMesh != undefined &&
- !this.options.shouldExportMesh(babylonMeshes[i])) {
- continue;
- }
- else {
- var babylonMesh = babylonMeshes[i];
- // Build Hierarchy with the node map.
- var glTFNodeIndex = this.nodeMap[babylonMesh.uniqueId];
- var glTFNode = this.nodes[glTFNodeIndex];
- if (!babylonMesh.parent) {
- scene.nodes.push(glTFNodeIndex);
- }
- var directDescendents = babylonMesh.getDescendants(true);
- if (!glTFNode.children && directDescendents && directDescendents.length) {
- glTFNode.children = [];
- for (var _i = 0, directDescendents_1 = directDescendents; _i < directDescendents_1.length; _i++) {
- var descendent = directDescendents_1[_i];
- glTFNode.children.push(this.nodeMap[descendent.uniqueId]);
- }
- }
- var mesh = { primitives: new Array() };
- byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
- }
- }
- this.scenes.push(scene);
- }
- return byteOffset;
- };
- /**
- * Creates a mapping of Node unique id to node index
- * @param scene - Babylon Scene.
- * @param byteOffset - The initial byte offset.
- * @returns - Node mapping of unique id to index.
- */
- _Exporter.prototype.createNodeMap = function (scene, byteOffset) {
- var nodeMap = {};
- for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
- var babylonMesh = _a[_i];
- var result = this.createNode(babylonMesh, byteOffset, null);
- this.nodes.push(result.node);
- nodeMap[babylonMesh.uniqueId] = this.nodes.length - 1;
- byteOffset = result.byteOffset;
- }
- return { nodeMap: nodeMap, byteOffset: byteOffset };
- };
- /**
- * Creates a glTF node from a Babylon mesh.
- * @param babylonMesh - Source Babylon mesh.
- * @param byteOffset - The initial byte offset.
- * @param dataBuffer - Buffer for storing geometry data.
- * @returns - Object containing an INode and byteoffset.
- */
- _Exporter.prototype.createNode = function (babylonMesh, byteOffset, dataBuffer) {
- // create node to hold translation/rotation/scale and the mesh
- var node = {};
- if (babylonMesh.name) {
- node.name = babylonMesh.name;
- }
- // Set transformation
- this.setNodeTransformation(node, babylonMesh);
- // create mesh
- var mesh = { primitives: new Array() };
- mesh.primitives = [];
- byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
- if (mesh.primitives.length) {
- this.meshes.push(mesh);
- node.mesh = this.meshes.length - 1;
- }
- return { node: node, byteOffset: byteOffset };
- };
- return _Exporter;
- }());
- GLTF2._Exporter = _Exporter;
- })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.glTFExporter.js.map
- var BABYLON;
- (function (BABYLON) {
- /**
- * Class for holding and downloading glTF file data
- */
- var _GLTFData = /** @class */ (function () {
- /**
- * Initializes the glTF file object.
- */
- function _GLTFData() {
- this.glTFFiles = {};
- }
- /**
- * Downloads the glTF data as files based on their names and data.
- */
- _GLTFData.prototype.downloadFiles = function () {
- /**
- * Checks for a matching suffix at the end of a string (for ES5 and lower).
- * @param str - Source string.
- * @param suffix - Suffix to search for in the source string.
- * @returns - Boolean indicating whether the suffix was found (true) or not (false).
- */
- function endsWith(str, suffix) {
- return str.indexOf(suffix, str.length - suffix.length) !== -1;
- }
- for (var key in this.glTFFiles) {
- var link = document.createElement('a');
- document.body.appendChild(link);
- link.setAttribute("type", "hidden");
- link.download = key;
- var blob = this.glTFFiles[key];
- var mimeType = void 0;
- if (endsWith(key, ".glb")) {
- mimeType = { type: "model/gltf-binary" };
- }
- else if (endsWith(key, ".bin")) {
- mimeType = { type: "application/octet-stream" };
- }
- else if (endsWith(key, ".gltf")) {
- mimeType = { type: "model/gltf+json" };
- }
- else if (endsWith(key, ".jpeg" || ".jpg")) {
- mimeType = { type: "image/jpeg" /* JPEG */ };
- }
- else if (endsWith(key, ".png")) {
- mimeType = { type: "image/png" /* PNG */ };
- }
- link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
- link.click();
- }
- };
- return _GLTFData;
- }());
- BABYLON._GLTFData = _GLTFData;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.glTFData.js.map
- var BABYLON;
- (function (BABYLON) {
- var GLTF2;
- (function (GLTF2) {
- /**
- * Utility methods for working with glTF material conversion properties. This class should only be used internally.
- */
- var _GLTFMaterial = /** @class */ (function () {
- function _GLTFMaterial() {
- }
- /**
- * Gets the materials from a Babylon scene and converts them to glTF materials.
- * @param scene
- * @param mimeType
- * @param images
- * @param textures
- * @param materials
- * @param imageData
- * @param hasTextureCoords
- */
- _GLTFMaterial.ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
- for (var i = 0; i < babylonMaterials.length; ++i) {
- var babylonMaterial = babylonMaterials[i];
- if (babylonMaterial instanceof BABYLON.StandardMaterial) {
- _GLTFMaterial.ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
- }
- else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
- _GLTFMaterial.ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
- }
- }
- };
- /**
- * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
- * @param babylonStandardMaterial
- * @returns - glTF Metallic Roughness Material representation
- */
- _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
- var P0 = new BABYLON.Vector2(0, 1);
- var P1 = new BABYLON.Vector2(0, 0.1);
- var P2 = new BABYLON.Vector2(0, 0.1);
- var P3 = new BABYLON.Vector2(1300, 0.1);
- /**
- * Given the control points, solve for x based on a given t for a cubic bezier curve.
- * @param t - a value between 0 and 1.
- * @param p0 - first control point.
- * @param p1 - second control point.
- * @param p2 - third control point.
- * @param p3 - fourth control point.
- * @returns - number result of cubic bezier curve at the specified t.
- */
- function cubicBezierCurve(t, p0, p1, p2, p3) {
- return ((1 - t) * (1 - t) * (1 - t) * p0 +
- 3 * (1 - t) * (1 - t) * t * p1 +
- 3 * (1 - t) * t * t * p2 +
- t * t * t * p3);
- }
- /**
- * Evaluates a specified specular power value to determine the appropriate roughness value,
- * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
- * and roughness on the ordinant axis (y-axis).
- * @param specularPower - specular power of standard material.
- * @returns - Number representing the roughness value.
- */
- function solveForRoughness(specularPower) {
- var t = Math.pow(specularPower / P3.x, 0.333333);
- return cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
- }
- var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
- var opacity = babylonStandardMaterial.alpha;
- var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this.maxSpecularPower);
- var roughness = solveForRoughness(specularPower);
- var glTFPbrMetallicRoughness = {
- baseColorFactor: [
- diffuse.r,
- diffuse.g,
- diffuse.b,
- opacity
- ],
- metallicFactor: 0,
- roughnessFactor: roughness,
- };
- return glTFPbrMetallicRoughness;
- };
- /**
- * Computes the metallic factor
- * @param diffuse - diffused value
- * @param specular - specular value
- * @param oneMinusSpecularStrength - one minus the specular strength
- * @returns - metallic value
- */
- _GLTFMaterial.SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
- if (specular < _GLTFMaterial.dielectricSpecular.r) {
- _GLTFMaterial.dielectricSpecular;
- return 0;
- }
- var a = _GLTFMaterial.dielectricSpecular.r;
- var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial.dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial.dielectricSpecular.r;
- var c = _GLTFMaterial.dielectricSpecular.r - specular;
- var D = b * b - 4.0 * a * c;
- return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
- };
- /**
- * Gets the glTF alpha mode from the Babylon Material
- * @param babylonMaterial - Babylon Material
- * @returns - The Babylon alpha mode value
- */
- _GLTFMaterial.GetAlphaMode = function (babylonMaterial) {
- if (babylonMaterial instanceof BABYLON.StandardMaterial) {
- var babylonStandardMaterial = babylonMaterial;
- if ((babylonStandardMaterial.alpha != 1.0) ||
- (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
- (babylonStandardMaterial.opacityTexture != null)) {
- return "BLEND" /* BLEND */;
- }
- else {
- return "OPAQUE" /* OPAQUE */;
- }
- }
- else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
- var babylonPBRMetallicRoughness = babylonMaterial;
- switch (babylonPBRMetallicRoughness.transparencyMode) {
- case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
- return "OPAQUE" /* OPAQUE */;
- }
- case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
- return "BLEND" /* BLEND */;
- }
- case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
- return "MASK" /* MASK */;
- }
- case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
- BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
- return "BLEND" /* BLEND */;
- }
- default: {
- throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
- }
- }
- }
- else {
- throw new Error("Unsupported Babylon material type");
- }
- };
- /**
- * Converts a Babylon Standard Material to a glTF Material.
- * @param babylonStandardMaterial - BJS Standard Material.
- * @param mimeType - mime type to use for the textures.
- * @param images - array of glTF image interfaces.
- * @param textures - array of glTF texture interfaces.
- * @param materials - array of glTF material interfaces.
- * @param imageData - map of image file name to data.
- * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
- */
- _GLTFMaterial.ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
- BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Standard Material is currently not fully supported/implemented in glTF serializer");
- var glTFPbrMetallicRoughness = _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
- var glTFMaterial = { name: babylonStandardMaterial.name };
- if (babylonStandardMaterial.backFaceCulling) {
- if (!babylonStandardMaterial.twoSidedLighting) {
- BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
- }
- glTFMaterial.doubleSided = true;
- }
- if (hasTextureCoords) {
- if (babylonStandardMaterial.diffuseTexture) {
- var glTFTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
- if (glTFTexture != null) {
- glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
- }
- }
- if (babylonStandardMaterial.bumpTexture) {
- var glTFTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
- if (glTFTexture) {
- glTFMaterial.normalTexture = glTFTexture;
- }
- }
- if (babylonStandardMaterial.emissiveTexture) {
- var glTFEmissiveTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
- if (glTFEmissiveTexture) {
- glTFMaterial.emissiveTexture = glTFEmissiveTexture;
- }
- glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
- }
- if (babylonStandardMaterial.ambientTexture) {
- var glTFOcclusionTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
- if (glTFOcclusionTexture) {
- glTFMaterial.occlusionTexture = glTFOcclusionTexture;
- }
- }
- }
- if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
- if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
- glTFMaterial.alphaMode = "BLEND" /* BLEND */;
- }
- else {
- BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
- }
- }
- if (babylonStandardMaterial.emissiveColor) {
- glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
- }
- glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
- materials.push(glTFMaterial);
- };
- /**
- * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
- * @param babylonPBRMetalRoughMaterial - BJS PBR Metallic Roughness Material.
- * @param mimeType - mime type to use for the textures.
- * @param images - array of glTF image interfaces.
- * @param textures - array of glTF texture interfaces.
- * @param materials - array of glTF material interfaces.
- * @param imageData - map of image file name to data.
- * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
- */
- _GLTFMaterial.ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
- var glTFPbrMetallicRoughness = {};
- if (babylonPBRMetalRoughMaterial.baseColor) {
- glTFPbrMetallicRoughness.baseColorFactor = [
- babylonPBRMetalRoughMaterial.baseColor.r,
- babylonPBRMetalRoughMaterial.baseColor.g,
- babylonPBRMetalRoughMaterial.baseColor.b,
- babylonPBRMetalRoughMaterial.alpha
- ];
- }
- if (babylonPBRMetalRoughMaterial.metallic != null) {
- glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
- }
- if (babylonPBRMetalRoughMaterial.roughness != null) {
- glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
- }
- var glTFMaterial = {
- name: babylonPBRMetalRoughMaterial.name
- };
- if (babylonPBRMetalRoughMaterial.doubleSided) {
- glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
- }
- if (hasTextureCoords) {
- if (babylonPBRMetalRoughMaterial.baseTexture != null) {
- var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
- if (glTFTexture != null) {
- glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
- }
- }
- if (babylonPBRMetalRoughMaterial.normalTexture) {
- var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
- if (glTFTexture) {
- glTFMaterial.normalTexture = glTFTexture;
- }
- }
- if (babylonPBRMetalRoughMaterial.occlusionTexture) {
- var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
- if (glTFTexture) {
- glTFMaterial.occlusionTexture = glTFTexture;
- if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
- glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
- }
- }
- }
- if (babylonPBRMetalRoughMaterial.emissiveTexture) {
- var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
- if (glTFTexture != null) {
- glTFMaterial.emissiveTexture = glTFTexture;
- }
- }
- }
- if (babylonPBRMetalRoughMaterial.emissiveColor.equalsFloats(0.0, 0.0, 0.0)) {
- glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
- }
- if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
- var alphaMode = _GLTFMaterial.GetAlphaMode(babylonPBRMetalRoughMaterial);
- if (alphaMode !== "OPAQUE" /* OPAQUE */) {
- glTFMaterial.alphaMode = alphaMode;
- if (alphaMode === "BLEND" /* BLEND */) {
- glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
- }
- }
- }
- glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
- materials.push(glTFMaterial);
- };
- /**
- * Extracts a texture from a Babylon texture into file data and glTF data.
- * @param babylonTexture - Babylon texture to extract.
- * @param mimeType - Mime Type of the babylonTexture.
- * @param images - Array of glTF images.
- * @param textures - Array of glTF textures.
- * @param imageData - map of image file name and data.
- * @return - glTF texture, or null if the texture format is not supported.
- */
- _GLTFMaterial.ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
- var textureInfo = null;
- var glTFTexture = {
- source: images.length
- };
- var textureName = "texture_" + (textures.length - 1).toString();
- var textureData = babylonTexture.getInternalTexture();
- if (textureData != null) {
- textureName = textureData.url;
- }
- textureName = BABYLON.Tools.GetFilename(textureName);
- var baseFile = textureName.split('.')[0];
- var extension = "";
- if (mimeType === "image/jpeg" /* JPEG */) {
- extension = ".jpg";
- }
- else if (mimeType === "image/png" /* PNG */) {
- extension = ".png";
- }
- else {
- BABYLON.Tools.Error("Unsupported mime type " + mimeType);
- }
- textureName = baseFile + extension;
- var pixels = babylonTexture.readPixels();
- var imageCanvas = document.createElement('canvas');
- imageCanvas.id = "ImageCanvas";
- var ctx = imageCanvas.getContext('2d');
- var size = babylonTexture.getSize();
- imageCanvas.width = size.width;
- imageCanvas.height = size.height;
- var imgData = ctx.createImageData(size.width, size.height);
- imgData.data.set(pixels);
- ctx.putImageData(imgData, 0, 0);
- var base64Data = imageCanvas.toDataURL(mimeType);
- var binStr = atob(base64Data.split(',')[1]);
- var arr = new Uint8Array(binStr.length);
- for (var i = 0; i < binStr.length; ++i) {
- arr[i] = binStr.charCodeAt(i);
- }
- var imageValues = { data: arr, mimeType: mimeType };
- imageData[textureName] = imageValues;
- if (mimeType === "image/jpeg" /* JPEG */) {
- var glTFImage = {
- uri: textureName
- };
- var foundIndex = -1;
- for (var i = 0; i < images.length; ++i) {
- if (images[i].uri === textureName) {
- foundIndex = i;
- break;
- }
- }
- if (foundIndex === -1) {
- images.push(glTFImage);
- glTFTexture.source = images.length - 1;
- textures.push({
- source: images.length - 1
- });
- textureInfo = {
- index: images.length - 1
- };
- }
- else {
- glTFTexture.source = foundIndex;
- textureInfo = {
- index: foundIndex
- };
- }
- }
- return textureInfo;
- };
- /**
- * Represents the dielectric specular values for R, G and B.
- */
- _GLTFMaterial.dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
- /**
- * Allows the maximum specular power to be defined for material calculations.
- */
- _GLTFMaterial.maxSpecularPower = 1024;
- return _GLTFMaterial;
- }());
- GLTF2._GLTFMaterial = _GLTFMaterial;
- })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.glTFMaterial.js.map
- (function universalModuleDefinition(root, factory) {
- var f = factory();
-
-
- if(typeof exports === 'object' && typeof module === 'object')
- module.exports = f;
- else if(typeof define === 'function' && define.amd)
- define("babylonjs-serializers", ["BABYLON"], factory);
- else if(typeof exports === 'object')
- exports["babylonjs-serializers"] = f;
- else {
- root["BABYLON"] = f;
- }
- })(this, function() {
- return BABYLON;
- });
|