Example #1
0
 public static void PerformSaveFileLoad()
 {
     System.IO.File.WriteAllText(GenFilePaths.FilePathForSavedGame(m_sfd.partial_name), m_sfd.tcontext);
     ThingFilterPatch.avoidThingFilterUsage = true;
     GameDataSaveLoader.LoadGame(m_sfd.partial_name);
     ThingFilterPatch.avoidThingFilterUsage = false;
 }
Example #2
0
        private static void UpdateFile(string fileName)
        {
            string filePath = GenFilePaths.FilePathForSavedGame(fileName);

            XmlElement xmlNode;

            using (StreamReader streamReader = new StreamReader(filePath))
            {
                using (XmlTextReader xmlTextReader = new XmlTextReader(streamReader))
                {
                    var XmlDocument = new XmlDocument();
                    XmlDocument.Load(xmlTextReader);
                    xmlNode = XmlDocument.DocumentElement;
                }
            }

            UpdateData(xmlNode);

            using (FileStream saveStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                var xmlWriterSettings = new XmlWriterSettings();
                xmlWriterSettings.Indent      = true;
                xmlWriterSettings.IndentChars = "\t";
                using (XmlWriter writer = XmlWriter.Create(saveStream, xmlWriterSettings))
                {
                    writer.WriteStartDocument();
                    writer.WriteNode(xmlNode.CreateNavigator(), false);
                }
            }

            Log.Message($"Save'{fileName}' converted successfuly");
        }
Example #3
0
 private static void SetupForQuickstart()
 {
     try {
         if (Settings.OperationMode == QuickstartSettings.QuickstartMode.Disabled)
         {
             return;
         }
         if (HugsLibUtility.ShiftIsHeld)
         {
             HugsLibController.Logger.Warning("Quickstart aborted: Shift key was held.");
             return;
         }
         CheckForErrorsAndWarnings();
         if (Settings.OperationMode == QuickstartSettings.QuickstartMode.GenerateMap)
         {
             if (GenCommandLine.CommandLineArgPassed("quicktest"))
             {
                 // vanilla QuickStarter will change the scene, only set up scenario and map size injection
                 PrepareMapGeneration();
             }
             else
             {
                 InitateMapGeneration();
             }
         }
         else if (Settings.OperationMode == QuickstartSettings.QuickstartMode.LoadMap)
         {
             var saveName = Settings.SaveFileToLoad;
             if (saveName == null)
             {
                 throw new WarningException("save filename not set");
             }
             var filePath = GenFilePaths.FilePathForSavedGame(saveName);
             if (!File.Exists(filePath))
             {
                 throw new WarningException("save file not found: " + Settings.SaveFileToLoad);
             }
             HugsLibController.Logger.Message("Quickstarter is loading saved game: " + saveName);
             Action loadAction = () => {
                 LongEventHandler.QueueLongEvent(delegate {
                     Current.Game = new Game {
                         InitData = new GameInitData {
                             gameToLoad = saveName
                         }
                     };
                 }, "Play", "LoadingLongEvent", true, null);
             };
             if (Settings.BypassSafetyDialog)
             {
                 loadAction();
             }
             else
             {
                 PreLoadUtility.CheckVersionAndLoad(filePath, ScribeMetaHeaderUtility.ScribeHeaderMode.Map, loadAction);
             }
         }
     } catch (WarningException e) {
         HugsLibController.Logger.Error("Quickstart aborted: " + e.Message);
     }
 }
        /// <summary>
        /// Инициализация при старте игры. Как можно раньше
        /// </summary>
        public static void Init()
        {
            ConfigPath = Path.Combine(GenFilePaths.ConfigFolderPath, "OnlineCity");
            if (!Directory.Exists(ConfigPath))
            {
                Directory.CreateDirectory(ConfigPath);
            }

            SaveFullName = GenFilePaths.FilePathForSavedGame(SaveName);
            MainHelper.CultureFromGame = Prefs.LangFolderName ?? "";

            try
            {
                var workPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
                    , @"..\LocalLow\Ludeon Studios\RimWorld by Ludeon Studios\OnlineCity");
                Directory.CreateDirectory(workPath);
                Loger.PathLog = workPath;
            }
            catch { }

            Loger.Log("Client Init " + MainHelper.VersionInfo);
            Loger.Log("Client Language: " + Prefs.LangFolderName);

            Loger.Log("Client MainThreadNum=" + ModBaseData.GlobalData.MainThreadNum.ToString());
        }
Example #5
0
        // lifted wholesale from HugsLib, with minor alterations
        public static void InitiateSaveLoading(string saveName)
        {
            saveName = saveName.Trim('"', '\'');

            Log.Message("Starting saved game: " + saveName);

            if (saveName == null)
            {
                throw new WarningException("save filename not set");
            }

            var filePath = GenFilePaths.FilePathForSavedGame(saveName);

            if (!File.Exists(filePath))
            {
                throw new WarningException("save file not found: " + filePath);
            }

            // skip mod/version checks, we're force loading here
            // (this also neatly hides the fact that we got weird bugs when nesting queued events)
            LongEventHandler.QueueLongEvent(delegate
            {
                Current.Game = new Game {
                    InitData = new GameInitData {
                        gameToLoad = saveName
                    }
                };
            }, "Play", "LoadingLongEvent", true, (err) => Log.Error(err.ToString()));
        }
Example #6
0
            public static bool Prefix(string saveFileName)
            {
                string fileName    = saveFileName;
                string fileContent = System.IO.File.ReadAllText(GenFilePaths.FilePathForSavedGame(saveFileName));

                if (SyncTickData.cliendID == 0)
                {
                    PirateRPC.PirateRPC.SendInvocation(NetDemo.ns, u =>
                    {
                        NetDemo.SetSFD(new NetDemo.SaveFileData()
                        {
                            tcontext = fileContent, partial_name = fileName + "_received"
                        });

                        PirateRPC.PirateRPC.SendInvocation(u, uu => { NetDemo.LoadFromRemoteSFD(); });
                    });

                    LongEventHandler.QueueLongEvent(() =>
                    {
                        for (; NetDemo.GetSFD() == null;)
                        {
                        }
                    }, "Downloading savefile".Translate(), true, e => { RimLog.Error(e.ToString()); });
                }

                return(false);
            }
