瀏覽代碼

Merge pull request #4533 from kcoley/glTFSerializer3dTexture

glTFSerializer: Exported textures no longer premultiplied with canvas
sebavan 7 年之前
父節點
當前提交
480722badd

+ 1 - 4
Tools/Gulp/config.json

@@ -1691,13 +1691,10 @@
                     "../../serializers/src/glTF/2.0/babylon.glTFSerializer.ts",
                     "../../serializers/src/glTF/2.0/babylon.glTFExporter.ts",
                     "../../serializers/src/glTF/2.0/babylon.glTFData.ts",
-                    "../../serializers/src/glTF/2.0/babylon.glTFMaterial.ts",
+                    "../../serializers/src/glTF/2.0/babylon.glTFMaterialExporter.ts",
                     "../../serializers/src/glTF/2.0/babylon.glTFAnimation.ts",
                     "../../serializers/src/glTF/2.0/babylon.glTFUtilities.ts"
                 ],
-                "shaderFiles": [
-                    "../../serializers/src/glTF/2.0/shaders/setAlphaToOne.fragment.fx"
-                ],
                 "output": "babylon.glTF2Serializer.js"
             }
         ],

+ 153 - 125
serializers/src/glTF/2.0/babylon.glTFExporter.ts

@@ -32,86 +32,90 @@ module BABYLON.GLTF2 {
         /**
          * Stores all generated buffer views, which represents views into the main glTF buffer data
          */
-        private bufferViews: IBufferView[];
+        private _bufferViews: IBufferView[];
         /**
          * Stores all the generated accessors, which is used for accessing the data within the buffer views in glTF
          */
-        private accessors: IAccessor[];
+        private _accessors: IAccessor[];
         /**
          * Stores all the generated nodes, which contains transform and/or mesh information per node
          */
-        private nodes: INode[];
+        private _nodes: INode[];
         /**
          * Stores the glTF asset information, which represents the glTF version and this file generator
          */
-        private asset: IAsset;
+        private _asset: IAsset;
         /**
          * Stores all the generated glTF scenes, which stores multiple node hierarchies
          */
-        private scenes: IScene[];
+        private _scenes: IScene[];
         /**
          * Stores all the generated mesh information, each containing a set of primitives to render in glTF
          */
-        private meshes: IMesh[];
+        private _meshes: IMesh[];
         /**
          * Stores all the generated material information, which represents the appearance of each primitive
          */
-        private materials: IMaterial[];
+        public _materials: IMaterial[];
 
-        private materialMap: { [materialID: number]: number };
+        public _materialMap: { [materialID: number]: number };
         /**
          * Stores all the generated texture information, which is referenced by glTF materials
          */
-        private textures: ITexture[];
+        public _textures: ITexture[];
         /**
          * Stores all the generated image information, which is referenced by glTF textures
          */
-        private images: IImage[];
+        public _images: IImage[];
 
         /**
          * Stores all the texture samplers
          */
-        private samplers: ISampler[];
+        public _samplers: ISampler[];
         /**
          * Stores all the generated animation samplers, which is referenced by glTF animations
          */
         /**
          * Stores the animations for glTF models
          */
-        private animations: IAnimation[];
+        private _animations: IAnimation[];
         /**
          * Stores the total amount of bytes stored in the glTF buffer
          */
-        private totalByteLength: number;
+        private _totalByteLength: number;
         /**
          * Stores a reference to the Babylon scene containing the source geometry and material information
          */
-        private babylonScene: Scene;
+        private _babylonScene: Scene;
         /**
          * Stores a map of the image data, where the key is the file name and the value
          * is the image data
          */
-        private imageData: { [fileName: string]: { data: Uint8Array, mimeType: ImageMimeType } };
+        public _imageData: { [fileName: string]: { data: Uint8Array, mimeType: ImageMimeType } };
 
         /**
          * Stores a map of the unique id of a node to its index in the node array
          */
-        private nodeMap: { [key: number]: number };
+        private _nodeMap: { [key: number]: number };
 
         /**
          * Specifies if the Babylon scene should be converted to right-handed on export
          */
-        private convertToRightHandedSystem: boolean;
+        private _convertToRightHandedSystem: boolean;
 
         /**
          * Baked animation sample rate
          */
-        private animationSampleRate: number;
+        private _animationSampleRate: number;
 
         /**
          * Callback which specifies if a transform node should be exported or not
          */
-        private shouldExportTransformNode: ((babylonTransformNode: TransformNode) => boolean);
+        private _shouldExportTransformNode: ((babylonTransformNode: TransformNode) => boolean);
+
+        private _localEngine: Engine;
+
+        private _glTFMaterialExporter: _GLTFMaterialExporter;
 
         /**
          * Creates a glTF Exporter instance, which can accept optional exporter options
@@ -119,24 +123,43 @@ module BABYLON.GLTF2 {
          * @param options Options to modify the behavior of the exporter
          */
         public constructor(babylonScene: Scene, options?: IExportOptions) {
-            this.asset = { generator: "BabylonJS", version: "2.0" };
-            this.babylonScene = babylonScene;
-            this.bufferViews = [];
-            this.accessors = [];
-            this.meshes = [];
-            this.scenes = [];
-            this.nodes = [];
-            this.images = [];
-            this.materials = [];
-            this.materialMap = [];
-            this.textures = [];
-            this.samplers = [];
-            this.animations = [];
-            this.imageData = {};
-            this.convertToRightHandedSystem = this.babylonScene.useRightHandedSystem ? false : true;
+            this._asset = { generator: "BabylonJS", version: "2.0" };
+            this._babylonScene = babylonScene;
+            this._bufferViews = [];
+            this._accessors = [];
+            this._meshes = [];
+            this._scenes = [];
+            this._nodes = [];
+            this._images = [];
+            this._materials = [];
+            this._materialMap = [];
+            this._textures = [];
+            this._samplers = [];
+            this._animations = [];
+            this._imageData = {};
+            this._convertToRightHandedSystem = this._babylonScene.useRightHandedSystem ? false : true;
             const _options = options || {};
-            this.shouldExportTransformNode = _options.shouldExportTransformNode ? _options.shouldExportTransformNode : (babylonTransformNode: TransformNode) => true;
-            this.animationSampleRate = _options.animationSampleRate ? _options.animationSampleRate : 1 / 60;
+            this._shouldExportTransformNode = _options.shouldExportTransformNode ? _options.shouldExportTransformNode : (babylonTransformNode: TransformNode) => true;
+            this._animationSampleRate = _options.animationSampleRate ? _options.animationSampleRate : 1 / 60;
+
+
+            this._glTFMaterialExporter = new _GLTFMaterialExporter(this);
+        }
+
+        /**
+         * Lazy load a local engine with premultiplied alpha set to false
+         */
+        public _getLocalEngine(): Engine {
+            if (!this._localEngine) {
+                const localCanvas = document.createElement('canvas');
+                localCanvas.id = "WriteCanvas";
+                localCanvas.width = 2048;
+                localCanvas.height = 2048;
+                this._localEngine = new Engine(localCanvas, true, { premultipliedAlpha: false, preserveDrawingBuffer: true });
+                this._localEngine.setViewport(new Viewport(0, 0, 1, 1));
+            }
+
+            return this._localEngine;
         }
 
         private reorderIndicesBasedOnPrimitiveMode(submesh: SubMesh, primitiveMode: number, babylonIndices: IndicesArray, byteOffset: number, binaryWriter: _BinaryWriter) {
@@ -182,7 +205,7 @@ module BABYLON.GLTF2 {
          * @param binaryWriter The binary data for the glTF file
          */
         private reorderVertexAttributeDataBasedOnPrimitiveMode(submesh: SubMesh, primitiveMode: number, sideOrientation: number, vertexBufferKind: string, meshAttributeArray: FloatArray, byteOffset: number, binaryWriter: _BinaryWriter): void {
-            if (this.convertToRightHandedSystem && sideOrientation === Material.ClockWiseSideOrientation) {
+            if (this._convertToRightHandedSystem && sideOrientation === Material.ClockWiseSideOrientation) {
                 switch (primitiveMode) {
                     case Material.TriangleFillMode: {
                         this.reorderTriangleFillMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
@@ -412,7 +435,7 @@ module BABYLON.GLTF2 {
          */
         private writeVertexAttributeData(vertices: Vector2[] | Vector3[] | Vector4[], byteOffset: number, vertexAttributeKind: string, meshAttributeArray: FloatArray, binaryWriter: _BinaryWriter) {
             for (let vertex of vertices) {
-                if (this.convertToRightHandedSystem && !(vertexAttributeKind === VertexBuffer.ColorKind) && !(vertex instanceof Vector2)) {
+                if (this._convertToRightHandedSystem && !(vertexAttributeKind === VertexBuffer.ColorKind) && !(vertex instanceof Vector2)) {
                     if (vertex instanceof Vector3) {
                         (vertexAttributeKind === VertexBuffer.PositionKind) ? _GLTFUtilities.GetRightHandedPositionVector3FromRef(vertex) : _GLTFUtilities.GetRightHandedNormalVector3FromRef(vertex);
                     }
@@ -445,7 +468,7 @@ module BABYLON.GLTF2 {
                     for (let k = 0, length = meshAttributeArray.length / stride; k < length; ++k) {
                         index = k * stride;
                         const vertexData = Vector3.FromArray(meshAttributeArray, index);
-                        if (this.convertToRightHandedSystem) {
+                        if (this._convertToRightHandedSystem) {
                             _GLTFUtilities.GetRightHandedPositionVector3FromRef(vertexData);
                         }
                         vertexAttributes.push(vertexData.asArray());
@@ -456,7 +479,7 @@ module BABYLON.GLTF2 {
                     for (let k = 0, length = meshAttributeArray.length / stride; k < length; ++k) {
                         index = k * stride;
                         const vertexData = Vector3.FromArray(meshAttributeArray, index);
-                        if (this.convertToRightHandedSystem) {
+                        if (this._convertToRightHandedSystem) {
                             _GLTFUtilities.GetRightHandedNormalVector3FromRef(vertexData);
                         }
                         vertexAttributes.push(vertexData.asArray());
@@ -467,7 +490,7 @@ module BABYLON.GLTF2 {
                     for (let k = 0, length = meshAttributeArray.length / stride; k < length; ++k) {
                         index = k * stride;
                         const vertexData = Vector4.FromArray(meshAttributeArray, index);
-                        if (this.convertToRightHandedSystem) {
+                        if (this._convertToRightHandedSystem) {
                             _GLTFUtilities.GetRightHandedVector4FromRef(vertexData);
                         }
                         vertexAttributes.push(vertexData.asArray());
@@ -486,7 +509,7 @@ module BABYLON.GLTF2 {
                 case VertexBuffer.UV2Kind: {
                     for (let k = 0, length = meshAttributeArray.length / stride; k < length; ++k) {
                         index = k * stride;
-                        vertexAttributes.push(this.convertToRightHandedSystem ? [meshAttributeArray[index], meshAttributeArray[index + 1]] : [meshAttributeArray[index], meshAttributeArray[index + 1]]);
+                        vertexAttributes.push(this._convertToRightHandedSystem ? [meshAttributeArray[index], meshAttributeArray[index + 1]] : [meshAttributeArray[index], meshAttributeArray[index + 1]]);
                     }
                     break;
                 }
@@ -510,61 +533,61 @@ module BABYLON.GLTF2 {
          * @returns json data as string
          */
         private generateJSON(shouldUseGlb: boolean, glTFPrefix?: string, prettyPrint?: boolean): string {
-            let buffer: IBuffer = { byteLength: this.totalByteLength };
+            let buffer: IBuffer = { byteLength: this._totalByteLength };
             let imageName: string;
             let imageData: { data: Uint8Array, mimeType: ImageMimeType };
             let bufferView: IBufferView;
-            let byteOffset: number = this.totalByteLength;
+            let byteOffset: number = this._totalByteLength;
 
             let glTF: IGLTF = {
-                asset: this.asset
+                asset: this._asset
             };
             if (buffer.byteLength) {
                 glTF.buffers = [buffer];
             }
-            if (this.nodes && this.nodes.length) {
-                glTF.nodes = this.nodes;
+            if (this._nodes && this._nodes.length) {
+                glTF.nodes = this._nodes;
             }
-            if (this.meshes && this.meshes.length) {
-                glTF.meshes = this.meshes;
+            if (this._meshes && this._meshes.length) {
+                glTF.meshes = this._meshes;
             }
-            if (this.scenes && this.scenes.length) {
-                glTF.scenes = this.scenes;
+            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._bufferViews && this._bufferViews.length) {
+                glTF.bufferViews = this._bufferViews;
             }
-            if (this.accessors && this.accessors.length) {
-                glTF.accessors = this.accessors;
+            if (this._accessors && this._accessors.length) {
+                glTF.accessors = this._accessors;
             }
-            if (this.animations && this.animations.length) {
-                glTF.animations = this.animations;
+            if (this._animations && this._animations.length) {
+                glTF.animations = this._animations;
             }
-            if (this.materials && this.materials.length) {
-                glTF.materials = this.materials;
+            if (this._materials && this._materials.length) {
+                glTF.materials = this._materials;
             }
-            if (this.textures && this.textures.length) {
-                glTF.textures = this.textures;
+            if (this._textures && this._textures.length) {
+                glTF.textures = this._textures;
             }
-            if (this.samplers && this.samplers.length) {
-                glTF.samplers = this.samplers;
+            if (this._samplers && this._samplers.length) {
+                glTF.samplers = this._samplers;
             }
-            if (this.images && this.images.length) {
+            if (this._images && this._images.length) {
                 if (!shouldUseGlb) {
-                    glTF.images = this.images;
+                    glTF.images = this._images;
                 }
                 else {
                     glTF.images = [];
 
-                    this.images.forEach((image) => {
+                    this._images.forEach((image) => {
                         if (image.uri) {
-                            imageData = this.imageData[image.uri];
+                            imageData = this._imageData[image.uri];
                             imageName = image.uri.split('.')[0] + " image";
                             bufferView = _GLTFUtilities.CreateBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
                             byteOffset += imageData.data.buffer.byteLength;
-                            this.bufferViews.push(bufferView);
-                            image.bufferView = this.bufferViews.length - 1;
+                            this._bufferViews.push(bufferView);
+                            image.bufferView = this._bufferViews.length - 1;
                             image.name = imageName;
                             image.mimeType = imageData.mimeType;
                             image.uri = undefined;
@@ -606,9 +629,9 @@ module BABYLON.GLTF2 {
                 container.glTFFiles[glTFFileName] = jsonText;
                 container.glTFFiles[glTFBinFile] = bin;
 
-                if (this.imageData) {
-                    for (let image in this.imageData) {
-                        container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
+                if (this._imageData) {
+                    for (let image in this._imageData) {
+                        container.glTFFiles[image] = new Blob([this._imageData[image].data], { type: this._imageData[image].mimeType });
                     }
                 }
 
@@ -623,7 +646,10 @@ module BABYLON.GLTF2 {
          */
         private _generateBinaryAsync(): Promise<ArrayBuffer> {
             let binaryWriter = new _BinaryWriter(4);
-            return this.createSceneAsync(this.babylonScene, binaryWriter).then(() => {
+            return this.createSceneAsync(this._babylonScene, binaryWriter).then(() => {
+                if (this._localEngine) {
+                    this._localEngine.dispose();
+                }
                 return binaryWriter.getArrayBuffer();
             });
         }
@@ -655,8 +681,8 @@ module BABYLON.GLTF2 {
                 const jsonLength = jsonText.length;
                 let imageByteLength = 0;
 
-                for (let key in this.imageData) {
-                    imageByteLength += this.imageData[key].data.byteLength;
+                for (let key in this._imageData) {
+                    imageByteLength += this._imageData[key].data.byteLength;
                 }
                 const jsonPadding = this._getPadding(jsonLength);
                 const binPadding = this._getPadding(binaryBuffer.byteLength);
@@ -711,8 +737,8 @@ module BABYLON.GLTF2 {
                 const glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
 
                 // binary data
-                for (let key in this.imageData) {
-                    glbData.push(this.imageData[key].data.buffer);
+                for (let key in this._imageData) {
+                    glbData.push(this._imageData[key].data.buffer);
                 }
                 glbData.push(binPaddingBuffer);
 
@@ -723,6 +749,8 @@ module BABYLON.GLTF2 {
                 const container = new GLTFData();
                 container.glTFFiles[glbFileName] = glbFile;
 
+                this._localEngine.dispose();
+
                 return container;
             });
         }
@@ -734,7 +762,7 @@ module BABYLON.GLTF2 {
          */
         private setNodeTransformation(node: INode, babylonTransformNode: TransformNode): void {
             if (!babylonTransformNode.position.equalsToFloats(0, 0, 0)) {
-                node.translation = this.convertToRightHandedSystem ? _GLTFUtilities.GetRightHandedPositionVector3(babylonTransformNode.position).asArray() : babylonTransformNode.position.asArray();
+                node.translation = this._convertToRightHandedSystem ? _GLTFUtilities.GetRightHandedPositionVector3(babylonTransformNode.position).asArray() : babylonTransformNode.position.asArray();
             }
 
             if (!babylonTransformNode.scaling.equalsToFloats(1, 1, 1)) {
@@ -746,7 +774,7 @@ module BABYLON.GLTF2 {
                 rotationQuaternion.multiplyInPlace(babylonTransformNode.rotationQuaternion);
             }
             if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
-                if (this.convertToRightHandedSystem) {
+                if (this._convertToRightHandedSystem) {
                     _GLTFUtilities.GetRightHandedQuaternionFromRef(rotationQuaternion);
 
                 }
@@ -781,7 +809,7 @@ module BABYLON.GLTF2 {
                 if (vertexData) {
                     const byteLength = vertexData.length * 4;
                     const bufferView = _GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, byteStride, kind + " - " + bufferMesh.name);
-                    this.bufferViews.push(bufferView);
+                    this._bufferViews.push(bufferView);
 
                     this.writeAttributeData(
                         kind,
@@ -854,27 +882,27 @@ module BABYLON.GLTF2 {
         private setAttributeKind(meshPrimitive: IMeshPrimitive, attributeKind: string): void {
             switch (attributeKind) {
                 case VertexBuffer.PositionKind: {
-                    meshPrimitive.attributes.POSITION = this.accessors.length - 1;
+                    meshPrimitive.attributes.POSITION = this._accessors.length - 1;
                     break;
                 }
                 case VertexBuffer.NormalKind: {
-                    meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
+                    meshPrimitive.attributes.NORMAL = this._accessors.length - 1;
                     break;
                 }
                 case VertexBuffer.ColorKind: {
-                    meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
+                    meshPrimitive.attributes.COLOR_0 = this._accessors.length - 1;
                     break;
                 }
                 case VertexBuffer.TangentKind: {
-                    meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
+                    meshPrimitive.attributes.TANGENT = this._accessors.length - 1;
                     break;
                 }
                 case VertexBuffer.UVKind: {
-                    meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
+                    meshPrimitive.attributes.TEXCOORD_0 = this._accessors.length - 1;
                     break;
                 }
                 case VertexBuffer.UV2Kind: {
-                    meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
+                    meshPrimitive.attributes.TEXCOORD_1 = this._accessors.length - 1;
                     break;
                 }
                 default: {
@@ -926,7 +954,7 @@ module BABYLON.GLTF2 {
                         }
 
                         this.createBufferViewKind(attributeKind, babylonTransformNode, binaryWriter, attribute.byteStride);
-                        attribute.bufferViewIndex = this.bufferViews.length - 1;
+                        attribute.bufferViewIndex = this._bufferViews.length - 1;
                         vertexAttributeBufferViews[attributeKind] = attribute.bufferViewIndex;
                     }
                 }
@@ -936,8 +964,8 @@ module BABYLON.GLTF2 {
                     if (indices) {
                         const byteLength = indices.length * 4;
                         bufferView = _GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, "Indices - " + bufferMesh.name);
-                        this.bufferViews.push(bufferView);
-                        indexBufferViewIndex = this.bufferViews.length - 1;
+                        this._bufferViews.push(bufferView);
+                        indexBufferViewIndex = this._bufferViews.length - 1;
 
                         for (let k = 0, length = indices.length; k < length; ++k) {
                             binaryWriter.setUInt32(indices[k]);
@@ -963,21 +991,21 @@ module BABYLON.GLTF2 {
                                         baseColorFactor: bufferMesh.color.asArray().concat([bufferMesh.alpha])
                                     }
                                 }
-                                this.materials.push(material);
-                                materialIndex = this.materials.length - 1;
+                                this._materials.push(material);
+                                materialIndex = this._materials.length - 1;
                             }
                             else if (babylonMaterial instanceof MultiMaterial) {
                                 babylonMaterial = babylonMaterial.subMaterials[submesh.materialIndex];
                                 if (babylonMaterial) {
-                                    materialIndex = this.materialMap[babylonMaterial.uniqueId];
+                                    materialIndex = this._materialMap[babylonMaterial.uniqueId];
                                 }
                             }
                             else {
-                                materialIndex = this.materialMap[babylonMaterial.uniqueId];
+                                materialIndex = this._materialMap[babylonMaterial.uniqueId];
                             }
                         }
 
-                        let glTFMaterial: Nullable<IMaterial> = materialIndex != null ? this.materials[materialIndex] : null;
+                        let glTFMaterial: Nullable<IMaterial> = materialIndex != null ? this._materials[materialIndex] : null;
 
                         const meshPrimitive: IMeshPrimitive = { attributes: {} };
                         this.setPrimitiveMode(meshPrimitive, primitiveMode);
@@ -985,7 +1013,7 @@ module BABYLON.GLTF2 {
                         for (const attribute of attributeData) {
                             const attributeKind = attribute.kind;
                             if (attributeKind === VertexBuffer.UVKind || attributeKind === VertexBuffer.UV2Kind) {
-                                if (glTFMaterial && !_GLTFMaterial._HasTexturesPresent(glTFMaterial)) {
+                                if (glTFMaterial && !this._glTFMaterialExporter._hasTexturesPresent(glTFMaterial)) {
                                     continue;
                                 }
                             }
@@ -998,10 +1026,10 @@ module BABYLON.GLTF2 {
                                     if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
                                         minMax = { min: null, max: null };
                                         if (attributeKind == VertexBuffer.PositionKind) {
-                                            minMax = _GLTFUtilities.CalculateMinMaxPositions(vertexData, 0, vertexData.length / stride, this.convertToRightHandedSystem);
+                                            minMax = _GLTFUtilities.CalculateMinMaxPositions(vertexData, 0, vertexData.length / stride, this._convertToRightHandedSystem);
                                         }
                                         const accessor = _GLTFUtilities.CreateAccessor(bufferViewIndex, attributeKind + " - " + babylonTransformNode.name, attribute.accessorType, AccessorComponentType.FLOAT, vertexData.length / stride, 0, minMax.min, minMax.max);
-                                        this.accessors.push(accessor);
+                                        this._accessors.push(accessor);
                                         this.setAttributeKind(meshPrimitive, attributeKind);
                                         if (meshPrimitive.attributes.TEXCOORD_0 != null || meshPrimitive.attributes.TEXCOORD_1 != null) {
                                             uvCoordsPresent = true;
@@ -1013,15 +1041,15 @@ module BABYLON.GLTF2 {
                         if (indexBufferViewIndex) {
                             // Create accessor
                             const accessor = _GLTFUtilities.CreateAccessor(indexBufferViewIndex, "indices - " + babylonTransformNode.name, AccessorType.SCALAR, AccessorComponentType.UNSIGNED_INT, submesh.indexCount, submesh.indexStart * 4, null, null);
-                            this.accessors.push(accessor);
-                            meshPrimitive.indices = this.accessors.length - 1;
+                            this._accessors.push(accessor);
+                            meshPrimitive.indices = this._accessors.length - 1;
                         }
                         if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
-                            let sideOrientation = this.babylonScene.materials[materialIndex].sideOrientation;
+                            let sideOrientation = this._babylonScene.materials[materialIndex].sideOrientation;
 
-                            if (this.convertToRightHandedSystem && sideOrientation === Material.ClockWiseSideOrientation) {
+                            if (this._convertToRightHandedSystem && sideOrientation === Material.ClockWiseSideOrientation) {
                                 //Overwrite the indices to be counter-clockwise
-                                let byteOffset = indexBufferViewIndex != null ? this.bufferViews[indexBufferViewIndex].byteOffset : null;
+                                let byteOffset = indexBufferViewIndex != null ? this._bufferViews[indexBufferViewIndex].byteOffset : null;
                                 if (byteOffset == null) { byteOffset = 0; }
                                 let babylonIndices: Nullable<IndicesArray> = null;
                                 if (indexBufferViewIndex != null) {
@@ -1034,7 +1062,7 @@ module BABYLON.GLTF2 {
                                     for (let attribute of attributeData) {
                                         let vertexData = bufferMesh.getVerticesData(attribute.kind);
                                         if (vertexData) {
-                                            let byteOffset = this.bufferViews[vertexAttributeBufferViews[attribute.kind]].byteOffset;
+                                            let byteOffset = this._bufferViews[vertexAttributeBufferViews[attribute.kind]].byteOffset;
                                             if (!byteOffset) {
                                                 byteOffset = 0
                                             }
@@ -1044,10 +1072,10 @@ module BABYLON.GLTF2 {
                                 }
                             }
 
-                            if (!uvCoordsPresent && _GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
-                                const newMat = _GLTFMaterial._StripTexturesFromMaterial(this.materials[materialIndex]);
-                                this.materials.push(newMat);
-                                materialIndex = this.materials.length - 1;
+                            if (!uvCoordsPresent && this._glTFMaterialExporter._hasTexturesPresent(this._materials[materialIndex])) {
+                                const newMat = this._glTFMaterialExporter._stripTexturesFromMaterial(this._materials[materialIndex]);
+                                this._materials.push(newMat);
+                                materialIndex = this._materials.length - 1;
                             }
 
                             meshPrimitive.material = materialIndex;
@@ -1072,23 +1100,23 @@ module BABYLON.GLTF2 {
             let directDescendents: Node[];
             const nodes = [...babylonScene.transformNodes, ...babylonScene.meshes];
 
-            return _GLTFMaterial._ConvertMaterialsToGLTFAsync(babylonScene.materials, ImageMimeType.PNG, this.images, this.textures, this.samplers, this.materials, this.materialMap, this.imageData, true).then(() => {
-                this.nodeMap = this.createNodeMapAndAnimations(babylonScene, nodes, this.shouldExportTransformNode, binaryWriter);
+            return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(babylonScene.materials, ImageMimeType.PNG, true).then(() => {
+                this._nodeMap = this.createNodeMapAndAnimations(babylonScene, nodes, this._shouldExportTransformNode, binaryWriter);
 
-                this.totalByteLength = binaryWriter.getByteOffset();
+                this._totalByteLength = binaryWriter.getByteOffset();
 
 
                 // Build Hierarchy with the node map.
                 for (let babylonTransformNode of nodes) {
-                    glTFNodeIndex = this.nodeMap[babylonTransformNode.uniqueId];
+                    glTFNodeIndex = this._nodeMap[babylonTransformNode.uniqueId];
                     if (glTFNodeIndex != null) {
-                        glTFNode = this.nodes[glTFNodeIndex];
+                        glTFNode = this._nodes[glTFNodeIndex];
                         if (!babylonTransformNode.parent) {
-                            if (!this.shouldExportTransformNode(babylonTransformNode)) {
+                            if (!this._shouldExportTransformNode(babylonTransformNode)) {
                                 Tools.Log("Omitting " + babylonTransformNode.name + " from scene.");
                             }
                             else {
-                                if (this.convertToRightHandedSystem) {
+                                if (this._convertToRightHandedSystem) {
                                     if (glTFNode.translation) {
                                         glTFNode.translation[2] *= -1;
                                         glTFNode.translation[0] *= -1;
@@ -1104,15 +1132,15 @@ module BABYLON.GLTF2 {
                         if (!glTFNode.children && directDescendents && directDescendents.length) {
                             glTFNode.children = [];
                             for (let descendent of directDescendents) {
-                                if (this.nodeMap[descendent.uniqueId] != null) {
-                                    glTFNode.children.push(this.nodeMap[descendent.uniqueId]);
+                                if (this._nodeMap[descendent.uniqueId] != null) {
+                                    glTFNode.children.push(this._nodeMap[descendent.uniqueId]);
                                 }
                             }
                         }
                     }
                 };
                 if (scene.nodes.length) {
-                    this.scenes.push(scene);
+                    this._scenes.push(scene);
                 }
             });
         }
@@ -1140,12 +1168,12 @@ module BABYLON.GLTF2 {
                 if (shouldExportTransformNode(babylonTransformNode)) {
                     node = this.createNode(babylonTransformNode, binaryWriter);
 
-                    this.nodes.push(node);
-                    nodeIndex = this.nodes.length - 1;
+                    this._nodes.push(node);
+                    nodeIndex = this._nodes.length - 1;
                     nodeMap[babylonTransformNode.uniqueId] = nodeIndex;
 
                     if (!babylonScene.animationGroups.length && babylonTransformNode.animations.length) {
-                        _GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations(babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, this.nodes, binaryWriter, this.bufferViews, this.accessors, this.convertToRightHandedSystem, this.animationSampleRate);
+                        _GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations(babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, this._nodes, binaryWriter, this._bufferViews, this._accessors, this._convertToRightHandedSystem, this._animationSampleRate);
                     }
                 }
                 else {
@@ -1154,16 +1182,16 @@ module BABYLON.GLTF2 {
             };
 
             if (runtimeGLTFAnimation.channels.length && runtimeGLTFAnimation.samplers.length) {
-                this.animations.push(runtimeGLTFAnimation);
+                this._animations.push(runtimeGLTFAnimation);
             }
             idleGLTFAnimations.forEach((idleGLTFAnimation) => {
                 if (idleGLTFAnimation.channels.length && idleGLTFAnimation.samplers.length) {
-                    this.animations.push(idleGLTFAnimation);
+                    this._animations.push(idleGLTFAnimation);
                 }
             });
 
             if (babylonScene.animationGroups.length) {
-                _GLTFAnimation._CreateNodeAnimationFromAnimationGroups(babylonScene, this.animations, nodeMap, this.nodes, binaryWriter, this.bufferViews, this.accessors, this.convertToRightHandedSystem, this.animationSampleRate);
+                _GLTFAnimation._CreateNodeAnimationFromAnimationGroups(babylonScene, this._animations, nodeMap, this._nodes, binaryWriter, this._bufferViews, this._accessors, this._convertToRightHandedSystem, this._animationSampleRate);
             }
 
             return nodeMap;
@@ -1190,8 +1218,8 @@ module BABYLON.GLTF2 {
             this.setPrimitiveAttributes(mesh, babylonTransformNode, binaryWriter);
 
             if (mesh.primitives.length) {
-                this.meshes.push(mesh);
-                node.mesh = this.meshes.length - 1;
+                this._meshes.push(mesh);
+                node.mesh = this._meshes.length - 1;
             }
 
             return node;

File diff suppressed because it is too large
+ 229 - 208
serializers/src/glTF/2.0/babylon.glTFMaterial.ts


+ 0 - 10
serializers/src/glTF/2.0/shaders/setAlphaToOne.fragment.fx

@@ -1,10 +0,0 @@
-precision highp float;
-
-uniform sampler2D textureSampler;
-
-varying vec2 vUV;
-
-void main(void) {
-    vec4 color = texture2D(textureSampler, vUV);
-    gl_FragColor = vec4(color.rgb, 1.0);
-}

+ 4 - 56
tests/unit/babylon/serializers/babylon.glTFSerializer.tests.ts

@@ -35,29 +35,6 @@ describe('Babylon glTF Serializer', () => {
      * This tests the glTF serializer help functions 
      */
     describe('#GLTF', () => {
-        // it('should get alpha mode from Babylon metallic roughness', () => {
-        //     let alphaMode: string;
-
-        //     const scene = new BABYLON.Scene(subject);
-        //     const babylonMaterial = new BABYLON.PBRMetallicRoughnessMaterial("metallicroughness", scene);
-        //     babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
-
-        //     alphaMode = BABYLON.GLTF2._GLTFMaterial._GetAlphaMode(babylonMaterial);
-        //     alphaMode.should.be.equal('OPAQUE');
-
-        //     babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
-        //     alphaMode = BABYLON.GLTF2._GLTFMaterial._GetAlphaMode(babylonMaterial);
-        //     alphaMode.should.be.equal('BLEND');
-
-        //     babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND;
-        //     alphaMode = BABYLON.GLTF2._GLTFMaterial._GetAlphaMode(babylonMaterial);
-        //     alphaMode.should.be.equal('BLEND');
-
-        //     babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
-        //     alphaMode = BABYLON.GLTF2._GLTFMaterial._GetAlphaMode(babylonMaterial);
-        //     alphaMode.should.be.equal('MASK');
-        // });
-
         it('should convert Babylon standard material to metallic roughness', () => {
             const scene = new BABYLON.Scene(subject);
             const babylonStandardMaterial = new BABYLON.StandardMaterial("specGloss", scene);
@@ -65,8 +42,9 @@ describe('Babylon glTF Serializer', () => {
             babylonStandardMaterial.specularColor = BABYLON.Color3.Black();
             babylonStandardMaterial.specularPower = 64;
             babylonStandardMaterial.alpha = 1;
+            const materialExporter = new BABYLON.GLTF2._GLTFMaterialExporter(new BABYLON.GLTF2._Exporter(scene));
 
-            const metalRough = BABYLON.GLTF2._GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
+            const metalRough = materialExporter._convertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
 
             metalRough.baseColorFactor.should.deep.equal([0.5, 0.5, 0.5, 1]);
 
@@ -74,12 +52,10 @@ describe('Babylon glTF Serializer', () => {
 
             metalRough.roughnessFactor.should.be.approximately(0.328809, 1e-6);
         });
-
         it('should solve for metallic', () => {
-            BABYLON.GLTF2._GLTFMaterial._SolveMetallic(1.0, 0.0, 1.0).should.be.equal(0);
-            BABYLON.GLTF2._GLTFMaterial._SolveMetallic(0.0, 1.0, 1.0).should.be.approximately(1, 1e-6);
+            BABYLON.GLTF2._GLTFMaterialExporter._SolveMetallic(1.0, 0.0, 1.0).should.be.equal(0);
+            BABYLON.GLTF2._GLTFMaterialExporter._SolveMetallic(0.0, 1.0, 1.0).should.be.approximately(1, 1e-6);
         });
-
         it('should serialize empty Babylon scene to glTF with only asset property', () => {
             const scene = new BABYLON.Scene(subject);
 
@@ -92,7 +68,6 @@ describe('Babylon glTF Serializer', () => {
                 jsonData.asset.generator.should.be.equal("BabylonJS");
             });
         });
-
         it('should serialize sphere geometry in scene to glTF', () => {
             const scene = new BABYLON.Scene(subject);
             BABYLON.Mesh.CreateSphere('sphere', 16, 2, scene);
@@ -125,33 +100,6 @@ describe('Babylon glTF Serializer', () => {
                     jsonData.scene.should.be.equal(0);
                 });
         });
-
-        // it('should serialize alpha mode and cutoff', () => {
-        //     const scene = new BABYLON.Scene(subject);
-
-        //     const plane = BABYLON.Mesh.CreatePlane('plane', 120, scene);
-        //     const babylonPBRMetalRoughMaterial = new BABYLON.PBRMetallicRoughnessMaterial('metalRoughMat', scene);
-        //     babylonPBRMetalRoughMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
-        //     const alphaCutoff = 0.8;
-        //     babylonPBRMetalRoughMaterial.alphaCutOff = alphaCutoff;
-
-        //     plane.material = babylonPBRMetalRoughMaterial;
-
-
-        //     return BABYLON.GLTF2Export.GLTFAsync(scene, 'test').then(glTFData => {
-        //         const jsonString = glTFData.glTFFiles['test.gltf'] as string;
-        //         const jsonData = JSON.parse(jsonString);
-
-        //         // accessors, asset, buffers, bufferViews, meshes, nodes, scene, scenes, materials
-        //         Object.keys(jsonData).length.should.be.equal(9);
-
-        //         jsonData.materials.length.should.be.equal(2);
-
-        //         jsonData.materials[0].alphaMode.should.be.equal('MASK');
-
-        //         jsonData.materials[0].alphaCutoff.should.be.equal(alphaCutoff);
-        //     });
-        // });
         it('should serialize single component translation animation to glTF', () => {
             const scene = new BABYLON.Scene(subject);
             const box = BABYLON.Mesh.CreateBox('box', 1, scene);