static void ExportTexture(Texture2D _saveTexture, string _name, enum_TextureExportType _exportType)
        {
            string extend = "";

            switch (_exportType)
            {
            default: throw new Exception("Invalid Export Type:" + _exportType);

            case enum_TextureExportType.JPG: extend = "jpg"; break;

            case enum_TextureExportType.PNG: extend = "png"; break;

            case enum_TextureExportType.TGA: extend = "tga"; break;

            case enum_TextureExportType.EXR: extend = "exr"; break;
            }


            if (!UEAsset.SaveFilePath(out string filePath, extend, _name + "_M"))
            {
                return;
            }
            byte[] bytes = null;
            switch (_exportType)
            {
            case enum_TextureExportType.TGA: bytes = _saveTexture.EncodeToTGA(); break;

            case enum_TextureExportType.EXR: bytes = _saveTexture.EncodeToEXR(); break;

            case enum_TextureExportType.JPG: bytes = _saveTexture.EncodeToJPG(); break;

            case enum_TextureExportType.PNG: bytes = _saveTexture.EncodeToPNG(); break;
            }
            UEAsset.CreateOrReplaceFile(filePath, bytes);
        }
Esempio n. 2
0
        public void Save()
        {
            if (!UEAsset.SaveFilePath(out string filePath, "asset", m_ModifingMesh.name))
            {
                return;
            }

            UEAsset.CreateOrReplaceMainAsset(m_ModifingMesh, UEPath.FilePathToAssetPath(filePath));
        }
