Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- C:\Windows\System32\cmd.exe /c "set LAUNCHER_PATH=dotnet&&set LAUNCHER_ARGS=.\bin\Debug\netcoreapp2.2\mysite.dll&& C:\iisexpress10_64\iisexpress.exe /path:C:\dev\mysite\web /port:8083 /trace:error"
- C:\Windows\System32\cmd.exe /c "cd C:\Program Files (x86)\IIS Express\&& iisexpress.exe /path:C:\dev\mysite\web /port:8084 /trace:error"
- (?:(?<!^)\G|((?:(?<!^)\G"|^)[^"]*"))(?:[^"]|(?<=[^\\]|[^\\]\\|[^\\]\\{3}|[^\\]\\{5})")
- have to reverse string to use this:
- (?:(?<!^)\G|((?:(?<!^)\G"|^)[^"]*"))(?:[^"]|"(?=\\(?:\\{2})*(?!\\)))
- loop through this to remove bottom-level brackets:
- ^((?:[^{}"']|"(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*'|\{(?!(?:[^{}"']|"(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*')*+\}))*+)\{(?:[^{}"']|"(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*')*+\}
- https://medium.com/planet-stories/a-gentle-introduction-to-gdal-part-4-working-with-satellite-data-d3835b5e2971
- gdalinfo -mm canyon.img
- gdal_translate -ot UInt16 -scale 757.586 2711.519 0 65535 -of ENVI canyon.img canyon.raw
- @{
- var str = "{adsfasdf \"asdf{ }asd\"{asdf\"asdfas{}\"{}asdfasdf}}";
- var c = 0;
- string Key;
- Match TheMatch;
- var Pattern = "^((?>(?:[^{}\\[\\]\"']|\"(?:[^\\\\\"]|\\\\.)*\"|'(?:[^\\\\']|\\\\.)*'|\\{(?!(?>(?:[^{}\\[\\]\"']|\"(?:[^\\\\\"]|\\\\.)*\"|'(?:[^\\\\']|\\\\.)*')*)\\})|\\[(?!(?>(?:[^{}\\[\\]\"']|\"(?:[^\\\\\"]|\\\\.)*\"|'(?:[^\\\\']|\\\\.)*')*)\\]))*))(\\{(?>(?:[^{}\\[\\]\"']|\"(?:[^\\\\\"]|\\\\.)*\"|'(?:[^\\\\']|\\\\.)*')*)\\}|\\[(?>(?:[^{}\\[\\]\"']|\"(?:[^\\\\\"]|\\\\.)*\"|'(?:[^\\\\']|\\\\.)*')*)\\])(.*)$";
- var TheRegex = new Regex(Pattern, RegexOptions.Singleline);
- var NestedObjects = new StringDictionary();
- while ((TheMatch = TheRegex.Match(str)).Success)
- {
- Key = "@" + c;
- NestedObjects.Add(Key, TheMatch.Groups[2].Value);
- str = TheMatch.Result("$1" + Key + "$3");
- c++;
- }
- <div style="background-color:aquamarine;padding:10px;">
- @str
- </div>
- <div>
- @TheRegex.Replace("{adsfasdf \"asdf{ }asd\"{asdf\"asdfas{}\"{}asdfasdf}}", "$1@0")
- </div>
- <div>
- @JsonTools.get_json_depth("{{[{asdfasdf}]{{{{asdfsdaf}}}}}}")
- </div>
- }
- using System;
- using System.IO;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Text.RegularExpressions;
- using UnityEditor;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- using System.Reflection;
- using static TerraLab.GenericHelpers;
- using static TerraLab.TerraLabHelpers;
- namespace TerraLab
- {
- public class TerraLab : ScriptableObject
- {
- public string Prop1;
- [HideInInspector]
- public string Params;
- private static TerraLab TheInstance;
- private static readonly string TerraLabFolder = "Assets/Editor/TerraLab";
- private static readonly string AssetPath = TerraLabFolder + "/TerraLabAssets.asset";
- [MenuItem("Terrain/TerraLabNEW")]
- private static TerraLab Init()
- {
- if (TheInstance == null && (TheInstance = AssetDatabase.LoadMainAssetAtPath(AssetPath) as TerraLab) == null)
- {
- var FullAssetPath = Regex.Replace(Application.dataPath, "Assets$", "") + AssetPath;
- if (File.Exists(FullAssetPath))
- {
- var FileName = Regex.Replace(AssetPath, ".*/", "");
- throw new Exception("No object could be loaded from " + FileName + ". Try restarting Unity.");
- }
- TheInstance = CreateInstance<TerraLab>();
- //set hideFlags = HideFlags.None or else you get an error
- //https://issuetracker.unity3d.com/issues/creating-asset-through-createasset-with-hideflags-dot-hideanddontsave-throws-error
- TheInstance.hideFlags = HideFlags.None;
- AssetDatabase.CreateAsset(TheInstance, AssetPath);
- }
- EditorWindow.GetWindow<TerraLabWindow>("TerraLab", typeof(Editor).Assembly.GetType("UnityEditor.InspectorWindow"));
- return TheInstance;
- }
- private class TerraLabWindow : EditorWindow
- {
- private string ScriptPath;
- private AssetBucket TheAssetBucket;
- private LayoutCSS TheLayout;
- private bool ScriptInRightPlace = false;
- //##########################################
- private bool SelectedTerrainHasNoData = false;
- private bool SelectedLayerCountsAreDifferent = false;
- private System.Random RNG = new System.Random();
- private int RandomInt32 { get { return RNG.Next(1000000000, 2147483647); } }
- private Terrain[] TerrainsInScene = new Terrain[0];
- private Terrain[] SelectedTerrains = new Terrain[0];
- void OnEnable()
- {
- //OnEnable is called by the object's constructor, so many
- //object properties may not be available from inside here
- //try and do post-instantiation config in the Init method
- Init();
- autoRepaintOnSceneChange = true;
- TheLayout = new LayoutCSS(this);
- TheAssetBucket = new AssetBucket(TheInstance);
- ScriptPath = AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(TheInstance));
- ScriptInRightPlace = Regex.IsMatch(ScriptPath, "^" + TerraLabFolder + "/TerraLab\\.cs$", RegexOptions.IgnoreCase);
- OnSelectionChange();
- }
- private void OnFocus()
- {
- //OnSelectionChange();
- //Debug.Log("OnFocus()");
- }
- private void OnHierarchyChange()
- {
- OnSelectionChange();
- Debug.Log("OnHierarchyChange()");
- }
- private void OnProjectChange()
- {
- OnSelectionChange();
- Debug.Log("OnProjectChange()");
- }
- private void OnValidate()
- {
- OnSelectionChange();
- Debug.Log("OnValidate()");
- }
- private void OnSelectionChange()
- {
- //##########################################
- //update the SelectedTerrains variable
- Terrain TheTerrain;
- TerrainData TData;
- var TerrainList = new List<Terrain>();
- SelectedTerrainHasNoData = false;
- //###############
- SelectedLayerCountsAreDifferent = false;
- TerrainLayer[] LastTerrainLayers = null;
- //###############
- var i = 0;
- foreach (var TheObject in Selection.objects)
- {
- var TheGameObject = TheObject as GameObject;
- if (TheGameObject != null)
- {
- TheTerrain = TheGameObject.GetComponent<Terrain>();
- if (TheTerrain != null)
- {
- if (TheTerrain.terrainData == null)
- {
- SelectedTerrainHasNoData = true;
- }
- else
- {
- TData = TheTerrain.terrainData;
- if (i == 0)
- {
- LastTerrainLayers = TData.terrainLayers;
- }
- if (LastTerrainLayers?.Length != TData.terrainLayers?.Length)
- {
- SelectedLayerCountsAreDifferent = true;
- }
- LastTerrainLayers = TData.terrainLayers;
- TerrainList.Add(TheTerrain);
- i++;
- }
- }
- }
- }
- SelectedTerrains = TerrainList.ToArray();
- //##########################################
- //update the TerrainsInScene variable
- TerrainList = new List<Terrain>();
- var SceneGameObjects = SceneManager.GetActiveScene().GetRootGameObjects();
- foreach (var TheGameObject in SceneGameObjects)
- {
- TheTerrain = TheGameObject.GetComponent<Terrain>();
- if (TheTerrain != null)
- {
- if (TheTerrain.terrainData != null)
- {
- TerrainList.Add(TheTerrain);
- }
- }
- }
- TerrainsInScene = TerrainList.ToArray();
- //##########################################
- RefreshLayersPanel(SelectedTerrains);
- //##########################################
- Repaint();
- }
- //##############################################################################
- //##############################################################################
- private static class MainPanel
- {
- public static int PanelInt = 0;
- }
- public class Truth
- {
- private string comparisonStr;
- private string variable;
- private string operate;
- private float constant;
- private Func<Truth, Dictionary<string, float>, bool> Compare;
- private Truth[] ANDS;
- private Truth[] ORS;
- private Truth(Truth[] ANDS, Truth[] ORS)
- {
- this.ANDS = ANDS;
- this.ORS = ORS;
- }
- private Truth(string comparisonStr, string variable, string operate, float constant, bool variableOnLeft)
- {
- this.comparisonStr = comparisonStr;
- this.variable = variable;
- this.operate = operate;
- this.constant = constant;
- if (variableOnLeft)
- {
- Compare = delegate (Truth obj, Dictionary<string, float> Values)
- {
- var value = Values[obj.variable];
- var result = false;
- if (obj.operate == ">=")
- {
- result = value >= obj.constant;
- }
- else if (obj.operate == "<=")
- {
- result = value <= obj.constant;
- }
- else if (obj.operate == ">")
- {
- result = value > obj.constant;
- }
- else if (obj.operate == "<")
- {
- result = value < obj.constant;
- }
- else if (obj.operate == "==")
- {
- result = value == obj.constant;
- }
- return result;
- };
- }
- else
- {
- Compare = delegate (Truth obj, Dictionary<string, float> Values)
- {
- var value = Values[obj.variable];
- var result = false;
- if (obj.operate == ">=")
- {
- result = obj.constant >= value;
- }
- else if (obj.operate == "<=")
- {
- result = obj.constant <= value;
- }
- else if (obj.operate == ">")
- {
- result = obj.constant > value;
- }
- else if (obj.operate == "<")
- {
- result = obj.constant < value;
- }
- else if (obj.operate == "==")
- {
- result = obj.constant == value;
- }
- return result;
- };
- }
- }
- public bool Evaluate(Dictionary<string, float> Values)
- {
- bool result;
- if (Compare != null)
- {
- result = Compare(this, Values);
- }
- else if (ANDS != null)
- {
- result = true;
- foreach (var TheTruth in ANDS)
- {
- if (!TheTruth.Evaluate(Values))
- {
- result = false;
- break;
- }
- }
- }
- else
- {
- result = false;
- foreach (var TheTruth in ORS)
- {
- if (TheTruth.Evaluate(Values))
- {
- result = true;
- break;
- }
- }
- }
- return result;
- }
- public static Truth Compile(string input, char[] variables, out string Errors)
- {
- Errors = "";
- Match TheMatch;
- Truth TheTruth;
- GroupCollection Groups;
- var ReplacementPrefix = "@";
- input = ApplyPrecedence(Regex.Replace((input ?? "").ToLower(), "\\s+", ""), ReplacementPrefix);
- input = ExtractParentheses(input, ReplacementPrefix, out string[] parenContent);
- float constant;
- string GroupErrors;
- var UseAnd = true;
- var RegexVarStr = Regex.Escape(new string(variables));
- string variable, operate;
- var TruthList = new List<Truth>();
- var Matches = Regex.Matches(input, "(?:^|\\G(?<!^)(\\&\\&|\\|\\|))(?:(?:([" + RegexVarStr + "])(>=|<=|>|<|==)(-?(?:[0-9]*\\.[0-9]+|[0-9]+))|(-?(?:[0-9]*\\.[0-9]+|[0-9]+))(>=|<=|>|<|==)([" + RegexVarStr + "]))|\\(@([0-9]+)\\))(?=(?:(?:\\&\\&|\\|\\|)(?:(?:[" + RegexVarStr + "](?:>=|<=|>|<|==)-?(?:[0-9]*\\.[0-9]+|[0-9]+)|-?(?:[0-9]*\\.[0-9]+|[0-9]+)(?:>=|<=|>|<|==)[" + RegexVarStr + "])|\\(@[0-9]+\\)))*$)");
- if (Matches.Count == 0)
- {
- Errors += "Invalid comparison string: " + input;
- }
- for (var i = 0; i < Matches.Count; i++)
- {
- TheTruth = null;
- TheMatch = Matches[i];
- Groups = TheMatch.Groups;
- UseAnd = (Groups[1].Value == "||") ? false : UseAnd;
- if (!string.IsNullOrEmpty(Groups[8].Value))
- {
- TheTruth = Compile(parenContent[int.Parse(Groups[8].Value)], variables, out GroupErrors);
- if (GroupErrors != "")
- {
- Errors += GroupErrors;
- break;
- }
- }
- else if (!string.IsNullOrEmpty(Groups[2].Value))
- {
- variable = Groups[2].Value;
- operate = Groups[3].Value;
- constant = float.Parse(Groups[4].Value);
- TheTruth = new Truth(TheMatch.Value, variable, operate, constant, true);
- }
- else if (!string.IsNullOrEmpty(Groups[5].Value))
- {
- constant = float.Parse(Groups[5].Value);
- operate = Groups[6].Value;
- variable = Groups[7].Value;
- TheTruth = new Truth(TheMatch.Value, variable, operate, constant, false);
- }
- else
- {
- Errors += "Invalid comparison element: " + TheMatch.Value;
- break;
- }
- TruthList.Add(TheTruth);
- }
- if (Errors == "")
- {
- return UseAnd ? new Truth(TruthList.ToArray(), null) : new Truth(null, TruthList.ToArray());
- }
- else
- {
- return null;
- }
- }
- private static string ApplyPrecedence(string input, string replacementPrefix)
- {
- //this method puts parentheses around comparisons needing left-to-right precedence
- //for example, h == 10 || s <= 323.22 && s == 3 becomes (h == 10 || s <= 323.22) && s == 3
- //first, take out all the parentheses content so the precedence regex can do its job
- input = ExtractParentheses(input, replacementPrefix, out string[] parenContent);
- //apply the parentheses where needed using a regex
- input = Regex.Replace(input, "(?<=\\|\\|)((?:[^|&]*&&)+[^|&]+)(?=\\|\\||$)|(?<=^|\\|\\|)((?:[^|&]*&&)+[^|&]+)(?=\\|\\|)|(?<=&&)((?:[^|&]*\\|\\|)+[^|&]+)(?=&&|$)|(?<=^|&&)((?:[^|&]*\\|\\|)+[^|&]+)(?=&&)", "($1$2$3$4)");
- //re-insert the parentheses content before returning
- for (var i = 0; i < parenContent.Length; i++)
- {
- input = input.Replace(replacementPrefix + i, parenContent[i]);
- }
- return input;
- }
- private static string ExtractParentheses(string inputStr, string replacementPrefix, out string[] parenContent)
- {
- char x;
- var Count = 0;
- var newStr = "";
- var IsOpen = false;
- var CurParenGroup = "";
- var ParenGroupList = new List<string>();
- var CharArr = (inputStr ?? "").ToCharArray();
- for (var i = 0; i < CharArr.Length; i++)
- {
- x = CharArr[i];
- if (x == '(')
- {
- if (!IsOpen)
- {
- CurParenGroup = "";
- newStr += x;
- }
- else
- {
- CurParenGroup += x;
- newStr += (replacementPrefix == null) ? " " : "";
- }
- Count++;
- IsOpen = true;
- }
- else
- {
- if (IsOpen)
- {
- if (x == ')')
- {
- Count--;
- if (Count == 0)
- {
- IsOpen = false;
- newStr += ((replacementPrefix == null) ? "" : (replacementPrefix + ParenGroupList.Count)) + x;
- ParenGroupList.Add(CurParenGroup);
- }
- else
- {
- CurParenGroup += x;
- newStr += (replacementPrefix == null) ? " " : "";
- }
- }
- else
- {
- CurParenGroup += x;
- newStr += (replacementPrefix == null) ? " " : "";
- }
- }
- else
- {
- newStr += x;
- }
- }
- }
- parenContent = ParenGroupList.ToArray();
- return newStr;
- }
- }
- private void OnGUI()
- {
- //var FontStyle = "font-size:14px;font-family:'Arial';";
- //var FontStyle = "font-size:14px;font-family:'Monaco','Consolas','Menlo','Lucida Console';";
- var FontStyle = "font-size:14px;font-family:'Arial';";
- TheLayout.SetDefaultRowSpace(5);
- TheLayout.SetBoxStyle(GUI.skin.box, "margin:0;border:0;padding:0;stretch-width:false;" + FontStyle + "");
- TheLayout.SetButtonStyle(GUI.skin.button, "margin:0;padding:4px 4px;vertical-align:top;min-height:text;stretch-width:false;" + FontStyle + "");
- TheLayout.SetToolbarStyle(GUI.skin.button, "margin:0;stretch-width:true;" + FontStyle + "");
- TheLayout.SetLabelStyle(GUI.skin.label, "margin:0px;border:0;padding:0px 4px;vertical-align:middle;min-height:text;stretch-width:false;white-space:nowrap;" + FontStyle + "");
- TheLayout.SetTextAreaStyle(GUI.skin.textArea, "margin:0;stretch-width:false;" + FontStyle + "");
- TheLayout.SetTextFieldStyle(GUI.skin.textField, "margin:0px;padding:2px 4px;vertical-align:middle;min-height:text;stretch-width:false;" + FontStyle + "");
- TheLayout.SetToggleStyle(GUI.skin.toggle, "margin:0;stretch-width:false;");
- TheLayout.SetDropdownStyle(EditorStyles.popup, "margin:0;");
- TheLayout.SetHorizontalStyle(new GUIStyle(), "margin:0;border:0;padding:0;stretch-width:false;" + FontStyle + "");
- TheLayout.SetVerticalStyle(new GUIStyle(), "margin:0;border:0;padding:0;stretch-width:false;" + FontStyle + "");
- TheLayout.BeginVertical("padding:10px;stretch-height:true;");
- TheLayout.StartRowSpace();
- if (!ScriptInRightPlace)
- {
- var ErrorMessage = "TerraLab is not installed correctly. Make sure the file \"TerraLab.cs\" resides in the directory \"" + TerraLabFolder + "\"";
- TheLayout.Label(ErrorMessage, "font-size:30px;background-color:rgba(255,0,0,0.75);");
- }
- else
- {
- if (SelectedTerrainHasNoData)
- {
- TheLayout.Label("One or more selected terrains has no TerrainData.", "background-color:rgba(255,0,0,0.75);");
- }
- MainPanel.PanelInt = TheLayout.Toolbar(MainPanel.PanelInt, new[] { "Create", "Arrange", "Heightmap", "Sew", "Smooth", "Layers", "Properties", "Debug" });
- GUILayout.Space(10);
- if (MainPanel.PanelInt == 0)
- {
- PaintCreatePanel();
- }
- else if (MainPanel.PanelInt == 1)
- {
- PaintArrangePanel();
- }
- else if (MainPanel.PanelInt == 2)
- {
- PaintHeightmapPanel();
- }
- else if (MainPanel.PanelInt == 3)
- {
- PaintSewPanel();
- }
- else if (MainPanel.PanelInt == 4)
- {
- PaintSmoothPanel();
- }
- else if (MainPanel.PanelInt == 5)
- {
- PaintLayersPanel();
- }
- else if (MainPanel.PanelInt == 6)
- {
- PaintPropertiesPanel();
- }
- else if (MainPanel.PanelInt == 7)
- {
- PaintDebugPanel();
- }
- if (MainPanel.PanelInt != 6)
- {
- DebugPanel.DebugMsg = "";
- }
- }
- TheLayout.EndRowSpace();
- TheLayout.EndVertical();
- }
- //##############################################################################
- //##############################################################################
- private static class CreatePanel
- {
- public static string AmountStr = "4";
- public static string LengthStr = "128";
- public static string WidthStr = "128";
- public static string HeightStr = "128";
- public static string ResolutionStr = "32";
- }
- private void PaintCreatePanel()
- {
- var Errors = "";
- var MaxAmount = 256;
- if (!int.TryParse(CreatePanel.AmountStr, out int Amount) || Amount < 1)
- {
- Errors += "Amount must be an integer greater than 0.\n";
- }
- else
- {
- Amount = Math.Min(MaxAmount, Amount);
- CreatePanel.AmountStr = Amount.ToString();
- }
- if (!int.TryParse(CreatePanel.LengthStr, out int Length) || Length < 1)
- {
- Errors += "Length must be an integer greater than 0.\n";
- }
- if (!int.TryParse(CreatePanel.WidthStr, out int Width) || Width < 1)
- {
- Errors += "Width must be an integer greater than 0.\n";
- }
- if (!int.TryParse(CreatePanel.HeightStr, out int Height) || Height < 0)
- {
- Errors += "Height must be an integer greater than 0.\n";
- }
- if (!int.TryParse(CreatePanel.ResolutionStr, out int Resolution) || Resolution < 32 || Resolution > 4096)
- {
- Errors += "Resolution must be an integer between 32 and 4096.\n";
- }
- TheLayout.BeginHorizontal();
- TheLayout.BeginVertical("width:500px;background-color:rgba(0,0,0,0.15);padding:5px;");
- TheLayout.BeginVertical();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Amount", "width:128px;");
- CreatePanel.AmountStr = TheLayout.TextField(CreatePanel.AmountStr, "width:100px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Length", "width:128px;");
- CreatePanel.LengthStr = TheLayout.TextField(CreatePanel.LengthStr, "width:100px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Width", "width:128px;");
- CreatePanel.WidthStr = TheLayout.TextField(CreatePanel.WidthStr, "width:100px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Height", "width:128px;");
- CreatePanel.HeightStr = TheLayout.TextField(CreatePanel.HeightStr, "width:100px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Resolution", "width:128px;");
- CreatePanel.ResolutionStr = TheLayout.TextField(CreatePanel.ResolutionStr, "width:100px;");
- TheLayout.EndHorizontal();
- GUI.enabled = (Errors == "");
- if (TheLayout.Button("Create Terrain" + (Amount == 1 ? "" : "s"), "width:200px;margin-top:5px;"))
- {
- CreateTerrains(Amount, Length, Width, Height, Resolution);
- }
- GUI.enabled = true;
- TheLayout.EndVertical();
- TheLayout.EndVertical();
- if (Errors != "")
- {
- TheLayout.BeginHorizontal("background-color:rgba(255,255,0,0.75);");
- TheLayout.Label(Errors);
- TheLayout.EndHorizontal();
- }
- TheLayout.EndHorizontal();
- }
- private void CreateTerrains(int Amount, int Length, int Width, int Height, int Resolution)
- {
- var UnixNow = DateTime.Now.ToUtcUnixTimeSeconds();
- var TerrainNum = Math.Max(int.TryParse(TheAssetBucket.GetKey("TerrainNum"), out int intResult) ? intResult : -1, -1) + 1;
- var LayerNum = Math.Max(int.TryParse(TheAssetBucket.GetKey("LayerNum"), out intResult) ? intResult : -1, -1) + 1;
- var TerrainTime = long.TryParse(TheAssetBucket.GetKey("TerrainTime"), out long longResult) ? longResult : 0;
- TerrainTime = (TerrainTime == UnixNow) ? UnixNow + 1 : UnixNow;
- var AlphaMapResolution = 16;
- Terrain TheTerrainComponent;
- TerrainData TheTerrainData;
- GameObject TheGameObject;
- string PaddedNum;
- var LastLayerNum = LayerNum + 1;
- var LastTerrainNum = 0;
- var NewTerrains = new GameObject[Amount];
- var NewTerrainDatas = new TerrainData[Amount];
- //AssetDatabase.Refresh();
- //the Texture2D needs to be made into an asset for it to save properly
- var DiffuseTexture = (Texture2D)TheAssetBucket.Get("DefaultTerrainTexture");
- if (DiffuseTexture == null)
- {
- DiffuseTexture = GetWhiteGridTexture(Color.blue, 0, 0.1);
- DiffuseTexture.name = "DefaultTerrainTexture";
- TheAssetBucket.Add(DiffuseTexture, false);
- }
- //beige
- //DiffuseTexture = GetWhiteGridTexture(0.886, 0.847, 0.733, 0, 0.5);
- //dark blue
- var TheTerrainLayer = new TerrainLayer
- {
- name = "Terrain_" + PadLeft(LastLayerNum, '0', 7) + "_Layer_" + TerrainTime,
- diffuseTexture = DiffuseTexture,
- maskMapTexture = null,
- normalMapTexture = null,
- metallic = 0,
- smoothness = 0,
- tileOffset = new Vector2(0, 0),
- tileSize = new Vector2(Width / (float)Resolution, Length / (float)Resolution)
- };
- TheAssetBucket.Add(TheTerrainLayer, false);
- var AlphaMap = new float[AlphaMapResolution, AlphaMapResolution, 1];
- //need to set all the vertices to opaque for layer 0
- for (var x = 0; x < AlphaMapResolution; x++)
- {
- for (var y = 0; y < AlphaMapResolution; y++)
- {
- AlphaMap[x, y, 0] = 1;
- }
- }
- for (var i = 0; i < Amount; i++)
- {
- //TerrainData is what the asset uses
- //GameObject is what the scene uses
- //CANNOT CREATE ASSETS OUT OF
- //GAMEOBJECTS OR COMPONENTS
- TheTerrainData = new TerrainData();
- //the TerrainData needs to be created as an asset before
- //modifying it so that all the property changes save properly
- TheAssetBucket.Add(TheTerrainData, false);
- LastTerrainNum = TerrainNum + i;
- PaddedNum = PadLeft(LastTerrainNum, '0', 7);
- TheTerrainData.name = "Terrain_" + PaddedNum + "_Data_" + TerrainTime;
- TheTerrainData.heightmapResolution = Resolution;
- TheTerrainData.alphamapResolution = AlphaMapResolution;
- //SET THE TERRAIN SIZE AFTER SETTING THE HEIGHTMAP RESOLUTION
- //OR ELSE THE SIZE WILL BE RESET
- TheTerrainData.size = new Vector3(Width, Height, Length);
- TheTerrainData.terrainLayers = new[] { TheTerrainLayer };
- TheTerrainData.alphamapTextures[0].name = "Terrain_" + PaddedNum + "_Alpha_" + TerrainTime;
- //TERRAINDATAS NEED TO BE
- //SAVED AS ASSETS BEFORE CALLING SETALPHAMAPS
- //OR ELSE THE TEXTURE WON'T APPEAR ON THE TERRAINS
- TheTerrainData.SetAlphamaps(0, 0, AlphaMap);
- TheGameObject = Terrain.CreateTerrainGameObject(TheTerrainData);
- TheGameObject.name = "Terrain_" + PaddedNum + "_" + TerrainTime;
- Undo.RegisterCreatedObjectUndo(TheGameObject, "TerraLab create terrain");
- TheTerrainComponent = TheGameObject.GetComponent<Terrain>();
- TheTerrainComponent.name = "Terrain_" + PaddedNum + "_Component_" + TerrainTime;
- TheTerrainComponent.heightmapPixelError = 1;
- TheTerrainComponent.basemapDistance = 1000000;
- TheTerrainComponent.allowAutoConnect = true;
- TheTerrainComponent.groupingID = 0;
- NewTerrains[i] = TheGameObject;
- NewTerrainDatas[i] = TheTerrainData;
- }
- TheAssetBucket.Save();
- TheAssetBucket.SetKey("TerrainNum", LastTerrainNum.ToString());
- TheAssetBucket.SetKey("TerrainTime", TerrainTime.ToString());
- Selection.objects = NewTerrains;
- }
- //##############################################################################
- //##############################################################################
- private static class ArrangePanel
- {
- public static string yCoordStr = "0";
- public static bool Rotate90 = false;
- public static int SortMethod = 0;
- public static PositionOptions PositionEnum = PositionOptions.MiddleCenter;
- public enum PositionOptions
- {
- TopLeft = 0,
- TopCenter = 1,
- TopRight = 2,
- MiddleLeft = 3,
- MiddleCenter = 4,
- MiddleRight = 5,
- BottomLeft = 6,
- BottomCenter = 7,
- BottomRight = 8
- }
- }
- private void PaintArrangePanel()
- {
- if (empty(SelectedTerrains))
- {
- TheLayout.Label("No terrains selected.");
- }
- else
- {
- TheLayout.BeginVertical("width:500px;background-color:rgba(0,0,0,0.15);padding:5px;");
- var Errors = "";
- var LastWidthHeight = SelectedTerrains[0].terrainData.size;
- foreach (var Terrain in SelectedTerrains)
- {
- if (LastWidthHeight != Terrain.terrainData.size)
- {
- Errors += "Cannot arrange terrains of different sizes.";
- break;
- }
- }
- if (Errors != "")
- {
- TheLayout.Label(Errors);
- }
- else
- {
- var Count = SelectedTerrains.Length;
- TheLayout.Label(Count + " terrain" + ((Count == 1) ? "" : "s") + " selected.", "margin-bottom:5px;");
- TheLayout.BeginHorizontal();
- TheLayout.Label("Y Coordinate:", "width:140px;");
- ArrangePanel.yCoordStr = TheLayout.TextField(ArrangePanel.yCoordStr, "width:110px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Position:", "width:140px;");
- ArrangePanel.PositionEnum = TheLayout.Dropdown(ArrangePanel.PositionEnum, "width:210px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Rotate 90°:", "width:140px;");
- ArrangePanel.Rotate90 = TheLayout.Toggle(ArrangePanel.Rotate90);
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Sort By:", "width:140px;");
- ArrangePanel.SortMethod = TheLayout.Toolbar(ArrangePanel.SortMethod, new[] { "Ascending", "Descending", "Random" });
- TheLayout.EndHorizontal();
- var yCoordIsValid = float.TryParse(ArrangePanel.yCoordStr, out float yCoord);
- var Factors = new Dictionary<int, int>();
- decimal Multiple;
- for (var i = 1; i <= (Count / 2) + 1; i++)
- {
- if (IsInteger(Multiple = Count / (decimal)i) && !Factors.ContainsKey((int)Multiple))
- {
- Factors.Add(i, (int)Multiple);
- }
- }
- foreach (var Factor in Factors)
- {
- if (TheLayout.Button(Factor.Key + " x " + Factor.Value, "width:128px;margin-top:5px;"))
- {
- if (yCoordIsValid)
- {
- ArrangeTerrains(SelectedTerrains, Factor.Value, Factor.Key, ArrangePanel.SortMethod, yCoord);
- }
- else
- {
- ArrangeTerrains(SelectedTerrains, Factor.Value, Factor.Key, ArrangePanel.SortMethod);
- }
- }
- }
- }
- TheLayout.EndVertical();
- }
- }
- private void ArrangeTerrains(Terrain[] Terrains, int xNum, int zNum, int SortMethod, float yCoord = 0)
- {
- if (SortMethod == 2)
- {
- Terrains = Terrains.OrderBy(x => RandomInt32).ToArray();
- }
- else if (SortMethod == 1)
- {
- Terrains = Terrains.OrderByDescending(x => x.name).ToArray();
- }
- else
- {
- Terrains = Terrains.OrderBy(x => x.name).ToArray();
- }
- if (!empty(Terrains) && xNum > 0 && zNum > 0 && xNum * zNum == Terrains.Length)
- {
- var xPos = -0.5F;
- var yPos = 0.5F;
- var ThePosition = ArrangePanel.PositionEnum;
- if (ThePosition == ArrangePanel.PositionOptions.TopLeft)
- {
- xPos = -1F;
- yPos = 1F;
- }
- else if (ThePosition == ArrangePanel.PositionOptions.TopCenter)
- {
- xPos = -0.5F;
- yPos = 1F;
- }
- else if (ThePosition == ArrangePanel.PositionOptions.TopRight)
- {
- xPos = 0F;
- yPos = 1F;
- }
- else if (ThePosition == ArrangePanel.PositionOptions.MiddleLeft)
- {
- xPos = -1F;
- yPos = 0.5F;
- }
- else if (ThePosition == ArrangePanel.PositionOptions.MiddleCenter)
- {
- xPos = -0.5F;
- yPos = 0.5F;
- }
- else if (ThePosition == ArrangePanel.PositionOptions.MiddleRight)
- {
- xPos = 0F;
- yPos = 0.5F;
- }
- else if (ThePosition == ArrangePanel.PositionOptions.BottomLeft)
- {
- xPos = -1F;
- yPos = 0F;
- }
- else if (ThePosition == ArrangePanel.PositionOptions.BottomCenter)
- {
- xPos = -0.5F;
- yPos = 0F;
- }
- else if (ThePosition == ArrangePanel.PositionOptions.BottomRight)
- {
- xPos = 0F;
- yPos = 0F;
- }
- if (ArrangePanel.Rotate90)
- {
- var Temp = xNum;
- xNum = zNum;
- zNum = Temp;
- }
- var Size = Terrains[0].terrainData.size;
- var xCoord = xNum * Size.x * xPos;
- //subtract one z-length from zCoord because
- //unlike with the x axis where we go from negative to positive,
- //with the z axis we go from positive to negative
- var zCoord = (zNum * Size.z * yPos) - Size.z;
- Terrain TheTerrain;
- var c = 0;
- for (var z = 0; z < zNum; z++)
- {
- for (var x = 0; x < xNum; x++)
- {
- TheTerrain = Terrains[c];
- Undo.RecordObject(TheTerrain.transform, "TerraLab arrange terrains");
- TheTerrain.transform.position = new Vector3(xCoord + (x * Size.x), yCoord, zCoord - (z * Size.z));
- c++;
- }
- }
- }
- }
- //##############################################################################
- //##############################################################################
- private static class HeightmapPanel
- {
- public static HeightmapInfo TheHeightmap = null;
- public static string LoadHeightmapErrors = "";
- public static string ApplyHeightmapErrors = "";
- public static string ResetHeightmapErrors = "";
- public static bool ReverseBytes = false;
- public static bool Use8Bit = false;
- public static bool FlipX = false;
- public static bool FlipZ = false;
- }
- private class HeightmapInfo
- {
- public readonly long Edge = -1;
- public readonly long Length = -1;
- public readonly bool Is8Bit = false;
- public readonly bool Is16Bit = false;
- public readonly bool IsImage = false;
- public readonly string FilePath = null;
- public static HeightmapInfo CreateInstance(string Path, out string Errors)
- {
- Errors = "";
- HeightmapInfo TheHeightmapInfo = null;
- if (!File.Exists(Path))
- {
- Errors += "Invalid file path.\n";
- }
- else
- {
- var FileName = Regex.Replace(Path, ".*/", "");
- long Length = -1;
- decimal Edge = -1;
- var Is8Bit = false;
- var Is16Bit = false;
- var IsImage = false;
- string FilePath = null;
- using (var TheStream = File.OpenRead(Path))
- {
- using (var TheReader = new BinaryReader(TheStream))
- {
- FilePath = Path;
- Length = TheStream.Length;
- Edge = (decimal)Math.Sqrt(Length / 2);
- if (IsInteger(Edge))
- {
- Is16Bit = true;
- }
- else
- {
- Edge = (decimal)Math.Sqrt(Length);
- if (IsInteger(Edge))
- {
- Is8Bit = true;
- }
- else
- {
- Edge = -1;
- }
- }
- }
- }
- if (Edge != 32 && Edge != 64 && Edge != 128 && Edge != 256 && Edge != 512 && Edge != 1024 && Edge != 2048 && Edge != 4096 && Edge != 8192 && Edge != 16384)
- {
- Errors += "\"" + FileName + "\"\n";
- Errors += "Could not determine heightmap resolution.\n";
- Errors += "Only these resolutions are supported: 32x32, 64x64, 128x128, 256x256, 512x512, 1024x1024, 2048x2048, 4096x4096, 8192x8192, 16384x16384\n";
- }
- if (Errors == "")
- {
- TheHeightmapInfo = new HeightmapInfo((int)Edge, Length, Is8Bit, Is16Bit, IsImage, FilePath);
- }
- }
- return TheHeightmapInfo;
- }
- private HeightmapInfo(int Edge, long Length, bool Is8Bit, bool Is16Bit, bool IsImage, string FilePath)
- {
- this.Edge = Edge;
- this.Length = Length;
- this.Is8Bit = Is8Bit;
- this.Is16Bit = Is16Bit;
- this.IsImage = IsImage;
- this.FilePath = FilePath;
- }
- }
- private void PaintHeightmapPanel()
- {
- TheLayout.BeginVertical();
- if (empty(SelectedTerrains))
- {
- TheLayout.Label("No terrains selected.");
- }
- else
- {
- var Errors = "";
- var TheTerrain = SelectedTerrains[0];
- //var Neighbors = new NeighborGroup(TheTerrain, TerrainsInScene, out string Errors);
- if (Errors != "")
- {
- TheLayout.Label(Errors);
- }
- else
- {
- if (HeightmapPanel.TheHeightmap == null)
- {
- Errors += "No heightmap file has been selected.\n";
- }
- TheLayout.BeginHorizontal();
- TheLayout.BeginVertical("width:500px;background-color:rgba(0,0,0,0.15);padding:5px;");
- TheLayout.BeginHorizontal();
- TheLayout.Label("Select Heightmap File:", "width:200px;");
- var FileName = (HeightmapPanel.TheHeightmap == null) ? null : Regex.Replace(HeightmapPanel.TheHeightmap.FilePath, ".*/", "");
- if (TheLayout.Button(empty(FileName) ? "Browse" : FileName))
- {
- HeightmapPanel.TheHeightmap = HeightmapInfo.CreateInstance(EditorUtility.OpenFilePanel("Heightmap File", "", ""), out HeightmapPanel.LoadHeightmapErrors);
- HeightmapPanel.Use8Bit = (HeightmapPanel.TheHeightmap == null) ? false : HeightmapPanel.TheHeightmap.Is8Bit;
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Heightmap Details:", "width:200px;");
- var HeightmapDetails = "";
- if (empty(HeightmapPanel.LoadHeightmapErrors))
- {
- if (HeightmapPanel.TheHeightmap == null)
- {
- HeightmapDetails += "No heightmap selected.";
- }
- else
- {
- var HM = HeightmapPanel.TheHeightmap;
- HeightmapDetails += "Bit Depth: " + (HM.Is16Bit ? "16" : "8") + "\nResolution: " + HM.Edge + "x" + HM.Edge + "\nSize:" + AddCommas(HM.Length) + " bytes";
- }
- }
- else
- {
- HeightmapDetails += Regex.Replace(HeightmapPanel.LoadHeightmapErrors, "[\\s\\r\\n]*$", "");
- }
- TheLayout.Label(HeightmapDetails);
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Reverse Byte Order:", "width:200px;");
- HeightmapPanel.ReverseBytes = TheLayout.Toggle(HeightmapPanel.ReverseBytes);
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Heightmap Is 8-bit:", "width:200px;");
- HeightmapPanel.Use8Bit = TheLayout.Toggle(HeightmapPanel.Use8Bit);
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Flip X:", "width:200px;");
- HeightmapPanel.FlipX = TheLayout.Toggle(HeightmapPanel.FlipX);
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Flip Z:", "width:200px;");
- HeightmapPanel.FlipZ = TheLayout.Toggle(HeightmapPanel.FlipZ);
- TheLayout.EndHorizontal();
- GUI.enabled = (Errors == "");
- if (TheLayout.Button("Apply Heightmap", "width:200px;margin-top:5px;"))
- {
- ApplyHeightmapMultiple(SelectedTerrains, HeightmapPanel.TheHeightmap, HeightmapPanel.ReverseBytes, HeightmapPanel.Use8Bit, HeightmapPanel.FlipX, HeightmapPanel.FlipZ, out HeightmapPanel.ApplyHeightmapErrors);
- }
- if (HeightmapPanel.ApplyHeightmapErrors != "")
- {
- Errors += HeightmapPanel.ApplyHeightmapErrors;
- }
- GUI.enabled = true;
- if (TheLayout.Button("Reset Heightmap", "width:200px;margin-top:5px;"))
- {
- ResetHeightmap(SelectedTerrains, out HeightmapPanel.ResetHeightmapErrors);
- }
- if (HeightmapPanel.ResetHeightmapErrors != "")
- {
- Errors += HeightmapPanel.ResetHeightmapErrors;
- }
- TheLayout.EndVertical();
- if (Errors != "")
- {
- Errors = Regex.Replace(Errors, "[\\s\\r\\n]*$", "");
- TheLayout.BeginHorizontal("background-color:rgba(255,255,0,0.75);");
- TheLayout.Label(Errors);
- TheLayout.EndHorizontal();
- }
- TheLayout.EndHorizontal();
- }
- }
- TheLayout.EndVertical();
- }
- private void ApplyHeightmapMultiple(Terrain[] Terrains, HeightmapInfo TheHeightmap, bool ReverseBytes, bool Use8Bit, bool FlipX, bool FlipZ, out string Errors)
- {
- Errors = "";
- if (empty(Terrains))
- {
- Errors += "No terrains were provided.\n";
- }
- else if (TheHeightmap == null)
- {
- Errors += "No heightmap was provided.\n";
- }
- else
- {
- var EdgeCount = Math.Sqrt(Terrains.Length);
- var NotSquareMsg = "Selected terrains must form a square (e.g. 2x2, 3x3, 4x4).\nMake sure the edges of each terrain are perfectly lined up with their neighbors.\n";
- if (!IsInteger((decimal)EdgeCount))
- {
- Errors += NotSquareMsg;
- }
- else
- {
- var TerrainEdge = (Terrains[0].terrainData.heightmapWidth - 1) * EdgeCount;
- if (TerrainEdge > TheHeightmap.Edge)
- {
- Errors += "The total terrain resolution is greater than the heightmap file's resolution (" + TerrainEdge + "x" + TerrainEdge + " versus " + TheHeightmap.Edge + "x" + TheHeightmap.Edge + ").\n";
- }
- else if (TerrainEdge < TheHeightmap.Edge)
- {
- Errors += "The total terrain resolution is less than the heightmap file's resolution (" + TerrainEdge + "x" + TerrainEdge + " versus " + TheHeightmap.Edge + "x" + TheHeightmap.Edge + ").\n";
- }
- if (Errors == "")
- {
- var StartingTerrain = Terrains[0];
- var LowestX = StartingTerrain.transform.position.x;
- var LowestZ = StartingTerrain.transform.position.z;
- var LastX = StartingTerrain.terrainData.heightmapWidth - 1;
- var LastZ = StartingTerrain.terrainData.heightmapHeight - 1;
- var NeighborGroupCollection = new Dictionary<Terrain, NeighborGroup>();
- var _1000 = 0;
- var _0100 = 0;
- var _0010 = 0;
- var _0001 = 0;
- var _1100 = 0;
- var _0110 = 0;
- var _0011 = 0;
- var _1001 = 0;
- var _1111 = 0;
- NeighborGroup TheNeighborGroup;
- string NeighborErrors;
- foreach (var TheTerrain in Terrains)
- {
- TheNeighborGroup = new NeighborGroup(TheTerrain, Terrains, out NeighborErrors);
- NeighborGroupCollection.Add(TheTerrain, TheNeighborGroup);
- if (NeighborErrors != "")
- {
- Errors += NeighborErrors;
- break;
- }
- else
- {
- if (TheTerrain.transform.position.x < LowestX)
- {
- StartingTerrain = TheTerrain;
- LowestX = TheTerrain.transform.position.x;
- }
- if (TheTerrain.transform.position.z < LowestZ)
- {
- StartingTerrain = TheTerrain;
- LowestZ = TheTerrain.transform.position.z;
- }
- _1000 += (TheNeighborGroup.Top == null && TheNeighborGroup.Right != null && TheNeighborGroup.Bottom != null && TheNeighborGroup.Left != null) ? 1 : 0;
- _0100 += (TheNeighborGroup.Top != null && TheNeighborGroup.Right == null && TheNeighborGroup.Bottom != null && TheNeighborGroup.Left != null) ? 1 : 0;
- _0010 += (TheNeighborGroup.Top != null && TheNeighborGroup.Right != null && TheNeighborGroup.Bottom == null && TheNeighborGroup.Left != null) ? 1 : 0;
- _0001 += (TheNeighborGroup.Top != null && TheNeighborGroup.Right != null && TheNeighborGroup.Bottom != null && TheNeighborGroup.Left == null) ? 1 : 0;
- _1100 += (TheNeighborGroup.Top != null && TheNeighborGroup.Right != null && TheNeighborGroup.Bottom == null && TheNeighborGroup.Left == null) ? 1 : 0;
- _0110 += (TheNeighborGroup.Top == null && TheNeighborGroup.Right != null && TheNeighborGroup.Bottom != null && TheNeighborGroup.Left == null) ? 1 : 0;
- _0011 += (TheNeighborGroup.Top == null && TheNeighborGroup.Right == null && TheNeighborGroup.Bottom != null && TheNeighborGroup.Left != null) ? 1 : 0;
- _1001 += (TheNeighborGroup.Top != null && TheNeighborGroup.Right == null && TheNeighborGroup.Bottom == null && TheNeighborGroup.Left != null) ? 1 : 0;
- _1111 += (TheNeighborGroup.Top != null && TheNeighborGroup.Right != null && TheNeighborGroup.Bottom != null && TheNeighborGroup.Left != null) ? 1 : 0;
- }
- }
- /*
- */
- var Test = "";
- Test += "1000: " + _1000 + ", ";
- Test += "0100: " + _0100 + ", ";
- Test += "0010: " + _0010 + ", ";
- Test += "0001: " + _0001 + ", ";
- Test += "1100: " + _1100 + ", ";
- Test += "0110: " + _0110 + ", ";
- Test += "0011: " + _0011 + ", ";
- Test += "1001: " + _1001 + ", ";
- Test += "1111: " + _1111 + "";
- Debug.Log(Test);
- var Minus2 = EdgeCount - 2;
- if (EdgeCount != 1 && ((EdgeCount > 2 && (_1000 != Minus2 || _0100 != Minus2 || _0010 != Minus2 || _0001 != Minus2 || _1111 != Math.Pow(Minus2, 2))) || _1100 != 1 || _0110 != 1 || _0011 != 1 || _1001 != 1))
- {
- Errors += NotSquareMsg;
- }
- if (Errors == "")
- {
- //###################################
- //pre-load heightmap values into arrays
- //to make it easier to flip it horizontally or vertically
- float[] H_Array;
- var V_Array = new float[TheHeightmap.Edge + 1][];
- using (var TheStream = File.OpenRead(TheHeightmap.FilePath))
- {
- using (var TheReader = new BinaryReader(TheStream))
- {
- for (var i = 0; i < V_Array.Length; i++)
- {
- if (i == V_Array.Length - 1)
- {
- V_Array[i] = V_Array[i - 1];
- }
- else
- {
- H_Array = new float[TheHeightmap.Edge + 1];
- for (var t = 0; t < H_Array.Length; t++)
- {
- if (t == H_Array.Length - 1)
- {
- H_Array[t] = H_Array[t - 1];
- }
- else
- {
- if (Use8Bit)
- {
- H_Array[t] = (float)TheReader.ReadByte() / 0xFF;
- }
- else
- {
- if (ReverseBytes)
- {
- H_Array[t] = (float)BitConverter.ToUInt16((byte[])TheReader.ReadBytes(2).Reverse(), 0) / 0xFFFF;
- }
- else
- {
- H_Array[t] = (float)TheReader.ReadUInt16() / 0xFFFF;
- }
- }
- }
- }
- if (FlipX)
- {
- Array.Reverse(H_Array);
- }
- V_Array[i] = H_Array;
- }
- }
- }
- }
- if (FlipZ)
- {
- Array.Reverse(V_Array);
- }
- //###################################
- float v;
- var x = 0;
- var z = 0;
- var RowStartNeighborGroup = NeighborGroupCollection[StartingTerrain];
- var CurrentNeighborGroup = RowStartNeighborGroup;
- for (var VIndex = 0; VIndex < V_Array.Length; VIndex++)
- {
- H_Array = V_Array[VIndex];
- for (var HIndex = 0; HIndex < H_Array.Length; HIndex++)
- {
- v = H_Array[HIndex];
- CurrentNeighborGroup.MainHeights[z, x] = v;
- if (x == LastX && CurrentNeighborGroup.Right != null)
- {
- NeighborGroupCollection[CurrentNeighborGroup.Right].MainHeights[z, 0] = v;
- }
- if (z == LastZ && CurrentNeighborGroup.Top != null)
- {
- NeighborGroupCollection[CurrentNeighborGroup.Top].MainHeights[0, x] = v;
- }
- //####################################
- //increment x and z values
- x++;
- if (x > LastX)
- {
- if (CurrentNeighborGroup.Right != null)
- {
- x = 1;
- CurrentNeighborGroup = NeighborGroupCollection[CurrentNeighborGroup.Right];
- }
- else
- {
- z++;
- x = 0;
- CurrentNeighborGroup = RowStartNeighborGroup;
- if (z > LastZ)
- {
- if (CurrentNeighborGroup.Top != null)
- {
- z = 1;
- RowStartNeighborGroup = CurrentNeighborGroup = NeighborGroupCollection[RowStartNeighborGroup.Top];
- }
- else
- {
- break;
- }
- }
- }
- }
- }
- }
- if (Errors == "")
- {
- foreach (var Item in NeighborGroupCollection)
- {
- Undo.RegisterCompleteObjectUndo(Item.Key.terrainData, "TerraLab apply heightmap");
- Item.Key.terrainData.SetHeights(0, 0, Item.Value.MainHeights);
- }
- }
- }
- }
- }
- }
- }
- private void ResetHeightmap(Terrain[] Terrains, out string Errors)
- {
- Errors = "";
- if (empty(Terrains))
- {
- Errors += "No terrains were provided.";
- }
- else
- {
- foreach (var TheTerrain in Terrains)
- {
- if (TheTerrain == null || TheTerrain.terrainData == null)
- {
- Errors += "The Terrain object has no TerrainData.";
- break;
- }
- }
- if (Errors == "")
- {
- int h, w;
- float[,] TheHeights;
- foreach (var TheTerrain in Terrains)
- {
- h = TheTerrain.terrainData.heightmapHeight;
- w = TheTerrain.terrainData.heightmapWidth;
- TheHeights = TheTerrain.terrainData.GetHeights(0, 0, w, h);
- for (int z = 0; z < h; z++)
- {
- for (int x = 0; x < w; x++)
- {
- TheHeights[z, x] = 0;
- }
- }
- Undo.RegisterCompleteObjectUndo(TheTerrain.terrainData, "TerraLab reset heightmaps");
- TheTerrain.terrainData.SetHeights(0, 0, TheHeights);
- }
- }
- }
- }
- private void ApplyHeightmap(Terrain TheTerrain, string PathToHeightmap, bool ReverseBytes, bool Use8Bit, out string Errors)
- {
- Errors = "";
- PathToHeightmap = PathToHeightmap ?? "";
- if (!File.Exists(PathToHeightmap))
- {
- Errors += "The path to the heightmap is invalid.";
- }
- if (TheTerrain == null || TheTerrain.terrainData == null)
- {
- Errors += "The Terrain object has no TerrainData.";
- }
- if (Errors == "")
- {
- long len;
- float v;
- var h = TheTerrain.terrainData.heightmapHeight;
- var w = TheTerrain.terrainData.heightmapWidth;
- var TheHeights = TheTerrain.terrainData.GetHeights(0, 0, w, h);
- using (var TheStream = File.OpenRead(PathToHeightmap))
- {
- using (var TheReader = new BinaryReader(TheStream))
- {
- len = TheReader.BaseStream.Length;
- if (false)
- {
- for (int z = 0; z < h; z++)
- {
- for (int x = 0; x < w; x++)
- {
- if (x == w - 1 && z == h - 1)
- {
- v = (TheHeights[z, x - 1] + TheHeights[z - 1, x]) / 2;
- }
- else if (x == w - 1)
- {
- v = TheHeights[z, x - 1];
- }
- else if (z == h - 1)
- {
- v = TheHeights[z - 1, x];
- }
- else
- {
- if (TheReader.BaseStream.Position < TheReader.BaseStream.Length)
- {
- if (Use8Bit)
- {
- v = (float)TheReader.ReadByte() / 0xFF;
- }
- else
- {
- if (ReverseBytes)
- {
- v = (float)BitConverter.ToUInt16((byte[])TheReader.ReadBytes(2).Reverse(), 0) / 0xFFFF;
- }
- else
- {
- v = (float)TheReader.ReadUInt16() / 0xFFFF;
- }
- }
- }
- else
- {
- v = 0;
- }
- }
- TheHeights[z, x] = v;
- }
- }
- }
- }
- }
- Debug.Log(len);
- TheTerrain.terrainData.SetHeights(0, 0, TheHeights);
- }
- }
- //##############################################################################
- //##############################################################################
- private static class SmoothPanel
- {
- public static string RadiusStr = "3";
- public static bool IgnoreNeighbors = false;
- public static string SmoothErrors = "";
- }
- private void PaintSmoothPanel()
- {
- TheLayout.BeginVertical();
- if (empty(SelectedTerrains))
- {
- TheLayout.Label("No terrains selected.");
- }
- else
- {
- var Errors = "";
- var TheTerrain = SelectedTerrains[0];
- //var Neighbors = new NeighborGroup(TheTerrain, TerrainsInScene, out string Errors);
- if (Errors != "")
- {
- TheLayout.Label(Errors);
- }
- else
- {
- var Resolution = TheTerrain.terrainData.heightmapResolution - 1;
- var RadiusLimit = (Resolution / 2) - 1;
- if (!int.TryParse(SmoothPanel.RadiusStr, out int Radius) || Radius < 0 || Radius > RadiusLimit)
- {
- Errors += "Radius must be between 0 and half the heightmap resolution minus 1 (the current resolution is " + Resolution + ").\n";
- }
- TheLayout.BeginHorizontal();
- TheLayout.BeginVertical("width:500px;background-color:rgba(0,0,0,0.15);padding:5px;");
- TheLayout.BeginHorizontal();
- TheLayout.Label("Radius:", "width:200px;");
- SmoothPanel.RadiusStr = TheLayout.TextField(SmoothPanel.RadiusStr, "width:100px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Ignore Neighbors:", "width:200px;");
- SmoothPanel.IgnoreNeighbors = TheLayout.Toggle(SmoothPanel.IgnoreNeighbors);
- TheLayout.EndHorizontal();
- GUI.enabled = (Errors == "");
- if (TheLayout.Button("Smooth Selected Terrains", "width:250px;margin-top:5px;"))
- {
- SmoothTerrains(SelectedTerrains, out SmoothPanel.SmoothErrors, Radius, SmoothPanel.IgnoreNeighbors);
- }
- if (SmoothPanel.SmoothErrors != "")
- {
- TheLayout.Label(SmoothPanel.SmoothErrors);
- }
- GUI.enabled = true;
- TheLayout.EndVertical();
- if (Errors != "")
- {
- Errors = Regex.Replace(Errors, "[\\s\\r\\n]*$", "");
- TheLayout.BeginHorizontal("background-color:rgba(255,255,0,0.75);");
- TheLayout.Label(Errors);
- TheLayout.EndHorizontal();
- }
- TheLayout.EndHorizontal();
- }
- }
- TheLayout.EndVertical();
- }
- private void SmoothTerrains(Terrain[] CurrentSelection, out string Errors, int Radius = 5, bool IgnoreNeighbors = false)
- {
- Errors = "";
- var NeighborGroupCollection = new List<NeighborGroup>();
- string NeighborErrors;
- foreach (var TerrainItem in CurrentSelection)
- {
- NeighborGroupCollection.Add(new NeighborGroup(TerrainItem, CurrentSelection, out NeighborErrors));
- if (NeighborErrors != "")
- {
- Errors += NeighborErrors;
- break;
- }
- }
- if (Radius < 0)
- {
- Errors += "Radius cannot be negative.\n";
- }
- if (Errors == "")
- {
- float[,] HeightsTemp;
- var HeightsCollection = new Dictionary<Terrain, float[,]>();
- int HeightMapWidth, HeightMapHeight, LastX, LastZ, x, z;
- foreach (var TheNeighborGroup in NeighborGroupCollection)
- {
- HeightsTemp = (float[,])TheNeighborGroup.MainHeights.Clone();
- HeightMapWidth = TheNeighborGroup.Main.terrainData.heightmapWidth;
- HeightMapHeight = TheNeighborGroup.Main.terrainData.heightmapHeight;
- LastX = HeightMapWidth - 1;
- LastZ = HeightMapHeight - 1;
- //##############################################################
- for (z = 0; z < HeightMapHeight; z++)
- {
- for (x = 0; x < HeightMapWidth; x++)
- {
- HeightsTemp[z, x] = GetAverageHeightValue(TheNeighborGroup, x, z, Radius, IgnoreNeighbors);
- }
- }
- //##############################################################
- HeightsCollection.Add(TheNeighborGroup.Main, HeightsTemp);
- }
- foreach (var Item in HeightsCollection)
- {
- Undo.RegisterCompleteObjectUndo(Item.Key.terrainData, "TerraLab smooth terrains");
- Item.Key.terrainData.SetHeights(0, 0, Item.Value);
- }
- }
- }
- //##############################################################################
- //##############################################################################
- private static class SewPanel
- {
- public static int Method = 0;
- public static string DistanceStr = "4";
- public static string RadiusStr = "4";
- public static string BlendPowerStr = "4";
- public static string SewErrors = "";
- }
- private class NeighborGroup
- {
- public NeighborGroup(Terrain TheTerrain, Terrain[] CurrentSelection, out string Errors)
- {
- Errors = "";
- Main = TheTerrain;
- if (TheTerrain.terrainData == null)
- {
- Errors += "The reference terrain has no TerrainData.\n";
- }
- if (Errors == "")
- {
- var x = TheTerrain.transform.position.x;
- var y = TheTerrain.transform.position.y;
- var z = TheTerrain.transform.position.z;
- var width = TheTerrain.terrainData.size.x;
- var height = TheTerrain.terrainData.size.y;
- var length = TheTerrain.terrainData.size.z;
- var HeightMapWidth = Main.terrainData.heightmapWidth;
- var HeightMapHeight = Main.terrainData.heightmapHeight;
- MainHeights = Main.terrainData.GetHeights(0, 0, HeightMapWidth, HeightMapHeight);
- float itemX, itemY, itemZ, itemWidth, itemHeight, itemLength;
- foreach (var Item in CurrentSelection)
- {
- if (Item.terrainData == null)
- {
- Errors += "One or more selected terrains has no TerrainData.\n";
- break;
- }
- else if (Item.terrainData.heightmapResolution != TheTerrain.terrainData.heightmapResolution)
- {
- Errors += "One or more selected terrains have different heightmap resolutions.\n";
- Errors += "A neighbor scan cannot take place until all the selected terrains have matching heightmap resolutions.\n";
- break;
- }
- else
- {
- itemX = Item.transform.position.x;
- itemY = Item.transform.position.y;
- itemZ = Item.transform.position.z;
- itemWidth = Item.terrainData.size.x;
- itemHeight = Item.terrainData.size.y;
- itemLength = Item.terrainData.size.z;
- if (TopLeft == null && itemY == y && itemHeight == height && (itemX + itemWidth == x && itemZ == z + length))
- {
- TopLeft = Item;
- TopLeftHeights = Item.terrainData.GetHeights(0, 0, HeightMapWidth, HeightMapHeight);
- }
- else if (Top == null && itemY == y && itemHeight == height && (itemX == x && itemZ == z + length))
- {
- Top = Item;
- TopHeights = Item.terrainData.GetHeights(0, 0, HeightMapWidth, HeightMapHeight);
- }
- else if (TopRight == null && itemY == y && itemHeight == height && (itemX == x + width && itemZ == z + length))
- {
- TopRight = Item;
- TopRightHeights = Item.terrainData.GetHeights(0, 0, HeightMapWidth, HeightMapHeight);
- }
- else if (Left == null && itemY == y && itemHeight == height && (itemX + itemWidth == x && itemZ == z))
- {
- Left = Item;
- LeftHeights = Item.terrainData.GetHeights(0, 0, HeightMapWidth, HeightMapHeight);
- }
- else if (Right == null && itemY == y && itemHeight == height && (itemX == x + width && itemZ == z))
- {
- Right = Item;
- RightHeights = Item.terrainData.GetHeights(0, 0, HeightMapWidth, HeightMapHeight);
- }
- else if (BottomLeft == null && itemY == y && itemHeight == height && (itemX + itemWidth == x && itemZ + itemLength == z))
- {
- BottomLeft = Item;
- BottomLeftHeights = Item.terrainData.GetHeights(0, 0, HeightMapWidth, HeightMapHeight);
- }
- else if (Bottom == null && itemY == y && itemHeight == height && (itemX == x && itemZ + itemLength == z))
- {
- Bottom = Item;
- BottomHeights = Item.terrainData.GetHeights(0, 0, HeightMapWidth, HeightMapHeight);
- }
- else if (BottomRight == null && itemY == y && itemHeight == height && (itemX == x + width && itemZ + itemLength == z))
- {
- BottomRight = Item;
- BottomRightHeights = Item.terrainData.GetHeights(0, 0, HeightMapWidth, HeightMapHeight);
- }
- }
- }
- }
- }
- public Terrain Main;
- public Terrain TopLeft;
- public Terrain Top;
- public Terrain TopRight;
- public Terrain Left;
- public Terrain Right;
- public Terrain BottomLeft;
- public Terrain Bottom;
- public Terrain BottomRight;
- public float[,] MainHeights;
- public float[,] TopLeftHeights;
- public float[,] TopHeights;
- public float[,] TopRightHeights;
- public float[,] LeftHeights;
- public float[,] RightHeights;
- public float[,] BottomLeftHeights;
- public float[,] BottomHeights;
- public float[,] BottomRightHeights;
- }
- private void PaintSewPanel()
- {
- TheLayout.BeginVertical();
- //TheLayout.Label("Terrains in scene: " + TerrainsInScene.Length);
- if (empty(SelectedTerrains))
- {
- TheLayout.Label("No terrains selected.");
- }
- else
- {
- var Errors = "";
- var TheTerrain = SelectedTerrains[0];
- //var Neighbors = new NeighborGroup(TheTerrain, TerrainsInScene, out string Errors);
- if (Errors != "")
- {
- TheLayout.Label(Errors);
- }
- else
- {
- /*
- TheLayout.Label("TopLeft: " + ((Neighbors.TopLeft == null) ? "" : "yes"));
- TheLayout.Label("Top: " + ((Neighbors.Top == null) ? "" : "yes"));
- TheLayout.Label("TopRight: " + ((Neighbors.TopRight == null) ? "" : "yes"));
- TheLayout.Label("Left: " + ((Neighbors.Left == null) ? "" : "yes"));
- TheLayout.Label("Right: " + ((Neighbors.Right == null) ? "" : "yes"));
- TheLayout.Label("BottomLeft: " + ((Neighbors.BottomLeft == null) ? "" : "yes"));
- TheLayout.Label("Bottom: " + ((Neighbors.Bottom == null) ? "" : "yes"));
- TheLayout.Label("BottomRight: " + ((Neighbors.BottomRight == null) ? "" : "yes"));
- */
- var UseAveraging = SewPanel.Method == 1;
- var UseSimple = SewPanel.Method == 2;
- var Resolution = TheTerrain.terrainData.heightmapResolution - 1;
- var RadiusLimit = (Resolution / 2) - 1;
- if (!int.TryParse(SewPanel.RadiusStr, out int Radius) || Radius < 0 || Radius > RadiusLimit)
- {
- Errors += "Radius must be between 0 and half the heightmap resolution minus 1 (the current resolution is " + Resolution + ").\n";
- }
- var DistanceLimit = (Resolution / 2) - 1;
- if (!int.TryParse(SewPanel.DistanceStr, out int Distance) || Distance < 0 || Distance > DistanceLimit)
- {
- Errors += "Distance must be between 0 and half the heightmap resolution minus 1 (the current resolution is " + Resolution + ").\n";
- }
- if (!float.TryParse(SewPanel.BlendPowerStr, out float BlendPower) || BlendPower < 0 || BlendPower > 32)
- {
- Errors += "Blend Power must be between 0 and 32.\n";
- }
- TheLayout.BeginHorizontal();
- TheLayout.BeginVertical("width:500px;background-color:rgba(0,0,0,0.15);padding:5px;");
- TheLayout.BeginHorizontal();
- TheLayout.Label("Method:", "width:128px;");
- SewPanel.Method = TheLayout.Toolbar(SewPanel.Method, new[] { "Difference", "Average", "Simple" });
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Radius:", "width:128px;");
- if (SewPanel.Method == 2)
- {
- TheLayout.Label("(no effect when using Simple)");
- }
- else if (SewPanel.Method == 0)
- {
- TheLayout.Label("(no effect when using Difference)");
- }
- else
- {
- SewPanel.RadiusStr = TheLayout.TextField(SewPanel.RadiusStr, "width:100px;");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Distance:", "width:128px;");
- if (SewPanel.Method == 2)
- {
- TheLayout.Label("(no effect when using Simple)");
- }
- else
- {
- SewPanel.DistanceStr = TheLayout.TextField(SewPanel.DistanceStr, "width:100px;");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("Blend Power:", "width:128px;");
- if (SewPanel.Method == 2)
- {
- TheLayout.Label("(no effect when using Simple)");
- }
- else
- {
- SewPanel.BlendPowerStr = TheLayout.TextField(SewPanel.BlendPowerStr, "width:100px;");
- }
- TheLayout.EndHorizontal();
- GUI.enabled = (Errors == "");
- if (TheLayout.Button("Sew Selected Terrains", "width:200px;margin-top:5px;"))
- {
- SewTerrains(SelectedTerrains, out SewPanel.SewErrors, UseAveraging, UseSimple ? 0 : Radius, UseSimple ? 0 : Distance, BlendPower);
- }
- if (SewPanel.SewErrors != "")
- {
- TheLayout.Label(SewPanel.SewErrors);
- }
- GUI.enabled = true;
- TheLayout.EndVertical();
- if (Errors != "")
- {
- Errors = Regex.Replace(Errors, "[\\s\\r\\n]*$", "");
- TheLayout.BeginHorizontal("background-color:rgba(255,255,0,0.75);");
- TheLayout.Label(Errors);
- TheLayout.EndHorizontal();
- }
- TheLayout.EndHorizontal();
- }
- }
- TheLayout.EndVertical();
- }
- private void SewTerrains(Terrain[] CurrentSelection, out string Errors, bool UseAverage = false, int Radius = 5, int Distance = 5, float BlendPower = 4)
- {
- Errors = "";
- var NeighborGroupCollection = new List<NeighborGroup>();
- string NeighborErrors;
- foreach (var TerrainItem in CurrentSelection)
- {
- NeighborGroupCollection.Add(new NeighborGroup(TerrainItem, CurrentSelection, out NeighborErrors));
- if (NeighborErrors != "")
- {
- Errors += NeighborErrors;
- break;
- }
- }
- if (Radius < 0)
- {
- Errors += "Radius cannot be negative.\n";
- }
- if (BlendPower < 0 || BlendPower > 16)
- {
- Errors += "Blend Power must be between 0 and 16.\n";
- }
- if (Errors == "")
- {
- //Tier 0 = full weight
- Radius = UseAverage ? Radius : Distance;
- float Tier;
- float[,] HeightsTemp;
- string CornerBlendKey;
- float[] CornerBlendVal;
- float[] SeamHeights = null;
- bool SharpSmoothing = true;
- Dictionary<string, float[]> CornerBlend;
- float OriginalHeight, Weight, WeightedAverage;
- int HeightMapWidth, HeightMapHeight, LastX, LastZ, x, z;
- foreach (var TheNeighborGroup in NeighborGroupCollection)
- {
- HeightsTemp = (float[,])TheNeighborGroup.MainHeights.Clone();
- HeightMapWidth = TheNeighborGroup.Main.terrainData.heightmapWidth;
- HeightMapHeight = TheNeighborGroup.Main.terrainData.heightmapHeight;
- LastX = HeightMapWidth - 1;
- LastZ = HeightMapHeight - 1;
- CornerBlend = new Dictionary<string, float[]>();
- //##############################################################
- //BottomLeft
- if (TheNeighborGroup.BottomLeft != null)
- {
- for (z = 0; z < Distance + 1; z++)
- {
- for (x = 0; x < Distance + 1; x++)
- {
- Tier = (float)Math.Sqrt(Math.Pow(x, 2) + Math.Pow(z, 2));
- Weight = Math.Max(0, ((Distance - Tier) + 1) / (Distance + 1));
- OriginalHeight = TheNeighborGroup.MainHeights[z, x];
- HeightsTemp[z, x] = OriginalHeight + ((GetAverageHeightValue(TheNeighborGroup, x, z, Radius) - OriginalHeight) * Weight);
- }
- }
- }
- //BottomRight
- if (TheNeighborGroup.BottomRight != null)
- {
- for (z = 0; z < Distance + 1; z++)
- {
- for (x = LastX - Distance; x < HeightMapWidth; x++)
- {
- Tier = (float)Math.Sqrt(Math.Pow(LastX - x, 2) + Math.Pow(z, 2));
- Weight = Math.Max(0, ((Distance - Tier) + 1) / (Distance + 1));
- OriginalHeight = TheNeighborGroup.MainHeights[z, x];
- HeightsTemp[z, x] = OriginalHeight + ((GetAverageHeightValue(TheNeighborGroup, x, z, Radius) - OriginalHeight) * Weight);
- }
- }
- }
- //TopLeft
- if (TheNeighborGroup.TopLeft != null)
- {
- for (z = LastZ - Distance; z < HeightMapHeight; z++)
- {
- for (x = 0; x < Distance + 1; x++)
- {
- Tier = (float)Math.Sqrt(Math.Pow(x, 2) + Math.Pow(LastZ - z, 2));
- Weight = Math.Max(0, ((Distance - Tier) + 1) / (Distance + 1));
- OriginalHeight = TheNeighborGroup.MainHeights[z, x];
- HeightsTemp[z, x] = OriginalHeight + ((GetAverageHeightValue(TheNeighborGroup, x, z, Radius) - OriginalHeight) * Weight);
- }
- }
- }
- //TopRight
- if (TheNeighborGroup.TopRight != null)
- {
- for (z = LastZ - Distance; z < HeightMapHeight; z++)
- {
- for (x = LastX - Distance; x < HeightMapWidth; x++)
- {
- Tier = (float)Math.Sqrt(Math.Pow(LastX - x, 2) + Math.Pow(LastZ - z, 2));
- Weight = Math.Max(0, ((Distance - Tier) + 1) / (Distance + 1));
- OriginalHeight = TheNeighborGroup.MainHeights[z, x];
- HeightsTemp[z, x] = OriginalHeight + ((GetAverageHeightValue(TheNeighborGroup, x, z, Radius) - OriginalHeight) * Weight);
- }
- }
- }
- //##############################################################
- //Top
- if (TheNeighborGroup.Top != null)
- {
- if (!UseAverage)
- {
- SeamHeights = new float[HeightMapWidth];
- for (x = 0; x < HeightMapWidth; x++)
- {
- SeamHeights[x] = GetAverageHeightValue(TheNeighborGroup, x, LastZ, 0);
- }
- }
- for (z = LastZ - Distance; z < HeightMapHeight; z++)
- {
- for (x = 0; x < HeightMapWidth; x++)
- {
- Tier = LastZ - z;
- if (UseAverage)
- {
- if (TheNeighborGroup.Left != null && x < Tier)
- {
- Tier = x;
- }
- else if (TheNeighborGroup.Right != null && LastX - x < Tier)
- {
- Tier = LastX - x;
- }
- }
- Weight = SharpSmoothing ? ((Distance - Tier) + 1) / (Distance + 1) : Math.Min(((Distance - Tier) + 1) / Distance, 1);
- Weight = (float)Math.Pow(Weight, BlendPower);
- OriginalHeight = TheNeighborGroup.MainHeights[z, x];
- if (UseAverage)
- {
- HeightsTemp[z, x] = OriginalHeight + ((GetAverageHeightValue(TheNeighborGroup, x, z, Radius) - OriginalHeight) * Weight);
- }
- else
- {
- if (z == LastZ)
- {
- HeightsTemp[z, x] = SeamHeights[x];
- }
- else if ((x > 0 && x < LastX) || (TheNeighborGroup.Left == null && x == 0) || (TheNeighborGroup.Right == null && x == LastX))
- {
- HeightsTemp[z, x] = OriginalHeight + ((SeamHeights[x] - OriginalHeight) * Weight);
- }
- if (z < LastZ && ((x > 0 && x < Distance + 1 && TheNeighborGroup.Left != null) || (x > LastX - (Distance + 1) && x < LastX && TheNeighborGroup.Right != null)))
- {
- CornerBlendKey = z + "," + x;
- if (CornerBlend.TryGetValue(CornerBlendKey, out CornerBlendVal))
- {
- WeightedAverage = ((HeightsTemp[z, x] * Weight) + (CornerBlendVal[0] * CornerBlendVal[1])) / (Weight + CornerBlendVal[1]);
- CornerBlend[CornerBlendKey] = new[] { WeightedAverage };
- }
- else
- {
- CornerBlend.Add(CornerBlendKey, new[] { HeightsTemp[z, x], Weight });
- }
- }
- }
- }
- }
- }
- //##############################################################
- //Bottom
- if (TheNeighborGroup.Bottom != null)
- {
- if (!UseAverage)
- {
- SeamHeights = new float[HeightMapWidth];
- for (x = 0; x < HeightMapWidth; x++)
- {
- SeamHeights[x] = GetAverageHeightValue(TheNeighborGroup, x, 0, 0);
- }
- }
- for (z = 0; z < Distance + 1; z++)
- {
- for (x = 0; x < HeightMapWidth; x++)
- {
- Tier = z;
- if (UseAverage)
- {
- if (TheNeighborGroup.Left != null && x < Tier)
- {
- Tier = x;
- }
- else if (TheNeighborGroup.Right != null && LastX - x < Tier)
- {
- Tier = LastX - x;
- }
- }
- Weight = SharpSmoothing ? ((Distance - Tier) + 1) / (Distance + 1) : Math.Min(((Distance - Tier) + 1) / Distance, 1);
- Weight = (float)Math.Pow(Weight, BlendPower);
- OriginalHeight = TheNeighborGroup.MainHeights[z, x];
- if (UseAverage)
- {
- HeightsTemp[z, x] = OriginalHeight + ((GetAverageHeightValue(TheNeighborGroup, x, z, Radius) - OriginalHeight) * Weight);
- }
- else
- {
- if (z == 0)
- {
- HeightsTemp[z, x] = SeamHeights[x];
- }
- else if ((x > 0 && x < LastX) || (TheNeighborGroup.Left == null && x == 0) || (TheNeighborGroup.Right == null && x == LastX))
- {
- HeightsTemp[z, x] = OriginalHeight + ((SeamHeights[x] - OriginalHeight) * Weight);
- }
- if (z > 0 && ((x > 0 && x < Distance + 1 && TheNeighborGroup.Left != null) || (x > LastX - (Distance + 1) && x < LastX && TheNeighborGroup.Right != null)))
- {
- CornerBlendKey = z + "," + x;
- if (CornerBlend.TryGetValue(CornerBlendKey, out CornerBlendVal))
- {
- WeightedAverage = ((HeightsTemp[z, x] * Weight) + (CornerBlendVal[0] * CornerBlendVal[1])) / (Weight + CornerBlendVal[1]);
- CornerBlend[CornerBlendKey] = new[] { WeightedAverage };
- }
- else
- {
- CornerBlend.Add(CornerBlendKey, new[] { HeightsTemp[z, x], Weight });
- }
- }
- }
- }
- }
- }
- //##############################################################
- //Left
- if (TheNeighborGroup.Left != null)
- {
- if (!UseAverage)
- {
- SeamHeights = new float[HeightMapHeight];
- for (z = 0; z < HeightMapHeight; z++)
- {
- SeamHeights[z] = GetAverageHeightValue(TheNeighborGroup, 0, z, 0);
- }
- }
- for (x = 0; x < Distance + 1; x++)
- {
- for (z = 0; z < HeightMapHeight; z++)
- {
- Tier = x;
- if (UseAverage)
- {
- if (TheNeighborGroup.Top != null && LastZ - z < Tier)
- {
- Tier = LastZ - z;
- }
- else if (TheNeighborGroup.Bottom != null && z < Tier)
- {
- Tier = z;
- }
- }
- Weight = SharpSmoothing ? ((Distance - Tier) + 1) / (Distance + 1) : Math.Min(((Distance - Tier) + 1) / Distance, 1);
- Weight = (float)Math.Pow(Weight, BlendPower);
- OriginalHeight = TheNeighborGroup.MainHeights[z, x];
- if (UseAverage)
- {
- HeightsTemp[z, x] = OriginalHeight + ((GetAverageHeightValue(TheNeighborGroup, x, z, Radius) - OriginalHeight) * Weight);
- }
- else
- {
- if (x == 0)
- {
- HeightsTemp[z, x] = SeamHeights[z];
- }
- else if ((z > 0 && z < LastZ) || (TheNeighborGroup.Top == null && z == LastZ) || (TheNeighborGroup.Bottom == null && z == 0))
- {
- HeightsTemp[z, x] = OriginalHeight + ((SeamHeights[z] - OriginalHeight) * Weight);
- }
- if (x > 0 && ((z > 0 && z < Distance + 1 && TheNeighborGroup.Bottom != null) || (z > LastZ - (Distance + 1) && z < LastZ && TheNeighborGroup.Top != null)))
- {
- CornerBlendKey = z + "," + x;
- if (CornerBlend.TryGetValue(CornerBlendKey, out CornerBlendVal))
- {
- WeightedAverage = ((HeightsTemp[z, x] * Weight) + (CornerBlendVal[0] * CornerBlendVal[1])) / (Weight + CornerBlendVal[1]);
- CornerBlend[CornerBlendKey] = new[] { WeightedAverage };
- }
- else
- {
- CornerBlend.Add(CornerBlendKey, new[] { HeightsTemp[z, x], Weight });
- }
- }
- }
- }
- }
- }
- //##############################################################
- //Right
- if (TheNeighborGroup.Right != null)
- {
- if (!UseAverage)
- {
- SeamHeights = new float[HeightMapHeight];
- for (z = 0; z < HeightMapHeight; z++)
- {
- SeamHeights[z] = GetAverageHeightValue(TheNeighborGroup, LastX, z, 0);
- }
- }
- for (x = LastX - Distance; x < HeightMapWidth; x++)
- {
- for (z = 0; z < HeightMapHeight; z++)
- {
- Tier = LastX - x;
- if (UseAverage)
- {
- if (TheNeighborGroup.Top != null && LastZ - z < Tier)
- {
- Tier = LastZ - z;
- }
- else if (TheNeighborGroup.Bottom != null && z < Tier)
- {
- Tier = z;
- }
- }
- Weight = SharpSmoothing ? ((Distance - Tier) + 1) / (Distance + 1) : Math.Min(((Distance - Tier) + 1) / Distance, 1);
- Weight = (float)Math.Pow(Weight, BlendPower);
- OriginalHeight = TheNeighborGroup.MainHeights[z, x];
- if (UseAverage)
- {
- HeightsTemp[z, x] = OriginalHeight + ((GetAverageHeightValue(TheNeighborGroup, x, z, Radius) - OriginalHeight) * Weight);
- }
- else
- {
- if (x == LastX)
- {
- HeightsTemp[z, x] = SeamHeights[z];
- }
- else if ((z > 0 && z < LastZ) || (TheNeighborGroup.Top == null && z == LastZ) || (TheNeighborGroup.Bottom == null && z == 0))
- {
- HeightsTemp[z, x] = OriginalHeight + ((SeamHeights[z] - OriginalHeight) * Weight);
- }
- if (x < LastX && ((z > 0 && z < Distance + 1 && TheNeighborGroup.Bottom != null) || (z > LastZ - (Distance + 1) && z < LastZ && TheNeighborGroup.Top != null)))
- {
- CornerBlendKey = z + "," + x;
- if (CornerBlend.TryGetValue(CornerBlendKey, out CornerBlendVal))
- {
- WeightedAverage = ((HeightsTemp[z, x] * Weight) + (CornerBlendVal[0] * CornerBlendVal[1])) / (Weight + CornerBlendVal[1]);
- CornerBlend[CornerBlendKey] = new[] { WeightedAverage };
- }
- else
- {
- CornerBlend.Add(CornerBlendKey, new[] { HeightsTemp[z, x], Weight });
- }
- }
- }
- }
- }
- }
- //##############################################################
- if (!UseAverage)
- {
- foreach (var Item in CornerBlend)
- {
- HeightsTemp[int.Parse(Regex.Replace(Item.Key, ",.*", "")), int.Parse(Regex.Replace(Item.Key, ".*,", ""))] = Item.Value[0];
- }
- }
- //##############################################################
- Undo.RecordObject(TheNeighborGroup.Main.terrainData, "TerraLab sew terrains");
- TheNeighborGroup.Main.terrainData.SetHeights(0, 0, HeightsTemp);
- }
- }
- }
- private float GetAverageHeightValue(NeighborGroup TheNeighborGroup, int x, int z, int Radius, bool IgnoreNeighbors = false)
- {
- //--- --- --- --- --- --- x-- -x- --x
- //--- -> --- -> --- -> x-- -> -x- -> --x -> --- -> --- -> ---
- //x-- -x- --x --- --- --- --- --- ---
- var LastX = TheNeighborGroup.Main.terrainData.heightmapWidth - 1;
- var LastZ = TheNeighborGroup.Main.terrainData.heightmapHeight - 1;
- float Average, Value, ExactPointCount, AverageCount, Sum;
- bool ValueExists;
- Sum = 0;
- AverageCount = 0;
- for (var RadZ = z - Radius; RadZ < z + Radius + 1; RadZ++)
- {
- for (var RadX = x - Radius; RadX < x + Radius + 1; RadX++)
- {
- Value = 0;
- ValueExists = false;
- if (IgnoreNeighbors)
- {
- if (RadX >= 0 && RadX <= LastX && RadZ >= 0 && RadZ <= LastZ)
- {
- ValueExists = true;
- Value = TheNeighborGroup.MainHeights[RadZ, RadX];
- }
- }
- else
- {
- if (RadX < 0 && RadZ > LastZ)
- {
- //TopLeft Neighbor
- if (TheNeighborGroup.TopLeft != null)
- {
- ValueExists = true;
- Value = TheNeighborGroup.TopLeftHeights[RadZ - LastZ, LastX + RadX];
- }
- }
- else if (RadX > LastX && RadZ > LastZ)
- {
- //TopRight Neighbor
- if (TheNeighborGroup.TopRight != null)
- {
- ValueExists = true;
- Value = TheNeighborGroup.TopRightHeights[RadZ - LastZ, RadX - LastX];
- }
- }
- else if (RadX < 0 && RadZ < 0)
- {
- //BottomLeft Neighbor
- if (TheNeighborGroup.BottomLeft != null)
- {
- ValueExists = true;
- Value = TheNeighborGroup.BottomLeftHeights[LastZ + RadZ, LastX + RadX];
- }
- }
- else if (RadX > LastX && RadZ < 0)
- {
- //BottomRight Neighbor
- if (TheNeighborGroup.BottomRight != null)
- {
- ValueExists = true;
- Value = TheNeighborGroup.BottomRightHeights[LastZ + RadZ, RadX - LastX];
- }
- }
- else
- {
- ExactPointCount = 0;
- if (RadZ > LastZ)
- {
- //Top Neighbor
- if (TheNeighborGroup.Top != null)
- {
- ValueExists = true;
- Value += TheNeighborGroup.TopHeights[RadZ - LastZ, RadX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.TopLeft != null && RadX == 0)
- {
- ValueExists = true;
- Value += TheNeighborGroup.TopLeftHeights[RadZ - LastZ, LastX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.TopRight != null && RadX == LastX)
- {
- ValueExists = true;
- Value += TheNeighborGroup.TopRightHeights[RadZ - LastZ, 0];
- ExactPointCount++;
- }
- }
- else if (RadZ < 0)
- {
- //Bottom Neighbor
- if (TheNeighborGroup.Bottom != null)
- {
- ValueExists = true;
- Value += TheNeighborGroup.BottomHeights[LastZ + RadZ, RadX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.BottomLeft != null && RadX == 0)
- {
- ValueExists = true;
- Value += TheNeighborGroup.BottomLeftHeights[LastZ + RadZ, LastX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.BottomRight != null && RadX == LastX)
- {
- ValueExists = true;
- Value += TheNeighborGroup.BottomRightHeights[LastZ + RadZ, 0];
- ExactPointCount++;
- }
- }
- else if (RadX < 0)
- {
- //Left Neighbor
- if (TheNeighborGroup.Left != null)
- {
- ValueExists = true;
- Value += TheNeighborGroup.LeftHeights[RadZ, LastX + RadX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.TopLeft != null && RadZ == LastZ)
- {
- ValueExists = true;
- Value += TheNeighborGroup.TopLeftHeights[0, LastX + RadX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.BottomLeft != null && RadZ == 0)
- {
- ValueExists = true;
- Value += TheNeighborGroup.BottomLeftHeights[LastZ, LastX + RadX];
- ExactPointCount++;
- }
- }
- else if (RadX > LastX)
- {
- //Right Neighbor
- if (TheNeighborGroup.Right != null)
- {
- ValueExists = true;
- Value += TheNeighborGroup.RightHeights[RadZ, RadX - LastX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.TopRight != null && RadZ == LastZ)
- {
- ValueExists = true;
- Value += TheNeighborGroup.TopRightHeights[0, RadX - LastX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.BottomRight != null && RadZ == 0)
- {
- ValueExists = true;
- Value += TheNeighborGroup.BottomRightHeights[LastZ, RadX - LastX];
- ExactPointCount++;
- }
- }
- else
- {
- //point is inside the terrain
- ValueExists = true;
- ExactPointCount = 1;
- Value = TheNeighborGroup.MainHeights[RadZ, RadX];
- if (RadX == 0 && RadZ == LastZ)
- {
- //TopLeft Exact
- if (TheNeighborGroup.Left != null)
- {
- Value += TheNeighborGroup.LeftHeights[LastZ, LastX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.TopLeft != null)
- {
- Value += TheNeighborGroup.TopLeftHeights[0, LastX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.Top != null)
- {
- Value += TheNeighborGroup.TopHeights[0, 0];
- ExactPointCount++;
- }
- }
- else if (RadX == LastX && RadZ == LastZ)
- {
- //TopRight Exact
- if (TheNeighborGroup.Top != null)
- {
- Value += TheNeighborGroup.TopHeights[0, LastX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.TopRight != null)
- {
- Value += TheNeighborGroup.TopRightHeights[0, 0];
- ExactPointCount++;
- }
- if (TheNeighborGroup.Right != null)
- {
- Value += TheNeighborGroup.RightHeights[LastZ, 0];
- ExactPointCount++;
- }
- }
- else if (RadX == 0 && RadZ == 0)
- {
- //BottomLeft Exact
- if (TheNeighborGroup.Bottom != null)
- {
- Value += TheNeighborGroup.BottomHeights[LastZ, 0];
- ExactPointCount++;
- }
- if (TheNeighborGroup.BottomLeft != null)
- {
- Value += TheNeighborGroup.BottomLeftHeights[LastZ, LastX];
- ExactPointCount++;
- }
- if (TheNeighborGroup.Left != null)
- {
- Value += TheNeighborGroup.LeftHeights[0, LastX];
- ExactPointCount++;
- }
- }
- else if (RadX == LastX && RadZ == 0)
- {
- //BottomRight Exact
- if (TheNeighborGroup.Right != null)
- {
- Value += TheNeighborGroup.RightHeights[0, 0];
- ExactPointCount++;
- }
- if (TheNeighborGroup.BottomRight != null)
- {
- Value += TheNeighborGroup.BottomRightHeights[LastZ, 0];
- ExactPointCount++;
- }
- if (TheNeighborGroup.Bottom != null)
- {
- Value += TheNeighborGroup.BottomHeights[LastZ, LastX];
- ExactPointCount++;
- }
- }
- else if (RadZ == LastZ)
- {
- //Top Exact
- if (TheNeighborGroup.Top != null)
- {
- Value += TheNeighborGroup.TopHeights[0, RadX];
- ExactPointCount++;
- }
- }
- else if (RadZ == 0)
- {
- //Bottom Exact
- if (TheNeighborGroup.Bottom != null)
- {
- Value += TheNeighborGroup.BottomHeights[LastZ, RadX];
- ExactPointCount++;
- }
- }
- else if (RadX == 0)
- {
- //Left Exact
- if (TheNeighborGroup.Left != null)
- {
- Value += TheNeighborGroup.LeftHeights[RadZ, LastX];
- ExactPointCount++;
- }
- }
- else if (RadX == LastX)
- {
- //Right Exact
- if (TheNeighborGroup.Right != null)
- {
- Value += TheNeighborGroup.RightHeights[RadZ, 0];
- ExactPointCount++;
- }
- }
- }
- Value = Value / ExactPointCount;
- }
- }
- if (ValueExists)
- {
- Sum += Value;
- AverageCount++;
- }
- }
- }
- Average = Sum / AverageCount;
- return Average;
- }
- //##############################################################################
- //##############################################################################
- private static class LayersPanel
- {
- public static string[] PaintString = null;
- public static string[] LayerPaintErrors = null;
- public static Vector2 ScrollVector = new Vector2(0, 0);
- public static int alphamapWidth;
- public static int alphamapHeight;
- public static int heightmapWidth;
- public static int heightmapHeight;
- public static bool Different_alphamapWidth;
- public static bool Different_alphamapHeight;
- public static bool Different_heightmapWidth;
- public static bool Different_heightmapHeight;
- //####################################
- public static TerrainLayer[][] LayerGroups = null;
- public static string[] LayerEditErrors = null;
- public static string[] nameStr = null;
- public static Texture2D[] diffuseTexture = null;
- public static Texture2D[] maskMapTexture = null;
- public static Texture2D[] normalMapTexture = null;
- public static string[] metallicStr = null;
- public static string[] smoothnessStr = null;
- public static string[] tileOffsetXStr = null;
- public static string[] tileOffsetYStr = null;
- public static string[] tileSizeXStr = null;
- public static string[] tileSizeYStr = null;
- public static string[] diffuseRemapMaxWStr = null;
- public static string[] diffuseRemapMaxXStr = null;
- public static string[] diffuseRemapMaxYStr = null;
- public static string[] diffuseRemapMaxZStr = null;
- public static string[] diffuseRemapMinWStr = null;
- public static string[] diffuseRemapMinXStr = null;
- public static string[] diffuseRemapMinYStr = null;
- public static string[] diffuseRemapMinZStr = null;
- public static string[] maskMapRemapMaxWStr = null;
- public static string[] maskMapRemapMaxXStr = null;
- public static string[] maskMapRemapMaxYStr = null;
- public static string[] maskMapRemapMaxZStr = null;
- public static string[] maskMapRemapMinWStr = null;
- public static string[] maskMapRemapMinXStr = null;
- public static string[] maskMapRemapMinYStr = null;
- public static string[] maskMapRemapMinZStr = null;
- public static string[] normalScaleStr = null;
- public static string[] specularRStr = null;
- public static string[] specularGStr = null;
- public static string[] specularBStr = null;
- public static string[] specularAStr = null;
- //####################################
- public static bool[] NullLayerExists;
- public static bool[] Different_name;
- public static bool[] Different_diffuseTexture;
- public static bool[] Different_maskMapTexture;
- public static bool[] Different_normalMapTexture;
- public static bool[] Different_metallic;
- public static bool[] Different_smoothness;
- public static bool[] Different_tileOffsetX;
- public static bool[] Different_tileOffsetY;
- public static bool[] Different_tileSizeX;
- public static bool[] Different_tileSizeY;
- public static bool[] Different_diffuseRemapMaxW;
- public static bool[] Different_diffuseRemapMaxX;
- public static bool[] Different_diffuseRemapMaxY;
- public static bool[] Different_diffuseRemapMaxZ;
- public static bool[] Different_diffuseRemapMinW;
- public static bool[] Different_diffuseRemapMinX;
- public static bool[] Different_diffuseRemapMinY;
- public static bool[] Different_diffuseRemapMinZ;
- public static bool[] Different_maskMapRemapMaxW;
- public static bool[] Different_maskMapRemapMaxX;
- public static bool[] Different_maskMapRemapMaxY;
- public static bool[] Different_maskMapRemapMaxZ;
- public static bool[] Different_maskMapRemapMinW;
- public static bool[] Different_maskMapRemapMinX;
- public static bool[] Different_maskMapRemapMinY;
- public static bool[] Different_maskMapRemapMinZ;
- public static bool[] Different_normalScale;
- public static bool[] Different_specularR;
- public static bool[] Different_specularG;
- public static bool[] Different_specularB;
- public static bool[] Different_specularA;
- //####################################
- }
- private void RefreshLayersPanel(Terrain[] Terrains)
- {
- if (!SelectedLayerCountsAreDifferent && Terrains.Length > 0)
- {
- List<TerrainLayer> LayerGroup;
- TerrainLayer TheLayer, LastLayer;
- var FirstTerrain = Terrains[0];
- var LayerCount = empty(FirstTerrain.terrainData.terrainLayers) ? 0 : FirstTerrain.terrainData.terrainLayers.Length;
- if (LayersPanel.PaintString == null || LayersPanel.PaintString.Length < LayerCount)
- {
- Array.Resize(ref LayersPanel.PaintString, LayerCount);
- }
- if (LayersPanel.LayerPaintErrors == null || LayersPanel.LayerPaintErrors.Length < LayerCount)
- {
- Array.Resize(ref LayersPanel.LayerPaintErrors, LayerCount);
- }
- //########################################################
- LayersPanel.alphamapWidth = 0;
- LayersPanel.alphamapHeight = 0;
- LayersPanel.heightmapWidth = 0;
- LayersPanel.heightmapHeight = 0;
- LayersPanel.Different_alphamapWidth = false;
- LayersPanel.Different_alphamapHeight = false;
- LayersPanel.Different_heightmapWidth = false;
- LayersPanel.Different_heightmapHeight = false;
- //########################################################
- TerrainData TheData;
- TerrainData LastData = null;
- var c = 0;
- foreach (var TerrainComponent in Terrains)
- {
- TheData = TerrainComponent.terrainData;
- if (c == 0)
- {
- LastData = TheData;
- }
- //###############
- LayersPanel.Different_alphamapWidth = (TheData.alphamapWidth != LastData.alphamapWidth) ? true : LayersPanel.Different_alphamapWidth;
- LayersPanel.Different_alphamapHeight = (TheData.alphamapHeight != LastData.alphamapHeight) ? true : LayersPanel.Different_alphamapHeight;
- LayersPanel.Different_heightmapWidth = (TheData.heightmapWidth != LastData.heightmapWidth) ? true : LayersPanel.Different_heightmapWidth;
- LayersPanel.Different_heightmapHeight = (TheData.heightmapHeight != LastData.heightmapHeight) ? true : LayersPanel.Different_heightmapHeight;
- //###############
- LayersPanel.alphamapWidth = LayersPanel.Different_alphamapWidth ? 0 : TheData.alphamapWidth;
- LayersPanel.alphamapHeight = LayersPanel.Different_alphamapHeight ? 0 : TheData.alphamapHeight;
- LayersPanel.heightmapWidth = LayersPanel.Different_heightmapWidth ? 0 : TheData.heightmapWidth;
- LayersPanel.heightmapHeight = LayersPanel.Different_heightmapHeight ? 0 : TheData.heightmapHeight;
- //###############
- LastData = TheData;
- c++;
- }
- //########################################################
- LayersPanel.LayerGroups = new TerrainLayer[LayerCount][];
- LayersPanel.LayerEditErrors = new string[LayerCount];
- LayersPanel.nameStr = new string[LayerCount];
- LayersPanel.diffuseTexture = new Texture2D[LayerCount];
- LayersPanel.maskMapTexture = new Texture2D[LayerCount];
- LayersPanel.normalMapTexture = new Texture2D[LayerCount];
- LayersPanel.metallicStr = new string[LayerCount];
- LayersPanel.smoothnessStr = new string[LayerCount];
- LayersPanel.tileOffsetXStr = new string[LayerCount];
- LayersPanel.tileOffsetYStr = new string[LayerCount];
- LayersPanel.tileSizeXStr = new string[LayerCount];
- LayersPanel.tileSizeYStr = new string[LayerCount];
- LayersPanel.diffuseRemapMaxWStr = new string[LayerCount];
- LayersPanel.diffuseRemapMaxXStr = new string[LayerCount];
- LayersPanel.diffuseRemapMaxYStr = new string[LayerCount];
- LayersPanel.diffuseRemapMaxZStr = new string[LayerCount];
- LayersPanel.diffuseRemapMinWStr = new string[LayerCount];
- LayersPanel.diffuseRemapMinXStr = new string[LayerCount];
- LayersPanel.diffuseRemapMinYStr = new string[LayerCount];
- LayersPanel.diffuseRemapMinZStr = new string[LayerCount];
- LayersPanel.maskMapRemapMaxWStr = new string[LayerCount];
- LayersPanel.maskMapRemapMaxXStr = new string[LayerCount];
- LayersPanel.maskMapRemapMaxYStr = new string[LayerCount];
- LayersPanel.maskMapRemapMaxZStr = new string[LayerCount];
- LayersPanel.maskMapRemapMinWStr = new string[LayerCount];
- LayersPanel.maskMapRemapMinXStr = new string[LayerCount];
- LayersPanel.maskMapRemapMinYStr = new string[LayerCount];
- LayersPanel.maskMapRemapMinZStr = new string[LayerCount];
- LayersPanel.normalScaleStr = new string[LayerCount];
- LayersPanel.specularRStr = new string[LayerCount];
- LayersPanel.specularGStr = new string[LayerCount];
- LayersPanel.specularBStr = new string[LayerCount];
- LayersPanel.specularAStr = new string[LayerCount];
- //########################################################
- LayersPanel.NullLayerExists = new bool[LayerCount];
- LayersPanel.Different_name = new bool[LayerCount];
- LayersPanel.Different_diffuseTexture = new bool[LayerCount];
- LayersPanel.Different_maskMapTexture = new bool[LayerCount];
- LayersPanel.Different_normalMapTexture = new bool[LayerCount];
- LayersPanel.Different_metallic = new bool[LayerCount];
- LayersPanel.Different_smoothness = new bool[LayerCount];
- LayersPanel.Different_tileOffsetX = new bool[LayerCount];
- LayersPanel.Different_tileOffsetY = new bool[LayerCount];
- LayersPanel.Different_tileSizeX = new bool[LayerCount];
- LayersPanel.Different_tileSizeY = new bool[LayerCount];
- LayersPanel.Different_diffuseRemapMaxW = new bool[LayerCount];
- LayersPanel.Different_diffuseRemapMaxX = new bool[LayerCount];
- LayersPanel.Different_diffuseRemapMaxY = new bool[LayerCount];
- LayersPanel.Different_diffuseRemapMaxZ = new bool[LayerCount];
- LayersPanel.Different_diffuseRemapMinW = new bool[LayerCount];
- LayersPanel.Different_diffuseRemapMinX = new bool[LayerCount];
- LayersPanel.Different_diffuseRemapMinY = new bool[LayerCount];
- LayersPanel.Different_diffuseRemapMinZ = new bool[LayerCount];
- LayersPanel.Different_maskMapRemapMaxW = new bool[LayerCount];
- LayersPanel.Different_maskMapRemapMaxX = new bool[LayerCount];
- LayersPanel.Different_maskMapRemapMaxY = new bool[LayerCount];
- LayersPanel.Different_maskMapRemapMaxZ = new bool[LayerCount];
- LayersPanel.Different_maskMapRemapMinW = new bool[LayerCount];
- LayersPanel.Different_maskMapRemapMinX = new bool[LayerCount];
- LayersPanel.Different_maskMapRemapMinY = new bool[LayerCount];
- LayersPanel.Different_maskMapRemapMinZ = new bool[LayerCount];
- LayersPanel.Different_normalScale = new bool[LayerCount];
- LayersPanel.Different_specularR = new bool[LayerCount];
- LayersPanel.Different_specularG = new bool[LayerCount];
- LayersPanel.Different_specularB = new bool[LayerCount];
- LayersPanel.Different_specularA = new bool[LayerCount];
- for (var i = 0; i < LayerCount; i++)
- {
- c = 0;
- TheLayer = null;
- LastLayer = null;
- LayerGroup = new List<TerrainLayer>();
- //########################################################
- LayersPanel.NullLayerExists[i] = false;
- LayersPanel.Different_name[i] = false;
- LayersPanel.Different_diffuseTexture[i] = false;
- LayersPanel.Different_maskMapTexture[i] = false;
- LayersPanel.Different_normalMapTexture[i] = false;
- LayersPanel.Different_metallic[i] = false;
- LayersPanel.Different_smoothness[i] = false;
- LayersPanel.Different_tileOffsetX[i] = false;
- LayersPanel.Different_tileOffsetY[i] = false;
- LayersPanel.Different_tileSizeX[i] = false;
- LayersPanel.Different_tileSizeY[i] = false;
- LayersPanel.Different_diffuseRemapMaxW[i] = false;
- LayersPanel.Different_diffuseRemapMaxX[i] = false;
- LayersPanel.Different_diffuseRemapMaxY[i] = false;
- LayersPanel.Different_diffuseRemapMaxZ[i] = false;
- LayersPanel.Different_diffuseRemapMinW[i] = false;
- LayersPanel.Different_diffuseRemapMinX[i] = false;
- LayersPanel.Different_diffuseRemapMinY[i] = false;
- LayersPanel.Different_diffuseRemapMinZ[i] = false;
- LayersPanel.Different_maskMapRemapMaxW[i] = false;
- LayersPanel.Different_maskMapRemapMaxX[i] = false;
- LayersPanel.Different_maskMapRemapMaxY[i] = false;
- LayersPanel.Different_maskMapRemapMaxZ[i] = false;
- LayersPanel.Different_maskMapRemapMinW[i] = false;
- LayersPanel.Different_maskMapRemapMinX[i] = false;
- LayersPanel.Different_maskMapRemapMinY[i] = false;
- LayersPanel.Different_maskMapRemapMinZ[i] = false;
- LayersPanel.Different_normalScale[i] = false;
- LayersPanel.Different_specularR[i] = false;
- LayersPanel.Different_specularG[i] = false;
- LayersPanel.Different_specularB[i] = false;
- LayersPanel.Different_specularA[i] = false;
- foreach (var TerrainComponent in Terrains)
- {
- TheLayer = TerrainComponent.terrainData.terrainLayers[i];
- if (c == 0)
- {
- LastLayer = TheLayer;
- }
- if (TheLayer == null)
- {
- LayersPanel.NullLayerExists[i] = true;
- }
- else if (!LayersPanel.NullLayerExists[i])
- {
- LayersPanel.Different_name[i] = (TheLayer.name != LastLayer.name) ? true : LayersPanel.Different_name[i];
- LayersPanel.Different_diffuseTexture[i] = (TheLayer.diffuseTexture != LastLayer.diffuseTexture) ? true : LayersPanel.Different_diffuseTexture[i];
- LayersPanel.Different_maskMapTexture[i] = (TheLayer.maskMapTexture != LastLayer.maskMapTexture) ? true : LayersPanel.Different_maskMapTexture[i];
- LayersPanel.Different_normalMapTexture[i] = (TheLayer.normalMapTexture != LastLayer.normalMapTexture) ? true : LayersPanel.Different_normalMapTexture[i];
- LayersPanel.Different_metallic[i] = (TheLayer.metallic != LastLayer.metallic) ? true : LayersPanel.Different_metallic[i];
- LayersPanel.Different_smoothness[i] = (TheLayer.smoothness != LastLayer.smoothness) ? true : LayersPanel.Different_smoothness[i];
- LayersPanel.Different_tileOffsetX[i] = (TheLayer.tileOffset.x != LastLayer.tileOffset.x) ? true : LayersPanel.Different_tileOffsetX[i];
- LayersPanel.Different_tileOffsetY[i] = (TheLayer.tileOffset.y != LastLayer.tileOffset.y) ? true : LayersPanel.Different_tileOffsetY[i];
- LayersPanel.Different_tileSizeX[i] = (TheLayer.tileSize.x != LastLayer.tileSize.x) ? true : LayersPanel.Different_tileSizeX[i];
- LayersPanel.Different_tileSizeY[i] = (TheLayer.tileSize.y != LastLayer.tileSize.y) ? true : LayersPanel.Different_tileSizeY[i];
- LayersPanel.Different_diffuseRemapMaxW[i] = (TheLayer.diffuseRemapMax.w != LastLayer.diffuseRemapMax.w) ? true : LayersPanel.Different_diffuseRemapMaxW[i];
- LayersPanel.Different_diffuseRemapMaxX[i] = (TheLayer.diffuseRemapMax.x != LastLayer.diffuseRemapMax.x) ? true : LayersPanel.Different_diffuseRemapMaxX[i];
- LayersPanel.Different_diffuseRemapMaxY[i] = (TheLayer.diffuseRemapMax.y != LastLayer.diffuseRemapMax.y) ? true : LayersPanel.Different_diffuseRemapMaxY[i];
- LayersPanel.Different_diffuseRemapMaxZ[i] = (TheLayer.diffuseRemapMax.z != LastLayer.diffuseRemapMax.z) ? true : LayersPanel.Different_diffuseRemapMaxZ[i];
- LayersPanel.Different_diffuseRemapMinW[i] = (TheLayer.diffuseRemapMin.w != LastLayer.diffuseRemapMin.w) ? true : LayersPanel.Different_diffuseRemapMinW[i];
- LayersPanel.Different_diffuseRemapMinX[i] = (TheLayer.diffuseRemapMin.x != LastLayer.diffuseRemapMin.x) ? true : LayersPanel.Different_diffuseRemapMinX[i];
- LayersPanel.Different_diffuseRemapMinY[i] = (TheLayer.diffuseRemapMin.y != LastLayer.diffuseRemapMin.y) ? true : LayersPanel.Different_diffuseRemapMinY[i];
- LayersPanel.Different_diffuseRemapMinZ[i] = (TheLayer.diffuseRemapMin.z != LastLayer.diffuseRemapMin.z) ? true : LayersPanel.Different_diffuseRemapMinZ[i];
- LayersPanel.Different_maskMapRemapMaxW[i] = (TheLayer.maskMapRemapMax.w != LastLayer.maskMapRemapMax.w) ? true : LayersPanel.Different_maskMapRemapMaxW[i];
- LayersPanel.Different_maskMapRemapMaxX[i] = (TheLayer.maskMapRemapMax.x != LastLayer.maskMapRemapMax.x) ? true : LayersPanel.Different_maskMapRemapMaxX[i];
- LayersPanel.Different_maskMapRemapMaxY[i] = (TheLayer.maskMapRemapMax.y != LastLayer.maskMapRemapMax.y) ? true : LayersPanel.Different_maskMapRemapMaxY[i];
- LayersPanel.Different_maskMapRemapMaxZ[i] = (TheLayer.maskMapRemapMax.z != LastLayer.maskMapRemapMax.z) ? true : LayersPanel.Different_maskMapRemapMaxZ[i];
- LayersPanel.Different_maskMapRemapMinW[i] = (TheLayer.maskMapRemapMin.w != LastLayer.maskMapRemapMin.w) ? true : LayersPanel.Different_maskMapRemapMinW[i];
- LayersPanel.Different_maskMapRemapMinX[i] = (TheLayer.maskMapRemapMin.x != LastLayer.maskMapRemapMin.x) ? true : LayersPanel.Different_maskMapRemapMinX[i];
- LayersPanel.Different_maskMapRemapMinY[i] = (TheLayer.maskMapRemapMin.y != LastLayer.maskMapRemapMin.y) ? true : LayersPanel.Different_maskMapRemapMinY[i];
- LayersPanel.Different_maskMapRemapMinZ[i] = (TheLayer.maskMapRemapMin.z != LastLayer.maskMapRemapMin.z) ? true : LayersPanel.Different_maskMapRemapMinZ[i];
- LayersPanel.Different_normalScale[i] = (TheLayer.normalScale != LastLayer.normalScale) ? true : LayersPanel.Different_normalScale[i];
- LayersPanel.Different_specularR[i] = (TheLayer.specular.r != LastLayer.specular.r) ? true : LayersPanel.Different_specularR[i];
- LayersPanel.Different_specularG[i] = (TheLayer.specular.g != LastLayer.specular.g) ? true : LayersPanel.Different_specularG[i];
- LayersPanel.Different_specularB[i] = (TheLayer.specular.b != LastLayer.specular.b) ? true : LayersPanel.Different_specularB[i];
- LayersPanel.Different_specularA[i] = (TheLayer.specular.a != LastLayer.specular.a) ? true : LayersPanel.Different_specularA[i];
- }
- LayerGroup.Add(TheLayer);
- LastLayer = TheLayer;
- c++;
- }
- LayersPanel.LayerGroups[i] = LayerGroup.ToArray();
- //########################################
- if (!LayersPanel.NullLayerExists[i])
- {
- LayersPanel.nameStr[i] = LayersPanel.Different_name[i] ? "" : TheLayer.name;
- LayersPanel.diffuseTexture[i] = LayersPanel.Different_diffuseTexture[i] ? null : TheLayer.diffuseTexture;
- LayersPanel.maskMapTexture[i] = LayersPanel.Different_maskMapTexture[i] ? null : TheLayer.maskMapTexture;
- LayersPanel.normalMapTexture[i] = LayersPanel.Different_normalMapTexture[i] ? null : TheLayer.normalMapTexture;
- LayersPanel.metallicStr[i] = LayersPanel.Different_metallic[i] ? "" : TheLayer.metallic + "";
- LayersPanel.smoothnessStr[i] = LayersPanel.Different_smoothness[i] ? "" : TheLayer.smoothness + "";
- LayersPanel.tileOffsetXStr[i] = LayersPanel.Different_tileOffsetX[i] ? "" : TheLayer.tileOffset.x + "";
- LayersPanel.tileOffsetYStr[i] = LayersPanel.Different_tileOffsetY[i] ? "" : TheLayer.tileOffset.y + "";
- LayersPanel.tileSizeXStr[i] = LayersPanel.Different_tileSizeX[i] ? "" : TheLayer.tileSize.x + "";
- LayersPanel.tileSizeYStr[i] = LayersPanel.Different_tileSizeY[i] ? "" : TheLayer.tileSize.y + "";
- LayersPanel.diffuseRemapMaxWStr[i] = LayersPanel.Different_diffuseRemapMaxW[i] ? "" : TheLayer.diffuseRemapMax.w + "";
- LayersPanel.diffuseRemapMaxXStr[i] = LayersPanel.Different_diffuseRemapMaxX[i] ? "" : TheLayer.diffuseRemapMax.x + "";
- LayersPanel.diffuseRemapMaxYStr[i] = LayersPanel.Different_diffuseRemapMaxY[i] ? "" : TheLayer.diffuseRemapMax.y + "";
- LayersPanel.diffuseRemapMaxZStr[i] = LayersPanel.Different_diffuseRemapMaxZ[i] ? "" : TheLayer.diffuseRemapMax.z + "";
- LayersPanel.diffuseRemapMinWStr[i] = LayersPanel.Different_diffuseRemapMinW[i] ? "" : TheLayer.diffuseRemapMin.w + "";
- LayersPanel.diffuseRemapMinXStr[i] = LayersPanel.Different_diffuseRemapMinX[i] ? "" : TheLayer.diffuseRemapMin.x + "";
- LayersPanel.diffuseRemapMinYStr[i] = LayersPanel.Different_diffuseRemapMinY[i] ? "" : TheLayer.diffuseRemapMin.y + "";
- LayersPanel.diffuseRemapMinZStr[i] = LayersPanel.Different_diffuseRemapMinZ[i] ? "" : TheLayer.diffuseRemapMin.z + "";
- LayersPanel.maskMapRemapMaxWStr[i] = LayersPanel.Different_maskMapRemapMaxW[i] ? "" : TheLayer.maskMapRemapMax.w + "";
- LayersPanel.maskMapRemapMaxXStr[i] = LayersPanel.Different_maskMapRemapMaxX[i] ? "" : TheLayer.maskMapRemapMax.x + "";
- LayersPanel.maskMapRemapMaxYStr[i] = LayersPanel.Different_maskMapRemapMaxY[i] ? "" : TheLayer.maskMapRemapMax.y + "";
- LayersPanel.maskMapRemapMaxZStr[i] = LayersPanel.Different_maskMapRemapMaxZ[i] ? "" : TheLayer.maskMapRemapMax.z + "";
- LayersPanel.maskMapRemapMinWStr[i] = LayersPanel.Different_maskMapRemapMinW[i] ? "" : TheLayer.maskMapRemapMin.w + "";
- LayersPanel.maskMapRemapMinXStr[i] = LayersPanel.Different_maskMapRemapMinX[i] ? "" : TheLayer.maskMapRemapMin.x + "";
- LayersPanel.maskMapRemapMinYStr[i] = LayersPanel.Different_maskMapRemapMinY[i] ? "" : TheLayer.maskMapRemapMin.y + "";
- LayersPanel.maskMapRemapMinZStr[i] = LayersPanel.Different_maskMapRemapMinZ[i] ? "" : TheLayer.maskMapRemapMin.z + "";
- LayersPanel.normalScaleStr[i] = LayersPanel.Different_normalScale[i] ? "" : TheLayer.normalScale + "";
- LayersPanel.specularRStr[i] = LayersPanel.Different_specularR[i] ? "" : TheLayer.specular.r + "";
- LayersPanel.specularGStr[i] = LayersPanel.Different_specularG[i] ? "" : TheLayer.specular.g + "";
- LayersPanel.specularBStr[i] = LayersPanel.Different_specularB[i] ? "" : TheLayer.specular.b + "";
- LayersPanel.specularAStr[i] = LayersPanel.Different_specularA[i] ? "" : TheLayer.specular.a + "";
- }
- }
- }
- }
- private void PaintLayersPanel()
- {
- TheLayout.BeginVertical();
- if (empty(SelectedTerrains))
- {
- TheLayout.Label("No terrains selected.");
- }
- else
- {
- var Errors = "";
- var FirstTerrain = SelectedTerrains[0];
- var LayerCount = empty(FirstTerrain.terrainData.terrainLayers) ? 0 : FirstTerrain.terrainData.terrainLayers.Length;
- if (SelectedLayerCountsAreDifferent)
- {
- Errors += "Selected terrains have varying layer counts. Each terrain must have the same number of layers to be edited here.";
- }
- if (Errors != "")
- {
- TheLayout.Label(Errors);
- }
- else
- {
- TheLayout.BeginVertical("background-color:rgba(0,0,0,0.15);padding:5px;");
- if (LayerCount == 0)
- {
- TheLayout.Label("Selected terrain" + ((SelectedTerrains.Length == 1) ? " has" : "s have") + " no layers.");
- }
- else
- {
- TheLayout.Label("Base Texture Resolution must be as large as the Heightmap Resolution for proper painting.", "stretch-width:true;");
- TheLayout.BeginHorizontal();
- TheLayout.Label("alphamapWidth: " + (LayersPanel.Different_alphamapWidth ? "(different)" : (LayersPanel.alphamapWidth + "")), "width:200px;");
- TheLayout.Label("heightmapWidth: " + (LayersPanel.Different_heightmapWidth ? "(different)" : (LayersPanel.heightmapWidth + "")), "width:200px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("alphamapHeight: " + (LayersPanel.Different_alphamapHeight ? "(different)" : (LayersPanel.alphamapHeight + "")), "width:200px;");
- TheLayout.Label("heightmapHeight: " + (LayersPanel.Different_heightmapHeight ? "(different)" : (LayersPanel.heightmapHeight + "")), "width:200px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginVertical("stretch-width:true;stretch-height:true;margin-top:5px;");
- LayersPanel.ScrollVector = GUILayout.BeginScrollView(LayersPanel.ScrollVector);
- var RemoveLayerNum = -1;
- var InstantiateLayerNum = -1;
- for (var i = 0; i < LayerCount; i++)
- {
- TheLayout.BeginHorizontal();
- TheLayout.Label(i + "", "stretch-width:false;font-size:30px;vertical-align:top;");
- TheLayout.BeginVertical("stretch-width:false;background-color:rgba(0,0,0,0.15);width:550px;padding:5px;");
- if (LayersPanel.NullLayerExists[i])
- {
- TheLayout.Label("One or more selected terrains has a null value for this layer.", "min-width:500px;");
- GUILayout.Space(10);
- TheLayout.BeginHorizontal("width:" + TheLayout.LargestWidth + "px;background-color:rgba(0,0,0,0.2);");
- if (TheLayout.Button("Instantiate Null Layer(s)", "width:200px;"))
- {
- InstantiateLayerNum = i;
- }
- GUILayout.FlexibleSpace();
- if (TheLayout.Button("Remove Layer", "width:200px"))
- {
- RemoveLayerNum = i;
- }
- TheLayout.EndHorizontal();
- }
- else
- {
- TheLayout.BeginHorizontal();
- TheLayout.Label("name:", "width:200px");
- LayersPanel.nameStr[i] = TheLayout.TextField(LayersPanel.nameStr[i], "stretch-width:true;");
- if (LayersPanel.Different_name[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("textures:", "width:200px");
- LayersPanel.diffuseTexture[i] = TheLayout.TextureField(LayersPanel.diffuseTexture[i], "diffuse");
- LayersPanel.maskMapTexture[i] = TheLayout.TextureField(LayersPanel.maskMapTexture[i], "maskMap");
- LayersPanel.normalMapTexture[i] = TheLayout.TextureField(LayersPanel.normalMapTexture[i], "normalMap");
- if (LayersPanel.Different_diffuseTexture[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("metallic:", "width:200px");
- LayersPanel.metallicStr[i] = TheLayout.TextField(LayersPanel.metallicStr[i], "width:65px;");
- if (LayersPanel.Different_metallic[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("smoothness:", "width:200px");
- LayersPanel.smoothnessStr[i] = TheLayout.TextField(LayersPanel.smoothnessStr[i], "width:65px;");
- if (LayersPanel.Different_smoothness[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("normalScale:", "width:200px");
- LayersPanel.normalScaleStr[i] = TheLayout.TextField(LayersPanel.normalScaleStr[i], "width:65px;");
- if (LayersPanel.Different_normalScale[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("tileOffset:", "width:200px");
- TheLayout.Label("X");
- LayersPanel.tileOffsetXStr[i] = TheLayout.TextField(LayersPanel.tileOffsetXStr[i], "width:65px;");
- TheLayout.Label("Y");
- LayersPanel.tileOffsetYStr[i] = TheLayout.TextField(LayersPanel.tileOffsetYStr[i], "width:65px;stretch-width:false;");
- if (LayersPanel.Different_tileOffsetX[i] || LayersPanel.Different_tileOffsetY[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("tileSize:", "width:200px");
- TheLayout.Label("X");
- LayersPanel.tileSizeXStr[i] = TheLayout.TextField(LayersPanel.tileSizeXStr[i], "width:65px;");
- TheLayout.Label("Y");
- LayersPanel.tileSizeYStr[i] = TheLayout.TextField(LayersPanel.tileSizeYStr[i], "width:65px;");
- if (LayersPanel.Different_tileSizeX[i] || LayersPanel.Different_tileSizeY[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("diffuseRemapMax:", "width:200px");
- TheLayout.Label("X");
- LayersPanel.diffuseRemapMaxXStr[i] = TheLayout.TextField(LayersPanel.diffuseRemapMaxXStr[i], "width:65px;");
- TheLayout.Label("Y");
- LayersPanel.diffuseRemapMaxYStr[i] = TheLayout.TextField(LayersPanel.diffuseRemapMaxYStr[i], "width:65px;");
- TheLayout.Label("Z");
- LayersPanel.diffuseRemapMaxZStr[i] = TheLayout.TextField(LayersPanel.diffuseRemapMaxZStr[i], "width:65px;");
- TheLayout.Label("W");
- LayersPanel.diffuseRemapMaxWStr[i] = TheLayout.TextField(LayersPanel.diffuseRemapMaxWStr[i], "width:65px;");
- if (LayersPanel.Different_diffuseRemapMaxW[i] || LayersPanel.Different_diffuseRemapMaxX[i] || LayersPanel.Different_diffuseRemapMaxY[i] || LayersPanel.Different_diffuseRemapMaxZ[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("diffuseRemapMin:", "width:200px");
- TheLayout.Label("X");
- LayersPanel.diffuseRemapMinXStr[i] = TheLayout.TextField(LayersPanel.diffuseRemapMinXStr[i], "width:65px;");
- TheLayout.Label("Y");
- LayersPanel.diffuseRemapMinYStr[i] = TheLayout.TextField(LayersPanel.diffuseRemapMinYStr[i], "width:65px;");
- TheLayout.Label("Z");
- LayersPanel.diffuseRemapMinZStr[i] = TheLayout.TextField(LayersPanel.diffuseRemapMinZStr[i], "width:65px;");
- TheLayout.Label("W");
- LayersPanel.diffuseRemapMinWStr[i] = TheLayout.TextField(LayersPanel.diffuseRemapMinWStr[i], "width:65px;");
- if (LayersPanel.Different_diffuseRemapMinW[i] || LayersPanel.Different_diffuseRemapMinX[i] || LayersPanel.Different_diffuseRemapMinY[i] || LayersPanel.Different_diffuseRemapMinZ[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("maskMapRemapMax:", "width:200px");
- TheLayout.Label("X");
- LayersPanel.maskMapRemapMaxXStr[i] = TheLayout.TextField(LayersPanel.maskMapRemapMaxXStr[i], "width:65px;");
- TheLayout.Label("Y");
- LayersPanel.maskMapRemapMaxYStr[i] = TheLayout.TextField(LayersPanel.maskMapRemapMaxYStr[i], "width:65px;");
- TheLayout.Label("Z");
- LayersPanel.maskMapRemapMaxZStr[i] = TheLayout.TextField(LayersPanel.maskMapRemapMaxZStr[i], "width:65px;");
- TheLayout.Label("W");
- LayersPanel.maskMapRemapMaxWStr[i] = TheLayout.TextField(LayersPanel.maskMapRemapMaxWStr[i], "width:65px;");
- if (LayersPanel.Different_maskMapRemapMaxW[i] || LayersPanel.Different_maskMapRemapMaxX[i] || LayersPanel.Different_maskMapRemapMaxY[i] || LayersPanel.Different_maskMapRemapMaxZ[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("maskMapRemapMin:", "width:200px");
- TheLayout.Label("X");
- LayersPanel.maskMapRemapMinXStr[i] = TheLayout.TextField(LayersPanel.maskMapRemapMinXStr[i], "width:65px;");
- TheLayout.Label("Y");
- LayersPanel.maskMapRemapMinYStr[i] = TheLayout.TextField(LayersPanel.maskMapRemapMinYStr[i], "width:65px;");
- TheLayout.Label("Z");
- LayersPanel.maskMapRemapMinZStr[i] = TheLayout.TextField(LayersPanel.maskMapRemapMinZStr[i], "width:65px;");
- TheLayout.Label("W");
- LayersPanel.maskMapRemapMinWStr[i] = TheLayout.TextField(LayersPanel.maskMapRemapMinWStr[i], "width:65px;");
- if (LayersPanel.Different_maskMapRemapMinW[i] || LayersPanel.Different_maskMapRemapMinX[i] || LayersPanel.Different_maskMapRemapMinY[i] || LayersPanel.Different_maskMapRemapMinZ[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label("specular:", "width:200px");
- TheLayout.Label("R");
- LayersPanel.specularRStr[i] = TheLayout.TextField(LayersPanel.specularRStr[i], "width:65px;");
- TheLayout.Label("G");
- LayersPanel.specularGStr[i] = TheLayout.TextField(LayersPanel.specularGStr[i], "width:65px;");
- TheLayout.Label("B");
- LayersPanel.specularBStr[i] = TheLayout.TextField(LayersPanel.specularBStr[i], "width:65px;");
- TheLayout.Label("A");
- LayersPanel.specularAStr[i] = TheLayout.TextField(LayersPanel.specularAStr[i], "width:65px;");
- if (LayersPanel.Different_specularR[i] || LayersPanel.Different_specularG[i] || LayersPanel.Different_specularB[i] || LayersPanel.Different_specularA[i])
- {
- TheLayout.Label("(varies)");
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal("");
- TheLayout.Label("Paint Condition:", "");
- LayersPanel.PaintString[i] = TheLayout.TextArea(LayersPanel.PaintString[i], "stretch-width:true;height:60px;margin:0px 10px");
- if (TheLayout.Button("Paint", "width:100px;height:60px;vertical-align:middle;"))
- {
- PaintLayer(SelectedTerrains, i, LayersPanel.PaintString[i], out LayersPanel.LayerPaintErrors[i]);
- }
- TheLayout.EndHorizontal();
- GUILayout.Space(10);
- TheLayout.BeginHorizontal("stretch-width:true;");
- if (TheLayout.Button("Save Layer", "width:200px"))
- {
- EditLayer(LayersPanel.LayerGroups[i], i, out LayersPanel.LayerEditErrors[i]);
- }
- GUILayout.FlexibleSpace();
- if (TheLayout.Button("Remove Layer", "width:200px"))
- {
- RemoveLayerNum = i;
- }
- TheLayout.EndHorizontal();
- }
- if (!empty(LayersPanel.LayerEditErrors[i]))
- {
- TheLayout.BeginHorizontal("background-color:rgba(255,255,0,0.75);");
- TheLayout.Label(LayersPanel.LayerEditErrors[i] ?? "", "");
- TheLayout.EndHorizontal();
- }
- TheLayout.EndVertical();
- TheLayout.EndHorizontal();
- GUILayout.Space(10);
- }
- GUILayout.EndScrollView();
- TheLayout.EndVertical();
- if (InstantiateLayerNum > -1)
- {
- InstantiateLayer(SelectedTerrains, InstantiateLayerNum);
- }
- if (RemoveLayerNum > -1)
- {
- RemoveLayer(SelectedTerrains, RemoveLayerNum);
- }
- }
- if (TheLayout.Button("Add Layer", "width:200px"))
- {
- AddLayer(SelectedTerrains);
- }
- TheLayout.EndVertical();
- }
- }
- TheLayout.EndVertical();
- }
- private void PaintLayer(Terrain[] Terrains, int LayerNum, string Criteria, out string Errors)
- {
- int AlphaWidth, AlphaHeight, MeshWidth, MeshHeight, MeshX, MeshZ;
- TerrainData TheData;
- float[,,] AlphaMaps;
- float[,] Heights;
- float Height, Steepness, NormalizedX, NormalizedZ;
- var Empty = string.IsNullOrEmpty(Criteria);
- var TheTruth = Truth.Compile(Empty ? "h==0" : Criteria, new[] { 'h', 's' }, out Errors);
- var Values = new Dictionary<string, float> { { "h", 0 }, { "s", 0 } };
- foreach (var TheTerrain in Terrains)
- {
- TheData = TheTerrain.terrainData;
- AlphaWidth = TheData.alphamapWidth;
- AlphaHeight = TheData.alphamapHeight;
- MeshWidth = TheData.heightmapWidth;
- MeshHeight = TheData.heightmapHeight;
- Heights = TheData.GetHeights(0, 0, MeshWidth, MeshHeight);
- AlphaMaps = TheData.GetAlphamaps(0, 0, AlphaWidth, AlphaHeight);
- if (LayerNum < TheData.terrainLayers.Length)
- {
- for (var AlphaX = 0; AlphaX < AlphaWidth; AlphaX++)
- {
- for (int AlphaZ = 0; AlphaZ < AlphaHeight; AlphaZ++)
- {
- NormalizedX = AlphaX / (float)(AlphaWidth - 1);
- NormalizedZ = AlphaZ / (float)(AlphaHeight - 1);
- MeshX = (int)Math.Round(NormalizedX * (MeshWidth - 1));
- MeshZ = (int)Math.Round(NormalizedZ * (MeshHeight - 1));
- Height = Heights[MeshZ, MeshX];
- Steepness = TheData.GetSteepness(NormalizedX, NormalizedZ);
- Values["h"] = Empty ? 0 : Height;
- Values["s"] = Steepness;
- if (TheTruth.Evaluate(Values))
- {
- for (var c = 0; c < TheData.terrainLayers.Length; c++)
- {
- AlphaMaps[AlphaZ, AlphaX, c] = 0;
- }
- AlphaMaps[AlphaZ, AlphaX, LayerNum] = 1;
- }
- }
- }
- TheData.SetAlphamaps(0, 0, AlphaMaps);
- }
- }
- }
- private void AddLayer(Terrain[] Terrains)
- {
- int CurLen;
- var SaveAsset = true;
- TerrainLayer[] NewArr;
- var NewLayer = new TerrainLayer();
- NewLayer.name = "Layer_" + RandomInt32;
- foreach (var TheTerrain in Terrains)
- {
- CurLen = (TheTerrain.terrainData.terrainLayers == null) ? 0 : TheTerrain.terrainData.terrainLayers.Length;
- NewArr = new TerrainLayer[CurLen + 1];
- for (var i = 0; i < CurLen; i++)
- {
- NewArr[i] = TheTerrain.terrainData.terrainLayers[i];
- }
- NewArr[CurLen] = NewLayer;
- TheTerrain.terrainData.terrainLayers = NewArr;
- }
- if (SaveAsset)
- {
- TheAssetBucket.Add(NewLayer, false);
- }
- RefreshLayersPanel(Terrains);
- }
- private void InstantiateLayer(Terrain[] Terrains, int LayerNum)
- {
- var NewLayer = new TerrainLayer();
- NewLayer.name = "Layer_" + RandomInt32;
- var SaveAsset = true;
- TerrainData TheData;
- TerrainLayer[] TheLayers;
- TerrainLayer[] NewLayers;
- foreach (var TheTerrain in Terrains)
- {
- if (TheTerrain != null)
- {
- TheData = TheTerrain.terrainData;
- if (TheData != null)
- {
- TheLayers = TheData.terrainLayers;
- if (TheLayers != null && TheLayers[LayerNum] == null)
- {
- NewLayers = new TerrainLayer[TheLayers.Length];
- for (var i = 0; i < NewLayers.Length; i++)
- {
- if (i == LayerNum)
- {
- NewLayers[i] = NewLayer;
- }
- else
- {
- NewLayers[i] = TheLayers[i];
- }
- }
- TheData.terrainLayers = NewLayers;
- SaveAsset = true;
- }
- }
- }
- }
- if (SaveAsset)
- {
- TheAssetBucket.Add(NewLayer, false);
- }
- RefreshLayersPanel(Terrains);
- }
- private void RemoveLayer(Terrain[] Terrains, int LayerNum)
- {
- List<TerrainLayer> LayerList;
- foreach (var TheTerrain in Terrains)
- {
- LayerList = new List<TerrainLayer>(TheTerrain.terrainData.terrainLayers);
- if (LayerNum < LayerList.Count)
- {
- LayerList.RemoveAt(LayerNum);
- }
- TheTerrain.terrainData.terrainLayers = LayerList.ToArray();
- }
- RefreshLayersPanel(Terrains);
- }
- private void EditLayer(TerrainLayer[] LayerGroup, int LayerNum, out string Errors)
- {
- Errors = "";
- var i = LayerNum;
- if (LayersPanel.NullLayerExists[i])
- {
- Errors += "Null layer exists.";
- }
- else
- {
- float[] TheSpecularColor;
- foreach (var Layer in LayerGroup)
- {
- TheSpecularColor = new float[] { Layer.specular.r, Layer.specular.g, Layer.specular.b, Layer.specular.a };
- if ((LayersPanel.Different_name[i] && !empty(LayersPanel.nameStr[i])) || !LayersPanel.Different_name[i])
- {
- if (empty(LayersPanel.nameStr[i]))
- {
- Errors += "name cannot be empty.\n";
- }
- else
- {
- Layer.name = LayersPanel.nameStr[i];
- }
- }
- if ((LayersPanel.Different_diffuseTexture[i] && !empty(LayersPanel.diffuseTexture[i])) || !LayersPanel.Different_diffuseTexture[i])
- {
- Layer.diffuseTexture = LayersPanel.diffuseTexture[i];
- }
- if ((LayersPanel.Different_maskMapTexture[i] && !empty(LayersPanel.maskMapTexture[i])) || !LayersPanel.Different_maskMapTexture[i])
- {
- Layer.maskMapTexture = LayersPanel.maskMapTexture[i];
- }
- if ((LayersPanel.Different_normalMapTexture[i] && !empty(LayersPanel.normalMapTexture[i])) || !LayersPanel.Different_normalMapTexture[i])
- {
- Layer.normalMapTexture = LayersPanel.normalMapTexture[i];
- }
- if ((LayersPanel.Different_metallic[i] && !empty(LayersPanel.metallicStr[i])) || !LayersPanel.Different_metallic[i])
- {
- if (!float.TryParse(LayersPanel.metallicStr[i], out float metallic) || metallic < 0)
- {
- Errors += "metallic must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.metallic = metallic;
- }
- }
- if ((LayersPanel.Different_smoothness[i] && !empty(LayersPanel.smoothnessStr[i])) || !LayersPanel.Different_smoothness[i])
- {
- if (!float.TryParse(LayersPanel.smoothnessStr[i], out float smoothness) || smoothness < 0)
- {
- Errors += "smoothness must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.smoothness = smoothness;
- }
- }
- if ((LayersPanel.Different_tileOffsetX[i] && !empty(LayersPanel.tileOffsetXStr[i])) || !LayersPanel.Different_tileOffsetX[i])
- {
- if (!float.TryParse(LayersPanel.tileOffsetXStr[i], out float tileOffsetX) || tileOffsetX < 0)
- {
- Errors += "tileOffsetX must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.tileOffset = new Vector2(tileOffsetX, Layer.tileOffset.y);
- }
- }
- if ((LayersPanel.Different_tileOffsetY[i] && !empty(LayersPanel.tileOffsetYStr[i])) || !LayersPanel.Different_tileOffsetY[i])
- {
- if (!float.TryParse(LayersPanel.tileOffsetYStr[i], out float tileOffsetY) || tileOffsetY < 0)
- {
- Errors += "tileOffsetY must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.tileOffset = new Vector2(Layer.tileOffset.y, tileOffsetY);
- }
- }
- if ((LayersPanel.Different_tileSizeX[i] && !empty(LayersPanel.tileSizeXStr[i])) || !LayersPanel.Different_tileSizeX[i])
- {
- if (!float.TryParse(LayersPanel.tileSizeXStr[i], out float tileSizeX) || tileSizeX < 0)
- {
- Errors += "tileSizeX must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.tileSize = new Vector2(tileSizeX, Layer.tileSize.y);
- }
- }
- if ((LayersPanel.Different_tileSizeY[i] && !empty(LayersPanel.tileSizeYStr[i])) || !LayersPanel.Different_tileSizeY[i])
- {
- if (!float.TryParse(LayersPanel.tileSizeYStr[i], out float tileSizeY) || tileSizeY < 0)
- {
- Errors += "tileSizeY must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.tileSize = new Vector2(Layer.tileSize.x, tileSizeY);
- }
- }
- if ((LayersPanel.Different_diffuseRemapMaxW[i] && !empty(LayersPanel.diffuseRemapMaxWStr[i])) || !LayersPanel.Different_diffuseRemapMaxW[i])
- {
- if (!float.TryParse(LayersPanel.diffuseRemapMaxWStr[i], out float diffuseRemapMaxW) || diffuseRemapMaxW < 0)
- {
- Errors += "diffuseRemapMaxW must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.diffuseRemapMax = new Vector4(Layer.diffuseRemapMax.x, Layer.diffuseRemapMax.y, Layer.diffuseRemapMax.z, diffuseRemapMaxW);
- }
- }
- if ((LayersPanel.Different_diffuseRemapMaxX[i] && !empty(LayersPanel.diffuseRemapMaxXStr[i])) || !LayersPanel.Different_diffuseRemapMaxX[i])
- {
- if (!float.TryParse(LayersPanel.diffuseRemapMaxXStr[i], out float diffuseRemapMaxX) || diffuseRemapMaxX < 0)
- {
- Errors += "diffuseRemapMaxX must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.diffuseRemapMax = new Vector4(diffuseRemapMaxX, Layer.diffuseRemapMax.y, Layer.diffuseRemapMax.z, Layer.diffuseRemapMax.w);
- }
- }
- if ((LayersPanel.Different_diffuseRemapMaxY[i] && !empty(LayersPanel.diffuseRemapMaxYStr[i])) || !LayersPanel.Different_diffuseRemapMaxY[i])
- {
- if (!float.TryParse(LayersPanel.diffuseRemapMaxYStr[i], out float diffuseRemapMaxY) || diffuseRemapMaxY < 0)
- {
- Errors += "diffuseRemapMaxY must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.diffuseRemapMax = new Vector4(Layer.diffuseRemapMax.x, diffuseRemapMaxY, Layer.diffuseRemapMax.z, Layer.diffuseRemapMax.w);
- }
- }
- if ((LayersPanel.Different_diffuseRemapMaxZ[i] && !empty(LayersPanel.diffuseRemapMaxZStr[i])) || !LayersPanel.Different_diffuseRemapMaxZ[i])
- {
- if (!float.TryParse(LayersPanel.diffuseRemapMaxZStr[i], out float diffuseRemapMaxZ) || diffuseRemapMaxZ < 0)
- {
- Errors += "diffuseRemapMaxZ must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.diffuseRemapMax = new Vector4(Layer.diffuseRemapMax.x, Layer.diffuseRemapMax.y, diffuseRemapMaxZ, Layer.diffuseRemapMax.w);
- }
- }
- if ((LayersPanel.Different_diffuseRemapMinW[i] && !empty(LayersPanel.diffuseRemapMinWStr[i])) || !LayersPanel.Different_diffuseRemapMinW[i])
- {
- if (!float.TryParse(LayersPanel.diffuseRemapMinWStr[i], out float diffuseRemapMinW) || diffuseRemapMinW < 0)
- {
- Errors += "diffuseRemapMinW must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.diffuseRemapMin = new Vector4(Layer.diffuseRemapMin.x, Layer.diffuseRemapMin.y, Layer.diffuseRemapMin.z, diffuseRemapMinW);
- }
- }
- if ((LayersPanel.Different_diffuseRemapMinX[i] && !empty(LayersPanel.diffuseRemapMinXStr[i])) || !LayersPanel.Different_diffuseRemapMinX[i])
- {
- if (!float.TryParse(LayersPanel.diffuseRemapMinXStr[i], out float diffuseRemapMinX) || diffuseRemapMinX < 0)
- {
- Errors += "diffuseRemapMinX must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.diffuseRemapMin = new Vector4(diffuseRemapMinX, Layer.diffuseRemapMin.y, Layer.diffuseRemapMin.z, Layer.diffuseRemapMin.w);
- }
- }
- if ((LayersPanel.Different_diffuseRemapMinY[i] && !empty(LayersPanel.diffuseRemapMinYStr[i])) || !LayersPanel.Different_diffuseRemapMinY[i])
- {
- if (!float.TryParse(LayersPanel.diffuseRemapMinYStr[i], out float diffuseRemapMinY) || diffuseRemapMinY < 0)
- {
- Errors += "diffuseRemapMinY must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.diffuseRemapMin = new Vector4(Layer.diffuseRemapMin.x, diffuseRemapMinY, Layer.diffuseRemapMin.z, Layer.diffuseRemapMin.w);
- }
- }
- if ((LayersPanel.Different_diffuseRemapMinZ[i] && !empty(LayersPanel.diffuseRemapMinZStr[i])) || !LayersPanel.Different_diffuseRemapMinZ[i])
- {
- if (!float.TryParse(LayersPanel.diffuseRemapMinZStr[i], out float diffuseRemapMinZ) || diffuseRemapMinZ < 0)
- {
- Errors += "diffuseRemapMinZ must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.diffuseRemapMin = new Vector4(Layer.diffuseRemapMin.x, Layer.diffuseRemapMin.y, diffuseRemapMinZ, Layer.diffuseRemapMin.w);
- }
- }
- if ((LayersPanel.Different_maskMapRemapMaxW[i] && !empty(LayersPanel.maskMapRemapMaxWStr[i])) || !LayersPanel.Different_maskMapRemapMaxW[i])
- {
- if (!float.TryParse(LayersPanel.maskMapRemapMaxWStr[i], out float maskMapRemapMaxW) || maskMapRemapMaxW < 0)
- {
- Errors += "maskMapRemapMaxW must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.maskMapRemapMax = new Vector4(Layer.maskMapRemapMax.x, Layer.maskMapRemapMax.y, Layer.maskMapRemapMax.z, maskMapRemapMaxW);
- }
- }
- if ((LayersPanel.Different_maskMapRemapMaxX[i] && !empty(LayersPanel.maskMapRemapMaxXStr[i])) || !LayersPanel.Different_maskMapRemapMaxX[i])
- {
- if (!float.TryParse(LayersPanel.maskMapRemapMaxXStr[i], out float maskMapRemapMaxX) || maskMapRemapMaxX < 0)
- {
- Errors += "maskMapRemapMaxX must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.maskMapRemapMax = new Vector4(maskMapRemapMaxX, Layer.maskMapRemapMax.y, Layer.maskMapRemapMax.z, Layer.maskMapRemapMax.w);
- }
- }
- if ((LayersPanel.Different_maskMapRemapMaxY[i] && !empty(LayersPanel.maskMapRemapMaxYStr[i])) || !LayersPanel.Different_maskMapRemapMaxY[i])
- {
- if (!float.TryParse(LayersPanel.maskMapRemapMaxYStr[i], out float maskMapRemapMaxY) || maskMapRemapMaxY < 0)
- {
- Errors += "maskMapRemapMaxY must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.maskMapRemapMax = new Vector4(Layer.maskMapRemapMax.x, maskMapRemapMaxY, Layer.maskMapRemapMax.z, Layer.maskMapRemapMax.w);
- }
- }
- if ((LayersPanel.Different_maskMapRemapMaxZ[i] && !empty(LayersPanel.maskMapRemapMaxZStr[i])) || !LayersPanel.Different_maskMapRemapMaxZ[i])
- {
- if (!float.TryParse(LayersPanel.maskMapRemapMaxZStr[i], out float maskMapRemapMaxZ) || maskMapRemapMaxZ < 0)
- {
- Errors += "maskMapRemapMaxZ must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.maskMapRemapMax = new Vector4(Layer.maskMapRemapMax.x, Layer.maskMapRemapMax.y, maskMapRemapMaxZ, Layer.maskMapRemapMax.w);
- }
- }
- if ((LayersPanel.Different_maskMapRemapMinW[i] && !empty(LayersPanel.maskMapRemapMinWStr[i])) || !LayersPanel.Different_maskMapRemapMinW[i])
- {
- if (!float.TryParse(LayersPanel.maskMapRemapMinWStr[i], out float maskMapRemapMinW) || maskMapRemapMinW < 0)
- {
- Errors += "maskMapRemapMinW must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.maskMapRemapMin = new Vector4(Layer.maskMapRemapMin.x, Layer.maskMapRemapMin.y, Layer.maskMapRemapMin.z, maskMapRemapMinW);
- }
- }
- if ((LayersPanel.Different_maskMapRemapMinX[i] && !empty(LayersPanel.maskMapRemapMinXStr[i])) || !LayersPanel.Different_maskMapRemapMinX[i])
- {
- if (!float.TryParse(LayersPanel.maskMapRemapMinXStr[i], out float maskMapRemapMinX) || maskMapRemapMinX < 0)
- {
- Errors += "maskMapRemapMinX must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.maskMapRemapMin = new Vector4(maskMapRemapMinX, Layer.maskMapRemapMin.y, Layer.maskMapRemapMin.z, Layer.maskMapRemapMin.w);
- }
- }
- if ((LayersPanel.Different_maskMapRemapMinY[i] && !empty(LayersPanel.maskMapRemapMinYStr[i])) || !LayersPanel.Different_maskMapRemapMinY[i])
- {
- if (!float.TryParse(LayersPanel.maskMapRemapMinYStr[i], out float maskMapRemapMinY) || maskMapRemapMinY < 0)
- {
- Errors += "maskMapRemapMinY must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.maskMapRemapMin = new Vector4(Layer.maskMapRemapMin.x, maskMapRemapMinY, Layer.maskMapRemapMin.z, Layer.maskMapRemapMin.w);
- }
- }
- if ((LayersPanel.Different_maskMapRemapMinZ[i] && !empty(LayersPanel.maskMapRemapMinZStr[i])) || !LayersPanel.Different_maskMapRemapMinZ[i])
- {
- if (!float.TryParse(LayersPanel.maskMapRemapMinZStr[i], out float maskMapRemapMinZ) || maskMapRemapMinZ < 0)
- {
- Errors += "maskMapRemapMinZ must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.maskMapRemapMin = new Vector4(Layer.maskMapRemapMin.x, Layer.maskMapRemapMin.y, maskMapRemapMinZ, Layer.maskMapRemapMin.w);
- }
- }
- if ((LayersPanel.Different_normalScale[i] && !empty(LayersPanel.normalScaleStr[i])) || !LayersPanel.Different_normalScale[i])
- {
- if (!float.TryParse(LayersPanel.normalScaleStr[i], out float normalScale) || normalScale < 0)
- {
- Errors += "normalScale must be a decimal greater than 0.\n";
- }
- else
- {
- Layer.normalScale = normalScale;
- }
- }
- if ((LayersPanel.Different_specularR[i] && !empty(LayersPanel.specularRStr[i])) || !LayersPanel.Different_specularR[i])
- {
- if (!float.TryParse(LayersPanel.specularRStr[i], out float specularR) || specularR < 0 || specularR > 1)
- {
- Errors += "specularR must be a decimal between 0 and 1.\n";
- }
- else
- {
- TheSpecularColor[0] = specularR;
- }
- }
- if ((LayersPanel.Different_specularG[i] && !empty(LayersPanel.specularGStr[i])) || !LayersPanel.Different_specularG[i])
- {
- if (!float.TryParse(LayersPanel.specularGStr[i], out float specularG) || specularG < 0 || specularG > 1)
- {
- Errors += "specularG must be a decimal between 0 and 1.\n";
- }
- else
- {
- TheSpecularColor[1] = specularG;
- }
- }
- if ((LayersPanel.Different_specularB[i] && !empty(LayersPanel.specularBStr[i])) || !LayersPanel.Different_specularB[i])
- {
- if (!float.TryParse(LayersPanel.specularBStr[i], out float specularB) || specularB < 0 || specularB > 1)
- {
- Errors += "specularB must be a decimal between 0 and 1.\n";
- }
- else
- {
- TheSpecularColor[2] = specularB;
- }
- }
- if ((LayersPanel.Different_specularA[i] && !empty(LayersPanel.specularAStr[i])) || !LayersPanel.Different_specularA[i])
- {
- if (!float.TryParse(LayersPanel.specularAStr[i], out float specularA) || specularA < 0 || specularA > 1)
- {
- Errors += "specularA must be a decimal between 0 and 1.\n";
- }
- else
- {
- TheSpecularColor[3] = specularA;
- }
- }
- Layer.specular = new Color(TheSpecularColor[0], TheSpecularColor[1], TheSpecularColor[2], TheSpecularColor[3]);
- }
- }
- }
- //##############################################################################
- //##############################################################################
- private static class PropertiesPanel
- {
- public static string DebugMsg = "";
- public static int Sort = 0;
- public static Vector2 ScrollVector = new Vector2(0, 0);
- }
- private void PaintPropertiesPanel()
- {
- if (empty(SelectedTerrains))
- {
- TheLayout.Label("No terrains selected.");
- }
- else
- {
- TheLayout.BeginVertical("width:500px;background-color:rgba(0,0,0,0.15);padding:5px;");
- TheLayout.EndVertical();
- }
- }
- //##############################################################################
- //##############################################################################
- private static class DebugPanel
- {
- public static string DebugMsg = "";
- public static int Sort = 0;
- public static Vector2 ScrollVector = new Vector2(0, 0);
- }
- private void PaintDebugPanel()
- {
- /*
- */
- var SubAssets = TheAssetBucket.GetSubAssets();
- TheLayout.BeginVertical("background-color:rgba(0,0,0,0.15);padding:5px;");
- TheLayout.BeginHorizontal();
- TheLayout.Label("Script Path", "width:128px;");
- TheLayout.TextField(ScriptPath, "width:400px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- GUI.enabled = !empty(SelectedTerrains);
- if (TheLayout.Button("Debug Terrain", "width:200px;"))
- {
- if (!empty(SelectedTerrains))
- {
- DebugPanel.DebugMsg = JsonTools.object_to_json(SelectedTerrains[0], 3);
- }
- }
- GUI.enabled = true;
- TheLayout.TextField(DebugPanel.DebugMsg, "vertical-align:middle;text-align:left;width:400px;");
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- GUI.enabled = SubAssets.Count() > 0;
- if (TheLayout.Button("Cleanup sub Assets", "width:200px;"))
- {
- TheAssetBucket.Clean();
- }
- GUI.enabled = true;
- if (TheLayout.Button("Do thing", "width:200px;"))
- {
- var AllObjects = Resources.FindObjectsOfTypeAll(typeof(TerrainData));
- foreach (var TheObject in SubAssets)
- {
- Debug.Log(TheObject.name);
- //TheObject.hideFlags = HideFlags.None;
- }
- Debug.Log(AllObjects.Count());
- }
- TheLayout.EndHorizontal();
- TheLayout.BeginHorizontal();
- TheLayout.Label(SubAssets.Count() + " sub Assets in " + Regex.Replace(AssetPath, ".*/", "") + "");
- TheLayout.EndHorizontal();
- TheLayout.Label(TheAssetBucket.GetParamString());
- TheLayout.BeginHorizontal("width:300px;");
- TheLayout.Label("Sort sub-assets:", "width:128px;");
- DebugPanel.Sort = TheLayout.Toolbar(DebugPanel.Sort, new[] { "A-Z", "Type" });
- TheLayout.EndHorizontal();
- DebugPanel.ScrollVector = GUILayout.BeginScrollView(DebugPanel.ScrollVector);
- /*
- foreach (var name in Font.GetOSInstalledFontNames())
- {
- TheLayout.Label(name);
- }
- var Fonts = Resources.FindObjectsOfTypeAll<Font>();
- foreach (var font in Fonts)
- {
- TheLayout.Label(font.name + ", names: " + JsonTools.object_to_json(font.fontNames));
- }
- */
- TerrainData TheTerrainData;
- Texture2D TheTexture;
- string LabelText;
- Type TheType;
- var AssetCollection = SubAssets.OrderBy(x => (DebugPanel.Sort == 0) ? x.name : x.GetType().Name);
- foreach (var Obj in AssetCollection)
- {
- if (Obj == null)
- {
- LabelText = "(null)";
- }
- else
- {
- TheType = Obj.GetType();
- LabelText = Obj.name;
- if (TheType == typeof(TerrainData))
- {
- TheTerrainData = (TerrainData)Obj;
- LabelText += " (" + TheType.Name + ")";
- }
- else if (TheType == typeof(Texture2D))
- {
- TheTexture = (Texture2D)Obj;
- LabelText += " (" + TheType.Name + " " + TheTexture.format.ToString() + ")";
- }
- else
- {
- LabelText += " (" + TheType.Name + ")";
- }
- }
- LabelText = LabelText + ", hideFlags: " + Obj.hideFlags.ToString();
- TheLayout.BeginHorizontal();
- TheLayout.Label(LabelText);
- TheLayout.EndHorizontal();
- }
- GUILayout.EndScrollView();
- TheLayout.EndVertical();
- }
- }
- //############################################################################################
- //############################################################################################
- //############################################################################################
- //############################################################################################
- private class AssetBucket
- {
- private TerraLab TheAsset;
- public AssetBucket(TerraLab Asset)
- {
- TheAsset = Asset ?? throw new NullReferenceException();
- }
- public IEnumerable<UnityEngine.Object> GetSubAssets()
- {
- return AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetPath).Where(x => x != null);
- }
- public string GetParamString()
- {
- return TheAsset.Params;
- }
- private static string Encode(string Input)
- {
- return (Input ?? "").Replace("@", "@1").Replace(";", "@2").Replace("=", "@3");
- }
- private static string Decode(string Input)
- {
- return (Input ?? "").Replace("@3", "=").Replace("@2", ";").Replace("@1", "@");
- }
- public string GetKey(string Key)
- {
- Key = Encode(Key);
- var Str = Regex.Replace(TheAsset.Params ?? "", ".*(?:^|;)" + Regex.Escape(Key) + "=", "");
- if (Str.Length != TheAsset.Params.Length)
- {
- //key exists
- return Decode(Regex.Replace(Str, ";.*", "", RegexOptions.Singleline));
- }
- else
- {
- return "";
- }
- }
- public string SetKey(string Key, string Val)
- {
- Key = Encode(Key);
- var NewVal = Encode(Val);
- var Str = Regex.Replace(TheAsset.Params ?? "", "(?<=^|;)" + Regex.Escape(Key) + "[^;]*(?:;|$)", "");
- TheAsset.Params = Regex.Replace(Str, "([^;])$", "$1;") + ((Val == "") ? "" : Key + "=" + NewVal + ";");
- return Val;
- }
- public UnityEngine.Object Get(string AssetName)
- {
- return GetSubAssets().Where(x => x != null && x.name == AssetName).FirstOrDefault();
- }
- public void Add(UnityEngine.Object Obj, bool Save = true)
- {
- Add(new[] { Obj }, Save);
- }
- public void Add(IEnumerable<UnityEngine.Object> Objs, bool Save = true)
- {
- if (!empty(Objs))
- {
- var SubAssets = GetSubAssets();
- try
- {
- AssetDatabase.StartAssetEditing();
- foreach (var Obj in Objs)
- {
- if (SubAssets.Contains(Obj))
- {
- throw new Exception("Object is already a sub-asset.");
- }
- AssetDatabase.AddObjectToAsset(Obj, AssetPath);
- }
- }
- finally
- {
- AssetDatabase.StopAssetEditing();
- }
- if (Save)
- {
- AssetDatabase.SaveAssets();
- }
- }
- }
- public void Remove(UnityEngine.Object Obj, bool Save = true)
- {
- Remove(new[] { Obj }, Save);
- }
- public void Remove(IEnumerable<UnityEngine.Object> Objs, bool Save = true)
- {
- if (!empty(Objs))
- {
- try
- {
- AssetDatabase.StartAssetEditing();
- foreach (var Obj in Objs)
- {
- AssetDatabase.RemoveObjectFromAsset(Obj);
- }
- }
- finally
- {
- AssetDatabase.StopAssetEditing();
- }
- if (Save)
- {
- AssetDatabase.SaveAssets();
- }
- }
- }
- public void Save()
- {
- AssetDatabase.SaveAssets();
- }
- public void Clean()
- {
- var SceneGameObjects = SceneManager.GetActiveScene().GetRootGameObjects();
- var Dependencies = EditorUtility.CollectDependencies(SceneGameObjects);
- var AssetsToRemove = new List<UnityEngine.Object>();
- var SubAssets = GetSubAssets();
- foreach (var TheObject in SubAssets)
- {
- if (!Dependencies.Contains(TheObject))
- {
- AssetsToRemove.Add(TheObject);
- }
- }
- foreach (var TheObject in AssetsToRemove)
- {
- AssetDatabase.RemoveObjectFromAsset(TheObject);
- //if you call DestroyImmediate on an object with the name "ABC" and later try
- //to create another object with the same name, you will get the following error:
- //"The object of type '...' has been destroyed but you are still trying to access it."
- //DestroyImmediate(TheObject, true);
- }
- //calling SaveAssets() automatically does an import on dirty assets
- //so there's no need to call ImportAsset()
- AssetDatabase.SaveAssets();
- }
- }
- }
- }
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Text.RegularExpressions;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using UnityEditor;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- namespace TerraLab
- {
- public class LayoutCSS
- {
- public LayoutCSS(EditorWindow Instance)
- {
- TheWindow = Instance;
- DefaultRowSpace = RowSpace = 5;
- OSFontNames = Font.GetOSInstalledFontNames();
- foreach (var TheFont in Resources.FindObjectsOfTypeAll<Font>())
- {
- BuiltInFonts[TheFont.name] = TheFont;
- }
- }
- public Font GetFont(string FontName)
- {
- FontName = FontName ?? "";
- if (!FontCache.TryGetValue(FontName, out Font TheFont) && OSFontNames.Contains(FontName))
- {
- TheFont = FontCache[FontName] = Font.CreateDynamicFontFromOSFont(FontName, 16);
- }
- return TheFont;
- }
- public Font GetBuiltInFont(string FontName)
- {
- return BuiltInFonts[FontName ?? ""];
- }
- private int LineHeightToFontSize(int LineHeight)
- {
- return (int)Math.Ceiling(LineHeight / LineHeightCoefficient);
- }
- private int FontSizeToLineHeight(int FontSize)
- {
- return (int)Math.Floor(FontSize * LineHeightCoefficient);
- }
- private float GetHeight(GUIStyle TheStyle)
- {
- return (float)Math.Ceiling(TheStyle.CalcSize(GUIContent.none).y);
- }
- private class MinMax
- {
- public MinMax(MinMax Existing = null)
- {
- if (Existing != null)
- {
- MinWidth = Existing.MinWidth;
- MaxWidth = Existing.MaxWidth;
- MinHeight = Existing.MinHeight;
- MaxHeight = Existing.MaxHeight;
- }
- }
- public float MinWidth = -1;
- public float MaxWidth = -1;
- public float MinHeight = -1;
- public float MaxHeight = -1;
- public GUILayoutOption[] ToOptionsArray()
- {
- var OptionsList = new List<GUILayoutOption>();
- if (MinWidth >= 0)
- {
- OptionsList.Add(GUILayout.MinWidth(MinWidth));
- }
- if (MaxWidth >= 0)
- {
- OptionsList.Add(GUILayout.MaxWidth(MaxWidth));
- }
- if (MinHeight >= 0)
- {
- OptionsList.Add(GUILayout.MinHeight(MinHeight));
- }
- if (MaxHeight >= 0)
- {
- OptionsList.Add(GUILayout.MaxHeight(MaxHeight));
- }
- return OptionsList.ToArray();
- }
- }
- public void ResetLargestWidth()
- {
- LargestWidth = 0;
- }
- public void SetDefaultRowSpace(int pixels)
- {
- DefaultRowSpace = pixels;
- }
- public void StartRowSpace(int pixels = -1)
- {
- RowSpace = (pixels >= 0) ? pixels : DefaultRowSpace;
- HorizontalJustEnded = false;
- }
- public void EndRowSpace()
- {
- RowSpace = -1;
- HorizontalJustEnded = false;
- }
- private int RowSpace;
- private int DefaultRowSpace;
- private string[] OSFontNames;
- private EditorWindow TheWindow;
- private int DefaultFontSize = 14;
- private bool HorizontalJustEnded = false;
- //the maximum unity font size is 500, and the default line height at this size is 574
- private float LineHeightCoefficient = 1.148F;
- private Tuple<GUIStyle, MinMax> BoxStyle;
- private Tuple<GUIStyle, MinMax> ButtonStyle;
- private Tuple<GUIStyle, MinMax> LabelStyle;
- private Tuple<GUIStyle, MinMax> TextAreaStyle;
- private Tuple<GUIStyle, MinMax> TextFieldStyle;
- private Tuple<GUIStyle, MinMax> ToggleStyle;
- private Tuple<GUIStyle, MinMax> DropdownStyle;
- private Tuple<GUIStyle, MinMax> HorizontalStyle;
- private Tuple<GUIStyle, MinMax> VerticalStyle;
- private Tuple<GUIStyle, MinMax> ToolbarStyle;
- public float LargestWidth { get; private set; } = 0;
- private Dictionary<string, Font> FontCache = new Dictionary<string, Font>();
- private Dictionary<string, Font> BuiltInFonts = new Dictionary<string, Font>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> BoxStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> ButtonStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> LabelStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> TextAreaStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> TextFieldStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> ToggleStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> DropdownStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> HorizontalStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> VerticalStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- private Dictionary<string, Tuple<GUIStyle, MinMax>> ToolbarStyleCache = new Dictionary<string, Tuple<GUIStyle, MinMax>>();
- public GUIStyle SetCommonProperties(GUIStyle TheStyle)
- {
- var NewStyle = new GUIStyle(TheStyle);
- NewStyle.overflow = new RectOffset(0, 0, 0, 0);
- NewStyle.stretchWidth = false;
- return NewStyle;
- }
- public void SetBoxStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, BoxStyleCache, out MinMax OptionsOut, out BoxStyle);
- }
- public void SetButtonStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, ButtonStyleCache, out MinMax OptionsOut, out ButtonStyle);
- }
- public void SetLabelStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, LabelStyleCache, out MinMax OptionsOut, out LabelStyle);
- }
- public void SetTextAreaStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, TextAreaStyleCache, out MinMax OptionsOut, out TextAreaStyle);
- }
- public void SetTextFieldStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, TextFieldStyleCache, out MinMax OptionsOut, out TextFieldStyle);
- }
- public void SetToggleStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, ToggleStyleCache, out MinMax OptionsOut, out ToggleStyle);
- }
- public void SetDropdownStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, DropdownStyleCache, out MinMax OptionsOut, out DropdownStyle);
- }
- public void SetHorizontalStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, HorizontalStyleCache, out MinMax OptionsOut, out HorizontalStyle);
- }
- public void SetVerticalStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, VerticalStyleCache, out MinMax OptionsOut, out VerticalStyle);
- }
- public void SetToolbarStyle(GUIStyle DefaultStyle, string CSSText = null, Texture2D BackgroundImage = null)
- {
- TextToGUIStyle(SetCommonProperties(DefaultStyle), null, CSSText, BackgroundImage, ToolbarStyleCache, out MinMax OptionsOut, out ToolbarStyle);
- }
- //############################
- public void Box(GUIContent content, out Rect ControlRect)
- {
- Box(content, null, null, out ControlRect);
- }
- public void Box(GUIContent content, string CSSText, out Rect ControlRect)
- {
- Box(content, CSSText, null, out ControlRect);
- }
- public void Box(GUIContent content, string CSSText = null, Texture2D BackgroundImage = null)
- {
- Box(content, CSSText, BackgroundImage, out _);
- }
- public void Box(GUIContent content, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var TheStyle = TextToGUIStyle(BoxStyle.Item1, BoxStyle.Item2, CSSText, BackgroundImage, BoxStyleCache, out MinMax Options);
- GUILayout.Box(content, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Box);
- HorizontalJustEnded = false;
- }
- public void Box(string text, out Rect ControlRect)
- {
- Box(text, null, null, out ControlRect);
- }
- public void Box(string text, string CSSText, out Rect ControlRect)
- {
- Box(text, CSSText, null, out ControlRect);
- }
- public void Box(string text, string CSSText = null, Texture2D BackgroundImage = null)
- {
- Box(text, CSSText, BackgroundImage, out _);
- }
- public void Box(string text, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- text = Regex.Replace(text ?? "", "\\s*$", "");
- var TheStyle = TextToGUIStyle(BoxStyle.Item1, BoxStyle.Item2, CSSText, BackgroundImage, BoxStyleCache, out MinMax Options);
- GUILayout.Box(text, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Box);
- HorizontalJustEnded = false;
- }
- public void Box(Texture image, out Rect ControlRect)
- {
- Box(image, null, null, out ControlRect);
- }
- public void Box(Texture image, string CSSText, out Rect ControlRect)
- {
- Box(image, CSSText, null, out ControlRect);
- }
- public void Box(Texture image, string CSSText = null, Texture2D BackgroundImage = null)
- {
- Box(image, CSSText, BackgroundImage, out _);
- }
- public void Box(Texture image, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var TheStyle = TextToGUIStyle(BoxStyle.Item1, BoxStyle.Item2, CSSText, BackgroundImage, BoxStyleCache, out MinMax Options);
- GUILayout.Box(image, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Box);
- HorizontalJustEnded = false;
- }
- //############################
- public bool Button(GUIContent content, out Rect ControlRect)
- {
- return Button(content, null, null, out ControlRect);
- }
- public bool Button(GUIContent content, string CSSText, out Rect ControlRect)
- {
- return Button(content, CSSText, null, out ControlRect);
- }
- public bool Button(GUIContent content, string CSSText = null, Texture2D BackgroundImage = null)
- {
- return Button(content, CSSText, BackgroundImage, out _);
- }
- public bool Button(GUIContent content, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var TheStyle = TextToGUIStyle(ButtonStyle.Item1, ButtonStyle.Item2, CSSText, BackgroundImage, ButtonStyleCache, out MinMax Options);
- var result = GUILayout.Button(content, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Button);
- HorizontalJustEnded = false;
- return result;
- }
- public bool Button(string text, out Rect ControlRect)
- {
- return Button(text, null, null, out ControlRect);
- }
- public bool Button(string text, string CSSText, out Rect ControlRect)
- {
- return Button(text, CSSText, null, out ControlRect);
- }
- public bool Button(string text, string CSSText = null, Texture2D BackgroundImage = null)
- {
- return Button(text, CSSText, BackgroundImage, out _);
- }
- public bool Button(string text, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- text = Regex.Replace(text ?? "", "\\s*$", "");
- var TheStyle = TextToGUIStyle(ButtonStyle.Item1, ButtonStyle.Item2, CSSText, BackgroundImage, ButtonStyleCache, out MinMax Options);
- if (Options.MinHeight >= 0)
- {
- //there is a bug where if wordWrap=true and a MinHeight is set, the MinHeight value will clip the content
- Options = new MinMax(Options);
- Options.MinHeight = TheStyle.wordWrap ? -1 : Math.Max(Options.MinHeight, GetHeight(TheStyle));
- }
- var result = GUILayout.Button(text, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Button);
- HorizontalJustEnded = false;
- return result;
- }
- public bool Button(Texture image, out Rect ControlRect)
- {
- return Button(image, null, null, out ControlRect);
- }
- public bool Button(Texture image, string CSSText, out Rect ControlRect)
- {
- return Button(image, CSSText, null, out ControlRect);
- }
- public bool Button(Texture image, string CSSText = null, Texture2D BackgroundImage = null)
- {
- return Button(image, CSSText, BackgroundImage, out _);
- }
- public bool Button(Texture image, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var TheStyle = TextToGUIStyle(ButtonStyle.Item1, ButtonStyle.Item2, CSSText, BackgroundImage, ButtonStyleCache, out MinMax Options);
- var result = GUILayout.Button(image, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Button);
- HorizontalJustEnded = false;
- return result;
- }
- //############################
- public void Label(GUIContent content, out Rect ControlRect)
- {
- Label(content, null, null, out ControlRect);
- }
- public void Label(GUIContent content, string CSSText, out Rect ControlRect)
- {
- Label(content, CSSText, null, out ControlRect);
- }
- public void Label(GUIContent content, string CSSText = null, Texture2D BackgroundImage = null)
- {
- Label(content, CSSText, BackgroundImage, out _);
- }
- public void Label(GUIContent content, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var TheStyle = TextToGUIStyle(LabelStyle.Item1, LabelStyle.Item2, CSSText, BackgroundImage, LabelStyleCache, out MinMax Options);
- GUILayout.Label(content, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Label);
- HorizontalJustEnded = false;
- }
- public void Label(string text, out Rect ControlRect)
- {
- Label(text, null, null, out ControlRect);
- }
- public void Label(string text, string CSSText, out Rect ControlRect)
- {
- Label(text, CSSText, null, out ControlRect);
- }
- public void Label(string text, string CSSText = null, Texture2D BackgroundImage = null)
- {
- Label(text, CSSText, BackgroundImage, out _);
- }
- public void Label(string text, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- text = Regex.Replace(text ?? "", "\\s*$", "");
- var TheStyle = TextToGUIStyle(LabelStyle.Item1, LabelStyle.Item2, CSSText, BackgroundImage, LabelStyleCache, out MinMax Options);
- if ((text ?? "").Length == 1 && TheStyle.fixedWidth == 0 && !TheStyle.stretchWidth)
- {
- TheStyle = new GUIStyle(TheStyle);
- TheStyle.fixedWidth = TheStyle.CalcSize(new GUIContent("%")).x;
- }
- if (Options.MinHeight >= 0)
- {
- //there is a bug where if wordWrap=true and a MinHeight is set, the MinHeight value will clip the content
- Options = new MinMax(Options);
- Options.MinHeight = TheStyle.wordWrap ? -1 : Math.Max(Options.MinHeight, GetHeight(TheStyle));
- }
- GUILayout.Label(text, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Label);
- HorizontalJustEnded = false;
- }
- public void Label(Texture image, out Rect ControlRect)
- {
- Label(image, null, null, out ControlRect);
- }
- public void Label(Texture image, string CSSText, out Rect ControlRect)
- {
- Label(image, CSSText, null, out ControlRect);
- }
- public void Label(Texture image, string CSSText = null, Texture2D BackgroundImage = null)
- {
- Label(image, CSSText, BackgroundImage, out _);
- }
- public void Label(Texture image, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var TheStyle = TextToGUIStyle(LabelStyle.Item1, LabelStyle.Item2, CSSText, BackgroundImage, LabelStyleCache, out MinMax Options);
- GUILayout.Label(image, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Label);
- HorizontalJustEnded = false;
- }
- //############################
- public string TextArea(string text, out Rect ControlRect)
- {
- return TextArea(text, null, null, out ControlRect);
- }
- public string TextArea(string text, string CSSText, out Rect ControlRect)
- {
- return TextArea(text, CSSText, null, out ControlRect);
- }
- public string TextArea(string text, string CSSText = null, Texture2D BackgroundImage = null)
- {
- return TextArea(text, CSSText, BackgroundImage, out _);
- }
- public string TextArea(string text, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var TheStyle = TextToGUIStyle(TextAreaStyle.Item1, TextAreaStyle.Item2, CSSText, BackgroundImage, TextAreaStyleCache, out MinMax Options);
- if (Options.MinHeight >= 0)
- {
- //there is a bug where if wordWrap=true and a MinHeight is set, the MinHeight value will clip the content
- Options = new MinMax(Options);
- Options.MinHeight = TheStyle.wordWrap ? -1 : Math.Max(Options.MinHeight, GetHeight(TheStyle));
- }
- var result = GUILayout.TextArea(text, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.TextArea);
- HorizontalJustEnded = false;
- return result;
- }
- //############################
- public string TextField(string text, out Rect ControlRect)
- {
- return TextField(text, null, null, out ControlRect);
- }
- public string TextField(string text, string CSSText, out Rect ControlRect)
- {
- return TextField(text, CSSText, null, out ControlRect);
- }
- public string TextField(string text, string CSSText = null, Texture2D BackgroundImage = null)
- {
- return TextField(text, CSSText, BackgroundImage, out _);
- }
- public string TextField(string text, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var TheStyle = TextToGUIStyle(TextFieldStyle.Item1, TextFieldStyle.Item2, CSSText, BackgroundImage, TextFieldStyleCache, out MinMax Options);
- if (Options.MinHeight >= 0)
- {
- //there is a bug where if wordWrap=true and a MinHeight is set, the MinHeight value will clip the content
- Options = new MinMax(Options);
- Options.MinHeight = TheStyle.wordWrap ? -1 : Math.Max(Options.MinHeight, GetHeight(TheStyle));
- }
- var result = GUILayout.TextField(text, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.TextField);
- HorizontalJustEnded = false;
- return result;
- }
- //############################
- public bool Toggle(bool value, out Rect ControlRect)
- {
- return Toggle(value, null, null, out ControlRect);
- }
- public bool Toggle(bool value, string CSSText, out Rect ControlRect)
- {
- return Toggle(value, CSSText, null, out ControlRect);
- }
- public bool Toggle(bool value, string CSSText = null, Texture2D BackgroundImage = null)
- {
- return Toggle(value, CSSText, BackgroundImage, out _);
- }
- public bool Toggle(bool value, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var TheStyle = TextToGUIStyle(ToggleStyle.Item1, ToggleStyle.Item2, CSSText, BackgroundImage, ToggleStyleCache, out MinMax Options);
- var result = GUILayout.Toggle(value, (string)null, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Toggle);
- HorizontalJustEnded = false;
- return result;
- }
- //############################
- public T Dropdown<T>(T options, out Rect ControlRect) where T : Enum
- {
- return Dropdown(options, null, null, out ControlRect);
- }
- public T Dropdown<T>(T options, string CSSText, out Rect ControlRect) where T : Enum
- {
- return Dropdown(options, CSSText, null, out ControlRect);
- }
- public T Dropdown<T>(T options, string CSSText = null, Texture2D BackgroundImage = null) where T : Enum
- {
- return Dropdown(options, CSSText, BackgroundImage, out _);
- }
- public T Dropdown<T>(T options, string CSSText, Texture2D BackgroundImage, out Rect ControlRect) where T : Enum
- {
- var TheStyle = TextToGUIStyle(DropdownStyle.Item1, DropdownStyle.Item2, CSSText, BackgroundImage, DropdownStyleCache, out MinMax Options);
- var result = (T)EditorGUILayout.EnumPopup(options, TheStyle, Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Dropdown);
- HorizontalJustEnded = false;
- return result;
- }
- //############################
- public Texture2D TextureField(Texture2D texture, string text = null, float width = -1, float height = -1)
- {
- return TextureField(texture, text, width, height, out _);
- }
- public Texture2D TextureField(Texture2D texture, string text, out Rect ControlRect)
- {
- return TextureField(texture, text, -1, -1, out ControlRect);
- }
- public Texture2D TextureField(Texture2D texture, string text, float width, float height, out Rect ControlRect)
- {
- var lengthX = (width >= 0) ? width : 80;
- var lengthY = (height >= 0) ? height : 80;
- BeginVertical("margin:0;border:0;padding:0;stretch-width:false;");
- if (text != null)
- {
- Label(text, "margin:0px 4px;width:" + lengthX + "px;height:0px;vertical-align:top;text-align:center;");
- }
- var TheTexture = (Texture2D)EditorGUILayout.ObjectField(texture, typeof(Texture2D), false, new GUILayoutOption[] { GUILayout.Width(lengthX), GUILayout.Height(lengthY) });
- EndVertical();
- ControlRect = GetLastRect(ControlTypes.ObjectField);
- HorizontalJustEnded = false;
- return TheTexture;
- }
- //############################
- public int Toolbar(int selected, GUIContent[] contents, out Rect ControlRect)
- {
- return Toolbar(selected, contents, null, null, out ControlRect);
- }
- public int Toolbar(int selected, GUIContent[] contents, string CSSText, out Rect ControlRect)
- {
- return Toolbar(selected, contents, CSSText, null, out ControlRect);
- }
- public int Toolbar(int selected, GUIContent[] contents, string CSSText = null, Texture2D BackgroundImage = null)
- {
- return Toolbar(selected, contents, CSSText, BackgroundImage, out _);
- }
- public int Toolbar(int selected, GUIContent[] contents, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var result = GUILayout.Toolbar(selected, contents, TextToGUIStyle(ToolbarStyle.Item1, ToolbarStyle.Item2, CSSText, BackgroundImage, ToolbarStyleCache, out MinMax Options), Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Toolbar);
- HorizontalJustEnded = false;
- return result;
- }
- public int Toolbar(int selected, string[] texts, out Rect ControlRect)
- {
- return Toolbar(selected, texts, null, null, out ControlRect);
- }
- public int Toolbar(int selected, string[] texts, string CSSText, out Rect ControlRect)
- {
- return Toolbar(selected, texts, CSSText, null, out ControlRect);
- }
- public int Toolbar(int selected, string[] texts, string CSSText = null, Texture2D BackgroundImage = null)
- {
- return Toolbar(selected, texts, CSSText, BackgroundImage, out _);
- }
- public int Toolbar(int selected, string[] texts, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var result = GUILayout.Toolbar(selected, texts, TextToGUIStyle(ToolbarStyle.Item1, ToolbarStyle.Item2, CSSText, BackgroundImage, ToolbarStyleCache, out MinMax Options), Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Toolbar);
- HorizontalJustEnded = false;
- return result;
- }
- public int Toolbar(int selected, Texture[] images, out Rect ControlRect)
- {
- return Toolbar(selected, images, null, null, out ControlRect);
- }
- public int Toolbar(int selected, Texture[] images, string CSSText, out Rect ControlRect)
- {
- return Toolbar(selected, images, CSSText, null, out ControlRect);
- }
- public int Toolbar(int selected, Texture[] images, string CSSText = null, Texture2D BackgroundImage = null)
- {
- return Toolbar(selected, images, CSSText, BackgroundImage, out _);
- }
- public int Toolbar(int selected, Texture[] images, string CSSText, Texture2D BackgroundImage, out Rect ControlRect)
- {
- var result = GUILayout.Toolbar(selected, images, TextToGUIStyle(ToolbarStyle.Item1, ToolbarStyle.Item2, CSSText, BackgroundImage, ToolbarStyleCache, out MinMax Options), Options.ToOptionsArray());
- ControlRect = GetLastRect(ControlTypes.Toolbar);
- HorizontalJustEnded = false;
- return result;
- }
- //############################
- public void BeginHorizontal(string CSSText = null, Texture2D BackgroundImage = null)
- {
- if (RowSpace > 0 && HorizontalJustEnded)
- {
- GUILayout.Space(RowSpace);
- }
- var TheStyle = TextToGUIStyle(HorizontalStyle.Item1, HorizontalStyle.Item2, CSSText, BackgroundImage, HorizontalStyleCache, out MinMax Options);
- GUILayout.BeginHorizontal(TheStyle, Options.ToOptionsArray());
- NestedWidths.Insert(0, TheStyle.fixedWidth);
- HorizontalJustEnded = false;
- }
- public void EndHorizontal()
- {
- EndHorizontal(out _);
- }
- public void EndHorizontal(out Rect ControlRect)
- {
- GUILayout.EndHorizontal();
- NestedWidths.RemoveAt(0);
- ControlRect = GetLastRect(ControlTypes.Horizontal);
- HorizontalJustEnded = true;
- }
- //############################
- public void BeginVertical(string CSSText = null, Texture2D BackgroundImage = null)
- {
- var TheStyle = TextToGUIStyle(VerticalStyle.Item1, VerticalStyle.Item2, CSSText, BackgroundImage, VerticalStyleCache, out MinMax Options);
- GUILayout.BeginVertical(TheStyle, Options.ToOptionsArray());
- NestedWidths.Insert(0, TheStyle.fixedWidth);
- HorizontalJustEnded = false;
- }
- public void EndVertical()
- {
- EndVertical(out _);
- }
- public void EndVertical(out Rect ControlRect)
- {
- GUILayout.EndVertical();
- NestedWidths.RemoveAt(0);
- ControlRect = GetLastRect(ControlTypes.Vertical);
- HorizontalJustEnded = false;
- }
- //############################
- private int ControlNum = 0;
- private bool ClearControlCaches = false;
- private bool ControlTypesConsistent = true;
- private List<Rect> RectCache = new List<Rect>();
- private List<ControlTypes> ControlTypeCache = new List<ControlTypes>();
- private List<float> NestedWidths = new List<float>();
- private EventType LastEventType = EventType.Layout;
- private enum ControlTypes
- {
- None = 0,
- Box = 1,
- Button = 2,
- Label = 3,
- TextArea = 4,
- TextField = 5,
- Toggle = 6,
- Dropdown = 7,
- Horizontal = 8,
- Vertical = 9,
- Toolbar = 10,
- ObjectField = 11
- }
- private Rect GetLastRect()
- {
- return GetLastRect(ControlTypes.None);
- }
- private Rect GetLastRect(ControlTypes ControlType)
- {
- if (Event.current.type != LastEventType)
- {
- ControlNum = 0;
- ResetLargestWidth();
- ControlTypesConsistent = true;
- if (LastEventType == EventType.Layout)
- {
- //repaint so controls aren't slow to refresh their positions
- TheWindow.Repaint();
- }
- }
- Rect TheRect;
- if (Event.current.type == EventType.Repaint)
- {
- TheRect = GUILayoutUtility.GetLastRect();
- if (ClearControlCaches)
- {
- RectCache.Clear();
- ControlTypeCache.Clear();
- ClearControlCaches = false;
- }
- if (RectCache.Count < 1000)
- {
- RectCache.Add(TheRect);
- ControlTypeCache.Add(ControlType);
- }
- }
- else
- {
- ClearControlCaches = true;
- if (ControlNum < RectCache.Count && ControlType == ControlTypeCache[ControlNum] && ControlTypesConsistent)
- {
- TheRect = RectCache[ControlNum];
- }
- else
- {
- //Debug.Log("inconsistent");
- ControlTypesConsistent = false;
- TheRect = new Rect();
- }
- }
- ControlNum++;
- LastEventType = Event.current.type;
- LargestWidth = Math.Max(TheRect.width, LargestWidth);
- return TheRect;
- }
- //############################
- private Dictionary<string, float> FloatCache = new Dictionary<string, float>();
- private float GetFloatVal(string str)
- {
- if (FloatCache.TryGetValue(str, out float value))
- {
- return value;
- }
- else if (float.TryParse(str, out value))
- {
- return FloatCache[str] = value;
- }
- else
- {
- return default;
- }
- }
- private Dictionary<string, int> IntCache = new Dictionary<string, int>();
- private int GetIntVal(string str)
- {
- if (IntCache.TryGetValue(str, out int value))
- {
- return value;
- }
- else if (int.TryParse(str, out value))
- {
- return IntCache[str] = value;
- }
- else
- {
- return default;
- }
- }
- private bool IsColorChannel(string str, out float value)
- {
- value = GetFloatVal(str);
- return value >= 0 && value <= 255;
- }
- private bool IsAlphaChannel(string str, out float value)
- {
- value = GetFloatVal(str);
- return value >= 0 && value <= 1;
- }
- private Dictionary<string, string> TextToCSSDictionary(string CSSText)
- {
- var TheDictionary = new Dictionary<string, string>();
- var Matches = Regex.Matches(CSSText, "(?<=\\G|^)\\s*([a-zA-Z0-9-_]+)\\s*:\\s*((?:[^:;'\\s]|\\s(?![\\s;])|'(?:[^\\\\']|\\\\.)*')*)\\s*(?:;|$)");
- foreach (Match TheMatch in Matches)
- {
- TheDictionary[TheMatch.Groups[1].Value.ToLower()] = TheMatch.Groups[2].Value;
- }
- return TheDictionary;
- }
- private GUIStyle TextToGUIStyle(GUIStyle DefaultStyle, MinMax OptionsIn, string CSSText, Texture2D BackgroundImage, Dictionary<string, Tuple<GUIStyle, MinMax>> GUIStyleCache, out MinMax OptionsOut)
- {
- return TextToGUIStyle(DefaultStyle, OptionsIn, CSSText, BackgroundImage, GUIStyleCache, out OptionsOut, out _);
- }
- private GUIStyle TextToGUIStyle(GUIStyle DefaultStyle, MinMax OptionsIn, string CSSText, Texture2D BackgroundImage, Dictionary<string, Tuple<GUIStyle, MinMax>> GUIStyleCache, out MinMax OptionsOut, out Tuple<GUIStyle, MinMax> TheTuple)
- {
- CSSText = CSSText ?? "";
- if (BackgroundImage == null && GUIStyleCache != null)
- {
- if (!GUIStyleCache.TryGetValue(CSSText, out TheTuple))
- {
- TheTuple = new Tuple<GUIStyle, MinMax>(DictionaryToGUIStyle(DefaultStyle, OptionsIn, TextToCSSDictionary(CSSText), out OptionsOut), OptionsOut);
- GUIStyleCache[CSSText] = TheTuple;
- }
- }
- else
- {
- TheTuple = new Tuple<GUIStyle, MinMax>(DictionaryToGUIStyle(DefaultStyle, OptionsIn, TextToCSSDictionary(CSSText), out OptionsOut), OptionsOut);
- if (BackgroundImage != null)
- {
- ApplyBackgroundImage(TheTuple.Item1, BackgroundImage);
- }
- }
- OptionsOut = TheTuple.Item2;
- return TheTuple.Item1;
- }
- private void ApplyBackgroundImage(GUIStyle TheStyle, Texture2D BackgroundImage)
- {
- TheStyle.active.background = BackgroundImage;
- TheStyle.focused.background = BackgroundImage;
- TheStyle.hover.background = BackgroundImage;
- TheStyle.normal.background = BackgroundImage;
- }
- private GUIStyle DictionaryToGUIStyle(GUIStyle DefaultStyle, MinMax OptionsIn, Dictionary<string, string> CSSDictionary, out MinMax OptionsOut)
- {
- //active.background---------
- //active.textColor---------
- //focused.background---------
- //focused.textColor---------
- //hover.background---------
- //hover.textColor---------
- //normal.background---------
- //normal.textColor---------
- //onActivebackground---------
- //onActive.textColor---------
- //onFocusedbackground---------
- //onFocused.textColor---------
- //onHoverbackground---------
- //onHover.textColor---------
- //onNormalbackground---------
- //onNormal.textColor---------
- //border---------
- //alignment---------
- //clipping---------
- //--contentOffset
- //fixedHeight---------
- //fixedWidth---------
- //font---------
- //fontSize---------
- //fontStyle
- //--imagePosition
- //--lineHeight
- //margin---------
- //--name
- //overflow---------
- //padding---------
- //--richText
- //--stretchHeight
- //--stretchWidth
- //wordWrap---------
- var TheStyle = new GUIStyle(DefaultStyle);
- OptionsOut = new MinMax(OptionsIn);
- var HeightSet = false;
- var MinHeightSet = false;
- string Key, Val;
- string[] FontFallbacks = null;
- var FontSize = -1;
- var LineHeight = -1;
- Match TheMatch;
- MatchCollection TheMatches;
- Color TheColor;
- Texture2D TheTexture;
- int Top, Right, Bottom, Left, i;
- float FloatVal, R, G, B, A;
- bool IsValid;
- bool AlignedTop, AlignedMiddle, AlignedLower, AlignedLeft, AlignedCenter, AlignedRight;
- GroupCollection Groups;
- var OutlineKeys = new[] {
- "border-width",
- "border-top-width",
- "border-right-width",
- "border-bottom-width",
- "border-left-width",
- "border",
- "border-top",
- "border-right",
- "border-bottom",
- "border-left",
- "padding",
- "padding-top",
- "padding-right",
- "padding-bottom",
- "padding-left",
- "margin",
- "margin-top",
- "margin-right",
- "margin-bottom",
- "margin-left"
- };
- foreach (var Item in CSSDictionary)
- {
- Key = Item.Key;
- Val = Item.Value;
- IsValid = false;
- TheColor = Color.clear;
- Top = Right = Bottom = Left = 0;
- if (Key == "background-color" || Key == "color")
- {
- if ((TheMatch = Regex.Match(Val, "^rgba?\\(\\s*(-?(?:[0-9]+|[0-9]*\\.[0-9]+))\\s*,\\s*(-?(?:[0-9]+|[0-9]*\\.[0-9]+))\\s*,\\s*(-?(?:[0-9]+|[0-9]*\\.[0-9]+))\\s*,\\s*(-?(?:[0-9]+|[0-9]*\\.[0-9]+))\\s*\\)$", RegexOptions.IgnoreCase)).Success)
- {
- Groups = TheMatch.Groups;
- if (IsColorChannel(Groups[1].Value, out R) && IsColorChannel(Groups[2].Value, out G) && IsColorChannel(Groups[3].Value, out B) && IsAlphaChannel(Groups[4].Value, out A))
- {
- IsValid = true;
- TheColor = new Color(R / 255, G / 255, B / 255, A);
- }
- }
- else if ((TheMatch = Regex.Match(Val, "^rgba?\\(\\s*(-?(?:[0-9]+|[0-9]*\\.[0-9]+))\\s*,\\s*(-?(?:[0-9]+|[0-9]*\\.[0-9]+))\\s*,\\s*(-?(?:[0-9]+|[0-9]*\\.[0-9]+))\\s*\\)$", RegexOptions.IgnoreCase)).Success)
- {
- Groups = TheMatch.Groups;
- if (IsColorChannel(Groups[1].Value, out R) && IsColorChannel(Groups[2].Value, out G) && IsColorChannel(Groups[3].Value, out B))
- {
- IsValid = true;
- TheColor = new Color(R / 255, G / 255, B / 255);
- }
- }
- if (IsValid)
- {
- if (Key == "background-color")
- {
- TheTexture = TerraLabHelpers.GetSolidTexture(TheColor, 1, 1);
- TheStyle.active.background = TheTexture;
- TheStyle.focused.background = TheTexture;
- TheStyle.hover.background = TheTexture;
- TheStyle.normal.background = TheTexture;
- }
- else
- {
- TheStyle.active.textColor = TheColor;
- TheStyle.focused.textColor = TheColor;
- TheStyle.hover.textColor = TheColor;
- TheStyle.normal.textColor = TheColor;
- }
- }
- }
- else if (OutlineKeys.Contains(Key))
- {
- if ((TheMatch = Regex.Match(Val, "^(-?(?:[0-9]+|[0-9]*\\.[0-9]+))(?:px)?(?:\\s+(-?(?:[0-9]+|[0-9]*\\.[0-9]+))(?:px)?(?:\\s+(-?(?:[0-9]+|[0-9]*\\.[0-9]+))(?:px)?\\s+(-?(?:[0-9]+|[0-9]*\\.[0-9]+))(?:px)?)?)?$", RegexOptions.IgnoreCase)).Success)
- {
- IsValid = true;
- Groups = TheMatch.Groups;
- if (String.IsNullOrEmpty(Groups[2].Value))
- {
- //is single value
- Top = GetIntVal(Groups[1].Value);
- Right = GetIntVal(Groups[1].Value);
- Bottom = GetIntVal(Groups[1].Value);
- Left = GetIntVal(Groups[1].Value);
- }
- else if (String.IsNullOrEmpty(Groups[3].Value) || String.IsNullOrEmpty(Groups[4].Value))
- {
- //is two-value shorthand
- Top = GetIntVal(Groups[1].Value);
- Right = GetIntVal(Groups[2].Value);
- Bottom = GetIntVal(Groups[1].Value);
- Left = GetIntVal(Groups[2].Value);
- }
- else
- {
- //is four-value
- Top = GetIntVal(Groups[1].Value);
- Right = GetIntVal(Groups[2].Value);
- Bottom = GetIntVal(Groups[3].Value);
- Left = GetIntVal(Groups[4].Value);
- }
- }
- if (IsValid)
- {
- if (Key.IndexOf("border") > -1)
- {
- if (Key == "border" || Key == "border-width" || Key.IndexOf("-top") > -1)
- {
- TheStyle.border.top = Top;
- }
- if (Key == "border" || Key == "border-width" || Key.IndexOf("-right") > -1)
- {
- TheStyle.border.right = Right;
- }
- if (Key == "border" || Key == "border-width" || Key.IndexOf("-bottom") > -1)
- {
- TheStyle.border.bottom = Bottom;
- }
- if (Key == "border" || Key == "border-width" || Key.IndexOf("-left") > -1)
- {
- TheStyle.border.left = Left;
- }
- }
- else if (Key.IndexOf("padding") > -1)
- {
- if (Key == "padding" || Key.IndexOf("-top") > -1)
- {
- TheStyle.padding.top = Top;
- }
- if (Key == "padding" || Key.IndexOf("-right") > -1)
- {
- TheStyle.padding.right = Right;
- }
- if (Key == "padding" || Key.IndexOf("-bottom") > -1)
- {
- TheStyle.padding.bottom = Bottom;
- }
- if (Key == "padding" || Key.IndexOf("-left") > -1)
- {
- TheStyle.padding.left = Left;
- }
- }
- else if (Key.IndexOf("margin") > -1)
- {
- if (Key == "margin" || Key.IndexOf("-top") > -1)
- {
- TheStyle.margin.top = Top;
- }
- if (Key == "margin" || Key.IndexOf("-right") > -1)
- {
- TheStyle.margin.right = Right;
- }
- if (Key == "margin" || Key.IndexOf("-bottom") > -1)
- {
- TheStyle.margin.bottom = Bottom;
- }
- if (Key == "margin" || Key.IndexOf("-left") > -1)
- {
- TheStyle.margin.left = Left;
- }
- }
- }
- }
- else if (Key == "text-align")
- {
- if (Val == "left" || Val == "center" || Val == "right")
- {
- AlignedTop = TheStyle.alignment == TextAnchor.UpperLeft || TheStyle.alignment == TextAnchor.UpperCenter || TheStyle.alignment == TextAnchor.UpperRight;
- AlignedMiddle = TheStyle.alignment == TextAnchor.MiddleLeft || TheStyle.alignment == TextAnchor.MiddleCenter || TheStyle.alignment == TextAnchor.MiddleRight;
- AlignedLower = TheStyle.alignment == TextAnchor.LowerLeft || TheStyle.alignment == TextAnchor.LowerCenter || TheStyle.alignment == TextAnchor.LowerRight;
- if (Val == "left")
- {
- TheStyle.alignment = AlignedTop ? TextAnchor.UpperLeft : (AlignedMiddle ? TextAnchor.MiddleLeft : TextAnchor.LowerLeft);
- }
- else if (Val == "center")
- {
- TheStyle.alignment = AlignedTop ? TextAnchor.UpperCenter : (AlignedMiddle ? TextAnchor.MiddleCenter : TextAnchor.LowerCenter);
- }
- else if (Val == "right")
- {
- TheStyle.alignment = AlignedTop ? TextAnchor.UpperRight : (AlignedMiddle ? TextAnchor.MiddleRight : TextAnchor.LowerRight);
- }
- }
- }
- else if (Key == "vertical-align")
- {
- if (Val == "top" || Val == "middle" || Val == "bottom")
- {
- AlignedLeft = TheStyle.alignment == TextAnchor.UpperLeft || TheStyle.alignment == TextAnchor.MiddleLeft || TheStyle.alignment == TextAnchor.LowerLeft;
- AlignedCenter = TheStyle.alignment == TextAnchor.UpperCenter || TheStyle.alignment == TextAnchor.MiddleCenter || TheStyle.alignment == TextAnchor.LowerCenter;
- AlignedRight = TheStyle.alignment == TextAnchor.UpperRight || TheStyle.alignment == TextAnchor.MiddleRight || TheStyle.alignment == TextAnchor.LowerRight;
- if (Val == "top")
- {
- TheStyle.alignment = AlignedLeft ? TextAnchor.UpperLeft : (AlignedCenter ? TextAnchor.UpperCenter : TextAnchor.UpperRight);
- }
- else if (Val == "middle")
- {
- TheStyle.alignment = AlignedLeft ? TextAnchor.MiddleLeft : (AlignedCenter ? TextAnchor.MiddleCenter : TextAnchor.MiddleRight);
- }
- else if (Val == "bottom")
- {
- TheStyle.alignment = AlignedLeft ? TextAnchor.LowerLeft : (AlignedCenter ? TextAnchor.LowerCenter : TextAnchor.LowerRight);
- }
- }
- }
- else if (Key == "overflow")
- {
- if (Val == "visible")
- {
- TheStyle.clipping = TextClipping.Overflow;
- }
- else if (Val == "hidden")
- {
- TheStyle.clipping = TextClipping.Clip;
- }
- }
- else if (Key == "stretch-width")
- {
- TheStyle.stretchWidth = (Val == "true");
- }
- else if (Key == "stretch-height")
- {
- TheStyle.stretchHeight = (Val == "true");
- }
- else if (Key == "white-space")
- {
- TheStyle.wordWrap = (Val != "nowrap");
- }
- else if (Key == "image-position")
- {
- if (Val == "image-left")
- {
- TheStyle.imagePosition = ImagePosition.ImageLeft;
- }
- else if (Val == "image-above")
- {
- TheStyle.imagePosition = ImagePosition.ImageAbove;
- }
- else if (Val == "image-only")
- {
- TheStyle.imagePosition = ImagePosition.ImageOnly;
- }
- else if (Val == "text-only")
- {
- TheStyle.imagePosition = ImagePosition.TextOnly;
- }
- }
- else if (Key == "line-height" || Key == "font-size")
- {
- if ((TheMatch = Regex.Match(Val, "(-?(?:[0-9]+|[0-9]*\\.[0-9]+))(px|%)?", RegexOptions.IgnoreCase)).Success)
- {
- Groups = TheMatch.Groups;
- if (Groups[2].Value == "%")
- {
- throw new Exception("percentage widths are not supported: '" + Val + "'");
- }
- FloatVal = GetFloatVal(Groups[1].Value);
- if (Key == "line-height")
- {
- LineHeight = (int)FloatVal;
- }
- else if (Key == "font-size")
- {
- FontSize = (int)FloatVal;
- }
- }
- }
- else if (Key == "font-family")
- {
- TheMatches = Regex.Matches(Val, "(?:^|\\G\\s*,)\\s*'((?:[^\\\\']|\\\\.)*)'");
- FontFallbacks = new string[TheMatches.Count];
- i = 0;
- foreach (Match fontMatch in TheMatches)
- {
- Groups = fontMatch.Groups;
- FontFallbacks[i] = Groups[1].Value;
- i++;
- }
- }
- }
- if (FontSize >= 0)
- {
- TheStyle.fontSize = FontSize;
- }
- else
- {
- FontSize = DefaultFontSize;
- }
- if (LineHeight < 0)
- {
- LineHeight = FontSizeToLineHeight(FontSize);
- }
- if (FontFallbacks != null)
- {
- Font TheFont = null;
- foreach (var FallbackName in FontFallbacks)
- {
- if ((TheFont = GetFont(FallbackName)) != null)
- {
- break;
- }
- }
- TheStyle.font = TheFont;
- }
- bool IsPercentage;
- float NearestSetWidth = 0;
- foreach (var fixedWidth in NestedWidths)
- {
- if (fixedWidth > 0)
- {
- NearestSetWidth = fixedWidth;
- break;
- }
- }
- var TextSize = GetHeight(TheStyle);
- foreach (var Item in CSSDictionary)
- {
- Key = Item.Key;
- Val = Item.Value;
- if (Key == "width" || Key == "height" || Key == "min-width" || Key == "max-width" || Key == "min-height" || Key == "max-height")
- {
- if ((TheMatch = Regex.Match(Val, "^(?:(-?(?:[0-9]+|[0-9]*\\.[0-9]+))(px|%)?|text)$", RegexOptions.IgnoreCase)).Success)
- {
- IsPercentage = false;
- Groups = TheMatch.Groups;
- if (Groups[2].Value == "%")
- {
- IsPercentage = true;
- //throw new Exception("percentage widths are not supported: '" + Val + "'");
- }
- if (TheMatch.Value == "text")
- {
- FloatVal = TextSize;
- }
- else
- {
- FloatVal = GetFloatVal(Groups[1].Value);
- }
- if (Key == "width")
- {
- FloatVal = IsPercentage ? (FloatVal * 0.01F * NearestSetWidth) : FloatVal;
- TheStyle.fixedWidth = FloatVal;
- }
- else if (Key == "height")
- {
- HeightSet = true;
- TheStyle.fixedHeight = FloatVal;
- }
- else if (Key == "min-width")
- {
- FloatVal = IsPercentage ? (FloatVal * 0.01F * NearestSetWidth) : FloatVal;
- OptionsOut.MinWidth = FloatVal;
- }
- else if (Key == "max-width")
- {
- OptionsOut.MaxWidth = FloatVal;
- }
- else if (Key == "min-height")
- {
- MinHeightSet = true;
- OptionsOut.MinHeight = FloatVal;
- }
- else if (Key == "max-height")
- {
- OptionsOut.MaxHeight = FloatVal;
- }
- }
- }
- }
- return TheStyle;
- }
- }
- }
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Text.RegularExpressions;
- using System.Reflection;
- using UnityEditor;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- namespace TerraLab
- {
- public static class TerraLabHelpers
- {
- private static Dictionary<string, Texture2D> SolidTextureCache = new Dictionary<string, Texture2D>();
- private static Dictionary<string, Texture2D> GridTextureCache = new Dictionary<string, Texture2D>();
- private static bool DelayApply = false;
- public static GUIStyle SetBackgroundColor(this GUIStyle TheStyle, Color TheColor, double alpha = -1, double light = -1)
- {
- return TheStyle.SetBackgroundColor(TheColor.r, TheColor.g, TheColor.b, alpha, light);
- }
- public static GUIStyle SetBackgroundColor(this GUIStyle TheStyle, double r, double g, double b, double alpha = -1, double light = -1)
- {
- var NewStyle = new GUIStyle(TheStyle);
- var TheTexture = GetSolidTexture(r, g, b, alpha, light);
- NewStyle.normal.background = TheTexture;
- NewStyle.focused.background = TheTexture;
- NewStyle.active.background = TheTexture;
- NewStyle.hover.background = TheTexture;
- return NewStyle;
- }
- public static Texture2D GetSolidTexture(Color TheColor, int width = -1, int height = -1)
- {
- return GetSolidTexture(TheColor.r, TheColor.g, TheColor.b, TheColor.a, 0.5, width = -1, height = -1);
- }
- public static Texture2D GetSolidTexture(Color TheColor, double alpha = -1, double light = -1, int width = -1, int height = -1)
- {
- return GetSolidTexture(TheColor.r, TheColor.g, TheColor.b, alpha, light, width, height);
- }
- public static Texture2D GetSolidTexture(double r, double g, double b, double alpha = -1, double light = -1, int width = -1, int height = -1)
- {
- alpha = (alpha < 0) ? 1 : Math.Min(alpha, 1);
- width = (width < 0) ? 32 : width;
- height = (height < 0) ? 32 : height;
- if (light >= 0 && light < 0.5)
- {
- r = r * (2 * light);
- g = g * (2 * light);
- b = b * (2 * light);
- }
- else if (light <= 1 && light > 0.5)
- {
- r = r + ((1 - r) * ((2 * light) - 1));
- g = g + ((1 - g) * ((2 * light) - 1));
- b = b + ((1 - b) * ((2 * light) - 1));
- }
- var Key = r + "," + g + "," + b + "," + alpha + "," + light + "," + width + "," + height;
- if (SolidTextureCache.TryGetValue(Key, out Texture2D TheTexture))
- {
- return TheTexture;
- }
- else
- {
- TheTexture = new Texture2D(width, height);
- for (var x = 0; x < width; x++)
- {
- for (var y = 0; y < height; y++)
- {
- TheTexture.SetPixel(x, y, new Color((float)r, (float)g, (float)b, (float)alpha));
- }
- }
- if (!DelayApply)
- {
- TheTexture.Apply();
- }
- SolidTextureCache.Add(Key, TheTexture);
- return TheTexture;
- }
- }
- public static Texture2D GetWhiteGridTexture(Color TheColor, int width = -1, int height = -1)
- {
- return GetWhiteGridTexture(TheColor.r, TheColor.g, TheColor.b, TheColor.a, 0.5, width, height);
- }
- public static Texture2D GetWhiteGridTexture(Color TheColor, double alpha = -1, double light = -1, int width = -1, int height = -1)
- {
- return GetWhiteGridTexture(TheColor.r, TheColor.g, TheColor.b, alpha, light, width, height);
- }
- public static Texture2D GetWhiteGridTexture(double r, double g, double b, double alpha = -1, double light = -1, int width = -1, int height = -1)
- {
- var Key = r + "," + g + "," + b + "," + alpha + "," + light + "," + width + "," + height;
- if (GridTextureCache.TryGetValue(Key, out Texture2D TheTexture))
- {
- return TheTexture;
- }
- else
- {
- DelayApply = true;
- TheTexture = GetSolidTexture(r, g, b, alpha, light, width, height);
- DelayApply = false;
- for (var y = 0; y < TheTexture.height; y++)
- {
- TheTexture.SetPixel(0, y, Color.white);
- }
- for (var x = 0; x < TheTexture.width; x++)
- {
- TheTexture.SetPixel(x, TheTexture.height - 1, Color.white);
- }
- TheTexture.Apply();
- GridTextureCache.Add(Key, TheTexture);
- return TheTexture;
- }
- }
- }
- }
- using System;
- using System.IO;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Reflection;
- namespace TerraLab
- {
- public static class GenericHelpers
- {
- //EXTENSIONS
- public static long ToUtcUnixTimeSeconds(this DateTime obj)
- {
- return ((DateTimeOffset)DateTime.SpecifyKind(obj, DateTimeKind.Utc)).ToUnixTimeSeconds();
- }
- //METHODS
- public static bool empty<T>(T val, bool TrueIfEmptyArray = true)
- {
- //this method returns true if val is null, an empty string, or an array with no elements
- //the optional parameter TrueIfEmptyArray lets you control whether to return true if val is an empty array
- if (is_null(val))
- {
- return true;
- }
- else if (val.GetType() == typeof(string))
- {
- return (val as string) == "";
- }
- else if (TrueIfEmptyArray && is_enumerable(val, out IEnumerable the_enumerable))
- {
- foreach (var the_element in the_enumerable)
- {
- return false;
- }
- return true;
- }
- return false;
- }
- public static bool is_null<T>(T val)
- {
- //this method returns null if val is null
- return is_null(val, out bool is_nullable);
- }
- public static bool is_null<T>(T val, out bool is_nullable)
- {
- //this method returns null if val is null
- //the out parameter is_nullable returns whether val was even nullable to begin with
- return ((is_nullable = (default(T) == null)) && EqualityComparer<T>.Default.Equals(val, default(T)));
- }
- public static bool is_enumerable<T>(T val)
- {
- //this method returns true if val implements IEnumerable
- return is_enumerable(val, out IEnumerable the_enumerable);
- }
- public static bool is_enumerable<T>(T val, out IEnumerable the_enumerable)
- {
- //this method returns true if val implements IEnumerable
- //the out parameter returns val cast as an IEnumerable
- return (the_enumerable = val as IEnumerable) != null;
- }
- public static bool value_or_string<T>(T val)
- {
- //this method returns true if val is a primitive, a value type, or is a string
- return is_null(val) ? true : value_or_string(val.GetType());
- }
- public static bool value_or_string(Type the_type)
- {
- //this method returns true if the_type is a primitive type, a value type, or is a string type
- return (the_type.IsPrimitive || the_type.IsValueType || the_type == typeof(string)) && the_type.GetGenericArguments().Length == 0;
- }
- public static Type[] GetTypesInNamespace(string Namespace)
- {
- //this method takes a namespace and returns an array of all the types/classes defined within it
- var SelectedTypes = new List<Type>();
- foreach (var TheType in Assembly.GetExecutingAssembly().GetTypes())
- {
- if (TheType.Namespace == Namespace)
- {
- SelectedTypes.Add(TheType);
- }
- }
- return SelectedTypes.ToArray();
- }
- public static Type[] GetAssignableTypes(Type ParentType, bool CurrentAssemblyOnly = false)
- {
- //this method takes a parent type and lists all the classes that can be cast to it
- var SelectedTypes = new List<Type>();
- if (CurrentAssemblyOnly)
- {
- SelectedTypes.AddRange(Assembly.GetExecutingAssembly().GetTypes().Where(x => ParentType.IsAssignableFrom(x) && x != ParentType));
- }
- else
- {
- foreach (var TheAssembly in AppDomain.CurrentDomain.GetAssemblies())
- {
- SelectedTypes.AddRange(TheAssembly.GetTypes().Where(x => ParentType.IsAssignableFrom(x) && x != ParentType));
- }
- }
- return SelectedTypes.ToArray();
- }
- public static string regex_mirror_replace(string SearchPattern, string Replacement, string SearchString, string ChangeString)
- {
- //this method replaces characters in "ChangeString" based on the location of matches found in "SearchString"
- //the length of "ChangeString" must match the length of "SearchString" for it to work
- //SearchPattern - the pattern to look for in the "mirror" string
- //SearchString - the "mirror" string to be searched
- //Replacement - the text to replace whatever was found by SearchPattern
- //ChangeString - the actual string that will be changed based on matches found in SearchString (the "mirror" string)
- string Str;
- int StrPos;
- int StrLen;
- string NewStr;
- ChangeString = ChangeString ?? "";
- SearchString = SearchString ?? "";
- if (SearchString.Length != ChangeString.Length)
- {
- throw new Exception("regex_mirror_replace error: SearchString and ChangeString are different lengths (" + SearchString.Length + " versus " + ChangeString.Length + ").");
- }
- var Matches = Regex.Matches(SearchString, SearchPattern);
- var Offset = 0;
- foreach (Match TheMatch in Matches)
- {
- Str = TheMatch.Value;
- StrPos = TheMatch.Index;
- StrLen = Str.Length;
- NewStr = Regex.Replace(Str, "^(.*)$", Replacement, RegexOptions.Singleline);
- ChangeString = ChangeString.Substring(0, StrPos + Offset) + NewStr + ChangeString.Substring(StrPos + StrLen + Offset);
- Offset = Offset + (NewStr.Length - StrLen);
- }
- return ChangeString;
- }
- public static string mirror_no_strings(string input, string RepeatChar = " ")
- {
- //this takes a string with quoted statements in it and replaces the statements with spaces
- //for example, the following string:
- //SELECT * FROM MYTABLE WHERE DESC = 'fresh'" AND ID > 5
- //becomes:
- //SELECT * FROM MYTABLE WHERE DESC = ' '" AND ID > 5
- return regex_repeat_string("\"(?:[^\\\\\"]|\\\\.)*\"|'(?:[^\\\\']|\\\\.)*'", RepeatChar, input, false, RegexOptions.Singleline);
- }
- public static string regex_repeat_string(string Pattern, string RepeatChar, string input, bool KeepMatchEndChars = false, RegexOptions Options = RegexOptions.None)
- {
- //this method takes a string (input) and searches for a regular expression (pattern)
- //for every match that is found, it replaces it with a string (RepeatChar) that is repeated as many times as the match is long
- //e.g. regex_repeat_string("a[bc]+", "4", "azbdacloabbl") returns "azbd44lo444l"
- //KeepMatchEndChars tells the method to not replace the end chars of the matches it finds (the previous example would return "azbdacloa4bl")
- //KeepMatchEndChars is helpful when you're using the method on, for example, an SQL string with string literals in it, and you want to see where the quotes were
- //it's useful when you want to parse SQL or other code where string literals might interfere with your parsing algorithm
- //regex_repeat_string("\"(?:[^\\\\\"]|\\\\.)*\"|'(?:[^\\\\']|\\\\.)*'", " ", "SELECT * FROM MYTABLE WHERE DESC = 'fresh and delicious'", true)
- //returns "SELECT * FROM MYTABLE WHERE DESC = ' '" (notice how the 'fresh and delicious' string is the same length as before, but just replaced with spaces)
- var ReplacePattern = KeepMatchEndChars ? "(?<=.).(?=.)" : ".";
- input = Regex.Replace(input, Pattern, delegate (Match TheMatch)
- {
- return Regex.Replace(TheMatch.Value, ReplacePattern, RepeatChar, RegexOptions.Singleline);
- }, Options);
- return input;
- }
- public static bool IsPowerOfTwo(int x)
- {
- return (x != 0) && ((x & (x - 1)) == 0);
- }
- public static bool IsInteger(decimal input)
- {
- //this method returns true if the decimal is a whole number
- return (input % 1) == 0;
- }
- public static string PadLeft<T>(T x, char repeatChar, int length)
- {
- var str = (x == null) ? "" : x.ToString();
- return new String(repeatChar, length - str.Length) + str;
- }
- public static string PadRight<T>(T x, char repeatChar, int length)
- {
- var str = (x == null) ? "" : x.ToString();
- return str + new String(repeatChar, length - str.Length);
- }
- public static string AddCommas(string input)
- {
- //this adds the thousands comma to a number (e.g. 1000 becomes 1,000)
- if (!decimal.TryParse(input, out decimal value))
- {
- throw new Exception("AddCommas error: input must be numeric");
- }
- return AddCommas(value);
- }
- public static string AddCommas(decimal input)
- {
- //this adds the thousands comma to a number (e.g. 1000 becomes 1,000)
- var decimals = Regex.Replace(input.ToString(), "^[^.]*\\.?", "").Length;
- return String.Format("{0:n" + decimals + "}", input);
- }
- public static byte[] ObjectToByteArray(object obj)
- {
- byte[] Result;
- var TheFormatter = new BinaryFormatter();
- using (var TheStream = new MemoryStream())
- {
- TheFormatter.Serialize(TheStream, obj);
- Result = TheStream.ToArray();
- }
- return Result;
- }
- public static object ByteArrayToObject(byte[] bytes)
- {
- object Result;
- var TheFormatter = new BinaryFormatter();
- using (var TheStream = new MemoryStream(bytes))
- {
- Result = TheFormatter.Deserialize(TheStream);
- }
- return Result;
- }
- public static string MemoryToBase64(object obj)
- {
- //this method takes an object from memory and encodes it into a Base64 string
- return Base64Encode(ObjectToByteArray(obj));
- }
- public static object Base64ToMemory(string base64EncodedData)
- {
- //this method takes a Base64 string and decodes it to an object in memory
- return ByteArrayToObject(Base64DecodeToBytes(base64EncodedData));
- }
- public static string Base64Encode(string plainText)
- {
- //this method takes a string and encodes it into a Base64 string
- return is_null(plainText) ? null : Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
- }
- public static string Base64Encode(byte[] bytes)
- {
- //this method takes a byte array and encodes it into a Base64 string
- return is_null(bytes) ? null : Convert.ToBase64String(bytes);
- }
- public static string Base64DecodeToString(string base64EncodedData)
- {
- //this method takes a Base64 string and decodes it to a string
- return is_null(base64EncodedData) ? null : Encoding.UTF8.GetString(Convert.FromBase64String(base64EncodedData));
- }
- public static byte[] Base64DecodeToBytes(string base64EncodedData)
- {
- //this method takes a Base64 string and decodes it to a byte array
- return is_null(base64EncodedData) ? null : Convert.FromBase64String(base64EncodedData);
- }
- }
- }
Add Comment
Please, Sign In to add comment