public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, Matrix4x4[] arr, BufferViewId bufferViewId = null, BinaryWriter writer = null)
        {
            var count = arr.Length;

            if (count == 0)
            {
                MyLog.LogError("Accessors can not have a count of 0.");
            }

            var accessor = new Accessor();

            accessor.ComponentType = GLTFComponentType.Float;
            accessor.Count         = count;
            accessor.Type          = GLTFAccessorAttributeType.MAT4;

            var byteOffset = writer.BaseStream.Position;

            foreach (var vec in arr)
            {
                writer.Write(vec.m00);
                writer.Write(vec.m10);
                writer.Write(vec.m20);
                writer.Write(vec.m30);
                writer.Write(vec.m01);
                writer.Write(vec.m11);
                writer.Write(vec.m21);
                writer.Write(vec.m31);
                writer.Write(vec.m02);
                writer.Write(vec.m12);
                writer.Write(vec.m22);
                writer.Write(vec.m32);
                writer.Write(vec.m03);
                writer.Write(vec.m13);
                writer.Write(vec.m23);
                writer.Write(vec.m33);
            }

            var byteLength = writer.BaseStream.Position - byteOffset;

            if (bufferViewId != null)
            {
                accessor.BufferView = bufferViewId;
                accessor.ByteOffset = (int)byteOffset;
            }
            else
            {
                accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength);
            }


            var id = new AccessorId
            {
                Id   = root.Accessors.Count,
                Root = root
            };

            root.Accessors.Add(accessor);

            return(id);
        }
        public byte[] EncodeToPNG(Texture2D source, string ext = "png")
        {
            var             path     = AssetDatabase.GetAssetPath(source);
            TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(path);

            MyLog.Log("---导出图片:" + source.name + " path:" + path);
            var saveTextureType = TextureImporterType.Default;
            var isRestore       = false;

            if (importer)
            {
                saveTextureType = importer.textureType;
                if (saveTextureType == TextureImporterType.NormalMap && !ExportToolsSetting.instance.unityNormalTexture)
                {
                    //法线贴图类型贴图因为Unity特殊处理过,如果要正常导出,就要转换一下类型
                    isRestore            = true;
                    importer.textureType = TextureImporterType.Default;
                    importer.SaveAndReimport();
                }
            }

            var renderTexture = RenderTexture.GetTemporary(source.width, source.height);

            Graphics.Blit(source, renderTexture);
            RenderTexture.active = renderTexture;
            var exportTexture = new Texture2D(source.width, source.height);

            exportTexture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
            exportTexture.Apply();

            byte[] res = null;
            try
            {
                if (ext == "jpg" || ext == "jpeg")
                {
                    res = exportTexture.EncodeToJPG();
                }
                else if (ext == "exr")
                {
                    res = exportTexture.EncodeToEXR();
                }
                else
                {
                    res = exportTexture.EncodeToPNG();
                }
            }
            catch (System.Exception e)
            {
                MyLog.LogError("图片导出出错:" + path + " 请保证原始资源是可读写,非压缩文件");
            }

            if (isRestore && importer)
            {
                importer.textureType = saveTextureType;
                importer.SaveAndReimport();
            }

            return(res);
        }
        /**
         * 判断命名是否合法
         */
        public static bool LegalName(string name, string objType)
        {
            Regex regex = new Regex("[^0-9a-zA-Z_+-.@() /]");
            Match match = regex.Match(name);

            if (match.Success)
            {
                MyLog.LogError(objType + "不合法的命名:" + name + "只支持字母、数字、_+-.@");
            }
            return(!match.Success);
        }
