Пример #1
0
    public static void UnZip(string zipPath, string destinationDir, bool deleteExistingDir = true)
    {
        if (string.IsNullOrWhiteSpace(zipPath))
        {
            Debug.LogError("Null or blank zip file path! Cannot unzip!");
            return;
        }

        if (string.IsNullOrWhiteSpace(destinationDir))
        {
            Debug.LogError("Null or blank destination directory path! Cannot unzip!");
            return;
        }

        if (!File.Exists(zipPath))
        {
            Debug.LogError("Did not find zip file at '{0}', cannot unzip!".Form(zipPath));
            return;
        }

        if (Directory.Exists(destinationDir))
        {
            // Delete it?
            if (deleteExistingDir)
            {
                Directory.Delete(destinationDir, true);
            }
        }

        GameIO.EnsureDirectory(destinationDir);
        ZipFile.ExtractToDirectory(zipPath, destinationDir);
    }
Пример #2
0
 public static void RemoveProfile(string _id)
 {
     try
     {
         string filepath1 = string.Format("{0}/Player/{1}.map", GameIO.GetSaveGameDir(), _id);
         string filepath2 = string.Format("{0}/Player/{1}.ttp", GameIO.GetSaveGameDir(), _id);
         if (!File.Exists(filepath1))
         {
             SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Could not find file {0}.map", _id));
         }
         else
         {
             File.Delete(filepath1);
         }
         if (!File.Exists(filepath2))
         {
             SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Could not find file {0}.ttp", _id));
         }
         else
         {
             File.Delete(filepath2);
         }
     }
     catch (Exception e)
     {
         Log.Out(string.Format("[SERVERTOOLS] Error in ResetPlayerConsole.RemoveProfile: {0}", e.Message));
     }
 }
Пример #3
0
 public static void ResetHardcoreProfile(ClientInfo _cInfo)
 {
     try
     {
         string filepath1 = string.Format("{0}/Player/{1}.map", GameIO.GetSaveGameDir(), _cInfo.CrossplatformId.CombinedString);
         string filepath2 = string.Format("{0}/Player/{1}.ttp", GameIO.GetSaveGameDir(), _cInfo.CrossplatformId.CombinedString);
         if (!File.Exists(filepath1))
         {
             SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("Could not find file {0}.map", _cInfo.CrossplatformId.CombinedString));
         }
         else
         {
             File.Delete(filepath1);
         }
         if (!File.Exists(filepath2))
         {
             SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("Could not find file {0}.ttp", _cInfo.CrossplatformId.CombinedString));
         }
         else
         {
             File.Delete(filepath2);
         }
         RemovePlayerData(_cInfo);
     }
     catch (Exception e)
     {
         Log.Out(string.Format("[SERVERTOOLS] Error in Hardcore.ResetHardcoreProfile: {0}", e.Message));
     }
 }
Пример #4
0
    private static void LoadAndMerge()
    {
        // Load default keys from resources...
        var defaultKeys = GameIO.ResourceToObject <Dictionary <string, KeyCode[]> >(GameIO.DefaultInputPath);
        int defNum      = defaultKeys.Count;

        // Load current keys from file...
        var currentKeys = GameIO.FileToObject <Dictionary <string, KeyCode[]> >(GameIO.CurrentInputPath);

        if (currentKeys == null)
        {
            currentKeys = new Dictionary <string, KeyCode[]>();
        }
        // Merge current keys into default keys, but current keys have priority.
        foreach (var pair in currentKeys)
        {
            if (defaultKeys.ContainsKey(pair.Key))
            {
                defaultKeys[pair.Key] = pair.Value;
            }
            else
            {
                defaultKeys.Add(pair.Key, pair.Value);
            }
        }

        bindings = defaultKeys;
        Debug.Log(string.Format("Loaded {0} default key bindings, {1} current key bindings, and merged to create {2} bindings.", defNum, currentKeys.Count, defaultKeys.Count));
    }
Пример #5
0
        private void SaveGame(string NewName)
        {
            WorldAdapter wa = new WorldAdapter();

            if (NewName != null && NewName != "")
            {
                wa.SaveGameName = NewName;
            }

            if (wa.SaveGameName == "" || wa.SaveGameName == null)
            {
                UiUtils.OpenTextInputDialog(grdMain, LangResources.CurLang.SaveGame, LangResources.CurLang.GameHasNotBeenSavedBefore, SaveGameInputCallback);
            }
            else
            {
                GameIO io = new GameIO();
                io.SaveGameName = wa.SaveGameName;
                io.SaveGame();

                List <DialogButton> buttons = new List <DialogButton>();
                buttons.Add(new DialogButton(LangResources.CurLang.OK, null, null));

                UiUtils.OpenDialogBox(grdMain, LangResources.CurLang.SaveGame, String.Format(LangResources.CurLang.GameSavedSuccessfully, wa.SaveGameName), buttons);
            }
        }
