示例#1
0
        void ExportFlatTexture()
        {
            int resolution = Resolutions[m_exportResolutionIndex];

            Color32[]        flatColors  = new Color32[resolution * resolution];
            float            sizePixel   = 1f / resolution;
            List <Texture2D> textures2D  = new List <Texture2D>();
            List <bool>      isReadables = new List <bool>();
            List <Vector2>   scales      = new List <Vector2>();
            List <Vector2>   offsets     = new List <Vector2>();
            List <Color>     tintColors  = new List <Color>();
            int flatColorIndex           = 0;

            string[,] propertiesName = m_propertiesNames;
            bool hasTintColor = m_exportTextureTypeIndex == 0 && m_material.HasProperty("_TintColor01");
            bool isNormalMap  = m_exportTextureTypeIndex == 1;

            if (m_exportTextureTypeIndex == 1)
            {
                propertiesName = NormalMapNames;
            }
            else if (m_exportTextureTypeIndex == 2)
            {
                propertiesName = HeightMapNames;
            }
            else if (m_exportTextureTypeIndex == 3)
            {
                propertiesName = IllumNames;
            }

            // Fill Texture2D List (and enable isReadable).
            for (int splatIndex = 0; splatIndex != SplatTextures.Count; ++splatIndex)
            {
                for (int texIndex = 0; texIndex != 5; ++texIndex)
                {
                    Texture2D tex2d        = null;
                    bool      isReadable   = false;
                    Color     tintColor    = Color.white;
                    Vector2   scale        = Vector2.one;
                    Vector2   offset       = Vector2.zero;
                    string    propertyName = propertiesName[splatIndex, texIndex];

                    if (hasTintColor && texIndex != 0)
                    {
                        tintColor = m_material.GetColor(TintPropertiesNames[splatIndex, texIndex]);
                    }

                    if (m_material.HasProperty(propertyName))
                    {
                        tex2d = (Texture2D)m_material.GetTexture(propertyName);

                        if (tex2d != null)
                        {
                            scale  = m_material.GetTextureScale(propertyName);
                            offset = m_material.GetTextureOffset(propertyName);
                            string          texPath  = AssetDatabase.GetAssetPath(tex2d);
                            TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(texPath);
                            isReadable          = importer.isReadable;
                            importer.isReadable = true;
                            AssetDatabase.ImportAsset(texPath);
                        }
                    }

                    tintColors.Add(tintColor);
                    isReadables.Add(isReadable);
                    textures2D.Add(tex2d);
                    offsets.Add(offset);
                    scales.Add(scale);
                }
            }

            // Set flat colors.
            for (int y = 0; y != resolution; ++y)
            {
                for (int x = 0; x != resolution; ++x)
                {
                    Color finalColor = Color.black;

                    for (int splatIndex = 0; splatIndex != SplatTextures.Count; ++splatIndex)
                    {
                        float u       = (float)x * sizePixel;
                        float v       = (float)y * sizePixel;
                        int   index00 = splatIndex * 5;
                        int   index01 = index00 + 1;
                        int   index02 = index00 + 2;
                        int   index03 = index00 + 3;
                        int   index04 = index00 + 4;

                        Color splatColor = GetPixelColor(u, v, scales[index00], offsets[index00], textures2D[index00], false);
                        Color tex01Color = GetPixelColor(u, v, scales[index01], offsets[index01], textures2D[index01], isNormalMap);
                        Color tex02Color = GetPixelColor(u, v, scales[index02], offsets[index02], textures2D[index02], isNormalMap);
                        Color tex03Color = GetPixelColor(u, v, scales[index03], offsets[index03], textures2D[index03], isNormalMap);
                        Color tex04Color = GetPixelColor(u, v, scales[index04], offsets[index04], textures2D[index04], isNormalMap);

                        if (hasTintColor)
                        {
                            finalColor += splatColor.r * tex01Color * tintColors[index01]
                                          + splatColor.g * tex02Color * tintColors[index02]
                                          + splatColor.b * tex03Color * tintColors[index03]
                                          + splatColor.a * tex04Color * tintColors[index04];
                        }
                        else
                        {
                            finalColor += splatColor.r * tex01Color
                                          + splatColor.g * tex02Color
                                          + splatColor.b * tex03Color
                                          + splatColor.a * tex04Color;
                        }
                    }

                    flatColors[flatColorIndex] = finalColor;
                    ++flatColorIndex;
                }
            }

            // Reset isReadable properties.
            for (int tex2DIndex = 0; tex2DIndex != textures2D.Count; ++tex2DIndex)
            {
                if (textures2D[tex2DIndex] != null)
                {
                    string          texPath  = AssetDatabase.GetAssetPath(textures2D[tex2DIndex]);
                    TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(texPath);
                    importer.isReadable = isReadables[tex2DIndex];
                    AssetDatabase.ImportAsset(texPath);
                }
            }

            // Export texture.
            string path = EditorUtility.SaveFilePanelInProject("Save texture", "New Flat Texture", "png", "Please enter a file name to save the texture to");

            if (!path.Equals(""))
            {
                string    assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path);
                Texture2D tex = new Texture2D(resolution, resolution, TextureFormat.RGB24, true);
                tex.SetPixels32(flatColors);
                byte[] pngData = tex.EncodeToPNG();
                File.WriteAllBytes(assetPathAndName, pngData);
                Object.DestroyImmediate(tex);
                AssetDatabase.Refresh();
                TextureImporter ti = (TextureImporter)TextureImporter.GetAtPath(assetPathAndName);
                ti.wrapMode = TextureWrapMode.Clamp;

                if (isNormalMap)
                {
                    ti.normalmap = true;
                }

                AssetDatabase.ImportAsset(assetPathAndName);
                AssetDatabase.Refresh();
            }
        }
示例#2
0
        public static bool CopyTextureToPng(string source, string dest)
        {
            AssetDatabase.DeleteAsset(dest);
            string sourceExtension = System.IO.Path.GetExtension(source);

            if (string.Compare(sourceExtension, ".png", true) != 0)
            {
                var    index = dest.LastIndexOf('/');
                string temp  = dest.Substring(0, index + 1) + "TEMP_" + dest.Substring(index + 1) + sourceExtension;
                AssetDatabase.DeleteAsset(temp);
                if (!AssetDatabase.CopyAsset(source, temp))
                {
                    Debug.LogError(string.Format("CopyTextureToPng error: Couldn't copy {0} to temp {1}", source, temp));
                    return(false);
                }
                AssetDatabase.ImportAsset(temp);
                var importer = TextureImporter.GetAtPath(temp) as TextureImporter;
                if (!importer.isReadable || importer.textureFormat != TextureImporterFormat.ARGB32)
                {
                    importer.isReadable    = true;
                    importer.textureFormat = TextureImporterFormat.ARGB32;
                    AssetDatabase.ImportAsset(temp);
                }

                var tex = AssetDatabase.LoadAssetAtPath(temp, typeof(Texture2D)) as Texture2D;
                if (tex == null)
                {
                    Debug.LogError("DAMNABBIT asset not readable: " + temp);
                    return(false);
                }

                System.IO.File.WriteAllBytes(dest, tex.EncodeToPNG());
                AssetDatabase.ImportAsset(dest);

                //var destTex = Texture2D.Instantiate(tex) as Texture2D;
                //var destTex = new Texture2D(tex.width, tex.height, tex.format, tex.mipmapCount > 0);
                //destTex.anisoLevel = tex.anisoLevel;
                //destTex.filterMode = tex.filterMode;
                //destTex.mipMapBias = tex.mipMapBias;
                //destTex.wrapMode = tex.wrapMode;
                //destTex.SetPixels32(tex.GetPixels32());
                //AssetDatabase.CreateAsset(destTex, dest);

                var tempimporter = TextureImporter.GetAtPath(temp) as TextureImporter;
                var destimporter = TextureImporter.GetAtPath(dest) as TextureImporter;

                var settings = new TextureImporterSettings();
                tempimporter.ReadTextureSettings(settings);
                destimporter.SetTextureSettings(settings);

                destimporter.normalmap  = false;
                destimporter.isReadable = true;
                AssetDatabase.ImportAsset(dest);
                AssetDatabase.DeleteAsset(temp);
            }
            else
            {
                if (!AssetDatabase.CopyAsset(source, dest))
                {
                    Debug.LogError(string.Format("CopyTextureToPng error: Couldn't copy {0} to {1}", source, dest));
                    return(false);
                }
                AssetDatabase.ImportAsset(dest);
            }
            return(true);
        }
        private void ImportSpriteSheetIntoAnimation(Texture2D spriteSheet, int animIdx = -1)
        {
            string assetPath = AssetDatabase.GetAssetPath(spriteSheet);

            if (string.IsNullOrEmpty(assetPath))
            {
                return;
            }
            TextureImporter spriteSheetImporter = (TextureImporter)TextureImporter.GetAtPath(assetPath);

            int characterNb;
            int charRowLength;
            int charColumnLength;
            int charFramesCount = m_target.DirectionsPerAnim * m_target.FramesPerAnim;
            int columns = 0, rows = 0;

            if (spriteSheetImporter.textureType != TextureImporterType.Sprite ||
                spriteSheetImporter.spriteImportMode != SpriteImportMode.Multiple ||
                spriteSheetImporter.spritesheet.Length == 0 ||
                spriteSheetImporter.spritesheet.Length % charFramesCount != 0)
            {
                Rect[] rects = InternalSpriteUtility.GenerateAutomaticSpriteRectangles(spriteSheet, 4, 0);
                if (rects.Length > 0 && rects.Length % charFramesCount == 0)
                {
                    for (; columns < rects.Length; ++columns)
                    {
                        //NOTE: the order of slicing in GenerateAutomaticSpriteRectangles is from bottom to top, not from top to bottom like Sprite Editor Slicing
                        if (rects[columns].yMin >= rects[0].yMax)
                        {
                            rows = rects.Length / columns;
                            break;
                        }
                    }
                }
                else
                {
                    columns = m_target.FramesPerAnim;
                    rows    = m_target.DirectionsPerAnim;
                }

                charRowLength    = Mathf.Max(1, columns / m_target.FramesPerAnim);
                charColumnLength = Mathf.Max(1, rows / m_target.FramesPerAnim);
                characterNb      = charRowLength * charColumnLength;

                int spriteCount = charFramesCount * characterNb;
                SpriteMetaData[] aSpriteMetaData = spriteSheetImporter.spritesheet;
                if (spriteSheetImporter.spritesheet.Length != spriteCount || spriteSheetImporter.spriteImportMode != SpriteImportMode.Multiple)
                {
                    aSpriteMetaData = new SpriteMetaData[spriteCount];
                    spriteSheetImporter.textureType      = TextureImporterType.Sprite;
                    spriteSheetImporter.spriteImportMode = SpriteImportMode.Multiple;
                    spriteSheetImporter.filterMode       = FilterMode.Point;
                    spriteSheetImporter.mipmapEnabled    = false;
#if UNITY_5_5_OR_NEWER
                    spriteSheetImporter.textureCompression = TextureImporterCompression.Uncompressed;
#else
                    spriteSheetImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;
#endif
                    Rect spriteRect = new Rect(0, 0, spriteSheet.width / (m_target.FramesPerAnim * charRowLength), spriteSheet.height / (m_target.DirectionsPerAnim * charColumnLength));
                    for (int gy = 0, spriteIdx = 0; gy < rows; ++gy)
                    {
                        for (int gx = 0; gx < columns; ++gx, ++spriteIdx)
                        {
                            spriteRect.position = new Vector2(gx * spriteRect.width, spriteSheet.height - (1 + gy) * spriteRect.height);
                            SpriteMetaData spriteMetaData = new SpriteMetaData();
                            //int characterIdx = (gy / m_target.DirectionNb) * charRowLength + (gx / m_target.FramesPerAnim);

                            //NOTE: the sprites are sorted alphabetically, so spriteIdx should be in the first place after the name and nothing else
                            spriteMetaData.name        = spriteSheet.name + "_" + spriteIdx; // + (characterNb > 1 ? ("_" + characterIdx) : "") + "_" + gy + "_" + gx;
                            spriteMetaData.rect        = spriteRect;
                            aSpriteMetaData[spriteIdx] = spriteMetaData;
                        }
                    }
                    spriteSheetImporter.spritesheet = aSpriteMetaData;
                    AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
                }
            }

            UpdateAligmentAndPivot(spriteSheet);

            List <Sprite> sprites = new List <Sprite>(AssetDatabase.LoadAllAssetsAtPath(assetPath).OfType <Sprite>().ToArray());
            //sort them properly using the last number
            sprites = sprites.OrderBy(s => int.Parse(s.name.Substring(s.name.LastIndexOf("_") + 1))).ToList();
            for (; columns < sprites.Count; ++columns)
            {
                if (sprites[columns].rect.yMax <= sprites[0].rect.yMin)
                {
                    rows = sprites.Count / columns;
                    break;
                }
            }

            if (columns * rows != sprites.Count || columns % m_target.FramesPerAnim != 0 || rows % m_target.DirectionsPerAnim != 0)
            {
                Debug.LogError("Something was wrong with the sprite sheet. Try slicing it again using the Sprite Editor using grid settings or set the Sprite Mode to single and try again.");
                return;
            }

            List <Sprite> sortedSprites = new List <Sprite>();
            charRowLength    = Mathf.Max(1, columns / m_target.FramesPerAnim);
            charColumnLength = Mathf.Max(1, rows / m_target.DirectionsPerAnim);
            for (int charY = 0; charY < charColumnLength; ++charY)
            {
                for (int charX = 0; charX < charRowLength; ++charX)
                {
                    for (int c = 0; c < m_target.DirectionsPerAnim; ++c)
                    {
                        for (int r = 0; r < m_target.FramesPerAnim; ++r)
                        {
                            int gx = charX * m_target.FramesPerAnim + r;
                            int gy = charY * m_target.DirectionsPerAnim + c;
                            sortedSprites.Add(sprites[gy * columns + gx]);
                        }
                    }
                }
            }
            characterNb = sortedSprites.Count / charFramesCount;

            if (animIdx >= 0)
            {
                ImportSpriteSheetIntoAnimation(spriteSheet, sortedSprites.Take(charFramesCount).ToArray(), animIdx, spriteSheet.name);
            }
            else
            {
                for (int characterIdx = 0; characterIdx < characterNb; ++characterIdx)
                {
                    Sprite[] characterSprites = sortedSprites.Skip(characterIdx * charFramesCount).Take(charFramesCount).ToArray();
                    string   charName         = spriteSheet.name + (characterNb > 1? ("_" + characterIdx) : "");
                    ImportSpriteSheetIntoAnimation(spriteSheet, characterSprites, m_target.GetAnimList().FindIndex(x => x.name == charName), charName);
                }
            }
        }
        private Texture RenderCubemapToTexture(Cubemap cubemap, int faceSize, Color clearColor,
                                               TextureFormat textureFormat, bool exportFaces, string assetPathPrefix, bool alphaIsTransparency)
        {
            CubeFaceData[] faces =
            {
                new CubeFaceData(CubemapFace.NegativeX, new Vector2(0,            faceSize)),
                new CubeFaceData(CubemapFace.PositiveX, new Vector2(faceSize * 2, faceSize)),
                new CubeFaceData(CubemapFace.PositiveY, new Vector2(faceSize,     faceSize * 2)),
                new CubeFaceData(CubemapFace.NegativeY, new Vector2(faceSize,                0)),
                new CubeFaceData(CubemapFace.PositiveZ, new Vector2(faceSize,     faceSize)),
                new CubeFaceData(CubemapFace.NegativeZ, new Vector2(faceSize * 3, faceSize))
            };

            RenderTexture oldRt = RenderTexture.active;

            Texture2D     faceTex       = new Texture2D(faceSize, faceSize, TextureFormat.RGBA32, false);
            RenderTexture faceRenderTex = new RenderTexture(faceSize, faceSize, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);

            faceRenderTex.Create();

            RenderTexture flatCubeTex = new RenderTexture(faceSize * 4, faceSize * 3, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);

            flatCubeTex.Create();

            Material flipMat = new Material(Shader.Find("Funly/Sky Studio/Utility/Flip Image"));
            Material blitMat = new Material(Shader.Find("Unlit/Transparent"));

            RenderTexture.active = flatCubeTex;
            GL.PushMatrix();
            GL.LoadPixelMatrix(0, flatCubeTex.width, flatCubeTex.height, 0);
            GL.Clear(true, true, new Color(0.0f, 0.0f, 0.0f, 0.0f));
            GL.PopMatrix();
            RenderTexture.active = null;

            for (int i = 0; i < faces.Length; i++)
            {
                CubeFaceData data = faces[i];

                // Pull a face texture out of the cubemap.
                Color[] pixels = cubemap.GetPixels(data.face);
                faceTex.SetPixels(pixels);
                faceTex.Apply();

                // Flip the image.
                RenderTexture.active = faceRenderTex;
                GL.PushMatrix();
                GL.LoadPixelMatrix(0, faceRenderTex.width, flatCubeTex.height, 0);
                Graphics.Blit(faceTex, faceRenderTex, flipMat, 0);
                GL.PopMatrix();

                if (exportFaces)
                {
                    string path = assetPathPrefix + data.face.ToString() + ".png";
                    SkyEditorUtility.WriteTextureToFile(faceRenderTex, path, textureFormat);
                    RenderTexture.active = null;
                    AssetDatabase.ImportAsset(path);
                }
                RenderTexture.active = null;

                // Target our cubemap, and render the flipped face into it.
                RenderTexture.active = flatCubeTex;
                GL.PushMatrix();
                GL.LoadPixelMatrix(0, flatCubeTex.width, flatCubeTex.height, 0);
                Graphics.DrawTexture(new Rect(data.offset.x, data.offset.y, faceSize, faceSize), faceRenderTex, blitMat);

                // Write the final texture on last face.
                if (i == faces.Length - 1)
                {
                    string path = assetPathPrefix + ".png";
                    Debug.Log("Exporting cubemap to compressed texture at path: " + path);
                    SkyEditorUtility.WriteTextureToFile(flatCubeTex, path, textureFormat);
                    RenderTexture.active = null;
                    AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);

                    // Adjust texture settings.
                    TextureImporter importer = TextureImporter.GetAtPath(path) as TextureImporter;
                    importer.textureShape        = TextureImporterShape.TextureCube;
                    importer.alphaIsTransparency = alphaIsTransparency;
                    AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                }

                GL.PopMatrix();
                RenderTexture.active = null;
            }

            RenderTexture.active = oldRt;

            return(flatCubeTex);
        }