Example #7
0
        public static bool PreFLoadGameFromSaveFile(string fileName)
        {
            string str = GenText.ToCommaList(from mod in LoadedModManager.RunningMods
                                             select mod.ToString(), true);

            Log.Message("Loading game from file " + fileName + " with mods " + str);
            DeepProfiler.Start("Loading game from file " + fileName);
            Current.Game = new Game();
            DeepProfiler.Start("InitLoading (read file)");
            Scribe.loader.InitLoading(GenFilePaths.FilePathForSavedGame(fileName));
            DeepProfiler.End();
            ScribeMetaHeaderUtility.LoadGameDataHeader(ScribeMetaHeaderUtility.ScribeHeaderMode.Map, true);
            bool flag = !Scribe.EnterNode("Κgame");
            bool result;

            if (flag)
            {
                Log.Error("Could not find DTMG XML node.");
                Scribe.ForceStop();
                GenScene.GoToMainMenu();
                Messages.Message("Game MUST be created with 'Don't Tempt Me!' loaded. Please select a 'Don't Tempt Me!' save game file.", MessageTypeDefOf.RejectInput);
                result = false;
            }
            else
            {
                Current.Game = new Game();
                Current.Game.LoadGame();
                PermadeathModeUtility.CheckUpdatePermadeathModeUniqueNameOnGameLoad(fileName);
                DeepProfiler.End();
                result = false;
            }
            return(result);
        }
Example #8
0
        public static void InitateSaveLoading()
        {
            var saveName = GetSaveNameToLoad()
                           ?? throw new WarningException("save filename not set");
            var filePath = GenFilePaths.FilePathForSavedGame(saveName);

            if (!File.Exists(filePath))
            {
                throw new WarningException("save file not found: " + saveName);
            }
            HugsLibController.Logger.Message("Quickstarter is loading saved game: " + saveName);
            Action loadAction = () => {
                LongEventHandler.QueueLongEvent(delegate {
                    Current.Game = new Game {
                        InitData = new GameInitData {
                            gameToLoad = saveName
                        }
                    };
                }, "Play", "LoadingLongEvent", true, null);
            };

            if (Settings.BypassSafetyDialog)
            {
                loadAction();
            }
            else
            {
                PreLoadUtility.CheckVersionAndLoad(filePath, ScribeMetaHeaderUtility.ScribeHeaderMode.Map, loadAction);
            }
        }
Example #9
0
        public static void BackupSavegame(string fileName)
        {
            string savegamePath = GenFilePaths.FilePathForSavedGame(fileName);
            string backupPath   = GetFilePathForBackup(savegamePath);

            File.Copy(savegamePath, backupPath, false);
            Log.Message($"Save copied to \"{backupPath}\"");
        }
Example #10
0
 public void SetPublishedFileId(PublishedFileId_t newPfid)
 {
     publishedFileIdInt = newPfid;
     if (Category == ScenarioCategory.CustomLocal && !fileName.NullOrEmpty())
     {
         GameDataSaveLoader.SaveScenario(this, GenFilePaths.AbsPathForScenario(fileName));
     }
 }
Example #11
0
        public static void DoSettingsWindowContents(Rect rect)
        {
            var l = new Listing_Standard();

            l.Begin(rect);

            l.CheckboxLabeled("CheckModCompatible".Translate(), ref CheckModCompatible);

            foreach (var optimization in ExperimentalOptimizations.Optimizations)
            {
                var opt = optimization.TryGetAttribute <Optimization>();
                opt.optimizationSetting.InvokeStaticMethod("DoSettingsWindowContents", l);
            }

            if (l.ButtonText("DEBUG: Dump needs, hediffs subclasses"))
            {
                var sb       = new StringBuilder();
                var allTypes = GenTypes.AllTypes.ToList();

                var hediffs = allTypes
                              .Where(t => t.IsSubclassOf(typeof(Hediff)))
                              .Where(t => TypeHasDeclaredMethod(t, "PostTick") || TypeHasDeclaredMethod(t, "Tick"))
                              .ToList();
                var hediffComps = allTypes
                                  .Where(t => t.IsSubclassOf(typeof(HediffComp)))
                                  .Where(t => TypeHasDeclaredMethod(t, "CompPostTick"))
                                  .ToList();
                var needs = allTypes
                            .Where(t => t.IsSubclassOf(typeof(Need)))
                            .ToList();

                sb.AppendLine($"needs:");
                foreach (var need in needs)
                {
                    sb.AppendLine($"  {need.FullName}");
                }

                sb.AppendLine($"hediffs:");
                foreach (var hediff in hediffs)
                {
                    sb.AppendLine($"  {hediff.FullName}");
                }

                sb.AppendLine($"hediffComps:");
                foreach (var comp in hediffComps)
                {
                    sb.AppendLine($"  {comp.FullName}");
                }

                File.WriteAllText($"{GenFilePaths.FolderUnderSaveData("EOptimizations")}\\subclasses_debug.txt", sb.ToString());

                // local functions
                bool TypeHasDeclaredMethod(Type t, string methodName) => t
                .GetMethods(AccessTools.all).Any(m => m.IsDeclaredMember() && m.Name.Equals(methodName));
            }

            l.End();
        }
        public IEnumerable <CodeInstruction> Transpiler(ILGenerator generator, IEnumerable <CodeInstruction> instr)
        {
            var dir  = GenFilePaths.FolderUnderSaveData("TranspilerDebug");
            var code = instr.ToList();

            File.WriteAllLines($"{dir}\\{Name}.before.txt", code.Select(x => x.ToString()));
            code = TranspilerDebug(generator, code).ToList();
            File.WriteAllLines($"{dir}\\{Name}.after.txt", code.Select(x => x.ToString()));
            return(code);
        }
        protected override void DoFileInteraction(string fileName)
        {
            string absPath = GenFilePaths.AbsPathForScenario(fileName);

            LongEventHandler.QueueLongEvent(delegate
            {
                GameDataSaveLoader.SaveScenario(this.savingScen, absPath);
            }, "SavingLongEvent", false, null);
            Messages.Message("SavedAs".Translate(fileName), MessageTypeDefOf.SilentInput);
            this.Close(true);
        }
Example #14
0
 public static Dictionary <string, string> GetSyncableConfigFiles()
 {
     return(new DirectoryInfo(GenFilePaths.ConfigFolderPath)
            .GetFiles("*.xml", SearchOption.AllDirectories)
            .Concat(new DirectoryInfo(GenFilePaths.FolderUnderSaveData("HugsLib")).GetFiles("*.xml",
                                                                                            SearchOption.AllDirectories))
            .Where(FilterNonSyncedConfigFiles)
            .ToDictionary(
                file => ModManagement.ModConfigFileRelative(file.FullName, true),
                file => file.OpenText().ReadToEnd()
                ));
 }
Example #15
0
        private string NewAutosaveFileName()
        {
            string text = (from name in AutoSaveNames()
                           where !SaveGameFilesUtility.SavedGameNamedExists(name)
                           select name).FirstOrDefault();

            if (text != null)
            {
                return(text);
            }
            return(AutoSaveNames().MinBy((string name) => new FileInfo(GenFilePaths.FilePathForSavedGame(name)).LastWriteTime));
        }
