From e5d0af38901b03a118ec56c91dd2e870b983a9d9 Mon Sep 17 00:00:00 2001 From: Chomp Date: Tue, 2 Sep 2025 14:27:10 +0100 Subject: [PATCH] Formatting and naming consistency changes --- .../Callbacks/BtrDeliveryCallbacks.cs | 4 +- .../Callbacks/HideoutCallbacks.cs | 4 +- .../Callbacks/InsuranceCallbacks.cs | 4 +- .../Callbacks/RagfairCallbacks.cs | 4 +- .../Callbacks/SaveCallbacks.cs | 4 +- .../Callbacks/TraderCallbacks.cs | 4 +- .../Controllers/AchievementController.cs | 4 +- .../Controllers/DialogueController.cs | 16 ++-- .../Controllers/GameController.cs | 26 +++--- .../Controllers/HideoutController.cs | 16 ++-- .../Controllers/InRaidController.cs | 16 ++-- .../Controllers/InsuranceController.cs | 10 +-- .../Controllers/LauncherController.cs | 11 ++- .../Controllers/LauncherV2Controller.cs | 4 +- .../Controllers/MatchController.cs | 10 +-- .../Controllers/RagfairController.cs | 20 ++--- .../Controllers/TradeController.cs | 10 +-- .../Controllers/WeatherController.cs | 7 +- .../Generators/BotEquipmentModGenerator.cs | 8 +- .../Generators/BotGenerator.cs | 16 ++-- .../Generators/BotInventoryGenerator.cs | 12 +-- .../Generators/BotLevelGenerator.cs | 8 ++ .../Generators/BotLootGenerator.cs | 44 ++++----- .../Generators/BotWeaponGenerator.cs | 30 +++---- .../Generators/FenceBaseAssortGenerator.cs | 14 +-- .../Generators/LocationLootGenerator.cs | 48 +++++----- .../Generators/PMCLootGenerator.cs | 16 ++-- .../Generators/PlayerScavGenerator.cs | 7 +- .../Generators/PmcWaveGenerator.cs | 10 +-- .../Generators/RagfairAssortGenerator.cs | 10 +-- .../Generators/RagfairOfferGenerator.cs | 87 +++++++++--------- .../Generators/ScavCaseRewardGenerator.cs | 74 +++++++-------- .../Generators/WeatherGenerator.cs | 8 +- .../Helpers/BotGeneratorHelper.cs | 6 +- .../SPTarkov.Server.Core/Helpers/BotHelper.cs | 12 +-- .../Dialogue/Commando/SptCommandoCommands.cs | 2 +- .../Helpers/Dialogue/CommandoDialogChatBot.cs | 6 +- .../Commands/ForceSnowMessageHandler.cs | 18 ++-- .../Commands/ForceSummerMessageHandler.cs | 18 ++-- .../Commands/GiveMeSpaceMessageHandler.cs | 6 +- .../Commands/SendGiftMessageHandler.cs | 26 +++--- .../Helpers/Dialogue/SptDialogueChatBot.cs | 22 ++--- .../Helpers/DurabilityLimitsHelper.cs | 56 ++++++------ .../Helpers/InventoryHelper.cs | 8 +- .../Helpers/QuestHelper.cs | 21 +++-- .../Helpers/RagfairHelper.cs | 4 +- .../Helpers/RagfairOfferHelper.cs | 18 ++-- .../Helpers/RagfairSellHelper.cs | 12 +-- .../Helpers/RepairHelper.cs | 12 +-- .../Helpers/TraderHelper.cs | 22 ++--- .../Helpers/WeatherHelper.cs | 4 +- .../Models/Spt/Config/CoreConfig.cs | 2 +- .../Servers/RagfairServer.cs | 4 +- .../Services/AirdropService.cs | 10 +-- .../Services/BackupService.cs | 28 +++--- .../Services/BotEquipmentFilterService.cs | 18 ++-- .../Services/BotNameService.cs | 22 ++--- .../Services/BotWeaponModLimitService.cs | 6 +- .../Services/BtrDeliveryService.cs | 12 +-- .../Services/CircleOfCultistService.cs | 20 ++--- .../Services/CustomLocationWaveService.cs | 14 +-- .../Services/GiftService.cs | 10 +-- .../Services/InsuranceService.cs | 28 +++--- .../Services/ItemFilterService.cs | 36 ++++---- .../Services/LocaleService.cs | 18 ++-- .../Services/LocationLifecycleService.cs | 64 ++++++------- .../Services/OpenZoneService.cs | 12 +-- .../Services/PaymentService.cs | 6 +- .../Services/PostDbLoadService.cs | 66 +++++++------- .../Services/ProfileFixerService.cs | 9 +- .../Services/RagfairOfferService.cs | 4 +- .../Services/RagfairPriceService.cs | 28 +++--- .../Services/RaidTimeAdjustmentService.cs | 10 +-- .../Services/RaidWeatherService.cs | 18 ++-- .../Services/RepairService.cs | 36 ++++---- .../Services/SeasonalEventService.cs | 90 +++++++++---------- .../TraderPurchasePersisterService.cs | 4 +- .../SPTarkov.Server.Core/Status/StatusPage.cs | 6 +- 78 files changed, 696 insertions(+), 724 deletions(-) diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/BtrDeliveryCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/BtrDeliveryCallbacks.cs index d531d4e3..f04fba4a 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/BtrDeliveryCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/BtrDeliveryCallbacks.cs @@ -21,11 +21,11 @@ public class BtrDeliveryCallbacks( SaveServer saveServer ) : IOnUpdate { - private readonly BtrDeliveryConfig _btrDeliveryConfig = configServer.GetConfig(); + protected readonly BtrDeliveryConfig BtrDeliveryConfig = configServer.GetConfig(); public Task OnUpdate(long secondsSinceLastRun) { - if (secondsSinceLastRun < _btrDeliveryConfig.RunIntervalSeconds) + if (secondsSinceLastRun < BtrDeliveryConfig.RunIntervalSeconds) { return Task.FromResult(false); } diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/HideoutCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/HideoutCallbacks.cs index c65eb0fd..11406875 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/HideoutCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/HideoutCallbacks.cs @@ -13,11 +13,11 @@ namespace SPTarkov.Server.Core.Callbacks; [Injectable(TypePriority = OnUpdateOrder.HideoutCallbacks)] public class HideoutCallbacks(HideoutController hideoutController, ConfigServer configServer) : IOnUpdate { - private readonly HideoutConfig _hideoutConfig = configServer.GetConfig(); + protected readonly HideoutConfig HideoutConfig = configServer.GetConfig(); public Task OnUpdate(long secondsSinceLastRun) { - if (secondsSinceLastRun < _hideoutConfig.RunIntervalSeconds) + if (secondsSinceLastRun < HideoutConfig.RunIntervalSeconds) { // Not enough time has passed since last run, exit early return Task.FromResult(false); diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/InsuranceCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/InsuranceCallbacks.cs index 789dc328..7445a4c3 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/InsuranceCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/InsuranceCallbacks.cs @@ -15,11 +15,11 @@ namespace SPTarkov.Server.Core.Callbacks; public class InsuranceCallbacks(InsuranceController insuranceController, HttpResponseUtil httpResponseUtil, ConfigServer configServer) : IOnUpdate { - private readonly InsuranceConfig _insuranceConfig = configServer.GetConfig(); + protected readonly InsuranceConfig InsuranceConfig = configServer.GetConfig(); public Task OnUpdate(long secondsSinceLastRun) { - if (secondsSinceLastRun < _insuranceConfig.RunIntervalSeconds) + if (secondsSinceLastRun < InsuranceConfig.RunIntervalSeconds) { return Task.FromResult(false); } diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/RagfairCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/RagfairCallbacks.cs index f870e82f..fb942072 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/RagfairCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/RagfairCallbacks.cs @@ -22,7 +22,7 @@ public class RagfairCallbacks( ConfigServer configServer ) : IOnLoad, IOnUpdate { - private readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); public Task OnLoad() { @@ -34,7 +34,7 @@ public class RagfairCallbacks( public Task OnUpdate(long secondsSinceLastRun) { - if (secondsSinceLastRun < _ragfairConfig.RunIntervalSeconds) + if (secondsSinceLastRun < RagfairConfig.RunIntervalSeconds) { // Not enough time has passed since last run, exit early return Task.FromResult(false); diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/SaveCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/SaveCallbacks.cs index ed6d1abe..c897e986 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/SaveCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/SaveCallbacks.cs @@ -9,7 +9,7 @@ namespace SPTarkov.Server.Core.Callbacks; [Injectable(TypePriority = OnLoadOrder.SaveCallbacks)] public class SaveCallbacks(SaveServer saveServer, ConfigServer configServer, BackupService backupService) : IOnLoad, IOnUpdate { - private readonly CoreConfig _coreConfig = configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); public async Task OnLoad() { @@ -19,7 +19,7 @@ public class SaveCallbacks(SaveServer saveServer, ConfigServer configServer, Bac public async Task OnUpdate(long secondsSinceLastRun) { - if (secondsSinceLastRun < _coreConfig.ProfileSaveIntervalInSeconds) + if (secondsSinceLastRun < CoreConfig.ProfileSaveIntervalInSeconds) { // Not enough time has passed since last run, exit early return false; diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/TraderCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/TraderCallbacks.cs index ca72e726..c73dfa45 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/TraderCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/TraderCallbacks.cs @@ -14,7 +14,7 @@ public class TraderCallbacks(HttpResponseUtil httpResponseUtil, TraderController : IOnLoad, IOnUpdate { - private readonly TraderConfig _traderConfig = configServer.GetConfig(); + protected readonly TraderConfig TraderConfig = configServer.GetConfig(); public Task OnLoad() { @@ -65,6 +65,6 @@ public class TraderCallbacks(HttpResponseUtil httpResponseUtil, TraderController /// public ValueTask GetModdedTraderData(string url, EmptyRequestData _, MongoId sessionID) { - return new ValueTask(httpResponseUtil.NoBody(_traderConfig.ModdedTraders)); + return new ValueTask(httpResponseUtil.NoBody(TraderConfig.ModdedTraders)); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/AchievementController.cs b/Libraries/SPTarkov.Server.Core/Controllers/AchievementController.cs index 625fedb8..49bfa1ba 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/AchievementController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/AchievementController.cs @@ -11,7 +11,7 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class AchievementController(ProfileHelper profileHelper, DatabaseService databaseService, ConfigServer configServer) { - protected readonly CoreConfig coreConfig = configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); /// /// Get base achievements @@ -33,7 +33,7 @@ public class AchievementController(ProfileHelper profileHelper, DatabaseService var stats = new Dictionary(); var profiles = profileHelper .GetProfiles() - .Where(kvp => !coreConfig.Features.AchievementProfileIdBlacklist.Contains(kvp.Value.ProfileInfo.ProfileId)) + .Where(kvp => !CoreConfig.Features.AchievementProfileIdBlacklist.Contains(kvp.Value.ProfileInfo.ProfileId)) .ToDictionary(); var achievements = databaseService.GetAchievements(); diff --git a/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs b/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs index 3d5e29b1..fa0151ad 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs @@ -28,20 +28,20 @@ public class DialogueController( IEnumerable dialogueChatBots ) { - protected readonly CoreConfig _coreConfig = configServer.GetConfig(); - protected readonly List _dialogueChatBots = dialogueChatBots.ToList(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); + protected readonly List DialogueChatBots = dialogueChatBots.ToList(); /// /// /// public virtual void RegisterChatBot(IDialogueChatBot chatBot) // TODO: this is in with the helper types { - if (_dialogueChatBots.Any(cb => cb.GetChatBot().Id == chatBot.GetChatBot().Id)) + if (DialogueChatBots.Any(cb => cb.GetChatBot().Id == chatBot.GetChatBot().Id)) { logger.Error(serverLocalisationService.GetText("dialog-chatbot_id_already_exists", chatBot.GetChatBot().Id)); } - _dialogueChatBots.Add(chatBot); + DialogueChatBots.Add(chatBot); } /// @@ -116,9 +116,9 @@ public class DialogueController( { var activeBots = new List(); - var chatBotConfig = _coreConfig.Features.ChatbotFeatures; + var chatBotConfig = CoreConfig.Features.ChatbotFeatures; - foreach (var bot in _dialogueChatBots) + foreach (var bot in DialogueChatBots) { var botData = bot.GetChatBot(); if (chatBotConfig.EnabledBots.ContainsKey(botData.Id)) @@ -302,7 +302,7 @@ public class DialogueController( var dialogue = profile.DialogueRecords[request.DialogId]; dialogue.Users = []; - var chatBot = _dialogueChatBots.FirstOrDefault(cb => cb.GetChatBot().Id == request.DialogId); + var chatBot = DialogueChatBots.FirstOrDefault(cb => cb.GetChatBot().Id == request.DialogId); if (chatBot is null) { @@ -515,7 +515,7 @@ public class DialogueController( { mailSendService.SendPlayerMessageToNpc(sessionId, request.DialogId, request.Text); - var chatBot = _dialogueChatBots.FirstOrDefault(cb => cb.GetChatBot().Id == request.DialogId); + var chatBot = DialogueChatBots.FirstOrDefault(cb => cb.GetChatBot().Id == request.DialogId); if (chatBot is not null) { diff --git a/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs b/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs index 9d0d6002..b85fbe78 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs @@ -36,11 +36,11 @@ public class GameController( ProfileActivityService profileActivityService ) { - protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly CoreConfig _coreConfig = configServer.GetConfig(); - protected readonly double _deviation = 0.0001; - protected readonly HideoutConfig _hideoutConfig = configServer.GetConfig(); - protected readonly HttpConfig _httpConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); + protected const double Deviation = 0.0001; + protected readonly HideoutConfig HideoutConfig = configServer.GetConfig(); + protected readonly HttpConfig HttpConfig = configServer.GetConfig(); /// /// Handle client/game/start @@ -96,7 +96,7 @@ public class GameController( var pmcProfile = fullProfile.CharacterData.PmcData; - if (_coreConfig.Fixes.FixProfileBreakingInventoryItemIssues) + if (CoreConfig.Fixes.FixProfileBreakingInventoryItemIssues) { profileFixerService.FixProfileBreakingInventoryItemIssues(pmcProfile); } @@ -122,7 +122,7 @@ public class GameController( pmcProfile.UnlockHideoutWallInProfile(); // Handle if player has been inactive for a long time, catch up on hideout update before the user goes to his hideout - if (!profileActivityService.ActiveWithinLastMinutes(sessionId, _hideoutConfig.UpdateProfileHideoutWhenActiveWithinMinutes)) + if (!profileActivityService.ActiveWithinLastMinutes(sessionId, HideoutConfig.UpdateProfileHideoutWhenActiveWithinMinutes)) { hideoutHelper.UpdatePlayerHideout(sessionId); } @@ -206,7 +206,7 @@ public class GameController( /// public List GetServer(MongoId sessionId) { - return [new ServerDetails { Ip = _httpConfig.BackendIp, Port = _httpConfig.BackendPort }]; + return [new ServerDetails { Ip = HttpConfig.BackendIp, Port = HttpConfig.BackendPort }]; } /// @@ -226,7 +226,7 @@ public class GameController( /// public CheckVersionResponse GetValidGameVersion(MongoId sessionId) { - return new CheckVersionResponse { IsValid = true, LatestVersion = _coreConfig.CompatibleTarkovVersion }; + return new CheckVersionResponse { IsValid = true, LatestVersion = CoreConfig.CompatibleTarkovVersion }; } /// @@ -257,7 +257,7 @@ public class GameController( /// public SurveyResponseData GetSurvey(MongoId sessionId) { - return _coreConfig.Survey; + return CoreConfig.Survey; } /// @@ -308,7 +308,7 @@ public class GameController( .Aggregate(0d, (sum, bonus) => sum + bonus.Value!.Value); // Player has energy deficit - if (pmcProfile.Health?.Energy?.Current - pmcProfile.Health?.Energy?.Maximum <= _deviation) + if (pmcProfile.Health?.Energy?.Current - pmcProfile.Health?.Energy?.Maximum <= Deviation) { // Set new value, whatever is smallest pmcProfile.Health!.Energy!.Current += Math.Round(energyRegenPerHour * (diffSeconds!.Value / 3600)); @@ -319,7 +319,7 @@ public class GameController( } // Player has hydration deficit - if (pmcProfile.Health?.Hydration?.Current - pmcProfile.Health?.Hydration?.Maximum <= _deviation) + if (pmcProfile.Health?.Hydration?.Current - pmcProfile.Health?.Hydration?.Maximum <= Deviation) { pmcProfile.Health!.Hydration!.Current += Math.Round(hydrationRegenPerHour * (diffSeconds!.Value / 3600)); if (pmcProfile.Health.Hydration.Current > pmcProfile.Health.Hydration.Maximum) @@ -464,7 +464,7 @@ public class GameController( var bots = databaseService.GetBots().Types; // Official names can only be 15 chars in length - if (playerName.Length > _botConfig.BotNameLengthLimit) + if (playerName.Length > BotConfig.BotNameLengthLimit) { return; } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs b/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs index b731a100..6c4a38e6 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs @@ -46,7 +46,7 @@ public class HideoutController( { public static readonly MongoId NameTaskConditionCountersCraftingId = new("673f5d6fdd6ed700c703afdc"); - protected readonly FrozenSet _areasWithResources = + protected readonly FrozenSet AreasWithResources = [ HideoutAreas.AirFilteringUnit, HideoutAreas.WaterCollector, @@ -55,7 +55,7 @@ public class HideoutController( HideoutAreas.RestSpace, // Can insert disk ]; - protected readonly HideoutConfig _hideoutConfig = configServer.GetConfig(); + protected readonly HideoutConfig HideoutConfig = configServer.GetConfig(); /// /// Handle HideoutUpgrade event @@ -468,7 +468,7 @@ public class HideoutController( } // Handle areas that have resources that can be placed in/taken out of slots from the area - if (_areasWithResources.Contains(hideoutArea.Type)) + if (AreasWithResources.Contains(hideoutArea.Type)) { var response = RemoveResourceFromArea(sessionID, pmcData, request, output, hideoutArea); @@ -860,18 +860,18 @@ public class HideoutController( if (area is not null && request.RecipeId != area.LastRecipe) // 1 point per craft upon the end of production for alternating between 2 different crafting recipes in the same module { - craftingExpAmount += _hideoutConfig.ExpCraftAmount; // Default is 10 + craftingExpAmount += HideoutConfig.ExpCraftAmount; // Default is 10 } // Update variable with time spent crafting item(s) // 1 point per 8 hours of crafting totalCraftingHours += recipe.ProductionTime; - if (totalCraftingHours / _hideoutConfig.HoursForSkillCrafting >= 1) + if (totalCraftingHours / HideoutConfig.HoursForSkillCrafting >= 1) { // Spent enough time crafting to get a bonus xp multiplier - var multiplierCrafting = Math.Floor(totalCraftingHours.Value / _hideoutConfig.HoursForSkillCrafting); + var multiplierCrafting = Math.Floor(totalCraftingHours.Value / HideoutConfig.HoursForSkillCrafting); craftingExpAmount += (int)(1 * multiplierCrafting); - totalCraftingHours -= _hideoutConfig.HoursForSkillCrafting * multiplierCrafting; + totalCraftingHours -= HideoutConfig.HoursForSkillCrafting * multiplierCrafting; } // Make sure we can fit both the craft result and tools in the stash @@ -1526,7 +1526,7 @@ public class HideoutController( if ( profile.CharacterData?.PmcData?.Hideout is not null - && profileActivityService.ActiveWithinLastMinutes(sessionId, _hideoutConfig.UpdateProfileHideoutWhenActiveWithinMinutes) + && profileActivityService.ActiveWithinLastMinutes(sessionId, HideoutConfig.UpdateProfileHideoutWhenActiveWithinMinutes) ) { hideoutHelper.UpdatePlayerHideout(sessionId); diff --git a/Libraries/SPTarkov.Server.Core/Controllers/InRaidController.cs b/Libraries/SPTarkov.Server.Core/Controllers/InRaidController.cs index c921b135..681e8026 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/InRaidController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/InRaidController.cs @@ -8,14 +8,10 @@ using SPTarkov.Server.Core.Servers; namespace SPTarkov.Server.Core.Controllers; [Injectable] -public class InRaidController( - ProfileHelper profileHelper, - //ApplicationContext _applicationContext, - ConfigServer configServer -) +public class InRaidController(ProfileHelper profileHelper, ConfigServer configServer) { - protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly InRaidConfig _inRaidConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly InRaidConfig InRaidConfig = configServer.GetConfig(); /// /// Save locationId to active profiles in-raid object AND app context @@ -51,7 +47,7 @@ public class InRaidController( /// public InRaidConfig GetInRaidConfig() { - return _inRaidConfig; + return InRaidConfig; } /// @@ -63,7 +59,7 @@ public class InRaidController( /// % chance scav is hostile to player public double GetTraitorScavHostileChance(string url, MongoId sessionId) { - return _inRaidConfig.PlayerScavHostileChancePercent; + return InRaidConfig.PlayerScavHostileChancePercent; } /// @@ -74,6 +70,6 @@ public class InRaidController( /// string array of boss types public List GetBossTypes(string url, MongoId sessionId) { - return _botConfig.Bosses; + return BotConfig.Bosses; } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs b/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs index 359c1407..6a4dd183 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs @@ -41,7 +41,7 @@ public class InsuranceController( ICloner cloner ) { - protected readonly InsuranceConfig _insuranceConfig = configServer.GetConfig(); + protected readonly InsuranceConfig InsuranceConfig = configServer.GetConfig(); /// /// Process insurance items of all profiles prior to being given back to the player through the mail service @@ -130,7 +130,7 @@ public class InsuranceController( // Update the insured items to have the new root parent ID for root/orphaned items insured.Items = insured.Items.AdoptOrphanedItems(rootItemParentId); - var simulateItemsBeingTaken = _insuranceConfig.SimulateItemsBeingTaken; + var simulateItemsBeingTaken = InsuranceConfig.SimulateItemsBeingTaken; if (simulateItemsBeingTaken) { // Find items that could be taken by another player off the players body @@ -556,14 +556,14 @@ public class InsuranceController( { const int removeCount = 0; - if (randomUtil.GetChance100(_insuranceConfig.ChanceNoAttachmentsTakenPercent)) + if (randomUtil.GetChance100(InsuranceConfig.ChanceNoAttachmentsTakenPercent)) { return removeCount; } // Get attachments count above or equal to price set in config return weightedAttachmentByPrice - .Where(attachment => attachment.Value >= _insuranceConfig.MinAttachmentRoublePriceToBeTaken) + .Where(attachment => attachment.Value >= InsuranceConfig.MinAttachmentRoublePriceToBeTaken) .Count(_ => RollForDelete(traderId) ?? false); } @@ -699,7 +699,7 @@ public class InsuranceController( const int conversionFactor = 100; var returnChance = randomUtil.GetInt(0, maxRoll) / conversionFactor; - var traderReturnChance = _insuranceConfig.ReturnChancePercent[traderId]; + var traderReturnChance = InsuranceConfig.ReturnChancePercent[traderId]; var roll = returnChance >= traderReturnChance; // Log the roll with as much detail as possible. diff --git a/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs b/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs index f0f7ba34..b6ba8ab9 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs @@ -6,7 +6,6 @@ using SPTarkov.Server.Core.Models.Eft.Launcher; using SPTarkov.Server.Core.Models.Eft.Profile; using SPTarkov.Server.Core.Models.Spt.Config; using SPTarkov.Server.Core.Models.Spt.Mod; -using SPTarkov.Server.Core.Models.Utils; using SPTarkov.Server.Core.Servers; using SPTarkov.Server.Core.Services; using SPTarkov.Server.Core.Utils; @@ -26,7 +25,7 @@ public class LauncherController( ConfigServer configServer ) { - protected readonly CoreConfig _coreConfig = configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); /// /// Handle launcher connecting to server @@ -37,13 +36,13 @@ public class LauncherController( // Get all possible profile types + filter out any that are blacklisted var profileTemplates = databaseService .GetProfileTemplates() - .Where(profile => !_coreConfig.Features.CreateNewProfileTypesBlacklist.Contains(profile.Key)) + .Where(profile => !CoreConfig.Features.CreateNewProfileTypesBlacklist.Contains(profile.Key)) .ToDictionary(); return new ConnectResponse { BackendUrl = httpServerHelper.GetBackendUrl(), - Name = _coreConfig.ServerName, + Name = CoreConfig.ServerName, Editions = profileTemplates.Select(x => x.Key).ToList(), ProfileDescriptions = GetProfileDescriptions(profileTemplates), }; @@ -174,7 +173,7 @@ public class LauncherController( /// Session id public MongoId Wipe(RegisterData info) { - if (!_coreConfig.AllowProfileWipe) + if (!CoreConfig.AllowProfileWipe) { return MongoId.Empty(); } @@ -196,7 +195,7 @@ public class LauncherController( /// public string GetCompatibleTarkovVersion() { - return _coreConfig.CompatibleTarkovVersion; + return CoreConfig.CompatibleTarkovVersion; } /// diff --git a/Libraries/SPTarkov.Server.Core/Controllers/LauncherV2Controller.cs b/Libraries/SPTarkov.Server.Core/Controllers/LauncherV2Controller.cs index 92635d45..793ce970 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/LauncherV2Controller.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/LauncherV2Controller.cs @@ -22,7 +22,7 @@ public class LauncherV2Controller( Watermark watermark ) { - protected readonly CoreConfig _coreConfig = configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); /// /// Returns a simple string of Pong! @@ -135,7 +135,7 @@ public class LauncherV2Controller( /// public string EftVersion() { - return _coreConfig.CompatibleTarkovVersion; + return CoreConfig.CompatibleTarkovVersion; } /// diff --git a/Libraries/SPTarkov.Server.Core/Controllers/MatchController.cs b/Libraries/SPTarkov.Server.Core/Controllers/MatchController.cs index d4e8a67d..020c9bd8 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/MatchController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/MatchController.cs @@ -18,8 +18,8 @@ public class MatchController( WeatherHelper weatherHelper ) { - protected readonly MatchConfig _matchConfig = configServer.GetConfig(); - protected readonly PmcConfig _pmcConfig = configServer.GetConfig(); + protected readonly MatchConfig MatchConfig = configServer.GetConfig(); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); /// /// Handle client/match/available @@ -27,7 +27,7 @@ public class MatchController( /// True if server should be available public bool GetEnabled() { - return _matchConfig.Enabled; + return MatchConfig.Enabled; } /// @@ -100,9 +100,9 @@ public class MatchController( // TODO: add code to strip PMC of equipment now they've started the raid // Set pmcs to difficulty set in pre-raid screen if override in bot config isnt enabled - if (!_pmcConfig.UseDifficultyOverride) + if (!PMCConfig.UseDifficultyOverride) { - _pmcConfig.Difficulty = ConvertDifficultyDropdownIntoBotDifficulty(request.WavesSettings.BotDifficulty.ToString()); + PMCConfig.Difficulty = ConvertDifficultyDropdownIntoBotDifficulty(request.WavesSettings.BotDifficulty.ToString()); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs b/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs index dce4d745..5e2d69e2 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs @@ -49,7 +49,7 @@ public class RagfairController( ConfigServer configServer ) { - protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); /// /// Check all profiles and sell player offers / send player money for listing if it sold @@ -566,7 +566,7 @@ public class RagfairController( // Check for and apply item price modifer if it exists in config var averageOfferPrice = averages.Avg; - if (_ragfairConfig.Dynamic.ItemPriceMultiplier.TryGetValue(rootOfferItem.Template, out var itemPriceModifer)) + if (RagfairConfig.Dynamic.ItemPriceMultiplier.TryGetValue(rootOfferItem.Template, out var itemPriceModifer)) { averageOfferPrice *= itemPriceModifer; } @@ -587,7 +587,7 @@ public class RagfairController( offer.SellResults = ragfairSellHelper.RollForSale(sellChancePercent, (int)stackCountTotal); // Subtract flea market fee from stash - if (_ragfairConfig.Sell.Fees) + if (RagfairConfig.Sell.Fees) { var taxFeeChargeFailed = ChargePlayerTaxFee( sessionID, @@ -669,7 +669,7 @@ public class RagfairController( var newRootOfferItem = offer.Items[0]; // TODO: add logic like single/multi offers to find root item // Check for and apply item price modifer if it exists in config - if (_ragfairConfig.Dynamic.ItemPriceMultiplier.TryGetValue(newRootOfferItem.Template, out var itemPriceModifer)) + if (RagfairConfig.Dynamic.ItemPriceMultiplier.TryGetValue(newRootOfferItem.Template, out var itemPriceModifer)) { singleItemPrice *= itemPriceModifer; } @@ -694,7 +694,7 @@ public class RagfairController( offer.SellResults = ragfairSellHelper.RollForSale(sellChancePercent, (int)stackCountTotal, true); // Subtract flea market fee from stash - if (_ragfairConfig.Sell.Fees) + if (RagfairConfig.Sell.Fees) { var taxFeeChargeFailed = ChargePlayerTaxFee( sessionID, @@ -775,7 +775,7 @@ public class RagfairController( var qualityMultiplier = itemHelper.GetItemQualityModifierForItems(offer.Items, true); // Check for and apply item price modifer if it exists in config - if (_ragfairConfig.Dynamic.ItemPriceMultiplier.TryGetValue(offerRootItem.Template, out var itemPriceModifer)) + if (RagfairConfig.Dynamic.ItemPriceMultiplier.TryGetValue(offerRootItem.Template, out var itemPriceModifer)) { averageOfferPriceSingleItem *= itemPriceModifer; } @@ -792,7 +792,7 @@ public class RagfairController( offer.SellResults = ragfairSellHelper.RollForSale(sellChancePercent, (int)stackCountTotal); // Subtract flea market fee from stash - if (_ragfairConfig.Sell.Fees) + if (RagfairConfig.Sell.Fees) { var taxFeeChargeFailed = ChargePlayerTaxFee( sessionID, @@ -1016,10 +1016,10 @@ public class RagfairController( // Only reduce time to end if time remaining is greater than what we would set it to var differenceInSeconds = playerOffer.EndTime - timeUtil.GetTimeStamp(); - if (differenceInSeconds > _ragfairConfig.Sell.ExpireSeconds) + if (differenceInSeconds > RagfairConfig.Sell.ExpireSeconds) { // `expireSeconds` Default is 71 seconds - var newEndTime = _ragfairConfig.Sell.ExpireSeconds + timeUtil.GetTimeStamp(); + var newEndTime = RagfairConfig.Sell.ExpireSeconds + timeUtil.GetTimeStamp(); playerOffer.EndTime = (long?)Math.Round((double)newEndTime); } @@ -1052,7 +1052,7 @@ public class RagfairController( var playerOffer = playerOffers[playerOfferIndex]; // MOD: Pay flea market fee - if (_ragfairConfig.Sell.Fees) + if (RagfairConfig.Sell.Fees) { var count = 1; var sellInOncePiece = playerOffer.SellInOnePiece.GetValueOrDefault(false); diff --git a/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs b/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs index 78e600a5..23392ac4 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs @@ -35,8 +35,8 @@ public class TradeController( ConfigServer configServer ) { - protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); - protected readonly TraderConfig _traderConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); + protected readonly TraderConfig TraderConfig = configServer.GetConfig(); /// /// Handle TradingConfirm event @@ -52,7 +52,7 @@ public class TradeController( // Buying if (request.Type == "buy_from_trader") { - var foundInRaid = _traderConfig.PurchasesAreFoundInRaid; + var foundInRaid = TraderConfig.PurchasesAreFoundInRaid; var buyData = (ProcessBuyTradeRequestData)request; tradeHelper.BuyItem(pmcData, buyData, sessionID, foundInRaid, output); @@ -163,7 +163,7 @@ public class TradeController( SchemeId = 0, SchemeItems = requestOffer.Items, }; - tradeHelper.BuyItem(pmcData, buyData, sessionId, _traderConfig.PurchasesAreFoundInRaid, output); + tradeHelper.BuyItem(pmcData, buyData, sessionId, TraderConfig.PurchasesAreFoundInRaid, output); // Remove/lower offer quantity of item purchased from trader flea offer ragfairServer.ReduceOfferQuantity(fleaOffer.Id, requestOffer.Count ?? 0); @@ -197,7 +197,7 @@ public class TradeController( }; // buyItem() must occur prior to removing the offer stack, otherwise item inside offer doesn't exist for confirmTrading() to use - tradeHelper.BuyItem(pmcData, buyData, sessionId, _ragfairConfig.Dynamic.PurchasesAreFoundInRaid, output); + tradeHelper.BuyItem(pmcData, buyData, sessionId, RagfairConfig.Dynamic.PurchasesAreFoundInRaid, output); if (output.Warnings?.Count > 0) { return; diff --git a/Libraries/SPTarkov.Server.Core/Controllers/WeatherController.cs b/Libraries/SPTarkov.Server.Core/Controllers/WeatherController.cs index 8a0feaa0..3ba8d0c1 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/WeatherController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/WeatherController.cs @@ -3,9 +3,7 @@ using SPTarkov.Server.Core.Generators; using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Weather; using SPTarkov.Server.Core.Models.Enums; -using SPTarkov.Server.Core.Models.Spt.Config; using SPTarkov.Server.Core.Models.Spt.Weather; -using SPTarkov.Server.Core.Servers; using SPTarkov.Server.Core.Services; namespace SPTarkov.Server.Core.Controllers; @@ -14,12 +12,9 @@ namespace SPTarkov.Server.Core.Controllers; public class WeatherController( WeatherGenerator weatherGenerator, SeasonalEventService seasonalEventService, - RaidWeatherService raidWeatherService, - ConfigServer configServer + RaidWeatherService raidWeatherService ) { - protected WeatherConfig _weatherConfig = configServer.GetConfig(); - /// /// Handle client/weather /// diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotEquipmentModGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotEquipmentModGenerator.cs index c01f93f8..0afef244 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotEquipmentModGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotEquipmentModGenerator.cs @@ -80,7 +80,7 @@ public class BotEquipmentModGenerator( const string modScopeKey = "mod_scope"; const string modScope000Key = "mod_scope_000"; - protected readonly BotConfig _botConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); /// /// Check mods are compatible and add to array @@ -460,7 +460,7 @@ public class BotEquipmentModGenerator( // Get pool of mods that fit weapon request.ModPool.TryGetValue(request.ParentTemplate.Id, out var compatibleModsPool); - _botConfig.Equipment.TryGetValue(request.BotData.EquipmentRole, out var botEquipConfig); + BotConfig.Equipment.TryGetValue(request.BotData.EquipmentRole, out var botEquipConfig); var botEquipBlacklist = botEquipmentFilterService.GetBotEquipmentBlacklist( request.BotData.EquipmentRole, pmcProfile?.Info?.Level ?? 0 @@ -996,7 +996,7 @@ public class BotEquipmentModGenerator( if ((request.WeaponStats?.HasOptic ?? false) && modPool.Count > 1) { // Attempt to limit modpool to low profile gas blocks when weapon has an optic - var onlyLowProfileGasBlocks = modPool.Where(tpl => _botConfig.LowProfileGasBlockTpls.Contains(tpl)); + var onlyLowProfileGasBlocks = modPool.Where(tpl => BotConfig.LowProfileGasBlockTpls.Contains(tpl)); if (onlyLowProfileGasBlocks.Any()) { modPool = onlyLowProfileGasBlocks.ToHashSet(); @@ -1005,7 +1005,7 @@ public class BotEquipmentModGenerator( else if ((request.WeaponStats?.HasRearIronSight ?? false) && modPool.Count > 1) { // Attempt to limit modpool to high profile gas blocks when weapon has rear iron sight + no front iron sight - var onlyHighProfileGasBlocks = modPool.Where(tpl => !_botConfig.LowProfileGasBlockTpls.Contains(tpl)); + var onlyHighProfileGasBlocks = modPool.Where(tpl => !BotConfig.LowProfileGasBlockTpls.Contains(tpl)); if (onlyHighProfileGasBlocks.Any()) { modPool = onlyHighProfileGasBlocks.ToHashSet(); diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotGenerator.cs index ad281764..5b77eba6 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotGenerator.cs @@ -36,8 +36,8 @@ public class BotGenerator( ICloner cloner ) { - protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly PmcConfig _pmcConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); /// /// Generate a player scav bot object @@ -187,7 +187,7 @@ public class BotGenerator( botJsonTemplate, botGenerationDetails, botRoleLowercase, - _botConfig.BotRolesThatMustHaveUniqueName + BotConfig.BotRolesThatMustHaveUniqueName ); // Only PMCs need a lower nickname @@ -263,7 +263,7 @@ public class BotGenerator( bot.Info.GameVersion ); - if (_botConfig.BotRolesWithDogTags.Contains(botRoleLowercase)) + if (BotConfig.BotRolesWithDogTags.Contains(botRoleLowercase)) { AddDogtagToBot(bot); } @@ -287,7 +287,7 @@ public class BotGenerator( /// True if name should be simulated pscav protected bool ShouldSimulatePlayerScav(string botRole) { - return botRole == Roles.Assault && randomUtil.GetChance100(_botConfig.ChanceAssaultScavHasPlayerScavName); + return botRole == Roles.Assault && randomUtil.GetChance100(BotConfig.ChanceAssaultScavHasPlayerScavName); } /// @@ -708,7 +708,7 @@ public class BotGenerator( } // Choose random weighted game version for bot - botInfo.GameVersion = weightedRandomHelper.GetWeightedValue(_pmcConfig.GameVersionWeight); + botInfo.GameVersion = weightedRandomHelper.GetWeightedValue(PMCConfig.GameVersionWeight); // Choose appropriate member category value switch (botInfo.GameVersion) @@ -721,7 +721,7 @@ public class BotGenerator( break; default: // Everyone else gets a weighted randomised category - botInfo.MemberCategory = weightedRandomHelper.GetWeightedValue(_pmcConfig.AccountTypeWeight); + botInfo.MemberCategory = weightedRandomHelper.GetWeightedValue(PMCConfig.AccountTypeWeight); break; } @@ -758,7 +758,7 @@ public class BotGenerator( /// item tpl protected MongoId GetDogtagTplByGameVersionAndSide(string side, string gameVersion) { - _pmcConfig.DogtagSettings.TryGetValue(side.ToLower(), out var gameVersionWeights); + PMCConfig.DogtagSettings.TryGetValue(side.ToLower(), out var gameVersionWeights); if (!gameVersionWeights.TryGetValue(gameVersion, out var possibleDogtags)) { gameVersionWeights.TryGetValue("default", out possibleDogtags); diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotInventoryGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotInventoryGenerator.cs index f31b7f3e..49727c7a 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotInventoryGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotInventoryGenerator.cs @@ -59,8 +59,8 @@ public class BotInventoryGenerator( EquipmentSlots.Earpiece, ]; - private readonly BotConfig _botConfig = configServer.GetConfig(); - private readonly PmcConfig _pmcConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); private readonly FrozenSet _slotsToCheck = [nameof(EquipmentSlots.Pockets), nameof(EquipmentSlots.SecuredContainer)]; @@ -197,7 +197,7 @@ public class BotInventoryGenerator( GetRaidConfigurationRequestData? raidConfig ) { - if (!_botConfig.Equipment.TryGetValue(botGeneratorHelper.GetBotEquipmentRole(botRole), out var botEquipConfig)) + if (!BotConfig.Equipment.TryGetValue(botGeneratorHelper.GetBotEquipmentRole(botRole), out var botEquipConfig)) { logger.Error($"Bot Equipment generation failed, unable to find equipment filters for: {botRole}"); @@ -224,13 +224,13 @@ public class BotInventoryGenerator( } // Is PMC + generating armband + armband forcing is enabled - if (_pmcConfig.ForceArmband.Enabled && isPmc) + if (PMCConfig.ForceArmband.Enabled && isPmc) { // Replace armband pool with single tpl from config if (templateInventory.Equipment.TryGetValue(EquipmentSlots.ArmBand, out var armbands)) { // Get tpl based on pmc side - var armbandTpl = botRole == "pmcusec" ? _pmcConfig.ForceArmband.Usec : _pmcConfig.ForceArmband.Bear; + var armbandTpl = botRole == "pmcusec" ? PMCConfig.ForceArmband.Usec : PMCConfig.ForceArmband.Bear; armbands.Clear(); armbands.Add(armbandTpl, 1); @@ -599,7 +599,7 @@ public class BotInventoryGenerator( // Edge case: Filter the armor items mod pool if bot exists in config dict + config has armor slot if ( - _botConfig.Equipment.ContainsKey(settings.BotData.EquipmentRole) + BotConfig.Equipment.ContainsKey(settings.BotData.EquipmentRole) && settings.RandomisationDetails?.RandomisedArmorSlots != null && settings.RandomisationDetails.RandomisedArmorSlots.Contains(settings.RootEquipmentSlot.ToString()) ) diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotLevelGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotLevelGenerator.cs index 1221dd01..b4bb00d3 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotLevelGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotLevelGenerator.cs @@ -44,6 +44,14 @@ public class BotLevelGenerator(RandomUtil randomUtil, DatabaseService databaseSe return new RandomisedBotLevelResult { Exp = baseExp + fractionalExp, Level = level }; } + /// + /// Choose a randomised level based on inputs + /// + /// Lowest level to choose + /// Highest level to choose + /// Bias shift to apply to the random number generation + /// Number of iterations to use for generating a Gaussian random number + /// Bot level public int ChooseBotLevel(double min, double max, int shift, double number) { return (int)randomUtil.GetBiasedRandomNumber(min, max, shift, number); diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotLootGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotLootGenerator.cs index db2bf6b1..451722ff 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotLootGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotLootGenerator.cs @@ -32,8 +32,8 @@ public class BotLootGenerator( ICloner cloner ) { - protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly PmcConfig _pmcConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); /// /// @@ -110,7 +110,7 @@ public class BotLootGenerator( var grenadeCount = weightedRandomHelper.GetWeightedValue(itemCounts.Grenades.Weights); // If bot has been flagged as not having loot, set below counts to 0 - if (_botConfig.DisableLootOnBotTypes.Contains(botRole.ToLowerInvariant())) + if (BotConfig.DisableLootOnBotTypes.Contains(botRole.ToLowerInvariant())) { backpackLootCount = 0; pocketLootCount = 0; @@ -119,7 +119,7 @@ public class BotLootGenerator( } // Forced pmc healing loot into secure container - if (isPmc && _pmcConfig.ForceHealingItemsIntoSecure) + if (isPmc && PMCConfig.ForceHealingItemsIntoSecure) { AddForcedMedicalItemsToPmcSecure(botInventory, botRole, botId); } @@ -248,7 +248,7 @@ public class BotLootGenerator( if (containersBotHasAvailable.Contains(EquipmentSlots.Backpack) && backpackLootCount > 0) { // Add randomly generated weapon to PMC backpacks - if (isPmc && randomUtil.GetChance100(_pmcConfig.LooseWeaponInBackpackChancePercent)) + if (isPmc && randomUtil.GetChance100(PMCConfig.LooseWeaponInBackpackChancePercent)) { AddLooseWeaponsToInventorySlot( botId, @@ -265,7 +265,7 @@ public class BotLootGenerator( } var backpackLootRoubleTotal = isPmc - ? _pmcConfig.LootSettings.Backpack.GetRoubleValue(botLevel, botGenerationDetails.Location) + ? PMCConfig.LootSettings.Backpack.GetRoubleValue(botLevel, botGenerationDetails.Location) : 0; AddLootFromPool( @@ -282,7 +282,7 @@ public class BotLootGenerator( ); } - var vestLootRoubleTotal = isPmc ? _pmcConfig.LootSettings.Vest.GetRoubleValue(botLevel, botGenerationDetails.Location) : 0; + var vestLootRoubleTotal = isPmc ? PMCConfig.LootSettings.Vest.GetRoubleValue(botLevel, botGenerationDetails.Location) : 0; // TacticalVest - generate loot if they have one if (containersBotHasAvailable.Contains(EquipmentSlots.TacticalVest)) @@ -302,7 +302,7 @@ public class BotLootGenerator( ); } - var pocketLootRoubleTotal = isPmc ? _pmcConfig.LootSettings.Pocket.GetRoubleValue(botLevel, botGenerationDetails.Location) : 0; + var pocketLootRoubleTotal = isPmc ? PMCConfig.LootSettings.Pocket.GetRoubleValue(botLevel, botGenerationDetails.Location) : 0; // Pockets AddLootFromPool( @@ -321,7 +321,7 @@ public class BotLootGenerator( // Secure // only add if not a pmc or is pmc and flag is true - if (!isPmc || (isPmc && _pmcConfig.AddSecureContainerLootFromBotConfig)) + if (!isPmc || (isPmc && PMCConfig.AddSecureContainerLootFromBotConfig)) { AddLootFromPool( botId, @@ -346,7 +346,7 @@ public class BotLootGenerator( return null; } - var matchingValue = _pmcConfig?.LootItemLimitsRub.FirstOrDefault(minMaxValue => + var matchingValue = PMCConfig?.LootItemLimitsRub.FirstOrDefault(minMaxValue => botLevel >= minMaxValue.Min && botLevel <= minMaxValue.Max ); @@ -475,9 +475,9 @@ public class BotLootGenerator( ]; // Is Simple-Wallet / WZ wallet - if (_botConfig.WalletLoot.WalletTplPool.Contains(weightedItemTpl)) + if (BotConfig.WalletLoot.WalletTplPool.Contains(weightedItemTpl)) { - var addCurrencyToWallet = randomUtil.GetChance100(_botConfig.WalletLoot.ChancePercent); + var addCurrencyToWallet = randomUtil.GetChance100(BotConfig.WalletLoot.ChancePercent); if (addCurrencyToWallet) { // Create the currency items we want to add to wallet @@ -576,17 +576,17 @@ public class BotLootGenerator( List> result = []; // Choose how many stacks of currency will be added to wallet - var itemCount = randomUtil.GetInt(_botConfig.WalletLoot.ItemCount.Min, _botConfig.WalletLoot.ItemCount.Max); + var itemCount = randomUtil.GetInt(BotConfig.WalletLoot.ItemCount.Min, BotConfig.WalletLoot.ItemCount.Max); for (var index = 0; index < itemCount; index++) { // Choose the size of the currency stack - default is 5k, 10k, 15k, 20k, 25k - var chosenStackCount = weightedRandomHelper.GetWeightedValue(_botConfig.WalletLoot.StackSizeWeight); + var chosenStackCount = weightedRandomHelper.GetWeightedValue(BotConfig.WalletLoot.StackSizeWeight); List items = [ new() { Id = new MongoId(), - Template = weightedRandomHelper.GetWeightedValue(_botConfig.WalletLoot.CurrencyWeight), + Template = weightedRandomHelper.GetWeightedValue(BotConfig.WalletLoot.CurrencyWeight), ParentId = walletId, Upd = new Upd { StackObjectsCount = int.Parse(chosenStackCount) }, }, @@ -663,8 +663,8 @@ public class BotLootGenerator( ] ); var randomisedWeaponCount = randomUtil.GetInt( - _pmcConfig.LooseWeaponInBackpackLootMinMax.Min, - _pmcConfig.LooseWeaponInBackpackLootMinMax.Max + PMCConfig.LooseWeaponInBackpackLootMinMax.Min, + PMCConfig.LooseWeaponInBackpackLootMinMax.Max ); if (randomisedWeaponCount <= 0) @@ -788,9 +788,9 @@ public class BotLootGenerator( public void RandomiseMoneyStackSize(string botRole, TemplateItem itemTemplate, Item moneyItem) { // Get all currency weights for this bot type - if (!_botConfig.CurrencyStackSize.TryGetValue(botRole, out var currencyWeights)) + if (!BotConfig.CurrencyStackSize.TryGetValue(botRole, out var currencyWeights)) { - currencyWeights = _botConfig.CurrencyStackSize["default"]; + currencyWeights = BotConfig.CurrencyStackSize["default"]; } var currencyWeight = currencyWeights[moneyItem.Template]; @@ -824,12 +824,12 @@ public class BotLootGenerator( { if (botHelper.IsBotPmc(botRole)) { - return _botConfig.ItemSpawnLimits["pmc"]; + return BotConfig.ItemSpawnLimits["pmc"]; } - if (_botConfig.ItemSpawnLimits.ContainsKey(botRole.ToLowerInvariant())) + if (BotConfig.ItemSpawnLimits.ContainsKey(botRole.ToLowerInvariant())) { - return _botConfig.ItemSpawnLimits[botRole.ToLowerInvariant()]; + return BotConfig.ItemSpawnLimits[botRole.ToLowerInvariant()]; } logger.Warning(serverLocalisationService.GetText("bot-unable_to_find_spawn_limits_fallback_to_defaults", botRole)); diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotWeaponGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotWeaponGenerator.cs index 3bc5f6ee..7ffbca44 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotWeaponGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotWeaponGenerator.cs @@ -35,11 +35,11 @@ public class BotWeaponGenerator( IEnumerable inventoryMagGenComponents ) { - protected const string _modMagazineSlotId = "mod_magazine"; - protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly IEnumerable _inventoryMagGenComponents = MagGenSetUp(inventoryMagGenComponents); - protected readonly PmcConfig _pmcConfig = configServer.GetConfig(); - protected readonly RepairConfig _repairConfig = configServer.GetConfig(); + private const string ModMagazineSlotId = "mod_magazine"; + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly IEnumerable InventoryMagGenComponents = MagGenSetUp(inventoryMagGenComponents); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); + protected readonly RepairConfig RepairConfig = configServer.GetConfig(); protected static List MagGenSetUp(IEnumerable components) { @@ -151,10 +151,10 @@ public class BotWeaponGenerator( var weaponWithModsArray = ConstructWeaponBaseList(weaponTpl, weaponParentId, slotName, weaponItemTemplate, botRole).ToList(); // Chance to add randomised weapon enhancement - if (isPmc && randomUtil.GetChance100(_pmcConfig.WeaponHasEnhancementChancePercent)) + if (isPmc && randomUtil.GetChance100(PMCConfig.WeaponHasEnhancementChancePercent)) // Add buff to weapon root { - repairService.AddBuff(_repairConfig.RepairKit.Weapon, weaponWithModsArray[0]); + repairService.AddBuff(RepairConfig.RepairKit.Weapon, weaponWithModsArray[0]); } // Add mods to weapon base @@ -194,7 +194,7 @@ public class BotWeaponGenerator( weaponWithModsArray = GetPresetWeaponMods(weaponTpl, slotName, weaponParentId, weaponItemTemplate, botRole); } - var tempList = cloner.Clone(weaponWithModsArray.Where(item => item.SlotId == _modMagazineSlotId)); + var tempList = cloner.Clone(weaponWithModsArray.Where(item => item.SlotId == ModMagazineSlotId)); // Fill existing magazines to full and sync ammo type foreach (var magazine in tempList) { @@ -455,12 +455,12 @@ public class BotWeaponGenerator( var inventoryMagGenModel = new InventoryMagGen(magWeights, magTemplate, weaponTemplate, ammoTemplate.Value, inventory, botId); - _inventoryMagGenComponents.FirstOrDefault(v => v.CanHandleInventoryMagGen(inventoryMagGenModel)).Process(inventoryMagGenModel); + InventoryMagGenComponents.FirstOrDefault(v => v.CanHandleInventoryMagGen(inventoryMagGenModel)).Process(inventoryMagGenModel); // Add x stacks of bullets to SecuredContainer (bots use a magic mag packing skill to reload instantly) AddAmmoToSecureContainer( botId, - _botConfig.SecureContainerAmmoStackCount, + BotConfig.SecureContainerAmmoStackCount, generatedWeaponResult.ChosenAmmoTemplate, ammoTemplate.Value.Properties.StackMaxSize ?? 0, inventory @@ -497,7 +497,7 @@ public class BotWeaponGenerator( // Add greandes to bot inventory var ubglAmmoGenModel = new InventoryMagGen(ubglMinMax, ubglDbTemplate, ubglDbTemplate, ubglAmmoDbTemplate, inventory, botId); - _inventoryMagGenComponents.FirstOrDefault(v => v.CanHandleInventoryMagGen(ubglAmmoGenModel)).Process(ubglAmmoGenModel); + InventoryMagGenComponents.FirstOrDefault(v => v.CanHandleInventoryMagGen(ubglAmmoGenModel)).Process(ubglAmmoGenModel); // Store extra grenades in secure container AddAmmoToSecureContainer(botId, 5, generatedWeaponResult.ChosenUbglAmmoTemplate.Value, 20, inventory); @@ -543,7 +543,7 @@ public class BotWeaponGenerator( /// Magazine template string. protected MongoId? GetMagazineTemplateFromWeaponTemplate(IEnumerable weaponMods, TemplateItem weaponTemplate, string botRole) { - var magazine = weaponMods.FirstOrDefault(m => m.SlotId == _modMagazineSlotId); + var magazine = weaponMods.FirstOrDefault(m => m.SlotId == ModMagazineSlotId); if (magazine is null) { // Edge case - magazineless chamber loaded weapons don't have magazines, e.g. mp18 @@ -708,10 +708,8 @@ public class BotWeaponGenerator( // Try to get cartridges from slots array first, if none found, try Cartridges array var cartridges = - magazineTemplate.Value.Properties.Slots.FirstOrDefault()?.Properties?.Filters.FirstOrDefault()?.Filter ?? magazineTemplate - .Value.Properties.Cartridges.FirstOrDefault() - ?.Properties?.Filters.FirstOrDefault() - ?.Filter; + magazineTemplate.Value.Properties.Slots.FirstOrDefault()?.Properties?.Filters.FirstOrDefault()?.Filter + ?? magazineTemplate.Value.Properties.Cartridges.FirstOrDefault()?.Properties?.Filters.FirstOrDefault()?.Filter; return cartridges ?? []; } diff --git a/Libraries/SPTarkov.Server.Core/Generators/FenceBaseAssortGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/FenceBaseAssortGenerator.cs index bebfa273..7ca63347 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/FenceBaseAssortGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/FenceBaseAssortGenerator.cs @@ -24,10 +24,10 @@ public class FenceBaseAssortGenerator( ServerLocalisationService localisationService, ConfigServer configServer, FenceService fenceService, - ICloner _cloner + ICloner cloner ) { - protected readonly TraderConfig traderConfig = configServer.GetConfig(); + protected readonly TraderConfig TraderConfig = configServer.GetConfig(); /// /// Create base fence assorts dynamically and store in memory @@ -63,9 +63,9 @@ public class FenceBaseAssortGenerator( } // Item base type blacklisted - if (traderConfig.Fence.Blacklist.Count > 0) + if (TraderConfig.Fence.Blacklist.Count > 0) { - if (traderConfig.Fence.Blacklist.Contains(itemId) || itemHelper.IsOfBaseclasses(itemId, traderConfig.Fence.Blacklist)) + if (TraderConfig.Fence.Blacklist.Contains(itemId) || itemHelper.IsOfBaseclasses(itemId, TraderConfig.Fence.Blacklist)) { continue; } @@ -81,7 +81,7 @@ public class FenceBaseAssortGenerator( } // Skip seasonal event items when not in seasonal event - if (traderConfig.Fence.BlacklistSeasonalItems && blockedSeasonalItems.Contains(itemId)) + if (TraderConfig.Fence.BlacklistSeasonalItems && blockedSeasonalItems.Contains(itemId)) { continue; } @@ -150,7 +150,7 @@ public class FenceBaseAssortGenerator( foreach (var defaultPreset in defaultPresets) { // Construct preset + mods - var itemAndChildren = _cloner.Clone(defaultPreset.Items).ReplaceIDs(); + var itemAndChildren = cloner.Clone(defaultPreset.Items).ReplaceIDs(); // Find root item and add some properties to it var rootItem = itemAndChildren.FirstOrDefault(item => string.IsNullOrEmpty(item.ParentId)); @@ -196,7 +196,7 @@ public class FenceBaseAssortGenerator( return false; } - return ammoPenetrationPower > traderConfig.Fence.AmmoMaxPenLimit; + return ammoPenetrationPower > TraderConfig.Fence.AmmoMaxPenLimit; } /// diff --git a/Libraries/SPTarkov.Server.Core/Generators/LocationLootGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/LocationLootGenerator.cs index 843cc244..1e44e83c 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/LocationLootGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/LocationLootGenerator.cs @@ -31,8 +31,8 @@ public class LocationLootGenerator( ICloner cloner ) { - protected readonly LocationConfig _locationConfig = configServer.GetConfig(); - protected readonly SeasonalEventConfig _seasonalEventConfig = configServer.GetConfig(); + protected readonly LocationConfig LocationConfig = configServer.GetConfig(); + protected readonly SeasonalEventConfig SeasonalEventConfig = configServer.GetConfig(); /// /// Generate Loot for provided location () @@ -56,7 +56,7 @@ public class LocationLootGenerator( // Pull location-specific spawn limits from db var itemsWithSpawnCountLimitsClone = cloner.Clone( - _locationConfig.LootMaxSpawnLimits.GetValueOrDefault(locationId.ToLowerInvariant()) + LocationConfig.LootMaxSpawnLimits.GetValueOrDefault(locationId.ToLowerInvariant()) ); // Store items with spawn count limits inside so they can be accessed later inside static/dynamic loot spawn methods @@ -123,7 +123,7 @@ public class LocationLootGenerator( if (!seasonalEventService.ChristmasEventEnabled()) { allStaticContainersOnMap = allStaticContainersOnMap.Where(item => - !_seasonalEventConfig.ChristmasContainerIds.Contains(item.Template.Id) + !SeasonalEventConfig.ChristmasContainerIds.Contains(item.Template.Id) ); } @@ -268,8 +268,8 @@ public class LocationLootGenerator( /// true = enabled protected bool LocationRandomisationEnabled(string locationId) { - return _locationConfig.ContainerRandomisationSettings.Enabled - && _locationConfig.ContainerRandomisationSettings.Maps.ContainsKey(locationId); + return LocationConfig.ContainerRandomisationSettings.Enabled + && LocationConfig.ContainerRandomisationSettings.Maps.ContainsKey(locationId); } /// @@ -282,7 +282,7 @@ public class LocationLootGenerator( return staticContainers.Where(staticContainer => staticContainer.Probability != 1 && !staticContainer.Template.IsAlwaysSpawn.GetValueOrDefault(false) - && !_locationConfig.ContainerRandomisationSettings.ContainerTypesToNotRandomise.Contains( + && !LocationConfig.ContainerRandomisationSettings.ContainerTypesToNotRandomise.Contains( staticContainer.Template.Items.FirstOrDefault().Template ) ); @@ -298,7 +298,7 @@ public class LocationLootGenerator( return staticContainersOnMap.Where(staticContainer => staticContainer.Probability == 1 || staticContainer.Template.IsAlwaysSpawn.GetValueOrDefault(false) - || _locationConfig.ContainerRandomisationSettings.ContainerTypesToNotRandomise.Contains( + || LocationConfig.ContainerRandomisationSettings.ContainerTypesToNotRandomise.Contains( staticContainer.Template.Items.FirstOrDefault().Template ) ); @@ -363,12 +363,12 @@ public class LocationLootGenerator( (int) Math.Round( groupKvP.Value.MinContainers.Value - * _locationConfig.ContainerRandomisationSettings.ContainerGroupMinSizeMultiplier + * LocationConfig.ContainerRandomisationSettings.ContainerGroupMinSizeMultiplier ), (int) Math.Round( groupKvP.Value.MaxContainers.Value - * _locationConfig.ContainerRandomisationSettings.ContainerGroupMaxSizeMultiplier + * LocationConfig.ContainerRandomisationSettings.ContainerGroupMaxSizeMultiplier ) ), }; @@ -465,7 +465,7 @@ public class LocationLootGenerator( // Choose items to add to container, factor in weighting + lock money down // Filter out items picked that are already in the above `tplsForced` array - var chosenTpls = _locationConfig.AllowDuplicateItemsInStaticContainers + var chosenTpls = LocationConfig.AllowDuplicateItemsInStaticContainers ? containerLootPool.Draw(itemCountToAdd).Where(tpl => !tplsForced.Contains(tpl) && !counterTrackerHelper.IncrementCount(tpl)) : containerLootPool .DrawAndRemove(itemCountToAdd, lockList) @@ -487,7 +487,7 @@ public class LocationLootGenerator( } // Check if item should have children removed - var items = _locationConfig.TplsToStripChildItemsFrom.Contains(tplToAdd) + var items = LocationConfig.TplsToStripChildItemsFrom.Contains(tplToAdd) ? [chosenItemWithChildren.Items.FirstOrDefault()] // Strip children from parent : chosenItemWithChildren.Items; @@ -495,7 +495,7 @@ public class LocationLootGenerator( var result = containerMap.FindSlotForItem(chosenItemWithChildren.Width, chosenItemWithChildren.Height); if (!result.Success.GetValueOrDefault(false)) { - if (failedToFitAttemptCount > _locationConfig.FitLootIntoContainerAttempts) + if (failedToFitAttemptCount > LocationConfig.FitLootIntoContainerAttempts) // x attempts to fit an item, container is probably full, stop trying to add more { break; @@ -625,9 +625,9 @@ public class LocationLootGenerator( /// multiplier protected double GetLooseLootMultiplierForLocation(string location) { - return _locationConfig.LooseLootMultiplier.TryGetValue(location, out var value) + return LocationConfig.LooseLootMultiplier.TryGetValue(location, out var value) ? value - : _locationConfig.LooseLootMultiplier["default"]; + : LocationConfig.LooseLootMultiplier["default"]; } /// @@ -637,9 +637,9 @@ public class LocationLootGenerator( /// multiplier protected double GetStaticLootMultiplierForLocation(string location) { - return _locationConfig.StaticLootMultiplier.TryGetValue(location, out var value) + return LocationConfig.StaticLootMultiplier.TryGetValue(location, out var value) ? value - : _locationConfig.StaticLootMultiplier["default"]; + : LocationConfig.StaticLootMultiplier["default"]; } /// @@ -681,7 +681,7 @@ public class LocationLootGenerator( * randomUtil.GetNormallyDistributedRandomNumber(dynamicLootDist.SpawnpointCount.Mean, dynamicLootDist.SpawnpointCount.Std) ); - var blacklistedSpawnPoints = _locationConfig.LooseLootBlacklist.GetValueOrDefault(locationName); + var blacklistedSpawnPoints = LocationConfig.LooseLootBlacklist.GetValueOrDefault(locationName); // Init empty array to hold spawn points, letting us pick them pseudo-randomly var spawnPointArray = new ProbabilityObjectArray(cloner); @@ -967,7 +967,7 @@ public class LocationLootGenerator( // Create array with just magazine List magazineItem = [new() { Id = new MongoId(), Template = chosenTpl }]; - if (randomUtil.GetChance100(_locationConfig.StaticMagazineLootHasAmmoChancePercent)) + if (randomUtil.GetChance100(LocationConfig.StaticMagazineLootHasAmmoChancePercent)) // Add randomised amount of cartridges { itemHelper.FillMagazineWithRandomCartridge( @@ -975,7 +975,7 @@ public class LocationLootGenerator( itemDbTemplate, // Magazine template staticAmmoDist, null, - _locationConfig.MinFillLooseMagazinePercent / 100d + LocationConfig.MinFillLooseMagazinePercent / 100d ); } @@ -990,7 +990,7 @@ public class LocationLootGenerator( // Ensure all IDs are unique itemWithChildren = cloner.Clone(itemWithChildren).ReplaceIDs().ToList(); - if (_locationConfig.TplsToStripChildItemsFrom.Contains(chosenItem.Template)) + if (LocationConfig.TplsToStripChildItemsFrom.Contains(chosenItem.Template)) // Strip children from parent before adding { itemWithChildren = [itemWithChildren.FirstOrDefault()]; @@ -1070,7 +1070,7 @@ public class LocationLootGenerator( } else if (itemHelper.IsOfBaseclass(chosenTpl, BaseClasses.MAGAZINE)) { - if (randomUtil.GetChance100(_locationConfig.MagazineLootHasAmmoChancePercent)) + if (randomUtil.GetChance100(LocationConfig.MagazineLootHasAmmoChancePercent)) { // Create array with just magazine GenerateStaticMagazineItem(staticAmmoDist, rootItem, itemTemplate, items); @@ -1114,7 +1114,7 @@ public class LocationLootGenerator( // We make base item in calling method, no need to do it here if (armorDbTemplate.Properties?.Slots is not null && armorDbTemplate.Properties.Slots.Any()) { - items = itemHelper.AddChildSlotItems(items, armorDbTemplate, _locationConfig.EquipmentLootSettings.ModSpawnChancePercent); + items = itemHelper.AddChildSlotItems(items, armorDbTemplate, LocationConfig.EquipmentLootSettings.ModSpawnChancePercent); } } @@ -1253,7 +1253,7 @@ public class LocationLootGenerator( itemTemplate, staticAmmoDist, null, - _locationConfig.MinFillStaticMagazinePercent / 100d + LocationConfig.MinFillStaticMagazinePercent / 100d ); // Replace existing magazine with above array diff --git a/Libraries/SPTarkov.Server.Core/Generators/PMCLootGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/PMCLootGenerator.cs index a2bda4b6..6f8c6854 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/PMCLootGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/PMCLootGenerator.cs @@ -20,7 +20,7 @@ public class PMCLootGenerator( ConfigServer configServer ) { - private readonly PmcConfig _pmcConfig = configServer.GetConfig(); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); // Store loot against its type, usec/bear private readonly Dictionary>? _backpackLootPool = []; @@ -47,7 +47,7 @@ public class PMCLootGenerator( } // Get a set of item types we want to generate - var allowedItemTypeWhitelist = _pmcConfig.PocketLoot.Whitelist; + var allowedItemTypeWhitelist = PMCConfig.PocketLoot.Whitelist; // Get a set of ids we don't want to generate var blacklist = GetContainerLootBlacklist(); @@ -79,11 +79,11 @@ public class PMCLootGenerator( } // Get a set of item types we want to generate - var allowedItemTypeWhitelist = _pmcConfig.VestLoot.Whitelist; + var allowedItemTypeWhitelist = PMCConfig.VestLoot.Whitelist; // Get a set of ids we don't want to generate var blacklist = GetContainerLootBlacklist(); - blacklist.UnionWith(_pmcConfig.VestLoot.Blacklist); // Include vest-specific blacklist + blacklist.UnionWith(PMCConfig.VestLoot.Blacklist); // Include vest-specific blacklist // Get pocket priceOverrides var vestPriceOverrides = GetPMCPriceOverrides(pmcRole, "vest"); @@ -111,9 +111,9 @@ public class PMCLootGenerator( return existingLootPool; } - var allowedItemTypeWhitelist = _pmcConfig.BackpackLoot.Whitelist; + var allowedItemTypeWhitelist = PMCConfig.BackpackLoot.Whitelist; var blacklist = GetContainerLootBlacklist(); - blacklist.UnionWith(_pmcConfig.BackpackLoot.Blacklist); // Include backpack-specific blacklist + blacklist.UnionWith(PMCConfig.BackpackLoot.Blacklist); // Include backpack-specific blacklist // Get pocket priceOverrides var backpackPriceOverrides = GetPMCPriceOverrides(pmcRole, "vest"); @@ -187,8 +187,8 @@ public class PMCLootGenerator( protected HashSet GetContainerLootBlacklist() { var blacklist = new HashSet(); - blacklist.UnionWith(_pmcConfig.PocketLoot.Blacklist); - blacklist.UnionWith(_pmcConfig.GlobalLootBlacklist); + blacklist.UnionWith(PMCConfig.PocketLoot.Blacklist); + blacklist.UnionWith(PMCConfig.GlobalLootBlacklist); blacklist.UnionWith(itemFilterService.GetBlacklistedItems()); blacklist.UnionWith(itemFilterService.GetItemRewardBlacklist()); blacklist.UnionWith(itemFilterService.GetBlacklistedLootableItems()); diff --git a/Libraries/SPTarkov.Server.Core/Generators/PlayerScavGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/PlayerScavGenerator.cs index 31fa9332..2426fd5c 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/PlayerScavGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/PlayerScavGenerator.cs @@ -36,7 +36,7 @@ public class PlayerScavGenerator( TimeUtil timeUtil ) { - protected readonly PlayerScavConfig _playerScavConfig = configServer.GetConfig(); + protected readonly PlayerScavConfig PlayerScavConfig = configServer.GetConfig(); /// /// Update a player profile to include a new player scav profile @@ -55,10 +55,7 @@ public class PlayerScavGenerator( // use karma level to get correct karmaSettings if ( - !_playerScavConfig.KarmaLevel.TryGetValue( - scavKarmaLevel.ToString(CultureInfo.InvariantCulture), - out var playerScavKarmaSettings - ) + !PlayerScavConfig.KarmaLevel.TryGetValue(scavKarmaLevel.ToString(CultureInfo.InvariantCulture), out var playerScavKarmaSettings) ) { logger.Error(serverLocalisationService.GetText("scav-missing_karma_settings", scavKarmaLevel)); diff --git a/Libraries/SPTarkov.Server.Core/Generators/PmcWaveGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/PmcWaveGenerator.cs index c80b8b48..05bf6213 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/PmcWaveGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/PmcWaveGenerator.cs @@ -9,7 +9,7 @@ namespace SPTarkov.Server.Core.Generators; [Injectable] public class PmcWaveGenerator(DatabaseService databaseService, ConfigServer configServer) { - protected readonly PmcConfig _pmcConfig = configServer.GetConfig(); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); /// /// Add a pmc wave to a map @@ -18,7 +18,7 @@ public class PmcWaveGenerator(DatabaseService databaseService, ConfigServer conf /// Boss wave to add to map public void AddPmcWaveToLocation(string locationId, BossLocationSpawn waveToAdd) { - _pmcConfig.CustomPmcWaves[locationId].Add(waveToAdd); + PMCConfig.CustomPmcWaves[locationId].Add(waveToAdd); } /// @@ -26,7 +26,7 @@ public class PmcWaveGenerator(DatabaseService databaseService, ConfigServer conf /// public void ApplyWaveChangesToAllMaps() { - foreach (var location in _pmcConfig.CustomPmcWaves) + foreach (var location in PMCConfig.CustomPmcWaves) { ApplyWaveChangesToMapByName(location.Key); } @@ -38,7 +38,7 @@ public class PmcWaveGenerator(DatabaseService databaseService, ConfigServer conf /// e.g. factory4_day, bigmap public void ApplyWaveChangesToMapByName(string name) { - if (!_pmcConfig.CustomPmcWaves.TryGetValue(name, out var pmcWavesToAdd)) + if (!PMCConfig.CustomPmcWaves.TryGetValue(name, out var pmcWavesToAdd)) { return; } @@ -53,7 +53,7 @@ public class PmcWaveGenerator(DatabaseService databaseService, ConfigServer conf /// Location Object public void ApplyWaveChangesToMap(LocationBase location) { - if (!_pmcConfig.CustomPmcWaves.TryGetValue(location.Id.ToLowerInvariant(), out var pmcWavesToAdd)) + if (!PMCConfig.CustomPmcWaves.TryGetValue(location.Id.ToLowerInvariant(), out var pmcWavesToAdd)) { return; } diff --git a/Libraries/SPTarkov.Server.Core/Generators/RagfairAssortGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/RagfairAssortGenerator.cs index a445f7a9..b6522a86 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/RagfairAssortGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/RagfairAssortGenerator.cs @@ -73,7 +73,7 @@ public class RagfairAssortGenerator( results = results.Union([presetAndModsClone]); } - foreach (var (id, item) in dbItems) + foreach (var (tpl, item) in dbItems) { if (!itemHelper.IsValidItem(item, RagfairItemInvalidBaseTypes)) { @@ -81,18 +81,18 @@ public class RagfairAssortGenerator( } // Skip seasonal items when not in-season - if (RagfairConfig.Dynamic.RemoveSeasonalItemsWhenNotInEvent && !seasonalEventActive && seasonalItemTplBlacklist.Contains(id)) + if (RagfairConfig.Dynamic.RemoveSeasonalItemsWhenNotInEvent && !seasonalEventActive && seasonalItemTplBlacklist.Contains(tpl)) { continue; } // Already processed - if (processedArmorItems.Contains(id)) + if (processedArmorItems.Contains(tpl)) { continue; } - var assortItemToAdd = new List { CreateRagfairAssortRootItem(id, id) }; // tpl and id must be the same so hideout recipe rewards work + var assortItemToAdd = new List { CreateRagfairAssortRootItem(tpl, tpl) }; // tpl and id must be the same so hideout recipe rewards work results = results.Union([assortItemToAdd]); } @@ -114,7 +114,7 @@ public class RagfairAssortGenerator( /// /// Create a base assort item and return it with populated values + 999999 stack count + unlimited count = true /// - /// tplid to add to item + /// tplId to add to item /// id to add to item /// Hydrated Item object protected Item CreateRagfairAssortRootItem(MongoId tplId, MongoId? id = null) diff --git a/Libraries/SPTarkov.Server.Core/Generators/RagfairOfferGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/RagfairOfferGenerator.cs index b8ccc582..245790b4 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/RagfairOfferGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/RagfairOfferGenerator.cs @@ -41,13 +41,13 @@ public class RagfairOfferGenerator( ICloner cloner ) { - protected List? allowedFleaPriceItemsForBarter; - protected readonly BotConfig botConfig = configServer.GetConfig(); + protected List? AllowedFleaPriceItemsForBarter; + protected readonly BotConfig BotConfig = configServer.GetConfig(); /// Internal counter to ensure each offer created has a unique value for its intId property - protected int offerCounter; + protected int OfferCounter; - protected readonly RagfairConfig ragfairConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); /// /// Create a flea offer and store it in the Ragfair server offers array @@ -109,7 +109,7 @@ public class RagfairOfferGenerator( var offer = new RagfairOffer { Id = new MongoId(), - InternalId = offerCounter, + InternalId = OfferCounter, User = details.Creator == OfferCreator.Player ? CreatePlayerUserDataForFleaOffer(details.UserId) @@ -128,7 +128,7 @@ public class RagfairOfferGenerator( Quantity = details.Quantity, }; - offerCounter++; + OfferCounter++; return offer; } @@ -152,8 +152,8 @@ public class RagfairOfferGenerator( { Id = userId, MemberType = MemberCategory.Default, - Nickname = botHelper.GetPmcNicknameOfMaxLength(botConfig.BotNameLengthLimit), - Rating = randomUtil.GetDouble(ragfairConfig.Dynamic.Rating.Min, ragfairConfig.Dynamic.Rating.Max), + Nickname = botHelper.GetPmcNicknameOfMaxLength(BotConfig.BotNameLengthLimit), + Rating = randomUtil.GetDouble(RagfairConfig.Dynamic.Rating.Min, RagfairConfig.Dynamic.Rating.Max), IsRatingGrowing = randomUtil.GetBool(), Avatar = null, Aid = hashUtil.GenerateAccountId(), @@ -188,15 +188,11 @@ public class RagfairOfferGenerator( /// rouble cost of offer protected double ConvertOfferRequirementsIntoRoubles(IEnumerable offerRequirements) { - var roublePrice = 0d; - foreach (var requirement in offerRequirements) - { - roublePrice += paymentHelper.IsMoneyTpl(requirement.TemplateId) + return offerRequirements.Sum(requirement => + paymentHelper.IsMoneyTpl(requirement.TemplateId) ? Math.Round(CalculateRoublePrice(requirement.Count.Value, requirement.TemplateId)) - : ragfairPriceService.GetFleaPriceForItem(requirement.TemplateId) * requirement.Count.Value; // Get flea price for barter offer items - } - - return roublePrice; + : ragfairPriceService.GetFleaPriceForItem(requirement.TemplateId) * requirement.Count.Value + ); } /// @@ -251,32 +247,31 @@ public class RagfairOfferGenerator( } // Generated pmc offer - return randomUtil.GetDouble(ragfairConfig.Dynamic.Rating.Min, ragfairConfig.Dynamic.Rating.Max); + return randomUtil.GetDouble(RagfairConfig.Dynamic.Rating.Min, RagfairConfig.Dynamic.Rating.Max); } /// /// Get number of section until offer should expire /// /// - /// ID of the offer owner + /// ID of the offer owner /// Time the offer is posted in seconds /// Number of seconds until offer expires - protected long GetOfferEndTime(OfferCreator creatorType, MongoId userID, long time) + protected long GetOfferEndTime(OfferCreator creatorType, MongoId userId, long time) { if (creatorType == OfferCreator.Player) { // Player offer = current time + offerDurationTimeInHour; var offerDurationTimeHours = databaseService.GetGlobals().Configuration.RagFair.OfferDurationTimeInHour; - return (long)(timeUtil.GetTimeStamp() + Math.Round((double)offerDurationTimeHours * TimeUtil.OneHourAsSeconds)); + return (long)(timeUtil.GetTimeStamp() + Math.Round(offerDurationTimeHours * TimeUtil.OneHourAsSeconds)); } if (creatorType == OfferCreator.Trader) - // Trader offer { - return (long)databaseService.GetTrader(userID).Base.NextResupply; + return (long)databaseService.GetTrader(userId).Base.NextResupply; } - var randomSpread = randomUtil.GetDouble(ragfairConfig.Dynamic.EndTimeSeconds.Min, ragfairConfig.Dynamic.EndTimeSeconds.Max); + var randomSpread = randomUtil.GetDouble(RagfairConfig.Dynamic.EndTimeSeconds.Min, RagfairConfig.Dynamic.EndTimeSeconds.Max); // Fake-player offer return (long)Math.Round(time + randomSpread); @@ -306,7 +301,7 @@ public class RagfairOfferGenerator( tasks.Add( Task.Factory.StartNew(() => { - CreateOffersFromAssort(assortItemWithChildren, replacingExpiredOffers, ragfairConfig.Dynamic); + CreateOffersFromAssort(assortItemWithChildren, replacingExpiredOffers, RagfairConfig.Dynamic); }) ); } @@ -338,9 +333,9 @@ public class RagfairOfferGenerator( // Armor presets can hold plates above the allowed flea level, remove if necessary var isPreset = rootItem?.Upd?.SptPresetId is not null && presetHelper.IsPreset(rootItem.Upd.SptPresetId.Value); - if (!isExpiredOffer && isPreset && ragfairConfig.Dynamic.Blacklist.EnableBsgList) + if (!isExpiredOffer && isPreset && RagfairConfig.Dynamic.Blacklist.EnableBsgList) { - RemoveBannedPlatesFromPreset(assortItemWithChildren, ragfairConfig.Dynamic.Blacklist.ArmorPlate); + RemoveBannedPlatesFromPreset(assortItemWithChildren, RagfairConfig.Dynamic.Blacklist.ArmorPlate); } // Get number of offers to create @@ -443,18 +438,18 @@ public class RagfairOfferGenerator( RemoveArmorPlates(itemWithChildren, rootItem); } - var isBarterOffer = randomUtil.GetChance100(ragfairConfig.Dynamic.Barter.ChancePercent); + var isBarterOffer = randomUtil.GetChance100(RagfairConfig.Dynamic.Barter.ChancePercent); var isPackOffer = !isBarterOffer - && randomUtil.GetChance100(ragfairConfig.Dynamic.Pack.ChancePercent) + && randomUtil.GetChance100(RagfairConfig.Dynamic.Pack.ChancePercent) && itemWithChildren.Count == 1 - && itemHelper.IsOfBaseclasses(rootItem.Template, ragfairConfig.Dynamic.Pack.ItemTypeWhitelist); + && itemHelper.IsOfBaseclasses(rootItem.Template, RagfairConfig.Dynamic.Pack.ItemTypeWhitelist); List barterScheme; if (isPackOffer) { // Set pack size - desiredStackSize = randomUtil.GetInt(ragfairConfig.Dynamic.Pack.ItemCountMin, ragfairConfig.Dynamic.Pack.ItemCountMax); + desiredStackSize = randomUtil.GetInt(RagfairConfig.Dynamic.Pack.ItemCountMin, RagfairConfig.Dynamic.Pack.ItemCountMax); // Don't randomise pack items barterScheme = CreateCurrencyBarterScheme(itemWithChildren, isPackOffer, desiredStackSize); @@ -463,8 +458,8 @@ public class RagfairOfferGenerator( { // Apply randomised properties RandomiseOfferItemUpdProperties(sellerId, itemWithChildren, itemToSellDetails, offerCreator); - barterScheme = CreateBarterBarterScheme(itemWithChildren, ragfairConfig.Dynamic.Barter); - if (ragfairConfig.Dynamic.Barter.MakeSingleStackOnly) + barterScheme = CreateBarterBarterScheme(itemWithChildren, RagfairConfig.Dynamic.Barter); + if (RagfairConfig.Dynamic.Barter.MakeSingleStackOnly) { var rootBarterItem = itemWithChildren.FirstOrDefault(); if (rootBarterItem?.Upd != null) @@ -502,7 +497,7 @@ public class RagfairOfferGenerator( /// Root armor item protected void RemoveArmorPlates(List itemWithChildren, Item rootItem) { - var armorConfig = ragfairConfig.Dynamic.Armor; + var armorConfig = RagfairConfig.Dynamic.Armor; var shouldRemovePlates = randomUtil.GetChance100(armorConfig.RemoveRemovablePlateChance); if (!shouldRemovePlates || !itemHelper.ArmorItemHasRemovablePlateSlots(rootItem.Template)) @@ -542,7 +537,7 @@ public class RagfairOfferGenerator( return; } - var blacklist = ragfairConfig.Dynamic.Blacklist; + var blacklist = RagfairConfig.Dynamic.Blacklist; var childAssortItems = assortsClone.Items.Where(x => !string.Equals(x.ParentId, "hideout", StringComparison.Ordinal)).ToList(); foreach (var item in assortsClone.Items) { @@ -601,7 +596,7 @@ public class RagfairOfferGenerator( Items = items, BarterScheme = barterSchemeItems, LoyalLevel = loyalLevel, - Quantity = (int?)item.Upd.StackObjectsCount ?? 1, + Quantity = (int?)item.Upd?.StackObjectsCount ?? 1, Creator = OfferCreator.Trader, }; CreateAndAddFleaOffer(createOfferDetails); @@ -615,12 +610,12 @@ public class RagfairOfferGenerator( /// Get array of an item with its mods + condition properties (e.g. durability)
/// Apply randomisation adjustments to condition if item base is found in ragfair.json/dynamic/condition ///
- /// ID of owner of item + /// ID of owner of item /// Item and mods, get condition of first item (only first array item is modified) /// DB details of first item /// protected void RandomiseOfferItemUpdProperties( - MongoId userID, + MongoId userId, IEnumerable itemWithMods, TemplateItem itemDetails, OfferCreator offerCreator @@ -639,7 +634,7 @@ public class RagfairOfferGenerator( } // Roll random chance to randomise item condition - if (randomUtil.GetChance100(ragfairConfig.Dynamic.Condition[parentId.Value].ConditionChance * 100)) + if (randomUtil.GetChance100(RagfairConfig.Dynamic.Condition[parentId.Value].ConditionChance * 100)) { RandomiseItemCondition(parentId.Value, itemWithMods, itemDetails); } @@ -654,7 +649,7 @@ public class RagfairOfferGenerator( protected MongoId? GetDynamicConditionIdForTpl(MongoId tpl) { // Get keys from condition config dictionary - var configConditions = ragfairConfig.Dynamic.Condition.Keys; + var configConditions = RagfairConfig.Dynamic.Condition.Keys; foreach (var baseClass in configConditions) { if (itemHelper.IsOfBaseclass(tpl, baseClass)) @@ -676,7 +671,7 @@ public class RagfairOfferGenerator( { var rootItem = itemWithMods.First(); - var itemConditionValues = ragfairConfig.Dynamic.Condition[conditionSettingsId]; + var itemConditionValues = RagfairConfig.Dynamic.Condition[conditionSettingsId]; var maxMultiplier = randomUtil.GetDouble(itemConditionValues.Max.Min, itemConditionValues.Max.Min); var currentMultiplier = randomUtil.GetDouble(itemConditionValues.Current.Min, itemConditionValues.Current.Max); @@ -692,7 +687,7 @@ public class RagfairOfferGenerator( var visorMod = itemWithMods.FirstOrDefault(item => item.ParentId == BaseClasses.ARMORED_EQUIPMENT.ToString() && item.SlotId == "mod_equipment_000" ); - if (randomUtil.GetChance100(25) && visorMod != null) + if (visorMod != null && randomUtil.GetChance100(25)) { visorMod.AddUpd(); @@ -806,7 +801,7 @@ public class RagfairOfferGenerator( /// /// Add missing conditions to an item if needed.
- /// Durabiltiy for repairable items.
+ /// Durability for repairable items.
/// HpResource for medical items. ///
/// Item to add conditions to @@ -911,7 +906,7 @@ public class RagfairOfferGenerator( protected List GetFleaPricesAsArray() { // Generate if needed - if (allowedFleaPriceItemsForBarter == null) + if (AllowedFleaPriceItemsForBarter == null) { var fleaPrices = databaseService.GetPrices(); @@ -920,13 +915,13 @@ public class RagfairOfferGenerator( .Select(kvTpl => new TplWithFleaPrice { Tpl = kvTpl.Key, Price = kvTpl.Value }) .Where(item => itemHelper.GetItem(item.Tpl).Key); - var itemTypeBlacklist = ragfairConfig.Dynamic.Barter.ItemTypeBlacklist; - allowedFleaPriceItemsForBarter = filteredFleaItems + var itemTypeBlacklist = RagfairConfig.Dynamic.Barter.ItemTypeBlacklist; + AllowedFleaPriceItemsForBarter = filteredFleaItems .Where(item => !itemHelper.IsOfBaseclasses(item.Tpl, itemTypeBlacklist)) .ToList(); } - return allowedFleaPriceItemsForBarter; + return AllowedFleaPriceItemsForBarter; } /// diff --git a/Libraries/SPTarkov.Server.Core/Generators/ScavCaseRewardGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/ScavCaseRewardGenerator.cs index 60fb3d03..9e9b99b3 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/ScavCaseRewardGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/ScavCaseRewardGenerator.cs @@ -31,9 +31,9 @@ public class ScavCaseRewardGenerator( ICloner cloner ) { - protected List _dbAmmoItemsCache = []; - protected List _dbItemsCache = []; - protected readonly ScavCaseConfig _scavCaseConfig = configServer.GetConfig(); + protected List DbAmmoItemsCache = []; + protected List DbItemsCache = []; + protected readonly ScavCaseConfig ScavCaseConfig = configServer.GetConfig(); /// /// Create an array of rewards that will be given to the player upon completing their scav case build @@ -49,9 +49,9 @@ public class ScavCaseRewardGenerator( var rewardItemCounts = GetScavCaseRewardCountsAndPrices(scavCaseDetails); // Get items that fit the price criteria as set by the scavCase config - var commonPricedItems = GetFilteredItemsByPrice(_dbItemsCache, rewardItemCounts.Common); - var rarePricedItems = GetFilteredItemsByPrice(_dbItemsCache, rewardItemCounts.Rare); - var superRarePricedItems = GetFilteredItemsByPrice(_dbItemsCache, rewardItemCounts.Superrare); + var commonPricedItems = GetFilteredItemsByPrice(DbItemsCache, rewardItemCounts.Common); + var rarePricedItems = GetFilteredItemsByPrice(DbItemsCache, rewardItemCounts.Rare); + var superRarePricedItems = GetFilteredItemsByPrice(DbItemsCache, rewardItemCounts.Superrare); // Get randomly picked items from each item collection, the count range of which is defined in hideout/scavcase.json var randomlyPickedCommonRewards = PickRandomRewards(commonPricedItems, rewardItemCounts.Common, RewardRarity.Common); @@ -78,9 +78,9 @@ public class ScavCaseRewardGenerator( { // Get an array of seasonal items that should not be shown right now as seasonal event is not active var inactiveSeasonalItems = seasonalEventService.GetInactiveSeasonalEventItems(); - if (!_dbItemsCache.Any()) + if (!DbItemsCache.Any()) { - _dbItemsCache = databaseService + DbItemsCache = databaseService .GetItems() .Values.Where(item => { @@ -103,7 +103,7 @@ public class ScavCaseRewardGenerator( // Skip item if item id is on blacklist if ( item.Type != "Item" - || _scavCaseConfig.RewardItemBlacklist.Contains(item.Id) + || ScavCaseConfig.RewardItemBlacklist.Contains(item.Id) || itemFilterService.IsItemBlacklisted(item.Id) ) { @@ -116,13 +116,13 @@ public class ScavCaseRewardGenerator( return false; } - if (!_scavCaseConfig.AllowBossItemsAsRewards && itemFilterService.IsBossItem(item.Id)) + if (!ScavCaseConfig.AllowBossItemsAsRewards && itemFilterService.IsBossItem(item.Id)) { return false; } // Skip item if parent id is blacklisted - if (itemHelper.IsOfBaseclasses(item.Id, _scavCaseConfig.RewardItemParentBlacklist)) + if (itemHelper.IsOfBaseclasses(item.Id, ScavCaseConfig.RewardItemParentBlacklist)) { return false; } @@ -137,9 +137,9 @@ public class ScavCaseRewardGenerator( .ToList(); } - if (!_dbAmmoItemsCache.Any()) + if (!DbAmmoItemsCache.Any()) { - _dbAmmoItemsCache = databaseService + DbAmmoItemsCache = databaseService .GetItems() .Values.Where(item => { @@ -161,7 +161,7 @@ public class ScavCaseRewardGenerator( } // Skip item if item id is on blacklist - if (_scavCaseConfig.RewardItemBlacklist.Contains(item.Id) || itemFilterService.IsItemBlacklisted(item.Id)) + if (ScavCaseConfig.RewardItemBlacklist.Contains(item.Id) || itemFilterService.IsItemBlacklisted(item.Id)) { return false; } @@ -172,7 +172,7 @@ public class ScavCaseRewardGenerator( return false; } - if (!_scavCaseConfig.AllowBossItemsAsRewards && itemFilterService.IsBossItem(item.Id)) + if (!ScavCaseConfig.AllowBossItemsAsRewards && itemFilterService.IsBossItem(item.Id)) { return false; } @@ -184,7 +184,7 @@ public class ScavCaseRewardGenerator( } // Skip ammo that doesn't stack as high as value in config - if (item.Properties.StackMaxSize < _scavCaseConfig.AmmoRewards.MinStackSize) + if (item.Properties.StackMaxSize < ScavCaseConfig.AmmoRewards.MinStackSize) { return false; } @@ -215,7 +215,7 @@ public class ScavCaseRewardGenerator( { // Only allow one reward to be money result.Add(GetRandomMoney()); - if (!_scavCaseConfig.AllowMultipleMoneyRewardsPerRarity) + if (!ScavCaseConfig.AllowMultipleMoneyRewardsPerRarity) { rewardWasMoney = true; } @@ -224,7 +224,7 @@ public class ScavCaseRewardGenerator( { // Only allow one reward to be ammo result.Add(GetRandomAmmo(rarity)); - if (!_scavCaseConfig.AllowMultipleAmmoRewardsPerRarity) + if (!ScavCaseConfig.AllowMultipleAmmoRewardsPerRarity) { rewardWasAmmo = true; } @@ -244,7 +244,7 @@ public class ScavCaseRewardGenerator( /// true if reward should be money protected bool RewardShouldBeMoney() { - return randomUtil.GetChance100(_scavCaseConfig.MoneyRewards.MoneyRewardChancePercent); + return randomUtil.GetChance100(ScavCaseConfig.MoneyRewards.MoneyRewardChancePercent); } /// @@ -253,7 +253,7 @@ public class ScavCaseRewardGenerator( /// true if reward should be ammo protected bool RewardShouldBeAmmo() { - return randomUtil.GetChance100(_scavCaseConfig.AmmoRewards.AmmoRewardChancePercent); + return randomUtil.GetChance100(ScavCaseConfig.AmmoRewards.AmmoRewardChancePercent); } /// @@ -278,12 +278,12 @@ public class ScavCaseRewardGenerator( /// random ammo item from items.json protected TemplateItem GetRandomAmmo(string rarity) { - var possibleAmmoPool = _dbAmmoItemsCache.Where(ammo => + var possibleAmmoPool = DbAmmoItemsCache.Where(ammo => { // Is ammo handbook price between desired range var handbookPrice = ragfairPriceService.GetStaticPriceForItem(ammo.Id); if ( - _scavCaseConfig.AmmoRewards.AmmoRewardValueRangeRub.TryGetValue(rarity, out var matchingAmmoRewardForRarity) + ScavCaseConfig.AmmoRewards.AmmoRewardValueRangeRub.TryGetValue(rarity, out var matchingAmmoRewardForRarity) && handbookPrice >= matchingAmmoRewardForRarity.Min && handbookPrice <= matchingAmmoRewardForRarity.Max ) @@ -398,22 +398,22 @@ public class ScavCaseRewardGenerator( { MinCount = scavCaseDetails.EndProducts.Common.Min, MaxCount = scavCaseDetails.EndProducts.Common.Max, - MinPriceRub = _scavCaseConfig.RewardItemValueRangeRub[RewardRarity.Common].Min, - MaxPriceRub = _scavCaseConfig.RewardItemValueRangeRub[RewardRarity.Common].Max, + MinPriceRub = ScavCaseConfig.RewardItemValueRangeRub[RewardRarity.Common].Min, + MaxPriceRub = ScavCaseConfig.RewardItemValueRangeRub[RewardRarity.Common].Max, }, Rare = new RewardCountAndPriceDetails { MinCount = scavCaseDetails.EndProducts.Rare.Min, MaxCount = scavCaseDetails.EndProducts.Rare.Max, - MinPriceRub = _scavCaseConfig.RewardItemValueRangeRub[RewardRarity.Rare].Min, - MaxPriceRub = _scavCaseConfig.RewardItemValueRangeRub[RewardRarity.Rare].Max, + MinPriceRub = ScavCaseConfig.RewardItemValueRangeRub[RewardRarity.Rare].Min, + MaxPriceRub = ScavCaseConfig.RewardItemValueRangeRub[RewardRarity.Rare].Max, }, Superrare = new RewardCountAndPriceDetails { MinCount = scavCaseDetails.EndProducts.Superrare.Min, MaxCount = scavCaseDetails.EndProducts.Superrare.Max, - MinPriceRub = _scavCaseConfig.RewardItemValueRangeRub[RewardRarity.SuperRare].Min, - MaxPriceRub = _scavCaseConfig.RewardItemValueRangeRub[RewardRarity.SuperRare].Max, + MinPriceRub = ScavCaseConfig.RewardItemValueRangeRub[RewardRarity.SuperRare].Min, + MaxPriceRub = ScavCaseConfig.RewardItemValueRangeRub[RewardRarity.SuperRare].Max, }, }; } @@ -449,7 +449,7 @@ public class ScavCaseRewardGenerator( /// value to set stack count to protected int GetRandomisedAmmoRewardStackSize(TemplateItem itemToCalculate) { - return randomUtil.GetInt(_scavCaseConfig.AmmoRewards.MinStackSize, itemToCalculate.Properties.StackMaxSize ?? 0); + return randomUtil.GetInt(ScavCaseConfig.AmmoRewards.MinStackSize, itemToCalculate.Properties.StackMaxSize ?? 0); } /// @@ -465,29 +465,29 @@ public class ScavCaseRewardGenerator( if (id == Money.ROUBLES) { return randomUtil.GetInt( - _scavCaseConfig.MoneyRewards.RubCount.GetByJsonProperty>(rarity).Min, - _scavCaseConfig.MoneyRewards.RubCount.GetByJsonProperty>(rarity).Max + ScavCaseConfig.MoneyRewards.RubCount.GetByJsonProperty>(rarity).Min, + ScavCaseConfig.MoneyRewards.RubCount.GetByJsonProperty>(rarity).Max ); } else if (id == Money.EUROS) { return randomUtil.GetInt( - _scavCaseConfig.MoneyRewards.EurCount.GetByJsonProperty>(rarity).Min, - _scavCaseConfig.MoneyRewards.EurCount.GetByJsonProperty>(rarity).Max + ScavCaseConfig.MoneyRewards.EurCount.GetByJsonProperty>(rarity).Min, + ScavCaseConfig.MoneyRewards.EurCount.GetByJsonProperty>(rarity).Max ); } else if (id == Money.DOLLARS) { return randomUtil.GetInt( - _scavCaseConfig.MoneyRewards.UsdCount.GetByJsonProperty>(rarity).Min, - _scavCaseConfig.MoneyRewards.UsdCount.GetByJsonProperty>(rarity).Max + ScavCaseConfig.MoneyRewards.UsdCount.GetByJsonProperty>(rarity).Min, + ScavCaseConfig.MoneyRewards.UsdCount.GetByJsonProperty>(rarity).Max ); } else if (id == Money.GP) { return randomUtil.GetInt( - _scavCaseConfig.MoneyRewards.GpCount.GetByJsonProperty>(rarity).Min, - _scavCaseConfig.MoneyRewards.GpCount.GetByJsonProperty>(rarity).Max + ScavCaseConfig.MoneyRewards.GpCount.GetByJsonProperty>(rarity).Min, + ScavCaseConfig.MoneyRewards.GpCount.GetByJsonProperty>(rarity).Max ); } else diff --git a/Libraries/SPTarkov.Server.Core/Generators/WeatherGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/WeatherGenerator.cs index ad811e6e..bc0cc347 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/WeatherGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/WeatherGenerator.cs @@ -20,7 +20,7 @@ public class WeatherGenerator( RandomUtil randomUtil ) { - protected readonly WeatherConfig _weatherConfig = configServer.GetConfig(); + protected readonly WeatherConfig WeatherConfig = configServer.GetConfig(); /// /// Get current + raid datetime and format into correct BSG format. @@ -34,7 +34,7 @@ public class WeatherGenerator( data.Date = formattedDate; data.Time = GetBsgFormattedInRaidTime(); - data.Acceleration = _weatherConfig.Acceleration; + data.Acceleration = WeatherConfig.Acceleration; data.Season = seasonalEventService.GetActiveWeatherSeason(); } @@ -90,10 +90,10 @@ public class WeatherGenerator( protected SeasonalValues GetWeatherValuesBySeason(Season currentSeason) { - var result = _weatherConfig.Weather.SeasonValues.TryGetValue(currentSeason.ToString(), out var value); + var result = WeatherConfig.Weather.SeasonValues.TryGetValue(currentSeason.ToString(), out var value); if (!result) { - return _weatherConfig.Weather.SeasonValues["default"]; + return WeatherConfig.Weather.SeasonValues["default"]; } return value!; diff --git a/Libraries/SPTarkov.Server.Core/Helpers/BotGeneratorHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/BotGeneratorHelper.cs index dc7e2ed6..b15e2a27 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/BotGeneratorHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/BotGeneratorHelper.cs @@ -39,7 +39,7 @@ public class BotGeneratorHelper( private static readonly FrozenSet _pmcTypes = [Sides.PmcBear.ToLowerInvariant(), Sides.PmcUsec.ToLowerInvariant()]; - private readonly BotConfig _botConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); /// /// Adds properties to an item @@ -56,7 +56,7 @@ public class BotGeneratorHelper( RandomisedResourceDetails? randomisationSettings = null; if (botRole is not null) { - _botConfig.LootItemResourceRandomization.TryGetValue(botRole, out randomisationSettings); + BotConfig.LootItemResourceRandomization.TryGetValue(botRole, out randomisationSettings); } Upd itemProperties = new(); @@ -188,7 +188,7 @@ public class BotGeneratorHelper( /// Equipment filter settings protected EquipmentFilters? GetBotEquipmentSettingFromConfig(string botRole) { - return _botConfig.Equipment.GetValueOrDefault(GetBotEquipmentRole(botRole)); + return BotConfig.Equipment.GetValueOrDefault(GetBotEquipmentRole(botRole)); } /// diff --git a/Libraries/SPTarkov.Server.Core/Helpers/BotHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/BotHelper.cs index 351abe29..a7f83dac 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/BotHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/BotHelper.cs @@ -23,8 +23,8 @@ public class BotHelper(ISptLogger logger, DatabaseService databaseSer Sides.PmcUsec.ToLowerInvariant(), ]; - private readonly BotConfig _botConfig = configServer.GetConfig(); - private readonly PmcConfig _pmcConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); private readonly ConcurrentDictionary> _pmcNameCache = new(); /// @@ -56,7 +56,7 @@ public class BotHelper(ISptLogger logger, DatabaseService databaseSer public bool IsBotBoss(string botRole) { - return !IsBotFollower(botRole) && _botConfig.Bosses.Any(x => string.Equals(x, botRole, StringComparison.CurrentCultureIgnoreCase)); + return !IsBotFollower(botRole) && BotConfig.Bosses.Any(x => string.Equals(x, botRole, StringComparison.CurrentCultureIgnoreCase)); } public bool IsBotFollower(string botRole) @@ -91,12 +91,12 @@ public class BotHelper(ISptLogger logger, DatabaseService databaseSer /// side (usec/bear) public string GetPmcSideByRole(string botRole) { - if (string.Equals(_pmcConfig.BearType, botRole, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(PMCConfig.BearType, botRole, StringComparison.OrdinalIgnoreCase)) { return Sides.Bear; } - if (string.Equals(_pmcConfig.UsecType, botRole, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(PMCConfig.UsecType, botRole, StringComparison.OrdinalIgnoreCase)) { return Sides.Usec; } @@ -128,7 +128,7 @@ public class BotHelper(ISptLogger logger, DatabaseService databaseSer /// pmc side as string protected string GetRandomizedPmcSide() { - return randomUtil.GetChance100(_pmcConfig.IsUsec) ? Sides.Usec : Sides.Bear; + return randomUtil.GetChance100(PMCConfig.IsUsec) ? Sides.Usec : Sides.Bear; } /// diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/Commando/SptCommandoCommands.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/Commando/SptCommandoCommands.cs index 02340df6..0e69643b 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/Commando/SptCommandoCommands.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/Commando/SptCommandoCommands.cs @@ -28,7 +28,7 @@ public class SptCommandoCommands : IChatCommand if ( !( coreConfigs.Features.ChatbotFeatures.CommandoFeatures.GiveCommandEnabled - && coreConfigs.Features.ChatbotFeatures.EnabledBots.ContainsKey(commandoId) + && coreConfigs.Features.ChatbotFeatures.EnabledBots.ContainsKey(commandoId.Value) ) ) { diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/CommandoDialogChatBot.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/CommandoDialogChatBot.cs index dfb2047b..95f20310 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/CommandoDialogChatBot.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/CommandoDialogChatBot.cs @@ -14,17 +14,17 @@ public class CommandoDialogChatBot( ISptLogger logger, MailSendService mailSendService, ServerLocalisationService localisationService, - ConfigServer _configServer, + ConfigServer configServer, IEnumerable chatCommands ) : AbstractDialogChatBot(logger, mailSendService, localisationService, chatCommands) { - protected readonly CoreConfig _coreConfig = _configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); public override UserDialogInfo GetChatBot() { return new UserDialogInfo { - Id = _coreConfig.Features.ChatbotFeatures.Ids["commando"], + Id = CoreConfig.Features.ChatbotFeatures.Ids["commando"], Aid = 1234566, Info = new UserDialogDetails { diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/ForceSnowMessageHandler.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/ForceSnowMessageHandler.cs index 672981e0..997b7e33 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/ForceSnowMessageHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/ForceSnowMessageHandler.cs @@ -12,32 +12,32 @@ namespace SPTarkov.Server.Core.Helpers.Dialogue.SPTFriend.Commands; [Injectable] public class ForceSnowMessageHandler( - ServerLocalisationService _serverLocalisationService, - MailSendService _mailSendService, - RandomUtil _randomUtil, - ConfigServer _configServer + ServerLocalisationService serverLocalisationService, + MailSendService mailSendService, + RandomUtil randomUtil, + ConfigServer configServer ) : IChatMessageHandler { - private readonly WeatherConfig _weatherConfig = _configServer.GetConfig(); + protected readonly WeatherConfig WeatherConfig = configServer.GetConfig(); public int GetPriority() { return 99; } - public bool CanHandle(string message) + public bool CanHandle(string? message) { return string.Equals(message, "itsonlysnowalan", StringComparison.OrdinalIgnoreCase); } public void Process(MongoId sessionId, UserDialogInfo sptFriendUser, PmcData? sender, object? extraInfo = null) { - _weatherConfig.OverrideSeason = Season.WINTER; + WeatherConfig.OverrideSeason = Season.WINTER; - _mailSendService.SendUserMessageToPlayer( + mailSendService.SendUserMessageToPlayer( sessionId, sptFriendUser, - _randomUtil.GetArrayValue([_serverLocalisationService.GetText("chatbot-snow_enabled")]), + randomUtil.GetArrayValue([serverLocalisationService.GetText("chatbot-snow_enabled")]), [], null ); diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/ForceSummerMessageHandler.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/ForceSummerMessageHandler.cs index 64f71d98..5ae45fcc 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/ForceSummerMessageHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/ForceSummerMessageHandler.cs @@ -12,32 +12,32 @@ namespace SPTarkov.Server.Core.Helpers.Dialogue.SPTFriend.Commands; [Injectable] public class ForceSummerMessageHandler( - ServerLocalisationService _serverLocalisationService, - MailSendService _mailSendService, - RandomUtil _randomUtil, - ConfigServer _configServer + ServerLocalisationService serverLocalisationService, + MailSendService mailSendService, + RandomUtil randomUtil, + ConfigServer configServer ) : IChatMessageHandler { - private readonly WeatherConfig _weatherConfig = _configServer.GetConfig(); + protected readonly WeatherConfig WeatherConfig = configServer.GetConfig(); public int GetPriority() { return 99; } - public bool CanHandle(string message) + public bool CanHandle(string? message) { return string.Equals(message, "givemesunshine", StringComparison.OrdinalIgnoreCase); } public void Process(MongoId sessionId, UserDialogInfo sptFriendUser, PmcData? sender, object? extraInfo = null) { - _weatherConfig.OverrideSeason = Season.SUMMER; + WeatherConfig.OverrideSeason = Season.SUMMER; - _mailSendService.SendUserMessageToPlayer( + mailSendService.SendUserMessageToPlayer( sessionId, sptFriendUser, - _randomUtil.GetArrayValue([_serverLocalisationService.GetText("chatbot-summer_enabled")]), + randomUtil.GetArrayValue([serverLocalisationService.GetText("chatbot-summer_enabled")]), [], null ); diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/GiveMeSpaceMessageHandler.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/GiveMeSpaceMessageHandler.cs index 1c3502d1..469eedb1 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/GiveMeSpaceMessageHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/GiveMeSpaceMessageHandler.cs @@ -20,14 +20,14 @@ public class GiveMeSpaceMessageHandler( ConfigServer configServer ) : IChatMessageHandler { - private readonly CoreConfig _coreConfig = configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); public int GetPriority() { return 100; } - public bool CanHandle(string message) + public bool CanHandle(string? message) { return string.Equals(message, "givemespace", StringComparison.OrdinalIgnoreCase); } @@ -35,7 +35,7 @@ public class GiveMeSpaceMessageHandler( public void Process(MongoId sessionId, UserDialogInfo sptFriendUser, PmcData? sender, object? extraInfo = null) { const string stashRowGiftId = "StashRows"; - var maxGiftsToSendCount = _coreConfig.Features.ChatbotFeatures.CommandUseLimits[stashRowGiftId] ?? 5; + var maxGiftsToSendCount = CoreConfig.Features.ChatbotFeatures.CommandUseLimits[stashRowGiftId] ?? 5; if (profileHelper.PlayerHasReceivedMaxNumberOfGift(sessionId, stashRowGiftId, maxGiftsToSendCount)) { mailSendService.SendUserMessageToPlayer( diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/SendGiftMessageHandler.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/SendGiftMessageHandler.cs index 8cceaabe..ae42e32c 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/SendGiftMessageHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/SendGiftMessageHandler.cs @@ -13,41 +13,41 @@ namespace SPTarkov.Server.Core.Helpers.Dialogue.SPTFriend.Commands; [Injectable] public class SendGiftMessageHandler( - MailSendService _mailSendService, - RandomUtil _randomUtil, - GiftService _giftService, - ConfigServer _configServer + MailSendService mailSendService, + RandomUtil randomUtil, + GiftService giftService, + ConfigServer configServer ) : IChatMessageHandler { - private readonly CoreConfig _coreConfig = _configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); public int GetPriority() { return 1; } - public bool CanHandle(string message) + public bool CanHandle(string? message) { - return _giftService.GiftExists(message); + return giftService.GiftExists(message); } public void Process(MongoId sessionId, UserDialogInfo sptFriendUser, PmcData? sender, object? extraInfo = null) { // Gifts may be disabled via config - if (!_coreConfig.Features.ChatbotFeatures.SptFriendGiftsEnabled) + if (!CoreConfig.Features.ChatbotFeatures.SptFriendGiftsEnabled) { return; } var messageTest = ((SendMessageRequest)extraInfo).Text; - var giftSent = _giftService.SendGiftToPlayer(sessionId, messageTest); + var giftSent = giftService.SendGiftToPlayer(sessionId, messageTest); switch (giftSent) { case GiftSentResult.SUCCESS: - _mailSendService.SendUserMessageToPlayer( + mailSendService.SendUserMessageToPlayer( sessionId, sptFriendUser, - _randomUtil.GetArrayValue( + randomUtil.GetArrayValue( [ "Hey! you got the right code!", "A secret code, how exciting!", @@ -62,10 +62,10 @@ public class SendGiftMessageHandler( return; case GiftSentResult.FAILED_GIFT_ALREADY_RECEIVED: - _mailSendService.SendUserMessageToPlayer( + mailSendService.SendUserMessageToPlayer( sessionId, sptFriendUser, - _randomUtil.GetArrayValue(["Looks like you already used that code", "You already have that!!"]), + randomUtil.GetArrayValue(["Looks like you already used that code", "You already have that!!"]), [], null ); diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SptDialogueChatBot.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SptDialogueChatBot.cs index 8d305f56..5a0fe4fe 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SptDialogueChatBot.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SptDialogueChatBot.cs @@ -12,27 +12,27 @@ namespace SPTarkov.Server.Core.Helpers.Dialogue; [Injectable] public class SptDialogueChatBot( - MailSendService _mailSendService, - ConfigServer _configServer, - ProfileHelper _profileHelper, + MailSendService mailSendService, + ConfigServer configServer, + ProfileHelper profileHelper, IEnumerable chatMessageHandlers ) : IDialogueChatBot { - protected readonly IEnumerable _chatMessageHandlers = ChatMessageHandlerSetup(chatMessageHandlers); - protected readonly CoreConfig _coreConfig = _configServer.GetConfig(); + protected readonly IEnumerable ChatMessageHandlers = ChatMessageHandlerSetup(chatMessageHandlers); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); public UserDialogInfo GetChatBot() { return new UserDialogInfo { - Id = _coreConfig.Features.ChatbotFeatures.Ids["spt"], + Id = CoreConfig.Features.ChatbotFeatures.Ids["spt"], Aid = 1234566, Info = new UserDialogDetails { Level = 1, MemberCategory = MemberCategory.Developer, SelectedMemberCategory = MemberCategory.Developer, - Nickname = _coreConfig.SptFriendNickname, + Nickname = CoreConfig.SptFriendNickname, Side = "Usec", }, }; @@ -40,7 +40,7 @@ public class SptDialogueChatBot( public ValueTask HandleMessage(MongoId sessionId, SendMessageRequest request) { - var sender = _profileHelper.GetPmcProfile(sessionId); + var sender = profileHelper.GetPmcProfile(sessionId); var sptFriendUser = GetChatBot(); if (string.Equals(request.Text, "help", StringComparison.OrdinalIgnoreCase)) @@ -48,7 +48,7 @@ public class SptDialogueChatBot( return SendPlayerHelpMessage(sessionId, request); } - var handler = _chatMessageHandlers.FirstOrDefault(h => h.CanHandle(request.Text)); + var handler = ChatMessageHandlers.FirstOrDefault(h => h.CanHandle(request.Text)); if (handler is not null) { handler.Process(sessionId, sptFriendUser, sender, request); @@ -56,7 +56,7 @@ public class SptDialogueChatBot( return new ValueTask(request.DialogId); } - _mailSendService.SendUserMessageToPlayer(sessionId, GetChatBot(), GetUnrecognizedCommandMessage(), [], null); + mailSendService.SendUserMessageToPlayer(sessionId, GetChatBot(), GetUnrecognizedCommandMessage(), [], null); return new ValueTask(request.DialogId); } @@ -76,7 +76,7 @@ public class SptDialogueChatBot( protected ValueTask SendPlayerHelpMessage(MongoId sessionId, SendMessageRequest request) { - _mailSendService.SendUserMessageToPlayer( + mailSendService.SendUserMessageToPlayer( sessionId, GetChatBot(), "The available commands are:\n GIVEMESPACE \n HOHOHO \n VERYSPOOKY \n ITSONLYSNOWALAN \n GIVEMESUNSHINE \n GARBAGE", diff --git a/Libraries/SPTarkov.Server.Core/Helpers/DurabilityLimitsHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/DurabilityLimitsHelper.cs index 83c8479c..3a985b1c 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/DurabilityLimitsHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/DurabilityLimitsHelper.cs @@ -16,7 +16,7 @@ public class DurabilityLimitsHelper( ConfigServer configServer ) { - private readonly BotConfig _botConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); /// /// Get max durability for a weapon based on bot role @@ -105,7 +105,7 @@ public class DurabilityLimitsHelper( return "zombie"; } - var roleExistsInConfig = _botConfig.Durability.BotDurabilities.ContainsKey(botRole); + var roleExistsInConfig = BotConfig.Durability.BotDurabilities.ContainsKey(botRole); if (roleExistsInConfig) { return botRole; @@ -140,8 +140,8 @@ public class DurabilityLimitsHelper( protected double GenerateMaxPmcArmorDurability(double itemMaxDurability) { - var lowestMaxPercent = _botConfig.Durability.Pmc.Armor.LowestMaxPercent; - var highestMaxPercent = _botConfig.Durability.Pmc.Armor.HighestMaxPercent; + var lowestMaxPercent = BotConfig.Durability.Pmc.Armor.LowestMaxPercent; + var highestMaxPercent = BotConfig.Durability.Pmc.Armor.HighestMaxPercent; var multiplier = randomUtil.GetDouble(lowestMaxPercent, highestMaxPercent); return itemMaxDurability * (multiplier / 100); @@ -153,12 +153,12 @@ public class DurabilityLimitsHelper( { case null: case "default": - return _botConfig.Durability.Default.Weapon.LowestMax; + return BotConfig.Durability.Default.Weapon.LowestMax; case "pmc": - return _botConfig.Durability.Pmc.Weapon.LowestMax; + return BotConfig.Durability.Pmc.Weapon.LowestMax; } - if (!_botConfig.Durability.BotDurabilities.TryGetValue(botRole, out var durability)) + if (!BotConfig.Durability.BotDurabilities.TryGetValue(botRole, out var durability)) { var message = $"Bot role {botRole} durability doesn't exist"; logger.Error(message); @@ -174,12 +174,12 @@ public class DurabilityLimitsHelper( { case null: case "default": - return _botConfig.Durability.Default.Weapon.HighestMax; + return BotConfig.Durability.Default.Weapon.HighestMax; case "pmc": - return _botConfig.Durability.Pmc.Weapon.HighestMax; + return BotConfig.Durability.Pmc.Weapon.HighestMax; } - if (!_botConfig.Durability.BotDurabilities.TryGetValue(botRole, out var durability)) + if (!BotConfig.Durability.BotDurabilities.TryGetValue(botRole, out var durability)) { var message = $"Bot role {botRole} durability doesn't exist"; logger.Error(message); @@ -217,15 +217,15 @@ public class DurabilityLimitsHelper( { if (botRole is null or "default") { - return _botConfig.Durability.Default.Weapon.MinDelta; + return BotConfig.Durability.Default.Weapon.MinDelta; } if (botRole == "pmc") { - return _botConfig.Durability.Pmc.Weapon.MinDelta; + return BotConfig.Durability.Pmc.Weapon.MinDelta; } - if (!_botConfig.Durability.BotDurabilities.TryGetValue(botRole, out var durability)) + if (!BotConfig.Durability.BotDurabilities.TryGetValue(botRole, out var durability)) { var message = $"Bot role {botRole} durability doesn't exist"; logger.Error(message); @@ -239,15 +239,15 @@ public class DurabilityLimitsHelper( { if (botRole is null or "default") { - return _botConfig.Durability.Default.Weapon.MaxDelta; + return BotConfig.Durability.Default.Weapon.MaxDelta; } if (botRole == "pmc") { - return _botConfig.Durability.Pmc.Weapon.MaxDelta; + return BotConfig.Durability.Pmc.Weapon.MaxDelta; } - if (!_botConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) + if (!BotConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) { var message = $"Bot role {botRole} durability doesn't exist"; logger.Error(message); @@ -261,15 +261,15 @@ public class DurabilityLimitsHelper( { if (botRole is null or "default") { - return _botConfig.Durability.Default.Armor.MinDelta; + return BotConfig.Durability.Default.Armor.MinDelta; } if (botRole == "pmc") { - return _botConfig.Durability.Pmc.Armor.MinDelta; + return BotConfig.Durability.Pmc.Armor.MinDelta; } - if (!_botConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) + if (!BotConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) { var message = $"Bot role {botRole} durability doesn't exist"; logger.Error(message); @@ -283,15 +283,15 @@ public class DurabilityLimitsHelper( { if (botRole is null or "default") { - return _botConfig.Durability.Default.Armor.MaxDelta; + return BotConfig.Durability.Default.Armor.MaxDelta; } if (botRole == "pmc") { - return _botConfig.Durability.Pmc.Armor.MaxDelta; + return BotConfig.Durability.Pmc.Armor.MaxDelta; } - if (!_botConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) + if (!BotConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) { var message = $"Bot role {botRole} durability doesn't exist"; logger.Error(message); @@ -305,15 +305,15 @@ public class DurabilityLimitsHelper( { if (botRole is null or "default") { - return _botConfig.Durability.Default.Armor.MinLimitPercent; + return BotConfig.Durability.Default.Armor.MinLimitPercent; } if (botRole == "pmc") { - return _botConfig.Durability.Pmc.Armor.MinLimitPercent; + return BotConfig.Durability.Pmc.Armor.MinLimitPercent; } - if (!_botConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) + if (!BotConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) { var message = $"Bot role {botRole} durability doesn't exist"; logger.Error(message); @@ -327,15 +327,15 @@ public class DurabilityLimitsHelper( { if (botRole is null or "default") { - return _botConfig.Durability.Default.Weapon.MinLimitPercent; + return BotConfig.Durability.Default.Weapon.MinLimitPercent; } if (botRole == "pmc") { - return _botConfig.Durability.Pmc.Weapon.MinLimitPercent; + return BotConfig.Durability.Pmc.Weapon.MinLimitPercent; } - if (!_botConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) + if (!BotConfig.Durability.BotDurabilities.TryGetValue(botRole, out var value)) { var message = $"Bot role {botRole} durability doesn't exist"; logger.Error(message); diff --git a/Libraries/SPTarkov.Server.Core/Helpers/InventoryHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/InventoryHelper.cs index 52e4488d..cc1083a2 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/InventoryHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/InventoryHelper.cs @@ -11,7 +11,6 @@ using SPTarkov.Server.Core.Models.Enums; using SPTarkov.Server.Core.Models.Spt.Config; using SPTarkov.Server.Core.Models.Spt.Inventory; using SPTarkov.Server.Core.Models.Utils; -using SPTarkov.Server.Core.Routers; using SPTarkov.Server.Core.Servers; using SPTarkov.Server.Core.Services; using SPTarkov.Server.Core.Utils; @@ -25,7 +24,6 @@ public class InventoryHelper( ISptLogger logger, HttpResponseUtil httpResponseUtil, DialogueHelper dialogueHelper, - EventOutputHolder eventOutputHolder, ProfileHelper profileHelper, ItemHelper itemHelper, ServerLocalisationService serverLocalisationService, @@ -35,7 +33,7 @@ public class InventoryHelper( { private static readonly FrozenSet _variableSizeItemTypes = [BaseClasses.WEAPON, BaseClasses.FUNCTIONAL_MOD, BaseClasses.MOD]; - protected readonly InventoryConfig _inventoryConfig = configServer.GetConfig(); + protected readonly InventoryConfig InventoryConfig = configServer.GetConfig(); /// /// Add multiple items to player stash (assuming they all fit) @@ -1153,7 +1151,7 @@ public class InventoryHelper( /// Reward details public RewardDetails? GetRandomLootContainerRewardDetails(MongoId itemTpl) { - _inventoryConfig.RandomLootContainers.TryGetValue(itemTpl, out var result); + InventoryConfig.RandomLootContainers.TryGetValue(itemTpl, out var result); return result; } @@ -1164,7 +1162,7 @@ public class InventoryHelper( /// Inventory configuration public InventoryConfig GetInventoryConfig() { - return _inventoryConfig; + return InventoryConfig; } public void ValidateInventoryUsesMongoIds(IEnumerable itemsToValidate) diff --git a/Libraries/SPTarkov.Server.Core/Helpers/QuestHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/QuestHelper.cs index 32b93627..6ff44f61 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/QuestHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/QuestHelper.cs @@ -24,7 +24,6 @@ namespace SPTarkov.Server.Core.Helpers; public class QuestHelper( ISptLogger logger, TimeUtil timeUtil, - ItemHelper itemHelper, DatabaseService databaseService, EventOutputHolder eventOutputHolder, LocaleService localeService, @@ -38,8 +37,8 @@ public class QuestHelper( ICloner cloner ) { - protected readonly FrozenSet _startedOrAvailToFinish = [QuestStatusEnum.Started, QuestStatusEnum.AvailableForFinish]; - protected readonly QuestConfig _questConfig = configServer.GetConfig(); + protected readonly FrozenSet StartedOrAvailToFinish = [QuestStatusEnum.Started, QuestStatusEnum.AvailableForFinish]; + protected readonly QuestConfig QuestConfig = configServer.GetConfig(); private Dictionary>? _sellToTraderQuestConditionCache; /// @@ -400,7 +399,7 @@ public class QuestHelper( } // Include if quest found in profile and is started or ready to hand in - return startedQuestInProfile is not null && _startedOrAvailToFinish.Contains(startedQuestInProfile.Status); + return startedQuestInProfile is not null && StartedOrAvailToFinish.Contains(startedQuestInProfile.Status); }); return GetQuestsWithOnlyLevelRequirementStartCondition(eligibleQuests).ToList(); @@ -429,7 +428,7 @@ public class QuestHelper( } // Should non-season event quests be shown to player - if (!_questConfig.ShowNonSeasonalEventQuests && seasonalEventService.IsQuestRelatedToEvent(questId, SeasonalEventType.None)) + if (!QuestConfig.ShowNonSeasonalEventQuests && seasonalEventService.IsQuestRelatedToEvent(questId, SeasonalEventType.None)) { return false; } @@ -446,13 +445,13 @@ public class QuestHelper( public bool QuestIsForOtherSide(string playerSide, MongoId questId) { var isUsec = string.Equals(playerSide, "usec", StringComparison.OrdinalIgnoreCase); - if (isUsec && _questConfig.BearOnlyQuests.Contains(questId)) + if (isUsec && QuestConfig.BearOnlyQuests.Contains(questId)) // Player is usec and quest is bear only, skip { return true; } - if (!isUsec && _questConfig.UsecOnlyQuests.Contains(questId)) + if (!isUsec && QuestConfig.UsecOnlyQuests.Contains(questId)) // Player is bear and quest is usec only, skip { return true; @@ -471,7 +470,7 @@ public class QuestHelper( /// True = Quest should not be visible to game version protected bool QuestIsProfileBlacklisted(string gameVersion, MongoId questId) { - var questBlacklist = _questConfig.ProfileBlacklist.GetValueOrDefault(gameVersion); + var questBlacklist = QuestConfig.ProfileBlacklist.GetValueOrDefault(gameVersion); if (questBlacklist is null) { // Not blacklisted @@ -490,7 +489,7 @@ public class QuestHelper( /// True = Quest should be visible to game version protected bool QuestIsProfileWhitelisted(string gameVersion, MongoId questId) { - var questBlacklist = _questConfig.ProfileBlacklist.GetValueOrDefault(gameVersion); + var questBlacklist = QuestConfig.ProfileBlacklist.GetValueOrDefault(gameVersion); if (questBlacklist is null) // Not blacklisted { @@ -1013,9 +1012,9 @@ public class QuestHelper( /// Hours item will be available for public double GetMailItemRedeemTimeHoursForProfile(PmcData pmcData) { - if (!_questConfig.MailRedeemTimeHours.TryGetValue(pmcData.Info.GameVersion, out var hours)) + if (!QuestConfig.MailRedeemTimeHours.TryGetValue(pmcData.Info.GameVersion, out var hours)) { - return _questConfig.MailRedeemTimeHours["default"]; + return QuestConfig.MailRedeemTimeHours["default"]; } return hours; diff --git a/Libraries/SPTarkov.Server.Core/Helpers/RagfairHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/RagfairHelper.cs index 0e6aba3e..70f353cb 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/RagfairHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/RagfairHelper.cs @@ -21,7 +21,7 @@ public class RagfairHelper( ICloner cloner ) { - protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); /// /// Gets currency TAG from currency tpl value @@ -102,7 +102,7 @@ public class RagfairHelper( var traders = databaseService.GetTraders(); return traders - .Keys.Where(traderId => _ragfairConfig.Traders.ContainsKey(traderId)) // Trader enabled in config + .Keys.Where(traderId => RagfairConfig.Traders.ContainsKey(traderId)) // Trader enabled in config .ToDictionary(traderId => traderId, traderId => traderAssortHelper.GetAssort(sessionId, traderId, showLockedAssorts)); } diff --git a/Libraries/SPTarkov.Server.Core/Helpers/RagfairOfferHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/RagfairOfferHelper.cs index e18aba73..2cb8d06a 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/RagfairOfferHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/RagfairOfferHelper.cs @@ -41,9 +41,9 @@ public class RagfairOfferHelper( ConfigServer configServer ) { - protected const string _goodSoldTemplate = "5bdabfb886f7743e152e867e 0"; // Your {soldItem} {itemCount} items were bought by {buyerNickname}. - protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected const string GoodSoldTemplate = "5bdabfb886f7743e152e867e 0"; // Your {soldItem} {itemCount} items were bought by {buyerNickname}. + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); /// /// Pass through to ragfairOfferService.getOffers(), get flea offers a player should see @@ -61,7 +61,7 @@ public class RagfairOfferHelper( ) { var playerIsFleaBanned = pmcData.PlayerIsFleaBanned(timeUtil.GetTimeStamp()); - var tieredFlea = _ragfairConfig.TieredFlea; + var tieredFlea = RagfairConfig.TieredFlea; var tieredFleaLimitTypes = tieredFlea.UnlocksType; return ragfairOfferService .GetOffers() @@ -175,7 +175,7 @@ public class RagfairOfferHelper( // Get all offers that require the desired item and filter out offers from non traders if player below ragfair unlock var offerIDsForItem = ragfairRequiredItemsService.GetRequiredOffersById(searchRequest.NeededSearchId.Value); - var tieredFlea = _ragfairConfig.TieredFlea; + var tieredFlea = RagfairConfig.TieredFlea; var tieredFleaLimitTypes = tieredFlea.UnlocksType; var tieredFleaKeys = tieredFleaLimitTypes.Keys.ToHashSet(); @@ -215,7 +215,7 @@ public class RagfairOfferHelper( var offersMap = new Dictionary>(); var offersToReturn = new List(); var playerIsFleaBanned = pmcData.PlayerIsFleaBanned(timeUtil.GetTimeStamp()); - var tieredFlea = _ragfairConfig.TieredFlea; + var tieredFlea = RagfairConfig.TieredFlea; var tieredFleaLimitTypes = tieredFlea.UnlocksType; foreach (var desiredItemTpl in searchRequest.BuildItems) @@ -810,9 +810,9 @@ public class RagfairOfferHelper( { // Generate a message to inform that item was sold var globalLocales = localeService.GetLocaleDb(); - if (!globalLocales.TryGetValue(_goodSoldTemplate, out var soldMessageLocaleGuid)) + if (!globalLocales.TryGetValue(GoodSoldTemplate, out var soldMessageLocaleGuid)) { - logger.Error(serverLocalisationService.GetText("ragfair-unable_to_find_locale_by_key", _goodSoldTemplate)); + logger.Error(serverLocalisationService.GetText("ragfair-unable_to_find_locale_by_key", GoodSoldTemplate)); } // Used to replace tokens in sold message sent to player @@ -822,7 +822,7 @@ public class RagfairOfferHelper( var tplVars = new SystemData { SoldItem = hasKey ? value : itemTpl, - BuyerNickname = botHelper.GetPmcNicknameOfMaxLength(_botConfig.BotNameLengthLimit), + BuyerNickname = botHelper.GetPmcNicknameOfMaxLength(BotConfig.BotNameLengthLimit), ItemCount = boughtAmount, }; diff --git a/Libraries/SPTarkov.Server.Core/Helpers/RagfairSellHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/RagfairSellHelper.cs index e270c795..7a276cb7 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/RagfairSellHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/RagfairSellHelper.cs @@ -19,7 +19,7 @@ public class RagfairSellHelper( ConfigServer configServer ) { - protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); /// /// Get the percent chance to sell an item based on its average listed price vs player chosen listing price @@ -30,7 +30,7 @@ public class RagfairSellHelper( /// percent value public double CalculateSellChance(double averageOfferPriceRub, double playerListedPriceRub, double qualityMultiplier) { - var sellConfig = _ragfairConfig.Sell.Chance; + var sellConfig = RagfairConfig.Sell.Chance; // Base sell chance modified by items quality var baseSellChancePercent = sellConfig.Base * qualityMultiplier; @@ -77,8 +77,8 @@ public class RagfairSellHelper( if (sellChancePercent is null) { - effectiveSellChance = _ragfairConfig.Sell.Chance.Base; - logger.Warning($"Sell chance was not a number: {sellChancePercent}, defaulting to {_ragfairConfig.Sell.Chance.Base}%"); + effectiveSellChance = RagfairConfig.Sell.Chance.Base; + logger.Warning($"Sell chance was not a number: {sellChancePercent}, defaulting to {RagfairConfig.Sell.Chance.Base}%"); } if (logger.IsLogEnabled(LogLevel.Debug)) @@ -100,8 +100,8 @@ public class RagfairSellHelper( // Passed roll check, item will be sold // Weight time to sell towards selling faster based on how cheap the item sold var weighting = (100 - effectiveSellChance) / 100; - var maximumTime = weighting * _ragfairConfig.Sell.Time.Max * 60d; - var minimumTime = _ragfairConfig.Sell.Time.Min * 60d; + var maximumTime = weighting * RagfairConfig.Sell.Time.Max * 60d; + var minimumTime = RagfairConfig.Sell.Time.Min * 60d; if (maximumTime < minimumTime) { maximumTime = minimumTime + 5; diff --git a/Libraries/SPTarkov.Server.Core/Helpers/RepairHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/RepairHelper.cs index bab40c9a..50ed9229 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/RepairHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/RepairHelper.cs @@ -1,9 +1,7 @@ using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Enums; -using SPTarkov.Server.Core.Models.Spt.Config; using SPTarkov.Server.Core.Models.Utils; -using SPTarkov.Server.Core.Servers; using SPTarkov.Server.Core.Services; using SPTarkov.Server.Core.Utils; using SPTarkov.Server.Core.Utils.Cloners; @@ -12,16 +10,8 @@ using LogLevel = SPTarkov.Server.Core.Models.Spt.Logging.LogLevel; namespace SPTarkov.Server.Core.Helpers; [Injectable] -public class RepairHelper( - ISptLogger logger, - RandomUtil randomUtil, - DatabaseService databaseService, - ConfigServer configServer, - ICloner cloner -) +public class RepairHelper(ISptLogger logger, RandomUtil randomUtil, DatabaseService databaseService, ICloner cloner) { - protected RepairConfig _repairConfig = configServer.GetConfig(); - /// /// Alter an items durability after a repair by trader/repair kit /// diff --git a/Libraries/SPTarkov.Server.Core/Helpers/TraderHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/TraderHelper.cs index d30233f0..42c34e28 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/TraderHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/TraderHelper.cs @@ -28,11 +28,11 @@ public class TraderHelper( ConfigServer configServer ) { - protected readonly FrozenSet _gameVersionsWithHigherBuyRestrictions = [GameEditions.EDGE_OF_DARKNESS, GameEditions.UNHEARD]; - protected readonly Dictionary _highestTraderPriceItems = new(); - protected readonly TraderConfig _traderConfig = configServer.GetConfig(); + protected readonly FrozenSet GameVersionsWithHigherBuyRestrictions = [GameEditions.EDGE_OF_DARKNESS, GameEditions.UNHEARD]; + protected readonly Dictionary HighestTraderPriceItems = new(); + protected readonly TraderConfig TraderConfig = configServer.GetConfig(); - protected Lock _highestPriceLock = new Lock(); + protected readonly Lock _highestPriceLock = new Lock(); /// /// Get a traders base data from its nickname, case insensitive @@ -354,22 +354,22 @@ public class TraderHelper( /// Time in seconds. public long? GetTraderUpdateSeconds(MongoId traderId) { - var traderDetails = _traderConfig.UpdateTime.FirstOrDefault(x => x.TraderId == traderId); + var traderDetails = TraderConfig.UpdateTime.FirstOrDefault(x => x.TraderId == traderId); if (traderDetails?.Seconds?.Min is null || traderDetails.Seconds?.Max is null) { logger.Warning( serverLocalisationService.GetText( "trader-missing_trader_details_using_default_refresh_time", - new { traderId, updateTime = _traderConfig.UpdateTimeDefault } + new { traderId, updateTime = TraderConfig.UpdateTimeDefault } ) ); - _traderConfig.UpdateTime.Add( + TraderConfig.UpdateTime.Add( new UpdateTime // create temporary entry to prevent logger spam { TraderId = traderId, - Seconds = new MinMax(_traderConfig.UpdateTimeDefault, _traderConfig.UpdateTimeDefault), + Seconds = new MinMax(TraderConfig.UpdateTimeDefault, TraderConfig.UpdateTimeDefault), } ); @@ -468,7 +468,7 @@ public class TraderHelper( /// buyRestrictionMax value public double GetAccountTypeAdjustedTraderPurchaseLimit(double buyRestrictionMax, string gameVersion) { - if (_gameVersionsWithHigherBuyRestrictions.Contains(gameVersion)) + if (GameVersionsWithHigherBuyRestrictions.Contains(gameVersion)) { return Math.Floor(buyRestrictionMax * 1.2); } @@ -485,7 +485,7 @@ public class TraderHelper( { lock (_highestPriceLock) { - if (!_highestTraderPriceItems.TryGetValue(tpl, out var highestPrice)) + if (!HighestTraderPriceItems.TryGetValue(tpl, out var highestPrice)) { highestPrice = 1d; // Default price var itemHandbookPrice = handbookHelper.GetTemplatePrice(tpl); @@ -510,7 +510,7 @@ public class TraderHelper( if (priceTraderBuysItemAt > highestPrice) { highestPrice = priceTraderBuysItemAt; - _highestTraderPriceItems[tpl] = highestPrice; + HighestTraderPriceItems[tpl] = highestPrice; } } } diff --git a/Libraries/SPTarkov.Server.Core/Helpers/WeatherHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/WeatherHelper.cs index 6034694f..b9304c29 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/WeatherHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/WeatherHelper.cs @@ -10,7 +10,7 @@ namespace SPTarkov.Server.Core.Helpers; [Injectable] public class WeatherHelper(ISptLogger logger, TimeUtil timeUtil, ConfigServer configServer) { - protected readonly WeatherConfig _weatherConfig = configServer.GetConfig(); + protected readonly WeatherConfig WeatherConfig = configServer.GetConfig(); /// /// Assumes current time @@ -35,7 +35,7 @@ public class WeatherHelper(ISptLogger logger, TimeUtil timeUtil, var currentTimestampSeconds = timestamp; var tarkovTime = timeUtil.GetUtcDateTimeFromTimeStamp( - (long)(russiaOffsetSeconds + currentTimestampSeconds * _weatherConfig.Acceleration) % twentyFourHoursSeconds + (long)(russiaOffsetSeconds + currentTimestampSeconds * WeatherConfig.Acceleration) % twentyFourHoursSeconds ); return tarkovTime; diff --git a/Libraries/SPTarkov.Server.Core/Models/Spt/Config/CoreConfig.cs b/Libraries/SPTarkov.Server.Core/Models/Spt/Config/CoreConfig.cs index 8e1596f4..615129be 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Spt/Config/CoreConfig.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Spt/Config/CoreConfig.cs @@ -235,7 +235,7 @@ public record ChatbotFeatures /// Human readable id to guid for each bot /// [JsonPropertyName("ids")] - public required Dictionary Ids { get; set; } + public required Dictionary Ids { get; set; } /// /// Bot Ids player is allowed to interact with diff --git a/Libraries/SPTarkov.Server.Core/Servers/RagfairServer.cs b/Libraries/SPTarkov.Server.Core/Servers/RagfairServer.cs index 0633e773..d5486169 100644 --- a/Libraries/SPTarkov.Server.Core/Servers/RagfairServer.cs +++ b/Libraries/SPTarkov.Server.Core/Servers/RagfairServer.cs @@ -25,7 +25,7 @@ public class RagfairServer( ICloner cloner ) { - protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); public void Load() { @@ -90,7 +90,7 @@ public class RagfairServer( /// List of traders public List GetUpdateableTraders() { - return _ragfairConfig.Traders.Keys.ToList(); + return RagfairConfig.Traders.Keys.ToList(); } public Dictionary GetAllActiveCategories( diff --git a/Libraries/SPTarkov.Server.Core/Services/AirdropService.cs b/Libraries/SPTarkov.Server.Core/Services/AirdropService.cs index 83743ef8..aaa19bdd 100644 --- a/Libraries/SPTarkov.Server.Core/Services/AirdropService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/AirdropService.cs @@ -26,11 +26,11 @@ public class AirdropService( ItemHelper itemHelper ) { - protected readonly AirdropConfig _airdropConfig = configServer.GetConfig(); + protected readonly AirdropConfig AirdropConfig = configServer.GetConfig(); public GetAirdropLootResponse GenerateCustomAirdropLoot(GetAirdropLootRequest request) { - if (_airdropConfig.CustomAirdropMapping.TryGetValue(request.ContainerId, out var customAirdropInformation)) + if (AirdropConfig.CustomAirdropMapping.TryGetValue(request.ContainerId, out var customAirdropInformation)) { // Found container id, generate specific loot return GenerateAirdropLoot(customAirdropInformation); @@ -195,7 +195,7 @@ public class AirdropService( /// airdrop type value protected SptAirdropTypeEnum ChooseAirdropType() { - var possibleAirdropTypes = _airdropConfig.AirdropTypeWeightings; + var possibleAirdropTypes = AirdropConfig.AirdropTypeWeightings; return weightedRandomHelper.GetWeightedValue(possibleAirdropTypes); } @@ -207,13 +207,13 @@ public class AirdropService( /// LootRequest protected AirdropLootRequest GetAirdropLootConfigByType(SptAirdropTypeEnum? airdropType) { - if (!_airdropConfig.Loot.TryGetValue(airdropType.ToString(), out var lootSettingsByType)) + if (!AirdropConfig.Loot.TryGetValue(airdropType.ToString(), out var lootSettingsByType)) { logger.Error(serverLocalisationService.GetText("location-unable_to_find_airdrop_drop_config_of_type", airdropType)); // TODO: Get Radar airdrop to work. Atm Radar will default to common supply drop (mixed) // Default to common - lootSettingsByType = _airdropConfig.Loot[nameof(AirdropTypeEnum.Common)]; + lootSettingsByType = AirdropConfig.Loot[nameof(AirdropTypeEnum.Common)]; } // Get all items that match the blacklisted types and fold into item blacklist diff --git a/Libraries/SPTarkov.Server.Core/Services/BackupService.cs b/Libraries/SPTarkov.Server.Core/Services/BackupService.cs index be512393..546d43ee 100644 --- a/Libraries/SPTarkov.Server.Core/Services/BackupService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/BackupService.cs @@ -12,10 +12,10 @@ namespace SPTarkov.Server.Core.Services; [Injectable(InjectionType.Singleton)] public class BackupService { - protected const string _profileDir = "./user/profiles"; + protected const string ProfileDir = "./user/profiles"; - protected readonly List _activeServerMods; - protected readonly BackupConfig _backupConfig; + protected readonly List ActiveServerMods; + protected readonly BackupConfig BackupConfig; // Runs Init() every x minutes protected Timer _backupIntervalTimer; @@ -41,8 +41,8 @@ public class BackupService FileUtil = fileUtil; LoadedMods = loadedMods; - _activeServerMods = GetActiveServerMods(); - _backupConfig = configServer.GetConfig(); + ActiveServerMods = GetActiveServerMods(); + BackupConfig = configServer.GetConfig(); } /// @@ -50,7 +50,7 @@ public class BackupService /// public async Task StartBackupSystem() { - if (!_backupConfig.BackupInterval.Enabled) + if (!BackupConfig.BackupInterval.Enabled) { // Not backing up at regular intervals, run once and exit await Init(); @@ -72,7 +72,7 @@ public class BackupService }, null, TimeSpan.Zero, - TimeSpan.FromMinutes(_backupConfig.BackupInterval.IntervalMinutes) + TimeSpan.FromMinutes(BackupConfig.BackupInterval.IntervalMinutes) ); } @@ -94,7 +94,7 @@ public class BackupService List currentProfilePaths; try { - currentProfilePaths = FileUtil.GetFiles(_profileDir); + currentProfilePaths = FileUtil.GetFiles(ProfileDir); } catch (Exception ex) { @@ -122,7 +122,7 @@ public class BackupService var profileFileName = FileUtil.GetFileNameAndExtension(profilePath); // Create absolute path to file - var relativeSourceFilePath = Path.Combine(_profileDir, profileFileName); + var relativeSourceFilePath = Path.Combine(ProfileDir, profileFileName); var absoluteDestinationFilePath = Path.Combine(targetDir, profileFileName); if (!FileUtil.CopyFile(relativeSourceFilePath, absoluteDestinationFilePath)) { @@ -131,7 +131,7 @@ public class BackupService } // Write a copy of active mods. - await FileUtil.WriteFileAsync(Path.Combine(targetDir, "activeMods.json"), JsonUtil.Serialize(_activeServerMods)); + await FileUtil.WriteFileAsync(Path.Combine(targetDir, "activeMods.json"), JsonUtil.Serialize(ActiveServerMods)); if (Logger.IsLogEnabled(LogLevel.Debug)) { @@ -153,7 +153,7 @@ public class BackupService /// True if enabled, false otherwise. protected bool IsEnabled() { - if (_backupConfig.Enabled) + if (BackupConfig.Enabled) { return true; } @@ -174,7 +174,7 @@ public class BackupService protected string GenerateBackupTargetDir() { var backupDate = GenerateBackupDate(); - return Path.GetFullPath($"{_backupConfig.Directory}/{backupDate}"); + return Path.GetFullPath($"{BackupConfig.Directory}/{backupDate}"); } /// @@ -193,12 +193,12 @@ public class BackupService /// protected void CleanBackups() { - var backupDir = _backupConfig.Directory; + var backupDir = BackupConfig.Directory; var backupPaths = GetBackupPaths(backupDir); // Filter out invalid backup paths by ensuring they contain a valid date. var backupPathsWithCreationDateTime = GetBackupPathsWithCreationTimestamp(backupPaths); - var excessCount = backupPathsWithCreationDateTime.Count - _backupConfig.MaxBackups; + var excessCount = backupPathsWithCreationDateTime.Count - BackupConfig.MaxBackups; if (excessCount > 0) { var excessBackupPaths = backupPaths.GetRange(0, excessCount); diff --git a/Libraries/SPTarkov.Server.Core/Services/BotEquipmentFilterService.cs b/Libraries/SPTarkov.Server.Core/Services/BotEquipmentFilterService.cs index 68f68aa8..db7e77a6 100644 --- a/Libraries/SPTarkov.Server.Core/Services/BotEquipmentFilterService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/BotEquipmentFilterService.cs @@ -20,8 +20,8 @@ public class BotEquipmentFilterService( ConfigServer configServer ) { - protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly Dictionary _botEquipmentConfig = configServer.GetConfig().Equipment; + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly Dictionary BotEquipmentConfig = configServer.GetConfig().Equipment; /// /// Filter a bots data to exclude equipment and cartridges defines in the botConfig @@ -41,7 +41,7 @@ public class BotEquipmentFilterService( var botWeightingAdjustmentsByPlayerLevel = GetBotWeightingAdjustmentsByPlayerLevel(botRole, pmcProfile?.Info?.Level ?? 1); RandomisationDetails? randomisationDetails = null; - if (_botEquipmentConfig.TryGetValue(botRole.ToLowerInvariant(), out var botEquipmentConfig)) + if (BotEquipmentConfig.TryGetValue(botRole.ToLowerInvariant(), out var botEquipmentConfig)) { randomisationDetails = botHelper.GetBotRandomizationDetails(botLevel, botEquipmentConfig); } @@ -124,7 +124,7 @@ public class BotEquipmentFilterService( /// EquipmentFilters object public EquipmentFilters GetBotEquipmentSettings(string botEquipmentRole) { - return _botEquipmentConfig[botEquipmentRole]; + return BotEquipmentConfig[botEquipmentRole]; } /// @@ -134,7 +134,7 @@ public class BotEquipmentFilterService( /// Dictionary of weapon type and their whitelisted scope types public Dictionary>? GetBotWeaponSightWhitelist(string botEquipmentRole) { - return _botConfig.Equipment.TryGetValue(botEquipmentRole, out var botEquipmentSettings) + return BotConfig.Equipment.TryGetValue(botEquipmentRole, out var botEquipmentSettings) ? botEquipmentSettings.WeaponSightWhitelist : null; } @@ -147,7 +147,7 @@ public class BotEquipmentFilterService( /// EquipmentBlacklistDetails object public EquipmentFilterDetails? GetBotEquipmentBlacklist(string botRole, double playerLevel) { - var blacklistDetailsForBot = _botEquipmentConfig.GetValueOrDefault(botRole, null); + var blacklistDetailsForBot = BotEquipmentConfig.GetValueOrDefault(botRole, null); return (blacklistDetailsForBot?.Blacklist ?? []).FirstOrDefault(equipmentFilter => playerLevel >= equipmentFilter.LevelRange.Min && playerLevel <= equipmentFilter.LevelRange.Max @@ -162,7 +162,7 @@ public class BotEquipmentFilterService( /// EquipmentFilterDetails object protected EquipmentFilterDetails? GetBotEquipmentWhitelist(string botRole, int playerLevel) { - var whitelistDetailsForBot = _botEquipmentConfig.GetValueOrDefault(botRole, null); + var whitelistDetailsForBot = BotEquipmentConfig.GetValueOrDefault(botRole, null); return (whitelistDetailsForBot?.Whitelist ?? []).FirstOrDefault(equipmentFilter => playerLevel >= equipmentFilter.LevelRange.Min && playerLevel <= equipmentFilter.LevelRange.Max @@ -177,7 +177,7 @@ public class BotEquipmentFilterService( /// Weighting adjustments for bot items protected WeightingAdjustmentDetails? GetBotWeightingAdjustments(string botRole, int botLevel) { - var weightingDetailsForBot = _botEquipmentConfig.GetValueOrDefault(botRole, null); + var weightingDetailsForBot = BotEquipmentConfig.GetValueOrDefault(botRole, null); return (weightingDetailsForBot?.WeightingAdjustmentsByBotLevel ?? []).FirstOrDefault(x => botLevel >= x.LevelRange.Min && botLevel <= x.LevelRange.Max @@ -192,7 +192,7 @@ public class BotEquipmentFilterService( /// Weighting adjustments for bot items protected WeightingAdjustmentDetails? GetBotWeightingAdjustmentsByPlayerLevel(string botRole, int playerLevel) { - var weightingDetailsForBot = _botEquipmentConfig.GetValueOrDefault(botRole, null); + var weightingDetailsForBot = BotEquipmentConfig.GetValueOrDefault(botRole, null); return (weightingDetailsForBot?.WeightingAdjustmentsByBotLevel ?? []).FirstOrDefault(x => playerLevel >= x.LevelRange.Min && playerLevel <= x.LevelRange.Max diff --git a/Libraries/SPTarkov.Server.Core/Services/BotNameService.cs b/Libraries/SPTarkov.Server.Core/Services/BotNameService.cs index f1e6129a..12636aff 100644 --- a/Libraries/SPTarkov.Server.Core/Services/BotNameService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/BotNameService.cs @@ -20,18 +20,18 @@ public class BotNameService( ConfigServer configServer ) { - protected readonly Lock _lockObject = new(); - protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly HashSet _usedNameCache = []; + protected readonly Lock LockObject = new(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly HashSet UsedNameCache = []; /// /// Clear out generated pmc names from cache /// public void ClearNameCache() { - lock (_lockObject) + lock (LockObject) { - _usedNameCache.Clear(); + UsedNameCache.Clear(); } } @@ -53,7 +53,7 @@ public class BotNameService( var isPmc = botGenerationDetails.IsPmc; // Never show for players - var showTypeInNickname = !botGenerationDetails.IsPlayerScav && _botConfig.ShowTypeInNickname; + var showTypeInNickname = !botGenerationDetails.IsPlayerScav && BotConfig.ShowTypeInNickname; var roleShouldBeUnique = uniqueRoles?.Contains(botRole.ToLowerInvariant()); var attempts = 0; @@ -61,7 +61,7 @@ public class BotNameService( { // Get bot name with leading/trailing whitespace removed var name = isPmc // Explicit handling of PMCs, all other bots will get "first_name last_name" - ? botHelper.GetPmcNicknameOfMaxLength(_botConfig.BotNameLengthLimit, botGenerationDetails.Side) + ? botHelper.GetPmcNicknameOfMaxLength(BotConfig.BotNameLengthLimit, botGenerationDetails.Side) : $"{randomUtil.GetArrayValue(botJsonTemplate.FirstNames)} {(botJsonTemplate.LastNames.Any() ? randomUtil.GetArrayValue(botJsonTemplate.LastNames) : "")}"; name = name.Trim(); @@ -119,17 +119,17 @@ public class BotNameService( private bool AddNameToCache(string name) { - lock (_lockObject) + lock (LockObject) { - return _usedNameCache.Add(name); + return UsedNameCache.Add(name); } } protected bool CacheContainsName(string name) { - lock (_lockObject) + lock (LockObject) { - return _usedNameCache.Contains(name); + return UsedNameCache.Contains(name); } } diff --git a/Libraries/SPTarkov.Server.Core/Services/BotWeaponModLimitService.cs b/Libraries/SPTarkov.Server.Core/Services/BotWeaponModLimitService.cs index 063badf7..84ce5664 100644 --- a/Libraries/SPTarkov.Server.Core/Services/BotWeaponModLimitService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/BotWeaponModLimitService.cs @@ -13,7 +13,7 @@ namespace SPTarkov.Server.Core.Services; [Injectable(InjectionType.Singleton)] public class BotWeaponModLimitService(ISptLogger logger, ConfigServer configServer, ItemHelper itemHelper) { - protected readonly BotConfig _botConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); /// /// Initalise mod limits to be used when generating a weapon @@ -25,7 +25,7 @@ public class BotWeaponModLimitService(ISptLogger logge return new BotModLimits { Scope = new ItemCount { Count = 0 }, - ScopeMax = _botConfig.Equipment[botRole]?.WeaponModLimits?.ScopeLimit, + ScopeMax = BotConfig.Equipment[botRole]?.WeaponModLimits?.ScopeLimit, ScopeBaseTypes = [ BaseClasses.OPTIC_SCOPE, @@ -35,7 +35,7 @@ public class BotWeaponModLimitService(ISptLogger logge BaseClasses.SPECIAL_SCOPE, ], FlashlightLaser = new ItemCount { Count = 0 }, - FlashlightLaserMax = _botConfig.Equipment[botRole]?.WeaponModLimits?.LightLaserLimit, + FlashlightLaserMax = BotConfig.Equipment[botRole]?.WeaponModLimits?.LightLaserLimit, FlashlightLaserBaseTypes = [BaseClasses.TACTICAL_COMBO, BaseClasses.FLASHLIGHT, BaseClasses.PORTABLE_RANGE_FINDER], }; } diff --git a/Libraries/SPTarkov.Server.Core/Services/BtrDeliveryService.cs b/Libraries/SPTarkov.Server.Core/Services/BtrDeliveryService.cs index 48e6a814..55f1fc59 100644 --- a/Libraries/SPTarkov.Server.Core/Services/BtrDeliveryService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/BtrDeliveryService.cs @@ -24,8 +24,8 @@ public class BtrDeliveryService( ServerLocalisationService serverLocalisationService ) { - protected readonly BtrDeliveryConfig _btrDeliveryConfig = configServer.GetConfig(); - protected readonly TraderConfig _traderConfig = configServer.GetConfig(); + protected readonly BtrDeliveryConfig BtrDeliveryConfig = configServer.GetConfig(); + protected readonly TraderConfig TraderConfig = configServer.GetConfig(); protected static readonly List _transferTypes = ["btr", "transit"]; @@ -104,7 +104,7 @@ public class BtrDeliveryService( } var messageId = randomUtil.GetArrayValue(itemsDelivered); - var messageStoreTime = timeUtil.GetHoursAsSeconds(_traderConfig.Fence.BtrDeliveryExpireHours); + var messageStoreTime = timeUtil.GetHoursAsSeconds(TraderConfig.Fence.BtrDeliveryExpireHours); // Send the items to the player mailSendService.SendLocalisedNpcMessageToPlayer( @@ -140,14 +140,14 @@ public class BtrDeliveryService( protected double GetBTRDeliveryReturnTimestamp() { // If override in config is non-zero, use that - if (_btrDeliveryConfig.ReturnTimeOverrideSeconds > 0) + if (BtrDeliveryConfig.ReturnTimeOverrideSeconds > 0) { if (logger.IsLogEnabled(LogLevel.Debug)) { - logger.Debug($"BTR delivery override used: returning in {_btrDeliveryConfig.ReturnTimeOverrideSeconds} seconds"); + logger.Debug($"BTR delivery override used: returning in {BtrDeliveryConfig.ReturnTimeOverrideSeconds} seconds"); } - return timeUtil.GetTimeStamp() + _btrDeliveryConfig.ReturnTimeOverrideSeconds; + return timeUtil.GetTimeStamp() + BtrDeliveryConfig.ReturnTimeOverrideSeconds; } return timeUtil.GetTimeStamp(); diff --git a/Libraries/SPTarkov.Server.Core/Services/CircleOfCultistService.cs b/Libraries/SPTarkov.Server.Core/Services/CircleOfCultistService.cs index e49b0697..6ce97fd9 100644 --- a/Libraries/SPTarkov.Server.Core/Services/CircleOfCultistService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/CircleOfCultistService.cs @@ -44,7 +44,7 @@ public class CircleOfCultistService( ) { protected const string CircleOfCultistSlotId = "CircleOfCultistsGrid1"; - protected readonly HideoutConfig _hideoutConfig = configServer.GetConfig(); + protected readonly HideoutConfig HideoutConfig = configServer.GetConfig(); /// /// Start a sacrifice event @@ -78,18 +78,18 @@ public class CircleOfCultistService( var sacrificedItems = GetSacrificedItems(pmcData); var sacrificedItemCostRoubles = sacrificedItems.Aggregate(0D, (sum, curr) => sum + (itemHelper.GetItemPrice(curr.Template) ?? 0)); - var rewardAmountMultiplier = GetRewardAmountMultiplier(pmcData, _hideoutConfig.CultistCircle); + var rewardAmountMultiplier = GetRewardAmountMultiplier(pmcData, HideoutConfig.CultistCircle); // Get the rouble amount we generate rewards with from cost of sacrificed items * above multiplier var rewardAmountRoubles = Math.Round(sacrificedItemCostRoubles * rewardAmountMultiplier); // Check if it matches any direct swap recipes - var directRewardsCache = GenerateSacrificedItemsCache(_hideoutConfig.CultistCircle.DirectRewards); + var directRewardsCache = GenerateSacrificedItemsCache(HideoutConfig.CultistCircle.DirectRewards); var directRewardSettings = CheckForDirectReward(sessionId, sacrificedItems, directRewardsCache); var hasDirectReward = directRewardSettings?.Reward.Count > 0; // Get craft time and bonus status - var craftingInfo = GetCircleCraftingInfo(rewardAmountRoubles, _hideoutConfig.CultistCircle, directRewardSettings); + var craftingInfo = GetCircleCraftingInfo(rewardAmountRoubles, HideoutConfig.CultistCircle, directRewardSettings); // Create production in pmc profile RegisterCircleOfCultistProduction(sessionId, pmcData, cultistCraftData.Id, sacrificedItems, craftingInfo.Time); @@ -106,10 +106,10 @@ public class CircleOfCultistService( var rewards = hasDirectReward ? GetDirectRewards(sessionId, directRewardSettings, cultistCircleStashId.Value) : GetRewardsWithinBudget( - GetCultistCircleRewardPool(sessionId, pmcData, craftingInfo, _hideoutConfig.CultistCircle), + GetCultistCircleRewardPool(sessionId, pmcData, craftingInfo, HideoutConfig.CultistCircle), rewardAmountRoubles, cultistCircleStashId.Value, - _hideoutConfig.CultistCircle + HideoutConfig.CultistCircle ); // Get the container grid for cultist stash area @@ -532,7 +532,7 @@ public class CircleOfCultistService( } // Look for parent in dict - var settings = _hideoutConfig.CultistCircle.DirectRewardStackSize.GetValueOrDefault(itemDetails.Value.Parent); + var settings = HideoutConfig.CultistCircle.DirectRewardStackSize.GetValueOrDefault(itemDetails.Value.Parent); if (settings is null) { return 1; @@ -577,7 +577,7 @@ public class CircleOfCultistService( if (itemHelper.IsOfBaseclass(itemTpl, BaseClasses.MONEY)) { // Get currency-specific values from config - var settings = _hideoutConfig.CultistCircle.CurrencyRewards[itemTpl]; + var settings = HideoutConfig.CultistCircle.CurrencyRewards[itemTpl]; // What % of the pool remaining should be rewarded as chosen currency var percentOfPoolToUse = randomUtil.GetDouble(settings.Min, settings.Max); @@ -787,7 +787,7 @@ public class CircleOfCultistService( var currentItemCount = 0; var attempts = 0; // `currentItemCount` var will look for the correct number of items, `attempts` var will keep this from never stopping if the highValueThreshold is too high - while (currentItemCount < _hideoutConfig.CultistCircle.MaxRewardItemCount + 2 && attempts < allItems.Count) + while (currentItemCount < HideoutConfig.CultistCircle.MaxRewardItemCount + 2 && attempts < allItems.Count) { attempts++; var randomItem = randomUtil.GetArrayValue(allItems); @@ -800,7 +800,7 @@ public class CircleOfCultistService( if (itemsShouldBeHighValue) { var itemValue = itemHelper.GetItemMaxPrice(randomItem.Key); - if (itemValue < _hideoutConfig.CultistCircle.HighValueThresholdRub) + if (itemValue < HideoutConfig.CultistCircle.HighValueThresholdRub) { continue; } diff --git a/Libraries/SPTarkov.Server.Core/Services/CustomLocationWaveService.cs b/Libraries/SPTarkov.Server.Core/Services/CustomLocationWaveService.cs index f6e91bf2..b9daa0bb 100644 --- a/Libraries/SPTarkov.Server.Core/Services/CustomLocationWaveService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/CustomLocationWaveService.cs @@ -14,7 +14,7 @@ public class CustomLocationWaveService( ConfigServer configServer ) { - protected readonly LocationConfig _locationConfig = configServer.GetConfig(); + protected readonly LocationConfig LocationConfig = configServer.GetConfig(); /// /// Add a boss wave to a map @@ -23,7 +23,7 @@ public class CustomLocationWaveService( /// Boss wave to add to map public void AddBossWaveToMap(string locationId, BossLocationSpawn waveToAdd) { - _locationConfig.CustomWaves.Boss[locationId].Add(waveToAdd); + LocationConfig.CustomWaves.Boss[locationId].Add(waveToAdd); } /// @@ -33,7 +33,7 @@ public class CustomLocationWaveService( /// Wave to add to map public void AddNormalWaveToMap(string locationId, Wave waveToAdd) { - _locationConfig.CustomWaves.Normal[locationId].Add(waveToAdd); + LocationConfig.CustomWaves.Normal[locationId].Add(waveToAdd); } /// @@ -42,7 +42,7 @@ public class CustomLocationWaveService( /// e.g. factory4_day, bigmap public void ClearBossWavesForMap(string locationId) { - _locationConfig.CustomWaves.Boss[locationId] = []; + LocationConfig.CustomWaves.Boss[locationId] = []; } /// @@ -51,7 +51,7 @@ public class CustomLocationWaveService( /// e.g. factory4_day, bigmap public void ClearNormalWavesForMap(string locationId) { - _locationConfig.CustomWaves.Normal[locationId] = []; + LocationConfig.CustomWaves.Normal[locationId] = []; } /// @@ -59,8 +59,8 @@ public class CustomLocationWaveService( /// public void ApplyWaveChangesToAllMaps() { - var bossWavesToApply = _locationConfig.CustomWaves.Boss; - var normalWavesToApply = _locationConfig.CustomWaves.Normal; + var bossWavesToApply = LocationConfig.CustomWaves.Boss; + var normalWavesToApply = LocationConfig.CustomWaves.Normal; foreach (var mapKvP in bossWavesToApply) { diff --git a/Libraries/SPTarkov.Server.Core/Services/GiftService.cs b/Libraries/SPTarkov.Server.Core/Services/GiftService.cs index fb37a971..cf2474b9 100644 --- a/Libraries/SPTarkov.Server.Core/Services/GiftService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/GiftService.cs @@ -22,7 +22,7 @@ public class GiftService( ConfigServer configServer ) { - protected readonly GiftsConfig _giftConfig = configServer.GetConfig(); + protected readonly GiftsConfig GiftConfig = configServer.GetConfig(); /// /// Does a gift with a specific ID exist in db @@ -31,12 +31,12 @@ public class GiftService( /// True if it exists in db public bool GiftExists(string giftId) { - return _giftConfig.Gifts.ContainsKey(giftId); + return GiftConfig.Gifts.ContainsKey(giftId); } public Gift? GetGiftById(string giftId) { - _giftConfig.Gifts.TryGetValue(giftId, out var gift); + GiftConfig.Gifts.TryGetValue(giftId, out var gift); return gift; } @@ -47,7 +47,7 @@ public class GiftService( /// Dict keyed by gift id public Dictionary GetGifts() { - return _giftConfig.Gifts; + return GiftConfig.Gifts; } /// @@ -56,7 +56,7 @@ public class GiftService( /// String list of gift ids public IEnumerable GetGiftIds() { - return _giftConfig.Gifts.Keys; + return GiftConfig.Gifts.Keys; } /// diff --git a/Libraries/SPTarkov.Server.Core/Services/InsuranceService.cs b/Libraries/SPTarkov.Server.Core/Services/InsuranceService.cs index e7169a78..920a663b 100644 --- a/Libraries/SPTarkov.Server.Core/Services/InsuranceService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/InsuranceService.cs @@ -30,8 +30,8 @@ public class InsuranceService( ConfigServer configServer ) { - protected readonly InsuranceConfig _insuranceConfig = configServer.GetConfig(); - protected readonly Dictionary>?> _insured = new(); + protected readonly InsuranceConfig InsuranceConfig = configServer.GetConfig(); + protected readonly Dictionary>?> Insured = new(); /// /// Does player have insurance dictionary exists @@ -40,7 +40,7 @@ public class InsuranceService( /// True if exists public bool InsuranceDictionaryExists(MongoId sessionId) { - return _insured.TryGetValue(sessionId, out _); + return Insured.TryGetValue(sessionId, out _); } /// @@ -50,14 +50,14 @@ public class InsuranceService( /// Item list public Dictionary>? GetInsurance(MongoId sessionId) { - return _insured[sessionId]; + return Insured[sessionId]; } public void ResetInsurance(MongoId sessionId) { - if (!_insured.TryAdd(sessionId, new Dictionary>())) + if (!Insured.TryAdd(sessionId, new Dictionary>())) { - _insured[sessionId] = new Dictionary>(); + Insured[sessionId] = new Dictionary>(); } } @@ -139,14 +139,14 @@ public class InsuranceService( protected double GetInsuranceReturnTimestamp(PmcData pmcData, TraderBase trader) { // If override in config is non-zero, use that instead of trader values - if (_insuranceConfig.ReturnTimeOverrideSeconds > 0) + if (InsuranceConfig.ReturnTimeOverrideSeconds > 0) { if (logger.IsLogEnabled(LogLevel.Debug)) { - logger.Debug($"Insurance override used: returning in {_insuranceConfig.ReturnTimeOverrideSeconds} seconds"); + logger.Debug($"Insurance override used: returning in {InsuranceConfig.ReturnTimeOverrideSeconds} seconds"); } - return timeUtil.GetTimeStamp() + _insuranceConfig.ReturnTimeOverrideSeconds; + return timeUtil.GetTimeStamp() + InsuranceConfig.ReturnTimeOverrideSeconds; } var insuranceReturnTimeBonusSum = pmcData.GetBonusValueFromProfile(BonusType.InsuranceReturnTime); @@ -180,10 +180,10 @@ public class InsuranceService( protected double GetMaxInsuranceStorageTime(TraderBase traderBase) { - if (_insuranceConfig.StorageTimeOverrideSeconds > 0) + if (InsuranceConfig.StorageTimeOverrideSeconds > 0) // Override exists, use instead of traders value { - return _insuranceConfig.StorageTimeOverrideSeconds; + return InsuranceConfig.StorageTimeOverrideSeconds; } return timeUtil.GetHoursAsSeconds((int)traderBase.Insurance.MaxStorageTime); @@ -303,7 +303,7 @@ public class InsuranceService( /// True if exists protected bool InsuranceTraderArrayExists(MongoId sessionId, MongoId traderId) { - return _insured[sessionId].GetValueOrDefault(traderId) is not null; + return Insured[sessionId].GetValueOrDefault(traderId) is not null; } /// @@ -313,7 +313,7 @@ public class InsuranceService( /// Trader items insured with public void ResetInsuranceTraderArray(MongoId sessionId, MongoId traderId) { - _insured[sessionId][traderId] = []; + Insured[sessionId][traderId] = []; } /// @@ -324,7 +324,7 @@ public class InsuranceService( /// Insured item (with children) public void AddInsuranceItemToArray(MongoId sessionId, MongoId traderId, Item itemToAdd) { - _insured[sessionId][traderId].Add(itemToAdd); + Insured[sessionId][traderId].Add(itemToAdd); } /// diff --git a/Libraries/SPTarkov.Server.Core/Services/ItemFilterService.cs b/Libraries/SPTarkov.Server.Core/Services/ItemFilterService.cs index b170b128..975a7586 100644 --- a/Libraries/SPTarkov.Server.Core/Services/ItemFilterService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/ItemFilterService.cs @@ -12,10 +12,10 @@ namespace SPTarkov.Server.Core.Services; [Injectable(InjectionType.Singleton)] public class ItemFilterService(ISptLogger logger, ConfigServer configServer) { - protected readonly ItemConfig _itemConfig = configServer.GetConfig(); + protected readonly ItemConfig ItemConfig = configServer.GetConfig(); - protected readonly HashSet _itemBlacklistCache = []; - protected readonly HashSet _lootableItemBlacklistCache = []; + protected readonly HashSet ItemBlacklistCache = []; + protected readonly HashSet LootableItemBlacklistCache = []; /// /// Get an HashSet of items that should never be given as a reward to player @@ -23,7 +23,7 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// HashSet of item tpls public HashSet GetItemRewardBlacklist() { - return _itemConfig.RewardItemBlacklist; + return ItemConfig.RewardItemBlacklist; } /// @@ -32,7 +32,7 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// HashSet of item base ids public HashSet GetItemRewardBaseTypeBlacklist() { - return _itemConfig.RewardItemTypeBlacklist; + return ItemConfig.RewardItemTypeBlacklist; } /// @@ -41,7 +41,7 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// HashSet of blacklisted template ids public HashSet GetBlacklistedItems() { - return _itemConfig.Blacklist; + return ItemConfig.Blacklist; } /// @@ -50,7 +50,7 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// HashSet of blacklisted template ids public HashSet GetBlacklistedLootableItems() { - return _itemConfig.LootableItemBlacklist; + return ItemConfig.LootableItemBlacklist; } /// @@ -59,7 +59,7 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// HashSet of boss item template ids public HashSet GetBossItems() { - return _itemConfig.BossItems; + return ItemConfig.BossItems; } /// @@ -68,7 +68,7 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// Tpls to blacklist public void AddItemToLootableBlacklistCache(IEnumerable itemTplsToBlacklist) { - _lootableItemBlacklistCache.UnionWith(itemTplsToBlacklist); + LootableItemBlacklistCache.UnionWith(itemTplsToBlacklist); } /// @@ -78,12 +78,12 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// True if blacklisted public bool IsLootableItemBlacklisted(MongoId itemKey) { - if (!_lootableItemBlacklistCache.Any()) + if (!LootableItemBlacklistCache.Any()) { - _lootableItemBlacklistCache.UnionWith(_itemConfig.LootableItemBlacklist); + LootableItemBlacklistCache.UnionWith(ItemConfig.LootableItemBlacklist); } - return _lootableItemBlacklistCache.Contains(itemKey); + return LootableItemBlacklistCache.Contains(itemKey); } /// @@ -92,17 +92,17 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// Tpls to blacklist public void AddItemToBlacklistCache(IEnumerable itemTplsToBlacklist) { - _itemBlacklistCache.UnionWith(itemTplsToBlacklist); + ItemBlacklistCache.UnionWith(itemTplsToBlacklist); } public bool IsItemBlacklisted(MongoId tpl) { - if (!_itemBlacklistCache.Any()) + if (!ItemBlacklistCache.Any()) { - _itemBlacklistCache.UnionWith(_itemConfig.Blacklist); + ItemBlacklistCache.UnionWith(ItemConfig.Blacklist); } - return _itemBlacklistCache.Contains(tpl); + return ItemBlacklistCache.Contains(tpl); } /// @@ -112,7 +112,7 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// True if boss item public bool IsBossItem(MongoId tpl) { - return _itemConfig.BossItems.Contains(tpl); + return ItemConfig.BossItems.Contains(tpl); } /// @@ -122,6 +122,6 @@ public class ItemFilterService(ISptLogger logger, ConfigServe /// true when blacklisted public bool IsItemRewardBlacklisted(MongoId tpl) { - return _itemConfig.RewardItemBlacklist.Contains(tpl); + return ItemConfig.RewardItemBlacklist.Contains(tpl); } } diff --git a/Libraries/SPTarkov.Server.Core/Services/LocaleService.cs b/Libraries/SPTarkov.Server.Core/Services/LocaleService.cs index 91eba8c1..add2afa6 100644 --- a/Libraries/SPTarkov.Server.Core/Services/LocaleService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/LocaleService.cs @@ -9,7 +9,7 @@ namespace SPTarkov.Server.Core.Services; [Injectable(InjectionType.Singleton)] public class LocaleService(ISptLogger logger, DatabaseServer databaseServer, ConfigServer configServer) { - protected readonly LocaleConfig _localeConfig = configServer.GetConfig(); + protected readonly LocaleConfig LocaleConfig = configServer.GetConfig(); private string _chosenServerLocale = string.Empty; private string _chosenClientLocale = string.Empty; @@ -58,9 +58,9 @@ public class LocaleService(ISptLogger logger, DatabaseServer data { if (string.IsNullOrEmpty(_chosenClientLocale)) { - _chosenClientLocale = string.Equals(_localeConfig.GameLocale, "system", StringComparison.OrdinalIgnoreCase) + _chosenClientLocale = string.Equals(LocaleConfig.GameLocale, "system", StringComparison.OrdinalIgnoreCase) ? GetPlatformForClientLocale() - : _localeConfig.GameLocale.ToLowerInvariant(); // Use custom locale value + : LocaleConfig.GameLocale.ToLowerInvariant(); // Use custom locale value } return _chosenClientLocale; @@ -75,9 +75,9 @@ public class LocaleService(ISptLogger logger, DatabaseServer data { if (string.IsNullOrEmpty(_chosenServerLocale)) { - _chosenServerLocale = string.Equals(_localeConfig.ServerLocale, "system", StringComparison.OrdinalIgnoreCase) + _chosenServerLocale = string.Equals(LocaleConfig.ServerLocale, "system", StringComparison.OrdinalIgnoreCase) ? GetPlatformForServerLocale() - : _localeConfig.ServerLocale.ToLowerInvariant(); // Use custom locale value + : LocaleConfig.ServerLocale.ToLowerInvariant(); // Use custom locale value } return _chosenServerLocale; @@ -89,7 +89,7 @@ public class LocaleService(ISptLogger logger, DatabaseServer data /// List of locales e.g. en/fr/cn public HashSet GetServerSupportedLocales() { - return _localeConfig.ServerSupportedLocales; + return LocaleConfig.ServerSupportedLocales; } /// @@ -98,7 +98,7 @@ public class LocaleService(ISptLogger logger, DatabaseServer data /// Dictionary of locales e.g. en/fr/cn public Dictionary GetLocaleFallbacks() { - return _localeConfig.Fallbacks; + return LocaleConfig.Fallbacks; } /// @@ -115,7 +115,7 @@ public class LocaleService(ISptLogger logger, DatabaseServer data } var baseNameCode = platformLocale.TwoLetterISOLanguageName.ToLowerInvariant(); - if (_localeConfig.ServerSupportedLocales.Contains(baseNameCode)) + if (LocaleConfig.ServerSupportedLocales.Contains(baseNameCode)) { // Found a matching locale return baseNameCode; @@ -123,7 +123,7 @@ public class LocaleService(ISptLogger logger, DatabaseServer data // Check if base language (e.g. CN / EN / DE) exists var languageCode = platformLocale.Name.ToLowerInvariant(); - if (_localeConfig.ServerSupportedLocales.Contains(languageCode)) + if (LocaleConfig.ServerSupportedLocales.Contains(languageCode)) { if (baseNameCode == "zh") // Handle edge case of zh diff --git a/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs b/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs index e45a4af2..6bd248cc 100644 --- a/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs @@ -49,13 +49,13 @@ public class LocationLifecycleService( BtrDeliveryService btrDeliveryService ) { - protected readonly LocationConfig _locationConfig = configServer.GetConfig(); - protected readonly InRaidConfig _inRaidConfig = configServer.GetConfig(); - protected readonly TraderConfig _traderConfig = configServer.GetConfig(); - protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); - protected readonly HideoutConfig _hideoutConfig = configServer.GetConfig(); - protected readonly PmcConfig _pmcConfig = configServer.GetConfig(); - protected readonly LostOnDeathConfig _lostOnDeathConfig = configServer.GetConfig(); + protected readonly LocationConfig LocationConfig = configServer.GetConfig(); + protected readonly InRaidConfig InRaidConfig = configServer.GetConfig(); + protected readonly TraderConfig TraderConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); + protected readonly HideoutConfig HideoutConfig = configServer.GetConfig(); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); + protected readonly LostOnDeathConfig LostOnDeathConfig = configServer.GetConfig(); protected const string Pmc = "pmc"; protected const string Savage = "savage"; @@ -88,8 +88,8 @@ public class LocationLifecycleService( ); // Raid is starting, adjust run times to reduce server load while player is in raid - _ragfairConfig.RunIntervalSeconds = _ragfairConfig.RunIntervalValues.InRaid; - _hideoutConfig.RunIntervalSeconds = _hideoutConfig.RunIntervalValues.InRaid; + RagfairConfig.RunIntervalSeconds = RagfairConfig.RunIntervalValues.InRaid; + HideoutConfig.RunIntervalSeconds = HideoutConfig.RunIntervalValues.InRaid; var result = new StartLocalRaidResponseData { @@ -155,7 +155,7 @@ public class LocationLifecycleService( protected void HandlePreRaidInventoryChecks(string playerSide, PmcData pmcData, MongoId sessionId) { // If config enabled, remove players equipped items to prevent alt-F4 from persisting items - if (!IsSide(playerSide) || !_lostOnDeathConfig.WipeOnRaidStart) + if (!IsSide(playerSide) || !LostOnDeathConfig.WipeOnRaidStart) { return; } @@ -201,9 +201,9 @@ public class LocationLifecycleService( /// Map to adjust values of protected void AdjustBotHostilitySettings(LocationBase location) { - foreach (var botId in _pmcConfig.HostilitySettings) + foreach (var botId in PMCConfig.HostilitySettings) { - var configHostilityChanges = _pmcConfig.HostilitySettings[botId.Key]; + var configHostilityChanges = PMCConfig.HostilitySettings[botId.Key]; var locationBotHostilityDetails = location.BotLocationModifier.AdditionalHostilitySettings.FirstOrDefault(botSettings => string.Equals(botSettings.BotRole, botId.Key, StringComparison.OrdinalIgnoreCase) ); @@ -318,7 +318,7 @@ public class LocationLifecycleService( var raidAdjustments = profileActivityService.GetProfileActivityRaidData(sessionId)?.RaidAdjustments; if (raidAdjustments is not null) { - locationConfigClone = cloner.Clone(_locationConfig); // Clone values so they can be used to reset originals later + locationConfigClone = cloner.Clone(LocationConfig); // Clone values so they can be used to reset originals later raidTimeAdjustmentService.MakeAdjustmentsToMap(raidAdjustments, locationBaseClone); } @@ -329,8 +329,8 @@ public class LocationLifecycleService( if (raidAdjustments is not null && locationConfigClone is not null) { logger.Debug("Resetting loot multipliers back to their original values"); - _locationConfig.StaticLootMultiplier = locationConfigClone.StaticLootMultiplier; - _locationConfig.LooseLootMultiplier = locationConfigClone.LooseLootMultiplier; + LocationConfig.StaticLootMultiplier = locationConfigClone.StaticLootMultiplier; + LocationConfig.LooseLootMultiplier = locationConfigClone.LooseLootMultiplier; profileActivityService.GetProfileActivityRaidData(sessionId).RaidAdjustments = null; } @@ -356,8 +356,8 @@ public class LocationLifecycleService( } // Reset flea interval time to out-of-raid value - _ragfairConfig.RunIntervalSeconds = _ragfairConfig.RunIntervalValues.OutOfRaid; - _hideoutConfig.RunIntervalSeconds = _hideoutConfig.RunIntervalValues.OutOfRaid; + RagfairConfig.RunIntervalSeconds = RagfairConfig.RunIntervalValues.OutOfRaid; + HideoutConfig.RunIntervalSeconds = HideoutConfig.RunIntervalValues.OutOfRaid; // ServerId has various info stored in it, delimited by a period var serverDetails = request.ServerId.Split("."); @@ -392,13 +392,13 @@ public class LocationLifecycleService( HandlePostRaidPmc(sessionId, fullProfile, scavProfile, isDead, isSurvived, isTransfer, request, locationName); // Handle car extracts - if (request.Results.TookCarExtract(_inRaidConfig.CarExtracts)) + if (request.Results.TookCarExtract(InRaidConfig.CarExtracts)) { HandleCarExtract(request.Results.ExitName, pmcProfile, sessionId); } // Handle coop exit - if (request.Results.TookCoopExtract(_inRaidConfig.CoopExtracts) && _traderConfig.Fence.CoopExtractGift.SendGift) + if (request.Results.TookCoopExtract(InRaidConfig.CoopExtracts) && TraderConfig.Fence.CoopExtractGift.SendGift) { HandleCoopExtract(sessionId, pmcProfile, request.Results.ExitName); SendCoopTakenFenceMessage(sessionId); @@ -412,7 +412,7 @@ public class LocationLifecycleService( protected void SendCoopTakenFenceMessage(MongoId sessionId) { // Generate randomised reward for taking coop extract - var loot = lootGenerator.CreateRandomLoot(_traderConfig.Fence.CoopExtractGift); + var loot = lootGenerator.CreateRandomLoot(TraderConfig.Fence.CoopExtractGift); var parentId = new MongoId(); foreach (var itemAndChildren in loot) @@ -429,9 +429,9 @@ public class LocationLifecycleService( sessionId, Traders.FENCE, MessageType.MessageWithItems, - randomUtil.GetArrayValue(_traderConfig.Fence.CoopExtractGift.MessageLocaleIds), + randomUtil.GetArrayValue(TraderConfig.Fence.CoopExtractGift.MessageLocaleIds), mailableLoot, - timeUtil.GetHoursAsSeconds(_traderConfig.Fence.CoopExtractGift.GiftExpiryHours) + timeUtil.GetHoursAsSeconds(TraderConfig.Fence.CoopExtractGift.GiftExpiryHours) ); } @@ -450,7 +450,7 @@ public class LocationLifecycleService( var newFenceStanding = GetFenceStandingAfterExtract( pmcData, - _inRaidConfig.CarExtractBaseStandingGain, + InRaidConfig.CarExtractBaseStandingGain, pmcData.CarExtractCounts[extractName] ); @@ -483,7 +483,7 @@ public class LocationLifecycleService( var newFenceStanding = GetFenceStandingAfterExtract( pmcData, - _inRaidConfig.CoopExtractBaseStandingGain, + InRaidConfig.CoopExtractBaseStandingGain, pmcData.CoopExtractCounts[extractName] ); @@ -518,8 +518,8 @@ public class LocationLifecycleService( fenceStanding += Math.Max(baseGain / extractCount, 0.01); // Ensure fence loyalty level is not above/below the range -7 to 15 - var fenceMax = _traderConfig.Fence.PlayerRepMax; - var fenceMin = _traderConfig.Fence.PlayerRepMin; + var fenceMax = TraderConfig.Fence.PlayerRepMax; + var fenceMin = TraderConfig.Fence.PlayerRepMin; var newFenceStanding = Math.Clamp(fenceStanding.GetValueOrDefault(0), fenceMin, fenceMax); logger.Debug($"Old vs new fence standing: {pmcData.TradersInfo[fenceId].Standing}, {newFenceStanding}"); @@ -579,8 +579,8 @@ public class LocationLifecycleService( ApplyTraderStandingAdjustments(scavProfile.TradersInfo, postRaidProfile.TradersInfo); // Clamp fence standing within -7 to 15 range - var fenceMax = _traderConfig.Fence.PlayerRepMax; // 15 - var fenceMin = _traderConfig.Fence.PlayerRepMin; //-7 + var fenceMax = TraderConfig.Fence.PlayerRepMax; // 15 + var fenceMin = TraderConfig.Fence.PlayerRepMin; //-7 if (!postRaidProfile.TradersInfo.TryGetValue(Traders.FENCE, out var postRaidFenceData)) { logger.Error($"post raid fence data not found for: {sessionId}"); @@ -591,7 +591,7 @@ public class LocationLifecycleService( // Successful extract as scav, give some rep if (request.Results.IsPlayerSurvived() && scavProfile.TradersInfo[Traders.FENCE].Standing < fenceMax) { - scavProfile.TradersInfo[Traders.FENCE].Standing += _inRaidConfig.ScavExtractStandingGain; + scavProfile.TradersInfo[Traders.FENCE].Standing += InRaidConfig.ScavExtractStandingGain; } // Copy scav fence values to PMC profile @@ -662,7 +662,7 @@ public class LocationLifecycleService( /// Profile health data to adjust protected void UpdateLimbValuesAfterTransit(BotBaseHealth? profileHealth) { - var transitSettings = _locationConfig.TransitSettings; + var transitSettings = LocationConfig.TransitSettings; if (transitSettings == null) { logger.Warning("Unable to find: _locationConfig.TransitSettings"); @@ -762,8 +762,8 @@ public class LocationLifecycleService( var fenceId = Traders.FENCE; // Clamp fence standing - var fenceMax = _traderConfig.Fence.PlayerRepMax; // 15 - var fenceMin = _traderConfig.Fence.PlayerRepMin; //-7 + var fenceMax = TraderConfig.Fence.PlayerRepMax; // 15 + var fenceMin = TraderConfig.Fence.PlayerRepMin; //-7 serverPmcProfile.TradersInfo[fenceId].Standing = Math.Clamp( postRaidProfile.TradersInfo[fenceId].Standing ?? 0d, diff --git a/Libraries/SPTarkov.Server.Core/Services/OpenZoneService.cs b/Libraries/SPTarkov.Server.Core/Services/OpenZoneService.cs index 503fde77..f595cd6d 100644 --- a/Libraries/SPTarkov.Server.Core/Services/OpenZoneService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/OpenZoneService.cs @@ -16,7 +16,7 @@ public class OpenZoneService( ConfigServer configServer ) { - protected readonly LocationConfig _locationConfig = configServer.GetConfig(); + protected readonly LocationConfig LocationConfig = configServer.GetConfig(); /// /// Add open zone to specified map @@ -25,11 +25,11 @@ public class OpenZoneService( /// zone to add public void AddZoneToMap(string locationId, string zoneToAdd) { - _locationConfig.OpenZones.TryAdd(locationId, []); + LocationConfig.OpenZones.TryAdd(locationId, []); - if (!_locationConfig.OpenZones[locationId].Contains(zoneToAdd)) + if (!LocationConfig.OpenZones[locationId].Contains(zoneToAdd)) { - _locationConfig.OpenZones[locationId].Add(zoneToAdd); + LocationConfig.OpenZones[locationId].Add(zoneToAdd); } } @@ -39,7 +39,7 @@ public class OpenZoneService( public void ApplyZoneChangesToAllMaps() { var dbLocations = databaseService.GetLocations().GetDictionary(); - foreach (var mapKvP in _locationConfig.OpenZones) + foreach (var mapKvP in LocationConfig.OpenZones) { if (!dbLocations.ContainsKey(mapKvP.Key)) { @@ -48,7 +48,7 @@ public class OpenZoneService( continue; } - var zonesToAdd = _locationConfig.OpenZones[mapKvP.Key]; + var zonesToAdd = LocationConfig.OpenZones[mapKvP.Key]; // Convert openzones string into list, easier to work wih var mapOpenZonesArray = dbLocations[mapKvP.Key].Base.OpenZones.Split(",").ToHashSet(); diff --git a/Libraries/SPTarkov.Server.Core/Services/PaymentService.cs b/Libraries/SPTarkov.Server.Core/Services/PaymentService.cs index f62a4593..e979d476 100644 --- a/Libraries/SPTarkov.Server.Core/Services/PaymentService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/PaymentService.cs @@ -29,7 +29,7 @@ public class PaymentService( ConfigServer configServer ) { - protected readonly InventoryConfig _inventoryConfig = configServer.GetConfig(); + protected readonly InventoryConfig InventoryConfig = configServer.GetConfig(); /// /// Take money and insert items into return to server request @@ -443,8 +443,8 @@ public class PaymentService( var aImmediateParent = inventoryItems.FirstOrDefault(item => item.Id == a.ParentId); var bImmediateParent = inventoryItems.FirstOrDefault(item => item.Id == b.ParentId); - var aInDeprioContainer = _inventoryConfig.DeprioritisedMoneyContainers.Contains(aImmediateParent.Template); - var bInDeprioContainer = _inventoryConfig.DeprioritisedMoneyContainers.Contains(bImmediateParent.Template); + var aInDeprioContainer = InventoryConfig.DeprioritisedMoneyContainers.Contains(aImmediateParent.Template); + var bInDeprioContainer = InventoryConfig.DeprioritisedMoneyContainers.Contains(bImmediateParent.Template); // Prioritize B if (!aInDeprioContainer && bInDeprioContainer) diff --git a/Libraries/SPTarkov.Server.Core/Services/PostDbLoadService.cs b/Libraries/SPTarkov.Server.Core/Services/PostDbLoadService.cs index 596b4790..beeaf3d4 100644 --- a/Libraries/SPTarkov.Server.Core/Services/PostDbLoadService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/PostDbLoadService.cs @@ -24,18 +24,18 @@ public class PostDbLoadService( ICloner cloner ) { - protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly CoreConfig _coreConfig = configServer.GetConfig(); - protected readonly HideoutConfig _hideoutConfig = configServer.GetConfig(); - protected readonly ItemConfig _itemConfig = configServer.GetConfig(); - protected readonly LocationConfig _locationConfig = configServer.GetConfig(); - protected readonly LootConfig _lootConfig = configServer.GetConfig(); - protected readonly PmcConfig _pmcConfig = configServer.GetConfig(); - protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly BotConfig BotConfig = configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); + protected readonly HideoutConfig HideoutConfig = configServer.GetConfig(); + protected readonly ItemConfig ItemConfig = configServer.GetConfig(); + protected readonly LocationConfig LocationConfig = configServer.GetConfig(); + protected readonly LootConfig LootConfig = configServer.GetConfig(); + protected readonly PmcConfig PMCConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); public void PerformPostDbLoadActions() { - _coreConfig.ServerStartTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + CoreConfig.ServerStartTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); // Regenerate base cache now mods are loaded and game is starting // Mods that add items and use the baseClass service generate the cache including their items, the next mod that @@ -57,27 +57,27 @@ public class PostDbLoadService( AdjustMinReserveRaiderSpawnChance(); - if (_coreConfig.Fixes.FixShotgunDispersion) + if (CoreConfig.Fixes.FixShotgunDispersion) { FixShotgunDispersions(); } - if (_locationConfig.AddOpenZonesToAllMaps) + if (LocationConfig.AddOpenZonesToAllMaps) { openZoneService.ApplyZoneChangesToAllMaps(); } - if (_pmcConfig.RemoveExistingPmcWaves) + if (PMCConfig.RemoveExistingPmcWaves) { RemoveExistingPmcWaves(); } - if (_locationConfig.AddCustomBotWavesToMaps) + if (LocationConfig.AddCustomBotWavesToMaps) { customLocationWaveService.ApplyWaveChangesToAllMaps(); } - if (_locationConfig.EnableBotTypeLimits) + if (LocationConfig.EnableBotTypeLimits) { AdjustMapBotLimits(); } @@ -88,15 +88,15 @@ public class PostDbLoadService( MergeCustomHideoutAreas(); - if (_locationConfig.RogueLighthouseSpawnTimeSettings.Enabled) + if (LocationConfig.RogueLighthouseSpawnTimeSettings.Enabled) { FixRoguesSpawningInstantlyOnLighthouse(); } AdjustLabsRaiderSpawnRate(); - AdjustHideoutCraftTimes(_hideoutConfig.OverrideCraftTimeSeconds); - AdjustHideoutBuildTimes(_hideoutConfig.OverrideBuildTimeSeconds); + AdjustHideoutCraftTimes(HideoutConfig.OverrideCraftTimeSeconds); + AdjustHideoutBuildTimes(HideoutConfig.OverrideBuildTimeSeconds); UnlockHideoutLootCrateCrafts(); @@ -115,7 +115,7 @@ public class PostDbLoadService( } // Flea bsg blacklist is off - if (!_ragfairConfig.Dynamic.Blacklist.EnableBsgList) + if (!RagfairConfig.Dynamic.Blacklist.EnableBsgList) { SetAllDbItemsAsSellableOnFlea(); } @@ -129,9 +129,9 @@ public class PostDbLoadService( var currentSeason = seasonalEventService.GetActiveWeatherSeason(); raidWeatherService.GenerateWeather(currentSeason); - if (_botConfig.WeeklyBoss.Enabled) + if (BotConfig.WeeklyBoss.Enabled) { - var chosenBoss = GetWeeklyBoss(_botConfig.WeeklyBoss.BossPool, _botConfig.WeeklyBoss.ResetDay); + var chosenBoss = GetWeeklyBoss(BotConfig.WeeklyBoss.BossPool, BotConfig.WeeklyBoss.ResetDay); FlagMapAsGuaranteedBoss(chosenBoss); } } @@ -282,7 +282,7 @@ public class PostDbLoadService( protected void CloneExistingCraftsAndAddNew() { var hideoutCraftDb = databaseService.GetHideout().Production; - var craftsToAdd = _hideoutConfig.HideoutCraftsToAdd; + var craftsToAdd = HideoutConfig.HideoutCraftsToAdd; foreach (var craftToAdd in craftsToAdd) { var clonedCraft = cloner.Clone(hideoutCraftDb.Recipes.FirstOrDefault(x => x.Id == craftToAdd.CraftIdToCopy)); @@ -311,8 +311,8 @@ public class PostDbLoadService( { var isTriggered = raiderSpawn.TriggerId.Length > 0; // Empty string if not triggered var newSpawnChance = isTriggered - ? _locationConfig.ReserveRaiderSpawnChanceOverrides.Triggered - : _locationConfig.ReserveRaiderSpawnChanceOverrides.NonTriggered; + ? LocationConfig.ReserveRaiderSpawnChanceOverrides.Triggered + : LocationConfig.ReserveRaiderSpawnChanceOverrides.NonTriggered; if (newSpawnChance == -1) { @@ -329,7 +329,7 @@ public class PostDbLoadService( protected void AddCustomLooseLootPositions() { - var looseLootPositionsToAdd = _lootConfig.LooseLoot; + var looseLootPositionsToAdd = LootConfig.LooseLoot; foreach (var (mapId, positionsToAdd) in looseLootPositionsToAdd) { if (mapId is null) @@ -422,12 +422,12 @@ public class PostDbLoadService( protected void AdjustMapBotLimits() { var mapsDb = databaseService.GetLocations().GetDictionary(); - if (_locationConfig.BotTypeLimits is null) + if (LocationConfig.BotTypeLimits is null) { return; } - foreach (var (mapId, limits) in _locationConfig.BotTypeLimits) + foreach (var (mapId, limits) in LocationConfig.BotTypeLimits) { if (!mapsDb.TryGetValue(mapId, out var map)) { @@ -465,12 +465,12 @@ public class PostDbLoadService( protected void AdjustLooseLootSpawnProbabilities() { - if (_lootConfig.LooseLootSpawnPointAdjustments is null) + if (LootConfig.LooseLootSpawnPointAdjustments is null) { return; } - foreach (var (mapId, mapAdjustments) in _lootConfig.LooseLootSpawnPointAdjustments) + foreach (var (mapId, mapAdjustments) in LootConfig.LooseLootSpawnPointAdjustments) { databaseService .GetLocation(mapId) @@ -507,7 +507,7 @@ public class PostDbLoadService( { var mapsDb = databaseService.GetLocations(); var mapsDict = mapsDb.GetDictionary(); - foreach (var (key, cap) in _botConfig.MaxBotCap) + foreach (var (key, cap) in BotConfig.MaxBotCap) { // Keys given are like this: "factory4_night" use GetMappedKey to change to "Factory4Night" which the dictionary contains if (!mapsDict.TryGetValue(mapsDb.GetMappedKey(key), out var map)) @@ -527,7 +527,7 @@ public class PostDbLoadService( /// protected void FixRoguesSpawningInstantlyOnLighthouse() { - var rogueSpawnDelaySeconds = _locationConfig.RogueLighthouseSpawnTimeSettings.WaitTimeSeconds; + var rogueSpawnDelaySeconds = LocationConfig.RogueLighthouseSpawnTimeSettings.WaitTimeSeconds; var lighthouse = databaseService.GetLocations().Lighthouse?.Base; if (lighthouse is null) // Just in case they remove this cursed map @@ -659,7 +659,7 @@ public class PostDbLoadService( var item in dbItems.Where(item => string.Equals(item.Type, "Item", StringComparison.OrdinalIgnoreCase) && !item.Properties.CanSellOnRagfair.GetValueOrDefault(false) - && !_ragfairConfig.Dynamic.Blacklist.Custom.Contains(item.Id) + && !RagfairConfig.Dynamic.Blacklist.Custom.Contains(item.Id) ) ) { @@ -676,7 +676,7 @@ public class PostDbLoadService( protected void ApplyFleaPriceOverrides() { var fleaPrices = databaseService.GetPrices(); - foreach (var (itemTpl, price) in _ragfairConfig.Dynamic.ItemPriceOverrideRouble) + foreach (var (itemTpl, price) in RagfairConfig.Dynamic.ItemPriceOverrideRouble) { fleaPrices[itemTpl] = price; } @@ -684,7 +684,7 @@ public class PostDbLoadService( protected void AddCustomItemPresetsToGlobals() { - foreach (var presetToAdd in _itemConfig.CustomItemGlobalPresets) + foreach (var presetToAdd in ItemConfig.CustomItemGlobalPresets) { if (databaseService.GetGlobals().ItemPresets.ContainsKey(presetToAdd.Id)) { diff --git a/Libraries/SPTarkov.Server.Core/Services/ProfileFixerService.cs b/Libraries/SPTarkov.Server.Core/Services/ProfileFixerService.cs index fe519297..97f6c7a9 100644 --- a/Libraries/SPTarkov.Server.Core/Services/ProfileFixerService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/ProfileFixerService.cs @@ -25,11 +25,10 @@ public class ProfileFixerService( HideoutHelper hideoutHelper, DatabaseService databaseService, ServerLocalisationService serverLocalisationService, - ConfigServer configServer, - InventoryHelper inventoryHelper + ConfigServer configServer ) { - protected readonly CoreConfig _coreConfig = configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); /// /// Find issues in the pmc profile data that may cause issues and fix them @@ -617,7 +616,7 @@ public class ProfileFixerService( { if (!traderHelper.TraderExists(traderId)) { - if (_coreConfig.Fixes.RemoveInvalidTradersFromProfile) + if (CoreConfig.Fixes.RemoveInvalidTradersFromProfile) { logger.Warning( $"Non - default trader: {traderId} removed from PMC TradersInfo in: {fullProfile.ProfileInfo?.ProfileId} profile" @@ -635,7 +634,7 @@ public class ProfileFixerService( { if (!traderHelper.TraderExists(traderId)) { - if (_coreConfig.Fixes.RemoveInvalidTradersFromProfile) + if (CoreConfig.Fixes.RemoveInvalidTradersFromProfile) { logger.Warning( $"Non - default trader: {traderId} removed from Scav TradersInfo in: {fullProfile.ProfileInfo?.ProfileId} profile" diff --git a/Libraries/SPTarkov.Server.Core/Services/RagfairOfferService.cs b/Libraries/SPTarkov.Server.Core/Services/RagfairOfferService.cs index 903c45d6..8d526488 100644 --- a/Libraries/SPTarkov.Server.Core/Services/RagfairOfferService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/RagfairOfferService.cs @@ -33,7 +33,7 @@ public class RagfairOfferService( ) { private bool _playerOffersLoaded; - protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); /// /// Get all offers @@ -357,6 +357,6 @@ public class RagfairOfferService( /// True if enough offers have expired public bool EnoughExpiredOffersExistToProcess() { - return ragfairOfferHolder.GetExpiredOfferCount() >= _ragfairConfig.Dynamic.ExpiredOfferThreshold; + return ragfairOfferHolder.GetExpiredOfferCount() >= RagfairConfig.Dynamic.ExpiredOfferThreshold; } } diff --git a/Libraries/SPTarkov.Server.Core/Services/RagfairPriceService.cs b/Libraries/SPTarkov.Server.Core/Services/RagfairPriceService.cs index b61940ad..9fa16001 100644 --- a/Libraries/SPTarkov.Server.Core/Services/RagfairPriceService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/RagfairPriceService.cs @@ -28,8 +28,8 @@ public class RagfairPriceService( ConfigServer configServer ) { - private readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); - protected Dictionary? _staticPrices; + protected readonly RagfairConfig RagfairConfig = configServer.GetConfig(); + protected Dictionary? StaticPrices; /// /// Generate static (handbook) and dynamic (prices.json) flea prices, store inside class as dictionaries @@ -50,14 +50,14 @@ public class RagfairPriceService( /// public void RefreshStaticPrices() { - _staticPrices = new Dictionary(); + StaticPrices = new Dictionary(); foreach ( var item in databaseService .GetItems() .Values.Where(item => string.Equals(item.Type, "Item", StringComparison.OrdinalIgnoreCase)) ) { - _staticPrices[item.Id] = handbookHelper.GetTemplatePrice(item.Id); + StaticPrices[item.Id] = handbookHelper.GetTemplatePrice(item.Id); } } @@ -130,18 +130,18 @@ public class RagfairPriceService( { var dynamicPrices = databaseService.GetPrices(); // Use dynamic prices first, fill in any gaps with data from static prices (handbook) - return dynamicPrices.Concat(_staticPrices).GroupBy(x => x.Key).ToDictionary(x => x.Key, x => x.First().Value); + return dynamicPrices.Concat(StaticPrices).GroupBy(x => x.Key).ToDictionary(x => x.Key, x => x.First().Value); } public Dictionary GetAllStaticPrices() { // Refresh the cache so we include any newly added custom items - if (_staticPrices is null) + if (StaticPrices is null) { RefreshStaticPrices(); } - return _staticPrices; + return StaticPrices; } /// @@ -211,13 +211,13 @@ public class RagfairPriceService( var price = GetFleaPriceForItem(itemTemplateId); // Adjust price if below handbook price, based on config. - if (_ragfairConfig.Dynamic.OfferAdjustment.AdjustPriceWhenBelowHandbookPrice) + if (RagfairConfig.Dynamic.OfferAdjustment.AdjustPriceWhenBelowHandbookPrice) { price = AdjustPriceIfBelowHandbook(price, itemTemplateId); } // Use trader price if higher, based on config. - if (_ragfairConfig.Dynamic.UseTraderPriceForOffersIfHigher) + if (RagfairConfig.Dynamic.UseTraderPriceForOffersIfHigher) { var traderPrice = traderHelper.GetHighestSellToTraderPrice(itemTemplateId); if (traderPrice > price) @@ -238,20 +238,20 @@ public class RagfairPriceService( } // Check for existence of manual price adjustment multiplier - if (_ragfairConfig.Dynamic.ItemPriceMultiplier.TryGetValue(itemTemplateId, out var multiplier)) + if (RagfairConfig.Dynamic.ItemPriceMultiplier.TryGetValue(itemTemplateId, out var multiplier)) { price *= multiplier; } // The quality of the item affects the price + not on the ignore list - if (item is not null && !_ragfairConfig.Dynamic.IgnoreQualityPriceVarianceBlacklist.Contains(itemTemplateId)) + if (item is not null && !RagfairConfig.Dynamic.IgnoreQualityPriceVarianceBlacklist.Contains(itemTemplateId)) { var qualityModifier = itemHelper.GetItemQualityModifier(item); price *= qualityModifier; } // Make adjustments for unreasonably priced items. - foreach (var (key, value) in _ragfairConfig.Dynamic.UnreasonableModPrices) + foreach (var (key, value) in RagfairConfig.Dynamic.UnreasonableModPrices) { if (!value.Enabled || !itemHelper.IsOfBaseclass(itemTemplateId, key)) { @@ -319,7 +319,7 @@ public class RagfairPriceService( protected MinMax GetOfferTypeRangeValues(bool isPreset, bool isPack) { // Use different min/max values if the item is a preset or pack - var priceRanges = _ragfairConfig.Dynamic.PriceRanges; + var priceRanges = RagfairConfig.Dynamic.PriceRanges; if (isPreset) { return priceRanges.Preset; @@ -343,7 +343,7 @@ public class RagfairPriceService( { var itemHandbookPrice = GetStaticPriceForItem(itemTpl); var priceDifferencePercent = GetPriceDifference(itemHandbookPrice.Value, itemPrice); - var offerAdjustmentSettings = _ragfairConfig.Dynamic.OfferAdjustment; + var offerAdjustmentSettings = RagfairConfig.Dynamic.OfferAdjustment; // Only adjust price if difference is > a percent AND item price passes threshold set in config if ( diff --git a/Libraries/SPTarkov.Server.Core/Services/RaidTimeAdjustmentService.cs b/Libraries/SPTarkov.Server.Core/Services/RaidTimeAdjustmentService.cs index 4107a1bb..e5287444 100644 --- a/Libraries/SPTarkov.Server.Core/Services/RaidTimeAdjustmentService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/RaidTimeAdjustmentService.cs @@ -22,7 +22,7 @@ public class RaidTimeAdjustmentService( ConfigServer configServer ) { - protected readonly LocationConfig _locationConfig = configServer.GetConfig(); + protected readonly LocationConfig LocationConfig = configServer.GetConfig(); /// /// Make alterations to the base map data passed in @@ -42,12 +42,12 @@ public class RaidTimeAdjustmentService( // Change loot multiplier values before they're used below if (raidAdjustments.DynamicLootPercent < 100) { - AdjustLootMultipliers(_locationConfig.LooseLootMultiplier, raidAdjustments.DynamicLootPercent); + AdjustLootMultipliers(LocationConfig.LooseLootMultiplier, raidAdjustments.DynamicLootPercent); } if (raidAdjustments.StaticLootPercent < 100) { - AdjustLootMultipliers(_locationConfig.StaticLootMultiplier, raidAdjustments.StaticLootPercent); + AdjustLootMultipliers(LocationConfig.StaticLootMultiplier, raidAdjustments.StaticLootPercent); } // Adjust the escape time limit @@ -253,7 +253,7 @@ public class RaidTimeAdjustmentService( /// ScavRaidTimeLocationSettings protected ScavRaidTimeLocationSettings GetMapSettings(string location) { - var mapSettings = _locationConfig.ScavRaidTimeSettings.Maps[location.ToLowerInvariant()]; + var mapSettings = LocationConfig.ScavRaidTimeSettings.Maps[location.ToLowerInvariant()]; if (mapSettings is null) { logger.Warning($"Unable to find scav raid time settings for map: {location}, using defaults"); @@ -309,7 +309,7 @@ public class RaidTimeAdjustmentService( // // I added 2 seconds just to be safe... // - var trainArrivalDelaySeconds = _locationConfig.ScavRaidTimeSettings.Settings.TrainArrivalDelayObservedSeconds; + var trainArrivalDelaySeconds = LocationConfig.ScavRaidTimeSettings.Settings.TrainArrivalDelayObservedSeconds; // Determine the earliest possible time in the raid when the train would leave var earliestPossibleDepartureMinutes = (exit.MinTime + exit.Count + exit.ExfiltrationTime + trainArrivalDelaySeconds) / 60; diff --git a/Libraries/SPTarkov.Server.Core/Services/RaidWeatherService.cs b/Libraries/SPTarkov.Server.Core/Services/RaidWeatherService.cs index 7896a1b5..e7e050f1 100644 --- a/Libraries/SPTarkov.Server.Core/Services/RaidWeatherService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/RaidWeatherService.cs @@ -18,8 +18,8 @@ public class RaidWeatherService( ConfigServer configServer ) { - protected readonly WeatherConfig _weatherConfig = configServer.GetConfig(); - protected readonly List _weatherForecast = []; + protected readonly WeatherConfig WeatherConfig = configServer.GetConfig(); + protected readonly List WeatherForecast = []; /// /// Generate 24 hours of weather data starting from midnight today @@ -30,7 +30,7 @@ public class RaidWeatherService( var staringTimestamp = timeUtil.GetTodayMidnightTimeStamp(); // How far into future do we generate weather - var futureTimestampToReach = staringTimestamp + timeUtil.GetHoursAsSeconds(_weatherConfig.Weather.GenerateWeatherAmountHours ?? 1); + var futureTimestampToReach = staringTimestamp + timeUtil.GetHoursAsSeconds(WeatherConfig.Weather.GenerateWeatherAmountHours ?? 1); // Keep adding new weather until we have reached desired future date var nextTimestamp = staringTimestamp; @@ -39,7 +39,7 @@ public class RaidWeatherService( var newWeatherToAddToCache = weatherGenerator.GenerateWeather(currentSeason, nextTimestamp); // Add generated weather for time period to cache - _weatherForecast.Add(newWeatherToAddToCache); + WeatherForecast.Add(newWeatherToAddToCache); // Increment timestamp so next loop can begin at correct time nextTimestamp += GetWeightedWeatherTimePeriod(); @@ -53,7 +53,7 @@ public class RaidWeatherService( protected long GetWeightedWeatherTimePeriod() { var chosenTimePeriodMinutes = weightedRandomHelper - .WeightedRandom(_weatherConfig.Weather.TimePeriod.Values, _weatherConfig.Weather.TimePeriod.Weights) + .WeightedRandom(WeatherConfig.Weather.TimePeriod.Values, WeatherConfig.Weather.TimePeriod.Weights) .Item; return chosenTimePeriodMinutes * 60; @@ -67,7 +67,7 @@ public class RaidWeatherService( var currentSeason = seasonalEventService.GetActiveWeatherSeason(); ValidateWeatherDataExists(currentSeason); - return _weatherForecast.Find(weather => weather.Timestamp >= timeUtil.GetTimeStamp()); + return WeatherForecast.Find(weather => weather.Timestamp >= timeUtil.GetTimeStamp()); } /// @@ -78,7 +78,7 @@ public class RaidWeatherService( var currentSeason = seasonalEventService.GetActiveWeatherSeason(); ValidateWeatherDataExists(currentSeason); - return _weatherForecast.Where(weather => weather.Timestamp >= timeUtil.GetTimeStamp()); + return WeatherForecast.Where(weather => weather.Timestamp >= timeUtil.GetTimeStamp()); } /// @@ -87,10 +87,10 @@ public class RaidWeatherService( protected void ValidateWeatherDataExists(Season currentSeason) { // Clear expired weather data - _weatherForecast.RemoveAll(weather => weather.Timestamp < timeUtil.GetTimeStamp()); + WeatherForecast.RemoveAll(weather => weather.Timestamp < timeUtil.GetTimeStamp()); // Check data exists for current time - var result = _weatherForecast.Where(weather => weather.Timestamp >= timeUtil.GetTimeStamp()); + var result = WeatherForecast.Where(weather => weather.Timestamp >= timeUtil.GetTimeStamp()); if (!result.Any()) { GenerateWeather(currentSeason); diff --git a/Libraries/SPTarkov.Server.Core/Services/RepairService.cs b/Libraries/SPTarkov.Server.Core/Services/RepairService.cs index 04e2bead..86210fa2 100644 --- a/Libraries/SPTarkov.Server.Core/Services/RepairService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/RepairService.cs @@ -34,7 +34,7 @@ public class RepairService( WeightedRandomHelper weightedRandomHelper ) { - protected readonly RepairConfig _repairConfig = configServer.GetConfig(); + protected readonly RepairConfig RepairConfig = configServer.GetConfig(); /// /// Use trader to repair an items durability @@ -73,7 +73,7 @@ public class RepairService( repairItemDetails.Count.Value, false, repairQualityMultiplier.Value, - repairQualityMultiplier != 0 && _repairConfig.ApplyRandomizeDurabilityLoss + repairQualityMultiplier != 0 && RepairConfig.ApplyRandomizeDurabilityLoss ); // get repair price @@ -83,14 +83,12 @@ public class RepairService( logger.Error(serverLocalisationService.GetText("repair-unable_to_find_item_repair_cost", itemToRepair.Template)); } - var repairCost = Math.Round( - itemRepairCost.Value * repairItemDetails.Count.Value * repairRate.Value * _repairConfig.PriceMultiplier - ); + var repairCost = Math.Round(itemRepairCost.Value * repairItemDetails.Count.Value * repairRate.Value * RepairConfig.PriceMultiplier); if (logger.IsLogEnabled(LogLevel.Debug)) { logger.Debug($"item base repair cost: {itemRepairCost}"); - logger.Debug($"price multiplier: {_repairConfig.PriceMultiplier}"); + logger.Debug($"price multiplier: {RepairConfig.PriceMultiplier}"); logger.Debug($"repair cost: {repairCost}"); } @@ -180,7 +178,7 @@ public class RepairService( logger.Error(serverLocalisationService.GetText("repair-item_has_no_repair_points", repairDetails.RepairedItem.Template)); } - var pointsToAddToVestSkill = repairDetails.RepairPoints * _repairConfig.ArmorKitSkillPointGainPerRepairPointMultiplier; + var pointsToAddToVestSkill = repairDetails.RepairPoints * RepairConfig.ArmorKitSkillPointGainPerRepairPointMultiplier; logger.Debug($"Added: {pointsToAddToVestSkill} {vestSkillToLevel} skill"); profileHelper.AddSkillPointsToPlayer(pmcData, vestSkillToLevel, pointsToAddToVestSkill.GetValueOrDefault(0)); @@ -201,8 +199,8 @@ public class RepairService( { // Weapons/armor have different multipliers var intRepairMultiplier = itemHelper.IsOfBaseclass(repairDetails.RepairedItem.Template, BaseClasses.WEAPON) - ? _repairConfig.RepairKitIntellectGainMultiplier.Weapon - : _repairConfig.RepairKitIntellectGainMultiplier.Armor; + ? RepairConfig.RepairKitIntellectGainMultiplier.Weapon + : RepairConfig.RepairKitIntellectGainMultiplier.Armor; // Limit gain to a max value defined in config.maxIntellectGainPerRepair if (repairDetails.RepairPoints is null) @@ -210,11 +208,11 @@ public class RepairService( logger.Error(serverLocalisationService.GetText("repair-item_has_no_repair_points", repairDetails.RepairedItem.Template)); } - return Math.Min(repairDetails.RepairPoints.Value * intRepairMultiplier, _repairConfig.MaxIntellectGainPerRepair.Kit); + return Math.Min(repairDetails.RepairPoints.Value * intRepairMultiplier, RepairConfig.MaxIntellectGainPerRepair.Kit); } // Trader repair - Not as accurate as kit, needs data from live - return Math.Min(repairDetails.RepairAmount.Value / 10, _repairConfig.MaxIntellectGainPerRepair.Trader); + return Math.Min(repairDetails.RepairAmount.Value / 10, RepairConfig.MaxIntellectGainPerRepair.Trader); } /// @@ -227,7 +225,7 @@ public class RepairService( var random = new Random(); // This formula and associated configs is calculated based on 30 repairs done on live // The points always came out 2-aligned, which is why there's a divide/multiply by 2 with ceil calls - var gainMult = _repairConfig.WeaponTreatment.PointGainMultiplier; + var gainMult = RepairConfig.WeaponTreatment.PointGainMultiplier; // First we get a baseline based on our repair amount, and gain multiplier with a bit of rounding var step1 = Math.Ceiling(repairDetails.RepairAmount.Value / 2) * gainMult; @@ -240,15 +238,15 @@ public class RepairService( // You can both crit fail and succeed at the same time, for fun (Balances out to 0 with default settings) // Add a random chance to crit-fail - if (random.Next() <= _repairConfig.WeaponTreatment.CritFailureChance) + if (random.Next() <= RepairConfig.WeaponTreatment.CritFailureChance) { - skillPoints -= _repairConfig.WeaponTreatment.CritFailureAmount; + skillPoints -= RepairConfig.WeaponTreatment.CritFailureAmount; } // Add a random chance to crit-succeed - if (random.Next() <= _repairConfig.WeaponTreatment.CritSuccessChance) + if (random.Next() <= RepairConfig.WeaponTreatment.CritSuccessChance) { - skillPoints += _repairConfig.WeaponTreatment.CritSuccessAmount; + skillPoints += RepairConfig.WeaponTreatment.CritSuccessAmount; } return Math.Max(skillPoints, 0); @@ -281,7 +279,7 @@ public class RepairService( var itemToRepairDetails = itemsDb[itemToRepair.Template]; var repairItemIsArmor = itemToRepairDetails.Properties.ArmorMaterial is not null; var repairAmount = repairKits[0].Count / GetKitDivisor(itemToRepairDetails, repairItemIsArmor, pmcData); - var shouldApplyDurabilityLoss = ShouldRepairKitApplyDurabilityLoss(pmcData, _repairConfig.ApplyRandomizeDurabilityLoss); + var shouldApplyDurabilityLoss = ShouldRepairKitApplyDurabilityLoss(pmcData, RepairConfig.ApplyRandomizeDurabilityLoss); repairHelper.UpdateItemDurability( itemToRepair, @@ -450,12 +448,12 @@ public class RepairService( ) ) { - var armorConfig = _repairConfig.RepairKit.Armor; + var armorConfig = RepairConfig.RepairKit.Armor; AddBuff(armorConfig, repairDetails.RepairedItem); } else if (itemHelper.IsOfBaseclass(repairDetails.RepairedItem.Template, BaseClasses.WEAPON)) { - var weaponConfig = _repairConfig.RepairKit.Weapon; + var weaponConfig = RepairConfig.RepairKit.Weapon; AddBuff(weaponConfig, repairDetails.RepairedItem); } // TODO: Knife repair kits may be added at some point, a bracket needs to be added here diff --git a/Libraries/SPTarkov.Server.Core/Services/SeasonalEventService.cs b/Libraries/SPTarkov.Server.Core/Services/SeasonalEventService.cs index e71c200f..acba63b6 100644 --- a/Libraries/SPTarkov.Server.Core/Services/SeasonalEventService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/SeasonalEventService.cs @@ -30,7 +30,7 @@ public class SeasonalEventService( { private bool _christmasEventActive; - protected readonly FrozenSet _christmasEventItems = + protected readonly FrozenSet ChristmasEventItems = [ ItemTpl.ARMOR_6B13_M_ASSAULT_ARMOR_CHRISTMAS_EDITION, ItemTpl.BACKPACK_SANTAS_BAG, @@ -63,7 +63,7 @@ public class SeasonalEventService( private List _currentlyActiveEvents = []; - protected readonly FrozenSet _equipmentSlotsToFilter = + protected readonly FrozenSet EquipmentSlotsToFilter = [ EquipmentSlots.FaceCover, EquipmentSlots.Headwear, @@ -73,7 +73,7 @@ public class SeasonalEventService( private bool _halloweenEventActive; - protected readonly FrozenSet _halloweenEventItems = + protected readonly FrozenSet HalloweenEventItems = [ ItemTpl.HEADWEAR_JACKOLANTERN_TACTICAL_PUMPKIN_HELMET, ItemTpl.FACECOVER_FACELESS_MASK, @@ -88,11 +88,11 @@ public class SeasonalEventService( ItemTpl.RANDOMLOOTCONTAINER_PUMPKIN_RAND_LOOT_CONTAINER, ]; - protected readonly HttpConfig _httpConfig = configServer.GetConfig(); - protected readonly LocationConfig _locationConfig = configServer.GetConfig(); - protected readonly QuestConfig _questConfig = configServer.GetConfig(); - protected readonly SeasonalEventConfig _seasonalEventConfig = configServer.GetConfig(); - protected readonly WeatherConfig _weatherConfig = configServer.GetConfig(); + protected readonly HttpConfig HttpConfig = configServer.GetConfig(); + protected readonly LocationConfig LocationConfig = configServer.GetConfig(); + protected readonly QuestConfig QuestConfig = configServer.GetConfig(); + protected readonly SeasonalEventConfig SeasonalEventConfig = configServer.GetConfig(); + protected readonly WeatherConfig WeatherConfig = configServer.GetConfig(); /// /// Get an array of christmas items found in bots inventories as loot @@ -100,7 +100,7 @@ public class SeasonalEventService( /// array public FrozenSet GetChristmasEventItems() { - return _christmasEventItems; + return ChristmasEventItems; } /// @@ -109,17 +109,17 @@ public class SeasonalEventService( /// array public FrozenSet GetHalloweenEventItems() { - return _halloweenEventItems; + return HalloweenEventItems; } public bool ItemIsChristmasRelated(MongoId itemTpl) { - return _christmasEventItems.Contains(itemTpl); + return ChristmasEventItems.Contains(itemTpl); } public bool ItemIsHalloweenRelated(MongoId itemTpl) { - return _halloweenEventItems.Contains(itemTpl); + return HalloweenEventItems.Contains(itemTpl); } /// @@ -129,7 +129,7 @@ public class SeasonalEventService( /// public bool ItemIsSeasonalRelated(MongoId itemTpl) { - return _christmasEventItems.Contains(itemTpl) || _halloweenEventItems.Contains(itemTpl); + return ChristmasEventItems.Contains(itemTpl) || HalloweenEventItems.Contains(itemTpl); } /// @@ -152,12 +152,12 @@ public class SeasonalEventService( var items = new HashSet(); if (!ChristmasEventEnabled()) { - items.UnionWith(_christmasEventItems); + items.UnionWith(ChristmasEventItems); } if (!HalloweenEventEnabled()) { - items.UnionWith(_halloweenEventItems); + items.UnionWith(HalloweenEventItems); } return items; @@ -196,7 +196,7 @@ public class SeasonalEventService( /// true if seasonal events should be checked for public bool IsAutomaticEventDetectionEnabled() { - return _seasonalEventConfig.EnableSeasonalEventDetection; + return SeasonalEventConfig.EnableSeasonalEventDetection; } /// @@ -206,7 +206,7 @@ public class SeasonalEventService( /// bots with equipment changes protected Dictionary>>? GetEventBotGear(SeasonalEventType eventType) { - return _seasonalEventConfig.EventGear.GetValueOrDefault(eventType, null); + return SeasonalEventConfig.EventGear.GetValueOrDefault(eventType, null); } /// @@ -216,7 +216,7 @@ public class SeasonalEventService( /// bots with loot changes protected Dictionary>> GetEventBotLoot(SeasonalEventType eventType) { - return _seasonalEventConfig.EventLoot.GetValueOrDefault(eventType, null); + return SeasonalEventConfig.EventLoot.GetValueOrDefault(eventType, null); } /// @@ -225,7 +225,7 @@ public class SeasonalEventService( /// Record with event name + start/end date public List GetEventDetails() { - return _seasonalEventConfig.Events; + return SeasonalEventConfig.Events; } /// @@ -236,7 +236,7 @@ public class SeasonalEventService( /// true if related public bool IsQuestRelatedToEvent(MongoId questId, SeasonalEventType eventType) { - var eventQuestData = _questConfig.EventQuests.GetValueOrDefault(questId, null); + var eventQuestData = QuestConfig.EventQuests.GetValueOrDefault(questId, null); return eventQuestData?.Season == eventType; } @@ -263,7 +263,7 @@ public class SeasonalEventService( public bool ForceSeasonalEvent(SeasonalEventType eventType) { var globalConfig = databaseService.GetGlobals().Configuration; - var seasonEvent = _seasonalEventConfig.Events.FirstOrDefault(e => e.Type == eventType); + var seasonEvent = SeasonalEventConfig.Events.FirstOrDefault(e => e.Type == eventType); if (seasonEvent is null) { logger.Warning($"Unable to force event: {eventType} as it cannot be found in events config"); @@ -307,13 +307,13 @@ public class SeasonalEventService( /// Season enum value public Season GetActiveWeatherSeason() { - if (_weatherConfig.OverrideSeason.HasValue) + if (WeatherConfig.OverrideSeason.HasValue) { - return _weatherConfig.OverrideSeason.Value; + return WeatherConfig.OverrideSeason.Value; } var currentDate = timeUtil.GetDateTimeNow(); - foreach (var seasonRange in _weatherConfig.SeasonDates) + foreach (var seasonRange in WeatherConfig.SeasonDates) { if ( currentDate.DateIsBetweenTwoDates( @@ -343,7 +343,7 @@ public class SeasonalEventService( var christmasItems = GetChristmasEventItems(); // Remove christmas related equipment - foreach (var equipmentSlotKey in _equipmentSlotsToFilter) + foreach (var equipmentSlotKey in EquipmentSlotsToFilter) { if (!botInventory.Equipment.TryGetValue(equipmentSlotKey, out var equipment)) { @@ -357,7 +357,7 @@ public class SeasonalEventService( continue; } - botInventory.Equipment[equipmentSlotKey] = equipment.Where(i => !_christmasEventItems.Contains(i.Key)).ToDictionary(); + botInventory.Equipment[equipmentSlotKey] = equipment.Where(i => !ChristmasEventItems.Contains(i.Key)).ToDictionary(); } var containersToCheck = new List> @@ -411,7 +411,7 @@ public class SeasonalEventService( RenameBitcoin(); if (eventType.Settings is not null && eventType.Settings.ReplaceBotHostility.GetValueOrDefault(false)) { - if (_seasonalEventConfig.HostilitySettingsForEvent.TryGetValue("AprilFools", out var botData)) + if (SeasonalEventConfig.HostilitySettingsForEvent.TryGetValue("AprilFools", out var botData)) { ReplaceBotHostility(botData); } @@ -419,7 +419,7 @@ public class SeasonalEventService( if (eventType.Settings?.ForceSeason != null) { - _weatherConfig.OverrideSeason = eventType.Settings.ForceSeason; + WeatherConfig.OverrideSeason = eventType.Settings.ForceSeason; } break; @@ -458,7 +458,7 @@ public class SeasonalEventService( if (eventType.Settings?.ReplaceBotHostility ?? false) { - ReplaceBotHostility(_seasonalEventConfig.HostilitySettingsForEvent.FirstOrDefault(x => x.Key == "zombies").Value); + ReplaceBotHostility(SeasonalEventConfig.HostilitySettingsForEvent.FirstOrDefault(x => x.Key == "zombies").Value); } if (eventType.Settings?.AdjustBotAppearances ?? false) @@ -530,7 +530,7 @@ public class SeasonalEventService( /// Season to apply changes for protected void AdjustBotAppearanceValues(SeasonalEventType season) { - if (!_seasonalEventConfig.BotAppearanceChanges.TryGetValue(season, out var appearanceAdjustments)) + if (!SeasonalEventConfig.BotAppearanceChanges.TryGetValue(season, out var appearanceAdjustments)) { // No changes found for this season return; @@ -575,7 +575,7 @@ public class SeasonalEventService( protected void ReplaceBotHostility(Dictionary> hostilitySettings) { var locations = databaseService.GetLocations().GetDictionary(); - var ignoreList = _locationConfig.NonMaps; + var ignoreList = LocationConfig.NonMaps; foreach (var (locationName, locationBase) in locations) { @@ -813,7 +813,7 @@ public class SeasonalEventService( protected void AddEventWavesToMaps(string eventType) { - var wavesToAddByMap = _seasonalEventConfig.EventWaves[eventType.ToLowerInvariant()]; + var wavesToAddByMap = SeasonalEventConfig.EventWaves[eventType.ToLowerInvariant()]; if (wavesToAddByMap is null) { @@ -843,7 +843,7 @@ public class SeasonalEventService( /// OPTIONAL - Maps to add bosses to protected void AddEventBossesToMaps(string eventType, HashSet? mapIdWhitelist = null) { - if (!_seasonalEventConfig.EventBossSpawns.TryGetValue(eventType.ToLowerInvariant(), out var botsToAddPerMap)) + if (!SeasonalEventConfig.EventBossSpawns.TryGetValue(eventType.ToLowerInvariant(), out var botsToAddPerMap)) { logger.Warning($"Unable to add: {eventType} bosses, eventBossSpawns is missing"); return; @@ -884,21 +884,21 @@ public class SeasonalEventService( switch (eventType) { case SeasonalEventType.Halloween: - _httpConfig.ServerImagePathOverride["./assets/images/traders/5a7c2ebb86f7746e324a06ab.png"] = + HttpConfig.ServerImagePathOverride["./assets/images/traders/5a7c2ebb86f7746e324a06ab.png"] = "./assets/images/traders/halloween/5a7c2ebb86f7746e324a06ab.png"; - _httpConfig.ServerImagePathOverride["./assets/images/traders/5ac3b86a86f77461491d1ad8.png"] = + HttpConfig.ServerImagePathOverride["./assets/images/traders/5ac3b86a86f77461491d1ad8.png"] = "./assets/images/traders/halloween/5ac3b86a86f77461491d1ad8.png"; - _httpConfig.ServerImagePathOverride["./assets/images/traders/5c06531a86f7746319710e1b.png"] = + HttpConfig.ServerImagePathOverride["./assets/images/traders/5c06531a86f7746319710e1b.png"] = "./assets/images/traders/halloween/5c06531a86f7746319710e1b.png"; - _httpConfig.ServerImagePathOverride["./assets/images/traders/59b91ca086f77469a81232e4.png"] = + HttpConfig.ServerImagePathOverride["./assets/images/traders/59b91ca086f77469a81232e4.png"] = "./assets/images/traders/halloween/59b91ca086f77469a81232e4.png"; - _httpConfig.ServerImagePathOverride["./assets/images/traders/59b91cab86f77469aa5343ca.png"] = + HttpConfig.ServerImagePathOverride["./assets/images/traders/59b91cab86f77469aa5343ca.png"] = "./assets/images/traders/halloween/59b91cab86f77469aa5343ca.png"; - _httpConfig.ServerImagePathOverride["./assets/images/traders/59b91cb486f77469a81232e5.png"] = + HttpConfig.ServerImagePathOverride["./assets/images/traders/59b91cb486f77469a81232e5.png"] = "./assets/images/traders/halloween/59b91cb486f77469a81232e5.png"; - _httpConfig.ServerImagePathOverride["./assets/images/traders/59b91cbd86f77469aa5343cb.png"] = + HttpConfig.ServerImagePathOverride["./assets/images/traders/59b91cbd86f77469aa5343cb.png"] = "./assets/images/traders/halloween/59b91cbd86f77469aa5343cb.png"; - _httpConfig.ServerImagePathOverride["./assets/images/traders/579dc571d53a0658a154fbec.png"] = + HttpConfig.ServerImagePathOverride["./assets/images/traders/579dc571d53a0658a154fbec.png"] = "./assets/images/traders/halloween/579dc571d53a0658a154fbec.png"; break; case SeasonalEventType.Christmas: @@ -1074,7 +1074,7 @@ public class SeasonalEventService( /// protected void AddGifterBotToMaps() { - var gifterSettings = _seasonalEventConfig.GifterSettings; + var gifterSettings = SeasonalEventConfig.GifterSettings; var maps = databaseService.GetLocations().GetDictionary(); foreach (var gifterMapSettings in gifterSettings) { @@ -1156,7 +1156,7 @@ public class SeasonalEventService( if (seasonalEvent.Settings?.ForceSeason != null) { - _weatherConfig.OverrideSeason = seasonalEvent.Settings.ForceSeason; + WeatherConfig.OverrideSeason = seasonalEvent.Settings.ForceSeason; } if (seasonalEvent.Settings?.AdjustBotAppearances ?? false) @@ -1186,7 +1186,7 @@ public class SeasonalEventService( /// Bot role as string public string GetBaseRoleForEventBot(string? eventBotRole) { - return _seasonalEventConfig.EventBotMapping.GetValueOrDefault(eventBotRole, null); + return SeasonalEventConfig.EventBotMapping.GetValueOrDefault(eventBotRole, null); } /// @@ -1194,6 +1194,6 @@ public class SeasonalEventService( /// public void EnableSnow() { - _weatherConfig.OverrideSeason = Season.WINTER; + WeatherConfig.OverrideSeason = Season.WINTER; } } diff --git a/Libraries/SPTarkov.Server.Core/Services/TraderPurchasePersisterService.cs b/Libraries/SPTarkov.Server.Core/Services/TraderPurchasePersisterService.cs index d51dd15d..dff29b7e 100644 --- a/Libraries/SPTarkov.Server.Core/Services/TraderPurchasePersisterService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/TraderPurchasePersisterService.cs @@ -19,7 +19,7 @@ public class TraderPurchasePersisterService( ConfigServer configServer ) { - protected readonly TraderConfig _traderConfig = configServer.GetConfig(); + protected readonly TraderConfig TraderConfig = configServer.GetConfig(); /// /// Get the purchases made from a trader for this profile before the last trader reset @@ -113,7 +113,7 @@ public class TraderPurchasePersisterService( foreach (var purchaseKvP in purchasesFromTrader) { - var traderUpdateDetails = _traderConfig.UpdateTime.FirstOrDefault(x => x.TraderId == traderId); + var traderUpdateDetails = TraderConfig.UpdateTime.FirstOrDefault(x => x.TraderId == traderId); if (traderUpdateDetails is null) { logger.Error( diff --git a/Libraries/SPTarkov.Server.Core/Status/StatusPage.cs b/Libraries/SPTarkov.Server.Core/Status/StatusPage.cs index 36c91f96..882c1861 100644 --- a/Libraries/SPTarkov.Server.Core/Status/StatusPage.cs +++ b/Libraries/SPTarkov.Server.Core/Status/StatusPage.cs @@ -13,7 +13,7 @@ namespace SPTarkov.Server.Core.Status; [Injectable(TypePriority = 0)] public class StatusPage(TimeUtil timeUtil, ProfileActivityService profileActivityService, ConfigServer configServer) : IHttpListener { - protected readonly CoreConfig _coreConfig = configServer.GetConfig(); + protected readonly CoreConfig CoreConfig = configServer.GetConfig(); public bool CanHandle(MongoId sessionId, HttpRequest req) { @@ -25,8 +25,8 @@ public class StatusPage(TimeUtil timeUtil, ProfileActivityService profileActivit var sptVersion = $"SPT version: {ProgramStatics.SPT_VERSION()}"; var debugEnabled = $"Debug enabled: {ProgramStatics.DEBUG()}"; var modsEnabled = $"Mods enabled: {ProgramStatics.MODS()}"; - var timeStarted = $"Started : {timeUtil.GetDateTimeFromTimeStamp(_coreConfig.ServerStartTime.Value)}"; - var uptime = $"Uptime: {DateTimeOffset.UtcNow.ToUnixTimeSeconds() - _coreConfig.ServerStartTime} seconds".ToArray(); + var timeStarted = $"Started : {timeUtil.GetDateTimeFromTimeStamp(CoreConfig.ServerStartTime.Value)}"; + var uptime = $"Uptime: {DateTimeOffset.UtcNow.ToUnixTimeSeconds() - CoreConfig.ServerStartTime} seconds".ToArray(); var activeProfiles = profileActivityService.GetActiveProfileIdsWithinMinutes(30); var activePlayerCount = $"Profiles active in last 30 minutes: {activeProfiles.Count}. {string.Join(",", activeProfiles)}";