示例#5
0
    void OnGUI()
    {
        EditorGUILayout.HelpBox(
            @"本工具是用来反向查找依赖的
比如找到依赖某个贴图a的所有预制体b
使用方法:把被依赖的资源a和要查找的目录拖到进来,点查找即可显示所有依赖资源b
这里要传一个目录是为了节省查找时间,不过目录包含东西越多查找越慢
默认查找 prefab, unity, mat, asset

如果想正向查找依赖
比如找到某预制体用到的所有资源
那么只要右键这个预制体菜单选“select dependencis ”就可以了
", MessageType.Info);
        prefab4CheckAltas = EditorGUILayout.ObjectField("prefab检查图集", prefab4CheckAltas, typeof(object), false);

        if (prefab4CheckAltas != null && GUILayout.Button("查找图集引用"))
        {
            GameObject prefab = prefab4CheckAltas as GameObject;
            //找出下面所有的Image
            Image[]   images      = prefab.GetComponentsInChildren <Image>(true);
            Texture2D packTexture = images[0].sprite.texture;
        }

        res        = EditorGUILayout.ObjectField("被依赖资源", res, typeof(object), false);
        replaceRes = EditorGUILayout.ObjectField("替换为这个资源", replaceRes, typeof(object), false);
        destDir    = EditorGUILayout.ObjectField("要查找的目录", destDir, typeof(Object), false);

        findSpritePackingTag = EditorGUILayout.TextField("要查找的SpritePackingTag", findSpritePackingTag);
        Repaint();

        string resPath = AssetDatabase.GetAssetPath(res);
        string resGuid = AssetDatabase.AssetPathToGUID(resPath);

        string replacePath = "";
        string replaceGuid = "";

        if (replaceRes != null && replaceRes != res)
        {
            replacePath = AssetDatabase.GetAssetPath(replaceRes);
            replaceGuid = AssetDatabase.AssetPathToGUID(replacePath);
        }

        if (GUILayout.Button("查找设置了SpritePackingTag的图片"))
        {
            //目录下所有的文件
            string[] arryRelativelyFilesPath = Directory.GetFiles(
                AssetDatabase.GetAssetPath(destDir), "*.*", SearchOption.AllDirectories);
            //Debug.LogError(string.Join("\n", files));

            EditorUtility.DisplayCancelableProgressBar("查找不合规资源中...", destDir.name, 0f);

            int i     = 0;
            int total = arryRelativelyFilesPath.Length;
            foreach (string relativelyFilePath in arryRelativelyFilesPath)
            {
                ++i;

                EditorUtility.DisplayCancelableProgressBar("查找不合规资源中...", relativelyFilePath.ToString(), 1f * i / total);

                if (!relativelyFilePath.EndsWith(".png") &&
                    !relativelyFilePath.EndsWith(".tga") &&
                    !relativelyFilePath.EndsWith(".jpg"))
                {
                    continue;
                }

                TextureImporter importer = TextureImporter.GetAtPath(relativelyFilePath) as TextureImporter;
                if (importer == null)
                {
                    continue;
                }

                if (importer.spritePackingTag == findSpritePackingTag)
                {
                    Object obj  = AssetDatabase.LoadMainAssetAtPath(relativelyFilePath);
                    string show = "null";
                    if (findSpritePackingTag != "")
                    {
                        show = findSpritePackingTag;
                    }
                    Debug.Log("pack tag:" + show + " " + relativelyFilePath, obj);
                }
            }

            EditorUtility.ClearProgressBar();
        }



        //长宽比例超过1:3
        //长,或宽超过400
        //大小超过200KB
        if (GUILayout.Button("查找不合规资源"))
        {
            //目录下所有的文件
            string[] arryRelativelyFilesPath = Directory.GetFiles(AssetDatabase.GetAssetPath(destDir), "*.*", SearchOption.AllDirectories);
            //Debug.LogError(string.Join("\n", files));

            EditorUtility.DisplayCancelableProgressBar("查找不合规资源中...", destDir.name, 0f);

            int i     = 0;
            int total = arryRelativelyFilesPath.Length;
            foreach (string relativelyFilePath in arryRelativelyFilesPath)
            {
                ++i;

                EditorUtility.DisplayCancelableProgressBar("查找不合规资源中...", relativelyFilePath.ToString(), 1f * i / total);

                if (!relativelyFilePath.EndsWith(".png") &&
                    !relativelyFilePath.EndsWith(".tga") &&
                    !relativelyFilePath.EndsWith(".jpg"))
                {
                    continue;
                }

                TextureImporter importer = TextureImporter.GetAtPath(relativelyFilePath) as TextureImporter;


                if (importer == null)
                {
                    continue;
                }
            }

            EditorUtility.ClearProgressBar();
        }

        if (GUILayout.Button("查找"))
        {
            objs.Clear();
            objs4EditorShow.Clear();

#if UNITY_EDITOR_OSX
            string appDataPath = Application.dataPath;
            string output      = "";
            //resPath = AssetDatabase.GetAssetPath(res);
            if (res == null)
            {
                resPath = AssetDatabase.GetAssetPath(Selection.activeObject);
            }

            List <string> references = new List <string>();

            resGuid = AssetDatabase.AssetPathToGUID(resPath);

            var psi = new System.Diagnostics.ProcessStartInfo();
            psi.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Maximized;
            psi.FileName               = "/usr/bin/mdfind";
            psi.Arguments              = "-onlyin " + Application.dataPath + " " + resGuid;
            psi.UseShellExecute        = false;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError  = true;

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo = psi;

            process.OutputDataReceived += (sender, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                {
                    return;
                }

                string relativePath = "Assets" + e.Data.Replace(appDataPath, "");

                // skip the meta file of whatever we have selected
                if (relativePath == resPath + ".meta")
                {
                    return;
                }

                references.Add(relativePath);
            };
            process.ErrorDataReceived += (sender, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                {
                    return;
                }

                output += "Error: " + e.Data + "\n";
            };
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            process.WaitForExit(2000);

            foreach (var file in references)
            {
                output += file + "\n";
                Object obj = AssetDatabase.LoadMainAssetAtPath(file);
                Debug.Log(file, obj);

                objs4EditorShow.Add(obj);

                string fullpath = Application.dataPath.Remove(Application.dataPath.Length - 7, 7) + "/" + file.Replace("\\", "/");
                objs.Add(obj, fullpath);
            }

            Debug.LogWarning(references.Count + " references found for object " + res.name + "\n\n" + output);
#else
            //目录下所有的文件
            var files = Directory.GetFiles(AssetDatabase.GetAssetPath(destDir), "*.*", SearchOption.AllDirectories);
            //Debug.LogError(string.Join("\n", files));

            EditorUtility.DisplayCancelableProgressBar(res.name + " 查找依赖中...", resPath, 0f);

            int i     = 0;
            int total = files.Length;
            foreach (var file in files)
            {
                ++i;

                EditorUtility.DisplayCancelableProgressBar(res.name + " 查找依赖中...", file.ToString(), 1f * i / total);

                if (!file.EndsWith(".prefab") &&
                    !file.EndsWith(".mat") &&
                    !file.EndsWith(".unity") &&
                    !file.EndsWith(".asset"))
                {
                    continue;
                }

                var depends = AssetDatabase.GetDependencies(new string[] { file });
                if (-1 == System.Array.IndexOf(depends, resPath))
                {
                    continue;
                }

                string fullpath = Application.dataPath.Remove(Application.dataPath.Length - 7, 7) + "/" + file.Replace("\\", "/");
                objs4EditorShow.Add(AssetDatabase.LoadMainAssetAtPath(file));
                objs.Add(AssetDatabase.LoadMainAssetAtPath(file), fullpath);
            }

            EditorUtility.ClearProgressBar();
#endif
        }

#if UNITY_EDITOR_OSX
        //检查无引用资源
        if (destDir != null && GUILayout.Button("检查无效资源(only for mac)"))
        {
            try
            {
                string appDataPath = Application.dataPath;
                string output      = "";

                List <string> references = new List <string>();

                //遍历查找
                EditorUtility.DisplayCancelableProgressBar("查找路径无引用资源中...", destDir.name, 0f);

                //目录下所有的文件
                string[] files = Directory.GetFiles(AssetDatabase.GetAssetPath(destDir), "*.*", SearchOption.AllDirectories);

                int i     = 0;
                int total = files.Length;
                foreach (string fileRelativelyPath in files)
                {
                    ++i;

                    EditorUtility.DisplayCancelableProgressBar("查找路径无引用资源中...", fileRelativelyPath, 1f * i / total);

                    if (fileRelativelyPath.EndsWith(".meta") ||
                        fileRelativelyPath.EndsWith(".DS_Store"))
                    {
                        continue;
                    }

                    //首先找到对应的guid
                    resGuid = AssetDatabase.AssetPathToGUID(fileRelativelyPath.Replace("\\", "/"));

                    //设置查找数据
                    var psi = new System.Diagnostics.ProcessStartInfo();
                    psi.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Maximized;
                    psi.FileName               = "/usr/bin/mdfind";
                    psi.Arguments              = "-onlyin " + Application.dataPath + " " + resGuid;
                    psi.UseShellExecute        = false;
                    psi.RedirectStandardOutput = true;
                    psi.RedirectStandardError  = true;

                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo = psi;

                    //清空
                    references.Clear();

                    process.OutputDataReceived += (sender, e) =>
                    {
                        if (string.IsNullOrEmpty(e.Data))
                        {
                            return;
                        }

                        string relativePath = "Assets" + e.Data.Replace(appDataPath, "");

                        // skip the meta file of whatever we have selected
                        if (relativePath == fileRelativelyPath + ".meta")
                        {
                            return;
                        }

                        references.Add(relativePath);
                    };
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (string.IsNullOrEmpty(e.Data))
                        {
                            return;
                        }

                        output += "Error: " + e.Data + "\n";
                    };
                    process.Start();
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    process.WaitForExit(2000);

                    if (references.Count <= 0)
                    {
                        Object obj = AssetDatabase.LoadMainAssetAtPath(fileRelativelyPath);
                        Debug.Log(references.Count + " references found for object " + fileRelativelyPath + "\n\n" + output, obj);
                        return;
                    }
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError("查找无效资源出错 " + ex.ToString());
            }

            EditorUtility.ClearProgressBar();
        }
#endif

        if (replaceGuid != "" && replaceRes != res && objs.Count != 0 && GUILayout.Button("替换"))
        {
            bool bReplaced = false;
            foreach (var item in objs)
            {
                //如果是指向自己, 则跳过
                if (item.Key.name == res.name)
                {
                    continue;
                }

                string       path = item.Value;
                FileStream   fs   = new FileStream(path, FileMode.Open, FileAccess.Read);
                StreamReader sr   = new StreamReader(fs);
                string       con  = sr.ReadToEnd();
                if (con.IndexOf(resGuid) < 0)
                {
                    sr.Close();
                    fs.Close();
                    continue;
                }

                con = con.Replace(resGuid, replaceGuid);
                sr.Close();
                fs.Close();

                FileStream   fs2 = new FileStream(path, FileMode.Open, FileAccess.Write);
                StreamWriter sw  = new StreamWriter(fs2);
                sw.WriteLine(con);
                sw.Close();
                fs2.Close();

                Debug.Log(string.Format("{0} replace <{1}> to <{2}> suc!", item.Key.name, res.name, replaceRes.name));

                bReplaced = true;
            }

            if (bReplaced)
            {
                AssetDatabase.Refresh();
                bReplaced = false;
            }
        }

        foreach (var obj in objs4EditorShow)
        {
            EditorGUILayout.ObjectField(obj, typeof(Object), false);
        }
    }
示例#6
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            string     sceneName = null;
            GameObject gltfScene = null;

            UnityEngine.Mesh[] meshes = null;
            try
            {
                sceneName = Path.GetFileNameWithoutExtension(ctx.assetPath);
                gltfScene = CreateGLTFScene(ctx.assetPath);

                // Remove empty roots
                if (_removeEmptyRootObjects)
                {
                    var t = gltfScene.transform;
                    while (
                        gltfScene.transform.childCount == 1 &&
                        gltfScene.GetComponents <Component>().Length == 1)
                    {
                        var parent = gltfScene;
                        gltfScene = gltfScene.transform.GetChild(0).gameObject;
                        t         = gltfScene.transform;
                        t.parent  = null;                // To keep transform information in the new parent
                        Object.DestroyImmediate(parent); // Get rid of the parent
                    }
                }

                // Ensure there are no hide flags present (will cause problems when saving)
                gltfScene.hideFlags &= ~(HideFlags.HideAndDontSave);
                foreach (Transform child in gltfScene.transform)
                {
                    child.gameObject.hideFlags &= ~(HideFlags.HideAndDontSave);
                }

                // Zero position
                gltfScene.transform.position = Vector3.zero;

                // Get meshes
                var meshNames    = new List <string>();
                var meshHash     = new HashSet <UnityEngine.Mesh>();
                var meshFilters  = gltfScene.GetComponentsInChildren <MeshFilter>();
                var vertexBuffer = new List <Vector3>();
                meshes = meshFilters.Select(mf =>
                {
                    var mesh = mf.sharedMesh;
                    vertexBuffer.Clear();
                    mesh.GetVertices(vertexBuffer);
                    for (var i = 0; i < vertexBuffer.Count; ++i)
                    {
                        vertexBuffer[i] *= _scaleFactor;
                    }
                    mesh.SetVertices(vertexBuffer);
                    if (_swapUvs)
                    {
                        var uv   = mesh.uv;
                        var uv2  = mesh.uv2;
                        mesh.uv  = uv2;
                        mesh.uv2 = uv2;
                    }
                    if (_importNormals == GLTFImporterNormals.None)
                    {
                        mesh.normals = new Vector3[0];
                    }
                    if (_importNormals == GLTFImporterNormals.Calculate)
                    {
                        mesh.RecalculateNormals();
                    }
                    mesh.UploadMeshData(!_readWriteEnabled);

                    if (_generateColliders)
                    {
                        var collider        = mf.gameObject.AddComponent <MeshCollider>();
                        collider.sharedMesh = mesh;
                    }

                    if (meshHash.Add(mesh))
                    {
                        var meshName = string.IsNullOrEmpty(mesh.name) ? mf.gameObject.name : mesh.name;
                        mesh.name    = ObjectNames.GetUniqueName(meshNames.ToArray(), meshName);
                        meshNames.Add(mesh.name);
                    }

                    return(mesh);
                }).ToArray();

                var renderers = gltfScene.GetComponentsInChildren <Renderer>();

                if (_importMaterials)
                {
                    // Get materials
                    var materialNames = new List <string>();
                    var materialHash  = new HashSet <UnityEngine.Material>();
                    var materials     = renderers.SelectMany(r =>
                    {
                        return(r.sharedMaterials.Select(mat =>
                        {
                            if (materialHash.Add(mat))
                            {
                                var matName = string.IsNullOrEmpty(mat.name) ? mat.shader.name : mat.name;
                                if (matName == mat.shader.name)
                                {
                                    matName = matName.Substring(Mathf.Min(matName.LastIndexOf("/") + 1, matName.Length - 1));
                                }

                                // Ensure name is unique
                                matName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(matName));
                                matName = ObjectNames.GetUniqueName(materialNames.ToArray(), matName);

                                mat.name = matName;
                                materialNames.Add(matName);
                            }

                            return mat;
                        }));
                    }).ToArray();

                    // Get textures
                    var textureNames   = new List <string>();
                    var textureHash    = new HashSet <Texture2D>();
                    var texMaterialMap = new Dictionary <Texture2D, List <TexMaterialMap> >();
                    var textures       = materials.SelectMany(mat =>
                    {
                        var shader = mat.shader;
                        if (!shader)
                        {
                            return(Enumerable.Empty <Texture2D>());
                        }

                        var matTextures = new List <Texture2D>();
                        for (var i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i)
                        {
                            if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
                            {
                                var propertyName = ShaderUtil.GetPropertyName(shader, i);
                                var tex          = mat.GetTexture(propertyName) as Texture2D;
                                if (tex)
                                {
                                    if (textureHash.Add(tex))
                                    {
                                        var texName = tex.name;
                                        if (string.IsNullOrEmpty(texName))
                                        {
                                            if (propertyName.StartsWith("_"))
                                            {
                                                texName = propertyName.Substring(Mathf.Min(1, propertyName.Length - 1));
                                            }
                                        }

                                        // Ensure name is unique
                                        texName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(texName));
                                        texName = ObjectNames.GetUniqueName(textureNames.ToArray(), texName);

                                        tex.name = texName;
                                        textureNames.Add(texName);
                                        matTextures.Add(tex);
                                    }

                                    List <TexMaterialMap> materialMaps;
                                    if (!texMaterialMap.TryGetValue(tex, out materialMaps))
                                    {
                                        materialMaps = new List <TexMaterialMap>();
                                        texMaterialMap.Add(tex, materialMaps);
                                    }

                                    materialMaps.Add(new TexMaterialMap(mat, propertyName, propertyName == "_BumpMap"));
                                }
                            }
                        }
                        return(matTextures);
                    }).ToArray();

                    var folderName = Path.GetDirectoryName(ctx.assetPath);

                    // Save textures as separate assets and rewrite refs
                    // TODO: Support for other texture types
                    if (textures.Length > 0)
                    {
                        var texturesRoot = string.Concat(folderName, "/", "Textures/");
                        Directory.CreateDirectory(texturesRoot);

                        foreach (var tex in textures)
                        {
                            var ext     = _useJpgTextures ? ".jpg" : ".png";
                            var texPath = string.Concat(texturesRoot, tex.name, ext);
                            File.WriteAllBytes(texPath, _useJpgTextures ? tex.EncodeToJPG() : tex.EncodeToPNG());

                            AssetDatabase.ImportAsset(texPath);
                        }
                    }

                    // Save materials as separate assets and rewrite refs
                    if (materials.Length > 0)
                    {
                        var materialRoot = string.Concat(folderName, "/", "Materials/");
                        Directory.CreateDirectory(materialRoot);

                        foreach (var mat in materials)
                        {
                            var materialPath = string.Concat(materialRoot, mat.name, ".mat");
                            var newMat       = mat;
                            CopyOrNew(mat, materialPath, m =>
                            {
                                // Fix references
                                newMat = m;
                                foreach (var r in renderers)
                                {
                                    var sharedMaterials = r.sharedMaterials;
                                    for (var i = 0; i < sharedMaterials.Length; ++i)
                                    {
                                        var sharedMaterial = sharedMaterials[i];
                                        if (sharedMaterial.name == mat.name)
                                        {
                                            sharedMaterials[i] = m;
                                        }
                                    }
                                    sharedMaterials   = sharedMaterials.Where(sm => sm).ToArray();
                                    r.sharedMaterials = sharedMaterials;
                                }
                            });
                            // Fix textures
                            // HACK: This needs to be a delayed call.
                            // Unity needs a frame to kick off the texture import so we can rewrite the ref
                            if (textures.Length > 0)
                            {
                                EditorApplication.delayCall += () =>
                                {
                                    for (var i = 0; i < textures.Length; ++i)
                                    {
                                        var tex          = textures[i];
                                        var texturesRoot = string.Concat(folderName, "/", "Textures/");
                                        var ext          = _useJpgTextures ? ".jpg" : ".png";
                                        var texPath      = string.Concat(texturesRoot, tex.name, ext);

                                        // Grab new imported texture
                                        var materialMaps = texMaterialMap[tex];
                                        var importer     = (TextureImporter)TextureImporter.GetAtPath(texPath);
                                        var importedTex  = AssetDatabase.LoadAssetAtPath <Texture2D>(texPath);
                                        if (importer != null)
                                        {
                                            var isNormalMap = false;
                                            foreach (var materialMap in materialMaps)
                                            {
                                                if (materialMap.Material == mat)
                                                {
                                                    isNormalMap |= materialMap.IsNormalMap;
                                                    newMat.SetTexture(materialMap.Property, importedTex);
                                                }
                                            }
                                            ;

                                            if (isNormalMap)
                                            {
                                                // Try to auto-detect normal maps
                                                importer.textureType = TextureImporterType.NormalMap;
                                            }
                                            else if (importer.textureType == TextureImporterType.Sprite)
                                            {
                                                // Force disable sprite mode, even for 2D projects
                                                importer.textureType = TextureImporterType.Default;
                                            }

                                            importer.SaveAndReimport();
                                        }
                                        else
                                        {
                                            Debug.LogWarning(string.Format("GLTFImporter: Unable to import texture at path: {0}", texPath));
                                        }
                                    }
                                };
                            }
                        }
                    }
                }
                else
                {
                    var temp = GameObject.CreatePrimitive(PrimitiveType.Plane);
                    temp.SetActive(false);
                    var defaultMat = new[] { temp.GetComponent <Renderer>().sharedMaterial };
                    DestroyImmediate(temp);

                    foreach (var rend in renderers)
                    {
                        rend.sharedMaterials = defaultMat;
                    }
                }
            }
            catch
            {
                if (gltfScene)
                {
                    DestroyImmediate(gltfScene);
                }
                throw;
            }

#if UNITY_2017_3_OR_NEWER
            // Set main asset
            ctx.AddObjectToAsset("main asset", gltfScene);

            // Add meshes
            foreach (var mesh in meshes)
            {
                ctx.AddObjectToAsset("mesh " + mesh.name, mesh);
            }

            ctx.SetMainObject(gltfScene);
#else
            // Set main asset
            ctx.SetMainAsset("main asset", gltfScene);

            // Add meshes
            foreach (var mesh in meshes)
            {
                ctx.AddSubAsset("mesh " + mesh.name, mesh);
            }
#endif
        }
示例#7
0
    static public void PackAndOutputSprites(Texture2D[] texs, string atlasAssetPath, string outputPath)
    {
        Texture2D atlas = new Texture2D(1, 1);

        Rect[] rs = atlas.PackTextures(texs, (int)padding, (int)matAtlasSize);//添加多个图片到一个图集中,返回值是每个图片在图集(大图片)中的U坐标等信息
        // 把图集写入到磁盘文件,最终在磁盘上会有一个图片生成,这个图片包含了很多小图片
        File.WriteAllBytes(outputPath, atlas.EncodeToPNG());
        RefreshAsset(atlasAssetPath);//刷新图片

        //记录图片的名字,只是用于输出日志用;
        StringBuilder names = new StringBuilder();

        //SpriteMetaData结构可以让我们编辑图片的一些信息,像图片的name,包围盒border,在图集中的区域rect等
        SpriteMetaData[] sheet = new SpriteMetaData[rs.Length];
        for (var i = 0; i < sheet.Length; i++)
        {
            SpriteMetaData meta = new SpriteMetaData();
            meta.name = texs[i].name;
            meta.rect = rs[i];//这里的rect记录的是单个图片在图集中的uv坐标值
            //因为rect最终需要记录单个图片在大图片图集中所在的区域rect,所以我们做如下的处理
            meta.rect.Set(
                meta.rect.x * atlas.width,
                meta.rect.y * atlas.height,
                meta.rect.width * atlas.width,
                meta.rect.height * atlas.height
                );
            //如果图片有包围盒信息的话
            var spriteInfo = GetSpriteMetaData(meta.name);
            if (spriteInfo != null)
            {
                meta.border = spriteInfo.spriteBorder;
                meta.pivot  = spriteInfo.spritePivot;
            }
            sheet[i] = meta;
            //打印日志用
            names.Append(meta.name);
            if (i < sheet.Length - 1)
            {
                names.Append(",");
            }
        }

        //设置图集的信息
        TextureImporter imp = TextureImporter.GetAtPath(atlasAssetPath) as TextureImporter;

        imp.textureType         = TextureImporterType.Sprite; //图集的类型
        imp.textureShape        = TextureImporterShape.Texture2D;
        imp.spriteImportMode    = SpriteImportMode.Multiple;  //Multiple表示我们这个大图片(图集)中包含很多小图片
        imp.ignorePngGamma      = false;
        imp.alphaIsTransparency = true;
        imp.mipmapEnabled       = false;//是否开启mipmap
        imp.isReadable          = false;
        imp.sRGBTexture         = true;
        imp.compressionQuality  = (int)TextureCompressionQuality.Normal;
        imp.spritesheet         = sheet;//设置图集中小图片的信息(每个图片所在的区域rect等)
        TextureImporterPlatformSettings setParam = new TextureImporterPlatformSettings();

#if UNITY_IOS
        //ios版本
        setParam = importer.GetPlatformTextureSettings("iOS");
        setParam.maxTextureSize       = 2048;
        setParam.overridden           = true;
        setParam.allowsAlphaSplitting = true;
        setParam.format = TextureImporterFormat.ASTC_4x4;
        imp.SetPlatformTextureSettings(setParam);
#else
        //安卓版本
        setParam = imp.GetPlatformTextureSettings("Android");  //必须用Get方法得到,否则Override for Android不会被设为true
        setParam.maxTextureSize       = 2048;
        setParam.overridden           = true;
        setParam.allowsAlphaSplitting = true;
        setParam.format = TextureImporterFormat.ASTC_4x4;
        imp.SetPlatformTextureSettings(setParam);
#endif
        // 保存并刷新
        imp.SaveAndReimport();
        spriteList.Clear();
        //输出日志
        Debug.Log("Atlas create ok. " + names.ToString());
        //打出图集后在Unity选中它
        EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(atlasAssetPath, typeof(Texture)));
    }