Example #16
0
        private void ReloadFiles()
        {
            selectedFile = null;

            spSaves.Clear();
            mpReplays.Clear();

            foreach (FileInfo file in GenFilePaths.AllSavedGameFiles)
            {
                var saveFile = new SaveFile(Path.GetFileNameWithoutExtension(file.Name), false, file);

                using (var stream = file.OpenRead())
                    ReadSaveInfo(stream, saveFile);

                spSaves.Add(saveFile);
            }

            var replaysDir = new DirectoryInfo(GenFilePaths.FolderUnderSaveData("MpReplays"));

            foreach (var file in replaysDir.GetFiles("*.zip", MpVersion.IsDebug ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).OrderByDescending(f => f.LastWriteTime))
            {
                var replay = Replay.ForLoading(file);
                if (!replay.LoadInfo())
                {
                    continue;
                }

                var displayName = Path.ChangeExtension(file.FullName.Substring(Multiplayer.ReplaysDir.Length + 1), null);

                var saveFile = new SaveFile(displayName, true, file)
                {
                    gameName       = replay.info.name,
                    protocol       = replay.info.protocol,
                    replaySections = replay.info.sections.Count
                };

                mpReplays.Add(saveFile);

                if (!replay.info.rwVersion.NullOrEmpty())
                {
                    saveFile.rwVersion         = replay.info.rwVersion;
                    saveFile.modIds            = replay.info.modIds.ToArray();
                    saveFile.modNames          = replay.info.modNames.ToArray();
                    saveFile.modAssemblyHashes = replay.info.modAssemblyHashes.ToArray();
                }
                else
                {
                    using (var zip = replay.ZipFile)
                        ReadSaveInfo(zip["world/000_save"].OpenReader(), saveFile);
                }
            }
        }
Example #17
0
        protected override void DoFileInteraction(string fileName)
        {
            string filePath = GenFilePaths.AbsPathForScenario(fileName);

            PreLoadUtility.CheckVersionAndLoad(filePath, ScribeMetaHeaderUtility.ScribeHeaderMode.Scenario, delegate
            {
                Scenario obj = null;
                if (GameDataSaveLoader.TryLoadScenario(filePath, ScenarioCategory.CustomLocal, out obj))
                {
                    this.scenarioReturner(obj);
                }
                this.Close(true);
            });
        }
Example #18
0
 protected override void DoFileInteraction(string saveFileName)
 {
     PreLoadUtility.CheckVersionAndLoad(GenFilePaths.FilePathForSavedGame(saveFileName), ScribeMetaHeaderUtility.ScribeHeaderMode.Map, delegate
     {
         Action preLoadLevelAction = delegate
         {
             MemoryUtility.ClearAllMapsAndWorld();
             Current.Game                     = new Game();
             Current.Game.InitData            = new GameInitData();
             Current.Game.InitData.gameToLoad = saveFileName;
         };
         LongEventHandler.QueueLongEvent(preLoadLevelAction, "Play", "LoadingLongEvent", true, null);
     });
 }
Example #19
0
        public static Parser[] GenerateCustomParsers()
        {
            var outputFileName = $"{GenFilePaths.FolderUnderSaveData("RimDumper")}\\tmpDll.dll";

            outputFileName = Path.GetFullPath(outputFileName);
            var outputFileNameCecil = $"{outputFileName}.new";

            var(compiler, parameters) = CreateCompiler(outputFileName);

            AddReferencedAssemblies(parameters);
            var results = CompileAssembly(compiler, parameters);

            if (results.Errors.Count > 0)
            {
                foreach (CompilerError CompErr in results.Errors)
                {
                    LogFn log = CompErr.IsWarning ? (LogFn)Log.Warning : (LogFn)Log.Error;
                    log($"{Path.GetFileName(CompErr.FileName)}:{CompErr.Line}, CS{CompErr.ErrorNumber} - '{CompErr.ErrorText};");
                }
                return(Array.Empty <Parser>());
            }

            if (!File.Exists(outputFileName))
            {
                Log.Error($"Compiled assembly {outputFileName} not found!");
                return(Array.Empty <Parser>());
            }

            //var asm = results.CompiledAssembly;
            string internalAssemblyFileName = Guid.NewGuid().ToString(); // need to change internal dll name so that you can inject it many times

            RenameInternalDllName(outputFileName, outputFileNameCecil, internalAssemblyFileName);

            var asm = Assembly.Load(File.ReadAllBytes(outputFileNameCecil));

            // clean dlls
            if (File.Exists(outputFileName))
            {
                File.Delete(outputFileName);
            }
            if (File.Exists(outputFileNameCecil))
            {
                File.Delete(outputFileNameCecil);
            }

            return(GetParserInstances(asm));
        }
        public static void UpdateModVersionMetaHeader()
        {
            string rawFilePath = SaveFilePathCache;
            string filePath    = GenFilePaths.FilePathForSavedGame(rawFilePath);

            MetaHeaderUtility.BeginReading(filePath);
            List <ModMetaHeader> metaHeaders = new List <ModMetaHeader>();

            foreach (var modContentPack in LoadedModManager.RunningMods)
            {
                // var metadata = modContentPack.GetMetaData();
                var version = MetaHeaderUtility.GetVersionFromManifestFile(modContentPack);
                metaHeaders.Add(new ModMetaHeader()
                {
                    Identifier = modContentPack.PackageId, Version = version
                });
                SimpleLog.Log($"Add metadata to metaHeaders list : {modContentPack.PackageId}, {version}");
            }
            MetaHeaderUtility.SetVersions(metaHeaders);
            MetaHeaderUtility.EndReading();
        }
