void ShowUnitError() { if (!GenericInfoPopup.HasAnyInfo()) { GenericInfoPopup.ShowInfo("No unit selected!"); } }
public void Export() { var paths = StandaloneFileBrowser.SaveFilePanel("Export types", DefaultPath, "types", extensions); if (paths == null || string.IsNullOrEmpty(paths)) { return; } Texture2D exportTexture = new Texture2D(TerrainTypeData2D.GetLength(0), TerrainTypeData2D.GetLength(1), TextureFormat.RGB24, false); Color32[] pixels = new Color32[exportTexture.width * exportTexture.height]; for (int x = 0; x < exportTexture.width; x++) { for (int y = 0; y < exportTexture.width; y++) { int PixelId = x + y * exportTexture.width; pixels[PixelId] = new Color32(TerrainTypeData2D[x, y], 0, 0, 255); } } exportTexture.SetPixels32(pixels); exportTexture.Apply(); byte[] data = exportTexture.EncodeToPNG(); File.WriteAllBytes(paths, data); EnvPaths.SetLastPath(ExportPathKey, Path.GetDirectoryName(paths)); GenericInfoPopup.ShowInfo("Types export success!\n" + Path.GetFileName(paths)); }
private void Awake() { if (grp) { Current = this; } }
void DuplicateAction() { if (gameObject.activeSelf) { DuplicateData = GetUnitsStorage(); if (DuplicateData != null && DuplicateData.Units.Length > 0) { if (FirstSelected == null) { ShowGroupError(); return; } Undo.RegisterUndo(new UndoHistory.HistoryUnitsRemove(), new UndoHistory.HistoryUnitsRemove.UnitsRemoveParam(new SaveLua.Army.UnitsGroup[] { FirstSelected.Source })); GameObject[] CreatedUnits = ReadUnitsStorage(DuplicateData); if (CreatedUnits.Length > 0) { FirstSelected.Refresh(); GoToSelection(); SelectionManager.Current.SelectObjects(CreatedUnits); GenericInfoPopup.ShowInfo("Pasted " + CreatedUnits.Length + " units."); } } } }
void ShowGroupError() { if (!GenericInfoPopup.HasAnyInfo()) { GenericInfoPopup.ShowInfo("No unit group selected!"); } }
public void ImportMarkers() { var extensions = new[] { new ExtensionFilter("Faf Markers", "fafmapmarkers") }; var paths = StandaloneFileBrowser.OpenFilePanel("Import markers", DefaultPath, extensions, false); if (paths.Length > 0 && !string.IsNullOrEmpty(paths[0])) { ExportMarkers ImpMarkers = JsonUtility.FromJson <ExportMarkers>(System.IO.File.ReadAllText(paths[0])); bool AnyCreated = false; int mc = 0; MapLua.SaveLua.Marker[] CreatedMarkers = new MapLua.SaveLua.Marker[ImpMarkers.Markers.Length]; for (int m = 0; m < ImpMarkers.Markers.Length; m++) { if (!AnyCreated) { Undo.Current.RegisterMarkersAdd(); } AnyCreated = true; if (SelectionManager.Current.SnapToGrid) { ImpMarkers.Markers[m].Pos = ScmapEditor.SnapToGridCenter(ImpMarkers.Markers[m].Pos, true, SelectionManager.Current.SnapToWater); } MapLua.SaveLua.Marker NewMarker = new MapLua.SaveLua.Marker(ImpMarkers.Markers[m].MarkerType); CreatedMarkers[m] = NewMarker; NewMarker.position = ScmapEditor.WorldPosToScmap(ImpMarkers.Markers[m].Pos); NewMarker.orientation = ImpMarkers.Markers[m].Rot.eulerAngles; MarkersControler.CreateMarker(NewMarker, mc); ChainsList.AddToCurrentChain(NewMarker); MapLuaParser.Current.SaveLuaFile.Data.MasterChains[mc].Markers.Add(NewMarker); } for (int m = 0; m < ImpMarkers.Markers.Length; m++) { CreatedMarkers[m].AdjacentToMarker = new List <MapLua.SaveLua.Marker>(); for (int c = 0; c < ImpMarkers.Markers[m].Connected.Length; c++) { CreatedMarkers[m].AdjacentToMarker.Add(CreatedMarkers[ImpMarkers.Markers[m].Connected[c]]); } } RenderMarkersConnections.Current.UpdateConnections(); EnvPaths.SetLastPath(ExportPathKey, System.IO.Path.GetDirectoryName(paths[0])); GenericInfoPopup.ShowInfo("Markers imported"); } }
private void Awake() { if (grp) { Current = this; } if (!Started && InfoStrings.Count > 0) { StartNextInfoPopup(); } }
public void Save() { if (string.IsNullOrEmpty(PathField.text)) { GenericInfoPopup.ShowInfo("Game installation path can't be empty!"); } else { EnvPaths.SetInstalationPath(PathField.text); } if (string.IsNullOrEmpty(MapsPathField.text)) { GenericInfoPopup.ShowInfo("Maps folder path can't be empty!"); } else { EnvPaths.SetMapsPath(MapsPathField.text); } EnvPaths.SetBackupPath(BackupPathField.text); PlayerPrefs.SetInt(UndoHistory, (int)HistorySlider.value); if (History) { History.MaxHistoryLength = (int)HistorySlider.value; } PlayerPrefs.SetInt("PlayMap_Faction", PlayAs.value); PlayerPrefs.SetInt("PlayMap_FogOfWar", FogOfWar.isOn ? 1 : 0); if (GetMarkers2D() != Markers2D.isOn) { if (Markers2D.isOn) { } else { Markers.MarkersControler.ForceResetMarkers2D(); } PlayerPrefs.SetInt("Markers_2D", Markers2D.isOn ? 1 : 0); } if (GetHeightmapClamp() != HeightmapClamp.isOn) { PlayerPrefs.SetInt("Heightmap_Clamp", HeightmapClamp.isOn ? 1 : 0); } PlayerPrefs.SetFloat("UiScale", UiScale.value); PlayerPrefs.Save(); gameObject.SetActive(false); }
public void ExportSelectedMarkers() { var extensions = new[] { new ExtensionFilter("Faf Markers", "fafmapmarkers") }; var paths = StandaloneFileBrowser.SaveFilePanel("Export markers", DefaultPath, "", extensions); if (!string.IsNullOrEmpty(paths)) { ExportMarkers ExpMarkers = new ExportMarkers(); ExpMarkers.MapWidth = ScmapEditor.Current.map.Width; ExpMarkers.MapHeight = ScmapEditor.Current.map.Height; List <MapLua.SaveLua.Marker> SelectedObjects = new List <MapLua.SaveLua.Marker>(); for (int i = 0; i < SelectionManager.Current.Selection.Ids.Count; i++) { SelectedObjects.Add(SelectionManager.Current.AffectedGameObjects[SelectionManager.Current.Selection.Ids[i]].GetComponent <MarkerObject>().Owner); } ExpMarkers.Markers = new ExportMarkers.ExportMarker[SelectedObjects.Count]; for (int i = 0; i < ExpMarkers.Markers.Length; i++) { ExpMarkers.Markers[i] = new ExportMarkers.ExportMarker(); ExpMarkers.Markers[i].MarkerType = SelectedObjects[i].MarkerType; ExpMarkers.Markers[i].Pos = SelectedObjects[i].MarkerObj.Tr.localPosition; ExpMarkers.Markers[i].Rot = SelectedObjects[i].MarkerObj.Tr.localRotation; List <int> Connected = new List <int>(); for (int c = 0; c < SelectedObjects[i].AdjacentToMarker.Count; c++) { if (SelectedObjects.Contains(SelectedObjects[i].AdjacentToMarker[c])) { Connected.Add(SelectedObjects.IndexOf(SelectedObjects[i].AdjacentToMarker[c])); } } ExpMarkers.Markers[i].Connected = Connected.ToArray(); } System.IO.File.WriteAllText(paths, JsonUtility.ToJson(ExpMarkers)); EnvPaths.SetLastPath(ExportPathKey, System.IO.Path.GetDirectoryName(paths)); GenericInfoPopup.ShowInfo("Markers exported"); } }
public void ExportHeightmap() { //string Filename = EnvPaths.GetMapsPath() + MapLuaParser.Current.FolderName + "/heightmap.raw"; //string Filename = EnvPaths.GetMapsPath() + MapLuaParser.Current.FolderName + "/heightmap.raw"; var extensions = new[] { new ExtensionFilter("Heightmap", new string[] { "raw" }), new ExtensionFilter("WM Heightmap", new string[] { "r16" }) //new ExtensionFilter("Stratum mask", "raw, bmp") }; var paths = StandaloneFileBrowser.SaveFilePanel("Export heightmap", DefaultPath, "heightmap", extensions); if (paths == null || string.IsNullOrEmpty(paths)) { return; } int h = ScmapEditor.Current.Teren.terrainData.heightmapResolution; int w = ScmapEditor.Current.Teren.terrainData.heightmapResolution; float[,] data = ScmapEditor.Current.Teren.terrainData.GetHeights(0, 0, w, h); using (BinaryWriter writer = new BinaryWriter(new System.IO.FileStream(paths, System.IO.FileMode.Create))) { for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { // float v = (float)(((double)reader.ReadUInt16() - 0.5) / (double)HeightConversion); << Import ushort ThisPixel = (ushort)(data[h - (y + 1), x] * ScmapEditor.HeightResize); writer.Write(System.BitConverter.GetBytes(ThisPixel)); } } writer.Close(); } EnvPaths.SetLastPath(ExportPathKey, System.IO.Path.GetDirectoryName(paths)); GenericInfoPopup.ShowInfo("Heightmap export success!\n" + System.IO.Path.GetFileName(paths)); }
IEnumerator _GenerateShoreline() { var ts = System.TimeSpan.FromTicks(System.DateTime.Now.Ticks); //Load data heights = ScmapEditor.Heights; heightmapWidth = ScmapEditor.HeightmapWidth; heightmapHeight = ScmapEditor.HeightmapHeight; terrainSizeX = ScmapEditor.Current.Teren.terrainData.size.x; terrainSizeY = ScmapEditor.Current.Teren.terrainData.size.y; terrainSizeZ = ScmapEditor.Current.Teren.terrainData.size.z; worldWaterLevel = ScmapEditor.GetWaterLevel(); waterLevel = worldWaterLevel / terrainSizeY; //Clear ShoreLines.Clear(); allEdges.Clear(); thread = new Thread(ThreadWork); thread.Priority = System.Threading.ThreadPriority.AboveNormal; thread.IsBackground = false; thread.Start(); while (thread.IsAlive) { yield return(null); } thread = null; //ThreadWork(); //yield return null; //Clear heights = null; allEdges.Clear(); ShoreLineTask = null; IsShoreLineGenerated = true; GenericInfoPopup.ShowInfo("Shoreline generated in " + (System.TimeSpan.FromTicks(System.DateTime.Now.Ticks).TotalSeconds - ts.TotalSeconds).ToString("F4") + "s"); //Debug.Log("Shoreline generated in time: " + (System.TimeSpan.FromTicks(System.DateTime.Now.Ticks).TotalSeconds - ts.TotalSeconds).ToString("F4")); }
public static void SetMapsPath(string value) { value = value.Replace("\\", "/"); if (value[value.Length - 1].ToString() != "/") { value += "/"; } if (value[0].ToString() == "/") { value = value.Remove(0, 1); } PlayerPrefs.SetString(MapsPath, value); if (!System.IO.Directory.Exists(value)) { GenericInfoPopup.ShowInfo("Wrong maps path!\nCheck preferences."); } }
public void ImportUnits() { if (FirstSelected == null) { ShowGroupError(); return; } var paths = StandaloneFileBrowser.OpenFilePanel("Import Units", DefaultPath, extensions, false); if (paths.Length == 0 || string.IsNullOrEmpty(paths[0])) { return; } string data = File.ReadAllText(paths[0]); UnitsStorage Data = JsonUtility.FromJson <UnitsStorage>(data); if (Data == null || Data.Units == null || Data.Units.Length == 0) { return; } Undo.RegisterUndo(new UndoHistory.HistoryUnitsRemove(), new UndoHistory.HistoryUnitsRemove.UnitsRemoveParam(new SaveLua.Army.UnitsGroup[] { FirstSelected.Source })); GameObject[] CreatedUnits = ReadUnitsStorage(Data); if (CreatedUnits.Length > 0) { FirstSelected.Refresh(); GoToSelection(); SelectionManager.Current.SelectObjects(CreatedUnits); GenericInfoPopup.ShowInfo("Imported " + CreatedUnits.Length + " units."); } }
public void ExportUnits() { GameObject[] Objs = SelectionManager.Current.GetAllSelectedObjects(false); if (SelectionManager.Current.Selection.Ids.Count <= 0) { GenericInfoPopup.ShowInfo("No units selected"); return; } var path = StandaloneFileBrowser.SaveFilePanel("Export Units", DefaultPath, "", extensions); if (string.IsNullOrEmpty(path)) { return; } UnitsStorage Data = GetUnitsStorage(); string DataString = JsonUtility.ToJson(Data, true); File.WriteAllText(path, DataString); EnvPaths.SetLastPath(ExportPathKey, Path.GetDirectoryName(path)); }
public static void SetInstalationPath(string value) { value = value.Replace("\\", "/"); if (value[value.Length - 1].ToString() != "/") { value += "/"; } if (value[0].ToString() == "/") { value = value.Remove(0, 1); } if (value.ToLower().EndsWith(InstalationGamedata)) { value = value.Remove(value.Length - InstalationGamedata.Length); } PlayerPrefs.SetString(InstalationPath, value); if (!System.IO.Directory.Exists(value)) { GenericInfoPopup.ShowInfo("Wrong game installation path!\nCheck preferences."); } }
public void LoadStratumScdTextures(bool Loading = true) { // Load Stratum Textures Paths bool NormalMapFix = false; for (int i = 0; i < Textures.Length; i++) { if (Loading) { MapLuaParser.Current.InfoPopup.Show(true, "Loading map...\n( Stratum textures " + (i + 1) + " )"); if (i >= map.Layers.Count) { map.Layers.Add(new Layer()); } Textures[i].AlbedoPath = GetGamedataFile.FixMapsPath(map.Layers[i].PathTexture); if (Textures[i].AlbedoPath.StartsWith("/")) { Textures[i].AlbedoPath = Textures[i].AlbedoPath.Remove(0, 1); } Textures[i].AlbedoScale = map.Layers[i].ScaleTexture; if (string.IsNullOrEmpty(map.Layers[i].PathNormalmap)) { if (i == 9) { // Upper stratum normal should be empty! Textures[i].NormalPath = ""; Debug.Log("Clear Upper stratum normal map"); } else { Textures[i].NormalPath = "env/tundra/layers/tund_sandlight_normal.dds"; Debug.Log("Add missing normalmap on stratum " + i); NormalMapFix = true; } } else { if (i == 9) { // Upper stratum normal should be empty! Textures[i].NormalPath = ""; NormalMapFix = true; } else { Textures[i].NormalPath = GetGamedataFile.FixMapsPath(map.Layers[i].PathNormalmap); if (Textures[i].NormalPath.StartsWith("/")) { Textures[i].NormalPath = Textures[i].NormalPath.Remove(0, 1); } } } Textures[i].NormalScale = map.Layers[i].ScaleNormalmap; } /*string Env = GetGamedataFile.EnvScd; * if (GetGamedataFile.IsMapPath(Textures[i].AlbedoPath)) * Env = GetGamedataFile.MapScd;*/ try { Textures[i].AlbedoPath = GetGamedataFile.FindFile(Textures[i].AlbedoPath); //Debug.Log("Found: " + Textures[i].AlbedoPath); GetGamedataFile.LoadTextureFromGamedata(Textures[i].AlbedoPath, i, false); } catch (System.Exception e) { Debug.LogError(i + ", Albedo tex: " + Textures[i].AlbedoPath); Debug.LogError(e); } /*Env = GetGamedataFile.EnvScd; * if (GetGamedataFile.IsMapPath(Textures[i].NormalPath)) * Env = GetGamedataFile.MapScd;*/ try { Textures[i].NormalPath = GetGamedataFile.FindFile(Textures[i].NormalPath); //Debug.Log("Found: " + Textures[i].NormalPath); GetGamedataFile.LoadTextureFromGamedata(Textures[i].NormalPath, i, true); } catch (System.Exception e) { Debug.LogError(i + ", Normal tex: " + Textures[i].NormalPath); Debug.LogError(e); } } if (NormalMapFix) { GenericInfoPopup.ShowInfo("Fixed wrong or missing normalmap textures on stratum layers"); } }
void ReadAllUnits() { FoundUnits.Clear(); IconBackgrounds.Clear(); //ZipFile zf = GetGamedataFile.GetZipFileInstance(GetGamedataFile.UnitsScd); //ZipFile FAF_zf = GetGamedataFile.GetFAFZipFileInstance(GetGamedataFile.UnitsScd); if (!EnvPaths.GamedataExist) { Preferences.Open(); GenericInfoPopup.ShowInfo("Gamedata path not exist!"); return; } IconBackgrounds.Add("land", GetGamedataFile.LoadTexture2D("/textures/ui/common/icons/units/land_up.dds", false, true, true)); IconBackgrounds.Add("amph", GetGamedataFile.LoadTexture2D("/textures/ui/common/icons/units/amph_up.dds", false, true, true)); IconBackgrounds.Add("sea", GetGamedataFile.LoadTexture2D("/textures/ui/common/icons/units/sea_up.dds", false, true, true)); IconBackgrounds.Add("air", GetGamedataFile.LoadTexture2D("/textures/ui/common/icons/units/air_up.dds", false, true, true)); string[] files = GetGamedataFile.GetFilesInPath("units/"); for (int f = 0; f < files.Length; f++) { string LocalName = files[f]; if (LocalName.ToLower().EndsWith("mesh.bp")) { continue; } if (LocalName.ToLower().EndsWith(".bp") && LocalName.Split('/').Length <= 3) { FoundUnits.Add(LocalName); } } /*foreach (ZipEntry zipEntry in zf) * { * if (zipEntry.IsDirectory) * { * continue; * } * * string LocalName = zipEntry.Name; * if (LocalName.ToLower().EndsWith("mesh.bp")) * continue; * * if (LocalName.ToLower().EndsWith(".bp") && LocalName.Split('/').Length <= 3) * { * FoundUnits.Add(LocalName); * } * } * int Count = FoundUnits.Count; * * if (FAF_zf != null) * { * string[] NewFiles = GetGamedataFile.GetNewFafFiles(GetGamedataFile.UnitsScd); * * for (int i = 0; i < NewFiles.Length; i++) * { * string LocalName = NewFiles[i]; * if (LocalName.ToLower().EndsWith("mesh.bp")) * continue; * * if (LocalName.ToLower().EndsWith(".bp")) * { * if (LocalName.Split('/').Length <= 3) // Only from main folder * { * FoundUnits.Add(LocalName); * } * } * } * } * * Debug.Log("Found " + FoundUnits.Count + " units ( FAF: " + (FoundUnits.Count - Count) + ")"); */ Debug.Log("Found " + FoundUnits.Count + " units"); FoundUnits.Sort(); Initialised = true; }
public void ImportHeightmap() { var extensions = new[] { new ExtensionFilter("Heightmap", new string[] { "raw", "r16", "bmp" }) //new ExtensionFilter("Stratum mask", "raw, bmp") }; var paths = StandaloneFileBrowser.OpenFilePanel("Import heightmap", DefaultPath, extensions, false); if (paths == null || paths.Length == 0 || string.IsNullOrEmpty(paths[0])) { return; } int h = ScmapEditor.Current.Teren.terrainData.heightmapHeight; int w = ScmapEditor.Current.Teren.terrainData.heightmapWidth; ScmapEditor.GetAllHeights(ref beginHeights); MapLuaParser.Current.History.RegisterTerrainHeightmapChange(beginHeights); float[,] data = new float[h, w]; //float[,] old = ScmapEditor.Current.Teren.terrainData.GetHeights(0, 0, w, h); if (paths[0].ToLower().EndsWith("bmp")) { BMPLoader loader = new BMPLoader(); BMPImage img = loader.LoadBMP(paths[0]); Debug.Log(img.info.compressionMethod + ", " + img.info.nBitsPerPixel + ", " + img.rMask + ", " + img.imageData[0].r); Texture2D ImportedImage = img.ToTexture2D(); if (ImportedImage.width != h || ImportedImage.height != w) { Debug.Log("Wrong size"); TextureScale.Bilinear(ImportedImage, h, w); ImportedImage.Apply(false); } Color[] ImportedColors = ImportedImage.GetPixels(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { data[y, x] = (float)ImportedColors[x + y * w].r / 0.567f; // 0.58 } } } else { using (var file = System.IO.File.OpenRead(paths[0])) using (var reader = new System.IO.BinaryReader(file)) { for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float v = (float)(((double)reader.ReadUInt16() - 0.5) / (double)HeightConversion); data[h - (y + 1), x] = v; } } } } //ScmapEditor.Current.Teren.terrainData.SetHeights(0, 0, data); ScmapEditor.SetAllHeights(data); RegenerateMaps(); OnTerrainChanged(); EnvPaths.SetLastPath(ExportPathKey, System.IO.Path.GetDirectoryName(paths[0])); GenericInfoPopup.ShowInfo("Heightmap import success!\n" + System.IO.Path.GetFileName(paths[0])); }
IEnumerator LoadingFile() { while (SavingMapProcess) { yield return(null); } Undo.Current.Clear(); bool AllFilesExists = true; string Error = ""; if (!System.IO.Directory.Exists(FolderParentPath)) { Error = "Map folder does not exist:\n" + FolderParentPath; Debug.LogWarning(Error); AllFilesExists = false; } if (AllFilesExists && !System.IO.File.Exists(LoadedMapFolderPath + ScenarioFileName + ".lua")) { AllFilesExists = SearchForScenario(); if (!AllFilesExists) { Error = "Scenario.lua does not exist:\n" + LoadedMapFolderPath + ScenarioFileName + ".lua"; Debug.LogWarning(Error); } } if (AllFilesExists) { string ScenarioText = System.IO.File.ReadAllText(LoadedMapFolderPath + ScenarioFileName + ".lua"); if (!ScenarioText.StartsWith("version = 3") && ScenarioText.StartsWith("version =")) { AllFilesExists = SearchForScenario(); if (!AllFilesExists) { Error = "Wrong scenario file version. Should be 3, is " + ScenarioText.Remove(11).Replace("version =", ""); Debug.LogWarning(Error); } } if (AllFilesExists && !ScenarioText.StartsWith("version = 3")) { AllFilesExists = SearchForScenario(); if (!AllFilesExists) { Error = "Selected file is not a proper scenario.lua file. "; Debug.LogWarning(Error); } } } if (AllFilesExists && !System.IO.File.Exists(EnvPaths.GamedataPath + "/env.scd")) { Error = "No source files in gamedata folder: " + EnvPaths.GamedataPath; Debug.LogWarning(Error); AllFilesExists = false; } if (AllFilesExists) { // Begin load LoadRecentMaps.MoveLastMaps(ScenarioFileName, FolderName, FolderParentPath); LoadingMapProcess = true; InfoPopup.Show(true, "Loading map...\n( " + ScenarioFileName + ".lua" + " )"); EditMenu.gameObject.SetActive(true); Background.SetActive(false); yield return(null); ScenarioLuaFile = new ScenarioLua(); SaveLuaFile = new SaveLua(); TablesLuaFile = new TablesLua(); AsyncOperation ResUn = Resources.UnloadUnusedAssets(); while (!ResUn.isDone) { yield return(null); } // Scenario LUA if (ScenarioLuaFile.Load(FolderName, ScenarioFileName, FolderParentPath)) { //Map Loaded } CameraControler.Current.MapSize = Mathf.Max(ScenarioLuaFile.Data.Size[0], ScenarioLuaFile.Data.Size[1]); CameraControler.Current.RestartCam(); InfoPopup.Show(true, "Loading map...\n(" + ScenarioLuaFile.Data.map + ")"); yield return(null); // SCMAP LoadScmapFile = HeightmapControler.StartCoroutine(ScmapEditor.Current.LoadScmapFile()); yield return(LoadScmapFile); CameraControler.Current.RestartCam(); EditMenu.MapInfoMenu.SaveAsFa.isOn = HeightmapControler.map.VersionMinor >= 60; EditMenu.MapInfoMenu.SaveAsSc.isOn = !EditMenu.MapInfoMenu.SaveAsFa.isOn; InfoPopup.Show(true, "Loading map...\n(" + ScenarioLuaFile.Data.save + ")"); yield return(null); if (loadSave) { // Save LUA SaveLuaFile.Load(); SetSaveLua(); //LoadSaveLua(); yield return(null); Coroutine UnitsLoader = StartCoroutine(SaveLuaFile.LoadUnits()); yield return(UnitsLoader); } //GetGamedataFile.LoadUnit("XEL0209").CreateUnitObject(MapLuaParser.Current.MapCenterPoint, Quaternion.identity); //GetGamedataFile.LoadUnit("UEB0201").CreateUnitObject(MapLuaParser.Current.MapCenterPoint + Vector3.forward * 0.7f, Quaternion.identity); //GetGamedataFile.LoadUnit("UEL0001").CreateUnitObject(MapLuaParser.Current.MapCenterPoint + Vector3.left * 0.3f, Quaternion.identity); /* * //4k Sparkys with GPU instancing * for (int x = 0; x < 63; x++) * { * for(int y = 0; y < 63; y++) * { * Vector3 Pos = MapLuaParser.Current.MapCenterPoint + new Vector3(x * -0.1f, 0, y * -0.1f); * GetGamedataFile.LoadUnit("XEL0209").CreateUnitObject(Pos, Quaternion.identity); * } * } */ // Load Props if (LoadProps) { PropsMenu.gameObject.SetActive(true); PropsMenu.AllowBrushUpdate = false; PropsMenu.StartCoroutine(PropsMenu.LoadProps()); while (PropsMenu.LoadingProps) { InfoPopup.Show(true, "Loading map...\n( Loading props " + PropsMenu.LoadedCount + "/" + ScmapEditor.Current.map.Props.Count + ")"); yield return(null); } PropsMenu.gameObject.SetActive(false); } if (LoadDecals) { DecalsMenu.gameObject.SetActive(true); //DecalsMenu.AllowBrushUpdate = false; DecalsMenu.StartCoroutine(DecalsMenu.LoadDecals()); while (DecalsInfo.LoadingDecals) { InfoPopup.Show(true, "Loading map...\n( Loading decals " + DecalsMenu.LoadedCount + "/" + ScmapEditor.Current.map.Decals.Count + ")"); yield return(null); } DecalsMenu.gameObject.SetActive(false); } if (TablesLuaFile.Load(FolderName, ScenarioFileName, FolderParentPath)) { //Map Loaded } InfoPopup.Show(false); WindowStateSever.WindowStateSaver.ChangeWindowName(FolderName); LoadingMapProcess = false; RenderMarkersConnections.Current.UpdateConnections(); EditMenu.Categorys[0].GetComponent <MapInfo>().UpdateFields(); MapLuaParser.Current.UpdateArea(); GenericInfoPopup.ShowInfo("Map successfully loaded!\n" + FolderName + "/" + ScenarioFileName + ".lua"); } else { ResetUI(); ReturnLoadingWithError(Error); } }
void ReadAllUnits() { FoundUnits.Clear(); IconBackgrounds.Clear(); ZipFile zf = GetGamedataFile.GetZipFileInstance(GetGamedataFile.UnitsScd); ZipFile FAF_zf = GetGamedataFile.GetFAFZipFileInstance(GetGamedataFile.UnitsScd); if (zf == null) { Preferences.Open(); GenericInfoPopup.ShowInfo("Gamedata path not exist!"); return; } IconBackgrounds.Add("land", GetGamedataFile.LoadTexture2DFromGamedata(GetGamedataFile.TexturesScd, "/textures/ui/common/icons/units/land_up.dds", false, true, true)); IconBackgrounds.Add("amph", GetGamedataFile.LoadTexture2DFromGamedata(GetGamedataFile.TexturesScd, "/textures/ui/common/icons/units/amph_up.dds", false, true, true)); IconBackgrounds.Add("sea", GetGamedataFile.LoadTexture2DFromGamedata(GetGamedataFile.TexturesScd, "/textures/ui/common/icons/units/sea_up.dds", false, true, true)); IconBackgrounds.Add("air", GetGamedataFile.LoadTexture2DFromGamedata(GetGamedataFile.TexturesScd, "/textures/ui/common/icons/units/air_up.dds", false, true, true)); foreach (ZipEntry zipEntry in zf) { if (zipEntry.IsDirectory) { continue; } string LocalName = zipEntry.Name; if (LocalName.ToLower().EndsWith("mesh.bp")) { continue; } if (LocalName.ToLower().EndsWith(".bp") && LocalName.Split('/').Length <= 3) { FoundUnits.Add(LocalName); } } int Count = FoundUnits.Count; if (FAF_zf != null) { string[] NewFiles = GetGamedataFile.GetNewFafFiles(GetGamedataFile.UnitsScd); for (int i = 0; i < NewFiles.Length; i++) { string LocalName = NewFiles[i]; if (LocalName.ToLower().EndsWith("mesh.bp")) { continue; } if (LocalName.ToLower().EndsWith(".bp") && LocalName.Split('/').Length <= 3) { FoundUnits.Add(LocalName); } } } Debug.Log("Found " + FoundUnits.Count + " units ( FAF: " + (FoundUnits.Count - Count) + ")"); FoundUnits.Sort(); Initialised = true; }
public void UploadMap() { ErrorText.enabled = false; if (!CheckUserInput()) { return; } string uniqueTempPathInProject = GetUniqueTempPath() + ".zip"; string tempPathForWrapperFolder = GetUniqueTempPath(); FileDirectory.DirectoryCopyWithSourceFolder(MapFolderPathInputField.text, tempPathForWrapperFolder, true); //Move Map Folder into a wrapper folder so map folder lies within the zip try { //Zip everything ZipUtil.CreateZipFromFolder(uniqueTempPathInProject, null, tempPathForWrapperFolder); } catch (Exception e) { OnError("Could not package map. Is the path you entered correct? Exception is:\n" + e.Message); return; } Debug.Log("Writing map to temp file: " + uniqueTempPathInProject); HttpClient httpClient = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); form.Add(new StringContent("{\"isRanked\":" + (RankedToggle.isOn ? "true" : "false") + " }", Encoding.UTF8, "application/json"), "metadata"); FileStream fileStream = new FileStream(uniqueTempPathInProject, FileMode.Open); StreamContent streamContent = new StreamContent(fileStream); streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); form.Add(streamContent, "file", Path.GetFileName(uniqueTempPathInProject)); try { var token = GetAccessTokenFromOwnAuthSvr(); httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.AccessToken); } catch (Exception e) { OnError("Login failed, please check connection and login data. Exception is : \n" + e.Message); return; } httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); try { HttpResponseMessage res = httpClient.PostAsync(Config.ApiUrl + "/maps/upload", form).Result; try { res.EnsureSuccessStatusCode(); } catch (Exception e) { OnError( "JAVA-API complains: \n" + res.Content.ReadAsStringAsync().Result + "\n\nException is: \n" + e.Message); } } catch (Exception e) { OnError("Sending failed. Maybe map is too big... Exception was: \n" + e.Message); } httpClient.Dispose(); form.Dispose(); GenericInfoPopup.ShowInfo("Uploaded Successful... Check the vault to see ;)"); }
public IEnumerator SaveMapProcess() { yield return(null); // Wait for all process to finish while (Markers.MarkersControler.IsUpdating) { yield return(null); } while (PropsRenderer.IsUpdating) { yield return(null); } while (UnitsControler.IsUpdating) { yield return(null); } while (DecalsControler.IsUpdating) { yield return(null); } GenerateBackupPath(); PreviewTex.ForcePreviewMode(true); yield return(null); // Scenario.lua string ScenarioFilePath = LoadedMapFolderPath + ScenarioFileName + ".lua"; if (BackupFiles && System.IO.File.Exists(ScenarioFilePath)) { System.IO.File.Move(ScenarioFilePath, BackupPath + "/" + ScenarioFileName + ".lua"); } ScenarioLuaFile.Save(ScenarioFilePath); yield return(null); //Save.lua string SaveFilePath = MapRelativePath(ScenarioLuaFile.Data.save); string FileName = ScenarioLuaFile.Data.save; string[] Names = FileName.Split(("/").ToCharArray()); if (BackupFiles && System.IO.File.Exists(SaveFilePath)) { System.IO.File.Move(SaveFilePath, BackupPath + "/" + Names[Names.Length - 1]); } SaveLuaFile.Save(SaveFilePath); yield return(null); //SaveScenarioLua(); //SaveSaveLua(); //SaveScriptLua(ScriptId); SaveScmap(); yield return(null); SaveTablesLua(); yield return(null); InfoPopup.Show(false); SavingMapProcess = false; GenericInfoPopup.ShowInfo("Map saved!\n" + FolderName + "/" + ScenarioFileName + ".lua"); }
public void SaveMapAs() { if (!MapLuaParser.IsMapLoaded) { return; } LateUpdate(); var paths = StandaloneFileBrowser.OpenFolderPanel("Save map as...", EnvPaths.GetMapsPath(), false); if (paths.Length > 0 && !string.IsNullOrEmpty(paths[0])) { // If its the same folder, then its the same map if (paths[0].Replace("\\", "/") + "/" == MapLuaParser.LoadedMapFolderPath) { MapLuaParser.Current.SaveMap(); return; } string[] PathSeparation = paths[0].Replace("\\", "/").Split("/".ToCharArray()); string ChosenFolderName = PathSeparation[PathSeparation.Length - 1]; string NewFolderName = ChosenFolderName; NewFolderName = NewFolderName.Replace(" ", "_"); int ReplaceVersion = GetVersionControll(NewFolderName); if (ReplaceVersion <= 0) { ReplaceVersion = 1; // Map without versioning should always be v1 } //ReplaceVersion = (int)MapLuaParser.Current.ScenarioLuaFile.Data.map_version; NewFolderName = ForceVersionControllValue(NewFolderName, ReplaceVersion); string ChosenPath = ""; if (ChosenFolderName != NewFolderName) { // Combine system path using old separation and new folder name ChosenPath = ""; for (int i = 0; i < PathSeparation.Length - 1; i++) { ChosenPath += PathSeparation[i] + "/"; } ChosenPath += NewFolderName; // If selected folder does not exist, then remove wrong folder, and make a new, proper one if (!Directory.Exists(ChosenPath)) { Directory.CreateDirectory(ChosenPath); // Remove only when folder is empty if (Directory.GetFiles(paths[0]).Length <= 0 && System.IO.Directory.GetFiles(paths[0]).Length <= 0) { Directory.Delete(paths[0]); } } } else { ChosenPath = paths[0]; } string[] FilePaths = System.IO.Directory.GetFiles(ChosenPath); if (System.IO.Directory.GetDirectories(ChosenPath).Length > 0 || System.IO.Directory.GetFiles(ChosenPath).Length > 0) { Debug.LogWarning("Selected directory is not empty! " + ChosenPath); // Check if its a map folder foreach (string path in FilePaths) { // If contains any of the map files, then it need to be a map if (path.EndsWith("_scenario.lua") || path.EndsWith("_save.lua") || path.EndsWith(".scmap")) { OverwritePath = ChosenPath; GenericPopup.ShowPopup(GenericPopup.PopupTypes.TwoButton, "Folder is not empty!", "Overwrite map " + NewFolderName + "?\nThis can't be undone!", "Overwrite", OverwriteYes, "Cancel", null); return; } } // Not a map folder, return error to prevent data lose GenericPopup.ShowPopup(GenericPopup.PopupTypes.Error, "Error!", "Selected " + NewFolderName + " folder is not empty and it's not a map folder!", "OK", null); return; } System.IO.DirectoryInfo Dir = new DirectoryInfo(ChosenPath); MapLuaParser.Current.FolderParentPath = Dir.Parent.FullName.Replace("\\", "/") + "/"; Debug.Log(MapLuaParser.Current.FolderParentPath); if (SaveAsNewFolder(NewFolderName, NonVersionControlledName(NewFolderName))) { // Inform user, that map was saved into different folder than he chose if (ChosenFolderName != NewFolderName) { string LogText = "Wrong folder name: " + ChosenFolderName + "\n Instead saved as: " + NewFolderName; Debug.Log(LogText); GenericInfoPopup.ShowInfo(LogText); } } } }
IEnumerator LoadingFile() { while (SavingMapProcess) yield return null; Undo.Current.Clear(); bool AllFilesExists = true; string Error = ""; if (!System.IO.Directory.Exists(FolderParentPath)) { Error = "Map folder does not exist:\n" + FolderParentPath; Debug.LogWarning(Error); AllFilesExists = false; } if (AllFilesExists && !System.IO.File.Exists(LoadedMapFolderPath + ScenarioFileName + ".lua")) { AllFilesExists = SearchForScenario(); if (!AllFilesExists) { Error = "Scenario.lua does not exist:\n" + LoadedMapFolderPath + ScenarioFileName + ".lua"; Debug.LogWarning(Error); } } if (AllFilesExists) { string ScenarioText = System.IO.File.ReadAllText(LoadedMapFolderPath + ScenarioFileName + ".lua"); if (!ScenarioText.StartsWith("version = 3") && ScenarioText.StartsWith("version =")) { AllFilesExists = SearchForScenario(); if (!AllFilesExists) { Error = "Wrong scenario file version. Should be 3, is " + ScenarioText.Remove(11).Replace("version =", ""); Debug.LogWarning(Error); } } if (AllFilesExists && !ScenarioText.StartsWith("version = 3")) { AllFilesExists = SearchForScenario(); if (!AllFilesExists) { Error = "Selected file is not a proper scenario.lua file. "; Debug.LogWarning(Error); } } } if (AllFilesExists && !System.IO.File.Exists(EnvPaths.GamedataPath + "/env.scd")) { Error = "No source files in gamedata folder: " + EnvPaths.GamedataPath; Debug.LogWarning(Error); AllFilesExists = false; } if (AllFilesExists) { // Begin load LoadRecentMaps.MoveLastMaps(ScenarioFileName, FolderName, FolderParentPath); LoadingMapProcess = true; InfoPopup.Show(true, "Loading map...\n( " + ScenarioFileName + ".lua" + " )"); EditMenu.gameObject.SetActive(true); Background.SetActive(false); yield return null; ScenarioLuaFile = new ScenarioLua(); SaveLuaFile = new SaveLua(); TablesLuaFile = new TablesLua(); AsyncOperation ResUn = Resources.UnloadUnusedAssets(); while (!ResUn.isDone) { yield return null; } // Scenario LUA if (ScenarioLuaFile.Load(FolderName, ScenarioFileName, FolderParentPath)) { //Map Loaded MapCenterPoint = Vector3.zero; MapCenterPoint.x = (GetMapSizeX() / 20f); MapCenterPoint.z = -1 * (GetMapSizeY() / 20f); } CameraControler.Current.MapSize = Mathf.Max(ScenarioLuaFile.Data.Size[0], ScenarioLuaFile.Data.Size[1]); CameraControler.Current.RestartCam(); InfoPopup.Show(true, "Loading map...\n(" + ScenarioLuaFile.Data.map + ")"); yield return null; // SCMAP LoadScmapFile = HeightmapControler.StartCoroutine(ScmapEditor.Current.LoadScmapFile()); System.GC.Collect(); yield return LoadScmapFile; if(ScmapEditor.Current.map.VersionMinor == 0) { Error = "scmap file not loaded!\n" + MapLuaParser.Current.ScenarioLuaFile.Data.map; InfoPopup.Show(false); LoadingMapProcess = false; ResetUI(); ReturnLoadingWithError(Error); yield return null; StopCoroutine(LoadingFileCoroutine); } CameraControler.Current.RestartCam(); if (HeightmapControler.map.VersionMinor >= 60) EditMenu.MapInfoMenu.SaveAsFa.isOn = true; else EditMenu.MapInfoMenu.SaveAsSc.isOn = true; InfoPopup.Show(true, "Loading map...\n(" + ScenarioLuaFile.Data.save + ")"); yield return null; if (loadSave) { // Save LUA SaveLuaFile.Load(); SetSaveLua(); System.GC.Collect(); //LoadSaveLua(); yield return null; Coroutine UnitsLoader = StartCoroutine(SaveLuaFile.LoadUnits()); yield return UnitsLoader; } // Load Props if (LoadProps) { PropsMenu.gameObject.SetActive(true); PropsMenu.AllowBrushUpdate = false; PropsMenu.StartCoroutine(PropsMenu.LoadProps()); while (PropsMenu.LoadingProps) { InfoPopup.Show(true, "Loading map...\n( Loading props " + PropsMenu.LoadedCount + "/" + ScmapEditor.Current.map.Props.Count + ")"); yield return null; } System.GC.Collect(); PropsMenu.gameObject.SetActive(false); } if (LoadDecals) { DecalsMenu.gameObject.SetActive(true); //DecalsMenu.AllowBrushUpdate = false; DecalsMenu.StartCoroutine(DecalsMenu.LoadDecals()); while (DecalsInfo.LoadingDecals) { InfoPopup.Show(true, "Loading map...\n( Loading decals " + DecalsMenu.LoadedCount + "/" + ScmapEditor.Current.map.Decals.Count + ")"); yield return null; } System.GC.Collect(); DecalsMenu.gameObject.SetActive(false); } if (TablesLuaFile.Load(FolderName, ScenarioFileName, FolderParentPath)) { //Map Loaded } int ParsedVersionValue = AppMenu.GetVersionControll(FolderName); if(ParsedVersionValue > 0) { ScenarioLuaFile.Data.map_version = ParsedVersionValue; } InfoPopup.Show(false); WindowStateSever.WindowStateSaver.ChangeWindowName(FolderName); LoadingMapProcess = false; RenderMarkersConnections.Current.UpdateConnections(); EditMenu.Categorys[0].GetComponent<MapInfo>().UpdateFields(); MapLuaParser.Current.UpdateArea(); GenericInfoPopup.ShowInfo("Map successfully loaded!\n" + FolderName + "/" + ScenarioFileName + ".lua"); } else { ResetUI(); ReturnLoadingWithError(Error); } }
public IEnumerator SaveMapProcess() { yield return null; // Wait for all process to finish while (Markers.MarkersControler.IsUpdating) { //Debug.Log("Wait for markers to finish..."); InfoPopup.Show(true, "Saving map...\nWait for markers upadate task..."); yield return new WaitForSeconds(0.5f); } while (PropsRenderer.IsUpdating) { //Debug.Log("Wait for props to finish..."); InfoPopup.Show(true, "Saving map...\nWait for props upadate task..."); yield return new WaitForSeconds(0.5f); } while (UnitsControler.IsUpdating) { //Debug.Log("Wait for units to finish..."); InfoPopup.Show(true, "Saving map...\nWait for units upadate task..."); yield return new WaitForSeconds(0.5f); } while (DecalsControler.IsUpdating) { //Debug.Log("Wait for decals to finish..."); InfoPopup.Show(true, "Saving map...\nWait for decals upadate task..."); yield return new WaitForSeconds(0.5f); } GenerateBackupPath(); PreviewTex.ForcePreviewMode(true); yield return null; // Scenario.lua string ScenarioFilePath = LoadedMapFolderPath + ScenarioFileName + ".lua"; if (BackupFiles && System.IO.File.Exists(ScenarioFilePath)) System.IO.File.Move(ScenarioFilePath, BackupPath + "/" + ScenarioFileName + ".lua"); SaveReclaim(); ScenarioLuaFile.Save(ScenarioFilePath); yield return null; //Save.lua string SaveFilePath = MapRelativePath(ScenarioLuaFile.Data.save); string FileName = ScenarioLuaFile.Data.save; string[] Names = FileName.Split(("/").ToCharArray()); if (BackupFiles && System.IO.File.Exists(SaveFilePath)) System.IO.File.Move(SaveFilePath, BackupPath + "/" + Names[Names.Length - 1]); SaveLuaFile.Save(SaveFilePath); yield return null; SaveScmap(); yield return null; SaveTablesLua(); yield return null; InfoPopup.Show(false); SavingMapProcess = false; GenericInfoPopup.ShowInfo("Map saved!\n" + FolderName + "/" + ScenarioFileName + ".lua" ); }
public void SaveScmapFile() { float LowestElevation = ScmapEditor.MaxElevation; float HighestElevation = 0; if (Teren) { heights = Teren.terrainData.GetHeights(0, 0, Teren.terrainData.heightmapWidth, Teren.terrainData.heightmapHeight); heightsLength = heights.GetLength(0); int y = 0; int x = 0; for (y = 0; y < map.Width + 1; y++) { for (x = 0; x < map.Height + 1; x++) { float Height = heights[x, y]; LowestElevation = Mathf.Min(LowestElevation, Height); HighestElevation = Mathf.Max(HighestElevation, Height); //double HeightValue = ((double)Height) * HeightResize; //map.SetHeight(y, map.Height - x, (short)(HeightValue + RoundingError)); map.SetHeight(y, map.Height - x, (ushort)(Height * HeightResize)); } } } LowestElevation = (LowestElevation * TerrainHeight) / 0.1f; HighestElevation = (HighestElevation * TerrainHeight) / 0.1f; if (HighestElevation - LowestElevation > 49.9) { Debug.Log("Lowest point: " + LowestElevation); Debug.Log("Highest point: " + HighestElevation); Debug.LogWarning("Height difference is too high! it might couse rendering issues! Height difference is: " + (HighestElevation - LowestElevation)); GenericInfoPopup.ShowInfo("Height difference " + (HighestElevation - LowestElevation) + " is too high!\nIt might couse rendering issues!"); } if (MapLuaParser.Current.EditMenu.MapInfoMenu.SaveAsFa.isOn) { if (map.AdditionalSkyboxData == null || map.AdditionalSkyboxData.Data == null || map.AdditionalSkyboxData.Data.Position.x == 0) { // Convert to v60 LoadDefaultSkybox(); } map.VersionMinor = 60; map.AdditionalSkyboxData.Data.UpdateSize(); } else if (map.VersionMinor >= 60) // Convert to v56 { LoadDefaultSkybox(); map.AdditionalSkyboxData.Data.UpdateSize(); map.VersionMinor = 56; } //Debug.Log("Set Heightmap to map " + map.Width + ", " + map.Height); //string MapPath = EnvPaths.GetMapsPath(); string path = MapLuaParser.MapRelativePath(MapLuaParser.Current.ScenarioLuaFile.Data.map); //TODO force values if needed //map.TerrainShader = Shader; map.TerrainShader = MapLuaParser.Current.EditMenu.TexturesMenu.TTerrainXP.isOn ? ("TTerrainXP") : ("TTerrain"); map.MinimapContourColor = new Color32(0, 0, 0, 255); map.MinimapDeepWaterColor = new Color32(71, 140, 181, 255); map.MinimapShoreColor = new Color32(141, 200, 225, 255); map.MinimapLandStartColor = new Color32(119, 101, 108, 255); map.MinimapLandEndColor = new Color32(206, 206, 176, 255); //map.MinimapLandEndColor = new Color32 (255, 255, 215, 255); map.MinimapContourInterval = 10; map.WatermapTex = new Texture2D(map.UncompressedWatermapTex.width, map.UncompressedWatermapTex.height, map.UncompressedWatermapTex.format, false); map.WatermapTex.SetPixels(map.UncompressedWatermapTex.GetPixels()); map.WatermapTex.Apply(); map.WatermapTex.Compress(true); map.WatermapTex.Apply(); map.NormalmapTex = new Texture2D(map.UncompressedNormalmapTex.width, map.UncompressedNormalmapTex.height, map.UncompressedNormalmapTex.format, false); map.NormalmapTex.SetPixels(map.UncompressedNormalmapTex.GetPixels()); map.NormalmapTex.Apply(); map.NormalmapTex.Compress(true); map.NormalmapTex.Apply(); map.PreviewTex = PreviewRenderer.RenderPreview(((LowestElevation + HighestElevation) / 2) * 0.1f); for (int i = 0; i < map.Layers.Count; i++) { Textures[i].AlbedoPath = GetGamedataFile.FixMapsPath(Textures[i].AlbedoPath); Textures[i].NormalPath = GetGamedataFile.FixMapsPath(Textures[i].NormalPath); map.Layers[i].PathTexture = Textures[i].AlbedoPath; map.Layers[i].PathNormalmap = Textures[i].NormalPath; map.Layers[i].ScaleTexture = Textures[i].AlbedoScale; map.Layers[i].ScaleNormalmap = Textures[i].NormalScale; } List <Prop> AllProps = new List <Prop>(); if (EditMap.PropsInfo.AllPropsTypes != null) { int Count = EditMap.PropsInfo.AllPropsTypes.Count; for (int i = 0; i < EditMap.PropsInfo.AllPropsTypes.Count; i++) { AllProps.AddRange(EditMap.PropsInfo.AllPropsTypes[i].GenerateSupComProps()); } } map.Props = AllProps; if (map.VersionMinor < 56) { map.ConvertToV56(); } map.Save(path, map.VersionMinor); }
public void ExportWithSizeHeightmap() { int scale = int.Parse(TerrainScale.text); scale = Mathf.Clamp(scale, 129, 2049); //string Filename = EnvPaths.GetMapsPath() + MapLuaParser.Current.FolderName + "/heightmap.raw"; var extensions = new[] { new ExtensionFilter("Heightmap", new string[] { "raw" }) //new ExtensionFilter("Stratum mask", "raw, bmp") }; var paths = StandaloneFileBrowser.SaveFilePanel("Export heightmap scalled", DefaultPath, "heightmap", extensions); if (paths == null || string.IsNullOrEmpty(paths)) { return; } float h = ScmapEditor.Current.Teren.terrainData.heightmapResolution; float w = ScmapEditor.Current.Teren.terrainData.heightmapResolution; float[,] data = ScmapEditor.Current.Teren.terrainData.GetHeights(0, 0, (int)w, (int)h); ExportAs = new Texture2D((int)w, (int)h, TextureFormat.RGB24, false, true); Debug.Log(w + ", " + h); float HeightValue = 1; HeightValue = float.Parse(TerrainScale_HeightValue.text); if (HeightValue < 0) { HeightValue = 1; } for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float Value = data[y, x]; // / HeightConversion; if (TerrainScale_Height.isOn) { Value *= HeightValue; } //float ColorR = (Mathf.Floor(Value) * (1f / 255f)); //float ColorG = (Value - Mathf.Floor(Value)); ExportAs.SetPixel((int)(h - (y + 1)), x, new Color(Value, 0, 0)); } } ExportAs.Apply(); bool differentSize = w != scale || h != scale; h = scale; w = scale; using (BinaryWriter writer = new BinaryWriter(new System.IO.FileStream(paths, System.IO.FileMode.Create))) { Color pixel = Color.black; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (differentSize) { pixel = ExportAs.GetPixelBilinear(y / h, x / w); } else { pixel = ExportAs.GetPixel(y, x); } //float value = (pixel.r + pixel.g * (1f / 255f)); float value = pixel.r; //uint ThisPixel = (uint)(value * HeightConversion); ushort ThisPixel = (ushort)(value * ScmapEditor.HeightResize); writer.Write(System.BitConverter.GetBytes(ThisPixel)); } } writer.Close(); } //ExportAs = null; EnvPaths.SetLastPath(ExportPathKey, System.IO.Path.GetDirectoryName(paths)); GenericInfoPopup.ShowInfo("Rescaled Heightmap export success!\n" + System.IO.Path.GetFileName(paths)); }
public void ImportHeightmap() { var extensions = new[] { new ExtensionFilter("Heightmap", new string[] { "raw", "r16", "bmp" }) }; var paths = StandaloneFileBrowser.OpenFilePanel("Import heightmap", DefaultPath, extensions, false); if (paths == null || paths.Length == 0 || string.IsNullOrEmpty(paths[0])) { return; } int h = ScmapEditor.Current.Teren.terrainData.heightmapResolution; int w = ScmapEditor.Current.Teren.terrainData.heightmapResolution; ScmapEditor.GetAllHeights(ref beginHeights); Undo.RegisterUndo(new UndoHistory.HistoryTerrainHeight(), new UndoHistory.HistoryTerrainHeight.TerrainHeightHistoryParameter(beginHeights)); float[,] data = new float[h, w]; //float[,] old = ScmapEditor.Current.Teren.terrainData.GetHeights(0, 0, w, h); if (paths[0].ToLower().EndsWith("bmp")) { BMPLoader loader = new BMPLoader(); BMPImage img = loader.LoadBMP(paths[0]); Debug.Log(img.info.compressionMethod + ", " + img.info.nBitsPerPixel + ", " + img.rMask + ", " + img.imageData[0].r); Texture2D ImportedImage = img.ToTexture2D(); if (ImportedImage.width != h || ImportedImage.height != w) { Debug.Log("Wrong size"); TextureScale.Bilinear(ImportedImage, h, w); ImportedImage.Apply(false); } Color[] ImportedColors = ImportedImage.GetPixels(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { data[y, x] = (float)ImportedColors[x + y * w].r / 0.567f; // 0.58 } } } else { using (var file = System.IO.File.OpenRead(paths[0])) using (var reader = new System.IO.BinaryReader(file)) { long CheckValue = 2; CheckValue *= (long)(w); CheckValue *= (long)(h); long FileLength = file.Length; if (FileLength != CheckValue) { reader.Dispose(); file.Dispose(); GenericPopup.ShowPopup(GenericPopup.PopupTypes.Error, "Error", "Selected heightmap is in wrong size.\nIs: " + FileLength + "B, should be: " + CheckValue + "B", "OK", null); return; } for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float v = (float)(reader.ReadUInt16() / ScmapEditor.HeightResize); data[h - (y + 1), x] = v; } } } } //ScmapEditor.Current.Teren.terrainData.SetHeights(0, 0, data); ScmapEditor.SetAllHeights(data); RegenerateMaps(); OnTerrainChanged(); EnvPaths.SetLastPath(ExportPathKey, Path.GetDirectoryName(paths[0])); GenericInfoPopup.ShowInfo("Heightmap import success!\n" + Path.GetFileName(paths[0])); if (ScmapEditor.IsOverMinMaxDistance()) { GenericPopup.ShowPopup(GenericPopup.PopupTypes.TriButton, "Importing heightmap", "Distance between lowest and highest point is higher than 50.\nClamp it?", "Clamp Top", ClampTop, "Clamp Bottom", ClampBottom, "Ignore", null); } }