示例#8
0
    public bool PackTextures(int index)
    {
#if !UNITY_WEBPLAYER
        int         decalCount = decalGroups[index].decals.Count;
        Texture2D[] imgs       = new Texture2D[decalCount];

        for (int i = 0; i < decalCount; i++)
        {
            imgs[i] = decalGroups[index].decals[i].texture;

            string          path            = AssetDatabase.GetAssetPath(imgs[i]);
            TextureImporter textureImporter = (TextureImporter)TextureImporter.GetAtPath(path);
            textureImporter.isReadable    = true;
            textureImporter.textureFormat = TextureImporterFormat.ARGB32;
            AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
        }

        int maxAtlasSize = 8192;

        Texture2D packedTexture = new Texture2D(maxAtlasSize, maxAtlasSize, TextureFormat.ARGB32, true);
        packedTexture.name = decalGroups[index].name;
        Rect[] coordinates = packedTexture.PackTextures(imgs, decalGroups[index].padding, maxAtlasSize, false);

        if (coordinates == null)
        {
            return(false);
        }

        for (int i = 0; i < decalCount; i++)
        {
            decalGroups[index].decals[i].atlasRect = coordinates[i];
            decalGroups[index].decals[i].isPacked  = true;
        }

        decalGroups[index].isPacked = true;

        byte[] png = packedTexture.EncodeToPNG();

        if (!Directory.Exists(DECALSHEETS_PATH))
        {
            Directory.CreateDirectory(DECALSHEETS_PATH);
        }

        if (decalGroups[index].material == null)
        {
            string matPath = AssetDatabase.GenerateUniqueAssetPath(DECALSHEETS_PATH + decalGroups[index].name + ".mat");

            Material mat = new Material(decalGroups[index].shader);
            AssetDatabase.CreateAsset(mat, matPath);

            decalGroups[index].material = mat;
        }
        else
        {
            if (decalGroups[index].material.name != decalGroups[index].name)
            {
                string matPath = AssetDatabase.GetAssetPath(decalGroups[index].material);
                AssetDatabase.RenameAsset(matPath, decalGroups[index].name);
            }
        }

        string pngPath;

        if (decalGroups[index].material != null && decalGroups[index].material.mainTexture != null)
        {
            pngPath = AssetDatabase.GetAssetPath(decalGroups[index].material.mainTexture);
        }
        else
        {
            pngPath = AssetDatabase.GenerateUniqueAssetPath(DECALSHEETS_PATH + decalGroups[index].name + ".png");
        }

        // http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension%28v=vs.110%29.aspx
        File.WriteAllBytes(pngPath, png);

        string curName = Path.GetFileNameWithoutExtension(pngPath);

        if (curName != decalGroups[index].name)
        {
            AssetDatabase.RenameAsset(pngPath, decalGroups[index].name);
        }

        AssetDatabase.Refresh();

        decalGroups[index].material.mainTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(pngPath, typeof(Texture2D));

        return(true);
#else
        return(false);
#endif
    }
        void UVPreviewWindow(Rect rect)
        {
            Event e         = Event.current;
            int   controlID = GUIUtility.GetControlID(s_UVPreviewWindowHash, FocusType.Passive, rect);

            switch (e.GetTypeForControl(controlID))
            {
            case EventType.MouseDown:
                if (rect.Contains(e.mousePosition) && e.alt)
                {
                    if (e.button == 0 || e.button == 1 || e.button == 2)
                    {
                        GUI.changed = true;

                        GUIUtility.keyboardControl = controlID;
                        GUIUtility.hotControl      = controlID;
                        e.Use();
                    }
                }
                break;

            case EventType.MouseUp:
                if (GUIUtility.hotControl == controlID)
                {
                    GUIUtility.hotControl = 0;
                    e.Use();
                }
                break;

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == controlID && e.alt)
                {
                    GUI.changed = true;

                    if (e.button == 0 || e.button == 2)
                    {
                        previewWindowPosition += new Vector2(e.delta.x, -e.delta.y) * (2.0f / rect.width) / previewWindowScale;
                    }

                    if (e.button == 1)
                    {
                        float aspect = Mathf.Min(viewportSize.x, viewportSize.y) / Mathf.Max(viewportSize.x, viewportSize.y, 1f);
                        previewWindowScale += e.delta.magnitude / aspect * Mathf.Sign(Vector2.Dot(e.delta, new Vector2(1.0f, 0.0f))) * (2.0f / rect.width) * (previewWindowScale) * 0.5f;
                        previewWindowScale  = Mathf.Max(previewWindowScale, 0.01f);
                    }

                    e.Use();
                }
                break;

            case EventType.ScrollWheel:
                if (rect.Contains(e.mousePosition))
                {
                    GUI.changed = true;

                    float aspect = Mathf.Min(viewportSize.x, viewportSize.y) / Mathf.Max(viewportSize.x, viewportSize.y, 1f);

                    previewWindowScale += e.delta.magnitude / aspect * Mathf.Sign(Vector2.Dot(e.delta, new Vector2(1.0f, -0.1f).normalized)) * (2.0f / rect.width) * (previewWindowScale) * 5.5f;
                    previewWindowScale  = Mathf.Max(previewWindowScale, 0.01f);

                    e.Use();
                }
                break;

            case EventType.Repaint:
            {
                GUI.BeginGroup(rect);


                Rect viewportRect = rect;

                viewportRect.position = viewportRect.position - scroolPosition;                        // apply scroll

                // clamp rect position zero
                if (viewportRect.position.x < 0f)
                {
                    viewportRect.width   += viewportRect.position.x;   // -= abs(x)
                    viewportRect.position = new Vector2(0f, viewportRect.position.y);

                    if (viewportRect.width <= 0f)
                    {
                        break;
                    }
                }
                if (viewportRect.position.y < 0f)
                {
                    viewportRect.height  += viewportRect.position.y;    // -= abs(y)
                    viewportRect.position = new Vector2(viewportRect.position.x, 0f);

                    if (viewportRect.height <= 0f)
                    {
                        break;
                    }
                }

                viewportSize = rect.size;     // save size

                // convert gui to screen coord
                Rect screenViewportRect = viewportRect;
                screenViewportRect.y = this.position.height - screenViewportRect.y - screenViewportRect.height;

                                        #if (UNITY_5_4_OR_NEWER)
                GL.Viewport(EditorGUIUtility.PointsToPixels(screenViewportRect));
                                        #else
                GL.Viewport(screenViewportRect);
                                        #endif
                GL.PushMatrix();

                // Clear bg
                {
                    GL.LoadIdentity();
                    GL.LoadProjectionMatrix(Matrix4x4.Ortho(0f, 1f, 0f, 1f, -1f, 1f));

                    SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", false);
                    SetMaterialKeyword(simpleMaterial, "_NORMALMAP", false);
                    simpleMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    simpleMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    simpleMaterial.SetTexture("_MainTex", null);
                    simpleMaterial.SetColor("_Color", Color.white);
                    simpleMaterial.SetPass(0);

                    GL.Begin(GL.TRIANGLE_STRIP);
                    GL.Color(Styles.backgroundColor);
                    GL.Vertex3(1, 0, 0);
                    GL.Vertex3(0, 0, 0);
                    GL.Vertex3(1, 1, 0);
                    GL.Vertex3(0, 1, 0);
                    GL.End();
                }

                GL.LoadIdentity();
                //float aspect = Mathf.Min(GUIUtility.ScreenToGUIRect(this.position).height - rect.y, rect.height) / rect.width;
                float     aspect           = viewportRect.height / viewportRect.width;
                Matrix4x4 projectionMatrix = Matrix4x4.Ortho(-1f, 1f, -1f * aspect, 1f * aspect, -1f, 1f);
                GL.LoadProjectionMatrix(projectionMatrix);
                Matrix4x4 viewMatrix = Matrix4x4.Scale(new Vector3(previewWindowScale, previewWindowScale, previewWindowScale))
                                       * Matrix4x4.TRS(new Vector3(previewWindowPosition.x, previewWindowPosition.y, 0), Quaternion.identity, Vector3.one);          // u5.0 have no translate
                GL.MultMatrix(viewMatrix);


                // Preview texture
                if ((previewTextureSource == PreviewTextureSource.Custom && customPreviewTexture != null) ||
                    (previewTextureSource == PreviewTextureSource.FromMaterial && previewTexture != null))
                {
                    Texture2D texture = (previewTextureSource == PreviewTextureSource.Custom) ? customPreviewTexture : previewTexture;

                    SetMaterialKeyword(simpleMaterial, "_NORMALMAP", false);

                    string texPath = AssetDatabase.GetAssetPath(texture);
                    if (texPath != null)
                    {
                        TextureImporter textureImporter = (TextureImporter)TextureImporter.GetAtPath(texPath);
                        if (textureImporter != null)
                        {
                                                        #if (UNITY_5_5_OR_NEWER)
                            if (textureImporter.textureType == TextureImporterType.NormalMap)
                            {
                                SetMaterialKeyword(simpleMaterial, "_NORMALMAP", true);
                            }
                                                        #else
                            if (textureImporter.textureType == TextureImporterType.Bump)
                            {
                                SetMaterialKeyword(simpleMaterial, "_NORMALMAP", true);
                            }
                                                        #endif
                        }
                    }

                    switch (previewTextureChannels)
                    {
                    case ColorChannels.R:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", true);
                        simpleMaterial.SetColor("_Color", new Color(1, 0, 0, 0));
                        break;

                    case ColorChannels.G:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", true);
                        simpleMaterial.SetColor("_Color", new Color(0, 1, 0, 0));
                        break;

                    case ColorChannels.B:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", true);
                        simpleMaterial.SetColor("_Color", new Color(0, 0, 1, 0));
                        break;

                    case ColorChannels.A:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", true);
                        simpleMaterial.SetColor("_Color", new Color(0, 0, 0, 1));
                        break;

                    case ColorChannels.All:
                        SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", false);
                        simpleMaterial.SetColor("_Color", new Color(1, 1, 1, 1));
                        break;
                    }

                    simpleMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                    simpleMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);

                    simpleMaterial.SetTexture("_MainTex", texture);
                    simpleMaterial.SetPass(0);

                    float min = tilePreviewTexture ? -100f : 0;
                    float max = tilePreviewTexture ? 100f : 1;

                    GL.Begin(GL.TRIANGLE_STRIP);
                    GL.Color(previewTextureTintColor);
                    GL.TexCoord2(max, min);
                    GL.Vertex3(max, min, 0);
                    GL.TexCoord2(min, min);
                    GL.Vertex3(min, min, 0);
                    GL.TexCoord2(max, max);
                    GL.Vertex3(max, max, 0);
                    GL.TexCoord2(min, max);
                    GL.Vertex3(min, max, 0);
                    GL.End();
                }



                // grid
                if (showGrid)
                {
                    GL.wireframe = false;

                    SetMaterialKeyword(simpleMaterial, "_COLOR_MASK", false);
                    SetMaterialKeyword(simpleMaterial, "_NORMALMAP", false);
                    simpleMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    simpleMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    simpleMaterial.SetTexture("_MainTex", null);
                    simpleMaterial.SetColor("_Color", Color.white);
                    simpleMaterial.SetPass(0);


                    GL.Begin(GL.LINES);

                    float x = -1.0f;
                    GL.Color(Styles.gridColor);
                    for (int i = 0; i <= 20; i++, x += 0.1f)
                    {
                        GL.Vertex3(x, 1, 0);
                        GL.Vertex3(x, -1, 0);
                    }


                    float y = -1.0f;
                    GL.Color(Styles.gridColor);
                    for (int i = 0; i <= 20; i++, y += 0.1f)
                    {
                        GL.Vertex3(1, y, 0);
                        GL.Vertex3(-1, y, 0);
                    }

                    GL.Color(Color.gray);
                    GL.Vertex3(1, 0, 0);
                    GL.Vertex3(-1, 0, 0);
                    GL.Vertex3(0, 1, 0);
                    GL.Vertex3(0, -1, 0);

                    GL.Color(Color.red);
                    GL.Vertex3(0.3f, 0, 0);
                    GL.Vertex3(0, 0, 0);


                    GL.Color(Color.green);
                    GL.Vertex3(0, 0.3f, 0);
                    GL.Vertex3(0, 0, 0);

                    GL.End();
                }



                // mesh uvs
                {
                    SetMaterialKeyword(uvPreviewMaterial, "_UV1", false);
                    SetMaterialKeyword(uvPreviewMaterial, "_UV2", false);
                    SetMaterialKeyword(uvPreviewMaterial, "_UV3", false);

                    switch (previewUVSet)
                    {
                    case UVSet.UV2:
                        SetMaterialKeyword(uvPreviewMaterial, "_UV1", true);
                        break;

                    case UVSet.UV3:
                        SetMaterialKeyword(uvPreviewMaterial, "_UV2", true);
                        break;

                    case UVSet.UV4:
                        SetMaterialKeyword(uvPreviewMaterial, "_UV3", true);
                        break;
                    }


                    GL.wireframe = true;


                    for (int i = 0; i < inspectedObjects.Count; i++)
                    {
                        SetMaterialKeyword(uvPreviewMaterial, "_VERTEX_COLORS", showVertexColors && inspectedObjects[i].hasColors);

                        if (i == inspectedObjects.Count - 1)
                        {
                            uvPreviewMaterial.SetColor("_Color", Styles.wireframeColor);
                        }
                        else
                        {
                            uvPreviewMaterial.SetColor("_Color", Styles.wireframeColor2);
                        }

                        uvPreviewMaterial.SetPass(0);

                        if (inspectedObjects.Count == 1)
                        {
                            for (int j = 0; j < inspectedObjects[i].subMeshCount && j < 32; j++)
                            {
                                if (subMeshToggleField[j])
                                {
                                    Graphics.DrawMeshNow(inspectedObjects[i].mesh, viewMatrix, j);
                                }
                            }
                        }
                        else
                        {
                            Graphics.DrawMeshNow(inspectedObjects[i].mesh, viewMatrix);
                        }
                    }
                }

                GL.PopMatrix();
                GL.wireframe = false;

                GUI.EndGroup();

                // grid numbers
                if (showGrid)
                {
                    GUI.BeginGroup(rect);
                    Matrix4x4 MVPMatrix = (projectionMatrix * viewMatrix);
                    DrawLabel(new Vector3(0, 0, 0), rect, MVPMatrix, "0.0", EditorStyles.whiteMiniLabel, TextAnchor.MiddleLeft);
                    DrawLabel(new Vector3(0, 1, 0), rect, MVPMatrix, "1.0", EditorStyles.whiteMiniLabel, TextAnchor.MiddleLeft);
                    DrawLabel(new Vector3(0, -1, 0), rect, MVPMatrix, "-1.0", EditorStyles.whiteMiniLabel, TextAnchor.UpperLeft);
                    DrawLabel(new Vector3(1, 0, 0), rect, MVPMatrix, "1.0", EditorStyles.whiteMiniLabel, TextAnchor.MiddleLeft);
                    DrawLabel(new Vector3(-1, 0, 0), rect, MVPMatrix, "-1.0", EditorStyles.whiteMiniLabel, TextAnchor.MiddleRight);
                    GUI.EndGroup();
                }
            }
            break;
            }

            return;
        }
    public void ConvertImages()
    {
        // directories
        string aNamePrefab         = "photo.prefab";
        string aName               = string.Format("{0:yyyyMMdd_HHmmss}", DateTime.Now);
        string aDirectory          = "Assets/kolmich/KGFMapSystem/photocache/" + aName + "/";
        string aDirectoryTextures  = aDirectory + "textures/";
        string aDirectoryMaterials = aDirectory + "materials/";
        string aDirectoryPrefabs   = aDirectory + "prefabs/";

        Directory.CreateDirectory(aDirectoryTextures);
        Directory.CreateDirectory(aDirectoryMaterials);
        Directory.CreateDirectory(aDirectoryPrefabs);

        KGFMapSystem.KGFPhotoData [] aData = itsTarget.GetPhotoData();
        for (int i = 0; i < aData.Length; i++)
        {
            // texture
            string aFilePathTexture = aDirectoryTextures + i + ".png";
            byte[] bt = aData[i].itsTexture.EncodeToPNG();
            File.WriteAllBytes(aFilePathTexture, bt);

            AssetDatabase.ImportAsset(aFilePathTexture);

            TextureImporter anImporter = TextureImporter.GetAtPath(aFilePathTexture) as TextureImporter;
            anImporter.wrapMode = TextureWrapMode.Clamp;

            AssetDatabase.ImportAsset(aFilePathTexture);

            // material
            aData[i].itsTexture = AssetDatabase.LoadAssetAtPath(aFilePathTexture, typeof(Texture2D)) as Texture2D;
            aData[i].itsPhotoPlaneMaterial.mainTexture = aData[i].itsTexture;

//			AssetDatabase.CreateAsset((Texture2D)(aData[i].itsTexture),"Assets/t"+i+".png");
            AssetDatabase.CreateAsset(aData[i].itsPhotoPlaneMaterial, aDirectoryMaterials + i + ".mat");
        }

        // prefab
        UnityEngine.Object aPrefab = PrefabUtility.CreatePrefab(aDirectoryPrefabs + aNamePrefab, itsTarget.GetPhotoParent(), ReplacePrefabOptions.ConnectToPrefab);

        // Mesh
        Mesh aMesh = null;

        for (int i = 0; i < aData.Length; i++)
        {
            if (aMesh == null)
            {
                // save first mesh we find to prefab
                aMesh      = aData[i].itsPhotoPlane.GetComponent <MeshFilter>().sharedMesh;
                aMesh.name = "SimplePlaneMesh";
                AssetDatabase.AddObjectToAsset(aMesh, aDirectoryPrefabs + aNamePrefab);
                AssetDatabase.ImportAsset(aDirectoryPrefabs + aNamePrefab);

                // get link of mesh in prefab
                aMesh = AssetDatabase.LoadAssetAtPath(aDirectoryPrefabs + aNamePrefab, typeof(Mesh)) as Mesh;
            }
            else
            {
                // set all other meshfilters to use the mesh in the prefab
                aData[i].itsPhotoPlane.GetComponent <MeshFilter>().sharedMesh = aMesh;
            }
        }

        // save changes to prefab
        PrefabUtility.ReplacePrefab(itsTarget.GetPhotoParent(), aPrefab, ReplacePrefabOptions.ConnectToPrefab);
    }
    /// <summary>
    /// Bakes the mobile lightshaft texture with the current lightshaft properties and dimensions in the default location.
    /// </summary>
    public void GenerateTexture()
    {
        if (!CheckShaderAndCreateMaterial())
        {
            Debug.LogWarning("LightShaft effect - Can't create texture since the shader is not available.");
            return;
        }

        // Clean old Texture
        if (!_currentTexturePath.Equals(string.Empty))
        {
            File.Delete(string.Format("{0}{1}", Application.dataPath, _currentTexturePath));
        }

        // Create temporary RenderTexture
        RenderTexture rt = RenderTexture.GetTemporary((int)TextureDimensions.x, (int)TextureDimensions.y, 0, RenderTextureFormat.ARGB32);

        // Setup light shaft shader parameter and color input
        SetGradientColors();
        SetParameters();

        // Render light shaft only (light shaft shader pass 1) to render texture
        Graphics.Blit(null, rt, _lightShaftMaterial, 1);

        // Create temporary texture and copy pixels from render texture
        Texture2D texture = new Texture2D((int)TextureDimensions.x, (int)TextureDimensions.y, TextureFormat.ARGB32, false);

        texture.ReadPixels(new Rect(0, 0, (int)TextureDimensions.x, (int)TextureDimensions.y), 0, 0);
        texture.Apply();

        // Release temporary render texture
        RenderTexture.ReleaseTemporary(rt);

        // Save texture to raw png data
        byte[] bytes = texture.EncodeToPNG();
        string mobileTextureExtension = ".png";

        // Delete temporary texture
        DestroyImmediate(texture);

        // Generate name
                #if UNITY_5_3_OR_NEWER
        string sceneName = Path.GetFileNameWithoutExtension(SceneManager.GetActiveScene().path);
                #else
        string sceneName = Path.GetFileNameWithoutExtension(EditorApplication.currentScene);
                #endif
        string name = string.Format("LightShaft-{0}.{1}", sceneName, gameObject.GetInstanceID());
        _currentTexturePath = string.Format("{0}{1}{2}", _mobileTexturePath, name, mobileTextureExtension);

        // Check if path exists
        string directoryPath = string.Format("{0}{1}", Application.dataPath, _mobileTexturePath);
        if (!AssetDatabase.IsValidFolder(directoryPath))
        {
            // Create folder if it doesn't exist yet
            Directory.CreateDirectory(directoryPath);
        }

        // Write texture to disk
        File.WriteAllBytes(string.Format("{0}{1}", Application.dataPath, _currentTexturePath), bytes);

        // Import the texture asset
        string assetPath = string.Format("Assets{0}", _currentTexturePath);
        AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);

        // Set the texture options (transparancy from alpha)
        TextureImporter imp = TextureImporter.GetAtPath(assetPath) as TextureImporter;
                #if UNITY_5_5_OR_NEWER
        imp.alphaSource = TextureImporterAlphaSource.FromInput;
                #else
        imp.grayscaleToAlpha = false;
                #endif
        imp.alphaIsTransparency = true;

        // Force AssetDatabes to load the texture
        LightShaftTexture = AssetDatabase.LoadAssetAtPath <Texture>(assetPath);
    }