Example #21
0
        public static bool PreFSaveGame(string fileName)
        {
            try
            {
                Traverse traverse = Traverse.CreateWithType("GameDataSaveLoader").Field("lastSaveTick");
                SafeSaver.Save(GenFilePaths.FilePathForSavedGame(fileName), "savegame", delegate
                {
                    ScribeMetaHeaderUtility.WriteMetaHeader();
                    Game game = Current.Game;
                    Scribe_Deep.Look <Game>(ref game, "Κgame", new object[0]);
                });
                traverse.SetValue(Find.TickManager.TicksGame);
            }
            catch (Exception e)
            {
                Log.Message(string.Format("EXCEPTION! {0}.{1} \n\tMESSAGE: {2} \n\tException occurred calling {3} method", e.TargetSite.ReflectedType.Name,
                                          e.TargetSite.Name, e.Message));
            }

            return(false);
        }
        static IEnumerable <CodeInstruction> Nandonalt_ColonyLeadership_HediffLeader_Tick_Transpiler(IEnumerable <CodeInstruction> instructions, ILGenerator ilGen)
        {
            IEnumerable <CodeInstruction> transpiler()
            {
                bool counter = false, condition = false;

                foreach (var ci in instructions)
                {
                    if (!counter && ci.opcode == OpCodes.Ldc_I4_1)
                    {
                        yield return(new CodeInstruction(OpCodes.Ldc_I4_5));

                        counter = true;
                    }
                    else if (!condition && ci.opcode == OpCodes.Brtrue_S) // if ticksLeader == 0 goto ...
                    {
                        yield return(new CodeInstruction(OpCodes.Ldc_I4_1));

                        yield return(new CodeInstruction(OpCodes.Bge_S, ci.operand)); // if ticksLeader >= 1 goto ...

                        condition = true;
                    }
                    else
                    {
                        yield return(ci);
                    }
                }
            }

            var result = transpiler();

#if DEBUG
            var dir  = GenFilePaths.FolderUnderSaveData("TranspilerDebug");
            var code = instructions.ToList();
            File.WriteAllLines($"{dir}\\Nandonalt_ColonyLeadership_HediffLeader_Tick_Transpiler.before.txt", code.Select(x => x.ToString()));
            code = result.ToList();
            File.WriteAllLines($"{dir}\\Nandonalt_ColonyLeadership_HediffLeader_Tick_Transpiler.after.txt", code.Select(x => x.ToString()));
#endif
            return(result);
        }
Example #23
0
        private void ReloadFiles()
        {
            selectedFile = null;

            spSaves.Clear();
            mpReplays.Clear();

            foreach (FileInfo file in GenFilePaths.AllSavedGameFiles)
            {
                spSaves.Add(
                    new SaveFile(Path.GetFileNameWithoutExtension(file.Name), false, file)
                {
                    rwVersion = ScribeMetaHeaderUtility.GameVersionOf(file)
                }
                    );
            }

            var replaysDir = new DirectoryInfo(GenFilePaths.FolderUnderSaveData("MpReplays"));

            if (!replaysDir.Exists)
            {
                replaysDir.Create();
            }

            foreach (var file in replaysDir.GetFiles("*.zip").OrderByDescending(f => f.LastWriteTime))
            {
                var replay = Replay.ForLoading(file);
                replay.LoadInfo();

                mpReplays.Add(
                    new SaveFile(Path.GetFileNameWithoutExtension(file.Name), true, file)
                {
                    gameName = replay.info.name,
                    protocol = replay.info.protocol
                }
                    );
            }
        }
Example #24
0
        public static void ApplyHostModConfigFiles(Dictionary <string, string> hostModConfigFiles)
        {
            if (hostModConfigFiles == null)
            {
                Log.Warning("MP: hostModConfigFiles is null");
                return;
            }
            if (CheckModConfigsMatch(hostModConfigFiles))
            {
                return;
            }

            var localConfigsBackupDir = GenFilePaths.FolderUnderSaveData($"LocalConfigsBackup-{DateTime.Now:yyyy-MM-ddTHH-mm-ss}");

            (new DirectoryInfo(Path.Combine(localConfigsBackupDir, "Config"))).Create();

            foreach (var modConfigData in hostModConfigFiles)
            {
                var relativeFilePath = modConfigData.Key.Replace('/', Path.DirectorySeparatorChar);
                var filePath         = Path.Combine(GenFilePaths.SaveDataFolderPath, relativeFilePath);
                if (File.Exists(filePath))
                {
                    var backupFilePath = Path.Combine(localConfigsBackupDir, relativeFilePath);
                    Directory.GetParent(backupFilePath).Create();
                    File.Move(filePath, backupFilePath);
                }
                else
                {
                    Directory.GetParent(filePath).Create();
                }
                File.WriteAllText(filePath, modConfigData.Value);
            }

            File.Copy(
                Path.Combine(GenFilePaths.SaveDataFolderPath, "Config", "ModsConfig.xml"),
                Path.Combine(localConfigsBackupDir, "Config", "ModsConfig.xml")
                );
        }
