From 566deba507d6f8dec10bf45d8a87d4e71df2885f Mon Sep 17 00:00:00 2001 From: Chomp Date: Sat, 18 Jan 2025 11:49:21 +0000 Subject: [PATCH] Various code linting changes --- Core/Callbacks/ItemEventCallbacks.cs | 10 +-- Core/Controllers/CustomizationController.cs | 5 +- Core/Controllers/DialogueController.cs | 7 +- Core/Controllers/HideoutController.cs | 1 + Core/Controllers/LauncherController.cs | 14 ++-- Core/Controllers/LocationController.cs | 6 +- Core/Controllers/PresetController.cs | 6 +- Core/Controllers/RepeatableQuestController.cs | 14 ++-- Core/Controllers/TraderController.cs | 41 ++++++------ Core/Generators/BotEquipmentModGenerator.cs | 41 ++++++------ Core/Generators/BotGenerator.cs | 14 ++-- Core/Generators/BotInventoryGenerator.cs | 31 +++++---- Core/Generators/BotLootGenerator.cs | 67 ++++++++++--------- Core/Generators/BotWeaponGenerator.cs | 9 +-- .../RepeatableQuestRewardGenerator.cs | 11 ++- Core/Helpers/ItemHelper.cs | 12 ++-- Core/Helpers/QuestConditionHelper.cs | 10 +-- Core/Helpers/QuestHelper.cs | 61 +++++++++-------- Core/Helpers/QuestRewardHelper.cs | 3 +- Core/Models/Spt/Server/Locations.cs | 8 +-- Core/Services/BotLootCacheService.cs | 29 ++++---- Core/Services/SeasonalEventService.cs | 4 +- server-csharp.sln.DotSettings | 7 +- 23 files changed, 213 insertions(+), 198 deletions(-) diff --git a/Core/Callbacks/ItemEventCallbacks.cs b/Core/Callbacks/ItemEventCallbacks.cs index f150b0c1..eb7dc0c9 100644 --- a/Core/Callbacks/ItemEventCallbacks.cs +++ b/Core/Callbacks/ItemEventCallbacks.cs @@ -59,9 +59,11 @@ public class ItemEventCallbacks public int? GetErrorCode(List warnings) { - if (warnings[0].Code != null) - return int.Parse(warnings[0]?.Code); - - return int.Parse(BackendErrorCodes.UNKNOWN_ERROR.ToString()); + if (warnings[0].Code is null) + { + return int.Parse(BackendErrorCodes.UNKNOWN_ERROR.ToString()); + } + + return int.Parse(warnings[0]?.Code); } } diff --git a/Core/Controllers/CustomizationController.cs b/Core/Controllers/CustomizationController.cs index a217b0cb..5a9804ac 100644 --- a/Core/Controllers/CustomizationController.cs +++ b/Core/Controllers/CustomizationController.cs @@ -333,12 +333,11 @@ public class CustomizationController /// /// Applies a purchased suit to the players doll /// - /// Suit to apply to profile + /// Suit to apply to profile /// Profile to update private void ApplyClothingItemToProfile(CustomizationSetOption customisation, PmcData pmcData) { - var dbSuit = _databaseService.GetCustomization()[customisation?.Id]; - if (dbSuit == null) + if (!_databaseService.GetCustomization().TryGetValue(customisation?.Id, out var dbSuit)) { _logger.Error($"Unable to find suit customisation id: {customisation?.Id}, cannot apply clothing to player profile: {pmcData.Id}"); return; diff --git a/Core/Controllers/DialogueController.cs b/Core/Controllers/DialogueController.cs index cc76107e..be362a3d 100644 --- a/Core/Controllers/DialogueController.cs +++ b/Core/Controllers/DialogueController.cs @@ -167,11 +167,10 @@ public class DialogueController var profile = _saveServer.GetProfile(sessionId); // User to user messages are special in that they need the player to exist in them, add if they don't - if ( - messageType == MessageType.USER_MESSAGE && - !dialog.Users.Any((userDialog) => userDialog.Id == profile.CharacterData.PmcData.SessionId)) + if (messageType == MessageType.USER_MESSAGE && + dialog.Users.All(userDialog => userDialog.Id != profile.CharacterData.PmcData.SessionId)) { - // nullguard + // Nullguard dialog.Users ??= []; dialog.Users.Add( new UserDialogInfo diff --git a/Core/Controllers/HideoutController.cs b/Core/Controllers/HideoutController.cs index 22ccc23d..c81b40cd 100644 --- a/Core/Controllers/HideoutController.cs +++ b/Core/Controllers/HideoutController.cs @@ -184,6 +184,7 @@ public class HideoutController { foreach (var poseKvP in request.Poses) { + // Nullguard pmcData.Hideout.MannequinPoses ??= new Dictionary(); pmcData.Hideout.MannequinPoses[poseKvP.Key] = poseKvP.Value; } diff --git a/Core/Controllers/LauncherController.cs b/Core/Controllers/LauncherController.cs index adbead2b..80e642df 100644 --- a/Core/Controllers/LauncherController.cs +++ b/Core/Controllers/LauncherController.cs @@ -84,7 +84,7 @@ public class LauncherController { var result = new Dictionary(); var dbProfiles = _databaseService.GetProfiles(); - foreach (var templatesProperty in typeof(ProfileTemplates).GetProperties().Where(p => p.CanWrite == true)) + foreach (var templatesProperty in typeof(ProfileTemplates).GetProperties().Where(p => p.CanWrite)) { var propertyValue = templatesProperty.GetValue(dbProfiles); if (propertyValue == null) { @@ -106,10 +106,10 @@ public class LauncherController public string? Login(LoginRequestData info) { - foreach (var sessionID in _saveServer.GetProfiles()) { - var account = _saveServer.GetProfile(sessionID.Key).ProfileInfo; + foreach (var kvp in _saveServer.GetProfiles()) { + var account = _saveServer.GetProfile(kvp.Key).ProfileInfo; if (info.Username == account.Username) { - return sessionID.Key; + return kvp.Key; } } @@ -118,8 +118,8 @@ public class LauncherController public string Register(RegisterData info) { - foreach (var sessionID in _saveServer.GetProfiles()) { - if (info.Username == _saveServer.GetProfile(sessionID.Key).ProfileInfo.Username) { + foreach (var kvp in _saveServer.GetProfiles()) { + if (info.Username == _saveServer.GetProfile(kvp.Key).ProfileInfo.Username) { return ""; } } @@ -131,7 +131,7 @@ public class LauncherController { var profileId = GenerateProfileId(); var scavId = GenerateProfileId(); - var newProfileDetails = new Info(){ + var newProfileDetails = new Info{ ProfileId = profileId, ScavengerId = scavId, Aid = _hashUtil.GenerateAccountId(), diff --git a/Core/Controllers/LocationController.cs b/Core/Controllers/LocationController.cs index 0e0a388a..ab727ca8 100644 --- a/Core/Controllers/LocationController.cs +++ b/Core/Controllers/LocationController.cs @@ -43,12 +43,12 @@ public class LocationController // keyed by _id location property var locationResult = new Dictionary(); - foreach (var location in maps) + foreach (var kvp in maps) { - var mapBase = location.Value?.Base; + var mapBase = kvp.Value?.Base; if (mapBase == null) { - _logger.Debug($"Map: {location} has no base json file, skipping generation"); + _logger.Debug($"Map: {kvp} has no base json file, skipping generation"); continue; } diff --git a/Core/Controllers/PresetController.cs b/Core/Controllers/PresetController.cs index de275015..e02a930b 100644 --- a/Core/Controllers/PresetController.cs +++ b/Core/Controllers/PresetController.cs @@ -32,12 +32,12 @@ public class PresetController { var presets = _databaseService.GetGlobals().ItemPresets; var reverse = new Dictionary>(); - foreach (var (id, preset) in presets) + foreach (var (key, preset) in presets) { - if (id != preset.Id) + if (key != preset.Id) { this._logger.Error( - $"Preset for template tpl: '{preset.Items[0].Template} {preset.Name}' has invalid key: ({id} != {preset.Id}). Skipping" + $"Preset for template tpl: '{preset.Items[0].Template} {preset.Name}' has invalid key: ({key} != {preset.Id}). Skipping" ); continue; diff --git a/Core/Controllers/RepeatableQuestController.cs b/Core/Controllers/RepeatableQuestController.cs index cb599169..695d7e3a 100644 --- a/Core/Controllers/RepeatableQuestController.cs +++ b/Core/Controllers/RepeatableQuestController.cs @@ -304,11 +304,11 @@ public class RepeatableQuestController var locations = GetAllowedLocationsForPmcLevel(repeatableConfig.Locations, pmcLevel.Value); // Populate Exploration and Pickup quest locations - foreach (var location in locations) { - if (location.Key != ELocationName.any) + foreach (var (location, value) in locations) { + if (location != ELocationName.any) { - questPool.Pool.Exploration.Locations[location.Key] = location.Value; - questPool.Pool.Pickup.Locations[location.Key] = location.Value; + questPool.Pool.Exploration.Locations[location] = value; + questPool.Pool.Pickup.Locations[location] = value; } } @@ -374,9 +374,9 @@ public class RepeatableQuestController { var allowedLocation = new Dictionary>(); - foreach (var locationKvP in locations) { + foreach (var (location, value) in locations) { var locationNames = new List(); - foreach (var locationName in locationKvP.Value) { + foreach (var locationName in value) { if (IsPmcLevelAllowedOnLocation(locationName, pmcLevel)) { locationNames.Add(locationName); @@ -385,7 +385,7 @@ public class RepeatableQuestController if (locationNames.Count > 0) { - allowedLocation[locationKvP.Key] = locationNames; + allowedLocation[location] = locationNames; } } diff --git a/Core/Controllers/TraderController.cs b/Core/Controllers/TraderController.cs index dbe964c2..b7d9e43a 100644 --- a/Core/Controllers/TraderController.cs +++ b/Core/Controllers/TraderController.cs @@ -97,9 +97,9 @@ public class TraderController // Adjust price by traderPriceMultipler config property if (_traderConfig.TraderPriceMultipler != 1) { - foreach (var scheme in trader.Value?.Assort?.BarterScheme) + foreach (var kvp in trader.Value?.Assort?.BarterScheme) { - var barterSchemeItem = scheme.Value[0][0]; + var barterSchemeItem = kvp.Value[0][0]; if (barterSchemeItem != null && _paymentHelper.IsMoneyTpl(barterSchemeItem?.Template)) { @@ -130,26 +130,28 @@ public class TraderController /// public bool Update() { - foreach (var trader in _databaseService.GetTables().Traders) + foreach (var (traderId, data) in _databaseService.GetTables().Traders) { - if (trader.Key == "ragfair" || trader.Key == Traders.LIGHTHOUSEKEEPER) - continue; - - if (trader.Key == Traders.FENCE) + switch (traderId) { - if (_fenceService.NeedsPartialRefresh()) - _fenceService.GenerateFenceAssorts(); + case Traders.LIGHTHOUSEKEEPER: + continue; + case Traders.FENCE: + { + if (_fenceService.NeedsPartialRefresh()) + _fenceService.GenerateFenceAssorts(); - continue; + continue; + } } // Trader needs to be refreshed - if (_traderAssortHelper.TraderAssortsHaveExpired(trader.Key)) + if (_traderAssortHelper.TraderAssortsHaveExpired(traderId)) { - _traderAssortHelper.ResetExpiredTrader(trader.Value); + _traderAssortHelper.ResetExpiredTrader(data); // Reset purchase data per trader as they have independent reset times - _traderPurchasePersisterService.ResetTraderPurchasesStoredInProfile(trader.Key); + _traderPurchasePersisterService.ResetTraderPurchasesStoredInProfile(traderId); } } @@ -165,18 +167,15 @@ public class TraderController { var traders = new List(); var pmcData = _profileHelper.GetPmcProfile(sessionId); - foreach (var trader in _databaseService.GetTables().Traders) + foreach (var (traderId, data) in _databaseService.GetTables().Traders) { - if (trader.Value.Base.Id == "ragfair") - continue; - - traders.Add(_traderHelper.GetTrader(trader.Key, sessionId)); + traders.Add(_traderHelper.GetTrader(traderId, sessionId)); if (pmcData?.Info != null) - _traderHelper.LevelUp(trader.Key, pmcData); + _traderHelper.LevelUp(traderId, pmcData); } - traders.Sort((a, b) => SortByTraderId(a, b)); + traders.Sort(SortByTraderId); return traders; } @@ -188,7 +187,7 @@ public class TraderController /// 1,-1 or 0 private int SortByTraderId(TraderBase traderA, TraderBase traderB) { - return string.Compare(traderA.Id, traderB.Id); + return string.CompareOrdinal(traderA.Id, traderB.Id); } /// diff --git a/Core/Generators/BotEquipmentModGenerator.cs b/Core/Generators/BotEquipmentModGenerator.cs index 14af5f39..6aae1bbc 100644 --- a/Core/Generators/BotEquipmentModGenerator.cs +++ b/Core/Generators/BotEquipmentModGenerator.cs @@ -101,16 +101,14 @@ public class BotEquipmentModGenerator var forceSpawn = shouldForceSpawn; // Get mod pool for the desired item - var compatibleModsPool = settings.ModPool[parentTemplate.Id]; - if (compatibleModsPool is null) + if (!settings.ModPool.TryGetValue(parentTemplate.Id, out var compatibleModsPool)) { _logger.Warning($"bot: {settings.BotData.Role} lacks a mod slot pool for item: {parentTemplate.Id} {parentTemplate.Name}"); } // Iterate over mod pool and choose mods to add to item - foreach (var modSlotKvP in compatibleModsPool) + foreach (var (modSlotName, modPool) in compatibleModsPool) { - var modSlotName = modSlotKvP.Key; // Get the templates slot object from db var itemSlotTemplate = GetModItemSlotFromDb(modSlotName, parentTemplate); if (itemSlotTemplate is null) @@ -138,7 +136,7 @@ public class BotEquipmentModGenerator settings.BotEquipmentConfig ); - // Rolled to skip mod and it shouldnt be force-spawned + // Rolled to skip mod and it shouldn't be force-spawned if (modSpawnResult == ModSpawn.SKIP && !forceSpawn) { continue; @@ -151,7 +149,7 @@ public class BotEquipmentModGenerator } // Get pool of items we can add for this slot - var modPoolToChooseFrom = modSlotKvP.Value; + var modPoolToChooseFrom = modPool; // Filter the pool of items in blacklist var filteredModPool = FilterModsByBlacklist(modPoolToChooseFrom, specificBlacklist, modSlotName); @@ -173,18 +171,17 @@ public class BotEquipmentModGenerator compatibleModsPool[modSlotName], parentTemplate ); - if (plateSlotFilteringOutcome.Result is Result.UNKNOWN_FAILURE or Result.NO_DEFAULT_FILTER) + switch (plateSlotFilteringOutcome.Result) { - _logger.Debug($"Plate slot: {modSlotName} selection for armor: {parentTemplate.Id} failed: {plateSlotFilteringOutcome.Result}, skipping"); + case Result.UNKNOWN_FAILURE or Result.NO_DEFAULT_FILTER: + _logger.Debug($"Plate slot: {modSlotName} selection for armor: {parentTemplate.Id} failed: {plateSlotFilteringOutcome.Result}, skipping"); - continue; - } - - if (plateSlotFilteringOutcome.Result == Result.LACKS_PLATE_WEIGHTS) - { - _logger.Warning( - $"Plate slot: {modSlotName} lacks weights for armor: {parentTemplate.Id}, unable to adjust plate choice, using existing data" - ); + continue; + case Result.LACKS_PLATE_WEIGHTS: + _logger.Warning( + $"Plate slot: {modSlotName} lacks weights for armor: {parentTemplate.Id}, unable to adjust plate choice, using existing data" + ); + break; } // Replace mod pool with pool of chosen plate items @@ -1145,12 +1142,12 @@ public List GenerateModsForWeapon(string sessionId, GenerateWeaponRequest _logger.Debug($"{request.BotData.Role} No default: {request.ModSlot} mod found for: {weaponTemplate.Name}, using existing pool"); } - // Couldnt find default in globals, use existing mod pool data + // Couldn't find default in globals, use existing mod pool data return request.ItemModPool[request.ModSlot]; } // Only filter mods down to single default item if it already exists in existing itemModPool, OR the default item has no children - // Filtering mod pool to item that wasnt already there can have problems; + // Filtering mod pool to item that wasn't already there can have problems; // You'd have a mod being picked without any sub-mods in its chain, possibly resulting in missing required mods not being added // Mod is in existing mod pool if (request.ItemModPool[request.ModSlot].Contains(matchingModFromPreset.Template)) @@ -1162,11 +1159,11 @@ public List GenerateModsForWeapon(string sessionId, GenerateWeaponRequest // Get an array of items that are allowed in slot from parent item // Check the filter of the slot to ensure a chosen mod fits var parentSlotCompatibleItems = request.ParentTemplate.Properties.Slots?.FirstOrDefault( - (slot) => slot.Name.ToLower() == request.ModSlot.ToLower() + (slot) => string.Equals(slot.Name.ToLower(), request.ModSlot.ToLower(), StringComparison.Ordinal) ) ?.Props.Filters[0].Filter; - // Mod isnt in existing pool, only add if it has no children and exists inside parent filter + // Mod isn't in existing pool, only add if it has no children and exists inside parent filter if ( parentSlotCompatibleItems?.Contains(matchingModFromPreset.Template) ?? false && @@ -1208,10 +1205,10 @@ public List GenerateModsForWeapon(string sessionId, GenerateWeaponRequest return request.ItemModPool[request.ModSlot]; } - public Item GetMatchingModFromPreset(ModToSpawnRequest request, TemplateItem weaponTemplate) + public Item? GetMatchingModFromPreset(ModToSpawnRequest request, TemplateItem weaponTemplate) { var matchingPreset = GetMatchingPreset(weaponTemplate, request.ParentTemplate.Id); - return matchingPreset?.Items.FirstOrDefault((item) => item?.SlotId?.ToLower() == request.ModSlot.ToLower()); + return matchingPreset?.Items?.FirstOrDefault((item) => item?.SlotId?.ToLower() == request.ModSlot.ToLower()); } /// diff --git a/Core/Generators/BotGenerator.cs b/Core/Generators/BotGenerator.cs index a4462785..a615a44f 100644 --- a/Core/Generators/BotGenerator.cs +++ b/Core/Generators/BotGenerator.cs @@ -416,11 +416,11 @@ public class BotGenerator return; } - foreach (var equipmentKvP in blacklist.Gear) + foreach (var (equipmentSlot, blacklistedTpls) in blacklist.Gear) { - var equipmentDict = botJsonTemplate.BotInventory.Equipment[equipmentKvP.Key]; + var equipmentDict = botJsonTemplate.BotInventory.Equipment[equipmentSlot]; - foreach (var blacklistedTpl in equipmentKvP.Value) + foreach (var blacklistedTpl in blacklistedTpls) { // Set weighting to 0, will never be picked equipmentDict[blacklistedTpl] = 0; @@ -452,7 +452,7 @@ public class BotGenerator // Remove blacklisted loot from loot containers foreach (var lootContainerKey in lootContainersToFilter) { - var prop = props.FirstOrDefault(x => x.Name.ToLower() == lootContainerKey.ToLower()); + var prop = props.FirstOrDefault(x => string.Equals(x.Name, lootContainerKey, StringComparison.CurrentCultureIgnoreCase)); var propValue = (Dictionary)prop.GetValue(botInventory.Items); // No container, skip @@ -462,11 +462,11 @@ public class BotGenerator } List tplsToRemove = []; - foreach (var item in propValue) + foreach (var (key, _) in propValue) { - if (_itemFilterService.IsLootableItemBlacklisted(item.Key)) + if (_itemFilterService.IsLootableItemBlacklisted(key)) { - tplsToRemove.Add(item.Key); + tplsToRemove.Add(key); } } diff --git a/Core/Generators/BotInventoryGenerator.cs b/Core/Generators/BotInventoryGenerator.cs index 059ac12d..460b2eab 100644 --- a/Core/Generators/BotInventoryGenerator.cs +++ b/Core/Generators/BotInventoryGenerator.cs @@ -221,19 +221,19 @@ public class BotInventoryGenerator // Iterate over all equipment slots of bot, do it in specifc order to reduce conflicts // e.g. ArmorVest should be generated after TactivalVest // or FACE_COVER before HEADWEAR - foreach (var equipmentSlotKvP in templateInventory.Equipment) + foreach (var (equipmentSlot, value) in templateInventory.Equipment) { // Skip some slots as they need to be done in a specific order + with specific parameter values // e.g. Weapons - if (excludedSlots.Contains(equipmentSlotKvP.Key)) + if (excludedSlots.Contains(equipmentSlot)) { continue; } GenerateEquipment(new GenerateEquipmentProperties { - RootEquipmentSlot = equipmentSlotKvP.Key, - RootEquipmentPool = equipmentSlotKvP.Value, + RootEquipmentSlot = equipmentSlot, + RootEquipmentPool = value, ModPool = templateInventory.Mods, SpawnChances = wornItemChances, BotData = new BotData { Role = botRole, Level = botLevel, EquipmentRole = botEquipmentRole }, @@ -372,11 +372,10 @@ public class BotInventoryGenerator /// /// Remove armored rigs from parameter data /// - /// Equpiment to filter TacticalVest of + /// Equipment to filter TacticalVest by /// Role of bot vests are being filtered for - /// Should the function return all rigs when 0 unarmored are found - public void FilterRigsToThoseWithoutProtection(Dictionary> templateEquipment, string botRole, - bool allowEmptyResult = true) + /// Should the function return all rigs when 0 unarmored are found + public void FilterRigsToThoseWithoutProtection(Dictionary> templateEquipment, string botRole, bool allowEmptyResult = true) { var tacVestsWithoutArmor = templateEquipment[EquipmentSlots.TacticalVest].Where(kvp => !_itemHelper.ItemHasSlots(kvp.Key)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); @@ -537,7 +536,7 @@ public class BotInventoryGenerator var blacklistedMods = equipmentBlacklist[modSlot] ?? []; var filteredMods = modPool[modSlot].Where((slotName) => !blacklistedMods.Contains(slotName)); - if (filteredMods.Count() > 0) + if (filteredMods.Any()) { modPool[modSlot] = filteredMods.ToList(); } @@ -561,14 +560,14 @@ public class BotInventoryGenerator string botRole, bool isPmc, Generation itemGenerationLimitsMinMax, int botLevel) { var weaponSlotsToFill = GetDesiredWeaponsForBot(equipmentChances); - foreach (var weaponSlot in weaponSlotsToFill) + foreach (var desiredWeapons in weaponSlotsToFill) { // Add weapon to bot if true and bot json has something to put into the slot - if (weaponSlot.ShouldSpawn && templateInventory.Equipment[weaponSlot.Slot].Any()) + if (desiredWeapons.ShouldSpawn && templateInventory.Equipment[desiredWeapons.Slot].Any()) { AddWeaponAndMagazinesToInventory( sessionId, - weaponSlot, + desiredWeapons, templateInventory, botInventory, equipmentChances, @@ -586,7 +585,7 @@ public class BotInventoryGenerator /// /// Chances bot has certain equipment /// What slots bot should have weapons generated for - public List GetDesiredWeaponsForBot(Chances equipmentChances) // TODO: Type fuckery { slot: EquipmentSlots; shouldSpawn: boolean }[] + public List GetDesiredWeaponsForBot(Chances equipmentChances) { var shouldSpawnPrimary = _randomUtil.GetChance100(equipmentChances.EquipmentChances["FirstPrimaryWeapon"]); return @@ -628,7 +627,7 @@ public class BotInventoryGenerator Chances equipmentChances, string botRole, bool isPmc, Generation itemGenerationWeights, int botLevel) { - var generatedweapon = _botWeaponGenerator.GenerateRandomWeapon( + var generatedWeapon = _botWeaponGenerator.GenerateRandomWeapon( sessionId, weaponSlot.Slot.ToString(), templateInventory, @@ -639,10 +638,10 @@ public class BotInventoryGenerator botLevel ); - botInventory.Items.AddRange(generatedweapon.Weapon); + botInventory.Items.AddRange(generatedWeapon.Weapon); _botWeaponGenerator.AddExtraMagazinesToInventory( - generatedweapon, + generatedWeapon, itemGenerationWeights.Items.Magazines, botInventory, botRole); diff --git a/Core/Generators/BotLootGenerator.cs b/Core/Generators/BotLootGenerator.cs index 7ff69f5a..a0e0504e 100644 --- a/Core/Generators/BotLootGenerator.cs +++ b/Core/Generators/BotLootGenerator.cs @@ -684,10 +684,10 @@ public class BotLootGenerator /// Add generated weapons to inventory as loot /// /// - /// inventory to add preset to - /// slot to place the preset in (backpack) - /// bots template, assault.json - /// chances for mods to spawn on weapon + /// Inventory to add preset to + /// Slot to place the preset in (backpack) + /// Bots template, assault.json + /// Chances for mods to spawn on weapon /// bots role .e.g. pmcBot /// are we generating for a pmc /// @@ -714,33 +714,36 @@ public class BotLootGenerator (int)_pmcConfig.LooseWeaponInBackpackLootMinMax.Min, (int)_pmcConfig.LooseWeaponInBackpackLootMinMax.Max ); - if (randomisedWeaponCount > 0) - { - for (var i = 0; i < randomisedWeaponCount; i++) - { - var generatedWeapon = _botWeaponGenerator.GenerateRandomWeapon( - sessionId, - chosenWeaponType, - templateInventory, - botInventory.Equipment, - modChances, - botRole, - isPmc, - botLevel - ); - var result = _botGeneratorHelper.AddItemWithChildrenToEquipmentSlot( - [equipmentSlot], - generatedWeapon.Weapon[0].Id, - generatedWeapon.Weapon[0].Template, - generatedWeapon.Weapon, - botInventory, - containersIdFull - ); - if (result != ItemAddedResult.SUCCESS) - { - _logger.Debug($"Failed to add additional weapon {generatedWeapon.Weapon[0].Id} to bot backpack, reason: {result.ToString()}"); - } + if (randomisedWeaponCount <= 0) + { + return; + } + + for (var i = 0; i < randomisedWeaponCount; i++) + { + var generatedWeapon = _botWeaponGenerator.GenerateRandomWeapon( + sessionId, + chosenWeaponType, + templateInventory, + botInventory.Equipment, + modChances, + botRole, + isPmc, + botLevel + ); + var result = _botGeneratorHelper.AddItemWithChildrenToEquipmentSlot( + [equipmentSlot], + generatedWeapon.Weapon[0].Id, + generatedWeapon.Weapon[0].Template, + generatedWeapon.Weapon, + botInventory, + containersIdFull + ); + + if (result != ItemAddedResult.SUCCESS) + { + _logger.Debug($"Failed to add additional weapon {generatedWeapon.Weapon[0].Id} to bot backpack, reason: {result.ToString()}"); } } } @@ -768,7 +771,7 @@ public class BotLootGenerator /// Bot type /// /// true if item has reached spawn limit - public bool ItemHasReachedSpawnLimit(TemplateItem itemTemplate, string botRole, ItemSpawnLimitSettings itemSpawnLimits) + public bool ItemHasReachedSpawnLimit(TemplateItem itemTemplate, string botRole, ItemSpawnLimitSettings? itemSpawnLimits) { // PMCs and scavs have different sections of bot config for spawn limits if (itemSpawnLimits is not null && itemSpawnLimits.GlobalLimits?.Count == 0) { @@ -884,7 +887,7 @@ public class BotLootGenerator return itemTemplate.Parent; } - // parentId and tplid not found + // parentId and tplId not found return null; } } diff --git a/Core/Generators/BotWeaponGenerator.cs b/Core/Generators/BotWeaponGenerator.cs index d88dec88..cd7bde51 100644 --- a/Core/Generators/BotWeaponGenerator.cs +++ b/Core/Generators/BotWeaponGenerator.cs @@ -339,13 +339,14 @@ public class BotWeaponGenerator ); List weaponMods = []; - // TODO: Right now, preset weapons trigger a lot of warnings regarding missing ammo in magazines & such + // TODO: Preset weapons trigger a lot of warnings regarding missing ammo in magazines & such Preset preset = null; - foreach (var presetObj in _databaseService.GetGlobals().ItemPresets) + foreach (var (_, itemPreset) in _databaseService.GetGlobals().ItemPresets) { - if (presetObj.Value.Items[0].Template == weaponTemplate) + if (itemPreset.Items[0].Template == weaponTemplate) { - preset = _cloner.Clone(presetObj.Value); + preset = _cloner.Clone(itemPreset); + break; } } diff --git a/Core/Generators/RepeatableQuestRewardGenerator.cs b/Core/Generators/RepeatableQuestRewardGenerator.cs index 1f951742..d741e0c5 100644 --- a/Core/Generators/RepeatableQuestRewardGenerator.cs +++ b/Core/Generators/RepeatableQuestRewardGenerator.cs @@ -92,8 +92,13 @@ namespace Core.Generators * @param rewardTplBlacklist OPTIONAL: list of tpls to NOT use when picking a reward * @returns IQuestRewards */ - public QuestRewards GenerateReward(int pmcLevel, double difficulty, string traderId, RepeatableQuestConfig repeatableConfig, - EliminationConfig eliminationConfig, BaseQuestConfig baseQuestConfig, List? rewardTplBlacklist = null) + public QuestRewards GenerateReward( + int pmcLevel, + double difficulty, + string traderId, + RepeatableQuestConfig repeatableConfig, + EliminationConfig eliminationConfig, + List? rewardTplBlacklist = null) { // Get vars to configure rewards with var rewardParams = GetQuestRewardValues(repeatableConfig.RewardScaling, difficulty, pmcLevel); @@ -208,7 +213,7 @@ namespace Core.Generators // Chance of adding skill reward if (_randomUtil.GetChance100((double)rewardParams.SkillRewardChance * 100)) { - var targetSkill = _randomUtil.GetArrayValue(baseQuestConfig.PossibleSkillRewards); + var targetSkill = _randomUtil.GetArrayValue(eliminationConfig.PossibleSkillRewards); Reward reward = new() { Id = _hashUtil.Generate(), diff --git a/Core/Helpers/ItemHelper.cs b/Core/Helpers/ItemHelper.cs index 0864a22d..ec089eaa 100644 --- a/Core/Helpers/ItemHelper.cs +++ b/Core/Helpers/ItemHelper.cs @@ -1434,10 +1434,10 @@ public class ItemHelper List magazine, TemplateItem magTemplate, Dictionary> staticAmmoDist, - string caliber = null, + string? caliber = null, double minSizePercent = 0.25, - string defaultCartridgeTpl = null, - TemplateItem weapon = null) + string? defaultCartridgeTpl = null, + TemplateItem? weapon = null) { var chosenCaliber = caliber ?? GetRandomValidCaliber(magTemplate); @@ -1456,7 +1456,7 @@ public class ItemHelper ); if (cartridgeTpl is null) { - _logger.Debug($"Unable to fill item: {magazine[0].Id} {magTemplate.Name} with cartrides as none were found."); + _logger.Debug($"Unable to fill item: {magazine[0].Id} {magTemplate.Name} with cartridges, none found."); return; } @@ -1523,7 +1523,7 @@ public class ItemHelper var cartridgeCountToAdd = desiredStackCount <= cartridgeMaxStackSize ? desiredStackCount : cartridgeMaxStackSize; - // Ensure we don't go over the max stackcount size + // Ensure we don't go over the max stackCount size var remainingSpace = desiredStackCount - currentStoredCartridgeCount; if (cartridgeCountToAdd > remainingSpace) { @@ -1545,7 +1545,7 @@ public class ItemHelper location++; } - // Only one cartridge stack added, remove location property as its only used for 2 or more stacks + // Only one cartridge stack added, remove location property as it's only used for 2 or more stacks if (location == 1) { magazineWithChildCartridges[1].Location = null; diff --git a/Core/Helpers/QuestConditionHelper.cs b/Core/Helpers/QuestConditionHelper.cs index 6a4f43cb..ef41ce38 100644 --- a/Core/Helpers/QuestConditionHelper.cs +++ b/Core/Helpers/QuestConditionHelper.cs @@ -8,28 +8,28 @@ public class QuestConditionHelper { public List GetQuestConditions( List questConditions, - Func> furtherFilter = null) + Func>? furtherFilter = null) { return FilterConditions(questConditions, "Quest", furtherFilter); } public List GetLevelConditions( List questConditions, - Func> furtherFilter = null) + Func>? furtherFilter = null) { return FilterConditions(questConditions, "Level", furtherFilter); } public List GetLoyaltyConditions( List questConditions, - Func> furtherFilter = null) + Func>? furtherFilter = null) { return FilterConditions(questConditions, "TraderLoyalty", furtherFilter); } public List GetStandingConditions( List questConditions, - Func> furtherFilter = null) + Func>? furtherFilter = null) { return FilterConditions(questConditions, "TraderStanding", furtherFilter); } @@ -37,7 +37,7 @@ public class QuestConditionHelper protected List FilterConditions( List questConditions, string questType, - Func> furtherFilter = null) + Func>? furtherFilter = null) { var filteredQuests = questConditions.Where((c) => { if (c.ConditionType == questType) diff --git a/Core/Helpers/QuestHelper.cs b/Core/Helpers/QuestHelper.cs index 98b58b11..44b2bba4 100644 --- a/Core/Helpers/QuestHelper.cs +++ b/Core/Helpers/QuestHelper.cs @@ -101,31 +101,31 @@ public class QuestHelper /// true if player level is greater than or equal to quest public bool DoesPlayerLevelFulfilCondition(double playerLevel, QuestCondition condition) { - if (condition.ConditionType == "Level") + if (condition.ConditionType != "Level") { - var conditionValue = double.Parse(condition.Value.ToString()); - switch (condition.CompareMethod) - { - case ">=": - return playerLevel >= conditionValue; - case ">": - return playerLevel > conditionValue; - case "<": - return playerLevel < conditionValue; - case "<=": - return playerLevel <= conditionValue; - case "=": - return playerLevel == conditionValue; - default: - _logger.Error( - _localisationService.GetText("quest-unable_to_find_compare_condition", condition.CompareMethod) - ); - - return false; - } + return true; } - return true; + var conditionValue = double.Parse(condition.Value.ToString()); + switch (condition.CompareMethod) + { + case ">=": + return playerLevel >= conditionValue; + case ">": + return playerLevel > conditionValue; + case "<": + return playerLevel < conditionValue; + case "<=": + return playerLevel <= conditionValue; + case "=": + return playerLevel == conditionValue; + default: + _logger.Error( + _localisationService.GetText("quest-unable_to_find_compare_condition", condition.CompareMethod) + ); + + return false; + } } /// @@ -858,8 +858,14 @@ public class QuestHelper */ public List GetClientQuests(string sessionID) { - List questsToShowPlayer = new List(); + List questsToShowPlayer = []; var profile = _profileHelper.GetPmcProfile(sessionID); + if (profile is null) + { + _logger.Error($"Profile {sessionID} not found, unable to return quests"); + + return []; + } var allQuests = GetQuestsFromDb(); foreach (var quest in allQuests) @@ -873,7 +879,7 @@ public class QuestHelper continue; } - // Filter out bear quests for usec and vice versa + // Filter out bear quests for USEC and vice versa if (QuestIsForOtherSide(profile.Info.Side, quest.Id)) { continue; @@ -911,11 +917,12 @@ public class QuestHelper // Check the status of each quest condition, if any are not completed // then this quest should not be visible - bool haveCompletedPreviousQuest = true; + var haveCompletedPreviousQuest = true; foreach (var conditionToFulfil in questRequirements) { // If the previous quest isn't in the user profile, it hasn't been completed or started - var prerequisiteQuest = profile.Quests.FirstOrDefault(profileQuest => (conditionToFulfil.Target as string[]).Contains(profileQuest.QId)); + var questIdsToFulfil = conditionToFulfil.Target as string[] ?? []; + var prerequisiteQuest = profile.Quests.FirstOrDefault(profileQuest => questIdsToFulfil.Contains(profileQuest.QId)); if (prerequisiteQuest is null) { @@ -1068,7 +1075,7 @@ public class QuestHelper * @returns QuestStatusChange array */ protected List GetQuestsWithDifferentStatuses( - List preQuestStatusus, + List preQuestStatuses, List postQuestStatuses ) { diff --git a/Core/Helpers/QuestRewardHelper.cs b/Core/Helpers/QuestRewardHelper.cs index a63e2777..f14f6fe4 100644 --- a/Core/Helpers/QuestRewardHelper.cs +++ b/Core/Helpers/QuestRewardHelper.cs @@ -408,8 +408,7 @@ public class QuestRewardHelper foreach (var target in targets) { // This has all the original id relations since we reset the id to the original after the splitStack - var itemsClone = new List(); - itemsClone.Add(_cloner.Clone(target)); + var itemsClone = new List { _cloner.Clone(target) }; // Here we generate a new id for the root item target.Id = _hashUtil.Generate(); diff --git a/Core/Models/Spt/Server/Locations.cs b/Core/Models/Spt/Server/Locations.cs index 04e9f72b..63f2696e 100644 --- a/Core/Models/Spt/Server/Locations.cs +++ b/Core/Models/Spt/Server/Locations.cs @@ -1,7 +1,5 @@ -using System.Reflection; -using System.Text.Json.Serialization; using Core.Models.Eft.Common.Tables; -using Core.Models.Eft.Common; +using System.Text.Json.Serialization; namespace Core.Models.Spt.Server; @@ -71,7 +69,7 @@ public record Locations { return (Eft.Common.Location?)GetType() .GetProperties() - .First(p => p.Name.ToLower() == _locationMappings[key].ToLower()) + .First(p => string.Equals(p.Name, _locationMappings[key], StringComparison.CurrentCultureIgnoreCase)) .GetGetMethod()? .Invoke(this, null) ?? null; } @@ -79,7 +77,7 @@ public record Locations { GetType() .GetProperties() - .First(p => p.Name.ToLower() == key.ToLower()) + .First(p => string.Equals(p.Name, key, StringComparison.CurrentCultureIgnoreCase)) .GetSetMethod() ? .Invoke(this, [value]); diff --git a/Core/Services/BotLootCacheService.cs b/Core/Services/BotLootCacheService.cs index e88fe152..f1cf318c 100644 --- a/Core/Services/BotLootCacheService.cs +++ b/Core/Services/BotLootCacheService.cs @@ -70,46 +70,47 @@ public class BotLootCacheService } Dictionary result = null; + var botRoleCache = _lootCache[botRole]; switch (lootType) { case LootCacheType.Special: - result = _lootCache[botRole].SpecialItems; + result = botRoleCache.SpecialItems; break; case LootCacheType.Backpack: - result = _lootCache[botRole].BackpackLoot; + result = botRoleCache.BackpackLoot; break; case LootCacheType.Pocket: - result = _lootCache[botRole].PocketLoot; + result = botRoleCache.PocketLoot; break; case LootCacheType.Vest: - result = _lootCache[botRole].VestLoot; + result = botRoleCache.VestLoot; break; case LootCacheType.Secure: - result = _lootCache[botRole].SecureLoot; + result = botRoleCache.SecureLoot; break; case LootCacheType.Combined: - result = _lootCache[botRole].CombinedPoolLoot; + result = botRoleCache.CombinedPoolLoot; break; case LootCacheType.HealingItems: - result = _lootCache[botRole].HealingItems; + result = botRoleCache.HealingItems; break; case LootCacheType.GrenadeItems: - result = _lootCache[botRole].GrenadeItems; + result = botRoleCache.GrenadeItems; break; case LootCacheType.DrugItems: - result = _lootCache[botRole].DrugItems; + result = botRoleCache.DrugItems; break; case LootCacheType.FoodItems: - result = _lootCache[botRole].FoodItems; + result = botRoleCache.FoodItems; break; case LootCacheType.DrinkItems: - result = _lootCache[botRole].DrinkItems; + result = botRoleCache.DrinkItems; break; case LootCacheType.CurrencyItems: - result = _lootCache[botRole].CurrencyItems; + result = botRoleCache.CurrencyItems; break; case LootCacheType.StimItems: - result = _lootCache[botRole].StimItems; + result = botRoleCache.StimItems; break; default: _logger.Error( @@ -161,7 +162,7 @@ public class BotLootCacheService /// Generate loot for a bot and store inside a private class property /// /// bots role (assault / pmcBot etc) - /// Is the bot a PMC (alteres what loot is cached) + /// Is the bot a PMC (alters what loot is cached) /// db template for bot having its loot generated protected void AddLootToCache(string botRole, bool isPmc, BotType botJsonTemplate) { diff --git a/Core/Services/SeasonalEventService.cs b/Core/Services/SeasonalEventService.cs index 485eecc7..69ad647b 100644 --- a/Core/Services/SeasonalEventService.cs +++ b/Core/Services/SeasonalEventService.cs @@ -819,8 +819,8 @@ public class SeasonalEventService /// Key of gift to give protected void GiveGift(string playerId, string giftKey) { - var gitftData = _giftService.GetGiftById(giftKey); - if (!_profileHelper.PlayerHasRecievedMaxNumberOfGift(playerId, giftKey, gitftData.MaxToSendPlayer ?? 5)) + var giftData = _giftService.GetGiftById(giftKey); + if (!_profileHelper.PlayerHasRecievedMaxNumberOfGift(playerId, giftKey, giftData.MaxToSendPlayer ?? 5)) { _giftService.SendGiftToPlayer(playerId, giftKey); } diff --git a/server-csharp.sln.DotSettings b/server-csharp.sln.DotSettings index a385c652..0c0208db 100644 --- a/server-csharp.sln.DotSettings +++ b/server-csharp.sln.DotSettings @@ -15,4 +15,9 @@ True True True - True \ No newline at end of file + True + True + True + True + True + True \ No newline at end of file