GetRelativePath() public static méthode

Turns the given full path into a relative one starting just above the given directory. For example, "GetRelativePath("C:/A/B/C", "B")" returns "B/C". Returns "null" if the given folder can't be found.
As a side effect, all '/' or '\' slashes will be changed to the correct directory separator char for this platform.
public static GetRelativePath ( string fullPath, string startFolder ) : string
fullPath string
startFolder string /// The folder that will appear at the top of the returned path. ///
Résultat string
Exemple #1
0
        /// <summary>
        /// Generates a texture containing the given graph's noise output.
        /// If this is being called very often, create a permanent render target and material and
        ///     use the other version of this method instead for much better performance.
        /// If an error occurred, outputs to the Unity debug console and returns "null".
        /// </summary>
        /// <param name="outputComponents">
        /// The texture output.
        /// For example, pass "rgb" or "xyz" to output the noise into the red, green, and blue channels
        ///     but not the alpha channel.
        /// </param>
        /// <param name="defaultColor">
        /// The color (generally 0-1) of the color components which aren't set by the noise.
        /// </param>
        public static Texture2D GenerateToTexture(Graph g, GraphParamCollection c, int width, int height,
                                                  string outputComponents, float defaultColor,
                                                  TextureFormat format = TextureFormat.RGBAFloat)
        {
            //Generate a shader from the graph and have Unity compile it.
            string shaderPath = Path.Combine(Application.dataPath, "gpuNoiseShaderTemp.shader");
            Shader shader     = SaveShader(g, shaderPath, "TempGPUNoiseShader", outputComponents, defaultColor);

            if (shader == null)
            {
                return(null);
            }

            //Render the shader's output into a render texture and copy the data to a Texture2D.
            RenderTexture target = new RenderTexture(width, height, 16, RenderTextureFormat.ARGBFloat);

            target.Create();
            Texture2D resultTex = new Texture2D(width, height, format, false, true);

            //Create the material and set its parameters.
            Material mat = new Material(shader);

            c.SetParams(mat);

            GraphUtils.GenerateToTexture(target, mat, resultTex);

            //Clean up.
            target.Release();
            if (!AssetDatabase.DeleteAsset(StringUtils.GetRelativePath(shaderPath, "Assets")))
            {
                Debug.LogError("Unable to delete temp file: " + shaderPath);
            }

            return(resultTex);
        }
Exemple #2
0
        /// <summary>
        /// Saves the shader for the given graph to the given file with the given name.
        /// Also forces Unity to immediately recognize and compile the shader
        ///     so that it can be immediately used after calling this function.
        /// If the shader fails to load for some reason, an error is output to the Unity console
        ///     and "null" is returned.
        /// </summary>
        /// <param name="gradientRampName">The name of the gradient ramp texture param.</param>
        public static Shader SaveShader(Graph g, string filePath, string shaderName,
                                        string gradientRampName)
        {
            string relativePath = StringUtils.GetRelativePath(filePath, "Assets");

            try
            {
                //Get the shader code.
                string shad = g.GenerateShader(shaderName, gradientRampName);
                if (shad == null)
                {
                    return(null);
                }

                //Write to the file.
                DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(filePath));
                if (!dir.Exists)
                {
                    dir.Create();
                }
                File.WriteAllText(filePath, shad);


                //Tell Unity to load/compile it.
                AssetDatabase.ImportAsset(relativePath, ImportAssetOptions.ForceSynchronousImport);
            }
            catch (Exception e)
            {
                Debug.LogError("Error saving/loading shader to/from file: " + e.Message);
            }

            return(AssetDatabase.LoadAssetAtPath <Shader>(relativePath));
        }