Example #25
0
        private void DoThingTab(Rect rect)
        {
            if (!Analyzer.SelectedMode.IsPatched)
            {
                Text.Font   = GameFont.Medium;
                Text.Anchor = TextAnchor.MiddleCenter;
                Widgets.Label(rect, $"Loading{GenText.MarchingEllipsis(0f)}");
                Text.Font   = GameFont.Small;
                Text.Anchor = TextAnchor.UpperLeft;
                return;
            }

            var  topslot = rect.TopPartPixels(20f);
            Rect rowby   = topslot.LeftPartPixels(25f);

            if (Widgets.ButtonImage(rowby, TexButton.SpeedButtonTextures[Analyzer.running ? 0 : 1]))
            {
                Analyzer.running = !Analyzer.running;
            }

            TooltipHandler.TipRegion(rowby, "Start and stop logging");
            bool save = false;

            if (Analyzer.Settings.AdvancedMode)
            {
                Rect searchbox = topslot.LeftPartPixels(topslot.width - 300f);
                searchbox.x += 25f;
                DubGUI.InputField(searchbox, "Search", ref TimesFilter, DubGUI.MintSearch);
                rowby.x     = searchbox.xMax;
                rowby.width = 175f;
                if (Widgets.ButtonTextSubtle(rowby, stlank, Mathf.Clamp01(Mathf.InverseLerp(H_RootUpdate.LastMinGC, H_RootUpdate.LastMaxGC, totalBytesOfMemoryUsed)), 5))
                {
                    totalBytesOfMemoryUsed = GC.GetTotalMemory(true);
                }
                TooltipHandler.TipRegion(rowby, "Approximation of total bytes currently allocated in managed memory + rate of new allocation\n\nClick to force GC");

                rowby.x     = rowby.xMax;
                rowby.width = 100f;
                save        = Widgets.ButtonTextSubtle(rowby, "Save .CSV");
                TooltipHandler.TipRegion(rowby, $"Save the current list of times to a csv file in {GenFilePaths.FolderUnderSaveData("Profiling")}");
            }
            else
            {
                Rect searchbox = topslot.RightPartPixels(topslot.width - 25f);
                DubGUI.InputField(searchbox, "Search", ref TimesFilter, DubGUI.MintSearch);
            }

            rowby.x     = rowby.xMax;
            rowby.width = 25f;


            rect.y      += 25f;
            rect.height -= 25f;

            var innyrek = rect.AtZero();

            innyrek.width -= 16f;
            innyrek.height = groaner;

            GizmoListRect    = rect.AtZero();
            GizmoListRect.y += scrolpos.y;
            Widgets.BeginScrollView(rect, ref scrolpos, innyrek);

            GUI.BeginGroup(innyrek);

            listing.Begin(innyrek);

            float goat = 0;

            //List<ProfileLog> logs = null;

            //if (Analyzer.SortBy == "First")
            //{
            //    logs = Analyzer.Logs.ToList();
            //}
            //else if (Analyzer.SortBy == "A-Z")
            //{
            //    logs = Analyzer.Logs.ToList().OrderBy(x => x.Key).ToList();
            //}
            //else if (Analyzer.SortBy == "Usage")
            //{
            //    logs = Analyzer.Logs.ToList().OrderByDescending(x => x.Average).ToList();
            //}

            Text.Anchor = TextAnchor.MiddleLeft;
            Text.Font   = GameFont.Tiny;

            lock (Analyzer.sync)
            {
                foreach (var log in Analyzer.Logs)
                {
                    if (!log.Label.Has(TimesFilter))
                    {
                        continue;
                    }

                    var r = listing.GetRect(40f);

                    if (r.Overlaps(GizmoListRect))
                    {
                        var profile = Analyzer.Profiles[log.Key];

                        if (Input.GetKey(KeyCode.LeftControl))
                        {
                            if (Widgets.ButtonInvisible(r))
                            {
                                Analyzer.SelectedMode.Clicked?.Invoke(null, new object[] { profile, log });
                                Analyzer.Settings.Write();
                            }
                        }

                        bool on = true;

                        if (Analyzer.SelectedMode.Selected != null)
                        {
                            on = (bool)Analyzer.SelectedMode.Selected.Invoke(null, new object[] { profile, log });
                        }

                        if (Analyzer.SelectedMode.Checkbox != null)
                        {
                            var r2 = new Rect(r.x, r.y, 25f, r.height);
                            r.x += 25f;
                            if (DubGUI.Checkbox(r2, "", ref on))
                            {
                                Analyzer.SelectedMode.Checkbox?.Invoke(null, new object[] { profile, log });
                                Analyzer.Settings.Write();
                            }
                        }

                        Widgets.DrawHighlightIfMouseover(r);

                        if (Widgets.ButtonInvisible(r))
                        {
                            Dialog_Graph.RunKey(log.Key);
                        }

                        if (Dialog_Graph.key == log.Key)
                        {
                            Widgets.DrawHighlightSelected(r);
                        }


                        var col = grey;
                        if (log.Percent > 0.25f)
                        {
                            col = blue;
                        }

                        if (log.Percent > 0.75f)
                        {
                            col = red;
                        }


                        Widgets.FillableBar(r.BottomPartPixels(8f), log.Percent, col, clear, false);

                        r = r.LeftPartPixels(50);

                        if (!on)
                        {
                            GUI.color = Color.grey;
                        }

                        Widgets.Label(r, log.Average_s);

                        if (Analyzer.Settings.AdvancedMode)
                        {
                            r.x = r.xMax;

                            Widgets.Label(r, profile.memRiseStr);
                        }

                        r.x     = r.xMax;
                        r.width = 2000;
                        Widgets.Label(r, log.Label);

                        GUI.color = Color.white;

                        if (save)
                        {
                            csv.Append($"{log.Label},{log.Average},{profile.BytesUsed}");
                            foreach (var historyTime in profile.History.times)
                            {
                                csv.Append($",{historyTime}");
                            }
                            csv.AppendLine();
                        }
                    }
                    listing.GapLine(0f);
                    goat += 4f;
                    goat += r.height;
                }
            }

            if (save)
            {
                var path = GenFilePaths.FolderUnderSaveData("Profiling") + $"/{Analyzer.SelectedMode.name}_{DateTime.Now.ToFileTime()}.csv";
                File.WriteAllText(path, csv.ToString());
                csv.Clear();
                Messages.Message($"Saved to {path}", MessageTypeDefOf.TaskCompletion, false);
            }

            listing.End();
            groaner = goat;
            GUI.EndGroup();

            Text.Font   = GameFont.Small;
            Text.Anchor = TextAnchor.UpperLeft;
            Widgets.EndScrollView();
        }
