babylon.glTF2Serializer.min.js 24 KB

1
  1. var BABYLON;!(function(e){var t=(function(){function t(){}return t.GLTF=function(t,r,a){var i=r.replace(/\.[^\/.]+$/,""),s=new e.GLTF2._Exporter(t,a);if(t.isReady)return s._generateGLTF(i);throw new Error("glTF Serializer: Scene is not ready!")},t.GLB=function(t,r,a){var i=r.replace(/\.[^\/.]+$/,""),s=new e.GLTF2._Exporter(t,a);if(t.isReady)return s._generateGLB(i);throw new Error("glTF Serializer: Scene is not ready!")},t})();e.GLTF2Export=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(){function r(e,t){this.asset={generator:"BabylonJS",version:"2.0"},this.babylonScene=e,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,t&&(this.options=t)}return r.prototype.createBufferView=function(e,t,r,a,i){var s={buffer:e,byteLength:r};return t&&(s.byteOffset=t),i&&(s.name=i),a&&(s.byteStride=a),s},r.prototype.createAccessor=function(e,t,r,a,i,s,n,o){var l={name:t,bufferView:e,componentType:a,count:i,type:r};return n&&(l.min=n),o&&(l.max=o),s&&(l.byteOffset=s),l},r.prototype.calculateMinMaxPositions=function(t,a,i){var s=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0],o=a+i;if(i)for(var l=a;l<o;++l)for(var u=3*l,h=e.Vector3.FromArray(t,u),c=this.convertToRightHandedSystem?r.GetRightHandedVector3(h).asArray():h.asArray(),f=0;f<3;++f){var d=c[f];d<s[f]&&(s[f]=d),d>n[f]&&(n[f]=d),++u}return{min:s,max:n}},r.GetRightHandedVector3=function(t){return new e.Vector3(t.x,t.y,-t.z)},r.GetRightHandedVector4=function(t){return new e.Vector4(t.x,t.y,-t.z,-t.w)},r.GetRightHandedQuaternion=function(t){return new e.Quaternion(-t.x,-t.y,t.z,t.w)},r.prototype.writeAttributeData=function(t,a,i,s){for(var n=i,o=e.VertexBuffer.DeduceStride(t),l=a.length/o,u=0;u<l;++u){var h=u*o,c=[];if(t===e.VertexBuffer.PositionKind||t===e.VertexBuffer.NormalKind){var f=e.Vector3.FromArray(a,h);c=this.convertToRightHandedSystem?r.GetRightHandedVector3(f).asArray():f.asArray()}else if(t===e.VertexBuffer.TangentKind||t===e.VertexBuffer.ColorKind){var f=e.Vector4.FromArray(a,h);c=this.convertToRightHandedSystem&&t!==e.VertexBuffer.ColorKind?r.GetRightHandedVector4(f).asArray():f.asArray()}else t===e.VertexBuffer.UVKind||t===e.VertexBuffer.UV2Kind?c=[a[h],a[h+1]]:e.Tools.Warn("Unsupported Vertex Buffer Type: "+t);for(var d=0;d<c.length;++d)s.setFloat32(n,c[d],!0),n+=4}return 4*a.length},r.prototype.generateJSON=function(e,t,r){var a={byteLength:this.totalByteLength},i={asset:this.asset};if(a.byteLength&&(i.buffers=[a]),this.nodes&&this.nodes.length&&(i.nodes=this.nodes),this.meshes&&this.meshes.length&&(i.meshes=this.meshes),this.scenes&&this.scenes.length&&(i.scenes=this.scenes,i.scene=0),this.bufferViews&&this.bufferViews.length&&(i.bufferViews=this.bufferViews),this.accessors&&this.accessors.length&&(i.accessors=this.accessors),this.materials&&this.materials.length&&(i.materials=this.materials),this.textures&&this.textures.length&&(i.textures=this.textures),this.images&&this.images.length)if(e){i.images=[];for(var s=this.images.length,n=this.totalByteLength,o=0;o<s;++o){var l=this.images[o];if(l.uri){var u=this.imageData[l.uri],h=l.uri.split(".")[0]+" image",c=this.createBufferView(0,n,u.data.length,void 0,h);n+=u.data.buffer.byteLength,this.bufferViews.push(c),l.bufferView=this.bufferViews.length-1,l.name=h,l.mimeType=u.mimeType,l.uri=void 0,i.images.push(l)}}a.byteLength=n}else i.images=this.images;return e||(a.uri=t+".bin"),r?JSON.stringify(i,null,2):JSON.stringify(i)},r.prototype._generateGLTF=function(t){var r=this.generateBinary(),a=this.generateJSON(!1,t,!0),i=new Blob([r],{type:"application/octet-stream"}),s=t+".gltf",n=t+".bin",o=new e._GLTFData;if(o.glTFFiles[s]=a,o.glTFFiles[n]=i,this.imageData)for(var l in this.imageData)o.glTFFiles[l]=new Blob([this.imageData[l].data],{type:this.imageData[l].mimeType});return o},r.prototype.generateBinary=function(){var e=0;return e=this.createScene(this.babylonScene,e),this.binaryBuffer},r.prototype._getPadding=function(e){var t=e%4;return 0===t?t:4-t},r.prototype._generateGLB=function(t){var r=this.generateBinary(),a=this.generateJSON(!0),i=t+".glb",s=a.length,n=0;for(var o in this.imageData)n+=this.imageData[o].data.byteLength;var l=this._getPadding(s),u=this._getPadding(r.byteLength),h=this._getPadding(n),c=28+s+l+r.byteLength+u+n+h,f=new ArrayBuffer(12),d=new DataView(f);d.setUint32(0,1179937895,!0),d.setUint32(4,2,!0),d.setUint32(8,c,!0);var g=new ArrayBuffer(8+s+l),p=new DataView(g);p.setUint32(0,s+l,!0),p.setUint32(4,1313821514,!0);for(var m=new Uint8Array(g,8),v=0;v<s;++v)m[v]=a.charCodeAt(v);for(var T=new Uint8Array(g,8+s),v=0;v<l;++v)T[v]=32;var x=new ArrayBuffer(8),b=new DataView(x);b.setUint32(0,r.byteLength+n+h,!0),b.setUint32(4,5130562,!0);for(var y=new ArrayBuffer(u),C=new Uint8Array(y),v=0;v<u;++v)C[v]=0;for(var B=new ArrayBuffer(h),M=new Uint8Array(B),v=0;v<h;++v)M[v]=0;var w=[f,g,x,r];for(var o in this.imageData)w.push(this.imageData[o].data.buffer);w.push(y),w.push(B);var A=new Blob(w,{type:"application/octet-stream"}),_=new e._GLTFData;return _.glTFFiles[i]=A,_},r.prototype.setNodeTransformation=function(t,a){a.position.equalsToFloats(0,0,0)||(t.translation=this.convertToRightHandedSystem?r.GetRightHandedVector3(a.position).asArray():a.position.asArray()),a.scaling.equalsToFloats(1,1,1)||(t.scale=a.scaling.asArray());var i=e.Quaternion.RotationYawPitchRoll(a.rotation.y,a.rotation.x,a.rotation.z);a.rotationQuaternion&&(i=i.multiply(a.rotationQuaternion)),0===i.x&&0===i.y&&0===i.z&&1===i.w||(t.rotation=this.convertToRightHandedSystem?r.GetRightHandedQuaternion(i).asArray():i.asArray())},r.prototype.createBufferViewKind=function(t,r,a,i){var s=null,n=0;if(r instanceof e.Mesh?s=r:r instanceof e.InstancedMesh&&(s=r.sourceMesh),s){var o=s.getVerticesData(t);if(o)if(i&&o)n=this.writeAttributeData(t,o,a,i),a+=n;else{n=4*o.length;var l=this.createBufferView(0,a,n,void 0,t+" - "+s.name);a+=n,this.bufferViews.push(l)}}return n},r.prototype.setPrimitiveAttributes=function(r,a,i,s){var n=null;a instanceof e.Mesh?n=a:a instanceof e.InstancedMesh&&(n=a.sourceMesh);var o=[{kind:e.VertexBuffer.PositionKind,accessorType:"VEC3"},{kind:e.VertexBuffer.NormalKind,accessorType:"VEC3"},{kind:e.VertexBuffer.ColorKind,accessorType:"VEC4"},{kind:e.VertexBuffer.TangentKind,accessorType:"VEC4"},{kind:e.VertexBuffer.UVKind,accessorType:"VEC2"},{kind:e.VertexBuffer.UV2Kind,accessorType:"VEC2"}],l=null;if(n){for(var u=0,h=o;u<h.length;u++){var c=h[u],f=c.kind;n.isVerticesDataPresent(f)&&(i+=this.createBufferViewKind(f,a,i,s),c.bufferViewIndex=this.bufferViews.length-1)}if(n.getTotalIndices()){var d=n.getIndices();if(d)if(s){for(var g=d.length,p=i,m=0;m<g;++m)s.setUint32(p,d[m],!0),p+=4;i=p}else{var v=4*d.length,T=this.createBufferView(0,i,v,void 0,"Indices - "+n.name);i+=v,this.bufferViews.push(T),l=this.bufferViews.length-1}}if(a.subMeshes)for(var x=!1,b=0,y=a.subMeshes;b<y.length;b++){var C=y[b],B={attributes:{}};if(!s){for(var M=0,w=o;M<w.length;M++){var c=w[M],f=c.kind,A=n.getVerticesData(f);if(A){var _=e.VertexBuffer.DeduceStride(f),R=void 0,F=null,S=null,L=c.bufferViewIndex;if(void 0!=L){f==e.VertexBuffer.PositionKind&&(R=this.calculateMinMaxPositions(A,0,A.length/_),F=R.min,S=R.max);var E=this.createAccessor(L,f+" - "+a.name,c.accessorType,5126,A.length/_,0,F,S);switch(this.accessors.push(E),f){case e.VertexBuffer.PositionKind:B.attributes.POSITION=this.accessors.length-1;break;case e.VertexBuffer.NormalKind:B.attributes.NORMAL=this.accessors.length-1;break;case e.VertexBuffer.ColorKind:B.attributes.COLOR_0=this.accessors.length-1;break;case e.VertexBuffer.TangentKind:B.attributes.TANGENT=this.accessors.length-1;break;case e.VertexBuffer.UVKind:B.attributes.TEXCOORD_0=this.accessors.length-1,x=!0;break;case e.VertexBuffer.UV2Kind:B.attributes.TEXCOORD_1=this.accessors.length-1,x=!0;break;default:e.Tools.Warn("Unsupported Vertex Buffer Type: "+f)}}}}if(l){var E=this.createAccessor(l,"indices - "+a.name,"SCALAR",5125,C.indexCount,4*C.indexStart,null,null);this.accessors.push(E),B.indices=this.accessors.length-1}}if(n.material){var V=null;if(n.material instanceof e.StandardMaterial||n.material instanceof e.PBRMetallicRoughnessMaterial||n.material instanceof e.PBRMaterial)V=a.getScene().materials.indexOf(n.material);else if(n.material instanceof e.MultiMaterial){var P=n.material,G=P.subMaterials[C.materialIndex];G&&(V=a.getScene().materials.indexOf(G))}else e.Tools.Warn("Material type "+n.material.getClassName()+" for material "+n.material.name+" is not yet implemented in glTF serializer.");if(null!=V&&Object.keys(B.attributes).length>0)if(x||!t._GLTFMaterial._HasTexturesPresent(this.materials[V]))B.material=V;else{var O=t._GLTFMaterial._StripTexturesFromMaterial(this.materials[V]);this.materials.push(O),B.material=this.materials.length-1}}r.primitives.push(B)}}return i},r.prototype.createScene=function(r,a){if(r.meshes.length){var i=r.meshes,s={nodes:new Array};t._GLTFMaterial._ConvertMaterialsToGLTF(r.materials,"image/png",this.images,this.textures,this.materials,this.imageData,!0);var n=this.createNodeMap(r,a);this.nodeMap=n.nodeMap,this.totalByteLength=n.byteOffset,this.binaryBuffer=new ArrayBuffer(this.totalByteLength);for(var o=new DataView(this.binaryBuffer),l=0;l<i.length;++l){var u=i[l],h=this.nodeMap[u.uniqueId],c=this.nodes[h];u.parent||(this.options&&void 0!=this.options.shouldExportMesh&&!this.options.shouldExportMesh(u)?e.Tools.Log("Omitting "+u.name+" from scene."):s.nodes.push(h));var f=u.getDescendants(!0);if(!c.children&&f&&f.length){c.children=[];for(var d=0,g=f;d<g.length;d++){var p=g[d];c.children.push(this.nodeMap[p.uniqueId])}}var m={primitives:new Array};a=this.setPrimitiveAttributes(m,u,a,o)}this.scenes.push(s)}return a},r.prototype.createNodeMap=function(e,t){for(var r={},a=0,i=e.meshes;a<i.length;a++){var s=i[a],n=this.createNode(s,t,null);this.nodes.push(n.node),r[s.uniqueId]=this.nodes.length-1,t=n.byteOffset}return{nodeMap:r,byteOffset:t}},r.prototype.createNode=function(e,t,r){var a={};e.name&&(a.name=e.name),this.setNodeTransformation(a,e);var i={primitives:new Array};return i.primitives=[],t=this.setPrimitiveAttributes(i,e,t,r),i.primitives.length&&(this.meshes.push(i),a.mesh=this.meshes.length-1),{node:a,byteOffset:t}},r})();t._Exporter=r})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.glTFFiles={}}return e.prototype.downloadFiles=function(){function e(e,t){return-1!==e.indexOf(t,e.length-t.length)}for(var t in this.glTFFiles){var r=document.createElement("a");document.body.appendChild(r),r.setAttribute("type","hidden"),r.download=t;var a=this.glTFFiles[t],i=void 0;e(t,".glb")?i={type:"model/gltf-binary"}:e(t,".bin")?i={type:"application/octet-stream"}:e(t,".gltf")?i={type:"model/gltf+json"}:e(t,".jpeg")?i={type:"image/jpeg"}:e(t,".png")&&(i={type:"image/png"}),r.href=window.URL.createObjectURL(new Blob([a],i)),r.click()}},e})();e._GLTFData=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(){function t(){}return t.FuzzyEquals=function(t,r,a){return e.Scalar.WithinEpsilon(t.r,r.r,a)&&e.Scalar.WithinEpsilon(t.g,r.g,a)&&e.Scalar.WithinEpsilon(t.b,r.b,a)},t._ConvertMaterialsToGLTF=function(r,a,i,s,n,o,l){for(var u=0;u<r.length;++u){var h=r[u];if(h instanceof e.StandardMaterial)t._ConvertStandardMaterial(h,a,i,s,n,o,l);else if(h instanceof e.PBRMetallicRoughnessMaterial)t._ConvertPBRMetallicRoughnessMaterial(h,a,i,s,n,o,l);else{if(!(h instanceof e.PBRMaterial))throw new Error("Unsupported material type: "+h.name);t._ConvertPBRMaterial(h,a,i,s,n,o,l)}}},t._StripTexturesFromMaterial=function(e){var t={};if(e){t.name=e.name,t.doubleSided=e.doubleSided,t.alphaMode=e.alphaMode,t.alphaCutoff=e.alphaCutoff,t.emissiveFactor=e.emissiveFactor;var r=e.pbrMetallicRoughness;r&&(t.pbrMetallicRoughness={},t.pbrMetallicRoughness.baseColorFactor=r.baseColorFactor,t.pbrMetallicRoughness.metallicFactor=r.metallicFactor,t.pbrMetallicRoughness.roughnessFactor=r.roughnessFactor)}return t},t._HasTexturesPresent=function(e){if(e.emissiveTexture||e.normalTexture||e.occlusionTexture)return!0;var t=e.pbrMetallicRoughness;return!(!t||!t.baseColorTexture&&!t.metallicRoughnessTexture)},t._ConvertToGLTFPBRMetallicRoughness=function(t){function r(e,t,r,a,i){return(1-e)*(1-e)*(1-e)*t+3*(1-e)*(1-e)*e*r+3*(1-e)*e*e*a+e*e*e*i}var a=new e.Vector2(0,1),i=new e.Vector2(0,.1),s=new e.Vector2(0,.1),n=new e.Vector2(1300,.1),o=t.diffuseColor.toLinearSpace().scale(.5),l=t.alpha,u=e.Scalar.Clamp(t.specularPower,0,this._maxSpecularPower),h=(function(e){return r(Math.pow(e/n.x,.333333),a.y,i.y,s.y,n.y)})(u);return{baseColorFactor:[o.r,o.g,o.b,l],metallicFactor:0,roughnessFactor:h}},t._SolveMetallic=function(r,a,i){if(a<t._dielectricSpecular.r)return t._dielectricSpecular,0;var s=t._dielectricSpecular.r,n=r*i/(1-t._dielectricSpecular.r)+a-2*t._dielectricSpecular.r,o=t._dielectricSpecular.r-a,l=n*n-4*s*o;return e.Scalar.Clamp((-n+Math.sqrt(l))/(2*s),0,1)},t._GetAlphaMode=function(t){if(t instanceof e.StandardMaterial){var r=t;return 1!=r.alpha||null!=r.diffuseTexture&&r.diffuseTexture.hasAlpha||null!=r.opacityTexture?"BLEND":"OPAQUE"}if(t instanceof e.PBRMetallicRoughnessMaterial){var a=t;switch(a.transparencyMode){case e.PBRMaterial.PBRMATERIAL_OPAQUE:return"OPAQUE";case e.PBRMaterial.PBRMATERIAL_ALPHABLEND:return"BLEND";case e.PBRMaterial.PBRMATERIAL_ALPHATEST:return"MASK";case e.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND:return e.Tools.Warn(t.name+": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead."),"BLEND";default:throw new Error("Unsupported alpha mode "+a.transparencyMode)}}else{if(!(t instanceof e.PBRMaterial))throw new Error("Unsupported Babylon material type");var i=t;switch(i.transparencyMode){case e.PBRMaterial.PBRMATERIAL_OPAQUE:return"OPAQUE";case e.PBRMaterial.PBRMATERIAL_ALPHABLEND:return"BLEND";case e.PBRMaterial.PBRMATERIAL_ALPHATEST:return"MASK";case e.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND:return e.Tools.Warn(t.name+": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead."),"BLEND";default:throw new Error("Unsupported alpha mode "+i.transparencyMode)}}},t._ConvertStandardMaterial=function(r,a,i,s,n,o,l){e.Tools.Warn(r.name+": Standard Material is currently not fully supported/implemented in glTF serializer");var u=t._ConvertToGLTFPBRMetallicRoughness(r),h={name:r.name};if(null==r.backFaceCulling||r.backFaceCulling||(r.twoSidedLighting||e.Tools.Warn(r.name+": Back-face culling enabled and two-sided lighting disabled is not supported in glTF."),h.doubleSided=!0),l){if(r.diffuseTexture){var c=t._ExportTexture(r.diffuseTexture,a,i,s,o);null!=c&&(u.baseColorTexture=c)}if(r.bumpTexture){var c=t._ExportTexture(r.bumpTexture,a,i,s,o);c&&(h.normalTexture=c)}if(r.emissiveTexture){var f=t._ExportTexture(r.emissiveTexture,a,i,s,o);f&&(h.emissiveTexture=f),h.emissiveFactor=[1,1,1]}if(r.ambientTexture){var c=t._ExportTexture(r.ambientTexture,a,i,s,o);if(c){var d={index:c.index};h.occlusionTexture=d,d.strength=1}}}(r.alpha<1||r.opacityTexture)&&(r.alphaMode===e.Engine.ALPHA_COMBINE?h.alphaMode="BLEND":e.Tools.Warn(r.name+": glTF 2.0 does not support alpha mode: "+r.alphaMode.toString())),r.emissiveColor&&!this.FuzzyEquals(r.emissiveColor,e.Color3.Black(),this._epsilon)&&(h.emissiveFactor=r.emissiveColor.asArray()),h.pbrMetallicRoughness=u,n.push(h)},t._ConvertPBRMetallicRoughnessMaterial=function(r,a,i,s,n,o,l){var u={};r.baseColor&&(u.baseColorFactor=[r.baseColor.r,r.baseColor.g,r.baseColor.b,r.alpha]),null!=r.metallic&&1!==r.metallic&&(u.metallicFactor=r.metallic),null!=r.roughness&&1!==r.roughness&&(u.roughnessFactor=r.roughness);var h={name:r.name};if(r.doubleSided&&(h.doubleSided=r.doubleSided),l){if(null!=r.baseTexture){var c=t._ExportTexture(r.baseTexture,a,i,s,o);null!=c&&(u.baseColorTexture=c)}if(r.normalTexture){var c=t._ExportTexture(r.normalTexture,a,i,s,o);c&&(h.normalTexture=c)}if(r.occlusionTexture){var c=t._ExportTexture(r.occlusionTexture,a,i,s,o);c&&(h.occlusionTexture=c,null!=r.occlusionStrength&&(h.occlusionTexture.strength=r.occlusionStrength))}if(r.emissiveTexture){var c=t._ExportTexture(r.emissiveTexture,a,i,s,o);null!=c&&(h.emissiveTexture=c)}}if(this.FuzzyEquals(r.emissiveColor,e.Color3.Black(),this._epsilon)&&(h.emissiveFactor=r.emissiveColor.asArray()),null!=r.transparencyMode){var f=t._GetAlphaMode(r);"OPAQUE"!==f&&(h.alphaMode=f,"BLEND"===f&&(h.alphaCutoff=r.alphaCutOff))}h.pbrMetallicRoughness=u,n.push(h)},t._CreateBase64FromCanvas=function(e,t,r,a){var i=document.createElement("canvas");i.id="WriteCanvas";var s=i.getContext("2d");i.width=t,i.height=r;var n=s.createImageData(t,r);return n.data.set(e),s.putImageData(n,0,0),i.toDataURL(a)},t._CreateWhiteTexture=function(t,r,a){for(var i=new Uint8Array(t*r*4),s=0;s<i.length;++s)i[s]=255;return e.RawTexture.CreateRGBATexture(i,t,r,a)},t._ResizeTexturesToSameDimensions=function(t,r,a){var i,s,n=t?t.getSize():{width:0,height:0},o=r?r.getSize():{width:0,height:0};return n.width<o.width?(i=t?e.TextureTools.CreateResizedCopy(t,o.width,o.height,!0):this._CreateWhiteTexture(o.width,o.height,a),s=r):n.width>o.width?(s=r?e.TextureTools.CreateResizedCopy(r,n.width,n.height,!0):this._CreateWhiteTexture(n.width,n.height,a),i=t):(i=t,s=r),{texture1:i,texture2:s}},t._ConvertSpecularGlossinessTexturesToMetallicRoughness=function(t,r,a,i){if(!t&&!r)return null;var s=t?t.getScene():r.getScene();if(!s)throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");var n,o,l=this._ResizeTexturesToSameDimensions(t,r,s),u=l.texture1.getSize(),h=u.width,c=u.height,f=l.texture1.readPixels();if(!(f instanceof Uint8Array))throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: "+l.texture1.name);if(n=l.texture1.readPixels(),!((f=l.texture2.readPixels())instanceof Uint8Array))throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: "+l.texture2.name);o=l.texture2.readPixels();for(var d=o.byteLength,g=new Uint8Array(d),p=new Uint8Array(d),m=e.Color3.Black(),v=0,T=0,x=0;x<c;++x)for(var b=0;b<h;++b){var y=4*(h*x+b),C=e.Color3.FromInts(n[y],n[y+1],n[y+2]).toLinearSpace().multiply(a.diffuseColor),B=e.Color3.FromInts(o[y],o[y+1],o[y+2]).toLinearSpace().multiply(a.specularColor),M=o[y+3]/255*a.glossiness,w={diffuseColor:C,specularColor:B,glossiness:M},A=this._ConvertSpecularGlossinessToMetallicRoughness(w);m.r=Math.max(m.r,A.baseColor.r),m.g=Math.max(m.g,A.baseColor.g),m.b=Math.max(m.b,A.baseColor.b),v=Math.max(v,A.metallic),T=Math.max(T,A.roughness),p[y]=255*A.baseColor.r,p[y+1]=255*A.baseColor.g,p[y+2]=255*A.baseColor.b,p[y+3]=l.texture1.hasAlpha?n[y+3]:255,g[y]=0,g[y+1]=255*A.roughness,g[y+2]=255*A.metallic,g[y+3]=255}for(var _={baseColor:m,metallic:v,roughness:T},R=!1,F=!1,x=0;x<c;++x)for(var b=0;b<h;++b){var S=4*(h*x+b);p[S]/=_.baseColor.r>this._epsilon?_.baseColor.r:1,p[S+1]/=_.baseColor.g>this._epsilon?_.baseColor.g:1,p[S+2]/=_.baseColor.b>this._epsilon?_.baseColor.b:1;var L=e.Color3.FromInts(p[S],p[S+1],p[S+2]),E=L.toGammaSpace();p[S]=255*E.r,p[S+1]=255*E.g,p[S+2]=255*E.b,this.FuzzyEquals(E,e.Color3.White(),this._epsilon)||(F=!0),g[S+1]/=_.roughness>this._epsilon?_.roughness:1,g[S+2]/=_.metallic>this._epsilon?_.metallic:1;var V=e.Color3.FromInts(255,g[S+1],g[S+2]);this.FuzzyEquals(V,e.Color3.White(),this._epsilon)||(R=!0)}if(R){var P=this._CreateBase64FromCanvas(g,h,c,i);_.metallicRoughnessTextureBase64=P}if(F){var G=this._CreateBase64FromCanvas(p,h,c,i);_.baseColorTextureBase64=G}return _},t._ConvertSpecularGlossinessToMetallicRoughness=function(r){var a=t._GetPerceivedBrightness(r.diffuseColor),i=t._GetPerceivedBrightness(r.specularColor),s=1-t._GetMaxComponent(r.specularColor),n=t._SolveMetallic(a,i,s),o=r.diffuseColor.scale(s/(1-this._dielectricSpecular.r)/Math.max(1-n,this._epsilon)),l=r.specularColor.subtract(this._dielectricSpecular.scale(1-n)).scale(1/Math.max(n,this._epsilon)),u=e.Color3.Lerp(o,l,n*n);return u=u.clampToRef(0,1,u),{baseColor:u,metallic:n,roughness:1-r.glossiness}},t._GetPerceivedBrightness=function(e){return e?Math.sqrt(.299*e.r*e.r+.587*e.g*e.g+.114*e.b*e.b):0},t._GetMaxComponent=function(e){return e?Math.max(e.r,Math.max(e.g,e.b)):0},t._ConvertMetalRoughFactorsToMetallicRoughness=function(e,r,a,i,s,n,o){var l={baseColor:e.albedoColor,metallic:e.metallic,roughness:e.roughness};if(o){if(e.albedoTexture){var u=t._ExportTexture(e.albedoTexture,r,a,i,n);u&&(s.baseColorTexture=u)}if(e.metallicTexture){var u=t._ExportTexture(e.metallicTexture,r,a,i,n);null!=u&&(s.metallicRoughnessTexture=u)}}return l},t._ConvertSpecGlossFactorsToMetallicRoughness=function(r,a,i,s,n,o,l){var u={diffuseColor:r.albedoColor||e.Color3.White(),specularColor:r.reflectivityColor||e.Color3.White(),glossiness:r.microSurface||1};if(r.reflectivityTexture&&!r.useMicroSurfaceFromReflectivityMapAlpha)throw new Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture currently not supported");var h=this._ConvertSpecularGlossinessTexturesToMetallicRoughness(r.albedoTexture,r.reflectivityTexture,u,a);if(h){if(l){if(h.baseColorTextureBase64){var c=t._GetTextureInfoFromBase64(h.baseColorTextureBase64,"bjsBaseColorTexture_"+s.length+".png",a,i,s,o);null!=c&&(n.baseColorTexture=c)}if(h.metallicRoughnessTextureBase64){var f=t._GetTextureInfoFromBase64(h.metallicRoughnessTextureBase64,"bjsMetallicRoughnessTexture_"+s.length+".png",a,i,s,o);null!=f&&(n.metallicRoughnessTexture=f)}}}else h=this._ConvertSpecularGlossinessToMetallicRoughness(u);return h},t._ConvertPBRMaterial=function(r,a,i,s,n,o,l){var u,h={},c={name:r.name};if(u=r.isMetallicWorkflow()?this._ConvertMetalRoughFactorsToMetallicRoughness(r,a,i,s,h,o,l):this._ConvertSpecGlossFactorsToMetallicRoughness(r,a,i,s,h,o,l),this.FuzzyEquals(u.baseColor,e.Color3.White(),this._epsilon)&&r.alpha>=this._epsilon||(h.baseColorFactor=[u.baseColor.r,u.baseColor.g,u.baseColor.b,r.alpha]),null!=u.metallic&&1!==u.metallic&&(h.metallicFactor=u.metallic),null!=u.roughness&&1!==u.roughness&&(h.roughnessFactor=u.roughness),null==r.backFaceCulling||r.backFaceCulling||(r.twoSidedLighting||e.Tools.Warn(r.name+": Back-face culling enabled and two-sided lighting disabled is not supported in glTF."),c.doubleSided=!0),l){if(r.bumpTexture){var f=t._ExportTexture(r.bumpTexture,a,i,s,o);f&&(c.normalTexture=f)}if(r.ambientTexture){var f=t._ExportTexture(r.ambientTexture,a,i,s,o);if(f){var d={index:f.index};c.occlusionTexture=d,r.ambientTextureStrength&&(d.strength=r.ambientTextureStrength)}}if(r.emissiveTexture){var f=t._ExportTexture(r.emissiveTexture,a,i,s,o);null!=f&&(c.emissiveTexture=f)}}if(this.FuzzyEquals(r.emissiveColor,e.Color3.Black(),this._epsilon)||(c.emissiveFactor=r.emissiveColor.asArray()),null!=r.transparencyMode){var g=t._GetAlphaMode(r);"OPAQUE"!==g&&(c.alphaMode=g,"BLEND"===g&&(c.alphaCutoff=r.alphaCutOff))}c.pbrMetallicRoughness=h,n.push(c)},t._ExportTexture=function(t,r,a,i,s){var n="texture_"+(i.length-1).toString(),o=t.getInternalTexture();null!=o&&(n=o.url||n),n=e.Tools.GetFilename(n);var l=n.split(".")[0],u="";if("image/jpeg"===r)u=".jpg";else{if("image/png"!==r)throw new Error("Unsupported mime type "+r);u=".png"}n=l+u;var h=t.readPixels(),c=t.getSize(),f=this._CreateBase64FromCanvas(h,c.width,c.height,r);return this._GetTextureInfoFromBase64(f,n,r,a,i,s)},t._GetTextureInfoFromBase64=function(e,t,r,a,i,s){for(var n=null,o={source:a.length},l=atob(e.split(",")[1]),u=new Uint8Array(l.length),h=0;h<l.length;++h)u[h]=l.charCodeAt(h);var c={data:u,mimeType:r};if(s[t]=c,"image/jpeg"===r||"image/png"===r){for(var f={uri:t},d=-1,h=0;h<a.length;++h)if(a[h].uri===t){d=h;break}-1===d?(a.push(f),o.source=a.length-1,i.push({source:a.length-1}),n={index:a.length-1}):(o.source=d,n={index:d})}return n},t._dielectricSpecular=new e.Color3(.04,.04,.04),t._maxSpecularPower=1024,t._epsilon=1e-6,t})();t._GLTFMaterial=r})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));