Exemple #3
0
    public static void GenerateBox()
    {
        string path = EditorUtility.SaveFilePanelInProject("Choose Path", "Skybox", "asset",
                                                           "Choose the path for the box mesh");

        if (path == "")
        {
            return;
        }


        Vector3[] verts = new Vector3[] {
            new Vector3(-1.0f, -1.0f, -1.0f),
            new Vector3(-1.0f, -1.0f, 1.0f),
            new Vector3(-1.0f, 1.0f, -1.0f),
            new Vector3(-1.0f, 1.0f, 1.0f),
            new Vector3(1.0f, -1.0f, -1.0f),
            new Vector3(1.0f, -1.0f, 1.0f),
            new Vector3(1.0f, 1.0f, -1.0f),
            new Vector3(1.0f, 1.0f, 1.0f)
        };
        Vector3[] normals = new Vector3[verts.Length];
        for (int i = 0; i < normals.Length; ++i)
        {
            normals[i] = verts[i].normalized;
        }
        int[] inds = new int[] {
            //X min:
            0, 2, 3,
            0, 3, 1,

            //X max:
            4, 7, 6,
            4, 5, 7,

            //Y min:
            0, 1, 5,
            0, 5, 4,

            //Y max:
            2, 7, 3,
            2, 6, 7,

            //Z min:
            0, 6, 2,
            0, 4, 6,

            //Z max:
            1, 3, 7,
            1, 7, 5,
        };

        Mesh mesh = new Mesh();

        mesh.vertices  = verts;
        mesh.normals   = normals;
        mesh.triangles = inds;
        mesh.UploadMeshData(true);
        AssetDatabase.CreateAsset(mesh, StringUtils.GetRelativePath(path, "Assets"));
    }
Exemple #4
0
        /// <summary>
        /// Gets the full paths for all graphs in this Unity project.
        /// </summary>
        public static List <string> GetAllGraphsInProject(string excludeGraph       = null,
                                                          bool makeRelativeToAssets = false)
        {
            DirectoryInfo inf = new DirectoryInfo(Application.dataPath);

            FileInfo[] files = inf.GetFiles("*." + Extension, SearchOption.AllDirectories);
            return(files
                   .Select(f => (makeRelativeToAssets ?
                                 StringUtils.GetRelativePath(f.FullName, "Assets") :
                                 f.FullName))
                   .Where(f => (f != excludeGraph))
                   .ToList());
        }
Exemple #5
0
 public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
 {
     using (OpenFileDialog openFileDialog = new OpenFileDialog())
     {
         openFileDialog.Filter = "Изображения | *.bmp;*.png;*.jpg;*.jpeg;*.ico";
         if (openFileDialog.ShowDialog() == DialogResult.OK)
         {
             Image image = Image.FromFile(openFileDialog.FileName);
             image.Tag = StringUtils.GetRelativePath(Application.StartupPath, openFileDialog.FileName);
             return(image);
         }
     }
     return(value);
 }
Exemple #6
0
        /// <summary>
        ///  Generate a new module for your current project
        /// </summary>
        /// <param name="ModuleName">The name of the Unreal module to create</param>
        /// <param name="PublicDependencies"></param>
        /// <param name="PrivateDependencies"></param>
        /// <param name="settings"></param>
        public void GenerateNewModule(string ModuleName, string[] PublicDependencies, string[] PrivateDependencies, UProjectModule settings)
        {
            //Generate a brand new module
            string ModulePath   = Path.Combine(SourcePath, ModuleName);
            string TemplatePath = Path.Combine(Directory.GetCurrentDirectory(), TemplateDir);

            Console.WriteLine("[GENERATE] Gathering file templates");

            //Go through all the files in the /Templates/ folder, templatizing and generating them in the right place
            string[] Files = null;
            try
            {
                Files = Directory.GetFiles(TemplatePath, "*", SearchOption.AllDirectories);
            }
            catch (DirectoryNotFoundException ex) { }

            if (Files == null || Files.Length == 0)
            {
                throw new FileNotFoundException("Templates folder was missing or empty!");
            }

            foreach (string Filename in Files)
            {
                //Replace the naming scheme
                string newFileName = Path.GetFileName(Filename).Replace(ModuleNameToken, ModuleName);

                //Get the path relative to the templates folder
                string relativePath   = StringUtils.GetRelativePath(Path.GetDirectoryName(Filename), TemplatePath);
                string outputFilepath = Path.Combine(ModulePath, relativePath, newFileName);

                Console.WriteLine("[GENERATE] {0}", outputFilepath);

                //Generate the path
                string builtFile = generateFromTokens(Filename, ModuleName, PublicDependencies, PrivateDependencies);
                Directory.CreateDirectory(Path.GetDirectoryName(outputFilepath));
                File.WriteAllText(outputFilepath, builtFile);
            }

            //Now, attempt to overwrite the *.uproject file with our new module entry
            //prepare your butts
            if (settings != null)
            {
                addOrEditUprojectModule(ProjectFile, ModuleName, settings);
            }

            Console.WriteLine("[GENERATE] Finished!");
        }