Пример #6
0
        private void SetupList()
        {
            GameIO io = new GameIO();

            Saves = io.ListSaveGames();

            lstSaves.Title = LangResources.CurLang.SavedGames;

            lstSaves.Columns = new List <ListColumn>()
            {
                new ListColumn(LangResources.CurLang.Name, 300),
                new ListColumn(LangResources.CurLang.Date, 200, HorizontalAlignment.Right)
            };

            List <ListRow> rows = new List <ListRow>();

            for (int s = 0; s < Saves.Count; s++)
            {
                rows.Add(new ListRow(s, new List <object>()
                {
                    Saves[s].Name,
                    Saves[s].SaveDate.ToString("dd/MM/yyyy HH:mm")
                }));
            }

            lstSaves.Rows = rows;
        }
Пример #7
0
    public static void Zip(string sourceDirectory, string destinationPath)
    {
        if (sourceDirectory == null)
        {
            Debug.LogError("Null source directory string, cannot zip!");
        }

        if (!Directory.Exists(sourceDirectory))
        {
            Debug.LogError("Directory does not exist, cannot zip!");
        }

        if (destinationPath == null)
        {
            Debug.LogError("Null destination path string, cannot zip!");
        }

        if (File.Exists(destinationPath))
        {
            File.Delete(destinationPath);
        }

        GameIO.EnsureDirectory(GameIO.DirectoryFromFile(destinationPath));
        ZipFile.CreateFromDirectory(sourceDirectory, destinationPath, CompressionLevel.Optimal, false);
        Debug.Log("Zipped '{0}' to '{1}'.".Form(sourceDirectory, destinationPath));
    }
Пример #8
0
 public static void SavePersistentPlayerDataXML()
 {
     if (GameManager.Instance.persistentPlayers != null)
     {
         GameManager.Instance.persistentPlayers.Write(GameIO.GetSaveGameDir(null, null) + "/players.xml");
     }
 }
Пример #9
0
        static void Main(string[] args)
        {
            GameIO         view  = new GameIO();
            GameLogic      logic = new GameLogic();
            GameController con   = new GameController(view, logic);

            con.StartGame();
        }
Пример #10
0
        public static void SavePlayerDataFile(string _id, PlayerDataFile _playerDataFile)
        {
            _playerDataFile.Save(GameIO.GetPlayerDataDir(), _id.Trim());
            ClientInfo cInfo = GetClientInfoFromNameOrId(_id);

            if (cInfo != null)
            {
                ModEvents.SavePlayerData.Invoke(cInfo, _playerDataFile);
            }
        }
Пример #11
0
        public static PlayerDataFile GetPlayerDataFileFromUId(PlatformUserIdentifierAbs _uId)
        {
            PlayerDataFile playerDatafile = new PlayerDataFile();

            playerDatafile.Load(GameIO.GetPlayerDataDir(), _uId.CombinedString.Trim());
            if (playerDatafile != null)
            {
                return(playerDatafile);
            }
            return(null);
        }
Пример #12
0
    public void SaveToFile()
    {
        Dictionary <string, KeyCode[]> dic = new Dictionary <string, KeyCode[]>();

        foreach (var item in Bindings)
        {
            dic.Add(item.Name, item.Keys);
        }
        GameIO.ObjectToResource(dic, GameIO.DefaultInputPath);
        Debug.Log(string.Format("Saved {0} inputs to '{1}'", Bindings.Count, GameIO.FullResourcePath(GameIO.DefaultInputPath)));
    }