Esempio n. 3
0
        public static void GenerateSkinnedTarget(string assetPath, GameObject _targetFBX, enum_VertexData _generateUV)
        {
            GameObject prefabSource = GameObject.Instantiate(_targetFBX);

            SkinnedMeshRenderer[] skinnedRenderers = prefabSource.GetComponentsInChildren <SkinnedMeshRenderer>();
            MeshFilter[]          meshFilters      = prefabSource.GetComponentsInChildren <MeshFilter>();
            List <Mesh>           sourceMeshes     = new List <Mesh>();

            foreach (SkinnedMeshRenderer renderer in skinnedRenderers)
            {
                sourceMeshes.Add(renderer.sharedMesh);
            }
            foreach (MeshFilter filter in meshFilters)
            {
                sourceMeshes.Add(filter.sharedMesh);
            }

            List <KeyValuePair <string, Object> > targetSubAsset = new List <KeyValuePair <string, Object> >();

            for (int i = 0; i < sourceMeshes.Count; i++)
            {
                targetSubAsset.Add(new KeyValuePair <string, Object>(sourceMeshes[i].name, GenerateMesh(sourceMeshes[i], _generateUV)));
            }

            GameObject mainAsset = PrefabUtility.SaveAsPrefabAsset(prefabSource, assetPath);

            UEAsset.CreateOrReplaceSubAsset(assetPath, targetSubAsset.ToArray());
            Mesh[] meshes = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetPath).ToArray(obj => (Mesh)obj);

            skinnedRenderers = mainAsset.GetComponentsInChildren <SkinnedMeshRenderer>();
            for (int i = 0; i < skinnedRenderers.Length; i++)
            {
                skinnedRenderers[i].sharedMesh = meshes[i];
            }

            meshFilters = mainAsset.GetComponentsInChildren <MeshFilter>();
            for (int i = 0; i < meshFilters.Length; i++)
            {
                meshFilters[i].sharedMesh = meshes.Find(p => p.name == meshFilters[i].sharedMesh.name);
            }
            PrefabUtility.SavePrefabAsset(mainAsset);
            GameObject.DestroyImmediate(prefabSource);
        }
        void GenerateBoneInstanceMeshAndTexture(GameObject _targetFBX, AnimationClip[] _clips, string exposeBones)
        {
            if (!UEAsset.SelectDirectory(_targetFBX, out string savePath, out string meshName))
            {
                Debug.LogWarning("Invalid Folder Selected");
                return;
            }
            GameObject          _instantiatedObj     = GameObject.Instantiate(m_TargetPrefab);
            SkinnedMeshRenderer _skinnedMeshRenderer = _instantiatedObj.GetComponentInChildren <SkinnedMeshRenderer>();

            try
            {
                Matrix4x4[] bindPoses = _skinnedMeshRenderer.sharedMesh.bindposes;
                Transform[] bones     = _skinnedMeshRenderer.bones;
                #region Record Expose Bone
                List <AnimationInstanceExposeBone> exposeBoneParam = new List <AnimationInstanceExposeBone>();
                if (exposeBones != "")
                {
                    Transform[] activeTransforms = _instantiatedObj.GetComponentsInChildren <Transform>();
                    for (int i = 0; i < activeTransforms.Length; i++)
                    {
                        if (!System.Text.RegularExpressions.Regex.Match(activeTransforms[i].name, exposeBones).Success)
                        {
                            continue;
                        }
                        int       relativeBoneIndex = -1;
                        Transform relativeBone      = activeTransforms[i];
                        while (relativeBone != null)
                        {
                            relativeBoneIndex = System.Array.FindIndex(bones, p => p == relativeBone);
                            if (relativeBoneIndex != -1)
                            {
                                break;
                            }
                            relativeBone = relativeBone.parent;
                        }
                        if (relativeBoneIndex == -1)
                        {
                            continue;
                        }

                        Matrix4x4 rootWorldToLocal = _skinnedMeshRenderer.transform.worldToLocalMatrix;

                        exposeBoneParam.Add(new AnimationInstanceExposeBone()
                        {
                            m_BoneIndex = relativeBoneIndex,
                            m_BoneName  = activeTransforms[i].name,
                            m_Position  = rootWorldToLocal.MultiplyPoint(activeTransforms[i].transform.position),
                            m_Direction = rootWorldToLocal.MultiplyVector(activeTransforms[i].transform.forward)
                        });
                    }
                }
                #endregion
                #region Bake Animation Atlas
                int boneCount  = _skinnedMeshRenderer.sharedMesh.bindposes.Length;
                int totalWdith = boneCount * 3;
                int totalFrame = GetInstanceParams(_clips, out AnimationInstanceParam[] instanceParams);
                List <AnimationInstanceEvent> instanceEvents = new List <AnimationInstanceEvent>();

                Texture2D atlasTexture = new Texture2D(Mathf.NextPowerOfTwo(totalWdith), Mathf.NextPowerOfTwo(totalFrame), TextureFormat.RGBAHalf, false);
                atlasTexture.filterMode = FilterMode.Point;
                atlasTexture.wrapModeU  = TextureWrapMode.Clamp;
                atlasTexture.wrapModeV  = TextureWrapMode.Repeat;
                UBoundsChecker.Begin();
                for (int i = 0; i < _clips.Length; i++)
                {
                    AnimationClip clip       = _clips[i];
                    float         length     = clip.length;
                    float         frameRate  = clip.frameRate;
                    int           frameCount = (int)(length * frameRate);
                    int           startFrame = instanceParams[i].m_FrameBegin;
                    for (int j = 0; j < frameCount; j++)
                    {
                        clip.SampleAnimation(_instantiatedObj, length * j / frameCount);
                        for (int k = 0; k < boneCount; k++)
                        {
                            Matrix4x4 curFrameBoneMatrix = _skinnedMeshRenderer.transform.worldToLocalMatrix * bones[k].localToWorldMatrix * bindPoses[k];
                            atlasTexture.SetPixel(k * 3, startFrame + j, UColor.VectorToColor(curFrameBoneMatrix.GetRow(0)));
                            atlasTexture.SetPixel(k * 3 + 1, startFrame + j, UColor.VectorToColor(curFrameBoneMatrix.GetRow(1)));
                            atlasTexture.SetPixel(k * 3 + 2, startFrame + j, UColor.VectorToColor(curFrameBoneMatrix.GetRow(2)));
                        }

                        Mesh boundsCheckMesh = new Mesh();
                        _skinnedMeshRenderer.BakeMesh(boundsCheckMesh);
                        Vector3[] verticies = boundsCheckMesh.vertices;
                        for (int k = 0; k < verticies.Length; k++)
                        {
                            UBoundsChecker.CheckBounds(verticies[k].Divide(_skinnedMeshRenderer.transform.localScale));
                        }

                        boundsCheckMesh.Clear();
                    }
                }
                atlasTexture.Apply();
                #endregion
                #region Bake Mesh
                Mesh         instanceMesh = _skinnedMeshRenderer.sharedMesh.Copy();
                BoneWeight[] boneWeights  = instanceMesh.boneWeights;
                Vector4[]    uv1          = new Vector4[boneWeights.Length];
                Vector4[]    uv2          = new Vector4[boneWeights.Length];
                for (int i = 0; i < boneWeights.Length; i++)
                {
                    uv1[i] = new Vector4(boneWeights[i].boneIndex0, boneWeights[i].boneIndex1, boneWeights[i].boneIndex2, boneWeights[i].boneIndex3);
                    uv2[i] = new Vector4(boneWeights[i].weight0, boneWeights[i].weight1, boneWeights[i].weight2, boneWeights[i].weight3);
                }
                instanceMesh.SetUVs(1, uv1);
                instanceMesh.SetUVs(2, uv2);
                instanceMesh.boneWeights = null;
                instanceMesh.bindposes   = null;
                instanceMesh.bounds      = UBoundsChecker.CalculateBounds();
                #endregion
                DestroyImmediate(_instantiatedObj);

                GPUAnimationData data = ScriptableObject.CreateInstance <GPUAnimationData>();
                data.m_Animations  = instanceParams;
                data.m_ExposeBones = exposeBoneParam.ToArray();

                data = UEAsset.CreateAssetCombination(savePath + meshName + "_GPU_Bone.asset", data, new KeyValuePair <string, Object>(meshName + "_AnimationAtlas", atlasTexture), new KeyValuePair <string, Object>(meshName + "_InstanceMesh", instanceMesh));
                Object[] assets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(data));
                foreach (var asset in assets)
                {
                    Texture2D atlas = asset as Texture2D;
                    Mesh      mesh  = asset as Mesh;
                    if (atlas)
                    {
                        data.m_AnimationAtlas = atlas;
                    }
                    if (mesh)
                    {
                        data.m_InstancedMesh = mesh;
                    }
                }
                AssetDatabase.SaveAssets();
            }
            catch (System.Exception e)
            {
                Debug.LogError("Generate Failed:" + e.Message);
                DestroyImmediate(_instantiatedObj);
            }
        }
        void GenerateVertexTexture(GameObject _targetFBX, AnimationClip[] _clips)
        {
            if (!UEAsset.SelectDirectory(_targetFBX, out string savePath, out string meshName))
            {
                Debug.LogWarning("Invalid Folder Selected");
                return;
            }
            GameObject          instantiatedObj     = GameObject.Instantiate(m_TargetPrefab);
            SkinnedMeshRenderer skinnedMeshRenderer = instantiatedObj.GetComponentInChildren <SkinnedMeshRenderer>();

            #region Bake Animation Atlas
            int vertexCount       = skinnedMeshRenderer.sharedMesh.vertexCount;
            int totalVertexRecord = vertexCount * 2;
            int totalFrame        = GetInstanceParams(_clips, out AnimationInstanceParam[] instanceParams);

            Texture2D atlasTexture = new Texture2D(Mathf.NextPowerOfTwo(totalVertexRecord), Mathf.NextPowerOfTwo(totalFrame), TextureFormat.RGBAHalf, false);
            atlasTexture.filterMode = FilterMode.Point;
            atlasTexture.wrapModeU  = TextureWrapMode.Clamp;
            atlasTexture.wrapModeV  = TextureWrapMode.Repeat;
            UBoundsChecker.Begin();
            for (int i = 0; i < _clips.Length; i++)
            {
                AnimationClip clip           = _clips[i];
                Mesh          vertexBakeMesh = new Mesh();
                float         length         = clip.length;
                float         frameRate      = clip.frameRate;
                int           frameCount     = (int)(length * frameRate);
                int           startFrame     = instanceParams[i].m_FrameBegin;
                for (int j = 0; j < frameCount; j++)
                {
                    clip.SampleAnimation(instantiatedObj, length * j / frameCount);
                    skinnedMeshRenderer.BakeMesh(vertexBakeMesh);
                    Vector3[] vertices = vertexBakeMesh.vertices;
                    Vector3[] normals  = vertexBakeMesh.normals;
                    for (int k = 0; k < vertexCount; k++)
                    {
                        UBoundsChecker.CheckBounds(vertices[k]);
                        atlasTexture.SetPixel(k * 2, startFrame + j, UColor.VectorToColor(vertices[k]));
                        atlasTexture.SetPixel(k * 2 + 1, startFrame + j, UColor.VectorToColor(normals[k]));
                    }
                }
                vertexBakeMesh.Clear();
            }
            atlasTexture.Apply();
            #endregion

            #region Bake Mesh
            Mesh instanceMesh = skinnedMeshRenderer.sharedMesh.Copy();
            instanceMesh.normals     = null;
            instanceMesh.tangents    = null;
            instanceMesh.boneWeights = null;
            instanceMesh.bindposes   = null;
            instanceMesh.bounds      = UBoundsChecker.CalculateBounds();
            #endregion
            DestroyImmediate(instantiatedObj);

            GPUAnimationData data = ScriptableObject.CreateInstance <GPUAnimationData>();
            data.m_Animations = instanceParams;
            data = UEAsset.CreateAssetCombination(savePath + meshName + "_GPU_Vertex.asset", data, new KeyValuePair <string, Object>(meshName + "_AnimationAtlas", atlasTexture), new KeyValuePair <string, Object>(meshName + "_InstanceMesh", instanceMesh));
            Object[] assets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(data));
            foreach (var asset in assets)
            {
                Texture2D atlas = asset as Texture2D;
                Mesh      mesh  = asset as Mesh;
                if (atlas)
                {
                    data.m_AnimationAtlas = atlas;
                }
                if (mesh)
                {
                    data.m_InstancedMesh = mesh;
                }
            }
            AssetDatabase.SaveAssets();
        }
        private void OnGUI()
        {
            EditorGUI.BeginChangeCheck();
            HorizontalScope.Begin(5, 5, 20);
            EditorGUI.LabelField(HorizontalScope.NextRect(0, 60), "Type:", UEGUIStyle_Window.m_TitleLabel);
            m_NoiseType = (enum_NoiseType)EditorGUI.EnumPopup(HorizontalScope.NextRect(5, 120), m_NoiseType);

            bool noiseSampleSupported = NoiseSampleSupported(m_NoiseType);

            if (noiseSampleSupported)
            {
                HorizontalScope.NextLine(2, 20);
                EditorGUI.LabelField(HorizontalScope.NextRect(0, 60), "Sample:", UEGUIStyle_Window.m_TitleLabel);
                m_NoiseSample = (enum_NoiseSample)EditorGUI.EnumPopup(HorizontalScope.NextRect(5, 120), m_NoiseSample);
            }
            HorizontalScope.NextLine(2, 20);
            EditorGUI.LabelField(HorizontalScope.NextRect(0, 60), "Filter:", UEGUIStyle_Window.m_TitleLabel);
            m_FilterMode = (FilterMode)EditorGUI.EnumPopup(HorizontalScope.NextRect(5, 120), m_FilterMode);
            HorizontalScope.NextLine(2, 20);
            EditorGUI.LabelField(HorizontalScope.NextRect(0, 60), "Size:", UEGUIStyle_Window.m_TitleLabel);
            m_SizePower = EditorGUI.IntSlider(HorizontalScope.NextRect(5, 120), m_SizePower, 3, 10);
            int size = Mathf.RoundToInt(Mathf.Pow(2, m_SizePower));

            EditorGUI.LabelField(HorizontalScope.NextRect(5, 40), size.ToString());
            HorizontalScope.NextLine(2, 20);
            EditorGUI.LabelField(HorizontalScope.NextRect(0, 60), "Scale:", UEGUIStyle_Window.m_TitleLabel);
            m_Scale = EditorGUI.Slider(HorizontalScope.NextRect(5, 120), m_Scale, 1f, 30f);

            HorizontalScope.NextLine(2, 20);
            EditorGUI.LabelField(HorizontalScope.NextRect(0, 60), "Octave:", UEGUIStyle_Window.m_TitleLabel);
            m_Octave = EditorGUI.Toggle(HorizontalScope.NextRect(5, 20), m_Octave);
            if (m_Octave)
            {
                HorizontalScope.NextLine(2, 20);
                EditorGUI.LabelField(HorizontalScope.NextRect(0, 60), "Count:", UEGUIStyle_Window.m_TitleLabel);
                m_OctaveCount = EditorGUI.IntSlider(HorizontalScope.NextRect(5, 120), m_OctaveCount, 2, 7);
                HorizontalScope.NextLine(2, 20);
            }

            if (!m_Texture || EditorGUI.EndChangeCheck())
            {
                float   sizeF  = size;
                Color[] colors = new Color[size * size];
                for (int i = 0; i < size; i++)
                {
                    for (int j = 0; j < size; j++)
                    {
                        float noiseX = j / sizeF;
                        float noiseY = i / sizeF;
                        float noise  = m_Octave ? GetNoiseOctave(noiseX, noiseY, m_Scale, m_NoiseType, m_OctaveCount) : GetNoise(noiseX, noiseY, m_Scale, m_NoiseType);
                        if (noiseSampleSupported)
                        {
                            switch (m_NoiseSample)
                            {
                            case enum_NoiseSample.Absolute: noise = Mathf.Abs(noise); break;

                            case enum_NoiseSample._01: noise = noise / 2f + .5f; break;
                            }
                        }
                        colors[i * size + j] = new Color(noise, noise, noise, 1);
                    }
                }
                m_Texture = new Texture2D(size, size, TextureFormat.ARGB32, true)
                {
                    filterMode = m_FilterMode
                };
                m_Texture.SetPixels(colors);
                m_Texture.Apply();
                Undo.RecordObject(this, "Noise Generator Change");
            }
            HorizontalScope.NextLine(2, 256);
            Rect textureRect = HorizontalScope.NextRect(0, 256);

            GUI.DrawTexture(textureRect, EditorGUIUtility.whiteTexture);
            GUI.DrawTexture(textureRect.Collapse(Vector2.one * 10f), m_Texture);
            HorizontalScope.NextLine(2, 20);
            if (GUI.Button(HorizontalScope.NextRect(0, 80), "Export"))
            {
                if (UEAsset.SaveFilePath(out string filePath, "png", "CustomNoise_" + m_NoiseType.ToString()))
                {
                    UEAsset.CreateOrReplaceFile(filePath, m_Texture.EncodeToPNG());
                }
            }
        }
        void CreateSquare(float _tileSize, int _radius, bool circled)
        {
            Vector3        tileSize  = new Vector3(_tileSize, 0, _tileSize);
            List <Vector3> verticies = new List <Vector3>();
            List <Vector2> uvs       = new List <Vector2>();
            List <int>     indices   = new List <int>();
            List <Vector3> normals   = new List <Vector3>();
            List <Vector4> tangents  = new List <Vector4>();

            Vector2 uv0 = new Vector2(0, 0);
            Vector2 uv1 = new Vector2(1, 0);
            Vector2 uv2 = new Vector2(0, 1);
            Vector2 uv3 = new Vector2(1, 1);

            int     tileIndex = 0;
            Vector3 halfSize  = tileSize / 2;

            for (int i = -_radius + 1; i < _radius; i++)
            {
                for (int j = -_radius + 1; j < _radius; j++)
                {
                    if (circled && (i * i + j * j > _radius * _radius))
                    {
                        continue;
                    }

                    int     verticiesStartIndex = tileIndex * 4;
                    Vector3 v0 = -halfSize + new Vector3(i, 0, j).Multiply(tileSize);
                    Vector3 v1 = -halfSize + new Vector3(i + 1, 0, j).Multiply(tileSize);
                    Vector3 v2 = -halfSize + new Vector3(i, 0, j + 1).Multiply(tileSize);
                    Vector3 v3 = -halfSize + new Vector3(i + 1, 0, j + 1).Multiply(tileSize);

                    verticies.Add(v0);
                    verticies.Add(v1);
                    verticies.Add(v2);
                    verticies.Add(v3);

                    normals.Add(Vector3.up);
                    normals.Add(Vector3.up);
                    normals.Add(Vector3.up);
                    normals.Add(Vector3.up);

                    tangents.Add(new Vector4(1, 0, 0, 1));
                    tangents.Add(new Vector4(1, 0, 0, 1));
                    tangents.Add(new Vector4(1, 0, 0, 1));
                    tangents.Add(new Vector4(1, 0, 0, 1));

                    uvs.Add(uv0);
                    uvs.Add(uv1);
                    uvs.Add(uv2);
                    uvs.Add(uv3);

                    int indice0 = verticiesStartIndex + 0;
                    int indice1 = verticiesStartIndex + 1;
                    int indice2 = verticiesStartIndex + 2;
                    int indice3 = verticiesStartIndex + 3;
                    indices.Add(indice0);
                    indices.Add(indice2);
                    indices.Add(indice3);
                    indices.Add(indice0);
                    indices.Add(indice3);
                    indices.Add(indice1);
                    tileIndex++;
                }
            }

            Mesh mesh = new Mesh();

            mesh.name = "CustomPlane";
            mesh.SetVertices(verticies);
            mesh.SetUVs(0, uvs);
            mesh.SetNormals(normals);
            mesh.SetTangents(tangents);
            mesh.SetIndices(indices, MeshTopology.Triangles, 0);

            if (!UEAsset.SaveFilePath(out string path, "asset", "CustomPlane"))
            {
                return;
            }

            UEAsset.CreateOrReplaceMainAsset(mesh, UEPath.FilePathToAssetPath(path));
        }