// This previews the contents of the savefile public void PreviewSave(string filename = "_autosave") { // Strings for the save directory and savefile string savePath = Application.dataPath + "/Saves"; string saveName = savePath + "/" + filename + ".txt"; // Sanity check: if the filename is "", assume it's "_autosave" if (filename == "") { saveName = savePath + "/_autosave.txt"; } // Try to open the file and preview its contents try { string saveString = File.ReadAllText(saveName); Savedata s = JsonConvert.DeserializeObject <Savedata>(saveString); string previewText = "Savefile: " + filename + "\n" + "City Funds: " + s.financialData + "\n" + "Game time: " + Timekeeper.SimpleDate(s.gameTime, 2000); ; _textSavefilePreview.text = previewText; } catch (FileNotFoundException) { _textSavefilePreview.text = "No data saved in slot to preview."; Debug.Log("[GameLoop]: Failed to find save for previewing."); } }
internal void CallPlugins(frmCareer frmCareer, CustomActivity parentActivity) { foreach (var plugin in MyActivePlugins) { using (var op_plugin = Timekeeper.StartSyncron("load_plugin_GetTabPage_Career_" + plugin.ToString(), parentActivity, CustomActivity.OperationType.DependencyOperation, plugin.ToString())) { var pages = plugin.GetTabPages(frmCareer); if (pages == null) { continue; } foreach (TabPage page in pages) { if (page != null) { if (!frmCareer.TabCharacterTabs.TabPages.Contains(page)) { frmCareer.TabCharacterTabs.TabPages.Add(page); } } } } } }
internal void CallPlugins(ToolStripMenuItem menu, CustomActivity parentActivity) { foreach (var plugin in MyActivePlugins) { using (var op_plugin = Timekeeper.StartSyncron("load_plugin_GetMenuItems_" + plugin.ToString(), parentActivity, CustomActivity.OperationType.DependencyOperation, plugin.ToString())) { var menuitems = plugin.GetMenuItems(menu); if (menuitems == null) { continue; } foreach (ToolStripMenuItem plugInMenu in menuitems) { if (plugInMenu != null) { if (!menu.DropDownItems.Contains(plugInMenu)) { menu.DropDownItems.Add(plugInMenu); } } } } } }
public void ImmediateSave(int tick = -100) { if (tick == -100) { tick = Timekeeper.getInstance().getTick(); } memComponent.hashtable[tick] = memComponent.memory; }
internal void LoadPlugins(CustomActivity parentActivity = null) { try { using (_ = Timekeeper.StartSyncron("LoadPlugins", parentActivity, CustomActivity.OperationType.DependencyOperation, _objMyDirectoryCatalog?.FullPath)) Initialize(); } catch (System.Security.SecurityException e) { string msg = "Well, something went wrong probably because we are not Admins. Let's just ignore it and move on." + Environment.NewLine + Environment.NewLine; Log.Warn(e, msg); } catch (ReflectionTypeLoadException e) { using (new FetchSafelyFromPool <StringBuilder>(Utils.StringBuilderPool, out StringBuilder sbdMessage)) { sbdMessage.AppendLine("Exception loading plugins: "); foreach (Exception exp in e.LoaderExceptions) { sbdMessage.AppendLine(exp.Message); } sbdMessage.AppendLine(); sbdMessage.Append(e); Log.Warn(e, sbdMessage.ToString()); } } catch (CompositionException e) { using (new FetchSafelyFromPool <StringBuilder>(Utils.StringBuilderPool, out StringBuilder sbdMessage)) { sbdMessage.AppendLine("Exception loading plugins: "); foreach (CompositionError exp in e.Errors) { sbdMessage.AppendLine(exp.Exception.ToString()); } sbdMessage.AppendLine(); sbdMessage.Append(e); Log.Error(e, sbdMessage.ToString()); } } catch (ApplicationException) { throw; } catch (Exception e) { string msg = "Exception loading plugins: " + Environment.NewLine; msg += Environment.NewLine; msg += e.ToString(); Log.Error(e, msg); } }
// Update is called once per frame void FixedUpdate() { int tick = Timekeeper.getInstance().getTick(); // If it's before or after the active period, byebye if ((tick < memComponent.firstActiveTick) || (tick > memComponent.lastActiveTick)) { transform.position = new Vector3(-100, -100, -10); return; } // Else we have to update the position and opacity etc. switch (memComponent.state) { case Memory.MemoryEvent.reposition: if (memComponent.position == memComponent.destPosition) { // Staying still; transform.position = MapGenerator.PositionFor(memComponent.position, -1); } else // Need to tween movement { transform.position = MapGenerator.PositionFor(memComponent.position, memComponent.destPosition, memComponent.progress); } // Update sprite for rotation int rotation = memComponent.position.third; if (animator != null) { animator.SetInteger("Direction", memComponent.position.third); animator.transform.rotation = Quaternion.identity; } transform.rotation = directions[rotation]; break; case Memory.MemoryEvent.appearing: spriteRenderer.color = new Color(1, 1, 1, memComponent.progress); break; case Memory.MemoryEvent.disappearing: spriteRenderer.color = new Color(1, 1, 1, 1.0f - memComponent.progress); break; case Memory.MemoryEvent.inactive: spriteRenderer.color = Color.clear; break; } }
internal void LoadPlugins(CustomActivity parentActivity) { try { using (var op_plugin = Timekeeper.StartSyncron("LoadPlugins", parentActivity, CustomActivity.OperationType.DependencyOperation, myDirectoryCatalog?.FullPath)) { this.Initialize(); } } catch (System.Security.SecurityException e) { string msg = "Well, something went wrong probably because we are not Admins. Let's just ignore it and move on." + Environment.NewLine + Environment.NewLine; Console.WriteLine(msg + e.Message); System.Diagnostics.Trace.TraceWarning(msg + e.Message); return; } catch (ReflectionTypeLoadException e) { string msg = "Exception loading plugins: " + Environment.NewLine; foreach (var exp in e.LoaderExceptions) { msg += exp.Message + Environment.NewLine; } msg += Environment.NewLine; msg += e.ToString(); Log.Warn(e, msg); } catch (CompositionException e) { string msg = "Exception loading plugins: " + Environment.NewLine; foreach (var exp in e.Errors) { msg += exp.Exception + Environment.NewLine; } msg += Environment.NewLine; msg += e.ToString(); Log.Error(e, msg); } catch (ApplicationException e) { throw; } catch (Exception e) { string msg = "Exception loading plugins: " + Environment.NewLine; msg += Environment.NewLine; msg += e.ToString(); Log.Error(e, msg); } }
private static void Main(string[] args) { var timekeeper = new Timekeeper(); // Timekeeper allows us to measure how long an action takes to run var elapsed = timekeeper.Measure(() => { // var numbers = new[] { 3, 5, 7, 9, 11, 13 }; // using GetLazyRandomNumber() now for a stream of numbers foreach (var prime in GetLazyRandomNumber(100).Find(IsPrime).Take(2)) { Console.WriteLine("Prime number found: {0}", prime); } }); Console.WriteLine("The elapsed time was {0}", elapsed); Console.ReadLine(); // Partial example var client = new WebClient(); Func <string, string> download = url => client.DownloadString(url); var data = download.Partial("https://api.tlopo.com/system/status/").WithRetry(); Console.WriteLine("Using Partial function with retry returns the following string: \nn" + data); Console.ReadLine(); // Curry example // build a Func of string that returns a func of string Func <string, Func <string> > downloadCurry = download.Curry(); var data2 = downloadCurry("https://api.tlopo.com/system/status/").WithRetry(); Console.WriteLine("Using Curry function with retry returns the following string: \n\n" + data2); // Now let's use TPL Async and Task in functional programming. elapsed = timekeeper.Measure(() => FindLargePrimes(900000, 1000000)); Console.WriteLine("Finding all prime numbers took: {0}", elapsed); // now use Async() elapsed = timekeeper.Measure(() => FindLargePrimesAsynch(900000, 1000000)); Console.WriteLine("Finding all prime numbers in parallel took: {0}", elapsed); // now use Task var task = new Task <IEnumerable <int> >(() => FindLargePrimes(3, 100)); var task2 = task.ContinueWith((prev) => { foreach (var number in prev.Result) { Console.WriteLine("The number found was {0}", number); } }); task.Start(); Console.WriteLine("Doing some other work right now"); task2.Wait(); }
void Start() { timeKeeper = FindObjectOfType <Timekeeper>(); complete = spawning = false; text_tasklist.text = "Level 1 Goal: Raise Thrust Cap to 45%\n\nMini-Goal: Collect a full set of gas canisters\n" + "(for a small boost to Thrust Cap)"; text_countdown.text = ""; text_subCountdown.text = ""; StartCoroutine(DoSpawn()); }
void Init() { audioSources = GetComponents <AudioSource>(); thisRigidbody = GetComponent <Rigidbody>(); thrustParticleSystem = GetComponent <ParticleSystem>(); fishDrones = FindObjectsOfType <FishDrone>(); fishPool = FindObjectOfType <FishPool>(); glueCam = FindObjectOfType <GlueCam>(); musicPlayer = FindObjectOfType <MusicPlayer>(); pickupTracker = FindObjectOfType <PickupTracker>(); pilot = FindObjectOfType <Pilot>(); timeKeeper = FindObjectOfType <Timekeeper>(); uiControl = FindObjectOfType <UIcontrol>(); cockpit = GameObject.FindGameObjectWithTag("Cockpit"); thrusterBell = GameObject.FindGameObjectWithTag("Thruster_Bell"); thrustLight = GameObject.FindGameObjectWithTag("Thruster_Light"); tutorialText = GameObject.FindGameObjectWithTag("Tutorial_Text"); debugMode = Debug.isDebugBuild; startPosition = transform.position; startRotation = transform.rotation; thrustAudioLength = thrustSound.length; thrustAudioTimer = 0 - thrustAudioLength; thrustBubbles = thrustParticleSystem.emission; thrustAudio = audioSources[0]; xAudio = audioSources[1]; casualMode = false; deRotating = false; invulnerable = false; paused = false; thrustAudioTrack = true; tutorialIsVisible = true; AdjustEmissionRate(EMISSION_RATE_INACTIVE); thrustPowerSlider.maxValue = THRUST_MAX; thrustPowerSlider.minValue = THRUST_MIN; thrustPowercapSlider.minValue = 0f; thrustPowercapSlider.maxValue = 1f; thrustPowercapSlider.value = maxPower; SetPower(INITIAL_POWER_LEVEL); DoPowercapUpdate(); gasLevelSlider.maxValue = FUEL_MAX; gasLevelSlider.minValue = 0; gasLevelSlider.value = fuelLevel; DoGasUpdate(); pilotNameText.text = pilot.ID; IndicateMode(); }
void OnTriggerEnter2D(Collider2D other) { // Check the provided Collider2D parameter other to see if it is tagged // "PickUp", if it is... if (other.gameObject.CompareTag("Player")) { timekeeper = Timekeeper.getInstance(); startTime = timekeeper.getTime(); hasEntered = true; } }
void generatePath() { Timekeeper timekeeper = Timekeeper.getInstance(); Tuple3I position = memComponent.position; int startTick = timekeeper.getTick(); int moveTick = timekeeper.GetTickIn(fadeTime); float tickIncrement = 1.0f / (moveTick - startTick); float progress = 0; Memory memory; // Add first reposition memory memory = new Memory(Memory.MemoryEvent.reposition, position); memComponent.hashtable[moveTick] = memory; // Create appearing animation for (int tick = startTick + 1; tick <= moveTick; tick++) { memory = new Memory(Memory.MemoryEvent.appearing, progress += tickIncrement); memComponent.hashtable[tick] = memory; } int speedTicks = timekeeper.GetTickIn(speed) - timekeeper.getTick(); moveTick++; // Add subsequent reposition memories while (MapGenerator.GetPathValueFor(position) != 1) { moveTick += speedTicks; if ((moveTick - startTick) / speedTicks > 1000) // more than 1000 steps { Debug.Log("Path taking too long!"); return; } position = NextPathFor(position); memory = new Memory(Memory.MemoryEvent.reposition, position); memComponent.hashtable[moveTick] = memory; } // Add animation for climbing the ladder position.third = 1; Tuple3I newPosition = position + new Tuple3I(1, 0, 0); for (int i = 0; i < 16; i++) { memory = new Memory(Memory.MemoryEvent.reposition, position, newPosition, i * 1.0f / 16); memComponent.hashtable[moveTick + i] = memory; } }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); List <PopupOption <string> > options = new List <PopupOption <string> >(); if (UnityObject.FindObjectOfType <Timekeeper>() != null) { Timekeeper timekeeper = Timekeeper.instance; foreach (GlobalClock globalClock in timekeeper .GetComponents <GlobalClock>() .Where(gc => !string.IsNullOrEmpty(gc.key))) { options.Add(new PopupOption <string>(globalClock.key)); } } PopupOption <string> selectedOption; if (options.Any(o => o.value == property.stringValue)) { selectedOption = new PopupOption <string>(property.stringValue); } else if (!string.IsNullOrEmpty(property.stringValue)) { selectedOption = new PopupOption <string>(property.stringValue, property.stringValue + " (Missing)"); } else { selectedOption = null; } PopupOption <string> noneOption = new PopupOption <string>(null, "None"); var currentProperty = property; position = EditorGUI.PrefixLabel(position, label); PopupGUI <string> .Render ( position, gc => ChangeValue(currentProperty, gc), options, selectedOption, noneOption, property.hasMultipleDifferentValues ); EditorGUI.EndProperty(); }
float GetTeamTime(Team team) { Timekeeper whiteKeeper = board.currentGame.whiteTimekeeper; Timekeeper blackKeeper = board.currentGame.blackTimekeeper; whiteKeeper.rwl.AcquireReaderLock(1); blackKeeper.rwl.AcquireReaderLock(1); float time = team == Team.White ? whiteKeeper.elapsed : blackKeeper.elapsed; whiteKeeper.rwl.ReleaseReaderLock(); blackKeeper.rwl.ReleaseReaderLock(); return(time); }
// Update is called once per frame void Update() { if (spriteRenderer == null) { return; } if (MapGenerator.GetPathValueFor(memComponent.position) <= 5 && MapGenerator.GetPathValueFor(memComponent.position) != 1) { alertObj.SetActive(true); } else { alertObj.SetActive(false); } if (observed.first == observed.second) { spriteRenderer.color = new Color(1, 1, 1, 1.0f); int tick = Timekeeper.getInstance().getTick(); if ((tick <= memComponent.firstActiveTick) || (tick >= memComponent.lastActiveTick)) { return; } memComponent.lastActiveTick = tick; memComponent.SetInactive(); GetComponent <MemorySystem>().ImmediateSave(); memComponent.enabled = false; GetComponent <MovementSystem>().enabled = false; this.enabled = false; GetComponent <AudioSource>().Play(); GetComponent <AnimatorChildComponent>().animator.runtimeAnimatorController = disappearAnimation; spriteRenderer.sprite = disappearSprite; chargeComponent.Increment(); } else { spriteRenderer.color = new Color(1, 1, 1, 1.0f - (float)observed.first / observed.second); } }
// Use this for initialization void Start() { playerControllerSystem = GetComponent <PlayerControllerSystem>(); timekeeper = GetComponent <Timekeeper>(); foreach (Button button in pauseButtons) { button.onClick.AddListener(Pause); } foreach (Button button in resumeButtons) { button.onClick.AddListener(Resume); } semaphore = 0; }
public void Spawn(int[] enemies) { Timekeeper timekeeper = Timekeeper.getInstance(); foreach (GameObject enemy in currentEnemies) { Destroy(enemy, 1.0f); } currentEnemies.Clear(); int spritesLength = enemyAnimators.Length; int spriteIndex = Random.Range(0, spritesLength); // Spawn for each entangled group for (int i = 0; i < enemies.Length; i++) { GameObject[] twins = new GameObject[enemies[i]]; TupleI observed = new TupleI(0, enemies[i]); for (int j = 0; j < enemies[i]; j++) { GameObject newEnemy = Instantiate(enemyPrefab, Vector3.zero, Quaternion.identity); twins[j] = newEnemy; newEnemy.name = "Enemy-" + wave + "-" + i + "-" + j; currentEnemies.Add(newEnemy); newEnemy.GetComponent <MemoryComponent>().position = randomValidPosition(); newEnemy.GetComponent <MemoryComponent>().firstActiveTick = timekeeper.getTick(); newEnemy.GetComponent <AnimatorChildComponent>().animator. runtimeAnimatorController = enemyAnimators[spriteIndex]; EnemyObservingSystem observer = newEnemy.GetComponent <EnemyObservingSystem>(); observer.twins = twins; observer.observed = observed; observer.spawnSystem = this; observer.chargeComponent = GetComponent <ChargeComponent>(); } spriteIndex = (spriteIndex + 1) % spritesLength; } }
public void StartTimekeeper() { whiteTimekeeper = new Timekeeper(!hasClock ? timerDuration > 0 ? timerDuration : (float?)null : (float?)null); blackTimekeeper = new Timekeeper(!hasClock ? timerDuration > 0 ? timerDuration : (float?)null : (float?)null); whiteTimekeeper.onTimerElapsed += () => Flagfall(Team.White); blackTimekeeper.onTimerElapsed += () => Flagfall(Team.Black); RecalculateTimekeepers(); Team currentTurn = GetCurrentTurn(); Timekeeper toPlay = GetCurrentTurn() == Team.White ? whiteTimekeeper : blackTimekeeper; toPlay.Play(); }
// readiness/unstable public IActionResult Unstable() { // This endpoint will change the return status from 200 to 500 every minute var minutesFromStart = Timekeeper.GetMinutesFromStart(); if (minutesFromStart % 2 != 0) { _logger.LogInformation($"{minutesFromStart} min from the start -> response with 200"); return(Ok("[lab-05 task #5] - ready")); } else { _logger.LogInformation($"{minutesFromStart} min from the start -> response with 500"); return(StatusCode(500)); } }
//-------------------------------------------// /// <summary> /// Initialize a new stats /// </summary> public Stats(int logTime) { _connectLock = new Lock(); _attemptLock = new Lock(); _processLock = new Lock(); _assetLock = new Lock(); _readLock = new Lock(); Assets = new Dictionary <string, Teple <long, long> >(); AssetTicks = new Dictionary <string, long>(); _startTime = DateTime.Now; _time = new Timekeeper(); _time.Start(); LogTime = logTime; }
private Canvas panelCanvas; // Canvas the panel is a child of // Activate the panel, play sound effect, pause the game public void PanelAndPause(bool activate) { pausePanel.SetActive(activate); Timekeeper.PauseGame(activate); SoundPlayer.Instance.PlaySoundEffect(quickClip); // If panel is activating, make the sorting order of the canvas arbitrarily large if (activate) { panelCanvas.sortingOrder = 10; } // Otherwise, make the sorting order zero else { panelCanvas.sortingOrder = 0; } }
// Update is called once per frame void Update() { int tick = Timekeeper.getInstance().getTick(); if ((tick < memComponent.firstActiveTick) || (tick > memComponent.lastActiveTick)) { return; } if (memComponent.hashtable.ContainsKey(tick)) { memComponent.memory = (Memory)memComponent.hashtable[tick]; } else if (memComponent.memory != null) { memComponent.hashtable[tick] = memComponent.memory; } }
// health/almost_healthy public IActionResult AlmostHealthy() { // For the first 10 seconds that the app is alive, the /health/almost_healthy handler returns a status of 200. // After that, the handler returns a status of 500. var secondsFromStart = Timekeeper.GetSecondsFromStart(); _logger.LogInformation($"{secondsFromStart} seconds from start..."); var secondsToWait = 10; if (secondsFromStart < secondsToWait) { _logger.LogInformation($"< {secondsToWait} seconds -> response with 200"); return(Ok("[lab-05 task #2] - healthy first 10 sec")); } else { _logger.LogInformation($"> {secondsToWait} seconds -> response with 500"); return(StatusCode(500)); } }
void Start() { leaderBoard = dreamloLeaderBoard.GetSceneDreamloLeaderboard(); pilot = FindObjectOfType <Pilot>(); pilot_ID_Field = FindObjectOfType <Pilot_ID_Field>(); readout = GetComponent <TextMeshProUGUI>(); timeKeeper = FindObjectOfType <Timekeeper>(); if (WebGL) { webGL = true; } else { leaderBoard.LoadScores(); } records.Clear(); pilot_ID_Field.PilotID = pilot.ID; pilot_ID_Field.SetID(); // triggers a parse }
internal void CallPlugins(CharacterCreate frmCreate, CustomActivity parentActivity) { foreach (IPlugin plugin in MyActivePlugins) { using (_ = Timekeeper.StartSyncron("load_plugin_GetTabPage_Create_" + plugin, parentActivity, CustomActivity.OperationType.DependencyOperation, plugin.ToString())) { IEnumerable <TabPage> pages = plugin.GetTabPages(frmCreate); if (pages == null) { continue; } foreach (TabPage page in pages) { if (page != null && !frmCreate.TabCharacterTabs.TabPages.Contains(page)) { frmCreate.TabCharacterTabs.TabPages.Add(page); } } } } }
public static void Main(string[] args) { SetTitle(); var employee1 = new Employee("Bob", Mediator); var employee2 = new Employee("Ethel", Mediator); var employee3 = new Employee("Jimmy", Mediator); var employee4 = new Employee("Gregory", Mediator); var employee5 = new Employee("Phyllis", Mediator); var timekeeper = new Timekeeper(Mediator); Mediator.RegisterRecipients(new List <Person> { employee1, employee2, employee3, employee4, employee5, timekeeper }); employee1.Send("Good Morning everyone!"); Hr(); employee1.SubmitTime(new Timesheet(24)); employee2.SubmitTime(new Timesheet(38)); employee3.SubmitTime(new Timesheet(14)); employee4.SubmitTime(new Timesheet(35)); employee5.SubmitTime(new Timesheet(42)); Hr(); timekeeper.PrintPayroll(); Write("\nDone\n"); if (Debugger.IsAttached) { Console.Write("Press Enter to exit... "); Console.ReadLine(); } }
public void ApplyDamage(int amount) { if (amount < _damageResistance) { return; } else { amount -= _damageResistance; } if (!_isTakingDamage && amount > 0) { ApplyDeduct(amount); if (Health.IsAlive) { OnDamage(); OnActorDamaged.Raise(this); _isTakingDamage = true; Timekeeper.SetTimer(_damageInvulnerabilityDuration, () => _isTakingDamage = false); } } }
//-------------------------------------------// /// <summary> /// Initialize a new Web Crawler. /// </summary> public Crawler(CrawlSession session) { _session = session; _timer = new Timer(3000, OnTimeout, true); _time = new Timekeeper(); // init the lock _lock = new Lock(); // create the common tasks _stopped = new Act(OnStopped); _timeout = new Act(OnTimeout); _preConnect = new Act(PreConnect); _connect = new Act(Connect); _preProcess = new Act(PreProcess); _process = new Act(Process); _postProcess = new Act(PostProcess); // cache common decoders _utf8 = Encoding.UTF8.GetDecoder(); _ascii = Encoding.ASCII.GetDecoder(); // start byte buffer _bytes = new byte[_session.CrawlerByteBuffer]; // start the initial char buffer _chars = new char[Encoding.UTF8.GetMaxCharCount(_session.CrawlerByteBuffer)]; // start the urls collection _urls = new Queue <Url>(); // init the cookie container Cookies = new CookieContainer(_session.CrawlerMaxCookieCount, _session.CrawlerMaxCookieCount, _session.CrawlerMaxCookieSize); // set a default url Url = Url.Empty; }
static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); var tk = new Timekeeper("Central Standard Time"); var selfSatisfiedTask = new Task { Execute = dt => { var msg = string.Format("Executed at {0}!", dt); System.Console.WriteLine("Executed at {0}!", dt); return new TaskResult { Message = msg }; }, FriendlyName = "Self Satisfied Task" }; var exceptionThrowingTask = new Task { Execute = dt => { var msg = string.Format("About to throw an exception at {0}!", dt); int i = 0; int never = 5/i; return new TaskResult { Message = msg }; }, FriendlyName = "Exception Throwing Task" }; tk.ScheduleForEveryHour(selfSatisfiedTask); tk.ScheduleForEveryHour(exceptionThrowingTask); tk.ExceptionHandler += (task, ex) => System.Console.WriteLine("[Exception Handler] Exception for {0}: {1}", task.FriendlyName, ex); tk.CompletedHandler += (task, result) => System.Console.WriteLine("[Completed Handler] {0} completed with a message of {1}", task.FriendlyName,result.Message); TimekeeperClock.Now = () => new DateTime(2010,2,17,2,59,59); tk.Start(); System.Console.ReadLine(); TimekeeperClock.Now = () => new DateTime(2010,2,17,3,0,1); System.Console.WriteLine("Press enter to exit."); System.Console.ReadLine(); }
internal void Load(XmlNode skillNode, bool legacy = false) { if (skillNode == null) { return; } Timekeeper.Start("load_char_skills"); if (!legacy) { Timekeeper.Start("load_char_skills_groups"); List <SkillGroup> loadingSkillGroups = new List <SkillGroup>(); foreach (XmlNode node in skillNode.SelectNodes("groups/group")) { SkillGroup skillgroup = SkillGroup.Load(_character, node); if (skillgroup != null) { loadingSkillGroups.Add(skillgroup); } } loadingSkillGroups.Sort((i1, i2) => String.Compare(i2.DisplayName, i1.DisplayName, StringComparison.Ordinal)); foreach (SkillGroup skillgroup in loadingSkillGroups) { SkillGroups.Add(skillgroup); } Timekeeper.Finish("load_char_skills_groups"); Timekeeper.Start("load_char_skills_normal"); //Load skills. Because sorting a BindingList is complicated we use a temporery normal list List <Skill> loadingSkills = new List <Skill>(); foreach (XmlNode node in skillNode.SelectNodes("skills/skill")) { Skill skill = Skill.Load(_character, node); if (skill != null) { loadingSkills.Add(skill); } } loadingSkills.Sort(CompareSkills); foreach (Skill skill in loadingSkills) { _skills.Add(skill); } Timekeeper.Finish("load_char_skills_normal"); Timekeeper.Start("load_char_skills_kno"); foreach (XmlNode node in skillNode.SelectNodes("knoskills/skill")) { KnowledgeSkill skill = Skill.Load(_character, node) as KnowledgeSkill; if (skill != null) { KnowledgeSkills.Add(skill); } } Timekeeper.Finish("load_char_skills_kno"); Timekeeper.Start("load_char_knowsoft_buffer"); // Knowsoft Buffer. foreach (XmlNode objXmlSkill in skillNode.SelectNodes("skilljackknowledgeskills/skill")) { string strName = string.Empty; if (objXmlSkill.TryGetStringFieldQuickly("name", ref strName)) { KnowsoftSkills.Add(new KnowledgeSkill(_character, strName)); } } Timekeeper.Finish("load_char_knowsoft_buffer"); } else { List <Skill> tempSkillList = new List <Skill>(); foreach (XmlNode node in skillNode.SelectNodes("skills/skill")) { Skill skill = Skill.LegacyLoad(_character, node); if (skill != null) { tempSkillList.Add(skill); } } List <Skill> unsoredSkills = new List <Skill>(); //Variable/Anon method as to not clutter anywhere else. Not sure if clever or stupid Predicate <Skill> oldSkillFilter = skill => { if (skill.Rating > 0) { return(true); } if (skill.SkillCategory == "Resonance Active" && !_character.RESEnabled) { return(false); } //This could be more fine grained, but frankly i don't care if (skill.SkillCategory == "Magical Active" && !_character.MAGEnabled) { return(false); } return(true); }; foreach (Skill skill in tempSkillList) { KnowledgeSkill knoSkill = skill as KnowledgeSkill; if (knoSkill != null) { KnowledgeSkills.Add(knoSkill); } else if (oldSkillFilter(skill)) { unsoredSkills.Add(skill); } } unsoredSkills.Sort(CompareSkills); unsoredSkills.ForEach(x => _skills.Add(x)); UpdateUndoList(skillNode); } //This might give subtle bugs in the future, //but right now it needs to be run once when upgrading or it might crash. //As some didn't they crashed on loading skills. //After this have run, it won't (for the crash i'm aware) //TODO: Move it to the other side of the if someday? //remove skillgroups whose skills did not make the final cut for (var i = SkillGroups.Count - 1; i >= 0; i--) { if (!SkillGroups[i].GetEnumerable().Any(x => Skills.Contains(x))) { SkillGroups.RemoveAt(i); i--; } } //Workaround for probably breaking compability between earlier beta builds if (skillNode["skillptsmax"] == null) { skillNode = skillNode.OwnerDocument["character"]; } int intTmp = 0; if (skillNode.TryGetInt32FieldQuickly("skillptsmax", ref intTmp)) { SkillPointsMaximum = intTmp; } if (skillNode.TryGetInt32FieldQuickly("skillgrpsmax", ref intTmp)) { SkillGroupPointsMaximum = intTmp; } skillNode.TryGetBoolFieldQuickly("uneducated", ref _blnUneducated); skillNode.TryGetBoolFieldQuickly("uncouth", ref _blnUncouth); skillNode.TryGetBoolFieldQuickly("schoolofhardknocks", ref _blnSchoolOfHardKnocks); skillNode.TryGetBoolFieldQuickly("collegeeducation", ref _blnCollegeEducation); skillNode.TryGetBoolFieldQuickly("jackofalltrades", ref _blnJackOfAllTrades); skillNode.TryGetBoolFieldQuickly("techschool", ref _blnTechSchool); skillNode.TryGetBoolFieldQuickly("linguist", ref _blnLinguist); Timekeeper.Finish("load_char_skills"); }
internal void Load(XmlNode xmlSkillNode, bool blnLegacy = false) { if (xmlSkillNode == null) { return; } Timekeeper.Start("load_char_skills"); if (!blnLegacy) { Timekeeper.Start("load_char_skills_groups"); List <SkillGroup> lstLoadingSkillGroups = new List <SkillGroup>(); using (XmlNodeList xmlGroupsList = xmlSkillNode.SelectNodes("groups/group")) if (xmlGroupsList != null) { foreach (XmlNode xmlNode in xmlGroupsList) { SkillGroup objGroup = new SkillGroup(_objCharacter); objGroup.Load(xmlNode); lstLoadingSkillGroups.Add(objGroup); } } lstLoadingSkillGroups.Sort((i1, i2) => string.Compare(i2.DisplayName, i1.DisplayName, StringComparison.Ordinal)); foreach (SkillGroup skillgroup in lstLoadingSkillGroups) { SkillGroups.Add(skillgroup); } Timekeeper.Finish("load_char_skills_groups"); Timekeeper.Start("load_char_skills_normal"); //Load skills. Because sorting a BindingList is complicated we use a temporery normal list List <Skill> lstLoadingSkills = new List <Skill>(); using (XmlNodeList xmlSkillsList = xmlSkillNode.SelectNodes("skills/skill")) if (xmlSkillsList != null) { foreach (XmlNode xmlNode in xmlSkillsList) { Skill objSkill = Skill.Load(_objCharacter, xmlNode); if (objSkill != null) { lstLoadingSkills.Add(objSkill); } } } lstLoadingSkills.Sort(CompareSkills); foreach (Skill objSkill in lstLoadingSkills) { string strName = objSkill.IsExoticSkill ? $"{objSkill.Name} ({objSkill.DisplaySpecializationMethod(GlobalOptions.DefaultLanguage)})" : objSkill.Name; bool blnDoAddToDictionary = true; _lstSkills.MergeInto(objSkill, CompareSkills, (objExistSkill, objNewSkill) => { blnDoAddToDictionary = false; if (objNewSkill.Base > objExistSkill.Base) { objExistSkill.Base = objNewSkill.Base; } if (objNewSkill.Karma > objExistSkill.Karma) { objExistSkill.Karma = objNewSkill.Karma; } objExistSkill.Specializations.MergeInto(objNewSkill.Specializations, (x, y) => x.Free == y.Free ? string.Compare(x.DisplayName(GlobalOptions.Language), y.DisplayName(GlobalOptions.Language), StringComparison.Ordinal) : (x.Free ? 1 : -1)); }); if (blnDoAddToDictionary) { _dicSkills.Add(strName, objSkill); } } // TODO: Skill groups don't refresh their CanIncrease property correctly when the last of their skills is being added, as the total basse rating will be zero. Call this here to force a refresh. foreach (SkillGroup g in SkillGroups) { g.OnPropertyChanged(nameof(SkillGroup.SkillList)); } Timekeeper.Finish("load_char_skills_normal"); Timekeeper.Start("load_char_skills_kno"); using (XmlNodeList xmlSkillsList = xmlSkillNode.SelectNodes("knoskills/skill")) if (xmlSkillsList != null) { foreach (XmlNode xmlNode in xmlSkillsList) { if (Skill.Load(_objCharacter, xmlNode) is KnowledgeSkill objSkill) { KnowledgeSkills.Add(objSkill); } } } Timekeeper.Finish("load_char_skills_kno"); Timekeeper.Start("load_char_knowsoft_buffer"); // Knowsoft Buffer. using (XmlNodeList xmlSkillsList = xmlSkillNode.SelectNodes("skilljackknowledgeskills/skill")) if (xmlSkillsList != null) { foreach (XmlNode xmlNode in xmlSkillsList) { string strName = string.Empty; if (xmlNode.TryGetStringFieldQuickly("name", ref strName)) { KnowsoftSkills.Add(new KnowledgeSkill(_objCharacter, strName)); } } } Timekeeper.Finish("load_char_knowsoft_buffer"); } else { List <Skill> lstTempSkillList = new List <Skill>(); using (XmlNodeList xmlSkillsList = xmlSkillNode.SelectNodes("skills/skill")) if (xmlSkillsList != null) { foreach (XmlNode xmlNode in xmlSkillsList) { Skill objSkill = Skill.LegacyLoad(_objCharacter, xmlNode); if (objSkill != null) { lstTempSkillList.Add(objSkill); } } } if (lstTempSkillList.Count > 0) { List <Skill> lstUnsortedSkills = new List <Skill>(); //Variable/Anon method as to not clutter anywhere else. Not sure if clever or stupid bool OldSkillFilter(Skill skill) { if (skill.Rating > 0) { return(true); } if (skill.SkillCategory == "Resonance Active" && !_objCharacter.RESEnabled) { return(false); } //This could be more fine grained, but frankly i don't care if (skill.SkillCategory == "Magical Active" && !_objCharacter.MAGEnabled) { return(false); } return(true); } foreach (Skill objSkill in lstTempSkillList) { if (objSkill is KnowledgeSkill objKnoSkill) { KnowledgeSkills.Add(objKnoSkill); } else if (OldSkillFilter(objSkill)) { lstUnsortedSkills.Add(objSkill); } } lstUnsortedSkills.Sort(CompareSkills); foreach (Skill objSkill in lstUnsortedSkills) { _lstSkills.Add(objSkill); _dicSkills.Add(objSkill.IsExoticSkill ? objSkill.Name + " (" + objSkill.DisplaySpecializationMethod(GlobalOptions.DefaultLanguage) + ')' : objSkill.Name, objSkill); } UpdateUndoList(xmlSkillNode); } } //This might give subtle bugs in the future, //but right now it needs to be run once when upgrading or it might crash. //As some didn't they crashed on loading skills. //After this have run, it won't (for the crash i'm aware) //TODO: Move it to the other side of the if someday? if (!_objCharacter.Created) { // zero out any skillgroups whose skills did not make the final cut foreach (SkillGroup objSkillGroup in SkillGroups) { if (!objSkillGroup.SkillList.Any(x => SkillsDictionary.ContainsKey(x.Name))) { objSkillGroup.Base = 0; objSkillGroup.Karma = 0; } } } //Workaround for probably breaking compability between earlier beta builds if (xmlSkillNode["skillptsmax"] == null) { xmlSkillNode = xmlSkillNode.OwnerDocument?["character"]; } int intTmp = 0; if (xmlSkillNode.TryGetInt32FieldQuickly("skillptsmax", ref intTmp)) { SkillPointsMaximum = intTmp; } if (xmlSkillNode.TryGetInt32FieldQuickly("skillgrpsmax", ref intTmp)) { SkillGroupPointsMaximum = intTmp; } Timekeeper.Finish("load_char_skills"); }