Пример #13
0
    public void Save(bool useTemp, bool deleteTemp = true)
    {
        if (Data == null)
        {
            Debug.LogError("Tile Map Data is null, cannot save! Invalid loaded map!");
            return;
        }

        // Should be in editor mode for this to work correctly, but it theoretically also works even at runtime.
        string zipFilePath = Data.SavedZipPath;

        Debug.Log("Saving map '{0}' to {1}".Form(this, zipFilePath));

        string fileSaveDir = null;

        if (useTemp)
        {
            // Save to a temporary folder.
            fileSaveDir = Path.Combine(Path.GetTempPath(), Data.InternalName);
        }
        else
        {
            // Save to the extracted (unzipped) folder, and then zip it up anyway.
            fileSaveDir = Path.Combine(GameIO.UnzippedMapsDirectory, Data.InternalName);
        }

        // Save all map data to file.
        Debug.Log("Saving files to '{0}' ({1}) ...".Form(fileSaveDir, useTemp ? "temp" : "pers"));
        GameIO.EnsureDirectory(fileSaveDir);
        var fs = MapIO.StartWrite(Path.Combine(fileSaveDir, TILE_DATA_FILE));

        MapIO.WriteTileIDs(fs, TileIDs);
        MapIO.End(fs);

        // Save metadata.
        GameIO.ObjectToFile(this.Data, Path.Combine(fileSaveDir, METADATA_FILE));

        // Work out all the tile varieties.
        // TODO
        fs = MapIO.StartWrite(Path.Combine(fileSaveDir, TILE_VARIATION_FILE));
        MapIO.WriteTileVariations(fs, this.TileVariations);
        MapIO.End(fs);

        // Grab all the saved files, and zip the up into the save zip path.
        MapIO.Zip(fileSaveDir, zipFilePath);

        // Delete the temporary directory, just to be clean.
        if (useTemp && deleteTemp)
        {
            Directory.Delete(fileSaveDir, true);
        }

        Debug.Log("Finished saving, zipped to '{0}'".Form(zipFilePath));
    }
Пример #14
0
        public static PlayerDataFile GetPlayerDataFileFromEntityId(int _entityId)
        {
            PersistentPlayerData persistentPlayerData = GetPersistentPlayerDataFromEntityId(_entityId);

            if (persistentPlayerData != null)
            {
                PlayerDataFile playerDatafile = new PlayerDataFile();
                playerDatafile.Load(GameIO.GetPlayerDataDir(), persistentPlayerData.UserIdentifier.CombinedString.Trim());
                if (playerDatafile != null)
                {
                    return(playerDatafile);
                }
            }
            return(null);
        }
Пример #15
0
        private void StartGame(string SaveGame)
        {
            bool FromSave;

            if (SaveGame == null)
            {
                Initialiser init = new Initialiser();
                init.CreateWorld();
                FromSave = false;
            }
            else
            {
                GameIO io = new GameIO();
                io.SaveGameName = SaveGame;

                try
                {
                    io.LoadGame();
                }
                catch (Exception ex)
                {
                    UiUtils.OpenDialogBox(grdMain, LangResources.CurLang.LoadSavedGame, LangResources.CurLang.Error + ": " + ex.Message,
                                          new List <DialogButton>()
                    {
                        new DialogButton(LangResources.CurLang.OK, null, null)
                    });
                    return;
                }


                FromSave = true;
            }


            GameWindow g = new GameWindow();

            UiUtils.MainWindowGrid  = g.grdMain;
            g.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            g.WindowState           = WindowState.Maximized;
            g.Show();
            g.StartGame(FromSave);

            this.Close();
        }
Пример #16
0
 public void LoadData()
 {
     if (File.Exists("Game_Data.json"))
     {
         var gamedata = GameIO.ReadFromJsonFile <DataObjects.GameDataObject>("Game_Data.json");
         CouldLoadFile = true;
         GSV           = gamedata.GameSceneVariables;
         Tiles         = new PlantTile[gamedata.Tiles.GetLength(0), gamedata.Tiles.GetLength(1)];
         for (int i = 0; i != gamedata.Tiles.GetLength(0); i++)
         {
             for (int j = 0; j != gamedata.Tiles.GetLength(1); j++)
             {
                 Tiles[i, j]         = gamedata.Tiles[i, j];
                 Tiles[i, j].Terrain = new Terrain.DirtPatch();
                 Tiles[i, j].Terrain.Generate(GSV.TerrainDepth, GSV.TerrainWidth, GSV.TerrainPointSpacing, Graphics.GraphicsDevice);
             }
         }
     }
 }