Exemple #7
0
        /// <summary>
        /// Generates a texture containing the given graph's noise output.
        /// If this is being called very often, create a permanent render target and material and
        ///     use the other version of this method instead for much better performance.
        /// If an error occurred, outputs to the Unity debug console and returns "null".
        /// </summary>
        /// <param name="gradientRampName">The name of the gradient ramp texture param.</param>
        public static Texture2D GenerateToTexture(Graph g, GraphParamCollection c, int width, int height,
                                                  Gradient gradientRamp,
                                                  TextureFormat format = TextureFormat.RGBAFloat)
        {
            //Generate a shader from the graph and have Unity compile it.
            string shaderPath = Path.Combine(Application.dataPath, "gpuNoiseShaderTemp.shader");
            Shader shader     = SaveShader(g, shaderPath, "TempGPUNoiseShader", "_MyGradientRamp14123");

            if (shader == null)
            {
                return(null);
            }

            //Generate a texture from the gradient.
            Texture2D myRamp = new Texture2D(1024, 1, TextureFormat.RGBA32, false);

            Color[] cols = new Color[myRamp.width];
            for (int i = 0; i < cols.Length; ++i)
            {
                cols[i] = gradientRamp.Evaluate((float)i / (float)(cols.Length - 1));
            }
            myRamp.SetPixels(cols);
            myRamp.Apply(false, true);

            //Render the shader's output into a render texture and copy the data to a Texture2D.
            RenderTexture target = new RenderTexture(width, height, 16, RenderTextureFormat.ARGBFloat);

            target.Create();
            Texture2D resultTex = new Texture2D(width, height, format, false, true);

            //Create the material and set its parameters.
            Material mat = new Material(shader);

            mat.SetTexture("_MyGradientRamp14123", myRamp);
            c.SetParams(mat);

            GraphUtils.GenerateToTexture(target, mat, resultTex);

            //Clean up.
            target.Release();
            if (!AssetDatabase.DeleteAsset(StringUtils.GetRelativePath(shaderPath, "Assets")))
            {
                Debug.LogError("Unable to delete temp file: " + shaderPath);
            }

            return(resultTex);
        }