示例#12
0
    // ------------------------------------------------------------------
    // Desc:
    // ------------------------------------------------------------------

    void Settings()
    {
        GUIContent content = null;

        EditorGUILayout.BeginVertical(new GUILayoutOption [] {
            GUILayout.Width(250),
            GUILayout.MinWidth(250),
            GUILayout.MaxWidth(250),
            GUILayout.ExpandWidth(false)
        });
        // ========================================================
        // canvas
        // ========================================================

        foldoutCanvas = EditorGUILayout.Foldout(foldoutCanvas, "Canvas");
        if (foldoutCanvas)
        {
            EditorGUI.indentLevel++;

            // width & height
            EditorGUI.BeginChangeCheck();
            int width  = EditorGUILayout.IntPopup("Width", curEdit.width, sizeTextList, sizeList);
            int height = EditorGUILayout.IntPopup("Height", curEdit.height, sizeTextList, sizeList);
            if (EditorGUI.EndChangeCheck())
            {
                curEdit.width       = width;
                curEdit.height      = height;
                curEdit.needRebuild = true;
                curEdit.needLayout  = true;
                EditorUtility.SetDirty(curEdit);
            }

            // bgColor, showCheckerboard,
            EditorGUI.BeginChangeCheck();
            curEdit.bgColor          = EditorGUILayout.ColorField("Background", curEdit.bgColor);
            curEdit.showCheckerboard = EditorGUILayout.Toggle("Checkerboard", curEdit.showCheckerboard);
            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(curEdit);
            }

            EditorGUI.indentLevel--;
        }
        EditorGUILayout.Space();

        // ========================================================
        // layout
        // ========================================================

        foldoutLayout = EditorGUILayout.Foldout(foldoutLayout, "Layout");
        if (foldoutLayout)
        {
            EditorGUI.indentLevel++;

            // algorithm, sortBy, sortOrder, paddingMode, pixels, allowRotate ....
            EditorGUI.BeginChangeCheck();
            curEdit.algorithm = (exAtlas.Algorithm)EditorGUILayout.EnumPopup("Algorithm", curEdit.algorithm);
            curEdit.sortBy    = (exAtlas.SortBy)EditorGUILayout.EnumPopup("Sort By", curEdit.sortBy);
            curEdit.sortOrder = (exAtlas.SortOrder)EditorGUILayout.EnumPopup("Sort Order", curEdit.sortOrder);

            // padding
            curEdit.paddingMode = (exAtlas.PaddingMode)EditorGUILayout.EnumPopup("Padding", curEdit.paddingMode);
            EditorGUI.indentLevel++;
            GUI.enabled           = (curEdit.paddingMode == exAtlas.PaddingMode.Custom);
            curEdit.customPadding = System.Math.Max(EditorGUILayout.IntField("Pixels", curEdit.actualPadding), 0);               // Clamp to 0
            GUI.enabled           = true;
            EditorGUI.indentLevel--;

            // allow rotate
            curEdit.allowRotate = EditorGUILayout.Toggle("Allow Rotate", curEdit.allowRotate);

            // DISABLE {
            // EditorGUILayout.BeginHorizontal();
            //     GUILayout.FlexibleSpace();
            //     if ( GUILayout.Button ( "Apply",
            //                             new GUILayoutOption [] {
            //                                 GUILayout.Width(80)
            //                             } ) ) {
            //         LayoutAtlasElements();
            //     }
            // EditorGUILayout.EndHorizontal();
            // } DISABLE end
            if (EditorGUI.EndChangeCheck())
            {
                curEdit.needLayout = true;
                EditorUtility.SetDirty(curEdit);
            }

            EditorGUI.indentLevel--;
        }
        EditorGUILayout.Space();
        EditorGUILayout.Space();

        // ========================================================
        // Element
        // ========================================================

        foldoutElement = EditorGUILayout.Foldout(foldoutElement, "Element");
        if (foldoutElement)
        {
            EditorGUI.indentLevel++;

            // elementBgColor, elementSelectColor
            EditorGUI.BeginChangeCheck();
            curEdit.elementBgColor     = EditorGUILayout.ColorField("Background", curEdit.elementBgColor);
            curEdit.elementSelectColor = EditorGUILayout.ColorField("Select", curEdit.elementSelectColor);
            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(curEdit);
            }

            // trim settings
            EditorGUI.BeginChangeCheck();
            // trim elements
            curEdit.trimElements = EditorGUILayout.Toggle("Trimmed Elements", curEdit.trimElements);

            // trim threshold
            curEdit.trimThreshold = EditorGUILayout.IntField("Trimmed Threshold", curEdit.trimThreshold);
            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(curEdit);
            }

            EditorGUI.indentLevel--;
        }
        EditorGUILayout.Space();
        EditorGUILayout.Space();

        // ========================================================
        // Build
        // ========================================================

        foldoutBuild = EditorGUILayout.Foldout(foldoutBuild, "Build");
        if (foldoutBuild)
        {
            EditorGUI.indentLevel++;

            // build color
            EditorGUILayout.BeginHorizontal();
            EditorGUI.BeginChangeCheck();
            // customBuildColor
            curEdit.customBuildColor = EditorGUILayout.Toggle("Custom Build Color", curEdit.customBuildColor);

            // buildColor
            if (curEdit.customBuildColor)
            {
                curEdit.buildColor = EditorGUILayout.ColorField(curEdit.buildColor);
            }
            if (EditorGUI.EndChangeCheck())
            {
                curEdit.needRebuild = true;
                EditorUtility.SetDirty(curEdit);
            }
            EditorGUILayout.EndHorizontal();

            // contour bleed
            GUI.enabled = !curEdit.customBuildColor;
            EditorGUILayout.BeginHorizontal();
            EditorGUI.BeginChangeCheck();
            // useContourBleed
            content = new GUIContent("Use Contour Bleed",
                                     "Prevents artifacts around the silhouette of artwork due to bilinear filtering (requires Build Color to be turned off)");
            curEdit.useContourBleed = EditorGUILayout.Toggle(content, curEdit.useContourBleed);
            if (EditorGUI.EndChangeCheck())
            {
                curEdit.needRebuild = true;
                EditorUtility.SetDirty(curEdit);
            }
            EditorGUILayout.EndHorizontal();
            GUI.enabled = true;

            // padding bleed
            GUI.enabled = (curEdit.paddingMode == exAtlas.PaddingMode.Auto) || (curEdit.actualPadding >= 2);
            EditorGUILayout.BeginHorizontal();
            EditorGUI.BeginChangeCheck();
            // usePaddingBleed
            content = new GUIContent("Use Padding Bleed",
                                     "Prevents artifacts and seams around the outer bounds of a texture due to bilinear filtering (requires at least Padding of 2)");
            curEdit.usePaddingBleed = EditorGUILayout.Toggle(content, curEdit.usePaddingBleed);
            if (EditorGUI.EndChangeCheck())
            {
                curEdit.needRebuild = true;
                EditorUtility.SetDirty(curEdit);
            }
            EditorGUILayout.EndHorizontal();
            GUI.enabled = true;

            // readable
            EditorGUI.BeginChangeCheck();
            curEdit.readable = EditorGUILayout.Toggle("Read/Write Enabled", curEdit.readable);
            if (EditorGUI.EndChangeCheck())
            {
                if (curEdit.texture != null)
                {
                    string          atlasTexturePath = AssetDatabase.GetAssetPath(curEdit.texture);
                    TextureImporter importSettings   = TextureImporter.GetAtPath(atlasTexturePath) as TextureImporter;
                    importSettings.isReadable = curEdit.readable;
                    AssetDatabase.ImportAsset(atlasTexturePath, ImportAssetOptions.ForceSynchronousImport);
                    // NOTE: if you click the readable button quickly, you may not see the changes of the texture in the inspector
                }

                EditorUtility.SetDirty(curEdit);
            }

            // texture
            EditorGUILayout.ObjectField("Texture"
                                        , curEdit.texture
                                        , typeof(Texture2D)
                                        , false
                                        );

            EditorGUI.indentLevel--;
        }
        EditorGUILayout.Space();
        EditorGUILayout.Space();

        EditorGUI.indentLevel++;
        GUIStyle style = new GUIStyle();

        style.normal.textColor = Color.yellow;
        EditorGUILayout.LabelField("Zoom in/out: Ctrl + MouseWheel", style);
        EditorGUI.indentLevel--;

        EditorGUILayout.EndVertical();
    }
        private static void CreateFaceMaskPrefab()
        {
            float  width    = 512f;
            float  height   = 512f;
            string basePath = "Assets/FaceMaskExample/FaceMaskPrefab/";

            GameObject newObj = new GameObject("FaceMaskTrackedMesh");

            //Add MeshFilter Component.
            MeshFilter meshFilter = newObj.AddComponent <MeshFilter> ();

            // Create Mesh.
            meshFilter.mesh = new Mesh();
            Mesh mesh = meshFilter.sharedMesh;

            mesh.name = "DlibFaceLandmark68Mesh";

            // Mesh_vertices
            Vector3[] vertices = new Vector3[68] {
                new Vector3(117, 250),
                new Vector3(124, 291),
                new Vector3(131, 330),
                new Vector3(136, 369),
                new Vector3(146, 404),
                new Vector3(167, 433),
                new Vector3(192, 459),
                new Vector3(222, 480),
                new Vector3(261, 485),
                new Vector3(300, 478),

                new Vector3(328, 453),
                new Vector3(353, 425),
                new Vector3(372, 394),
                new Vector3(383, 357),
                new Vector3(387, 319),
                new Vector3(392, 281),
                new Vector3(397, 241),
                new Vector3(135, 224),
                new Vector3(151, 205),
                new Vector3(175, 196),

                new Vector3(202, 192),
                //22^23
                new Vector3(228, 205),  //new Vector3(228, 197), y+10
                new Vector3(281, 205),  //new Vector3(281, 197), y+10

                new Vector3(308, 191),
                new Vector3(334, 195),
                new Vector3(358, 205),
                new Vector3(374, 222),
                new Vector3(255, 228),
                new Vector3(256, 254),
                new Vector3(257, 279),

                new Vector3(258, 306),
                new Vector3(230, 322),
                new Vector3(243, 325),
                new Vector3(259, 329),
                new Vector3(274, 324),
                new Vector3(288, 320),
                new Vector3(168, 237),
                new Vector3(182, 229),
                new Vector3(200, 229),
                new Vector3(214, 239),

                new Vector3(199, 241),
                new Vector3(182, 242),
                new Vector3(296, 238),
                new Vector3(310, 228),
                new Vector3(327, 228),
                new Vector3(341, 235),
                new Vector3(328, 240),
                new Vector3(311, 240),
                //49
                new Vector3(198, 372),  //new Vector3(198, 367), y+5

                new Vector3(219, 360),

                new Vector3(242, 357),
                new Vector3(261, 360),
                new Vector3(280, 357),
                new Vector3(301, 357),
                //55
                new Vector3(322, 367),  //new Vector3(322, 362), y+5

                new Vector3(303, 387),
                new Vector3(282, 396),
                new Vector3(261, 398),
                new Vector3(241, 396),
                new Vector3(218, 388),
                //61^65
                new Vector3(205, 373),  //new Vector3(205, 368), y+5
                new Vector3(242, 371),  //new Vector3(242, 366), y+5
                new Vector3(261, 373),  //new Vector3(261, 368), y+5
                new Vector3(280, 370),  //new Vector3(280, 365), y+5
                new Vector3(314, 368),  //new Vector3(314, 363) y+5

                new Vector3(281, 382),
                new Vector3(261, 384),
                new Vector3(242, 383)
            };

            Vector3[] vertices2 = (Vector3[])vertices.Clone();
            for (int j = 0; j < vertices2.Length; j++)
            {
                vertices2 [j].x = (vertices2 [j].x - width / 2f) / width;
                vertices2 [j].y = (height / 2f - vertices2 [j].y) / height;
            }
            mesh.vertices = vertices2;

            // Mesh_triangles
            int[] triangles = new int[327] {
                // Around the right eye 21
                0, 36, 1,
                1, 36, 41,
                1, 41, 31,
                41, 40, 31,
                40, 29, 31,
                40, 39, 29,
                39, 28, 29,
                39, 27, 28,
                39, 21, 27,
                38, 21, 39,
                20, 21, 38,
                37, 20, 38,
                37, 19, 20,
                18, 19, 37,
                18, 37, 36,
                17, 18, 36,
                0, 17, 36,

                // (inner right eye 4)
                36, 37, 41,
                37, 40, 41,
                37, 38, 40,
                38, 39, 40,

                // Around the left eye 21
                45, 16, 15,
                46, 45, 15,
                46, 15, 35,
                47, 46, 35,
                29, 47, 35,
                42, 47, 29,
                28, 42, 29,
                27, 42, 28,
                27, 22, 42,
                22, 43, 42,
                22, 23, 43,
                23, 44, 43,
                23, 24, 44,
                24, 25, 44,
                44, 25, 45,
                25, 26, 45,
                45, 26, 16,

                // (inner left eye 4)
                44, 45, 46,
                47, 44, 46,
                43, 44, 47,
                42, 43, 47,

                // Eyebrows, nose and cheeks 13
                20, 23, 21,
                21, 23, 22,
                21, 22, 27,
                29, 30, 31,
                29, 35, 30,
                30, 32, 31,
                30, 33, 32,
                30, 34, 33,
                30, 35, 34,
                1, 31, 2,
                2, 31, 3,
                35, 15, 14,
                35, 14, 13,

                // mouth 48
                33, 51, 50,
                32, 33, 50,
                31, 32, 50,
                31, 50, 49,
                31, 49, 48,
                3, 31, 48,
                3, 48, 4,
                4, 48, 5,
                48, 59, 5,
                5, 59, 6,
                59, 58, 6,
                58, 7, 6,
                58, 57, 7,
                57, 8, 7,
                57, 9, 8,
                57, 56, 9,
                56, 10, 9,
                56, 55, 10,
                55, 11, 10,
                55, 54, 11,
                54, 12, 11,
                54, 13, 12,
                35, 13, 54,
                35, 54, 53,
                35, 53, 52,
                34, 35, 52,
                33, 34, 52,
                33, 52, 51,

                48, 49, 60,
                48, 60, 59,
                49, 50, 61,
                49, 61, 60,
                60, 67, 59,
                59, 67, 58,
                50, 51, 61,
                51, 62, 61,
                67, 66, 58,
                66, 57, 58,
                51, 52, 63,
                51, 63, 62,
                66, 65, 56,
                66, 56, 57,
                52, 53, 63,
                53, 64, 63,
                65, 64, 55,
                65, 55, 56,
                53, 54, 64,
                64, 54, 55,

                // inner mouth 6
                60, 61, 67,
                61, 62, 67,
                62, 66, 67,
                62, 63, 65,
                62, 65, 66,
                63, 64, 65
            };
            mesh.triangles = triangles;

            // Mesh_uv
            Vector2[] uv = new Vector2[68];
            for (int j = 0; j < uv.Length; j++)
            {
                uv [j].x = vertices [j].x / width;
                uv [j].y = (height - vertices [j].y) / height;
            }
            mesh.uv  = uv;
            mesh.uv2 = (Vector2[])uv.Clone();

            mesh.RecalculateNormals();

            // Add Collider Component.
            MeshCollider meshCollider = newObj.AddComponent <MeshCollider> ();

            meshCollider.sharedMesh = CreatePrimitiveQuadMesh();

            // Add Renderer Component.
            MeshRenderer meshRenderer = newObj.AddComponent <MeshRenderer> ();
            Material     material     = new Material(Shader.Find("Hide/FaceMaskShader"));

            // Create alpha mask texture.
            Vector2[] facialContourUVPoints = new Vector2[] {
                uv [0],
                uv [1],
                uv [2],
                uv [3],
                uv [4],
                uv [5],
                uv [6],
                uv [7],
                uv [8],
                uv [9],
                uv [10],
                uv [11],
                uv [12],
                uv [13],
                uv [14],
                uv [15],
                uv [16],
                uv [26],
                uv [25],
                uv [24],
                uv [23],
                uv [20],
                uv [19],
                uv [18],
                uv [17]
            };

            /*
             * Vector2[] rightEyeContourUVPoints = new Vector2[]{
             *  uv[36],
             *  uv[37],
             *  uv[38],
             *  uv[39],
             *  uv[40],
             *  uv[41]
             * };
             *
             * Vector2[] leftEyeContourUVPoints = new Vector2[]{
             *  uv[42],
             *  uv[43],
             *  uv[44],
             *  uv[45],
             *  uv[46],
             *  uv[47]
             * };
             */

            Vector2[] mouthContourUVPoints = new Vector2[] {
                uv [60],
                uv [61],
                uv [62],
                uv [63],
                uv [64],
                uv [65],
                uv [66],
                uv [67]
            };

            Texture2D alphaMaskTexture     = AlphaMaskTextureCreater.CreateAlphaMaskTexture(width, height, facialContourUVPoints, /*rightEyeContourUVPoints, leftEyeContourUVPoints,*/ mouthContourUVPoints);
            string    alphaMaskTexturePath = basePath + "FaceMaskAlphaMask.png";

            byte[] pngData = alphaMaskTexture.EncodeToPNG();

            if (CreateWithoutFolder(basePath))
            {
                File.WriteAllBytes(alphaMaskTexturePath, pngData);
                AssetDatabase.ImportAsset(alphaMaskTexturePath, ImportAssetOptions.ForceUpdate);
                AssetDatabase.SaveAssets();
            }

            TextureImporter importer = TextureImporter.GetAtPath(alphaMaskTexturePath) as TextureImporter;

            importer.textureType    = TextureImporterType.Default;
            importer.mipmapEnabled  = false;
            importer.wrapMode       = TextureWrapMode.Clamp;
            importer.maxTextureSize = 1024;
//            importer.textureFormat = TextureImporterFormat.RGBA16;
            EditorUtility.SetDirty(importer);
            AssetDatabase.ImportAsset(alphaMaskTexturePath, ImportAssetOptions.ForceUpdate);
            AssetDatabase.SaveAssets();

            GameObject.DestroyImmediate(alphaMaskTexture);
            alphaMaskTexture = AssetDatabase.LoadAssetAtPath(alphaMaskTexturePath, typeof(Texture2D)) as Texture2D;
            material.SetTexture("_MaskTex", alphaMaskTexture);
            meshRenderer.material = material;

            // Add TracedMesh Compornent.
            newObj.AddComponent <TrackedMesh> ();

            // Save FaceMask Assets.
            if (CreateWithoutFolder(basePath))
            {
                AssetDatabase.CreateAsset(material, basePath + "FaceMaskMaterial.mat");
                AssetDatabase.CreateAsset(mesh, basePath + "DlibFaceLandmark68Mesh.asset");
                AssetDatabase.SaveAssets();

                UnityEngine.Object prefab = AssetDatabase.LoadAssetAtPath(basePath + "FaceMaskTrackedMesh.prefab", typeof(UnityEngine.Object));
                if (prefab == null)
                {
                    UnityEditor.PrefabUtility.CreatePrefab(basePath + "FaceMaskTrackedMesh.prefab", newObj);
                }
                else
                {
                    UnityEditor.PrefabUtility.ReplacePrefab(newObj, prefab);
                }
                AssetDatabase.SaveAssets();
            }

            GameObject.DestroyImmediate(newObj);
        }
    public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)
    {
        Material material = materialEditor.target as Material;
        Shader   shader   = material.shader;

        isCutout        = shader.name.Contains("Cutout") && !shader.name.Contains("A2C");
        isOutlined      = shader.name.Contains("Outline");
        isPatreonShader = shader.name.Contains("Patreon");
        isEyeTracking   = shader.name.Contains("EyeTracking");
        isRave          = shader.name.Contains("Rave");
        isSparkle       = shader.name.Contains("Sparkle");

        //Find all material properties listed in the script using reflection, and set them using a loop only if they're of type MaterialProperty.
        //This makes things a lot nicer to maintain and cleaner to look at.
        foreach (var property in GetType().GetFields(bindingFlags))
        {
            if (property.FieldType == typeof(MaterialProperty))
            {
                try{ property.SetValue(this, FindProperty(property.Name, props)); } catch { /*Is it really a problem if it doesn't exist?*/ }
            }
        }

        EditorGUI.BeginChangeCheck();
        {
            if (!isCutout)            // Do this to make sure that if you're using AlphaToCoverage that you fallback to cutout with 0.5 Cutoff if your shaders are blocked.
            {
                material.SetFloat("_Cutoff", 0.5f);
            }

            XSStyles.ShurikenHeaderCentered("XSToon v" + XSStyles.ver);
            materialEditor.ShaderProperty(_AdvMode, new GUIContent("Shader Mode", "Setting this to 'Advanced' will give you access to things such as stenciling, and other expiremental/advanced features."));
            materialEditor.ShaderProperty(_Culling, new GUIContent("Culling Mode", "Changes the culling mode. 'Off' will result in a two sided material, while 'Front' and 'Back' will cull those sides respectively"));
            materialEditor.ShaderProperty(_TilingMode, new GUIContent("Tiling Mode", "Setting this to Merged will tile and offset all textures based on the Main texture's Tiling/Offset."));

            showMainSettings = XSStyles.ShurikenFoldout("Main Settings", showMainSettings);
            if (showMainSettings)
            {
                materialEditor.TexturePropertySingleLine(new GUIContent("Main Texture", "The main Albedo texture."), _MainTex, _Color);
                if (isCutout)
                {
                    materialEditor.ShaderProperty(_Cutoff, new GUIContent("Cutoff", "The Cutoff Amount"), 2);
                }
                materialEditor.ShaderProperty(_UVSetAlbedo, new GUIContent("UV Set", "The UV set to use for the Albedo Texture."), 2);
                materialEditor.TextureScaleOffsetProperty(_MainTex);
                materialEditor.ShaderProperty(_Saturation, new GUIContent("Saturation", "Controls saturation of the final output from the shader."));
            }

            showShadows = XSStyles.ShurikenFoldout("Shadows", showShadows);
            if (showShadows)
            {
                materialEditor.TexturePropertySingleLine(new GUIContent("Ramp Selection Mask", "A black to white mask that determins how far up on the multi ramp to sample. 0 for bottom, 1 for top, 0.5 for middle, 0.25, and 0.75 for mid bottom and mid top respectively."), _RampSelectionMask);

                XSStyles.SeparatorThin();
                if (_RampSelectionMask.textureValue != null)
                {
                    string          rampMaskPath = AssetDatabase.GetAssetPath(_RampSelectionMask.textureValue);
                    TextureImporter ti           = (TextureImporter)TextureImporter.GetAtPath(rampMaskPath);
                    if (ti.sRGBTexture)
                    {
                        if (XSStyles.HelpBoxWithButton(new GUIContent("This texture is not marked as Linear.", "This is recommended for the mask"), new GUIContent("Fix Now")))
                        {
                            ti.sRGBTexture = false;
                            AssetDatabase.ImportAsset(rampMaskPath, ImportAssetOptions.ForceUpdate);
                            AssetDatabase.Refresh();
                        }
                    }
                }

                materialEditor.TexturePropertySingleLine(new GUIContent("Shadow Ramp", "Shadow Ramp, Dark to Light should be Left to Right"), _Ramp);
                materialEditor.ShaderProperty(_ShadowSharpness, new GUIContent("Shadow Sharpness", "Controls the sharpness of recieved shadows, as well as the sharpness of 'shadows' from Vertex Lighting."));

                XSStyles.SeparatorThin();
                materialEditor.TexturePropertySingleLine(new GUIContent("Occlusion Map", "Occlusion Map, used to darken areas on the model artifically."), _OcclusionMap);
                XSStyles.constrainedShaderProperty(materialEditor, _OcclusionColor, new GUIContent("Occlusion Tint", "Occlusion shadow tint."), 2);
                materialEditor.ShaderProperty(_UVSetOcclusion, new GUIContent("UV Set", "The UV set to use for the Occlusion Texture"), 2);
                materialEditor.TextureScaleOffsetProperty(_OcclusionMap);

                XSStyles.SeparatorThin();
                XSStyles.constrainedShaderProperty(materialEditor, _ShadowRim, new GUIContent("Shadow Rim", "Shadow Rim Color. Set to white to disable."), 0);
                materialEditor.ShaderProperty(_ShadowRimRange, new GUIContent("Range", "Range of the Shadow Rim"), 2);
                materialEditor.ShaderProperty(_ShadowRimThreshold, new GUIContent("Threshold", "Threshold of the Shadow Rim"), 2);
                materialEditor.ShaderProperty(_ShadowRimSharpness, new GUIContent("Sharpness", "Sharpness of the Shadow Rim"), 2);
                XSStyles.callGradientEditor(material);
            }

            if (isOutlined)
            {
                showOutlines = XSStyles.ShurikenFoldout("Outlines", showOutlines);
                if (showOutlines)
                {
                    materialEditor.ShaderProperty(_OutlineLighting, new GUIContent("Outline Lighting", "Makes outlines respect the lighting, or be emissive."));
                    materialEditor.ShaderProperty(_OutlineAlbedoTint, new GUIContent("Outline Albedo Tint", "Includes the color of the Albedo Texture in the calculation for the color of the outline."));
                    materialEditor.TexturePropertySingleLine(new GUIContent("Outline Mask", "Outline width mask, black will make the outline minimum width."), _OutlineMask);
                    materialEditor.ShaderProperty(_OutlineWidth, new GUIContent("Outline Width", "Width of the Outlines"));
                    XSStyles.constrainedShaderProperty(materialEditor, _OutlineColor, new GUIContent("Outline Color", "Color of the outlines"), 0);
                }
            }

            showNormalMapSettings = XSStyles.ShurikenFoldout("Normal Maps", showNormalMapSettings);
            if (showNormalMapSettings)
            {
                materialEditor.TexturePropertySingleLine(new GUIContent("Normal Map", "Normal Map"), _BumpMap);
                materialEditor.ShaderProperty(_BumpScale, new GUIContent("Normal Strength", "Strength of the main Normal Map"), 2);
                materialEditor.ShaderProperty(_UVSetNormal, new GUIContent("UV Set", "The UV set to use for the Normal Map"), 2);
                materialEditor.TextureScaleOffsetProperty(_BumpMap);

                XSStyles.SeparatorThin();
                materialEditor.TexturePropertySingleLine(new GUIContent("Detail Normal Map", "Detail Normal Map"), _DetailNormalMap);
                materialEditor.ShaderProperty(_DetailNormalMapScale, new GUIContent("Detail Normal Strength", "Strength of the detail Normal Map"), 2);
                materialEditor.ShaderProperty(_UVSetDetNormal, new GUIContent("UV Set", "The UV set to use for the Detail Normal Map"), 2);
                materialEditor.TextureScaleOffsetProperty(_DetailNormalMap);

                XSStyles.SeparatorThin();
                materialEditor.TexturePropertySingleLine(new GUIContent("Detail Mask", "Mask for Detail Maps"), _DetailMask);
                materialEditor.ShaderProperty(_UVSetDetMask, new GUIContent("UV Set", "The UV set to use for the Detail Mask"), 2);
                materialEditor.TextureScaleOffsetProperty(_DetailMask);
            }

            showSpecular = XSStyles.ShurikenFoldout("Specular", showSpecular);
            if (showSpecular)
            {
                materialEditor.ShaderProperty(_SpecMode, new GUIContent("Specular Mode", "Specular Mode."));
                materialEditor.ShaderProperty(_SpecularStyle, new GUIContent("Specular Style", "Specular Style."));

                XSStyles.SeparatorThin();
                materialEditor.TexturePropertySingleLine(new GUIContent("Specular Map(R,G,B)", "Specular Map. Red channel controls Intensity, Green controls how much specular is tinted by Albedo, and Blue controls Smoothness (Only for Blinn-Phong, and GGX)."), _SpecularMap);
                materialEditor.TextureScaleOffsetProperty(_SpecularMap);
                materialEditor.ShaderProperty(_UVSetSpecular, new GUIContent("UV Set", "The UV set to use for the Specular Map"), 2);
                materialEditor.ShaderProperty(_SpecularIntensity, new GUIContent("Specular Intensity", "Specular Intensity."), 2);
                materialEditor.ShaderProperty(_SpecularAlbedoTint, new GUIContent("Specular Albedo Tint", "How much the specular highlight should derive color from the albedo of the object."), 2);
                if (_SpecMode.floatValue == 0 || _SpecMode.floatValue == 2)
                {
                    materialEditor.ShaderProperty(_SpecularArea, new GUIContent("Specular Area", "Specular Area."), 2);
                }
                else
                {
                    materialEditor.ShaderProperty(_AnisotropicAX, new GUIContent("Anisotropic Width", "Anisotropic Width, makes anistropic relfections more horizontal"), 2);
                    materialEditor.ShaderProperty(_AnisotropicAY, new GUIContent("Anisotropic Height", "Anisotropic Height, makes anistropic relfections more vertical"), 2);
                }
            }

            showReflection = XSStyles.ShurikenFoldout("Reflections", showReflection);
            if (showReflection)
            {
                materialEditor.ShaderProperty(_ReflectionMode, new GUIContent("Reflection Mode", "Reflection Mode."));

                if (_ReflectionMode.floatValue == 0) // PBR
                {
                    materialEditor.ShaderProperty(_ReflectionBlendMode, new GUIContent("Reflection Blend Mode", "Blend mode for reflection. Additive is Color + reflection, Multiply is Color * reflection, and subtractive is Color - reflection"));
                    materialEditor.ShaderProperty(_ClearCoat, new GUIContent("Clearcoat", "Clearcoat"));

                    XSStyles.SeparatorThin();
                    materialEditor.TexturePropertySingleLine(new GUIContent("Fallback Cubemap", " Used as fallback in 'Unity' reflection mode if reflection probe is black."), _BakedCubemap);

                    XSStyles.SeparatorThin();
                    materialEditor.TexturePropertySingleLine(new GUIContent("Metallic Map", "Metallic Map, Metallic on Red Channel, Smoothness on Alpha Channel. \nIf Clearcoat is enabled, Clearcoat Smoothness on Green Channel, Clearcoat Reflectivity on Blue Channel."), _MetallicGlossMap);
                    materialEditor.TextureScaleOffsetProperty(_MetallicGlossMap);
                    materialEditor.ShaderProperty(_UVSetMetallic, new GUIContent("UV Set", "The UV set to use for the Metallic Smoothness Map"), 2);
                    materialEditor.ShaderProperty(_Metallic, new GUIContent("Metallic", "Metallic, set to 1 if using metallic map"), 2);
                    materialEditor.ShaderProperty(_Glossiness, new GUIContent("Smoothness", "Smoothness, set to 1 if using metallic map"), 2);
                    materialEditor.ShaderProperty(_ClearcoatSmoothness, new GUIContent("Clearcoat Smoothness", "Smoothness of the clearcoat."), 2);
                    materialEditor.ShaderProperty(_ClearcoatStrength, new GUIContent("Clearcoat Reflectivity", "The strength of the clearcoat reflection."), 2);
                }
                else if (_ReflectionMode.floatValue == 1) //Baked cube
                {
                    materialEditor.ShaderProperty(_ReflectionBlendMode, new GUIContent("Reflection Blend Mode", "Blend mode for reflection. Additive is Color + reflection, Multiply is Color * reflection, and subtractive is Color - reflection"));
                    materialEditor.ShaderProperty(_ClearCoat, new GUIContent("Clearcoat", "Clearcoat"));

                    XSStyles.SeparatorThin();
                    materialEditor.TexturePropertySingleLine(new GUIContent("Baked Cubemap", "Baked cubemap."), _BakedCubemap);

                    XSStyles.SeparatorThin();
                    materialEditor.TexturePropertySingleLine(new GUIContent("Metallic Map", "Metallic Map, Metallic on Red Channel, Smoothness on Alpha Channel. \nIf Clearcoat is enabled, Clearcoat Smoothness on Green Channel, Clearcoat Reflectivity on Blue Channel."), _MetallicGlossMap);
                    materialEditor.TextureScaleOffsetProperty(_MetallicGlossMap);
                    materialEditor.ShaderProperty(_UVSetMetallic, new GUIContent("UV Set", "The UV set to use for the MetallicSmoothness Map"), 2);
                    materialEditor.ShaderProperty(_Metallic, new GUIContent("Metallic", "Metallic, set to 1 if using metallic map"), 2);
                    materialEditor.ShaderProperty(_Glossiness, new GUIContent("Smoothness", "Smoothness, set to 1 if using metallic map"), 2);
                    materialEditor.ShaderProperty(_ClearcoatSmoothness, new GUIContent("Clearcoat Smoothness", "Smoothness of the clearcoat."), 2);
                    materialEditor.ShaderProperty(_ClearcoatStrength, new GUIContent("Clearcoat Reflectivity", "The strength of the clearcoat reflection."), 2);
                }
                else if (_ReflectionMode.floatValue == 2) //Matcap
                {
                    materialEditor.ShaderProperty(_ReflectionBlendMode, new GUIContent("Reflection Blend Mode", "Blend mode for reflection. Additive is Color + reflection, Multiply is Color * reflection, and subtractive is Color - reflection"));

                    XSStyles.SeparatorThin();
                    materialEditor.TexturePropertySingleLine(new GUIContent("Matcap", "Matcap Texture"), _Matcap, _MatcapTint);
                    materialEditor.ShaderProperty(_Glossiness, new GUIContent("Matcap Blur", "Matcap blur, blurs the Matcap, set to 1 for full clarity"), 2);
                    material.SetFloat("_Metallic", 0);
                    material.SetFloat("_ClearCoat", 0);
                    material.SetTexture("_MetallicGlossMap", null);
                }
                if (_ReflectionMode.floatValue != 3)
                {
                    XSStyles.SeparatorThin();
                    materialEditor.TexturePropertySingleLine(new GUIContent("Reflectivity Mask", "Mask for reflections."), _ReflectivityMask);
                    materialEditor.TextureScaleOffsetProperty(_ReflectivityMask);
                    materialEditor.ShaderProperty(_UVSetReflectivity, new GUIContent("UV Set", "The UV set to use for the Reflectivity Mask"), 2);
                    materialEditor.ShaderProperty(_Reflectivity, new GUIContent("Reflectivity", "The strength of the reflections."), 2);
                }
                if (_ReflectionMode.floatValue == 3)
                {
                    material.SetFloat("_Metallic", 0);
                    material.SetFloat("_ReflectionBlendMode", 0);
                    material.SetFloat("_ClearCoat", 0);
                }
            }

            showEmission = XSStyles.ShurikenFoldout("Emission", showEmission);
            if (showEmission)
            {
                materialEditor.TexturePropertySingleLine(new GUIContent("Emission Scroll Texture", "Emissive coloring. White to black, unless you want multiple colors."), _EmissionMap, _EmissionColor);
                materialEditor.TextureScaleOffsetProperty(_EmissionMap);

                if (isRave)
                {
                    materialEditor.TexturePropertySingleLine(new GUIContent("Emission Map", "Emissive Map"), _EmissionScaleTex);
                    materialEditor.VectorProperty(_EmissionSpeed, "Scroll Speed");
                }

                if (isSparkle)
                {
                    materialEditor.FloatProperty(_EmissionNoiseSizeCoeff, "Noise Size Coeff");
                    materialEditor.FloatProperty(_EmissionNoiseDensity, "Noise Density");
                    materialEditor.FloatProperty(_EmissionSparkleSpeed, "Sparkle Speed");
                    materialEditor.FloatProperty(_EmissionGreyShift, "Grey Shift");
                }

                materialEditor.ShaderProperty(_UVSetEmission, new GUIContent("UV Set", "The UV set to use for the Emission Map"), 2);
                materialEditor.ShaderProperty(_EmissionToDiffuse, new GUIContent("Tint To Diffuse", "Tints the emission to the Diffuse Color"), 2);

                XSStyles.SeparatorThin();
                materialEditor.ShaderProperty(_ScaleWithLight, new GUIContent("Scale w/ Light", "Scales the emission intensity based on how dark or bright the environment is."));
                if (_ScaleWithLight.floatValue == 0)
                {
                    materialEditor.ShaderProperty(_ScaleWithLightSensitivity, new GUIContent("Scaling Sensitivity", "How agressively the emission should scale with the light."));
                }
            }

            showRimlight = XSStyles.ShurikenFoldout("Rimlight", showRimlight);
            if (showRimlight)
            {
                materialEditor.ShaderProperty(_RimColor, new GUIContent("Rimlight Tint", "The Tint of the Rimlight."));
                materialEditor.ShaderProperty(_RimAlbedoTint, new GUIContent("Rim Albedo Tint", "How much the Albedo texture should effect the rimlight color."));
                materialEditor.ShaderProperty(_RimCubemapTint, new GUIContent("Rim Environment Tint", "How much the Environment cubemap should effect the rimlight color."));
                materialEditor.ShaderProperty(_RimAttenEffect, new GUIContent("Rim Attenuation Effect", "How much should realtime shadows mask out the rimlight?"));
                materialEditor.ShaderProperty(_RimIntensity, new GUIContent("Rimlight Intensity", "Strength of the Rimlight."));
                materialEditor.ShaderProperty(_RimRange, new GUIContent("Range", "Range of the Rim"), 2);
                materialEditor.ShaderProperty(_RimThreshold, new GUIContent("Threshold", "Threshold of the Rim"), 2);
                materialEditor.ShaderProperty(_RimSharpness, new GUIContent("Sharpness", "Sharpness of the Rim"), 2);
            }

            showSubsurface = XSStyles.ShurikenFoldout("Subsurface Scattering", showSubsurface);
            if (showSubsurface)
            {
                materialEditor.TexturePropertySingleLine(new GUIContent("Thickness Map", "Thickness Map, used to mask areas where subsurface can happen"), _ThicknessMap);
                materialEditor.TextureScaleOffsetProperty(_ThicknessMap);
                materialEditor.ShaderProperty(_UVSetThickness, new GUIContent("UV Set", "The UV set to use for the Thickness Map"), 2);
                XSStyles.constrainedShaderProperty(materialEditor, _SSColor, new GUIContent("Subsurface Color", "Subsurface Scattering Color"), 2);
                materialEditor.ShaderProperty(_SSDistortion, new GUIContent("Subsurface Distortion", "How much the subsurface should follow the normals of the mesh and/or normal map."), 2);
                materialEditor.ShaderProperty(_SSPower, new GUIContent("Subsurface Power", "Subsurface Power"), 2);
                materialEditor.ShaderProperty(_SSScale, new GUIContent("Subsurface Scale", "Subsurface Scale"), 2);
            }

            if (_AdvMode.floatValue == 1)
            {
                showAdvanced = XSStyles.ShurikenFoldout("Advanced Settings", showAdvanced);
                if (showAdvanced)
                {
                    materialEditor.ShaderProperty(_VertexColorAlbedo, new GUIContent("Vertex Color Albedo", "Multiplies the vertex color of the mesh by the Albedo texture to derive the final Albedo color."));
                    materialEditor.ShaderProperty(_Stencil, _Stencil.displayName);
                    materialEditor.ShaderProperty(_StencilComp, _StencilComp.displayName);
                    materialEditor.ShaderProperty(_StencilOp, _StencilOp.displayName);
                }
            }

            //Plugins for Patreon releases
            if (isPatreonShader)
            {
                if (isEyeTracking)
                {
                    showEyeTracking = XSStyles.ShurikenFoldout("Eye Tracking Settings", showEyeTracking);
                    if (showEyeTracking)
                    {
                        materialEditor.ShaderProperty(_LeftRightPan, new GUIContent("Left Right Adj.", "Adjusts the eyes manually left or right."));
                        materialEditor.ShaderProperty(_UpDownPan, new GUIContent("Up Down Adj.", "Adjusts the eyes manually up or down."));

                        XSStyles.SeparatorThin();
                        materialEditor.ShaderProperty(_AttentionSpan, new GUIContent("Attention Span", "How often should the eyes look at the target; 0 = never, 1 = always, 0.5 = half of the time."));
                        materialEditor.ShaderProperty(_FollowPower, new GUIContent("Follow Power", "The influence the target has on the eye"));
                        materialEditor.ShaderProperty(_LookSpeed, new GUIContent("Look Speed", "How fast the eye transitions to looking at the target"));
                        materialEditor.ShaderProperty(_Twitchyness, new GUIContent("Refocus Frequency", "How much should the eyes look around near the target?"));

                        XSStyles.SeparatorThin();
                        materialEditor.ShaderProperty(_IrisSize, new GUIContent("Iris Size", "Size of the iris"));
                        materialEditor.ShaderProperty(_FollowLimit, new GUIContent("Follow Limit", "Limits the angle from the front of the face on how far the eyes can track/rotate."));
                        materialEditor.ShaderProperty(_EyeOffsetLimit, new GUIContent("Offset Limit", "Limit for how far the eyes can turn"));
                    }
                }
            }
            //

            XSStyles.DoFooter();
        }
    }