Example #26
0
            public static void Listener(PawnGroupMakerParms parms, bool warnOnZeroResults, ref IEnumerable <Pawn> __result)
            {
                try {
                    //If active solar flare then no surrogates are generated to prevent ridiculous spawn of dawned surrogates
                    if (!Settings.otherFactionsCanUseSurrogate || Utils.ExceptionBlacklistedFactionNoSurrogate.Contains(parms.faction.def.defName) || Utils.getRandomMapOfPlayer().gameConditionManager.ConditionIsActive(GameConditionDefOf.SolarFlare) || (Settings.androidsAreRare && Rand.Chance(0.95f)))
                    {
                        return;
                    }

                    int nbHumanoids = 0;

                    foreach (var e in __result)
                    {
                        //Si humanoide
                        if (e.def.race != null && e.def.race.Humanlike)
                        {
                            //Si pas commercant
                            if (e.trader == null && e.TraderKind == null)
                            {
                                nbHumanoids++;
                            }

                            //Si android T1/T2 suppression traits ==> Je suis bete cest a cause des surrogates que j'ai crus qu'il avais des traits

                            /*if(e.def.defName == Utils.T1 || e.def.defName == Utils.T2)
                             * {
                             *  Utils.removeAllTraits(e);
                             * }*/
                        }
                    }

                    //Faction de niveau industriel et plus ET nb pawn généré supérieur ou égal à 5
                    if (parms.faction.def.techLevel >= TechLevel.Industrial && nbHumanoids >= 5)
                    {
                        List <Pawn> other = new List <Pawn>();
                        List <Pawn> ret   = new List <Pawn>();
                        List <Pawn> tmp   = __result.ToList();

                        //On supprime les non humains ET trader
                        //int nba = tmp.RemoveAll((Pawn x) => (x.def.race == null || !x.def.race.Humanlike || x.trader != null || x.TraderKind != null));
                        foreach (var x in tmp)
                        {
                            if (x.def.race == null || !x.def.race.Humanlike || x.trader != null || x.TraderKind != null)
                            {
                                other.Add(x);
                            }
                        }

                        //Purge dans list de travail
                        foreach (var e in other)
                        {
                            tmp.Remove(e);
                        }

                        //Log.Message(other.Count + " animaux et traders virés");

                        //Calcul nb pawn a recreer en mode surrogate
                        int nb = (int)(tmp.Count() * Rand.Range(Settings.percentageOfSurrogateInAnotherFactionGroupMin, Settings.percentageOfSurrogateInAnotherFactionGroup));
                        if (nb <= 0)
                        {
                            if (Settings.percentageOfSurrogateInAnotherFactionGroupMin == 0.0f)
                            {
                                return;
                            }
                            else
                            {
                                nb = 1;
                            }
                        }

                        //On va supprimer aleatoirement N pawns pour arriver a nb
                        while (tmp.Count > nb)
                        {
                            Pawn p = tmp.RandomElement();
                            other.Add(p);
                            tmp.Remove(p);
                        }

                        //Log.Message("HERE");
                        //On va se servir des nb pawn pregénéré par la fonction patché comme controller
                        for (int i = 0; i != nb; i++)
                        {
                            //PawnGenerationRequest request = new PawnGenerationRequest(Utils.AndroidsPKD[3], parms.faction, PawnGenerationContext.NonPlayer, parms.tile, false, false, false, false, true, false, 1f, false, true, true, false, false, false, false, null, null, null, null, null, null, null, null);
                            //Pawn surrogate = PawnGenerator.GeneratePawn(request);

                            PawnKindDef rpkd = null;

                            if (parms.groupKind == PawnGroupKindDefOf.Peaceful || parms.groupKind == PawnGroupKindDefOf.Trader)
                            {
                                if (Rand.Chance(0.10f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDNeutral[3];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDNeutral[3];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDNeutral[3];
                                    }
                                }
                                else if (Rand.Chance(0.35f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDNeutral[2];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDNeutral[2];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDNeutral[2];
                                    }
                                }
                                else if (Rand.Chance(0.55f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsPKDNeutral[1];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDNeutral[1];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDNeutral[1];
                                    }
                                }
                                else
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDNeutral[0];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDNeutral[0];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDNeutral[0];
                                    }
                                }
                            }
                            else
                            {
                                if (Rand.Chance(0.10f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDHostile[3];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDHostile[3];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDHostile[3];
                                    }
                                }
                                else if (Rand.Chance(0.35f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDHostile[2];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDHostile[2];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDHostile[2];
                                    }
                                }
                                else if (Rand.Chance(0.55f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsPKDHostile[1];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDHostile[1];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDHostile[1];
                                    }
                                }
                                else
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDHostile[0];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDHostile[0];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDHostile[0];
                                    }
                                }
                            }

                            //Utils.AndroidsPKD.RandomElement();
                            Pawn surrogate = Utils.generateSurrogate(parms.faction, rpkd, IntVec3.Invalid, null, false, true, parms.tile, true, parms.inhabitants);

                            //Si en mode rare alors override de la creation d'androides en ancient, on squeeze l'init du pawn
                            if (!surrogate.IsAndroidTier())
                            {
                                surrogate.Destroy();
                                ret.Add(tmp[i]);
                                continue;
                            }

                            //Log.Message("--Surrogate generated pour "+tmp[i].def.defName);

                            //On vire les equipements/inventaires/vetements du surrogate
                            if (surrogate.inventory != null && surrogate.inventory.innerContainer != null)
                            {
                                surrogate.inventory.innerContainer.Clear();
                            }

                            surrogate.apparel.DestroyAll();

                            surrogate.equipment.DestroyAllEquipment();


                            CompAndroidState cas = surrogate.ATCompState;
                            if (cas != null)
                            {
                                cas.externalController = tmp[i];
                                CompSurrogateOwner cso = tmp[i].ATCompSurrogateOwner;
                                if (cso != null)
                                {
                                    cso.setControlledSurrogate(surrogate, true);
                                }
                            }

                            //Transfere equipement
                            //Log.Message("--Traitement des equipements");
                            if (tmp[i].equipment != null && surrogate.equipment != null)
                            {
                                /*Pawn_EquipmentTracker pet = tmp[i].equipment;
                                 * pet.pawn = surrogate;
                                 * tmp[i].equipment = surrogate.equipment;
                                 * tmp[i].equipment.pawn = tmp[i];
                                 * surrogate.equipment = pet;*/
                                surrogate.equipment.DestroyAllEquipment();

                                foreach (var e in tmp[i].equipment.AllEquipmentListForReading.ToList())
                                {
                                    try
                                    {
                                        tmp[i].equipment.Remove(e);
                                        if (!(e.def.equipmentType == EquipmentType.Primary && surrogate.equipment.Primary != null))
                                        {
                                            surrogate.equipment.AddEquipment(e);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Message("[ATPP] PawnGroupMakerUtility.GeneratePawns.transfertEquipment " + ex.Message + " " + ex.StackTrace);
                                    }
                                }


                                foreach (var e in surrogate.equipment.AllEquipmentListForReading)
                                {
                                    try
                                    {
                                        if (Utils.CELOADED && e != null && e.def.IsRangedWeapon)
                                        {
                                            ThingComp ammoUser = Utils.TryGetCompByTypeName(e, "CompAmmoUser", "CombatExtended");
                                            if (ammoUser != null)
                                            {
                                                var      props        = Traverse.Create(ammoUser).Property("Props").GetValue();
                                                int      magazineSize = Traverse.Create(props).Field("magazineSize").GetValue <int>();
                                                ThingDef def          = Traverse.Create(ammoUser).Field("selectedAmmo").GetValue <ThingDef>();
                                                if (def != null)
                                                {
                                                    Traverse.Create(ammoUser).Method("ResetAmmoCount", new object[] { def }).GetValue();
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                            }

                            /*foreach(var e in tmp[i].equipment.AllEquipmentListForReading.ToList())
                             * {
                             *  e.
                             *  surrogate.equipment.AddEquipment(e);
                             * }*/


                            //Transfert vetements
                            if (tmp[i].apparel != null)
                            {
                                try
                                {
                                    //Log.Message("--Traitement des vetements");
                                    foreach (var e in tmp[i].apparel.WornApparel.ToList())
                                    {
                                        //Check si vetement peut etre porté par le surrogate
                                        string path = "";
                                        if (e.def.apparel.LastLayer == ApparelLayerDefOf.Overhead)
                                        {
                                            path = e.def.apparel.wornGraphicPath;
                                        }
                                        else
                                        {
                                            path = e.def.apparel.wornGraphicPath + "_" + surrogate.story.bodyType.defName + "_south";
                                        }

                                        Texture2D appFoundTex = null;
                                        Texture2D appTex      = null;
                                        //CHeck dans les mods de la texture
                                        for (int j = LoadedModManager.RunningModsListForReading.Count - 1; j >= 0; j--)
                                        {
                                            appTex = LoadedModManager.RunningModsListForReading[j].GetContentHolder <Texture2D>().Get(path);
                                            if (appTex != null)
                                            {
                                                appFoundTex = appTex;
                                                break;
                                            }
                                        }
                                        //Check RW mods  de la texture
                                        if (appFoundTex == null)
                                        {
                                            path        = GenFilePaths.ContentPath <Texture2D>() + path;
                                            appFoundTex = (Texture2D)((object)Resources.Load <Texture2D>(path));
                                        }

                                        //SI pb avec texture on ne l'ajoute pas
                                        if (appFoundTex != null)
                                        {
                                            tmp[i].apparel.Remove(e);
                                            surrogate.apparel.Wear(e);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.Message("[ATPP] PawnGroupMakerUtility.TransfertApparel " + ex.Message + " " + ex.StackTrace);
                                }
                            }


                            //Log.Message((tmp[i].inventory == null)+" "+(tmp[i].inventory.innerContainer == null)+" "+(surrogate.inventory == null)+" "+(surrogate.inventory.innerContainer== null));
                            //Inventaire
                            if (tmp[i].inventory != null && tmp[i].inventory.innerContainer != null && surrogate.inventory != null && surrogate.inventory.innerContainer != null)
                            {
                                //foreach (var e in tmp[i].inventory.innerContainer.ToList())
                                //{
                                //Log.Message("Items transfered " + tmp[i].inventory.innerContainer.Count);
                                try
                                {
                                    tmp[i].inventory.innerContainer.TryTransferAllToContainer(surrogate.inventory.innerContainer);

                                    //Suppression des drogues
                                    foreach (var el in surrogate.inventory.innerContainer.ToList())
                                    {
                                        if (el.def.IsDrug)
                                        {
                                            surrogate.inventory.innerContainer.Remove(el);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.Message("[ATPP] PawnGroupMakerUtility.GeneratePawns.transfertInventory " + ex.Message + " " + ex.StackTrace);
                                }
                                //}
                            }

                            ret.Add(surrogate);
                        }

                        //On remet dans le ret les autres pawns non "surogatisés"
                        __result = other.Concat(ret);
                    }
                }
                catch (Exception ex)
                {
                    Log.Message("[ATPP] PawnGroupMakerUtility.GeneratePawns " + ex.Message + " " + ex.StackTrace);
                }
            }
Example #27
0
        /// <summary>
        /// Generates a high quality texture from a PNG file.
        /// </summary>
        public static Texture2D GetHQTexture(string fileName, string folderName = null)
        {
            Texture2D texture = new Texture2D(2, 2, TextureFormat.ARGB32, false);             //Mipmaps off;

            ModContentPack content = LoadedModManager.RunningModsListForReading.Find(mod => mod.Name == ModName);

            if (content == null)
            {
                Log.Error($"Could not find '{ModName}' in the mod list.");

                return(texture);
            }

            string texturesPath = Path.Combine(content.RootDir, GenFilePaths.ContentPath <Texture2D>());

            string folderPath = folderName == null ? texturesPath : Path.Combine(new DirectoryInfo(texturesPath).ToString(), folderName);

            DirectoryInfo contentDirectory = new DirectoryInfo(folderPath);

            if (!contentDirectory.Exists)
            {
                Log.Error("Could not find specific textures folder");

                return(texture);
            }

            FileInfo image = null;

            foreach (FileInfo f in contentDirectory.GetFiles("*", SearchOption.AllDirectories))
            {
                if (Path.GetFileNameWithoutExtension(f.Name) == fileName)
                {
                    image = f;
                    break;
                }
            }

            if (image == null)
            {
                Log.Message($"Could not find texture for WorkType {fileName}. Using default for modded work.");

                Texture2D moddedWorkTexture = GetHQTexture("ModdedWork", folderName);

                if (moddedWorkTexture == null)
                {
                    Log.Error("Could not load default texture. Please verify mod installation.");

                    return(texture);
                }

                return(moddedWorkTexture);
            }

            byte[] fileData = File.ReadAllBytes(image.FullName);

            texture.LoadImage(fileData);             //Loads PNG data, sets format to ARGB32 and resizes texture by the source image size
            texture.name       = "DD_" + Path.GetFileNameWithoutExtension(fileName);
            texture.filterMode = FilterMode.Trilinear;
            texture.anisoLevel = 9;             //default 2, max 9

            /* texture.Compress(true); //Compresses texture
             * texture.Apply(false, false); //Saves the compressed texture */

            if (texture.width == 2)
            {
                Log.Error("Could not load high quality texture :: " + fileName);
            }

            return(texture);
        }
            public static void Listener(PawnGroupMakerParms parms, bool warnOnZeroResults, ref IEnumerable <Pawn> __result)
            {
                try
                {
                    if (!Settings.otherFactionsCanUseSurrogate || Utils.ExceptionBlacklistedFactionNoSurrogate.Contains(parms.faction.def.defName) ||
                        Utils.getRandomMapOfPlayer().gameConditionManager.ConditionIsActive(GameConditionDefOf.SolarFlare) || Settings.androidsAreRare && Rand.Chance(0.95f))
                    {
                        return;
                    }

                    IEnumerable <Pawn> pawn = __result as Pawn[] ?? __result.ToArray();
                    var nbHumanoids         = pawn.Where(e => e.def.race != null && e.def.race.Humanlike).Count(e => e.trader == null && e.TraderKind == null);


                    /*if(e.def.defName == Utils.T1 || e.def.defName == Utils.T2)
                     *  {
                     *      Utils.removeAllTraits(e);
                     *  }*/


                    if (parms.faction.def.techLevel < TechLevel.Industrial || nbHumanoids < 5)
                    {
                        return;
                    }

                    {
                        var ret = new List <Pawn>();
                        var tmp = pawn.ToList();


                        var other = tmp.Where(x => x.def.race == null || !x.def.race.Humanlike || x.trader != null || x.TraderKind != null).ToList();


                        foreach (var e in other)
                        {
                            tmp.Remove(e);
                        }


                        var nb = (int)(tmp.Count() * Rand.Range(Settings.percentageOfSurrogateInAnotherFactionGroupMin, Settings.percentageOfSurrogateInAnotherFactionGroup));
                        if (nb <= 0)
                        {
                            if (Settings.percentageOfSurrogateInAnotherFactionGroupMin == 0.0f)
                            {
                                return;
                            }

                            nb = 1;
                        }


                        while (tmp.Count > nb)
                        {
                            var p = tmp.RandomElement();
                            other.Add(p);
                            tmp.Remove(p);
                        }


                        for (var i = 0; i != nb; i++)
                        {
                            PawnKindDef rpkd = null;

                            if (parms.groupKind == PawnGroupKindDefOf.Peaceful || parms.groupKind == PawnGroupKindDefOf.Trader)
                            {
                                if (Rand.Chance(0.10f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDNeutral[3];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDNeutral[3];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDNeutral[3];
                                    }
                                }
                                else if (Rand.Chance(0.35f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDNeutral[2];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDNeutral[2];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDNeutral[2];
                                    }
                                }
                                else if (Rand.Chance(0.55f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsPKDNeutral[1];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDNeutral[1];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDNeutral[1];
                                    }
                                }
                                else
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDNeutral[0];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDNeutral[0];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDNeutral[0];
                                    }
                                }
                            }
                            else
                            {
                                if (Rand.Chance(0.10f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDHostile[3];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDHostile[3];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDHostile[3];
                                    }
                                }
                                else if (Rand.Chance(0.35f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDHostile[2];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDHostile[2];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDHostile[2];
                                    }
                                }
                                else if (Rand.Chance(0.55f))
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsPKDHostile[1];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDHostile[1];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDHostile[1];
                                    }
                                }
                                else
                                {
                                    if (!Utils.TXSERIE_LOADED || Rand.Chance(0.5f))
                                    {
                                        rpkd = Utils.AndroidsPKDHostile[0];
                                    }
                                    else if (Rand.Chance(0.75f))
                                    {
                                        rpkd = Utils.AndroidsXISeriePKDHostile[0];
                                    }
                                    else
                                    {
                                        rpkd = Utils.AndroidsXSeriePKDHostile[0];
                                    }
                                }
                            }


                            var surrogate = Utils.generateSurrogate(parms.faction, rpkd, IntVec3.Invalid, null, false, true, parms.tile, true, parms.inhabitants);


                            if (!surrogate.IsAndroidTier())
                            {
                                surrogate.Destroy();
                                ret.Add(tmp[i]);
                                continue;
                            }


                            if (surrogate.inventory != null && surrogate.inventory.innerContainer != null)
                            {
                                surrogate.inventory.innerContainer.Clear();
                            }

                            surrogate.apparel.DestroyAll();

                            surrogate.equipment.DestroyAllEquipment();


                            var cas = surrogate.TryGetComp <CompAndroidState>();
                            if (cas != null)
                            {
                                cas.externalController = tmp[i];
                                var cso = tmp[i].TryGetComp <CompSurrogateOwner>();
                                cso?.setControlledSurrogate(surrogate, true);
                            }


                            if (tmp[i].equipment != null && surrogate.equipment != null)
                            {
                                /*Pawn_EquipmentTracker pet = tmp[i].equipment;
                                 * pet.pawn = surrogate;
                                 * tmp[i].equipment = surrogate.equipment;
                                 * tmp[i].equipment.pawn = tmp[i];
                                 * surrogate.equipment = pet;*/
                                surrogate.equipment.DestroyAllEquipment();

                                foreach (var e in tmp[i].equipment.AllEquipmentListForReading.ToList())
                                {
                                    try
                                    {
                                        tmp[i].equipment.Remove(e);
                                        if (!(e.def.equipmentType == EquipmentType.Primary && surrogate.equipment.Primary != null))
                                        {
                                            surrogate.equipment.AddEquipment(e);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Message("[ATPP] PawnGroupMakerUtility.GeneratePawns.transfertEquipment " + ex.Message + " " + ex.StackTrace);
                                    }
                                }


                                foreach (var e in surrogate.equipment.AllEquipmentListForReading)
                                {
                                    try
                                    {
                                        if (!Utils.CELOADED || e == null || !e.def.IsRangedWeapon)
                                        {
                                            continue;
                                        }

                                        var ammoUser = Utils.TryGetCompByTypeName(e, "CompAmmoUser", "CombatExtended");
                                        if (ammoUser == null)
                                        {
                                            continue;
                                        }

                                        var props        = Traverse.Create(ammoUser).Property("Props").GetValue();
                                        var magazineSize = Traverse.Create(props).Field("magazineSize").GetValue <int>();
                                        var def          = Traverse.Create(ammoUser).Field("selectedAmmo").GetValue <ThingDef>();
                                        if (def != null)
                                        {
                                            Traverse.Create(ammoUser).Method("ResetAmmoCount", def).GetValue();
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                            }

                            /*foreach(var e in tmp[i].equipment.AllEquipmentListForReading.ToList())
                             * {
                             *  e.
                             *  surrogate.equipment.AddEquipment(e);
                             * }*/


                            if (tmp[i].apparel != null)
                            {
                                try
                                {
                                    foreach (var e in tmp[i].apparel.WornApparel.ToList())
                                    {
                                        var path = "";
                                        if (e.def.apparel.LastLayer == ApparelLayerDefOf.Overhead)
                                        {
                                            path = e.def.apparel.wornGraphicPath;
                                        }
                                        else
                                        {
                                            path = e.def.apparel.wornGraphicPath + "_" + surrogate.story.bodyType.defName + "_south";
                                        }

                                        Texture2D appFoundTex = null;

                                        for (var j = LoadedModManager.RunningModsListForReading.Count - 1; j >= 0; j--)
                                        {
                                            var appTex = LoadedModManager.RunningModsListForReading[j].GetContentHolder <Texture2D>().Get(path);
                                            if (appTex == null)
                                            {
                                                continue;
                                            }

                                            appFoundTex = appTex;
                                            break;
                                        }


                                        if (appFoundTex == null)
                                        {
                                            path        = GenFilePaths.ContentPath <Texture2D>() + path;
                                            appFoundTex = Resources.Load <Texture2D>(path);
                                        }


                                        if (appFoundTex == null)
                                        {
                                            continue;
                                        }

                                        tmp[i].apparel.Remove(e);
                                        surrogate.apparel.Wear(e);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.Message("[ATPP] PawnGroupMakerUtility.TransfertApparel " + ex.Message + " " + ex.StackTrace);
                                }
                            }


                            if (tmp[i].inventory != null && tmp[i].inventory.innerContainer != null && surrogate.inventory != null && surrogate.inventory.innerContainer != null)
                            {
                                try
                                {
                                    tmp[i].inventory.innerContainer.TryTransferAllToContainer(surrogate.inventory.innerContainer);


                                    foreach (var el in surrogate.inventory.innerContainer.ToList().Where(el => el.def.IsDrug))
                                    {
                                        surrogate.inventory.innerContainer.Remove(el);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.Message("[ATPP] PawnGroupMakerUtility.GeneratePawns.transfertInventory " + ex.Message + " " + ex.StackTrace);
                                }
                            }


                            ret.Add(surrogate);
                        }


                        __result = other.Concat(ret);
                    }
                }
                catch (Exception ex)
                {
                    Log.Message("[ATPP] PawnGroupMakerUtility.GeneratePawns " + ex.Message + " " + ex.StackTrace);
                }
            }
Example #29
0
        private string NewAutosaveFileName()
        {
            string text = (from name in this.AutoSaveNames()
                           where !SaveGameFilesUtility.SavedGameNamedExists(name)
                           select name).FirstOrDefault <string>();
            string result;

            if (text != null)
            {
                result = text;
            }
            else
            {
                string text2 = this.AutoSaveNames().MinBy((string name) => new FileInfo(GenFilePaths.FilePathForSavedGame(name)).LastWriteTime);
                result = text2;
            }
            return(result);
        }
Example #30
0
 private static DateTime <NewAutosaveFileName> m__1(string name)
 {
     return(new FileInfo(GenFilePaths.FilePathForSavedGame(name)).LastWriteTime);
 }