static DaggerfallBankPurchasePopUp() { int editorLayer = LayerMask.NameToLayer(goName); if (editorLayer == -1) { DaggerfallUnity.LogMessage("Did not find Layer with name \"BankPurchase\"! Defaulting to Layer 12.", true); } else { layer = editorLayer; } Camera.main.cullingMask = Camera.main.cullingMask & ~((1 << layer)); // don't render this layer with main camera goBankPurchase = GameObject.Find(goName); }
private bool ReadyCheck() { // Do nothing if DaggerfallUnity not ready if (!DaggerfallUnity.Instance.IsReady) { DaggerfallUnity.LogMessage("FPSSpellCasting: DaggerfallUnity component is not ready. Have you set your Arena2 path?"); return(false); } // Must have current spell texture anims if (currentAnims == null || currentAnims.Length == 0) { return(false); } return(true); }
void Start() { dfUnity = DaggerfallUnity.Instance; if (!streamingWorld) { streamingWorld = GameObject.Find("StreamingWorld").GetComponent <StreamingWorld>(); } if (!streamingWorld) { DaggerfallUnity.LogMessage("InjectReflectiveMaterialProperty: Missing StreamingWorld reference.", true); if (Application.isEditor) { Debug.Break(); } else { Application.Quit(); } } if (GameObject.Find("IncreasedTerrainDistanceMod") != null) { if (DaggerfallUnity.Settings.Nystul_IncreasedTerrainDistance) { extraTranslationY = GameObject.Find("IncreasedTerrainDistanceMod").GetComponent <ProjectIncreasedTerrainDistance.IncreasedTerrainDistance>().ExtraTranslationY; } } gameObjectReflectionPlaneGroundLevel = GameObject.Find("ReflectionPlaneBottom"); gameObjectReflectionPlaneSeaLevel = GameObject.Find("ReflectionPlaneSeaLevel"); gameObjectReflectionPlaneLowerLevel = gameObjectReflectionPlaneSeaLevel; // get inactive gameobject StreamingTarget (just GameObject.Find() would fail to find inactive gameobjects) GameObject[] gameObjects = Resources.FindObjectsOfTypeAll <GameObject>(); foreach (GameObject currentGameObject in gameObjects) { string objectPathInHierarchy = GetGameObjectPath(currentGameObject); if (objectPathInHierarchy == "/Exterior/StreamingTarget") { gameObjectStreamingTarget = currentGameObject; } } iniData = getIniParserConfigInjectionTextures(); }
/// <summary> /// Deletes save folder. /// </summary> /// <param name="key">Save key.</param> public void DeleteSaveFolder(int key) { if (!enumeratedSaveFolders.ContainsKey(key)) { return; } // For safety only delete known save files - do not perform a recursive delete // This way we don't blow up folder if user has placed something custom inside string path = GetSaveFolder(key); File.Delete(Path.Combine(path, saveDataFilename)); File.Delete(Path.Combine(path, saveInfoFilename)); File.Delete(Path.Combine(path, screenshotFilename)); File.Delete(Path.Combine(path, containerDataFilename)); File.Delete(Path.Combine(path, automapDataFilename)); File.Delete(Path.Combine(path, conversationDataFilename)); File.Delete(Path.Combine(path, discoveryDataFilename)); File.Delete(Path.Combine(path, factionDataFilename)); File.Delete(Path.Combine(path, questDataFilename)); File.Delete(Path.Combine(path, bioFileName)); File.Delete(Path.Combine(path, notebookDataFilename)); if (ModManager.Instance != null) { foreach (Mod mod in ModManager.Instance.GetAllModsWithSaveData()) { File.Delete(Path.Combine(path, GetModDataFilename(mod))); } } // Attempt to delete path itself // Even if delete fails path should be invalid with save info removed // Folder index will be excluded from enumeration and recycled later try { Directory.Delete(path); } catch (Exception ex) { string message = string.Format("Could not delete save folder '{0}'. Exception message: {1}", path, ex.Message); DaggerfallUnity.LogMessage(message); } // Update saves EnumerateSaves(); }
protected void DaedraSummoningService(int npcFactionId) { if (!GameManager.Instance.PlayerEntity.FactionData.GetFactionData(npcFactionId, out summonerFactionData)) { DaggerfallUnity.LogMessage("Error no faction data for NPC FactionId: " + npcFactionId); return; } // Select appropriate Daedra for summoning attempt. if (summonerFactionData.id == (int)FactionFile.FactionIDs.The_Glenmoril_Witches) { // Always Hircine at Glenmoril witches. daedraToSummon = daedraData[0]; } else if ((FactionFile.FactionTypes)summonerFactionData.type == FactionFile.FactionTypes.WitchesCoven) { // Witches covens summon a random Daedra. daedraToSummon = daedraData[Random.Range(1, daedraData.Length)]; } else { // Is this a summoning day? int dayOfYear = DaggerfallUnity.Instance.WorldTime.DaggerfallDateTime.DayOfYear; foreach (DaedraData dd in daedraData) { if (dd.dayOfYear == dayOfYear) { daedraToSummon = dd; break; } } } DaggerfallMessageBox messageBox = new DaggerfallMessageBox(uiManager, uiManager.TopWindow); if (daedraToSummon.factionId == 0) { // Display not summoning day message. TextFile.Token[] tokens = DaggerfallUnity.Instance.TextProvider.GetRandomTokens(SummonNotToday); messageBox.SetTextTokens(tokens, this); messageBox.ClickAnywhereToClose = true; } else { // Ask player if they really want to risk the summoning. messageBox.SetTextTokens(SummonAreYouSure, this); messageBox.AddButton(DaggerfallMessageBox.MessageBoxButtons.Yes); messageBox.AddButton(DaggerfallMessageBox.MessageBoxButtons.No); messageBox.OnButtonClick += ConfirmSummon_OnButtonClick; } messageBox.Show(); }
public Quest SelectQuest(List <QuestData> pool, int factionId) { Debug.Log("Quest pool has " + pool.Count); // Choose random quest from pool and try to parse it if (pool.Count > 0) { QuestData questData = pool[UnityEngine.Random.Range(0, pool.Count)]; try { return(LoadQuest(questData, factionId)); } catch (Exception ex) { // Log exception DaggerfallUnity.LogMessage("Exception for quest " + questData.name + " during quest compile: " + ex.Message, true); } } return(null); }
/// <summary> /// Retrieve the guild object for the given faction id. /// </summary> public IGuild GetGuild(int factionId) { try { FactionFile.GuildGroups guildGroup = GetGuildGroup(factionId); if (guildGroup == FactionFile.GuildGroups.None) { return(guildNotMember); } else { return(GetGuild(guildGroup, factionId)); } // Catch erroneous faction data entries. (e.g. #91) } catch (ArgumentOutOfRangeException e) { DaggerfallUnity.LogMessage(e.Message, true); return(guildNotMember); } }
private bool SetupSingleton() { if (instance == null) { instance = this; DontDestroyOnLoad(this.gameObject); } else if (instance != this) { if (Application.isPlaying) { DaggerfallUnity.LogMessage("Multiple GameManager instances detected in scene!", true); Destroy(gameObject); } } return(instance == this); }
private bool ReadyCheck() { // Do nothing if DaggerfallUnity not ready if (!dfUnity.IsReady) { DaggerfallUnity.LogMessage("FPSWeapon: DaggerfallUnity component is not ready. Have you set your Arena2 path?"); return(false); } // Ensure cif reader is ready if (cifFile == null) { cifFile = new CifRciFile(); cifFile.Palette.Load(Path.Combine(dfUnity.Arena2Path, cifFile.PaletteName)); } return(true); }
public override IQuestAction CreateNew(string source, Quest parentQuest) { base.CreateNew(source, parentQuest); // Source must match pattern Match match = Test(source); if (!match.Success) { return(null); } // Trim source end or trailing white space will be split to an empty symbol at end of array source = source.TrimEnd(); // Factory new action PickOneOf action = new PickOneOf(parentQuest); try { var splits = source.Split(); if (splits == null || splits.Length < 4) { return(null); } else { action.taskSymbols = new Symbol[splits.Length - 3]; } for (int i = 0; i < action.taskSymbols.Length; i++) { action.taskSymbols[i] = new Symbol(splits[i + 3]); } } catch (System.Exception ex) { DaggerfallUnity.LogMessage("PickOneOf.Create() failed with exception: " + ex.Message, true); action = null; } return(action); }
Dictionary <int, SaveInfo_v1> EnumerateSaveInfo(Dictionary <int, string> saveFolders) { Dictionary <int, SaveInfo_v1> saveInfoDict = new Dictionary <int, SaveInfo_v1>(); foreach (var kvp in saveFolders) { try { SaveInfo_v1 saveInfo = ReadSaveInfo(kvp.Value); saveInfoDict.Add(kvp.Key, saveInfo); } catch (Exception ex) { DaggerfallUnity.LogMessage(string.Format("Failed to read {0} in save folder {1}. Exception.Message={2}", saveInfoFilename, kvp.Value, ex.Message)); } } return(saveInfoDict); }
/// <summary> /// Attempts to get a Daggerfall block from BLOCKS.BSA. /// </summary> /// <param name="name">Name of block.</param> /// <param name="blockOut">DFBlock data out.</param> /// <returns>True if successful.</returns> public bool GetBlock(string name, out DFBlock blockOut) { blockOut = new DFBlock(); if (!isReady) { return(false); } // Get block data blockOut = blockFileReader.GetBlock(name); if (blockOut.Type == DFBlock.BlockTypes.Unknown) { DaggerfallUnity.LogMessage(string.Format("Unknown block '{0}'.", name), true); return(false); } return(true); }
/// <summary> /// Attempts to get a Daggerfall location from MAPS.BSA. /// </summary> /// <param name="regionName">Name of region.</param> /// <param name="locationName">Name of location.</param> /// <param name="locationOut">DFLocation data out.</param> /// <returns>True if successful.</returns> public bool GetLocation(string regionName, string locationName, out DFLocation locationOut) { locationOut = new DFLocation(); if (!isReady) { return(false); } // Get location data locationOut = mapFileReader.GetLocation(regionName, locationName); if (!locationOut.Loaded) { DaggerfallUnity.LogMessage(string.Format("Unknown location RegionName='{0}', LocationName='{1}'.", regionName, locationName), true); return(false); } return(true); }
public void Setup(Mod mod) { this.mod = mod; mod.IsReady = true; var settings = mod.GetSettings(); string keyName = settings.GetValue <string>("General", "Hotkey"); var key = (KeyCode)Enum.Parse(typeof(KeyCode), keyName); if (Enum.IsDefined(typeof(KeyCode), key)) { toggleKey = key; } else { DaggerfallUnity.LogMessage("ToggleMount: Hotkey could not be processed! Falling back to 'G'!", true); } }
public static GameObject CreateDaggerfallDungeonGameObject(DFLocation location, Transform parent) { if (!location.HasDungeon) { string multiName = string.Format("{0}/{1}", location.RegionName, location.Name); DaggerfallUnity.LogMessage(string.Format("Location '{0}' does not contain a dungeon map", multiName), true); return(null); } GameObject go = new GameObject(string.Format("DaggerfallDungeon [Region={0}, Name={1}]", location.RegionName, location.Name)); if (parent) { go.transform.parent = parent; } DaggerfallDungeon c = go.AddComponent <DaggerfallDungeon>(); c.SetDungeon(location); return(go); }
/// <summary> /// Links action chains together. /// </summary> public static void LinkActionNodes(Dictionary <int, ActionLink> actionLinkDict) { // Exit if no actions if (actionLinkDict.Count == 0) { return; } // Iterate through actions foreach (var item in actionLinkDict) { ActionLink link = item.Value; DaggerfallAction dfAction = link.gameObject.GetComponent <DaggerfallAction>(); if (dfAction == null) { continue; } try { // Link to next node if (actionLinkDict.ContainsKey(link.nextKey)) { dfAction.NextObject = actionLinkDict[link.nextKey].gameObject; } // Link to previous node if (actionLinkDict.ContainsKey(link.prevKey)) { dfAction.PreviousObject = actionLinkDict[link.prevKey].gameObject; } } catch (Exception ex) { DaggerfallUnity.LogMessage(ex.Message, true); DaggerfallUnity.LogMessage(string.Format("Error in LinkActionNodes; {0} : {1} : {2} : {3}", link.gameObject.name, link.nextKey, link.prevKey, dfAction), true); } } }
public DistanceMatch[] FindBestMatches(string needle, int ntop) { #if DEBUG_SHOW_EDITDISTANCE_TIMES // Start timing System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); long startTime = stopwatch.ElapsedMilliseconds; #endif string canonized_needle = canonize_string(needle); PriorityQueue <InternalMatchResult> kept = new PriorityQueue <InternalMatchResult>(); float worseKeptDistance = float.PositiveInfinity; foreach (KeyValuePair <String, String> kv in dictionary) { float answer_distance = GetDistance(canonized_needle, kv.Value, worseKeptDistance); if (answer_distance < worseKeptDistance) { kept.Enqueue(new InternalMatchResult(kv.Key, answer_distance, GetRelevance(answer_distance))); // start dropping results? if (kept.Count() > ntop) { kept.Dequeue(); worseKeptDistance = kept.Peek().distance; } } } // Dump the heap in reverse order so highest relevances are at the beginning of results DistanceMatch[] result = new DistanceMatch[kept.Count()]; for (int i = kept.Count(); i-- > 0;) { result[i] = kept.Dequeue().GetMatchResult(); } #if DEBUG_SHOW_EDITDISTANCE_TIMES // Show timer long totalTime = stopwatch.ElapsedMilliseconds - startTime; DaggerfallUnity.LogMessage(string.Format("Time to findBestMatches {0}: {1}ms", needle, totalTime), true); #endif return(result); }
private bool ReadyCheck() { if (!dfUnity) { dfUnity = DaggerfallUnity.Instance; } // Must have a light component if (!myLight) { return(false); } // Do nothing if DaggerfallUnity not ready if (!dfUnity.IsReady) { DaggerfallUnity.LogMessage("SunlightManager: DaggerfallUnity component is not ready. Have you set your Arena2 path?"); return(false); } return(true); }
void Start() { try { // Load a keybind file if possible if (HasKeyBindsSave()) { LoadKeyBinds(); } // Ensure defaults are deployed if missing SetupDefaults(); // Update keybinds save SaveKeyBinds(); } catch (Exception ex) { DaggerfallUnity.LogMessage(string.Format("Could not load keybinds file. The exception was: '{0}'", ex.Message), true); DaggerfallUnity.LogMessage("Setting default key binds after failed load.", true); } }
private void AddRandomRDBEnemy(DFBlock.RdbObject obj) { // Get dungeon type index int index = (int)dungeonType >> 8; if (index < RandomEncounters.EncounterTables.Length) { // Get encounter table RandomEncounterTable table = RandomEncounters.EncounterTables[index]; // Get random monster from table // Normally this would be weighted by player level MobileTypes type = table.Enemies[UnityEngine.Random.Range(0, table.Enemies.Length)]; // Add enemy AddEnemy(obj, type); } else { DaggerfallUnity.LogMessage(string.Format("RDBLayout: Dungeon type {0} is out of range or unknown.", dungeonType), true); } }
private bool ReadyCheck() { // Ensure we have a DaggerfallUnity reference if (dfUnity == null) { dfUnity = DaggerfallUnity.Instance; // Stop component if not necessary if (!dfUnity.Option_AutomateCityLights && !dfUnity.Option_AutomateCityWindows) { Destroy(this); } // Get lights if (toggleLighting == LightingSelection.All) { particles = GetComponentsInChildren <ParticleSystem>(); lights = GetComponentsInChildren <Light>(); } // Get emissive material if (emissionColors != EmissionColors.NoColors) { InitEmissiveMaterial(); } // Force first update to set lastFlag = !dfUnity.WorldTime.Now.IsCityLightsOn; } // Do nothing if DaggerfallUnity not ready if (!dfUnity.IsReady) { DaggerfallUnity.LogMessage("DayNight: DaggerfallUnity component is not ready. Have you set your Arena2 path?"); return(false); } return(true); }
string GetDaggerfallSavePath() { if (!string.IsNullOrEmpty(daggerfallSavePath)) { return(daggerfallSavePath); } string result = string.Empty; // Test result is a valid path result = Path.GetDirectoryName(DaggerfallUnity.Instance.Arena2Path); if (!Directory.Exists(result)) { throw new Exception("Could not locate valid path for Daggerfall save files. Check 'MyDaggerfallPath' in settings.ini points to your Daggerfall folder."); } // Log result and save path DaggerfallUnity.LogMessage(string.Format("Using path '{0}' for Daggerfall save importing.", result), true); daggerfallSavePath = result; return(result); }
private bool ReadyCheck() { // Arena2 path must be set if (string.IsNullOrEmpty(Arena2Path)) { DaggerfallUnity.LogMessage("TextureReader: Arena2Path not set.", true); return(false); } // Ensure texture reader is ready if (textureFile == null) { textureFile = new TextureFile(); if (!textureFile.Palette.Load(Path.Combine(Arena2Path, textureFile.PaletteName))) { DaggerfallUnity.LogMessage("TextureReader: Failed to load palette file, is Arena2Path correct?", true); textureFile = null; return(false); } } return(true); }
/// <summary> /// Checks all of the GameManager's properties at start up. /// </summary> public void GetProperties() { var props = typeof(GameManager).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (PropertyInfo prop in props) { try { prop.GetValue(GameManager.instance, null); //DaggerfallUnity.LogMessage(string.Format("GameManager Startup...property: {0} value: {1}", prop.Name, value), true); } catch (Exception ex) { Debug.Log(string.Format("{0} | GameManager Failed to get value for prop: {1}", ex.Message, prop.Name)); } } if (GameManager.HasInstance) { IsReady = true; DaggerfallUnity.LogMessage("GameManager ready"); } }
void Awake() { if (!componentUpdateReflectionTextures) { componentUpdateReflectionTextures = GameObject.Find("RealtimeReflections").GetComponent <UpdateReflectionTextures>(); } if (!componentUpdateReflectionTextures) { DaggerfallUnity.LogMessage("InjectReflectiveMaterialProperty: Could not locate UpdateReflectionTextures component.", true); if (Application.isEditor) { Debug.Break(); } else { Application.Quit(); } } StreamingWorld.OnInitWorld += InjectMaterialProperties; StreamingWorld.OnTeleportToCoordinates += InjectMaterialProperties; FloatingOrigin.OnPositionUpdate += InjectMaterialProperties; DaggerfallTerrain.OnInstantiateTerrain += InjectMaterialProperties; }
public override IQuestAction CreateNew(string source, Quest parentQuest) { // Source must match pattern Match match = Test(source); if (!match.Success) { return(null); } RemoveLogMessage action = new RemoveLogMessage(parentQuest); try { action.stepID = Parser.ParseInt(match.Groups["step"].Value); } catch (System.Exception ex) { DaggerfallUnity.LogMessage("RemoveLogMessage.Create() failed with exception: " + ex.Message, true); action = null; } return(action); }
private bool ReadyCheck() { if (isReady) { return(true); } if (dfUnity == null) { dfUnity = DaggerfallUnity.Instance; } // Do nothing if DaggerfallUnity not ready if (!dfUnity.IsReady) { DaggerfallUnity.LogMessage("ExtendedTerrainDistance: DaggerfallUnity component is not ready. Have you set your Arena2 path?"); return(false); } // Raise ready flag isReady = true; return(true); }
/// <summary> /// Get a random quest for a guild from appropriate subset. /// </summary> public Quest GetGuildQuest(FactionFile.GuildGroups guildGroup, MembershipStatus status, int factionId, int rep) { #if UNITY_EDITOR // Reload every time when in editor LoadQuestLists(); #endif List <QuestData> guildQuests; if (guilds.TryGetValue(guildGroup, out guildQuests)) { MembershipStatus tplMemb = (guildGroup == FactionFile.GuildGroups.HolyOrder && status != MembershipStatus.Nonmember) ? MembershipStatus.Member : status; List <QuestData> pool = new List <QuestData>(); foreach (QuestData quest in guildQuests) { if ((status == (MembershipStatus)quest.membership || tplMemb == (MembershipStatus)quest.membership) && (rep >= quest.minRep || status == MembershipStatus.Nonmember) && (!quest.unitWildC || rep < quest.minRep + 10)) { pool.Add(quest); } } Debug.Log("Quest pool has " + pool.Count); // Choose random quest from pool and try to parse it if (pool.Count > 0) { QuestData questData = pool[UnityEngine.Random.Range(0, pool.Count)]; try { return(LoadQuest(questData, factionId)); } catch (Exception ex) { // Log exception DaggerfallUnity.LogMessage("Exception during quest compile: " + ex.Message, true); } } } return(null); }
void StartFromClassicSave() { DaggerfallUnity.ResetUID(); QuestMachine.Instance.ClearState(); RaiseOnNewGameEvent(); ResetWeaponManager(); // Save index must be in range if (classicSaveIndex < 0 || classicSaveIndex >= 6) { throw new IndexOutOfRangeException("classicSaveIndex out of range."); } // Open saves in parent path of Arena2 folder string path = SaveLoadManager.Instance.DaggerfallSavePath; SaveGames saveGames = new SaveGames(path); if (!saveGames.IsPathOpen) { throw new Exception(string.Format("Could not open Daggerfall saves path {0}", path)); } // Open save index if (!saveGames.TryOpenSave(classicSaveIndex)) { string error = string.Format("Could not open classic save index {0}.", classicSaveIndex); DaggerfallUI.MessageBox(error); DaggerfallUnity.LogMessage(string.Format(error), true); return; } // Get required save data SaveTree saveTree = saveGames.SaveTree; SaveVars saveVars = saveGames.SaveVars; SaveTreeBaseRecord positionRecord = saveTree.FindRecord(RecordTypes.CharacterPositionRecord); if (NoWorld) { playerEnterExit.DisableAllParents(); } else { // Set player to world position playerEnterExit.EnableExteriorParent(); StreamingWorld streamingWorld = FindStreamingWorld(); int worldX = positionRecord.RecordRoot.Position.WorldX; int worldZ = positionRecord.RecordRoot.Position.WorldZ; streamingWorld.TeleportToWorldCoordinates(worldX, worldZ); streamingWorld.suppressWorld = false; } GameObject cameraObject = GameObject.FindGameObjectWithTag("MainCamera"); PlayerMouseLook mouseLook = cameraObject.GetComponent <PlayerMouseLook>(); if (mouseLook) { // Classic save value ranges from -256 (looking up) to 256 (looking down). // The maximum up and down range of view in classic is similar to 45 degrees up and down in DF Unity. float pitch = positionRecord.RecordRoot.Pitch; if (pitch != 0) { pitch = (pitch * 45 / 256); } mouseLook.Pitch = pitch; float yaw = positionRecord.RecordRoot.Yaw; // In classic saves 2048 units of yaw is 360 degrees. if (yaw != 0) { yaw = (yaw * 360 / 2048); } mouseLook.Yaw = yaw; } // Set whether the player's weapon is drawn WeaponManager weaponManager = GameManager.Instance.WeaponManager; weaponManager.Sheathed = (!saveVars.WeaponDrawn); // Set game time DaggerfallUnity.Instance.WorldTime.Now.FromClassicDaggerfallTime(saveVars.GameTime); // Get character record List <SaveTreeBaseRecord> records = saveTree.FindRecords(RecordTypes.Character); if (records.Count != 1) { throw new Exception("SaveTree CharacterRecord not found."); } // Get prototypical character document data CharacterRecord characterRecord = (CharacterRecord)records[0]; characterDocument = characterRecord.ToCharacterDocument(); // Assign data to player entity PlayerEntity playerEntity = FindPlayerEntity(); playerEntity.AssignCharacter(characterDocument, characterRecord.ParsedData.level, characterRecord.ParsedData.maxHealth, false); // Assign biography modifiers playerEntity.BiographyResistDiseaseMod = saveVars.BiographyResistDiseaseMod; playerEntity.BiographyResistMagicMod = saveVars.BiographyResistMagicMod; playerEntity.BiographyAvoidHitMod = saveVars.BiographyAvoidHitMod; playerEntity.BiographyResistPoisonMod = saveVars.BiographyResistPoisonMod; playerEntity.BiographyFatigueMod = saveVars.BiographyFatigueMod; // Assign faction data playerEntity.FactionData.ImportClassicReputation(saveVars); // Assign global variables playerEntity.GlobalVars.ImportClassicGlobalVars(saveVars); // Set time of last check for raising skills playerEntity.TimeOfLastSkillIncreaseCheck = saveVars.LastSkillCheckTime; // Assign items to player entity playerEntity.AssignItems(saveTree); // Assign guild memberships playerEntity.AssignGuildMemberships(saveTree); // Assign diseases and poisons to player entity playerEntity.AssignDiseasesAndPoisons(saveTree); // Assign gold pieces playerEntity.GoldPieces = (int)characterRecord.ParsedData.physicalGold; // Assign weapon hand being used weaponManager.UsingRightHand = !saveVars.UsingLeftHandWeapon; // GodMode setting playerEntity.GodMode = saveVars.GodMode; // Setup bank accounts var bankRecords = saveTree.FindRecord(RecordTypes.BankAccount); Banking.DaggerfallBankManager.ReadNativeBankData(bankRecords); // Get regional data. playerEntity.RegionData = saveVars.RegionData; // Set time tracked by playerEntity for game minute-based updates playerEntity.LastGameMinutes = saveVars.GameTime; // Get breath remaining if player was submerged (0 if they were not in the water) playerEntity.CurrentBreath = saveVars.BreathRemaining; // TODO: Import classic spellbook playerEntity.DeserializeSpellbook(null); // Get last type of crime committed playerEntity.CrimeCommitted = (PlayerEntity.Crimes)saveVars.CrimeCommitted; // Get weather byte[] climateWeathers = saveVars.ClimateWeathers; // Enums for thunder and snow are reversed in classic and Unity, so they are converted here. for (int i = 0; i < climateWeathers.Length; i++) { // TODO: 0x80 flag can be set for snow or rain, to add fog to these weathers. This isn't in DF Unity yet, so // temporarily removing the flag. climateWeathers[i] &= 0x7f; if (climateWeathers[i] == 5) { climateWeathers[i] = 6; } else if (climateWeathers[i] == 6) { climateWeathers[i] = 5; } } GameManager.Instance.WeatherManager.PlayerWeather.ClimateWeathers = climateWeathers; // Load character biography text playerEntity.BackStory = saveGames.BioFile.Lines; // Validate spellbook item DaggerfallUnity.Instance.ItemHelper.ValidateSpellbookItem(playerEntity); // Start game DaggerfallUI.Instance.PopToHUD(); GameManager.Instance.PauseGame(false); DaggerfallUI.Instance.FadeBehaviour.FadeHUDFromBlack(); DaggerfallUI.PostMessage(PostStartMessage); lastStartMethod = StartMethods.LoadClassicSave; SaveIndex = -1; if (OnStartGame != null) { OnStartGame(this, null); } }
private void UpdateWeapon() { // Do nothing if weapon not ready if (weaponAtlas == null || weaponAnims == null || weaponRects == null || weaponIndices == null) { return; } // Reset state if weapon not visible if (!ShowWeapon || WeaponType == WeaponTypes.None) { weaponState = WeaponStates.Idle; currentFrame = 0; } // Handle bow with no arrows if (!GameManager.Instance.WeaponManager.Sheathed && WeaponType == WeaponTypes.Bow && GameManager.Instance.PlayerEntity.Items.GetItem(Items.ItemGroups.Weapons, (int)Items.Weapons.Arrow) == null) { GameManager.Instance.WeaponManager.SheathWeapons(); DaggerfallUI.SetMidScreenText(UserInterfaceWindows.HardStrings.youHaveNoArrows); } // Store rect and anim int weaponAnimRecordIndex; if (WeaponType == WeaponTypes.Bow) { weaponAnimRecordIndex = 0; // Bow has only 1 animation } else { weaponAnimRecordIndex = (int)weaponState; } try { bool isImported = customTextures.TryGetValue(MaterialReader.MakeTextureKey(0, (byte)weaponState, (byte)currentFrame), out curCustomTexture); if (FlipHorizontal && (weaponState == WeaponStates.Idle || weaponState == WeaponStates.StrikeDown || weaponState == WeaponStates.StrikeUp)) { // Mirror weapon rect if (isImported) { curAnimRect = new Rect(0, 1, -1, 1); } else { Rect rect = weaponRects[weaponIndices[weaponAnimRecordIndex].startIndex + currentFrame]; curAnimRect = new Rect(rect.xMax, rect.yMin, -rect.width, rect.height); } } else { curAnimRect = isImported ? new Rect(0, 0, 1, 1) : weaponRects[weaponIndices[weaponAnimRecordIndex].startIndex + currentFrame]; } WeaponAnimation anim = weaponAnims[(int)weaponState]; // Get weapon dimensions int width = weaponIndices[weaponAnimRecordIndex].width; int height = weaponIndices[weaponAnimRecordIndex].height; // Get weapon scale weaponScaleX = (float)Screen.width / (float)nativeScreenWidth; weaponScaleY = (float)Screen.height / (float)nativeScreenHeight; // Adjust scale to be slightly larger when not using point filtering // This reduces the effect of filter shrink at edge of display if (dfUnity.MaterialReader.MainFilterMode != FilterMode.Point) { weaponScaleX *= 1.01f; weaponScaleY *= 1.01f; } // Source weapon images are designed to overlay a fixed 320x200 display. // Some weapons need to align with both top, bottom, and right of display. // This means they might be a little stretched on widescreen displays. switch (anim.Alignment) { case WeaponAlignment.Left: AlignLeft(anim, width, height); break; case WeaponAlignment.Center: AlignCenter(anim, width, height); break; case WeaponAlignment.Right: AlignRight(anim, width, height); break; } } catch (IndexOutOfRangeException) { DaggerfallUnity.LogMessage("Index out of range exception for weapon animation. Probably due to weapon breaking + being unequipped during animation."); } }