示例#15
0
    static void SeperateRGBAandlphaChannel(string _texPath)
    {
        string assetRelativePath = GetRelativeAssetPath(_texPath);

        //设置文件只读
        SetTextureReadableEx(assetRelativePath);

        Texture2D sourcetex = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(Texture2D)) as Texture2D;

        if (!sourcetex)
        {
            Debug.LogError("Load Texture : " + sourcetex);
            return;
        }

        TextureImporter ti = null;

        try
        {
            ti = (TextureImporter)TextureImporter.GetAtPath(assetRelativePath);
        }
        catch
        {
            Debug.LogError("Load Texture : " + sourcetex);
            return;
        }
        if (ti == null)
        {
            return;
        }
        bool bGenerateMipMap = ti.mipmapEnabled;

        Texture2D rgbTex = new Texture2D(sourcetex.width, sourcetex.height, TextureFormat.RGB24, bGenerateMipMap);

        rgbTex.SetPixels(sourcetex.GetPixels());

        Texture2D mipMapTex = new Texture2D(sourcetex.width, sourcetex.height, TextureFormat.RGBA32, true);

        mipMapTex.SetPixels(sourcetex.GetPixels());

        mipMapTex.Apply();

        Color[] colors2rdLevel = mipMapTex.GetPixels(1);

        Color[] colorsAlpha = new Color[colors2rdLevel.Length];

        if (colors2rdLevel.Length != (mipMapTex.width) / 2 * (mipMapTex.height) / 2)
        {
            Debug.LogError("Size Error.");
            return;
        }

        bool bAlphaExist = false;

        for (int i = 0; i < colors2rdLevel.Length; ++i)
        {
            colorsAlpha[i].r = colors2rdLevel[i].a;
            colorsAlpha[i].g = colors2rdLevel[i].a;
            colorsAlpha[i].b = colors2rdLevel[i].a;

            if (!Mathf.Approximately(colors2rdLevel[i].a, 1.0f))
            {
                bAlphaExist = true;
            }
        }

        Texture2D alphaTex = null;

        if (bAlphaExist)
        {
            alphaTex = new Texture2D((sourcetex.width + 1) / 2, (sourcetex.height + 1) / 2, TextureFormat.RGB24, bGenerateMipMap);
        }
        else
        {
            alphaTex = new Texture2D(defaultWhiteTex.width, defaultWhiteTex.height, TextureFormat.RGB24, false);
        }

        alphaTex.SetPixels(colorsAlpha);

        rgbTex.Apply();

        alphaTex.Apply();

        byte[] bytes = rgbTex.EncodeToPNG();

        assetRelativePath = GetRGBTexPath(_texPath);

        File.WriteAllBytes(assetRelativePath, bytes);

        byte[] alphabytes = alphaTex.EncodeToPNG();

        string alphaTexRelativePath = GetAlphaTexPath(_texPath);

        File.WriteAllBytes(alphaTexRelativePath, alphabytes);

        ReImportAsset(assetRelativePath, rgbTex.width, rgbTex.height);

        ReImportAsset(alphaTexRelativePath, alphaTex.width, alphaTex.height);
    }
示例#16
0
    static void CheckStaticCommonIssues()
    {
        if (OVRManager.IsUnityAlphaOrBetaVersion())
        {
            AddFix("General", OVRManager.UnityAlphaOrBetaVersionWarningMessage, null, null);
        }

        if (QualitySettings.anisotropicFiltering != AnisotropicFiltering.Enable && QualitySettings.anisotropicFiltering != AnisotropicFiltering.ForceEnable)
        {
            AddFix("Optimize Aniso", "Anisotropic filtering is recommended for optimal image sharpness and GPU performance.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                // Ideally this would be multi-option: offer Enable or ForceEnable.
                QualitySettings.anisotropicFiltering = AnisotropicFiltering.Enable;
            }, null, "Fix");
        }

#if UNITY_ANDROID
        int recommendedPixelLightCount = 1;
#else
        int recommendedPixelLightCount = 3;
#endif

        if (QualitySettings.pixelLightCount > recommendedPixelLightCount)
        {
            AddFix("Optimize Pixel Light Count", "For GPU performance set no more than " + recommendedPixelLightCount + " pixel lights in Quality Settings (currently " + QualitySettings.pixelLightCount + ").", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                QualitySettings.pixelLightCount = recommendedPixelLightCount;
            }, null, "Fix");
        }

#if false
        // Should we recommend this?  Seems to be mutually exclusive w/ dynamic batching.
        if (!PlayerSettings.graphicsJobs)
        {
            AddFix("Optimize Graphics Jobs", "For CPU performance, please use graphics jobs.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                PlayerSettings.graphicsJobs = true;
            }, null, "Fix");
        }
#endif

#if UNITY_2017_2_OR_NEWER
        if ((!PlayerSettings.MTRendering || !PlayerSettings.GetMobileMTRendering(BuildTargetGroup.Android)))
#else
        if ((!PlayerSettings.MTRendering || !PlayerSettings.mobileMTRendering))
#endif
        {
            AddFix("Optimize MT Rendering", "For CPU performance, please enable multithreaded rendering.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
#if UNITY_2017_2_OR_NEWER
                PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Standalone, true);
                PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, true);
#else
                PlayerSettings.MTRendering = PlayerSettings.mobileMTRendering = true;
#endif
            }, null, "Fix");
        }

#if UNITY_ANDROID
        if (!PlayerSettings.use32BitDisplayBuffer)
        {
            AddFix("Optimize Display Buffer Format", "We recommend to enable use32BitDisplayBuffer.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                PlayerSettings.use32BitDisplayBuffer = true;
            }, null, "Fix");
        }