Пример #17
0
 public static void Exec()
 {
     try
     {
         if (Regions.Count > 0)
         {
             string regionDir = GameIO.GetSaveGameRegionDir();
             if (Directory.Exists(regionDir))
             {
                 string[] files = Directory.GetFiles(regionDir, "*.7rg", SearchOption.AllDirectories);
                 if (files != null && files.Length > 0)
                 {
                     foreach (var file in files)
                     {
                         string fileName = file.Remove(0, file.IndexOf("Region") + 9).Replace(".7rg", "");
                         if (Regions.Contains(fileName))
                         {
                             FileInfo fInfo = new FileInfo(file);
                             if (fInfo != null)
                             {
                                 fInfo.Delete();
                                 Log.Out(string.Format("[SERVERTOOLS] Region reset: r.{0}.7rg", fileName));
                             }
                         }
                     }
                 }
             }
             else
             {
                 Log.Out("[SERVERTOOLS] Region directory not found. Unable to delete regions from the reset list");
                 return;
             }
         }
     }
     catch (Exception e)
     {
         Log.Out(string.Format("[SERVERTOOLS] Error in RegionReset.Exec: {0}", e.Message));
     }
 }
Пример #18
0
    public void Load(string mapInternalName, bool forceExtract)
    {
        var sw = new System.Diagnostics.Stopwatch();

        sw.Start();

        if (mapInternalName == null)
        {
            Debug.LogError("Map internal name is null, cannot load!");
            return;
        }

        string unzippedPath = GameIO.UnzippedMapsDirectory;

        if (!Directory.Exists(unzippedPath))
        {
            Debug.LogWarning("Unzipped map path ({0}) does not exist, creating it...".Form(unzippedPath));
            Directory.CreateDirectory(unzippedPath);
        }

        string zippedPath     = GameIO.ZippedMapsDirectory;
        string zippedFilePath = Path.Combine(zippedPath, mapInternalName + ".zip");
        bool   zippedExists   = false;

        if (!Directory.Exists(zippedPath))
        {
            Debug.LogWarning("Zipped map path ({0}) does not exist, why? Map will not load unless it has already been unzipped previously.".Form(zippedPath));
        }
        else
        {
            if (File.Exists(zippedFilePath))
            {
                zippedExists = true;
            }
        }

        string destinationUnzippedDirectory = Path.Combine(unzippedPath, mapInternalName);

        if (forceExtract)
        {
            if (!zippedExists)
            {
                Debug.LogError("Extract is required (forced), but map zipped file '{0}' could not be found. Cannot load map!".Form(zippedPath));
                return;
            }

            // Extract the zipped file to the unzipped folder.
            MapIO.UnZip(zippedFilePath, destinationUnzippedDirectory, true);
            Debug.Log("Unzipped map '{0}' to {1}, was forced ({2}).".Form(mapInternalName, destinationUnzippedDirectory, Directory.Exists(destinationUnzippedDirectory) ? "not necessary" : "necessary"));
        }
        else
        {
            // Check to see if an unzipped version exists, otherwise extract...
            if (Directory.Exists(destinationUnzippedDirectory))
            {
                // It does exist! Assume that the files are all correct and loaded properly...
                Debug.Log("Extract not forced, unzipped version of '{0}' found.".Form(mapInternalName));
            }
            else
            {
                // An unzipped version does not exist, extract it!
                if (!zippedExists)
                {
                    Debug.LogError("Extract is required, but map zipped file '{0}' could not be found. Cannot load map!".Form(zippedPath));
                    return;
                }

                // Extract the zipped file to the unzipped folder.
                MapIO.UnZip(zippedFilePath, destinationUnzippedDirectory, true);
                Debug.Log("Unzipped map '{0}' to {1}, was NOT forced (necessary).".Form(mapInternalName, destinationUnzippedDirectory));
            }
        }

        // Now the extracted version should exist.

        // Load map metadata...
        this.Data = GameIO.FileToObject <TileMapData>(Path.Combine(destinationUnzippedDirectory, METADATA_FILE));

        // Load map tile ID data.
        string dataFile = Path.Combine(destinationUnzippedDirectory, TILE_DATA_FILE);
        var    fs       = MapIO.StartRead(dataFile);
        var    data     = MapIO.ReadAllTileIDs(fs, this.Data.SizeInRegions);

        this.TileIDs = null;
        this.TileIDs = data;
        MapIO.End(fs);

        // Load map tile variations...
        string variationFile = Path.Combine(destinationUnzippedDirectory, TILE_VARIATION_FILE);

        fs = MapIO.StartRead(variationFile);
        var varData = MapIO.ReadAllTileVariations(fs, this.Data.SizeInRegions);

        this.TileVariations = null;
        this.TileVariations = varData;
        MapIO.End(fs);

        // Run GC
        Debug.Log("Running GC...");
        Memory.GC();
        Debug.Log("Done!");

        // Done!
        sw.Stop();
        Debug.Log("Done loading map '{0}' in {1} seconds.".Form(mapInternalName, sw.Elapsed.TotalSeconds.ToString("N2")));
    }