Exemple #4
0
        public static void ExportScene(List <GameObject> roots, string exportPath = "")
        {
            string sceneName = PathHelper.CurSceneName;

            //导出场景
            try
            {
                ExportImageTools.instance.Clear();
                ResourceManager.instance.Clean();
                //路径
                string scenePath = sceneName + ".scene.json";
                PathHelper.SetSceneOrPrefabPath(scenePath);
                //Scene
                var           scene     = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene();
                MyJson_Object sceneJson = new MyJson_Object();
                sceneJson.SetUUID(scene.GetHashCode().ToString());//用场景名称的hashCode
                sceneJson.SetUnityID(scene.GetHashCode());
                sceneJson.SetClass("paper.Scene");
                sceneJson.SetString("name", sceneName.Substring(sceneName.LastIndexOf('/') + 1));

                sceneJson.SetColor("ambientColor", RenderSettings.ambientLight);
                sceneJson.SetNumber("lightmapIntensity", UnityEditor.Lightmapping.indirectOutputScale);
                //allGameObjects
                var gameObjectsJson = new MyJson_Array();
                sceneJson["gameObjects"] = gameObjectsJson;
                GameObject[] allObjs = GameObject.FindObjectsOfType <GameObject>();
                for (int i = 0; i < allObjs.Length; i++)
                {
                    gameObjectsJson.AddHashCode(allObjs[i]);
                }
                //lightmaps
                sceneJson["lightmaps"] = ExportSceneTools.AddLightmaps(exportPath);
                ResourceManager.instance.AddObjectJson(sceneJson);
                //序列化
                foreach (var root in roots)
                {
                    SerializeObject.Serialize(root);
                }
                ResourceManager.instance.ExportFiles(scenePath, exportPath);
                MyLog.Log("----场景导出成功----");
            }
            catch (System.Exception e)
            {
                MyLog.LogError(sceneName + "  : 导出失败-----------" + e.StackTrace);
            }
        }
 public void AddExr(string inputPath, string outPath)
 {
     if (this.taskString.Contains(inputPath))
     {
         return;
     }
     if (inputPath.Contains(" "))
     {
         MyLog.LogError("路劲=>" + inputPath + "  包含空格,请检查");
     }
     if (outPath.Contains(" "))
     {
         MyLog.LogError("路劲=>" + outPath + "  包含空格,请检查");
     }
     this.taskString.Add(inputPath);
     this.taskString.Add(outPath);
 }
        public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, UnityEngine.Color[] arr, BufferViewId bufferViewId = null, BinaryWriter writer = null)
        {
            var count = arr.Length;

            if (count == 0)
            {
                MyLog.LogError("Accessors can not have a count of 0.");
            }

            var accessor = new Accessor();

            accessor.ComponentType = GLTFComponentType.Float;
            accessor.Count         = count;
            accessor.Type          = GLTFAccessorAttributeType.VEC4;

            float minR = arr[0].r;
            float minG = arr[0].g;
            float minB = arr[0].b;
            float minA = arr[0].a;
            float maxR = arr[0].r;
            float maxG = arr[0].g;
            float maxB = arr[0].b;
            float maxA = arr[0].a;

            for (var i = 1; i < count; i++)
            {
                var cur = arr[i];

                if (cur.r < minR)
                {
                    minR = cur.r;
                }
                if (cur.g < minG)
                {
                    minG = cur.g;
                }
                if (cur.b < minB)
                {
                    minB = cur.b;
                }
                if (cur.a < minA)
                {
                    minA = cur.a;
                }
                if (cur.r > maxR)
                {
                    maxR = cur.r;
                }
                if (cur.g > maxG)
                {
                    maxG = cur.g;
                }
                if (cur.b > maxB)
                {
                    maxB = cur.b;
                }
                if (cur.a > maxA)
                {
                    maxA = cur.a;
                }
            }

            accessor.Normalized = true;
            accessor.Min        = new List <double> {
                minR, minG, minB, minA
            };
            accessor.Max = new List <double> {
                maxR, maxG, maxB, maxA
            };

            var byteOffset = writer.BaseStream.Position;

            foreach (var color in arr)
            {
                writer.Write(color.r);
                writer.Write(color.g);
                writer.Write(color.b);
                writer.Write(color.a);
            }

            var byteLength = writer.BaseStream.Position - byteOffset;

            if (bufferViewId != null)
            {
                accessor.BufferView = bufferViewId;
                accessor.ByteOffset = (int)byteOffset;
            }
            else
            {
                accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength);
            }

            var id = new AccessorId
            {
                Id   = root.Accessors.Count,
                Root = root
            };

            root.Accessors.Add(accessor);

            return(id);
        }
        public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, Vector4[] arr, BufferViewId bufferViewId = null, bool normalized = false, BinaryWriter writer = null)
        {
            var count = arr.Length;

            if (count == 0)
            {
                MyLog.LogError("Accessors can not have a count of 0.");
            }

            var accessor = new Accessor();

            accessor.ComponentType = GLTFComponentType.Float;
            accessor.Count         = count;
            accessor.Type          = GLTFAccessorAttributeType.VEC4;

            float minX = arr[0].x;
            float minY = arr[0].y;
            float minZ = arr[0].z;
            float minW = arr[0].w;
            float maxX = arr[0].x;
            float maxY = arr[0].y;
            float maxZ = arr[0].z;
            float maxW = arr[0].w;

            for (var i = 1; i < count; i++)
            {
                var cur = arr[i];

                if (cur.x < minX)
                {
                    minX = cur.x;
                }
                if (cur.y < minY)
                {
                    minY = cur.y;
                }
                if (cur.z < minZ)
                {
                    minZ = cur.z;
                }
                if (cur.w < minW)
                {
                    minW = cur.w;
                }
                if (cur.x > maxX)
                {
                    maxX = cur.x;
                }
                if (cur.y > maxY)
                {
                    maxY = cur.y;
                }
                if (cur.z > maxZ)
                {
                    maxZ = cur.z;
                }
                if (cur.w > maxW)
                {
                    maxW = cur.w;
                }
            }
            accessor.Normalized = normalized;
            accessor.Min        = new List <double> {
                minX, minY, minZ, minW
            };
            accessor.Max = new List <double> {
                maxX, maxY, maxZ, maxW
            };

            var byteOffset = writer.BaseStream.Position;

            foreach (var vec in arr)
            {
                writer.Write(vec.x);
                writer.Write(vec.y);
                writer.Write(vec.z);
                writer.Write(vec.w);
            }

            var byteLength = writer.BaseStream.Position - byteOffset;

            if (bufferViewId != null)
            {
                accessor.BufferView = bufferViewId;
                accessor.ByteOffset = (int)byteOffset;
            }
            else
            {
                accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength);
            }


            var id = new AccessorId
            {
                Id   = root.Accessors.Count,
                Root = root
            };

            root.Accessors.Add(accessor);

            return(id);
        }
        public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, Vector3[] arr, BufferViewId bufferViewId = null, bool normalized = false, Transform rootNode = null, BinaryWriter writer = null)
        {
            var count = arr.Length;

            if (count == 0)
            {
                MyLog.LogError("Accessors can not have a count of 0.");
            }

            var accessor = new Accessor();

            accessor.ComponentType = GLTFComponentType.Float;
            accessor.Count         = count;
            accessor.Type          = GLTFAccessorAttributeType.VEC3;

            /*float minX = arr[0].x;
             * float minY = arr[0].y;
             * float minZ = arr[0].z;
             * float maxX = arr[0].x;
             * float maxY = arr[0].y;
             * float maxZ = arr[0].z;
             *
             * for (var i = 1; i < count; i++)
             * {
             *  var cur = arr[i];
             *
             *  if (cur.x < minX)
             *  {
             *      minX = cur.x;
             *  }
             *  if (cur.y < minY)
             *  {
             *      minY = cur.y;
             *  }
             *  if (cur.z < minZ)
             *  {
             *      minZ = cur.z;
             *  }
             *  if (cur.x > maxX)
             *  {
             *      maxX = cur.x;
             *  }
             *  if (cur.y > maxY)
             *  {
             *      maxY = cur.y;
             *  }
             *  if (cur.z > maxZ)
             *  {
             *      maxZ = cur.z;
             *  }
             * }*/

            accessor.Normalized = normalized;
            //accessor.Min = new List<double> { minX, minY, minZ };
            //accessor.Max = new List<double> { maxX, maxY, maxZ };

            var       byteOffset = writer.BaseStream.Position;
            Matrix4x4 mA         = rootNode != null ? rootNode.localToWorldMatrix : new Matrix4x4();
            Matrix4x4 mB         = rootNode != null ? rootNode.parent.worldToLocalMatrix : new Matrix4x4();

            foreach (var vec in arr)
            {
                writer.Write(vec.x);
                writer.Write(vec.y);
                writer.Write(vec.z);
            }

            var byteLength = writer.BaseStream.Position - byteOffset;

            if (bufferViewId != null)
            {
                accessor.BufferView = bufferViewId;
                accessor.ByteOffset = (int)byteOffset;
            }
            else
            {
                accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength);
            }


            var id = new AccessorId
            {
                Id   = root.Accessors.Count,
                Root = root
            };

            root.Accessors.Add(accessor);

            return(id);
        }
        public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, int[] arr, bool isIndices = false, BinaryWriter writer = null)
        {
            var count = arr.Length;

            if (count == 0)
            {
                MyLog.LogError("Accessors can not have a count of 0.");
            }

            var accessor = new Accessor();

            accessor.Count = count;
            accessor.Type  = GLTFAccessorAttributeType.SCALAR;

            int min = arr[0];
            int max = arr[0];

            for (var i = 1; i < count; i++)
            {
                var cur = arr[i];

                if (cur < min)
                {
                    min = cur;
                }
                if (cur > max)
                {
                    max = cur;
                }
            }

            var byteOffset = writer.BaseStream.Position;

            if (max <= byte.MaxValue && min >= byte.MinValue && !isIndices)
            {
                accessor.ComponentType = GLTFComponentType.UnsignedByte;

                foreach (var v in arr)
                {
                    writer.Write((byte)v);
                }
            }
            else if (max <= sbyte.MaxValue && min >= sbyte.MinValue && !isIndices)
            {
                accessor.ComponentType = GLTFComponentType.Byte;

                foreach (var v in arr)
                {
                    writer.Write((sbyte)v);
                }
            }
            else if (max <= short.MaxValue && min >= short.MinValue && !isIndices)
            {
                accessor.ComponentType = GLTFComponentType.Short;

                foreach (var v in arr)
                {
                    writer.Write((short)v);
                }
            }
            else if (max <= ushort.MaxValue && min >= ushort.MinValue)
            {
                accessor.ComponentType = GLTFComponentType.UnsignedShort;

                foreach (var v in arr)
                {
                    writer.Write((ushort)v);
                }
            }
            else if (min >= uint.MinValue)
            {
                accessor.ComponentType = GLTFComponentType.UnsignedInt;

                foreach (var v in arr)
                {
                    writer.Write((uint)v);
                }
            }
            else
            {
                accessor.ComponentType = GLTFComponentType.Float;

                foreach (var v in arr)
                {
                    writer.Write((float)v);
                }
            }

            accessor.Min = new List <double> {
                min
            };
            accessor.Max = new List <double> {
                max
            };

            var byteLength = writer.BaseStream.Position - byteOffset;

            accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength);

            var id = new AccessorId
            {
                Id   = root.Accessors.Count,
                Root = root
            };

            root.Accessors.Add(accessor);

            return(id);
        }
        public static byte[] Export(Texture2D source)
        {
            var path           = AssetDatabase.GetAssetPath(source);
            var textureSetting = ExportSetting.instance.texture;

            MyLog.Log("---导出图片:" + source.name + " path:" + path);

            //只有jpg、png可以原始图片导出,其他类型不支持
            var fileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.dataPath), path);

            byte[] bs = null;
            if (textureSetting.useOriginalTexture && PathHelper.IsSupportedExt(source) && System.IO.File.Exists(fileName))
            {
                bs = System.IO.File.ReadAllBytes(fileName);
            }
            else
            {
                var saveTextureType = TextureImporterType.Default;
                var importer        = UnityEditor.TextureImporter.GetAtPath(path) as TextureImporter;
                if (importer)
                {
                    saveTextureType = importer.textureType;
                    if (saveTextureType == TextureImporterType.NormalMap && !textureSetting.useNormalTexture)
                    {
                        //法线贴图类型贴图因为Unity特殊处理过,如果要正常导出,就要转换一下类型
                        importer.textureType = TextureImporterType.Default;
                        importer.SaveAndReimport();
                    }
                }

                var renderTexture = RenderTexture.GetTemporary(source.width, source.height);
                Graphics.Blit(source, renderTexture);
                RenderTexture.active = renderTexture;
                var exportTexture = new Texture2D(source.width, source.height);
                exportTexture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
                exportTexture.Apply();

                try
                {
                    string ext = PathHelper.GetTextureExt(source);
                    if (ext == "jpg" || ext == "jpeg")
                    {
                        bs = exportTexture.EncodeToJPG(textureSetting.jpgQuality);
                    }
                    // else if (ext == "exr")
                    // {
                    //     bs = exportTexture.EncodeToEXR();
                    // }
                    else
                    {
                        bs = exportTexture.EncodeToPNG();
                    }
                }
                catch (System.Exception e)
                {
                    MyLog.LogError(e.StackTrace);
                    MyLog.LogError("图片导出出错:" + path + " 请保证原始资源是可读写,非压缩文件");
                }

                if (importer && importer.textureType != saveTextureType)
                {
                    importer.textureType = saveTextureType;
                    importer.SaveAndReimport();
                }
            }

            return(bs);
        }