#endif

#if UNITY_2017_3_OR_NEWER && !UNITY_ANDROID
        if (!PlayerSettings.VROculus.dashSupport)
        {
            AddFix("Enable Dash Integration", "We recommend to enable Dash Integration for better user experience.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                PlayerSettings.VROculus.dashSupport = true;
            }, null, "Fix");
        }

        if (!PlayerSettings.VROculus.sharedDepthBuffer)
        {
            AddFix("Enable Depth Buffer Sharing", "We recommend to enable Depth Buffer Sharing for better user experience on Oculus Dash.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                PlayerSettings.VROculus.sharedDepthBuffer = true;
            }, null, "Fix");
        }
#endif

        BuildTargetGroup target = EditorUserBuildSettings.selectedBuildTargetGroup;
        var tier         = UnityEngine.Rendering.GraphicsTier.Tier1;
        var tierSettings = UnityEditor.Rendering.EditorGraphicsSettings.GetTierSettings(target, tier);

        if ((tierSettings.renderingPath == RenderingPath.DeferredShading ||
             tierSettings.renderingPath == RenderingPath.DeferredLighting))
        {
            AddFix("Optimize Rendering Path", "For CPU performance, please do not use deferred shading.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                tierSettings.renderingPath = RenderingPath.Forward;
                UnityEditor.Rendering.EditorGraphicsSettings.SetTierSettings(target, tier, tierSettings);
            }, null, "Use Forward");
        }

        if (PlayerSettings.stereoRenderingPath == StereoRenderingPath.MultiPass)
        {
            AddFix("Optimize Stereo Rendering", "For CPU performance, please enable single-pass or instanced stereo rendering.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                PlayerSettings.stereoRenderingPath = StereoRenderingPath.Instancing;
            }, null, "Fix");
        }

        if (LightmapSettings.lightmaps.Length > 0 && LightmapSettings.lightmapsMode != LightmapsMode.NonDirectional)
        {
            AddFix("Optimize Lightmap Directionality", "Switching from directional lightmaps to non-directional lightmaps can save a small amount of GPU time.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                LightmapSettings.lightmapsMode = LightmapsMode.NonDirectional;
            }, null, "Switch to non-directional lightmaps");
        }

        if (Lightmapping.realtimeGI)
        {
            AddFix("Disable Realtime GI", "Disabling real-time global illumination can improve GPU performance.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                Lightmapping.realtimeGI = false;
            }, null, "Set Lightmapping.realtimeGI = false.");
        }

        var lights = GameObject.FindObjectsOfType <Light>();
        for (int i = 0; i < lights.Length; ++i)
        {
#if UNITY_2017_3_OR_NEWER
            if (lights [i].type != LightType.Directional && !lights [i].bakingOutput.isBaked && IsLightBaked(lights[i]))
#else
            if (lights[i].type != LightType.Directional && !lights[i].isBaked && IsLightBaked(lights[i]))
#endif
            {
                AddFix("Unbaked Lights", "The following lights in the scene are marked as Baked, but they don't have up to date lightmap data. Generate the lightmap data, or set it to auto-generate, in Window->Lighting->Settings.", null, lights[i], null);
            }

            if (lights[i].shadows != LightShadows.None && !IsLightBaked(lights[i]))
            {
                AddFix("Optimize Shadows", "For CPU performance, consider disabling shadows on realtime lights.", delegate(UnityEngine.Object obj, bool last, int selected)
                {
                    Light thisLight   = (Light)obj;
                    thisLight.shadows = LightShadows.None;
                }, lights[i], "Set \"Shadow Type\" to \"No Shadows\"");
            }
        }

        var sources = GameObject.FindObjectsOfType <AudioSource>();
        if (sources.Length > 16)
        {
            List <AudioSource> playingAudioSources = new List <AudioSource>();
            foreach (var audioSource in sources)
            {
                if (audioSource.isPlaying)
                {
                    playingAudioSources.Add(audioSource);
                }
            }

            if (playingAudioSources.Count > 16)
            {
                // Sort playing audio sources by priority
                playingAudioSources.Sort(delegate(AudioSource x, AudioSource y)
                {
                    return(x.priority.CompareTo(y.priority));
                });
                for (int i = 16; i < playingAudioSources.Count; ++i)
                {
                    AddFix("Optimize Audio Source Count", "For CPU performance, please disable all but the top 16 AudioSources.", delegate(UnityEngine.Object obj, bool last, int selected)
                    {
                        AudioSource audioSource = (AudioSource)obj;
                        audioSource.enabled     = false;
                    }, playingAudioSources[i], "Disable");
                }
            }
        }

        var clips = GameObject.FindObjectsOfType <AudioClip>();
        for (int i = 0; i < clips.Length; ++i)
        {
            if (clips[i].loadType == AudioClipLoadType.DecompressOnLoad)
            {
                AddFix("Audio Loading", "For fast loading, please don't use decompress on load for audio clips", delegate(UnityEngine.Object obj, bool last, int selected)
                {
                    AudioClip thisClip = (AudioClip)obj;
                    if (selected == 0)
                    {
                        SetAudioLoadType(thisClip, AudioClipLoadType.CompressedInMemory, last);
                    }
                    else
                    {
                        SetAudioLoadType(thisClip, AudioClipLoadType.Streaming, last);
                    }
                }, clips[i], "Change to Compressed in Memory", "Change to Streaming");
            }

            if (clips[i].preloadAudioData)
            {
                AddFix("Audio Preload", "For fast loading, please don't preload data for audio clips.", delegate(UnityEngine.Object obj, bool last, int selected)
                {
                    SetAudioPreload(clips[i], false, last);
                }, clips[i], "Fix");
            }
        }

        if (Physics.defaultContactOffset < 0.01f)
        {
            AddFix("Optimize Contact Offset", "For CPU performance, please don't use default contact offset below 0.01.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                Physics.defaultContactOffset = 0.01f;
            }, null, "Fix");
        }

        if (Physics.sleepThreshold < 0.005f)
        {
            AddFix("Optimize Sleep Threshold", "For CPU performance, please don't use sleep threshold below 0.005.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                Physics.sleepThreshold = 0.005f;
            }, null, "Fix");
        }

        if (Physics.defaultSolverIterations > 8)
        {
            AddFix("Optimize Solver Iterations", "For CPU performance, please don't use excessive solver iteration counts.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                Physics.defaultSolverIterations = 8;
            }, null, "Fix");
        }

        var materials = Resources.FindObjectsOfTypeAll <Material>();
        for (int i = 0; i < materials.Length; ++i)
        {
            if (materials[i].shader.name.Contains("Parallax") || materials[i].IsKeywordEnabled("_PARALLAXMAP"))
            {
                AddFix("Optimize Shading", "For GPU performance, please don't use parallax-mapped materials.", delegate(UnityEngine.Object obj, bool last, int selected)
                {
                    Material thisMaterial = (Material)obj;
                    if (thisMaterial.IsKeywordEnabled("_PARALLAXMAP"))
                    {
                        thisMaterial.DisableKeyword("_PARALLAXMAP");
                    }

                    if (thisMaterial.shader.name.Contains("Parallax"))
                    {
                        var newName   = thisMaterial.shader.name.Replace("-ParallaxSpec", "-BumpSpec");
                        newName       = newName.Replace("-Parallax", "-Bump");
                        var newShader = Shader.Find(newName);
                        if (newShader)
                        {
                            thisMaterial.shader = newShader;
                        }
                        else
                        {
                            Debug.LogWarning("Unable to find a replacement for shader " + materials[i].shader.name);
                        }
                    }
                }, materials[i], "Fix");
            }
        }

        var renderers = GameObject.FindObjectsOfType <Renderer>();
        for (int i = 0; i < renderers.Length; ++i)
        {
            if (renderers[i].sharedMaterial == null)
            {
                AddFix("Instanced Materials", "Please avoid instanced materials on renderers.", null, renderers[i]);
            }
        }

        var overlays = GameObject.FindObjectsOfType <OVROverlay>();
        if (overlays.Length > 4)
        {
            AddFix("Optimize VR Layer Count", "For GPU performance, please use 4 or fewer VR layers.", delegate(UnityEngine.Object obj, bool last, int selected)
            {
                for (int i = 4; i < OVROverlay.instances.Length; ++i)
                {
                    OVROverlay.instances[i].enabled = false;
                }
            }, null, "Fix");
        }

        var splashScreen = PlayerSettings.virtualRealitySplashScreen;
        if (splashScreen != null)
        {
            if (splashScreen.filterMode != FilterMode.Trilinear)
            {
                AddFix("Optimize VR Splash Filtering", "For visual quality, please use trilinear filtering on your VR splash screen.", delegate(UnityEngine.Object obj, bool last, int EditorSelectedRenderState)
                {
                    var assetPath       = AssetDatabase.GetAssetPath(splashScreen);
                    var importer        = (TextureImporter)TextureImporter.GetAtPath(assetPath);
                    importer.filterMode = FilterMode.Trilinear;
                    AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
                }, null, "Fix");
            }

            if (splashScreen.mipmapCount <= 1)
            {
                AddFix("Generate VR Splash Mipmaps", "For visual quality, please use mipmaps with your VR splash screen.", delegate(UnityEngine.Object obj, bool last, int EditorSelectedRenderState)
                {
                    var assetPath          = AssetDatabase.GetAssetPath(splashScreen);
                    var importer           = (TextureImporter)TextureImporter.GetAtPath(assetPath);
                    importer.mipmapEnabled = true;
                    AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
                }, null, "Fix");
            }
        }
    }
示例#17
0
        private static void SetupURPMaterial(int pass, DiggerSystem diggerSystem, List <Texture2D> textures)
        {
            var material           = diggerSystem.Materials[pass];
            var expectedShaderName = $"Digger/URP/Mesh-Pass{pass}";

            if (!material || material.shader.name != expectedShaderName)
            {
                material = new Material(Shader.Find(expectedShaderName));
            }

            var tData = diggerSystem.Terrain.terrainData;

            if (tData.terrainLayers.Length <= 4 && diggerSystem.Terrain.materialTemplate.IsKeywordEnabled("_TERRAIN_BLEND_HEIGHT"))
            {
                material.EnableKeyword("_TERRAIN_BLEND_HEIGHT");
                material.SetFloat(EnableHeightBlend, 1);
                material.SetFloat(HeightTransition, diggerSystem.Terrain.materialTemplate.GetFloat("_HeightTransition"));
            }
            else
            {
                material.DisableKeyword("_TERRAIN_BLEND_HEIGHT");
                material.SetFloat(EnableHeightBlend, 0);
            }

            var normalmap = false;
            var maskmap   = false;
            var offset    = pass * TxtCountPerPass;

            for (var i = 0; i + offset < tData.terrainLayers.Length && i < TxtCountPerPass; i++)
            {
                var terrainLayer = tData.terrainLayers[i + offset];
                if (terrainLayer == null || terrainLayer.diffuseTexture == null)
                {
                    continue;
                }

                if (terrainLayer.normalMapTexture)
                {
                    normalmap = true;
                }
                if (terrainLayer.maskMapTexture)
                {
                    maskmap = true;
                }

                var importer = (TextureImporter)TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(terrainLayer.diffuseTexture));

                material.SetFloat($"_NumLayersCount", tData.terrainLayers.Length);
                material.SetFloat($"_NormalScale{i}", terrainLayer.normalScale);
                material.SetFloat($"_Metallic{i}", terrainLayer.metallic);
                material.SetFloat($"_Smoothness{i}", importer && importer.DoesSourceTextureHaveAlpha() ? 1 : terrainLayer.smoothness);
                material.SetFloat($"_LayerHasMask{i}", terrainLayer.maskMapTexture ? 1 : 0);
                material.SetVector($"_DiffuseRemapScale{i}", terrainLayer.diffuseRemapMax - terrainLayer.diffuseRemapMin);
                material.SetVector($"_MaskMapRemapScale{i}", terrainLayer.maskMapRemapMax);
                material.SetVector($"_MaskMapRemapOffset{i}", terrainLayer.maskMapRemapMin);
                material.SetTexture(SplatPrefixProperty + i, terrainLayer.diffuseTexture);
                material.SetTexture(NormalPrefixProperty + i, terrainLayer.normalMapTexture);
                material.SetTexture(MaskPrefixProperty + i, terrainLayer.maskMapTexture);
                material.SetTextureScale(SplatPrefixProperty + i,
                                         new Vector2(1f / terrainLayer.tileSize.x, 1f / terrainLayer.tileSize.y));
                material.SetTextureOffset(SplatPrefixProperty + i, terrainLayer.tileOffset);
                textures.Add(terrainLayer.diffuseTexture);
            }

            if (normalmap)
            {
                material.EnableKeyword("_NORMALMAP");
            }
            else
            {
                material.DisableKeyword("_NORMALMAP");
            }

            if (maskmap)
            {
                material.EnableKeyword("_MASKMAP");
            }
            else
            {
                material.DisableKeyword("_MASKMAP");
            }

            var matPath = Path.Combine(diggerSystem.BasePathData, $"meshMaterialPass{pass}.mat");

            material = EditorUtils.CreateOrReplaceAsset(material, matPath);
            AssetDatabase.ImportAsset(matPath, ImportAssetOptions.ForceUpdate);
            diggerSystem.Materials[pass] = material;
        }
示例#18
0
        static public void UpdateSpriteSlices(Texture texture, Atlas atlas)
        {
            string texturePath = AssetDatabase.GetAssetPath(texture.GetInstanceID());
            var    t           = (TextureImporter)TextureImporter.GetAtPath(texturePath);

            t.spriteImportMode = SpriteImportMode.Multiple;
            var spriteSheet = t.spritesheet;
            var sprites     = new List <SpriteMetaData>(spriteSheet);

            var regions = AtlasAssetInspector.GetRegions(atlas);

            char[] FilenameDelimiter = { '.' };
            int    updatedCount      = 0;
            int    addedCount        = 0;

            foreach (var r in regions)
            {
                string pageName    = r.page.name.Split(FilenameDelimiter, StringSplitOptions.RemoveEmptyEntries)[0];
                string textureName = texture.name;
                bool   pageMatch   = string.Equals(pageName, textureName, StringComparison.Ordinal);

//				if (pageMatch) {
//					int pw = r.page.width;
//					int ph = r.page.height;
//					bool mismatchSize = pw != texture.width || pw > t.maxTextureSize || ph != texture.height || ph > t.maxTextureSize;
//					if (mismatchSize)
//						Debug.LogWarningFormat("Size mismatch found.\nExpected atlas size is {0}x{1}. Texture Import Max Size of texture '{2}'({4}x{5}) is currently set to {3}.", pw, ph, texture.name, t.maxTextureSize, texture.width, texture.height);
//				}

                int spriteIndex = pageMatch ? sprites.FindIndex(
                    (s) => string.Equals(s.name, r.name, StringComparison.Ordinal)
                    ) : -1;
                bool spriteNameMatchExists = spriteIndex >= 0;

                if (pageMatch)
                {
                    Rect spriteRect = new Rect();

                    if (r.rotate)
                    {
                        spriteRect.width  = r.height;
                        spriteRect.height = r.width;
                    }
                    else
                    {
                        spriteRect.width  = r.width;
                        spriteRect.height = r.height;
                    }
                    spriteRect.x = r.x;
                    spriteRect.y = r.page.height - spriteRect.height - r.y;

                    if (spriteNameMatchExists)
                    {
                        var s = sprites[spriteIndex];
                        s.rect = spriteRect;
                        sprites[spriteIndex] = s;
                        updatedCount++;
                    }
                    else
                    {
                        sprites.Add(new SpriteMetaData {
                            name  = r.name,
                            pivot = new Vector2(0.5f, 0.5f),
                            rect  = spriteRect
                        });
                        addedCount++;
                    }
                }
            }

            t.spritesheet = sprites.ToArray();
            EditorUtility.SetDirty(t);
            AssetDatabase.ImportAsset(texturePath, ImportAssetOptions.ForceUpdate);
            EditorGUIUtility.PingObject(texture);
            Debug.Log(string.Format("Applied sprite slices to {2}. {0} added. {1} updated.", addedCount, updatedCount, texture.name));
        }