Exemple #8
0
        /// <summary>
        /// Generates both textures and saves them to the given file paths.
        /// Returns whether the operation succeeded.
        /// </summary>
        private bool GenerateTextures(string texPath, string normalTexPath = null)
        {
            //The base data set should be large enough for both textures.
            int baseDataSizeX = X,
                baseDataSizeY = Y,
                baseDataSizeZ = Z;

            if (GenerateNormals)
            {
                baseDataSizeX = Math.Max(baseDataSizeX, Normals_X);
                baseDataSizeY = Math.Max(baseDataSizeY, Normals_Y);
                baseDataSizeZ = Math.Max(baseDataSizeZ, Normals_Z);
            }

            Graph graph = LoadGraph();
            GraphParamCollection graphParams = GraphParams;

            //Generate the initial data.
            float[,,] baseData = GraphEditorUtils.GenerateToArray(graph, graphParams,
                                                                  baseDataSizeX,
                                                                  baseDataSizeY,
                                                                  baseDataSizeZ);


            //Generate the value texture.

            float[,,] valueTexData = baseData.ResampleFull(Mathf.Lerp, X, Y, Z);
            Gradient colorGradient = MakeGradient();

            Color[] valueTexPixels = new Color[X * Y * Z];

            for (int z = 0; z < Z; ++z)
            {
                for (int y = 0; y < Y; ++y)
                {
                    for (int x = 0; x < X; ++x)
                    {
                        float value = valueTexData[x, y, z];
                        int   index = x +
                                      (y * X) +
                                      (z * X * Y);

                        valueTexPixels[index] = colorGradient.Evaluate(value);
                    }
                }
            }

            Texture3D valueTex = new Texture3D(X, Y, Z, TextureFormat.ARGB32, false);

            valueTex.wrapMode   = Wrapping;
            valueTex.filterMode = Filtering;
            valueTex.SetPixels(valueTexPixels);
            valueTex.Apply(UseMipmaps, !LeaveReadable);
            AssetDatabase.CreateAsset(valueTex, StringUtils.GetRelativePath(texPath, "Assets"));


            //Generate the normals texture.

            if (normalTexPath == null)
            {
                return(true);
            }

            float[,,] normalsValueData = baseData.ResampleFull(Mathf.Lerp,
                                                               Normals_X, Normals_Y, Normals_Z);
            Color[] normalsPixels = new Color[Normals_X * Normals_Y * Normals_Z];

            for (int z = 0; z < Normals_Z; ++z)
            {
                for (int y = 0; y < Normals_Y; ++y)
                {
                    for (int x = 0; x < Normals_X; ++x)
                    {
                        //The first digit is the X, the second is the Y, the third is the Z.
                        float _000, _100, _010, _110, _001, _101, _011, _111;
                        normalsValueData.Sample(x, y, z, true,
                                                out _000, out _100, out _010, out _110,
                                                out _001, out _101, out _011, out _111);

                        Vector3 gradient = new Vector3();
                        gradient.x = (_100 - _000) +
                                     (_110 - _010) +
                                     (_101 - _001) +
                                     (_111 - _011);
                        gradient.y = (_010 - _000) +
                                     (_110 - _100) +
                                     (_011 - _001) +
                                     (_111 - _101);
                        gradient.z = (_001 - _000) +
                                     (_101 - _100) +
                                     (_011 - _010) +
                                     (_111 - _110);

                        //Normalize.
                        if (gradient == Vector3.zero)
                        {
                            gradient = Vector3.up;
                        }
                        else
                        {
                            gradient = gradient.normalized;
                        }

                        //Pack into a color.
                        int index = x + (y * Normals_X) + (z * Normals_X * Normals_Y);
                        normalsPixels[index] = new Color(0.5f + (0.5f * gradient.x),
                                                         0.5f + (0.5f * gradient.y),
                                                         0.5f + (0.5f * gradient.z));
                    }
                }
            }

            Texture3D normalsTex = new Texture3D(Normals_X, Normals_Y, Normals_Z,
                                                 Normals_Format, Normals_UseMipmaps);

            normalsTex.wrapMode   = Normals_Wrapping;
            normalsTex.filterMode = Normals_Filtering;
            normalsTex.SetPixels(normalsPixels);
            normalsTex.Apply(Normals_UseMipmaps, !Normals_LeaveReadable);
            AssetDatabase.CreateAsset(normalsTex, StringUtils.GetRelativePath(normalTexPath, "Assets"));


            return(true);
        }
        void OnGUI()
        {
            GUILayout.Space(10.0f);

            X = EditorGUILayout.IntField("Width", X);
            Y = EditorGUILayout.IntField("Height", Y);

            GUILayout.Space(15.0f);

            GUILayout.Label("Gradient");
            GUILayout.BeginHorizontal();
            GUILayout.Space(15.0f);
            GUILayout.BeginVertical();
            for (int i = 0; i < GradientRamp_Colors.Count; ++i)
            {
                GUILayout.BeginHorizontal();
                GradientRamp_Colors[i] = EditorGUILayout.ColorField(GradientRamp_Colors[i]);
                if (i > 0)
                {
                    GradientRamp_Times[i] = EditorGUILayout.Slider(GradientRamp_Times[i],
                                                                   0.0f, 1.0f);
                }
                if (i > 0 && GUILayout.Button("+"))
                {
                    GradientRamp_Colors.Insert(i, GradientRamp_Colors[i]);
                    GradientRamp_Times.Insert(i, GradientRamp_Times[i] - 0.00000001f);
                }
                if (i > 0 && GradientRamp_Colors.Count > 2 && GUILayout.Button("-"))
                {
                    GradientRamp_Colors.RemoveAt(i);
                    GradientRamp_Times.RemoveAt(i);
                    i -= 1;
                }
                GUILayout.EndHorizontal();

                if (i > 0 && GradientRamp_Times[i] < GradientRamp_Times[i - 1])
                {
                    GradientRamp_Times[i] = GradientRamp_Times[i - 1] + 0.000001f;
                }
                else if (i < GradientRamp_Colors.Count - 1 &&
                         GradientRamp_Times[i] > GradientRamp_Times[i + 1])
                {
                    GradientRamp_Times[i] = GradientRamp_Times[i + 1] - 0.00001f;
                }
            }
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();

            GUILayout.Space(15.0f);


            GUILayout.BeginHorizontal();
            GUILayout.Label("Graph:");
            int oldIndex = SelectedGraphIndex;

            SelectedGraphIndex = EditorGUILayout.Popup(SelectedGraphIndex, graphNameOptions);
            if (oldIndex != SelectedGraphIndex)
            {
                Graph g = new Graph(graphPaths[SelectedGraphIndex]);
                if (g.Load().Length == 0)
                {
                    SelectedGraphIndex = oldIndex;
                }
                else
                {
                    gParams = new GraphParamCollection(g);
                }
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(10.0f);

            //Show some GUI elements for changing the parameters.
            if (graphPaths.Count > 0)
            {
                gParams.ParamEditorGUI();
            }

            GUILayout.Space(10.0f);

            //If a graph is selected, display a button to generate the texture.
            if (graphPaths.Count > 0)
            {
                if (GUILayout.Button("Generate Texture"))
                {
                    string savePath = EditorUtility.SaveFilePanel("Choose where to save the texture.",
                                                                  Application.dataPath, "MyTex.png", "png");
                    if (savePath.Length > 0)
                    {
                        //Load the graph.
                        Graph g = new Graph(graphPaths[SelectedGraphIndex]);
                        if (g.Load().Length > 0)
                        {
                            return;
                        }

                        //Render the gradient ramp to a texture,
                        //    then render the graph's noise to a texture.
                        Gradient grd = new Gradient();
                        grd.SetKeys(GradientRamp_Colors.Select((c, i) =>
                                                               new GradientColorKey(c, GradientRamp_Times[i])).ToArray(),
                                    new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f) });
                        Texture2D tex = GraphEditorUtils.GenerateToTexture(g, new GraphParamCollection(g, gParams),
                                                                           X, Y, grd);
                        if (tex == null)
                        {
                            return;
                        }

                        //Write out the texture as a PNG.
                        try
                        {
                            File.WriteAllBytes(savePath, tex.EncodeToPNG());
                        }
                        catch (Exception e)
                        {
                            Debug.LogError("Unable to save texture to file: " + e.Message);
                        }


                        //Now that we're finished, clean up.
                        AssetDatabase.ImportAsset(StringUtils.GetRelativePath(savePath, "Assets"));

                        //Finally, open explorer to show the user the texture.
                        if (Application.platform == RuntimePlatform.WindowsEditor)
                        {
                            System.Diagnostics.Process.Start("explorer.exe",
                                                             "/select," +
                                                             StringUtils.FixDirectorySeparators(savePath));
                        }
                        else if (Application.platform == RuntimePlatform.OSXEditor)
                        {
                            try
                            {
                                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                                proc.StartInfo.FileName  = "open";
                                proc.StartInfo.Arguments = "-n -R \"" +
                                                           StringUtils.FixDirectorySeparators(savePath) +
                                                           "\"";
                                proc.StartInfo.UseShellExecute        = false;
                                proc.StartInfo.RedirectStandardError  = false;
                                proc.StartInfo.RedirectStandardOutput = false;
                                proc.ErrorDataReceived += (s, a) => Debug.Log(a.Data);
                                if (proc.Start())
                                {
                                    proc.BeginErrorReadLine();
                                    proc.BeginOutputReadLine();
                                }
                                else
                                {
                                    Debug.LogError("Error opening Finder to show texture file");
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.LogError("Error opening Finder to show texture file: " + e.Message);
                            }
                        }
                    }
                }
            }
            else
            {
                GUILayout.Space(15.0f);
                GUILayout.Label("No graph files detected in the project!");
            }
        }