Пример #19
0
 public void SaveData()
 {
     GameIO.WriteToJsonFile("Game_Data.json", GetGameDataObject());
 }
Пример #20
0
 void Awake()
 {
     _instance = this;
 }
Пример #21
0
 public string ToJson()
 {
     return(GameIO.ObjectToJson(this, Formatting.Indented, true));
 }
Пример #22
0
 public GameController(GameIO io, GameLogic logic)
 {
     _io        = io;
     _logic     = logic;
     _playAgain = true;
 }
Пример #23
0
    /// <summary>
    /// Builds the mod. Assumes that the mod def state is valid (name and all that).
    /// </summary>
    public void Build(bool zip)
    {
        var watch = new System.Diagnostics.Stopwatch();

        watch.Start();

        Debug.Log($"Building mod {Name} ({ID})...");

        // Step 0: Clear the output.
        string modDir    = Path.Combine(new DirectoryInfo(Application.dataPath).Parent.FullName, "Mod Builds");
        string outputDir = Path.Combine(modDir, ID);

        if (zip)
        {
            if (File.Exists(Path.Combine(modDir, ID + ".zip")))
            {
                File.Delete(Path.Combine(modDir, ID + ".zip"));
            }
        }
        if (Directory.Exists(outputDir))
        {
            Debug.Log("Clearing output dir.");
            Directory.Delete(outputDir, true);
        }

        // Step 1: Assign all assets in the Content folder to the asset bundle.
        // TODO get all assets in subfolders too.
        string[] guids = UnityEditor.AssetDatabase.FindAssets("", new string[] { "Assets/Mods/" + ID + "/Content" });

        // TODO aparently scenes and assets can't be in the same bundle, so create more than one bundle per mod.
        int count = 0;

        foreach (var guid in guids)
        {
            string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guid);
            UnityEditor.AssetImporter.GetAtPath(path).assetBundleName = ID;
            count++;
        }
        Debug.Log($"Assigned {count} assets to the bundle.");

        // Step 2: Create mod info.
        ModInfo info = new ModInfo
        {
            ID          = ID,
            Name        = Name,
            Author      = Author,
            Version     = Version,
            Description = Description,
            HasBundle   = count != 0,
            Assemblies  = new string[] { ID + ".dll" } // TODO allow more that one assembly to exist. Such as packaging Json.NET.
        };

        // Step 3: Write info file to the output directory.
        string infoPath       = Path.Combine(outputDir, "Info.txt");
        string tempBundle     = Path.Combine(outputDir, "TempBundleDir");
        string assembliesPath = Path.Combine(outputDir, "Assemblies");

        string json = JsonUtility.ToJson(info, true);

        GameIO.EnsureParentDir(infoPath);
        File.WriteAllText(infoPath, json);
        Debug.Log("Written mod info.");

        // Step 4: Write asset bundle. Can take ages.
        BuildBundleTo(tempBundle);
        File.Copy(Path.Combine(tempBundle, ID), Path.Combine(outputDir, "Bundle"));
        File.Copy(Path.Combine(tempBundle, ID + ".manifest"), Path.Combine(outputDir, "Bundle.manifest"));
        Directory.Delete(tempBundle, true);
        Debug.Log("Built asset bundle.");

        // Step 5: Write assemblies. They just need to be copied, they are automatically compiled by unity.
        if (!Directory.Exists(assembliesPath))
        {
            Directory.CreateDirectory(assembliesPath);
        }

        // TODO allow custom assemblies.
        CopyAssembliesTo(assembliesPath, new string[] { ID });
        Debug.Log("Copied assemblies to output.");

        if (zip)
        {
            Debug.Log("Zipping...");
            System.IO.Compression.ZipFile.CreateFromDirectory(outputDir, Path.Combine(modDir, ID + ".zip"));
            Debug.Log("Deleting uncompressed directory...");
            Directory.Delete(outputDir, true);
        }

        watch.Stop();
        Debug.Log($"Finished build in {watch.Elapsed.TotalMilliseconds:n1} ms.");
        Debug.Log($"Path: {outputDir}");
    }