示例#19
0
        void SaveGeneratedMapData()
        {
                        #if UNITY_EDITOR
            if (string.IsNullOrEmpty(outputFolder))
            {
                outputFolder = "CustomMap";
            }

            string path = GetGenerationMapOutputPath();
            if (string.IsNullOrEmpty(path))
            {
                Debug.LogError("Could not find WMSK folder.");
                return;
            }

            Directory.CreateDirectory(path);
            if (!Directory.Exists(path))
            {
                EditorUtility.DisplayDialog("Invalid output folder", "The path " + path + " is no valid.", "Ok");
                return;
            }

            // Set Geodata folder to custom path
            _map.geodataResourcesPath = "WMSK/Geodata/" + outputFolder;

            // Save country data
            string fullPathName = path + "/" + GetCountryGeoDataFileName();
            string data         = _map.GetCountryGeoData();
            File.WriteAllText(fullPathName, data, System.Text.Encoding.UTF8);
            AssetDatabase.ImportAsset(fullPathName);

            // Save province data
            fullPathName = path + "/" + GetProvinceGeoDataFileName();
            data         = _map.GetProvinceGeoData();
            File.WriteAllText(fullPathName, data, System.Text.Encoding.UTF8);
            AssetDatabase.ImportAsset(fullPathName);

            // Save cities
            fullPathName = path + "/" + GetCityGeoDataFileName();
            data         = _map.GetCityGeoData();
            File.WriteAllText(fullPathName, data, System.Text.Encoding.UTF8);
            AssetDatabase.ImportAsset(fullPathName);

            // Save heightmap
            byte[] bytes      = heightMapTexture.EncodeToPNG();
            string outputFile = path + "/heightmap.png";
            File.WriteAllBytes(outputFile, bytes);
            AssetDatabase.ImportAsset(outputFile);
            TextureImporter timp = (TextureImporter)TextureImporter.GetAtPath(outputFile);
            timp.isReadable = true;
            timp.SaveAndReimport();

            // Save background texture
            bytes      = backgroundTexture.EncodeToPNG();
            outputFile = path + "/worldColors.png";
            File.WriteAllBytes(outputFile, bytes);
            AssetDatabase.ImportAsset(outputFile);
            timp            = (TextureImporter)TextureImporter.GetAtPath(outputFile);
            timp.isReadable = true;
            timp.SaveAndReimport();

            // Save normal map texture
            if (generateNormalMap)
            {
                bytes      = heightMapTexture.EncodeToPNG();
                outputFile = path + "/normalMap.png";
                File.WriteAllBytes(outputFile, bytes);
                AssetDatabase.ImportAsset(outputFile);
                timp                    = (TextureImporter)TextureImporter.GetAtPath(outputFile);
                timp.textureType        = TextureImporterType.NormalMap;
                timp.heightmapScale     = normalMapBumpiness;
                timp.convertToNormalmap = true;
                timp.isReadable         = true;
                timp.SaveAndReimport();
                _map.earthBumpMapTexture = Resources.Load <Texture2D> (_map.geodataResourcesPath + "/normalMap");
                _map.earthBumpEnabled    = true;
            }
            else
            {
                _map.earthBumpMapTexture = null;
                _map.earthBumpEnabled    = false;
            }

            // Save water mask texture
            bytes      = waterMaskTexture.EncodeToPNG();
            outputFile = path + "/waterMask.png";
            File.WriteAllBytes(outputFile, bytes);
            AssetDatabase.ImportAsset(outputFile);
            timp            = (TextureImporter)TextureImporter.GetAtPath(outputFile);
            timp.isReadable = true;
            timp.SaveAndReimport();

            // Set textures
            _map.waterMask        = Resources.Load <Texture2D> (_map.geodataResourcesPath + "/waterMask");
            _map.earthTexture     = Resources.Load <Texture2D> (_map.geodataResourcesPath + "/worldColors");
            _map.heightMapTexture = Resources.Load <Texture2D> (_map.geodataResourcesPath + "/heightmap");
                        #endif
        }
    static void RemoveResource()
    {
        LibaryAssetSetting _assetSetting = Resources.Load <LibaryAssetSetting>("AssetLibarySetting");

        if (_assetSetting == null)
        {
            return;
        }
        string             path         = AssetDatabase.GetAssetPath(_assetSetting);
        LibaryAssetSetting assetSetting = AssetDatabase.LoadAssetAtPath <LibaryAssetSetting>(path);

        if (assetSetting == null)
        {
            return;
        }
        // 选择的要保存的对象
        Dictionary <string, List <string> > dictMsg = assetSetting.GetAssetDict();

        Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        foreach (Object item in selection)
        {
            if (item == null || item.GetType() == typeof(DefaultAsset))
            {
                continue;
            }
            if (ResLibaryConfig.ExistType.ContainsValue(item.GetType().Name))
            {
                if (item.GetType() == typeof(Texture2D))
                {
                    string          tex2dpath       = AssetDatabase.GetAssetPath(item);
                    TextureImporter textureImporter = TextureImporter.GetAtPath(tex2dpath) as TextureImporter;
                    if (textureImporter.textureType == TextureImporterType.Sprite)
                    {
                        Object[] sprs = AssetDatabase.LoadAllAssetsAtPath(tex2dpath);
                        for (int i = 0; i < sprs.Length; i++)
                        {
                            Object spr = sprs[i];

                            if (spr != null && spr.GetType() == typeof(Sprite))
                            {
                                List <string> sprslist;
                                dictMsg.TryGetValue(spr.GetType().Name, out sprslist);
                                if (sprslist != null && sprslist.Contains(spr.name))
                                {
                                    int dindex = sprslist.FindLastIndex(x => x == spr.name);
                                    assetSetting.DelResToLibary(spr.GetType().Name, dindex);
                                }
                            }
                        }

                        if (textureImporter.spriteImportMode != SpriteImportMode.Multiple)
                        {
                            List <string> sprslist;
                            dictMsg.TryGetValue(item.GetType().Name, out sprslist);
                            if (sprslist != null && sprslist.Contains(item.name))
                            {
                                int dindex = sprslist.FindLastIndex(x => x == item.name);
                                assetSetting.DelResToLibary(item.GetType().Name, dindex);
                            }
                        }
                    }
                }
            }
            else
            {
                List <string> sprslist;
                dictMsg.TryGetValue(item.GetType().Name, out sprslist);
                if (sprslist != null && sprslist.Contains(item.name))
                {
                    int dindex = sprslist.FindLastIndex(x => x == item.name);
                    assetSetting.DelResToLibary(item.GetType().Name, dindex);
                }
            }
        }
        AssetDatabase.ImportAsset(path);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
示例#21
0
    private static Result CropWithRect(RectOptions rectOptions, Texture2D texture, Rect r, int xMod, int yMod,
                                       string path)
    {
        if (r.height < 0 || r.width < 0)
        {
            return(new Result()
            {
                texture = texture, xRect = -1, yRect = -1
            });
        }


        Texture2D result   = new Texture2D((int)r.width, (int)r.height);
        var       importer = (TextureImporter)TextureImporter.GetAtPath(path);
        var       sprites  = new SpriteMetaData [importer.spritesheet.Length];
        float     xRect    = r.x;
        float     yRect    = r.y;

        if (r.width != 0 && r.height != 0)
        {
            float widthRect  = r.width;
            float heightRect = r.height;

            switch (rectOptions)
            {
            case RectOptions.Center:
                xRect = (texture.width - r.width) / 2;
                yRect = (texture.height - r.height) / 2;
                break;

            case RectOptions.BottomRight:
                xRect = texture.width - r.width;
                break;

            case RectOptions.BottomLeft:
                break;

            case RectOptions.TopLeft:
                yRect = texture.height - r.height;
                break;

            case RectOptions.TopRight:
                xRect = texture.width - r.width;
                yRect = texture.height - r.height;
                break;

            case RectOptions.Custom:
                float tempWidth  = texture.width - r.width - xMod;
                float tempHeight = texture.height - r.height - yMod;
                xRect = tempWidth > texture.width ? 0 : tempWidth;
                yRect = tempHeight > texture.height ? 0 : tempHeight;
                break;
            }

            if (texture.width < r.x + r.width || texture.height < r.y + r.height || xRect > r.x + texture.width ||
                yRect > r.y + texture.height || xRect < 0 || yRect < 0 || r.width < 0 || r.height < 0)
            {
                //EditorUtility.DisplayDialog("Set value crop", "Set value crop (Width and Height > 0) less than origin texture size \n" + texture.name + " wrong size", "ReSet");

                return(new Result()
                {
                    texture = result, xRect = xRect, yRect = yRect
                });
            }

            result.SetPixels(texture.GetPixels(Mathf.FloorToInt(xRect), Mathf.FloorToInt(yRect),
                                               Mathf.FloorToInt(widthRect), Mathf.FloorToInt(heightRect)));
            result.Apply();
        }

        return(new Result()
        {
            texture = result, yRect = yRect, xRect = xRect
        });
    }
示例#22
0
        //Analyzes textures in library, finds identical textures, removes duplicates
        public int removeTextures()
        {
            string[]         assetLib   = AssetDatabase.FindAssets("t:texture2D");
            List <string>    textureLib = new List <string>();
            List <Texture2D> duplicates = new List <Texture2D>();
            bool             remapped;
            List <Texture2D> remove = new List <Texture2D>();

            for (int i = 0; i < assetLib.Length; i++)
            {
                if (!AssetDatabase.GUIDToAssetPath(assetLib[i]).Contains(".cubemap"))
                {
                    textureLib.Add(assetLib[i]);
                }
            }
            string[] path = new string[textureLib.Count];
            byte[]   texData;
            int      index;

            int[]       texSize         = new int[textureLib.Count];
            Texture2D[] compareTextures = new Texture2D[textureLib.Count];
            Color32[]   comparePixels1;
            Color32[]   comparePixels2;

            bool dup  = false;
            bool orig = false;

            TextureImporterType[] texTypes = new TextureImporterType[textureLib.Count];

            string newPath = "Removed Assets";

            if (!Directory.Exists(newPath))
            {
                CreateFileStructure();
            }

            //Imports all textures as "advanced" so the pixel information is readable
            for (int i = 0; i < textureLib.Count; i++)
            {
                path[i]    = AssetDatabase.GUIDToAssetPath(textureLib[i]);
                texData    = File.ReadAllBytes(path[i]);
                texSize[i] = texData.Length;
                TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(path[i]);
                texTypes[i]             = texImporter.textureType;
                texImporter.textureType = TextureImporterType.Advanced;
                texImporter.isReadable  = true;
                compareTextures[i]      = AssetDatabase.LoadAssetAtPath(path[i], typeof(Texture2D)) as Texture2D;
                AssetDatabase.ImportAsset(path[i], ImportAssetOptions.ForceUpdate);
            }

            for (int a = 0; a < textureLib.Count; a++)
            {
                for (int b = 1; b < textureLib.Count - a; b++)
                {
                    index = a + b;
                    //is the size of texture[a] equal to the size of each subsesquent texture?
                    if (texSize[a] == texSize[index])
                    {
                        comparePixels1 = compareTextures[a].GetPixels32();
                        comparePixels2 = compareTextures[index].GetPixels32();
                        //does texture[a] have the same number of pixels?
                        if (comparePixels1.Length == comparePixels2.Length)
                        {
                            //is each pixel in texture[a] the same color?
                            for (int c = 0; c < comparePixels1.Length; c++)
                            {
                                if (!comparePixels1[c].Equals(comparePixels2[c]))
                                {
                                    c   = comparePixels1.Length;
                                    dup = false;
                                }
                                else
                                {
                                    dup = true;
                                }
                            }
                            //add the texture that matches texture[a] to the list of duplicates
                            if (dup)
                            {
                                duplicates.Add(compareTextures[index]);
                                //if texture[a] doesn't already exist in the duplicates, it is the original texture
                                for (int d = 0; d < duplicates.Count; d++)
                                {
                                    if (compareTextures[a] == duplicates[d])
                                    {
                                        orig = false;
                                        d    = duplicates.Count;
                                    }
                                    else
                                    {
                                        orig = true;
                                    }
                                }
                                //if texture[a] is the original texture, remap the duplicate texture to it. if able to remap, add the duplicate texture to the list of textures to remove
                                if (orig)
                                {
                                    remapped = remapMaterials(compareTextures[a], compareTextures[index], texTypes[a]);
                                    if (remapped)
                                    {
                                        remove.Add(compareTextures[index]);
                                    }
                                    if (path[index].Contains("Perfect Parallel Libraries"))
                                    {
                                        remove.Add(compareTextures[index]);
                                        remove.Add(compareTextures[a]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //Reformats textures to be their original type
            for (int i = 0; i < textureLib.Count; i++)
            {
                path[i] = AssetDatabase.GUIDToAssetPath(textureLib[i]);
                if (File.Exists(path[i]))
                {
                    TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(path[i]);
                    texImporter.textureType = texTypes[i];
                    AssetDatabase.ImportAsset(path[i], ImportAssetOptions.ForceUpdate);
                }
            }
            //Moves remapped duplicate textures out of library; excludes if they are in the library associated with the course
            for (int i = 0; i < remove.Count; i++)
            {
                string currentAsset = AssetDatabase.GetAssetPath(remove.ElementAt(i).GetInstanceID());
                if (File.Exists(currentAsset) && !currentAsset.Contains(Course.LibraryName))
                {
                    File.Move(currentAsset, "Removed Assets/" + currentAsset);
                    if (File.Exists(currentAsset + ".meta"))
                    {
                        File.Move(currentAsset + ".meta", "Removed Assets/" + currentAsset + ".meta");
                    }
                    File.AppendAllText("Removed Assets/duplicateTextures.txt", currentAsset + "\r\n");
                    AssetDatabase.Refresh();
                }
            }
            return(remove.Count);
        }
示例#23
0
    static void printLightMapIndex()
    {
        TextureImporterFormat format = TextureImporterFormat.ASTC_4x4;
        string root = AssetDatabase.GetAssetPath(Lightmapping.lightingDataAsset);

        root = root.Substring(0, root.LastIndexOf('/'));
        string        end1        = "_comp_shadowmask.png";
        string        end2        = "_comp_light.exr";
        var           s           = UnityEngine.SceneManagement.SceneManager.GetActiveScene();
        string        end3        = "_LightSM.tga";
        List <string> found_paths = new List <string>();

        int width  = 512;
        int height = 512;

        string [] paths = System.IO.Directory.GetFiles(root);
        Dictionary <int, string> lightMapTemp = new Dictionary <int, string>();
        int maxIndex = -1;

        for (int i = 0; i < paths.Length; i++)
        {
            string path = paths[i];
            if (path.EndsWith(end1))
            {
                string heater = path.Substring(0, path.Length - end1.Length);
                int    index  = int.Parse(heater.Substring(heater.LastIndexOf('-') + 1));
                maxIndex = Mathf.Max(index, maxIndex);
                string path2 = heater + end2;
                if (System.IO.File.Exists(path2))
                {
                    Texture2D t  = AssetDatabase.LoadAssetAtPath <Texture2D>(path);
                    Texture2D t2 = AssetDatabase.LoadAssetAtPath <Texture2D>(path2);
                    found_paths.Add(path);
                    found_paths.Add(path2);
                    width  = t.width;
                    height = t.height;

                    RenderTexture rt  = RenderTexture.GetTemporary(t.width, t.height, 0);
                    Material      mat = new Material(Shader.Find("Hidden/HdrToHalfColor"));
                    mat.SetTexture("_MainTex", t2);
                    mat.SetTexture("_MainTex2", t);
                    Graphics.Blit(t2, rt, mat);

                    RenderTexture.active = rt;
                    Texture2D png = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false);
                    png.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);

                    byte[] bytes = EncodeToTGAExtension.EncodeToTGA(png, 4);
                    string path3 = heater + end3;
                    System.IO.File.WriteAllBytes(path3, bytes);

                    AssetDatabase.ImportAsset(path3);

                    TextureFormatHelper.ModifyTextureFormat(path3, "iPhone", format);
                    TextureFormatHelper.ModifyTextureFormat(path3, "Android", format);
                    TextureImporter texImporter = TextureImporter.GetAtPath(path3) as TextureImporter;
                    texImporter.isReadable = true;

                    GameObject.DestroyImmediate(png, true);

                    RenderTexture.ReleaseTemporary(rt);

                    GameObject.DestroyImmediate(t, false);
                    GameObject.DestroyImmediate(t2, false);;
                    lightMapTemp[index] = path3;
                }
            }
        }
        Texture2DArray texture2DArray = new Texture2DArray(width, height, maxIndex + 1, TextureFormat.ASTC_4x4, true);


        foreach (var kp in lightMapTemp)
        {
            AssetDatabase.ImportAsset(kp.Value);
            Texture2D t = AssetDatabase.LoadAssetAtPath <Texture2D>(kp.Value);
            Graphics.CopyTexture(t, 0, texture2DArray, kp.Key);
            texture2DArray.Apply();
            GameObject.DestroyImmediate(t, true);
            AssetDatabase.DeleteAsset(kp.Value);
            //System.IO.File.Delete(kp.Value) ;
        }
        texture2DArray.wrapMode   = TextureWrapMode.Clamp;
        texture2DArray.filterMode = FilterMode.Bilinear;
        string arrayPath = root + "\\" + s.name + "_LMSM.asset";

        AssetDatabase.CreateAsset(texture2DArray, arrayPath);
        AssetDatabase.ImportAsset(arrayPath);
        ShadowMarkTex2dAry sma = GameObject.FindObjectOfType <ShadowMarkTex2dAry>();

        if (null == sma)
        {
            GameObject g = null;
            if (null != Camera.main)
            {
                g = Camera.main.gameObject;
            }
            else
            {
                g = new GameObject("Camera");
                g.AddComponent <Camera>();
            }
            sma = g.AddComponent <ShadowMarkTex2dAry>();
        }
        sma.shadowMark = AssetDatabase.LoadAssetAtPath <Texture2DArray>(arrayPath);

        AddCmpToRender();

        //Texture2D empty = new Texture2D(1, 1,TextureFormat.RGBA32,false);
        //empty.SetPixel(0, 0, Color.white);
        for (int i = 0; i < found_paths.Count; i++)
        {
            var str = found_paths[i];
            //System.IO.File.WriteAllBytes(str,empty.EncodeToPNG());
            //AssetDatabase.ImportAsset(str);
            AssetDatabase.DeleteAsset(str);
        }

        EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());
        //GameObject.DestroyImmediate(empty, true);
    }
示例#24
0
    void BuildWhenReadable()
    {
        var texturePath = AssetDatabase.GetAssetPath(font.texture);
        var importer    = TextureImporter.GetAtPath(texturePath) as TextureImporter;

        if (!SupportedTextureFormat(importer))
        {
            if (EditorUtility.DisplayDialog(
                    "Unsupported Texture Format",
                    "Unsupported texture format. Needs to be ARGB32, RGBA32, RGB24, Alpha8 or DXT. "
                    + "Change to ARGB32 now?",
                    "Yes", "No"))
            {
                importer.textureFormat = TextureImporterFormat.ARGB32;
                AssetDatabase.ImportAsset(texturePath, ImportAssetOptions.ForceUpdate);
            }
        }

        font.createStatus = MadFont.CreateStatus.Ok;

        pixels     = font.texture.GetPixels();
        lineHeight = font.texture.height / font.linesCount;

        bool  atGlyph           = false;
        int   currentGlyphIndex = -1;
        float fillFactor        = 0;
        int   fillFactorCount   = 0;

        for (int line = 0; line < font.linesCount; ++line)
        {
            int y = (int)Mathf.Floor(line * lineHeight);
            int x = 0;

            for (; x < font.texture.width; ++x)
            {
                if (!IsEmpty(line, x))
                {
                    if (!atGlyph)
                    {
                        atGlyph         = true;
                        fillFactor      = 0;
                        fillFactorCount = 0;

                        if (font.glyphs.Length == currentGlyphIndex + 1)
                        {
                            Debug.LogError("No more glyphs! Have you defined all glyphs?");
                            font.createStatus = MadFont.CreateStatus.TooMuchGlypsFound;
                            break;
                        }

                        glyphChar   = font.glyphs[++currentGlyphIndex];
                        glyphX      = x / (float)font.texture.width;
                        glyphY      = y / (float)font.texture.height;
                        glyphHeight = lineHeight / font.texture.height;
                    }

                    fillFactor += FillFactor(line, x);
                    fillFactorCount++;
                }
                else     // IsEmpty
                {
                    if (atGlyph)
                    {
                        // add glyph only if its fill factor is big enough
                        fillFactor /= fillFactorCount;
                        if (fillFactor >= font.fillFactorTolerance)
                        {
                            glyphWidth = (x / (float)font.texture.width) - glyphX;
                            AddGlyph();
                        }
                        else
                        {
                            currentGlyphIndex--;
                        }

                        atGlyph = false;
                    }
                }
            }

            if (atGlyph)
            {
                glyphWidth = ((x - 1) / (float)font.texture.width) - glyphX;
                AddGlyph();
                atGlyph = false;
            }
        }

        // check correctness
        if (currentGlyphIndex + 1 < font.glyphs.Length)
        {
            Debug.LogWarning(
                string.Format("Not all glyphs used (used={0}, expected={1})",
                              currentGlyphIndex + 1, font.glyphs.Length));
            font.createStatus = MadFont.CreateStatus.TooMuchGlypsDefined;
        }

        font.dimensions = fontString.ToString();
        BuildFinalize();
    }
示例#25
0
    void OnGUI()
    {
        this.minSize = new Vector2(355, 500);

        #region fonts variables
        var bold     = new GUIStyle("label");
        var boldFold = new GUIStyle("foldout");
        bold.fontStyle     = FontStyle.Bold;
        bold.fontSize      = 14;
        boldFold.fontStyle = FontStyle.Bold;

        var Slim = new GUIStyle("label");
        Slim.fontStyle = FontStyle.Normal;
        Slim.fontSize  = 10;

        var style = new GUIStyle("label");
        style.wordWrap = true;
        #endregion fonts variables

        _UMA = GameObject.Find("UMA");
        if (_UMA == null)
        {
            _UMA      = (GameObject)PrefabUtility.InstantiatePrefab(Resources.Load("UMA"));
            _UMA.name = "DK_UMA";
            _UMA      = GameObject.Find("UMA");
        }
        if (_UMA_Variables == null)
        {
            _UMA_Variables = _UMA.GetComponent <UMA_Variables>();
        }
        if (_UMA_Variables == null)
        {
            _UMA_Variables = _UMA.AddComponent <UMA_Variables>();
        }

        #region Menu
        using (new Horizontal()) {
            GUILayout.Label("UMA Elements", "toolbarbutton", GUILayout.ExpandWidth(true));
            if (showAbout == true)
            {
                GUI.color = Green;
            }
            else
            {
                GUI.color = Color.white;
            }
            if (GUILayout.Button("About", "toolbarbutton", GUILayout.ExpandWidth(false)))
            {
                if (showAbout == true)
                {
                    showAbout = false;
                }
                else
                {
                    showAbout = true;
                }
            }
            if (Helper)
            {
                GUI.color = Green;
            }
            else
            {
                GUI.color = Color.yellow;
            }
            if (GUILayout.Button("?", "toolbarbutton", GUILayout.ExpandWidth(false)))
            {
                if (Helper)
                {
                    Helper = false;
                }
                else
                {
                    Helper = true;
                }
            }
        }
        if (!showAbout)
        {
            // Libraries
            GUILayout.Space(5);
            using (new Horizontal()) {
                GUI.color = Color.white;
                GUILayout.Label("Libraries", "toolbarbutton", GUILayout.ExpandWidth(true));
                if (ShowLibs)
                {
                    GUI.color = Green;
                }
                else
                {
                    GUI.color = Color.gray;
                }
                if (GUILayout.Button("Show", "toolbarbutton", GUILayout.ExpandWidth(false)))
                {
                    if (ShowLibs)
                    {
                        ShowLibs = false;
                    }
                    else
                    {
                        ShowLibs = true;
                    }
                }
            }

            // libraries variables
            _SlotLibrary = _UMA_Variables._SlotLibrary;
            if (_SlotLibrary == null)
            {
                try{
                    _UMA_Variables._SlotLibrary = GameObject.Find("SlotLibrary").GetComponent <SlotLibrary>();
                }catch (NullReferenceException) { Debug.LogError("UMA is not installed in your scene, please install UMA."); }
            }

            _OverlayLibrary = _UMA_Variables._OverlayLibrary;
            if (_OverlayLibrary == null)
            {
                try{
                    _UMA_Variables._OverlayLibrary = GameObject.Find("OverlayLibrary").GetComponent <OverlayLibrary>();
                }catch (NullReferenceException) { Debug.LogError("UMA is not installed in your scene, please install UMA."); }
            }
            if (ShowLibs)
            {
                using (new Horizontal()) {
                    if (_SlotLibrary)
                    {
                        GUI.color = Color.white;
                        GUILayout.TextField(_SlotLibrary.name, 256, style, GUILayout.Width(110));
                        if (GUILayout.Button("Change", GUILayout.ExpandWidth(false)))
                        {
                            OpenChooseLibWin();
                            UMAChangeLibrary.CurrentLibrary = _SlotLibrary.gameObject;
                        }
                    }
                    else
                    {
                        GUILayout.Label("No Slots Library", GUILayout.Width(120));
                        if (GUILayout.Button("Find", GUILayout.ExpandWidth(false)))
                        {
                            _UMA_Variables._SlotLibrary = GameObject.Find("SlotLibrary").GetComponent <SlotLibrary>();
                        }
                    }

                    if (_OverlayLibrary)
                    {
                        GUI.color = Color.white;
                        GUILayout.TextField(_OverlayLibrary.name, 256, style, GUILayout.Width(110));
                        if (GUILayout.Button("Change", GUILayout.ExpandWidth(false)))
                        {
                            OpenChooseLibWin();
                            UMAChangeLibrary.CurrentLibrary = _OverlayLibrary.gameObject;
                        }
                    }
                    else
                    {
                        GUILayout.Label("No Overlay Library", GUILayout.Width(120));
                        if (GUILayout.Button("Find", GUILayout.ExpandWidth(false)))
                        {
                            _UMA_Variables._OverlayLibrary = GameObject.Find("OverlayLibrary").GetComponent <OverlayLibrary>();
                        }
                    }
                }
            }

            #region Actions
            GUILayout.Space(5);
            GUI.color = Color.white;
            GUILayout.Label("Options to Detect assets", "toolbarbutton", GUILayout.ExpandWidth(true));
            using (new Horizontal()) {
                GUI.color = Green;
                if (GUILayout.Button("Search all Elements in the project", GUILayout.ExpandWidth(true)))
                {
                    //	Debug.Log ("Test");
                    Action = "Detecting";
                    SearchUMASlots();
                    SearchUMAOverlays();
                    //	Done = "Done";
                }

                if (GUILayout.Button("Previews (Double clic)", GUILayout.ExpandWidth(true)))
                {
                    //	PreviewsList.Clear();
                    MakePreviews();
                }
            }

            using (new Horizontal()) {
                try {
                    if (_SlotLibrary && _OverlayLibrary && GUILayout.Button("Add all UMA Elements to the Libraries", GUILayout.ExpandWidth(true)))
                    {
                        //	Done4 = "Done";
                        AddToUMALib();
                    }
                }catch (ArgumentException) {}
            }

            #endregion Actions
            #endregion Menu

            #region Lists
            GUILayout.Space(5);
            using (new Horizontal()) {
                GUI.color = Color.white;
                GUILayout.Label("List of Elements", "toolbarbutton", GUILayout.ExpandWidth(true));

                if (Showslot)
                {
                    GUI.color = Color.cyan;
                }
                else
                {
                    GUI.color = Color.gray;
                }
                if (GUILayout.Button("UMA slots", "toolbarbutton", GUILayout.Width(85)))
                {
                    if (Showslot)
                    {
                        //	ShowUMA = false;
                        Showslot = false;
                    }
                    else
                    {
                        //	ShowUMA = true;
                        Showslot = true;
                    }
                }
                if (InfoSlots)
                {
                    GUI.color = Green;
                }
                else
                {
                    GUI.color = Color.gray;
                }
                if (GUILayout.Button("Info", "toolbarbutton", GUILayout.ExpandWidth(false)))
                {
                    if (InfoSlots)
                    {
                        InfoSlots = false;
                    }
                    else
                    {
                        InfoSlots = true;
                    }
                }
                if (Showoverlay)
                {
                    GUI.color = Color.cyan;
                }
                else
                {
                    GUI.color = Color.gray;
                }
                if (GUILayout.Button("UMA overlays", "toolbarbutton", GUILayout.Width(85)))
                {
                    if (Showoverlay)
                    {
                        //	ShowUMA = false;
                        Showoverlay = false;
                    }
                    else
                    {
                        //	ShowUMA = true;
                        Showoverlay = true;
                    }
                }

                if (InfoOverlays)
                {
                    GUI.color = Green;
                }
                else
                {
                    GUI.color = Color.gray;
                }
                if (GUILayout.Button("Info", "toolbarbutton", GUILayout.ExpandWidth(false)))
                {
                    if (InfoOverlays)
                    {
                        InfoOverlays = false;
                    }
                    else
                    {
                        InfoOverlays = true;
                    }
                }
            }
            #region Search
            using (new Horizontal()) {
                GUI.color = Color.white;
                GUILayout.Label("Search for :", GUILayout.ExpandWidth(false));
                SearchString = GUILayout.TextField(SearchString, 100, GUILayout.ExpandWidth(true));
            }
            #endregion Search

            using (new Horizontal()) {
                using (new ScrollView(ref scroll))      {
                    if (Showslot)
                    {
                        using (new Horizontal()) {
                            // UMA Slots
                            GUI.color = Color.cyan;
                            GUILayout.Label("UMA Slots (" + _UMA_Variables.UMASlotsList.Count.ToString() + ")", "toolbarbutton", GUILayout.ExpandWidth(true));
                            if (InfoSlots)
                            {
                                GUI.color = Green;
                            }
                            else
                            {
                                GUI.color = Color.gray;
                            }

                            if (Showslot)
                            {
                                GUI.color = Green;
                            }
                            else
                            {
                                GUI.color = Color.gray;
                            }
                            if (GUILayout.Button("Show", "toolbarbutton", GUILayout.ExpandWidth(false)))
                            {
                                if (Showslot)
                                {
                                    Showslot = false;
                                }
                                else
                                {
                                    Showslot = true;
                                }
                            }
                        }
                    }
                    if (ShowUMA && Showslot && _UMA_Variables.UMASlotsList.Count > 0)
                    {
                        #region Helper
                        // Helper
                        GUI.color = Color.white;
                        if (Helper)
                        {
                            GUILayout.TextField("Click on the name to select a Slot.", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true));
                        }
                        #endregion Helper

                        for (int i = 0; i < _UMA_Variables.UMASlotsList.Count; i++)
                        {
                            Texture2D Preview;
                            if (_UMA_Variables.UMASlotsList[i] != null && (SearchString == "" ||
                                                                           _UMA_Variables.UMASlotsList[i].name.ToLower().Contains(SearchString.ToLower())))
                            {
                                using (new Horizontal()) {
                                    using (new Vertical()) {
                                        string path = AssetDatabase.GetAssetPath(_UMA_Variables.UMASlotsList[i]);
                                        path    = path.Replace(_UMA_Variables.UMASlotsList[i].name + ".asset", "");
                                        Preview = AssetDatabase.LoadAssetAtPath(path + "Preview-" + _UMA_Variables.UMASlotsList[i].name + ".asset", typeof(Texture2D)) as Texture2D;
                                        if (Preview == null)
                                        {
                                            path    = AssetDatabase.GetAssetPath(_UMA_Variables.UMASlotsList[i]);
                                            path    = path.Replace(_UMA_Variables.UMASlotsList[i].name + ".asset", "");
                                            Preview = AssetDatabase.LoadAssetAtPath(path + "Preview-" + _UMA_Variables.UMASlotsList[i].name + ".asset", typeof(Texture2D)) as Texture2D;
                                        }
                                        if (Preview != null)
                                        {
                                            GUI.color = Color.white;
                                        }
                                        else
                                        {
                                            GUI.color = Red;
                                        }
                                        if (InfoSlots == true || Selection.activeObject == _UMA_Variables.UMASlotsList[i])
                                        {
                                            if (GUILayout.Button(Preview, GUILayout.Width(75), GUILayout.Height(75)))
                                            {
                                                Selection.activeObject = _UMA_Variables.UMASlotsList[i];
                                            }
                                        }
                                    }

                                    using (new Vertical()) {
                                        if (_UMA_Variables.UMASlotsList[i] != null && (SearchString == "" ||
                                                                                       _UMA_Variables.UMASlotsList[i].name.ToLower().Contains(SearchString.ToLower())))
                                        {
                                            using (new Horizontal()) {
                                                GUILayout.Space(5);
                                                if (Selection.activeObject == _UMA_Variables.UMASlotsList[i])
                                                {
                                                    GUI.color = Color.yellow;
                                                }
                                                else
                                                {
                                                    GUI.color = Color.white;
                                                }
                                                if (_UMA_Variables.UMASlotsList[i].meshRenderer == null || _UMA_Variables.UMASlotsList[i].materialSample == null)
                                                {
                                                    GUI.color = Red;
                                                }
                                                if (GUILayout.Button(_UMA_Variables.UMASlotsList[i].name, "toolbarbutton", GUILayout.Width(225)))
                                                {
                                                    Selection.activeObject = _UMA_Variables.UMASlotsList[i];
                                                }
                                                GUI.color = Red;
                                                if (GUILayout.Button("X", "toolbarbutton", GUILayout.ExpandWidth(false)))
                                                {
                                                }
                                            }
                                        }
                                        if (InfoSlots == true || Selection.activeObject == _UMA_Variables.UMASlotsList[i])
                                        {
                                            using (new Horizontal()) {
                                                // preview
                                                if (Preview != null)
                                                {
                                                    GUI.color = Green;
                                                }
                                                else
                                                {
                                                    GUI.color = Color.gray;
                                                }
                                                if (Preview == null && GUILayout.Button("preview (Double click)", "toolbarbutton", GUILayout.Width(240)))
                                                {
                                                    if (Preview == null)
                                                    {
                                                        if (_UMA_Variables.UMASlotsList[i].meshRenderer.gameObject != null)
                                                        {
                                                            string path = AssetDatabase.GetAssetPath(_UMA_Variables.UMASlotsList[i]);
                                                            path    = path.Replace(_UMA_Variables.UMASlotsList[i].name + ".asset", "");
                                                            Preview = AssetPreview.GetAssetPreview(_UMA_Variables.UMASlotsList[i].meshRenderer.gameObject);
                                                            //	Preview.name = "preview (Double click)";
                                                            if (Preview)
                                                            {
                                                                AssetDatabase.CreateAsset(Preview, path + "Preview-" + _UMA_Variables.UMASlotsList[i].name + ".asset");
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        try{ if (InfoSlots == true || Selection.activeObject == _UMA_Variables.UMASlotsList[i])
                                             {
                                                 if (_SlotLibrary)
                                                 {
                                                     using (new Horizontal()) {
                                                         string InLibText = "";

                                                         if (_SlotLibrary.GetAllSlots().ToList().Contains(_UMA_Variables.UMASlotsList[i]) == true)
                                                         {
                                                             GUI.color = Green;
                                                             InLibText = "Remove from Library";
                                                         }
                                                         else if (InfoSlots == true || Selection.activeObject == _UMA_Variables.UMASlotsList[i])
                                                         {
                                                             GUI.color = Color.gray;
                                                             InLibText = "Add to Library";
                                                         }
                                                         if (InfoSlots == true || Selection.activeObject == _UMA_Variables.UMASlotsList[i])
                                                         {
                                                             if (GUILayout.Button(InLibText, "toolbarbutton", GUILayout.Width(240)))
                                                             {
                                                                 if (_SlotLibrary.GetAllSlots().ToList().Contains(_UMA_Variables.UMASlotsList[i]) == false)
                                                                 {
                                                                     _SlotLibrary.AddSlot(_UMA_Variables.UMASlotsList[i]);
                                                                     EditorUtility.SetDirty(_SlotLibrary);
                                                                     AssetDatabase.SaveAssets();
                                                                 }
                                                                 else if (InfoSlots == true || Selection.activeObject == _UMA_Variables.UMASlotsList[i])
                                                                 {
                                                                     _SlotLibrary.GetAllSlots().ToList().Remove(_UMA_Variables.UMASlotsList[i]);
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                        }catch (ArgumentException) {}
                                        if (InfoSlots == true || Selection.activeObject == _UMA_Variables.UMASlotsList[i])
                                        {
                                            using (new Horizontal()) {
                                                if (_UMA_Variables.UMASlotsList[i].meshRenderer != null)
                                                {
                                                    GUI.color = Green;
                                                }
                                                else
                                                {
                                                    GUI.color = Red;
                                                }
                                                GUILayout.Label("Renderer OK", "toolbarbutton", GUILayout.Width(120));
                                                if (_UMA_Variables.UMASlotsList[i].materialSample != null)
                                                {
                                                    GUI.color = Green;
                                                }
                                                else
                                                {
                                                    GUI.color = Red;
                                                }
                                                GUILayout.Label("Material OK", "toolbarbutton", GUILayout.Width(120));

                                                /*	if ( _UMA_Variables.UMASlotsList[i].textureNameList.Length > 0 ) GUI.color = Green ;
                                                 *      else GUI.color = Color.yellow ;
                                                 *      GUILayout.Label("Texture(s)", "toolbarbutton", GUILayout.Width (70));*/
                                            }
                                        }
                                    }
                                }
                            }
                            if (_UMA_Variables.UMASlotsList[i] == null)
                            {
                                _UMA_Variables.UMASlotsList.Remove(_UMA_Variables.UMASlotsList[i]);
                            }
                            if (_UMA_Variables.UMASlotsList[i] != null && (SearchString == "" ||
                                                                           _UMA_Variables.UMASlotsList[i].name.ToLower().Contains(SearchString.ToLower())))
                            {
                                GUILayout.Space(10);
                            }
                        }
                    }

                    // UMA Overlays
                    if (Showoverlay)
                    {
                        using (new Horizontal()) {
                            GUI.color = Color.cyan;
                            GUILayout.Label("UMA Overlays (" + _UMA_Variables.UMAOverlaysList.Count.ToString() + ")", "toolbarbutton", GUILayout.ExpandWidth(true));

                            if (Showoverlay)
                            {
                                GUI.color = Green;
                            }
                            else
                            {
                                GUI.color = Color.gray;
                            }
                            if (GUILayout.Button("Show", "toolbarbutton", GUILayout.ExpandWidth(false)))
                            {
                                if (Showoverlay)
                                {
                                    Showoverlay = false;
                                }
                                else
                                {
                                    Showoverlay = true;
                                }
                            }
                        }
                    }
                    if (ShowUMA && Showoverlay && _UMA_Variables.UMAOverlaysList.Count > 0)
                    {
                        #region Helper
                        // Helper
                        GUI.color = Color.white;
                        if (Helper)
                        {
                            GUILayout.TextField("Click on the name to select an Overlay.", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true));
                        }

                        #endregion Helper
                        if (ShowUMA && Showoverlay && _UMA_Variables.UMAOverlaysList.Count > 0)
                        {
                            for (int i = 0; i < _UMA_Variables.UMAOverlaysList.Count; i++)
                            {
                                if (_UMA_Variables.UMAOverlaysList[i] != null && (SearchString == "" ||
                                                                                  _UMA_Variables.UMAOverlaysList[i].name.ToLower().Contains(SearchString.ToLower())))
                                {
                                    using (new Horizontal()) {
                                        GUI.color = Color.white;
                                        if (Selection.activeObject == _UMA_Variables.UMAOverlaysList[i])
                                        {
                                            GUI.color = Color.yellow;
                                        }
                                        if (GUILayout.Button(_UMA_Variables.UMAOverlaysList[i].name, "toolbarbutton", GUILayout.Width(310)))
                                        {
                                            Selection.activeObject = _UMA_Variables.UMAOverlaysList[i];
                                        }
                                        GUI.color = Red;
                                        if (GUILayout.Button("X", "toolbarbutton", GUILayout.ExpandWidth(false)))
                                        {
                                        }
                                    }
                                }
                                if ((InfoOverlays == true || Selection.activeObject == _UMA_Variables.UMAOverlaysList[i]) &&
                                    _UMA_Variables.UMAOverlaysList[i] != null && (SearchString == "" ||
                                                                                  _UMA_Variables.UMAOverlaysList[i].name.ToLower().Contains(SearchString.ToLower())))
                                {
                                    using (new Horizontal()) {
                                        foreach (Texture2D _Texture2D in _UMA_Variables.UMAOverlaysList[i].textureList)
                                        {
                                            using (new Vertical()) {
                                                if (_Texture2D != null)
                                                {
                                                    GUI.color = Color.white;
                                                }
                                                else
                                                {
                                                    GUI.color = Red;
                                                }
                                                if (GUILayout.Button(_Texture2D, GUILayout.Width(75), GUILayout.Height(75)))
                                                {
                                                    Selection.activeObject = _UMA_Variables.UMAOverlaysList[i];
                                                }
                                                GUILayout.Space(5);
                                            }
                                        }
                                        using (new Vertical()) {
                                            using (new Horizontal()) {
                                                string InLibText = "";
                                                GUI.color = Green;
                                                if (_OverlayLibrary)
                                                {
                                                    using (new Horizontal()) {
                                                        if (_OverlayLibrary.GetAllOverlays().ToList().Contains(_UMA_Variables.UMAOverlaysList[i]) == true)
                                                        {
                                                            InLibText = "Remove from Library";
                                                            GUI.color = Green;
                                                        }
                                                        else
                                                        {
                                                            GUI.color = Color.gray;
                                                            InLibText = "Add to Library";
                                                        }
                                                        if (GUILayout.Button(InLibText, "toolbarbutton", GUILayout.Width(120)))
                                                        {
                                                            if (InLibText == "Add to Library" && _OverlayLibrary.GetAllOverlays().ToList().Contains(_UMA_Variables.UMAOverlaysList[i]) == false)
                                                            {
                                                                _OverlayLibrary.AddOverlay(_UMA_Variables.UMAOverlaysList[i]);
                                                            }
                                                            else if (InLibText == "Remove from Library")
                                                            {
                                                                _OverlayLibrary.GetAllOverlays().ToList().Remove(_UMA_Variables.UMAOverlaysList[i]);
                                                            }
                                                            EditorUtility.SetDirty(_OverlayLibrary);
                                                            AssetDatabase.SaveAssets();
                                                        }
                                                    }
                                                }
                                            }
                                            using (new Horizontal()) {
                                                bool Ok = true;
                                                foreach (Texture2D _Texture2D in _UMA_Variables.UMAOverlaysList[i].textureList)
                                                {
                                                    var importer = TextureImporter.GetAtPath(_Texture2D.name) as TextureImporter;
                                                    if (importer && importer.isReadable != true)
                                                    {
                                                        Ok = false;
                                                    }
                                                }
                                                if (Ok == true)
                                                {
                                                    GUI.color = Green;
                                                }
                                                else
                                                {
                                                    GUI.color = Red;
                                                }
                                                if (GUILayout.Button("Read/Write OK", "toolbarbutton", GUILayout.Width(120)))
                                                {
                                                }

                                                /*	if ( _UMA_Variables.UMASlotsList[i].materialSample != null ) GUI.color = Green ;
                                                 *      else GUI.color = Red ;
                                                 *      GUILayout.Label("Material OK", "toolbarbutton", GUILayout.Width (120));
                                                 */	/*	if ( _UMA_Variables.UMASlotsList[i].textureNameList.Length > 0 ) GUI.color = Green ;
                                                 * else GUI.color = Color.yellow ;
                                                 * GUILayout.Label("Texture(s)", "toolbarbutton", GUILayout.Width (70));*/
                                            }

                                            if (_UMA_Variables.UMAOverlaysList[i] == null)
                                            {
                                                _UMA_Variables.UMAOverlaysList.Remove(_UMA_Variables.UMAOverlaysList[i]);
                                            }
                                        }
                                        if (_UMA_Variables.UMAOverlaysList[i] != null && (SearchString == "" ||
                                                                                          _UMA_Variables.UMAOverlaysList[i].name.ToLower().Contains(SearchString.ToLower())))
                                        {
                                            GUILayout.Space(5);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion Lists
        }
        #region About
        if (showAbout)
        {
            using (new HorizontalCentered())
            {
                GUI.color = Color.white;
                GUILayout.Label("U.M.A. Elements", bold);
            }
            using (new HorizontalCentered())
            {
                GUI.color = Color.white;
                GUILayout.Label("for U.M.A. & Dynamic Kit U.M.A. Editor");
            }
            using (new HorizontalCentered())
            {
                GUILayout.Label("Unity version 4.5 & higher");
            }
            GUILayout.Space(5);
            GUI.color = Color.yellow;
            GUILayout.TextField("Greetings to Fernando Ribeiro for the creation of U.M.A. and LaneFox for his models.", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true));
            GUILayout.Space(5);

            using (new HorizontalCentered())
            {
                GUI.color = Green;
                GUILayout.TextField("(c) 2014 Ricardo Luque Martos", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true));
            }
            using (new Horizontal())
            {
                GUI.color = Color.cyan;
                if (GUILayout.Button("Website"))
                {
                    Application.OpenURL("http://alteredreality.wix.com/dk-uma");
                }
            }
            GUI.color = Color.yellow;
            using (new Horizontal()){
                if (GUILayout.Button("Web Video Tutorials"))
                {
                    Application.OpenURL("http://www.youtube.com/playlist?list=PLz3lDsmTMvxZpbSXp79gRm3XOiZs31g5t");
                }
            }

            using (new Horizontal())
            {
                GUI.color = Color.cyan;
                if (GUILayout.Button("Facebook Page"))
                {
                    Application.OpenURL("https://www.facebook.com/DKeditorsUnity3D");
                }
            }
            // Previous Plug Ins
            GUILayout.Label("Previous Plug-In(s) :", GUILayout.ExpandWidth(false));
            GUI.color = Color.white;
            using (new Horizontal())
            {
                if (GUILayout.Button("UMA Natural Behaviour"))
                {
                    Application.OpenURL("https://www.assetstore.unity3d.com/en/#!/content/20836");
                }
            }

            // Next to come
            GUILayout.Label("The next Plug-In(s) to come :", GUILayout.ExpandWidth(false));
            using (new Horizontal())
            {
                GUILayout.Label("'Final IK' Grounder for UMA", bold);
                GUILayout.Label(" (December 2014)", GUILayout.ExpandWidth(false));
            }
            using (new Horizontal())
            {
                GUILayout.Label("UMA Moods", bold);
                GUILayout.Label(" (January 2015)", GUILayout.ExpandWidth(false));
            }
        }
        #endregion About
    }
示例#26
0
        void OnPreprocessTexture()
        {
            string extension = Path.GetExtension(assetPath);
            string filenameWithoutExtention = Path.GetFileNameWithoutExtension(assetPath);
            var    match = Regex.Match(filenameWithoutExtention, @".mip(\d)+$");

            if (match.Success)
            {
                string filenameWithoutMip = filenameWithoutExtention.Substring(0, match.Index);
                string directoryName      = Path.GetDirectoryName(assetPath);
                string mip0Path           = Path.Combine(directoryName, filenameWithoutMip + extension);

                TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(mip0Path);
                if (importer != null)
                {
                    importer.SaveAndReimport();
                }
            }

            if (ShouldImportAsset(assetPath))
            {
                m_importing = true;

                string pattern = GetMipmapFilenamePattern(assetPath);
                int    m       = 1;

                bool reimport = false;

                while (true)
                {
                    string mipPath = string.Format(pattern, m);
                    m++;

                    TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(mipPath);
                    if (importer != null)
                    {
                        if (!importer.mipmapEnabled || !importer.isReadable)
                        {
                            importer.mipmapEnabled = true;
                            importer.isReadable    = true;
                            importer.SaveAndReimport();

                            reimport = true;
                        }
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }

                if (reimport)
                {
                    m_importing = false;
                    return;
                }
                TextureImporter textureImporter = (TextureImporter)assetImporter;
                m_isReadable = textureImporter.isReadable;
                textureImporter.isReadable = true;
            }
        }
示例#27
0
        public static void PacketSprite4Atlas(Texture2D[] texs, string outputPath)
        {
            Texture2D atlas = new Texture2D(1, 1);

            Rect[] rect = atlas.PackTextures(texs, (int)Padding, (int)AtlasMaxSize);

            File.WriteAllBytes(outputPath, atlas.EncodeToPNG());
            RefreshAsset(outputPath);

            // 记录图片的名字,只是用于输出日志用;
            StringBuilder names = new StringBuilder();

            // SpriteMetaData结构可以让我们编辑图片的一些信息,想图片的name,包围盒border,在图集中的区域rect等
            SpriteMetaData[] sheet = new SpriteMetaData[rect.Length];
            for (int i = 0; i < sheet.Length; i++)
            {
                SpriteMetaData meta = new SpriteMetaData();
                meta.name = texs[i].name;
                meta.rect = rect[i];
                // 这里的rect记录的是单个图片在图集中的uv坐标值
                // 因为rect最终需要记录单个图片在大图片图集中所在的区域rect,所以我们做如下的处理
                meta.rect.Set(
                    meta.rect.x * atlas.width,
                    meta.rect.y * atlas.height,
                    meta.rect.width * atlas.width,
                    meta.rect.height * atlas.height
                    );
                // 如果图片有包围盒信息的话
                SpriteInfo spriteInfo = GetSpriteMetaData(meta.name);
                if (spriteInfo != null)
                {
                    meta.border = spriteInfo.SpriteBorder;
                    meta.pivot  = spriteInfo.SpritePivot;
                }
                sheet[i] = meta;
                // 打印日志用
                names.Append(meta.name);
                if (i < sheet.Length - 1)
                {
                    names.Append(",");
                }
            }

            // 设置图集的信息
            TextureImporter importer = TextureImporter.GetAtPath(outputPath) as TextureImporter;

            importer.textureType   = TextureImporterType.Sprite;
            importer.textureFormat = TextureImporterFormat.AutomaticCompressed;
            // Multiple表示我们这个大图片(图集)中包含很多小图片
            importer.spriteImportMode = SpriteImportMode.Multiple;
            // 是否开启mipmap
            importer.mipmapEnabled = false;
            importer.spritesheet   = sheet;
            // 设置图集中小图片的信息(每个图片所在的区域rect等)
            // 保存并刷新
            importer.SaveAndReimport();
            SpriteList.Clear();

            // 输出日志
            Debug.Log("Atlas create ok, " + names.ToString());
        }