static bool Prefix(SG_HiringHall_Screen __instance, Pilot ___selectedPilot, string button) { Mod.Log.Debug?.Write("Updating Dialog"); if (___selectedPilot != null && "Hire".Equals(button, StringComparison.InvariantCultureIgnoreCase) && __instance.HireButtonValid()) { Mod.Log.Debug?.Write(" -- pilot is selected"); CrewDetails details = ModState.GetCrewDetails(___selectedPilot.pilotDef); int modifiedBonus = (int)Mathf.RoundToInt(details.AdjustedBonus); string salaryS = new Text(Mod.LocalizedText.Labels[ModText.LT_Crew_Hire_Button], new string[] { SimGameState.GetCBillString(Mathf.RoundToInt(modifiedBonus)) }) .ToString(); Mod.Log.Debug?.Write($" -- bonus will be: {salaryS}"); GenericPopupBuilder.Create("Confirm?", salaryS) .AddButton("Cancel") .AddButton("Accept", __instance.HireCurrentPilot) .CancelOnEscape() .AddFader(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill) .Render(); return(false); } return(true); }
static void Postfix(SG_HiringHall_Screen __instance, Pilot ___selectedPilot, LocalizableText ___MWInitialCostText, UIColorRefTracker ___MWCostColor, HBSDOTweenButton ___HireButton) { Mod.Log.Debug?.Write("Updating UpdateMoneySpot"); if (___selectedPilot != null) { Mod.Log.Debug?.Write(" -- pilot is selected"); // Account for the salary CrewDetails details = ModState.GetCrewDetails(___selectedPilot.pilotDef); int modifiedBonus = (int)Mathf.RoundToInt(details.AdjustedBonus); string bonus = new Text(Mod.LocalizedText.Labels[ModText.LT_Crew_Bonus_Label], new string[] { SimGameState.GetCBillString(Mathf.RoundToInt(modifiedBonus)) }) .ToString(); Mod.Log.Debug?.Write($" -- bonus will be: {bonus}"); ___MWInitialCostText.SetText(bonus); if (modifiedBonus > ModState.SimGameState.Funds) { Mod.Log.Debug?.Write(" -- Disabling hire."); ___MWCostColor.SetUIColor(UIColor.Red); ___HireButton.SetState(ButtonState.Disabled); } else { Mod.Log.Debug?.Write(" -- Enabling hire."); ___MWCostColor.SetUIColor(UIColor.White); ___HireButton.SetState(ButtonState.Enabled); } } }
static void Postfix(AAR_ContractObjectivesWidget __instance, Contract ___theContract) { try { List <Pilot> deployedPilots = ___theContract.PlayerUnitResults.Select(ur => ur.pilot).ToList(); int hazardPaySum = 0; foreach (Pilot p in deployedPilots) { CrewDetails details = ModState.GetCrewDetails(p.pilotDef); hazardPaySum -= details.HazardPay; } Mod.Log.Debug?.Write($"Total hazard pay for mission is: {hazardPaySum}"); string hazardPayTitleS = new Text(Mod.LocalizedText.Labels[ModText.LT_Contract_Hazard_Pay], new object[] { SimGameState.GetCBillString(hazardPaySum) }).ToString(); string guid = Guid.NewGuid().ToString(); MissionObjectiveResult hazardPayObjective = new MissionObjectiveResult(hazardPayTitleS, guid, false, true, ObjectiveStatus.Succeeded, false); Traverse addObjective = Traverse.Create(__instance).Method("AddObjective", new Type[] { typeof(MissionObjectiveResult) }); addObjective.GetValue(new object[] { hazardPayObjective }); } catch (Exception e) { Mod.Log.Warn?.Write(e, "Failed to build hazard pay for contract!"); } }
public static void MultiPurchasePopup_Refresh_Postfix(SG_Stores_MultiPurchasePopup __instance, int ___costPerUnit, int ___quantityBeingSold, LocalizableText ___TitleText, LocalizableText ___DescriptionText, string ___itemName, HBSDOTweenButton ___ConfirmButton) { Mod.Log.Debug("SG_S_MPP:R entered."); int value = ___costPerUnit * ___quantityBeingSold; Mod.Log.Debug($"SG_S_MPP:R value:{value} = costPerUnit:{___costPerUnit} x quantityBeingSold:{___quantityBeingSold}."); string actionS = "??"; if (State.StoreIsBuying) { actionS = "BUY"; } else if (State.StoreIsSelling) { actionS = "SELL"; } Text titleT = new Text($"{actionS}: {___itemName}"); ___TitleText.SetText(titleT.ToString(), new object[] { }); Text descT = new Text($"{actionS} FOR <color=#F79B26>{SimGameState.GetCBillString(value)}</color>"); ___DescriptionText.SetText(descT.ToString(), new object[] { }); ___ConfirmButton.SetText(actionS); }
public static SimGameEventDef ModifyContractExpirationEventForPilot(Pilot pilot, CrewDetails details) { SimGameEventDef rawEventDef = ModState.SimGameState.DataManager.SimGameEventDefs.Get(ModConsts.Event_ContractExpired); // Change the description fields BaseDescriptionDef rawBaseDescDef = rawEventDef.Description; StringBuilder detailsSB = new StringBuilder(rawBaseDescDef.Details); detailsSB.Append("\n"); detailsSB.Append("<margin=5em>\n"); // TODO: Localize detailsSB.Append($" Hiring Bonus: {SimGameState.GetCBillString(details.AdjustedBonus)}\n\n"); detailsSB.Append($" Monthly Salary: {SimGameState.GetCBillString(details.AdjustedSalary)}\n\n"); detailsSB.Append("</margin>\n"); BaseDescriptionDef newBaseDescDef = new BaseDescriptionDef(rawBaseDescDef.Id, rawBaseDescDef.Name, detailsSB.ToString(), rawBaseDescDef.Icon); // Change the options to have the correct pay values SimGameEventOption[] newOptions = rawEventDef.Options; foreach (SimGameEventOption sgeOption in newOptions) { if (ModConsts.Event_Option_ContractExpired_Hire_Bonus.Equals(sgeOption.Description.Id)) { (Pilot Pilot, CrewDetails Details)expired = ModState.ExpiredContracts.Peek(); UpdateFundsStat(pilot, expired.Details.AdjustedBonus, sgeOption); } } SimGameEventDef expiredEventDef = new SimGameEventDef( rawEventDef.PublishState, rawEventDef.EventType, rawEventDef.Scope, newBaseDescDef, rawEventDef.Requirements, rawEventDef.AdditionalRequirements, rawEventDef.AdditionalObjects, newOptions, rawEventDef.Weight, rawEventDef.OneTimeEvent, rawEventDef.Tags); return(expiredEventDef); }
public static string GetCurrentDescription() { var text = new Text(mech.Description.UIName); var result = "Assembling <b><color=#20ff20>" + text.ToString() + "</color></b> Using `Mech Parts:\n"; foreach (var info in used_parts) { if (info.used > 0) { result += $"\n <b>{info.mechname}</b>: <color=#20ff20>{info.used}</color> {(info.used == 1 ? "part" : "parts")}"; if (info.cbills > 0) { result += $", <color=#ffff00>{SimGameState.GetCBillString(info.cbills * info.used)}</color>"; } } } int cbills = used_parts.Sum(i => i.used * i.cbills); result += $"\n\n <b>Total:</b> <color=#ffff00>{SimGameState.GetCBillString(cbills)}</color>"; int left = chassis.MechPartMax - used_parts.Sum(i => i.used); if (left > 0) { result += $"\n\nNeed <color=#ff2020>{left}</color> more {(left == 1 ? "part" : "parts")}"; } else { result += $"\n\nPreparations complete. Proceed?"; } return(result); }
static void Prefix(AAR_ContractObjectivesWidget __instance, Contract ___theContract) { int repairCost = (int)Math.Ceiling(State.CombatDamage) * Mod.Config.LeopardRepairCostPerDamage; if (repairCost != 0) { Mod.Log.Debug($"AAR_COW:FIO adding repair cost objective:{repairCost}"); string objectiveLabel = $"LEOPARD REPAIR COSTS: {SimGameState.GetCBillString(repairCost)}"; MissionObjectiveResult missionObjectiveResult = new MissionObjectiveResult(objectiveLabel, "7facf07a-626d-4a3b-a1ec-b29a35ff1ac0", false, true, ObjectiveStatus.Succeeded, false); ___theContract.MissionObjectiveResultList.Add(missionObjectiveResult); } }
public static SimGameEventDef CreateHeadHuntingEvent(Pilot pilot, CrewDetails details, float retentionCost, float buyoutPayment) { SimGameEventDef rawEventDef = ModState.SimGameState.DataManager.SimGameEventDefs.Get(ModConsts.Event_HeadHunting); int counterOffer = SalaryHelper.CalcCounterOffer(details) * -1; int buyout = details.AdjustedBonus; Mod.Log.Info?.Write($"For headhunting event, counterOffer: {counterOffer} buyout: {buyout}"); // Change the description fields BaseDescriptionDef rawBaseDescDef = rawEventDef.Description; StringBuilder detailsSB = new StringBuilder(rawBaseDescDef.Details); detailsSB.Append("\n\n"); detailsSB.Append("<margin=5em>\n"); detailsSB.Append( new Text(Mod.LocalizedText.Events[ModText.ET_HeadHunted_Retention], new object[] { SimGameState.GetCBillString(counterOffer) }).ToString() ); detailsSB.Append( new Text(Mod.LocalizedText.Events[ModText.ET_HeadHunted_Buyout], new object[] { SimGameState.GetCBillString(buyout) }).ToString() ); detailsSB.Append("</margin>\n"); BaseDescriptionDef newBaseDescDef = new BaseDescriptionDef(rawBaseDescDef.Id, rawBaseDescDef.Name, detailsSB.ToString(), rawBaseDescDef.Icon); // Change the options to have the correct pay values SimGameEventOption[] newOptions = rawEventDef.Options; foreach (SimGameEventOption sgeOption in newOptions) { if (ModConsts.Event_Option_HeadHunting_Leaves.Equals(sgeOption.Description.Id)) { // Mechwarrior leaves, company gets a payoff UpdateFundsStat(pilot, buyout, sgeOption); } else if (ModConsts.Event_Option_HeadHunting_Retained.Equals(sgeOption.Description.Id)) { // Mechwarrior statys, company pays them retention UpdateFundsStat(pilot, counterOffer, sgeOption); } } SimGameEventDef eventDef = new SimGameEventDef( rawEventDef.PublishState, rawEventDef.EventType, rawEventDef.Scope, newBaseDescDef, rawEventDef.Requirements, rawEventDef.AdditionalRequirements, rawEventDef.AdditionalObjects, newOptions, rawEventDef.Weight, rawEventDef.OneTimeEvent, rawEventDef.Tags); return(eventDef); }
public static void ReplaceTitle(LocalizableText ___TitleText, LocalizableText ___DescriptionText, string ___itemName, int ___costPerUnit, int ___quantityBeingSold, HBSDOTweenButton ___ConfirmButton) { if (!SG_Stores_MultiPurchasePopup_Handler.Replace) { return; } ___TitleText.SetText($"{SG_Stores_MultiPurchasePopup_Handler.Text} {___itemName}"); var value = SimGameState.GetCBillString(___costPerUnit * ___quantityBeingSold); ___DescriptionText.SetText($"{SG_Stores_MultiPurchasePopup_Handler.Text} FOR <color=#F79B26>{value}</color>"); ___ConfirmButton.SetText(SG_Stores_MultiPurchasePopup_Handler.Text); }
static void Postfix(SGCaptainsQuartersStatusScreen __instance, EconomyScale expenditureLevel, SimGameState ___simState, Transform ___SectionOneExpensesList, LocalizableText ___SectionOneExpensesField) { try { List <KeyValuePair <string, int> > keyValuePairList = new List <KeyValuePair <string, int> >(); float expenditureCostModifier = ___simState.GetExpenditureCostModifier(expenditureLevel); string sectionOneExpenses = ___SectionOneExpensesField.OriginalText; sectionOneExpenses = sectionOneExpenses.Replace("¢", "").Replace(",", ""); int ongoingUpgradeCosts = int.Parse(sectionOneExpenses); List <string> mechNames = new List <string>(); foreach (MechDef mechDef in ___simState.ActiveMechs.Values) { string key = mechDef.Name; mechNames.Add(key); int value = Mathf.RoundToInt(expenditureCostModifier * (float)___simState.Constants.Finances.MechCostPerQuarter); ongoingUpgradeCosts -= value; if (settings.CostByTons) { value = Mathf.RoundToInt(expenditureCostModifier * (float)mechDef.Chassis.Tonnage * settings.cbillsPerTon); if (settings.TonsAdditive) { value += Mathf.RoundToInt(expenditureCostModifier * Helper.CalculateCBillValue(mechDef) * settings.PercentageOfMechCost); } } else { value = Mathf.RoundToInt(expenditureCostModifier * Helper.CalculateCBillValue(mechDef) * settings.PercentageOfMechCost); } ongoingUpgradeCosts += value; keyValuePairList.Add(new KeyValuePair <string, int>(key, value)); } FilterListItems(___SectionOneExpensesList, ___simState, mechNames, keyValuePairList); keyValuePairList.Sort((Comparison <KeyValuePair <string, int> >)((a, b) => b.Value.CompareTo(a.Value))); keyValuePairList.ForEach((Action <KeyValuePair <string, int> >)(entry => { Traverse.Create(__instance).Method("AddListLineItem", new Type[] { typeof(Transform), typeof(string), typeof(string) }).GetValue( new object[] { ___SectionOneExpensesList, entry.Key, SimGameState.GetCBillString(entry.Value) }); })); Traverse.Create(__instance).Method("SetField", new Type[] { typeof(LocalizableText), typeof(string) }).GetValue( new object[] { ___SectionOneExpensesField, SimGameState.GetCBillString(ongoingUpgradeCosts) }); } catch (Exception e) { Helper.Logger.LogError(e); } }
static bool Prefix(SimGameState __instance, PilotDef def, ref string __result) { string salaryLabel = "------"; if (!def.IsFree) { CrewDetails details = ModState.GetCrewDetails(def); string cbillString = SimGameState.GetCBillString(Mathf.RoundToInt(details.AdjustedSalary)); salaryLabel = new Text(Mod.LocalizedText.Labels[ModText.LT_Crew_Salary_Label], new object[] { cbillString }) .ToString(); } __result = salaryLabel; return(false); }
static void Postfix(SG_HiringHall_MWSelectedPanel __instance, Pilot p, LocalizableText ___BaseSalaryText) { if (p != null && ___BaseSalaryText != null) { Mod.Log.Debug?.Write($"Updating MWSelectedPanel for pilot: {p.Name}"); // Account for the salary CrewDetails details = ModState.GetCrewDetails(p.pilotDef); int modifiedSalary = (int)Mathf.RoundToInt(details.AdjustedSalary); string modifiedSalaryS = SimGameState.GetCBillString(modifiedSalary); Mod.Log.Debug?.Write($" -- salary will be: {modifiedSalaryS}"); string salaryS = new Text(Mod.LocalizedText.Labels[ModText.LT_Crew_Salary_Label], new string[] { modifiedSalaryS }) .ToString(); ___BaseSalaryText.SetText(salaryS); } }
public static void BuildScrapAllDialog(List <ChassisCount> filteredChassis, float scrapPartModifier, string title, Action confirmAction) { int cbills = ScrapHelper.CalculateTotalScrap(filteredChassis, scrapPartModifier); string cbillStr = SimGameState.GetCBillString(cbills); string descLT = new Text(Mod.LocalizedText.Dialog[ModText.DT_Desc_ScrapAll], new object[] { cbillStr }).ToString(); string cancelLT = new Text(Mod.LocalizedText.Dialog[ModText.DT_Button_Cancel]).ToString(); string scrapLT = new Text(Mod.LocalizedText.Dialog[ModText.DT_Button_Scrap]).ToString(); GenericPopupBuilder.Create(title, descLT) .AddButton(cancelLT) .AddButton(scrapLT, confirmAction) .CancelOnEscape() .AddFader(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill) .Render(); }
static void Postfix(SG_HiringHall_DetailPanel __instance, Pilot p, LocalizableText ___DescriptionText) { CrewDetails details = ModState.GetCrewDetails(p.pilotDef); StringBuilder sb = new StringBuilder(); // Check hazard pay if (details.HazardPay > 0) { string hazardPayS = new Text(Mod.LocalizedText.Labels[ModText.LT_Crew_Hazard_Pay], new object[] { SimGameState.GetCBillString(details.HazardPay) }).ToString(); Mod.Log.Debug?.Write($"Hazard pay is: {hazardPayS}"); sb.Append(hazardPayS); sb.Append("\n\n"); } // Convert favored and hated faction if (details.FavoredFactionId > 0) { FactionValue faction = FactionEnumeration.GetFactionByID(details.FavoredFactionId); string favoredFactionS = new Text(Mod.LocalizedText.Labels[ModText.LT_Crew_Dossier_Biography_Faction_Favored], new object[] { faction.FactionDef.CapitalizedName }).ToString(); sb.Append(favoredFactionS); sb.Append("\n\n"); Mod.Log.Debug?.Write($" Favored Faction is: {favoredFactionS}"); //Mod.Log.Debug?.Write($" Favored Faction => name: '{faction.Name}' friendlyName: '{faction.FriendlyName}' " + // $"factionDef.Name: {faction.FactionDef?.Name} factionDef.CapitalizedName: {faction.FactionDef.CapitalizedName} " + // $"factionDef.ShortName: {faction.FactionDef?.ShortName} factionDef.CapitalizedShortName: {faction.FactionDef.CapitalizedShortName} " + // $""); } if (details.HatedFactionId > 0) { FactionValue faction = FactionEnumeration.GetFactionByID(details.HatedFactionId); string hatedFactionS = new Text(Mod.LocalizedText.Labels[ModText.LT_Crew_Dossier_Biography_Faction_Hated], new object[] { faction.FactionDef.CapitalizedName }).ToString(); sb.Append(hatedFactionS); sb.Append("\n\n"); Mod.Log.Debug?.Write($" Hated Faction is: {hatedFactionS}"); } sb.Append(Interpolator.Interpolate(p.pilotDef.Description.GetLocalizedDetails().ToString(true), ModState.SimGameState.Context, true)); ___DescriptionText.SetText(sb.ToString()); }
public static void Postfix(object data, TextMeshProUGUI ___detailText) { Mod.Log.Debug?.Write($"TP_E:SD - Init"); SimGameState sgs = UnityGameInstance.BattleTechGame.Simulation; if (data != null && ___detailText != null && sgs != null) { // Calculate total gear storage size MechComponentDef mcDef = (MechComponentDef)data; float componentStorageSize = Helper.CalculateGearStorageSize(mcDef); double totalSize = Helper.GetGearInventorySize(sgs); int storageCost = 0; if (totalSize > 0) { // Handle exponentiation of cost int totalCost = Helper.CalculateTotalForGearCargo(sgs, totalSize); double sizeFraction = componentStorageSize / totalSize; storageCost = (int)Math.Ceiling(totalCost * sizeFraction); Mod.Log.Debug?.Write($" totalCost: {totalCost} storageSize: {componentStorageSize} sizeFraction: {sizeFraction} fractionalCost: {storageCost}"); } else { // Assume no exponentiation when there is no gear double factoredSize = Math.Ceiling(componentStorageSize * Mod.Config.GearFactor); double scaledUnits = Math.Pow(factoredSize, Mod.Config.GearExponent); storageCost = (int)(Mod.Config.GearCostPerUnit * scaledUnits); Mod.Log.Info?.Write($" totalUnits:{componentStorageSize} x factor:{Mod.Config.GearFactor} = {factoredSize}"); } string costLabel = new Text(Mod.LocalizedText.Tooltips[ModText.LT_Tooltip_Cargo_Chassis], new object[] { SimGameState.GetCBillString(storageCost), componentStorageSize }).ToString(); Text newDetails = new Text(mcDef.Description.Details + costLabel); Mod.Log.Debug?.Write($" Setting details: {newDetails}u"); ___detailText.SetText(newDetails.ToString()); } else { Mod.Log.Debug?.Write($"TP_E:SD - Skipping"); } }
public static void Postfix(SGCaptainsQuartersStatusScreen __instance, EconomyScale expenditureLevel, bool showMoraleChange, Transform ___SectionOneExpensesList, TextMeshProUGUI ___SectionOneExpensesField, SimGameState ___simState) { SimGameState simulation = UnityGameInstance.BattleTechGame.Simulation; bool flag = __instance == null || ___SectionOneExpensesList == null || ___SectionOneExpensesField == null || simulation == null; List <KeyValuePair <string, int> > list = LoanSharks.GetCurrentKeys(___SectionOneExpensesList, ___simState); LoanSharks.ClearListLineItems(___SectionOneExpensesList, ___simState); string name = "Interest From Loans"; int value = ModState.InterestFromLoans; //___simState.CompanyStats.GetValue<int>("Item.HeatSinkDef.Gear_HeatSink_Generic_Standard"); int ongoingUpgradeCosts = 0; list.Add(new KeyValuePair <string, int>(name, value)); list.ForEach(delegate(KeyValuePair <string, int> entry) { ongoingUpgradeCosts += entry.Value; LoanSharks.AddListLineItem(___SectionOneExpensesList, ___simState, entry.Key, SimGameState.GetCBillString(entry.Value)); }); ___SectionOneExpensesField.SetText(SimGameState.GetCBillString(ongoingUpgradeCosts)); }
static void Postfix(SGFinancialForecastWidget __instance) { try { SimGameState simState = (SimGameState)AccessTools.Field(typeof(SGFinancialForecastWidget), "simState").GetValue(__instance); int expenditures = simState.GetExpenditures(false); if (expenditures < 0) { List <Image> PipFills = (List <Image>)AccessTools.Field(typeof(SGFinancialForecastWidget), "PipFills").GetValue(__instance); List <UIColorRefTracker> PipColors = (List <UIColorRefTracker>)AccessTools.Field(typeof(SGFinancialForecastWidget), "PipColors").GetValue(__instance); List <DOTweenAnimation> PipsToFlash = (List <DOTweenAnimation>)AccessTools.Field(typeof(SGFinancialForecastWidget), "PipsToFlash").GetValue(__instance); for (int i = 0; i < PipFills.Count; i++) { PipFills[i].gameObject.SetActive(true); PipColors[i].SetUIColor(UIColor.Green); } PipsToFlash.ForEach(delegate(DOTweenAnimation tween) { tween.DOPause(); }); UIColorRefTracker UnderlineColor = (UIColorRefTracker)AccessTools.Field(typeof(SGFinancialForecastWidget), "UnderlineColor").GetValue(__instance); UIColorRefTracker ReportBGColor = (UIColorRefTracker)AccessTools.Field(typeof(SGFinancialForecastWidget), "ReportBGColor").GetValue(__instance); UIColorRefTracker SpendingValueColor = (UIColorRefTracker)AccessTools.Field(typeof(SGFinancialForecastWidget), "SpendingValueColor").GetValue(__instance); UIColorRefTracker FinancialTextColor = (UIColorRefTracker)AccessTools.Field(typeof(SGFinancialForecastWidget), "FinancialTextColor").GetValue(__instance); Image BankrupcyIncomingOverlay = (Image)AccessTools.Field(typeof(SGFinancialForecastWidget), "BankrupcyIncomingOverlay").GetValue(__instance); UnderlineColor.SetUIColor(UIColor.Green); ReportBGColor.SetUIColor(UIColor.Green); SpendingValueColor.SetUIColor(UIColor.Green); FinancialTextColor.SetUIColor(UIColor.Green); BankrupcyIncomingOverlay.gameObject.SetActive(false); } TextMeshProUGUI CurrSpendingValueText = (TextMeshProUGUI)AccessTools.Field(typeof(SGFinancialForecastWidget), "CurrSpendingValueText").GetValue(__instance); CurrSpendingValueText.text = string.Format("{0} / mo", SimGameState.GetCBillString(0 - expenditures)); } catch (Exception e) { Logger.LogError(e); } }
public static void Postfix(object data, TextMeshProUGUI ___descriptionText) { Mod.Log.Debug?.Write($"TP_C:SD - Init"); if (data != null && ___descriptionText != null) { ChassisDef chassisDef = (ChassisDef)data; double storageTons = Helper.CalculateChassisTonnage(chassisDef); // Calculate total tonnage costs SimGameState sgs = UnityGameInstance.BattleTechGame.Simulation; double totalTonnage = Helper.CalculateTonnageForAllMechParts(sgs); int storageCost = 0; if (totalTonnage > 0) { int totalCost = Helper.CalculateTotalForMechPartsCargo(sgs, totalTonnage); double tonnageFraction = storageTons / totalTonnage; storageCost = (int)Math.Ceiling(totalCost * tonnageFraction); } else { double factoredTonnage = Math.Ceiling(storageTons * Mod.Config.PartsFactor); double scaledTonnage = Math.Pow(factoredTonnage, Mod.Config.PartsExponent); storageCost = (int)(Mod.Config.PartsCostPerTon * scaledTonnage); } string costLabel = new Text(Mod.LocalizedText.Tooltips[ModText.LT_Tooltip_Cargo_Chassis], new object[] { SimGameState.GetCBillString(storageCost), storageTons }).ToString(); Text newDetails = new Text(chassisDef.Description.Details + costLabel); Mod.Log.Debug?.Write($" Setting details: {newDetails}u"); ___descriptionText.SetText(newDetails.ToString()); } else { Mod.Log.Debug?.Write($"TP_C:SD - Skipping"); } }
public static bool OnReadyClicked(ChassisDef ___selectedChassis, MechBayPanel ___mechBay , MechBayChassisUnitElement ___chassisElement, MechBayChassisInfoWidget __instance) { if (___selectedChassis == null) { return(false); } var mech = ChassisHandler.GetMech(___selectedChassis.Description.Id); var name = new Text(mech.Description.UIName).ToString(); if (___selectedChassis.MechPartMax == 0) { int value = Mathf.RoundToInt((float)___selectedChassis.Description.Cost * ___mechBay.Sim.Constants.Finances.MechScrapModifier); if (Control.Settings.AllowScrapToParts) { int max = ___mechBay.Sim.Constants.Story.DefaultMechPartMax; int n1 = Mathf.Clamp(Mathf.RoundToInt(max * Control.Settings.MinScrapParts), 1, max); int n2 = Mathf.Clamp(Mathf.RoundToInt(max * Control.Settings.MaxScrapParts), 1, max); GenericPopupBuilder.Create($"Scrap {name}?", $"Do you want scrap this chassis and sale spare parts for <color=#F79B26FF>{SimGameState.GetCBillString(value)}</color> or scrap and keep parts ({n1}-{n2} parts)") .AddButton("Cancel", null, true, null) .AddButton("Keep Parts", () => SplitToParts(___selectedChassis, n1, n2, ___mechBay), true, null) .AddButton("Sale", () => ScrapChassis(1, ___selectedChassis, __instance, ___mechBay), true, null) .CancelOnEscape() .AddFader(new UIColorRef?(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill), 0f, true) .Render(); } else { GenericPopupBuilder.Create($"Scrap {name}?", $"Are you sure you want to scrap this 'Mech Chassis? It will be removed permanently from your inventory.\n\nSCRAP VALUE: < color =#F79B26FF>{SimGameState.GetCBillString(value)}</color>") .AddButton("Cancel", null, true, null) .AddButton("scrap", () => ScrapChassis(1, ___selectedChassis, __instance, ___mechBay), true, null) .CancelOnEscape() .AddFader(new UIColorRef?(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill), 0f, true) .Render(); } } else { int num = ___selectedChassis.MechPartCount; int value = Mathf.RoundToInt((float)___selectedChassis.Description.Cost * ___mechBay.Sim.Constants.Finances.MechScrapModifier) / ___selectedChassis.MechPartMax; if (num == 1) { GenericPopupBuilder.Create($"Scrap {name} part?", $"Are you sure you want to scrap this 'Mech part? It will be removed permanently from your inventory.\n\nSCRAP VALUE: <color=#F79B26FF>{SimGameState.GetCBillString(value)}</color>") .AddButton("Cancel", null, true, null) .AddButton("Scrap", () => ScrapParts(1, ___selectedChassis, __instance, ___mechBay), true, null) .CancelOnEscape().AddFader(new UIColorRef?(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill), 0f, true).Render(); } else { var popup = LazySingletonBehavior <UIManager> .Instance.GetOrCreatePopupModule <SG_Stores_MultiPurchasePopup>(string.Empty); var shopdef = new ShopDefItem(mech.Description.Id, ShopItemType.MechPart, 1, num, true, false, value); popup.SetData(___mechBay.Sim, shopdef, name + " parts", num, value, (n) => ScrapParts(n, ___selectedChassis, __instance, ___mechBay)); } } return(false); }
public static bool Prefix(SGCaptainsQuartersStatusScreen __instance, EconomyScale expenditureLevel, bool showMoraleChange, SimGameState ___simState, SGDifficultyIndicatorWidget ___ExpenditureLevelIndicatorWidget, LocalizableText ___ExpenditureLevelField, LocalizableText ___SectionOneExpenseLevel, LocalizableText ___SectionTwoExpenseLevel, SGFinancialForecastWidget ___FinanceWidget, LocalizableText ___MoraleValueField, SGMoraleBar ___MoralBar, Transform ___SectionOneExpensesList, LocalizableText ___SectionOneExpensesField, LocalizableText ___SectionTwoExpensesField, Transform ___SectionTwoExpensesList, LocalizableText ___EndOfQuarterFunds, LocalizableText ___QuarterOperatingExpenses, LocalizableText ___CurrentFunds, List <LocalizableText> ___ExpenditureLvlBtnMoraleFields, List <LocalizableText> ___ExpenditureLvlBtnCostFields) { if (__instance == null || ___simState == null) { return(true); } float expenditureCostModifier = ___simState.GetExpenditureCostModifier(expenditureLevel); Traverse methodSetField = Traverse.Create(__instance) .Method("SetField", new Type[] { typeof(LocalizableText), typeof(string) }); int expLevel = (int)Traverse.Create(__instance) .Method("GetExpendetureLevelIndexNormalized", new object[] { expenditureLevel }).GetValue(); ___ExpenditureLevelIndicatorWidget.SetDifficulty(expLevel * 2); methodSetField.GetValue(new object[] { ___ExpenditureLevelField, string.Format("{0}", (object)expenditureLevel) }); methodSetField.GetValue(new object[] { ___SectionOneExpenseLevel, string.Format("{0}", (object)expenditureLevel) }); methodSetField.GetValue(new object[] { ___SectionTwoExpenseLevel, string.Format("{0}", (object)expenditureLevel) }); ___FinanceWidget.RefreshData(expenditureLevel); int num1 = ___simState.ExpenditureMoraleValue[expenditureLevel]; methodSetField.GetValue(new object[] { ___MoraleValueField, string.Format("{0}{1}", num1 > 0 ? (object)"+" : (object)"", (object)num1) }); if (showMoraleChange) { int morale = ___simState.Morale; ___MoralBar.ShowMoraleChange(morale, morale + num1); } else { ___MoralBar.ShowCurrentMorale(); } Traverse.Create(__instance).Method("ClearListLineItems", new object[] { ___SectionOneExpensesList }).GetValue(); List <KeyValuePair <string, int> > keyValuePairList = new List <KeyValuePair <string, int> >(); int ongoingUpgradeCosts = 0; string key = ___simState.CurDropship == DropshipType.Leopard ? Strings.T("Bank Loan Interest Payment") : Strings.T("Argo Operating Costs"); int num2 = Mathf.RoundToInt(expenditureCostModifier * (float)___simState.GetShipBaseMaintenanceCost()); keyValuePairList.Add(new KeyValuePair <string, int>(key, num2)); foreach (ShipModuleUpgrade shipUpgrade in ___simState.ShipUpgrades) { float pilotQurikModifier = PilotQuirkManager.Instance.getArgoUpgradeCostModifier(___simState.PilotRoster.ToList(), shipUpgrade.Description.Id, true); float baseCost = (float)shipUpgrade.AdditionalCost * pilotQurikModifier; if (___simState.CurDropship == DropshipType.Argo && Mathf.CeilToInt((float)baseCost * ___simState.Constants.CareerMode.ArgoMaintenanceMultiplier) > 0) { string name = shipUpgrade.Description.Name; int num3 = Mathf.RoundToInt(expenditureCostModifier * (float)Mathf.CeilToInt((float)baseCost * ___simState.Constants.CareerMode.ArgoMaintenanceMultiplier)); keyValuePairList.Add(new KeyValuePair <string, int>(name, num3)); } } foreach (MechDef mechDef in ___simState.ActiveMechs.Values) { string name = mechDef.Name; int num3 = Mathf.RoundToInt(expenditureCostModifier * (float)___simState.Constants.Finances.MechCostPerQuarter); keyValuePairList.Add(new KeyValuePair <string, int>(name, num3)); } keyValuePairList.Sort((Comparison <KeyValuePair <string, int> >)((a, b) => b.Value.CompareTo(a.Value))); keyValuePairList.ForEach((Action <KeyValuePair <string, int> >)(entry => { ongoingUpgradeCosts += entry.Value; methodAddLineItem.Invoke(__instance, new object[] { ___SectionOneExpensesList, entry.Key, SimGameState.GetCBillString(entry.Value) }); })); methodSetField.GetValue(new object[] { ___SectionOneExpensesField, SimGameState.GetCBillString(ongoingUpgradeCosts) }); keyValuePairList.Clear(); Traverse.Create(__instance).Method("ClearListLineItems", new object[] { ___SectionTwoExpensesList }).GetValue(); int ongoingMechWariorCosts = 0; foreach (Pilot pilot in ___simState.PilotRoster) { string displayName = pilot.pilotDef.Description.DisplayName; int num3 = Mathf.CeilToInt(expenditureCostModifier * (float)___simState.GetMechWarriorValue(pilot.pilotDef)); keyValuePairList.Add(new KeyValuePair <string, int>(displayName, num3)); } keyValuePairList.Sort((Comparison <KeyValuePair <string, int> >)((a, b) => b.Value.CompareTo(a.Value))); keyValuePairList.ForEach((Action <KeyValuePair <string, int> >)(entry => { ongoingMechWariorCosts += entry.Value; methodAddLineItem.Invoke(__instance, new object[] { ___SectionTwoExpensesList, entry.Key, SimGameState.GetCBillString(entry.Value) }); })); methodSetField.GetValue(new object[] { ___SectionTwoExpensesField, SimGameState.GetCBillString(ongoingMechWariorCosts) }); methodSetField.GetValue(new object[] { ___EndOfQuarterFunds, SimGameState.GetCBillString(___simState.Funds + ___simState.GetExpenditures(false)) }); methodSetField.GetValue(new object[] { ___QuarterOperatingExpenses, SimGameState.GetCBillString(___simState.GetExpenditures(false)) }); methodSetField.GetValue(new object[] { ___CurrentFunds, SimGameState.GetCBillString(___simState.Funds) }); int index = 0; foreach (KeyValuePair <EconomyScale, int> keyValuePair in ___simState.ExpenditureMoraleValue) { ___ExpenditureLvlBtnMoraleFields[index].SetText(string.Format("{0}", (object)keyValuePair.Value), (object[])Array.Empty <object>()); ___ExpenditureLvlBtnCostFields[index].SetText(SimGameState.GetCBillString(___simState.GetExpenditures(keyValuePair.Key, false)), (object[])Array.Empty <object>()); ++index; } return(false); }
static bool Prefix( string button, SG_Shop_Screen __instance) { shopScreen = __instance; var selectedController = Traverse.Create(shopScreen).Field("selectedController").GetValue <InventoryDataObject_BASE>(); var selectedControllerIsPresent = selectedController != null; var isBuySellButton = button == "Capitalism"; if (!isBuySellButton || !selectedControllerIsPresent) { Logger.Debug($"buysellbutton: {isBuySellButton}\nselectedController: {selectedControllerIsPresent}"); ResetVariables(); return(true); } var simGameState = Traverse.Create(shopScreen).Field("simState").GetValue <SimGameState>(); var isTraveling = simGameState.TravelState != SimGameTravelStatus.IN_SYSTEM; if (isTraveling) { Logger.Debug("traveling, so block buy/sell"); ResetVariables(); return(false); } var shiftHeld = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); var ctrlHeld = Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl); var ctrlAndShiftHeld = shiftHeld && ctrlHeld; Logger.Debug($"shift held: {shiftHeld}\nctrl held: {ctrlHeld}\nctrlshift held: {ctrlAndShiftHeld}"); var isInBuyingState = Traverse.Create(shopScreen).Field("isInBuyingState").GetValue <bool>(); var activeModifierAmounts = new List <int> { ModSettings.CtrlAndShiftKeyCombinationModifierActive&& ctrlAndShiftHeld?ModSettings.CtrlAndShiftKeyCombinationAmount : 0, ModSettings.CtrlKeyModifierActive&& ctrlHeld ? ModSettings.CtrlKeyAmount : 0, ModSettings.ShiftKeyModifierActive&& shiftHeld ? ModSettings.ShiftKeyAmount : 0, 1 // no modifier keys }; var maxModifierAmount = activeModifierAmounts.Max(); // selectedController.RefreshInfo(); var shopDefItem = selectedController.shopDefItem; var quantity = shopDefItem.IsInfinite ? BigNumberForApproxInfinity : selectedController.quantity; Logger.Debug($"raw count: {selectedController.quantity}"); Logger.Debug($"count: {quantity}"); var numberToTrade = new List <int> { maxModifierAmount, quantity }.Min(); Logger.Debug($"how many? {numberToTrade}"); numToBuyOrSell = numberToTrade; var minimumThreshold = simGameState.Constants.Finances.ShopWarnBeforeSellingPriceMinimum; activeModifierAmounts.ForEach(delegate(int amount) { Logger.Debug($"{amount}"); }); Logger.Debug($"max: {numToBuyOrSell}"); Logger.Debug($"threshold: {minimumThreshold}"); if (isInBuyingState) { var cbillValue = simGameState.CurSystem.Shop.GetPrice(shopDefItem, Shop.PurchaseType.Normal); var cbillTotal = cbillValue * numToBuyOrSell; Logger.Debug($"item value: {cbillValue}"); Logger.Debug($"item total: {cbillTotal}"); if (cbillTotal > minimumThreshold && ModSettings.WarnWhenBuyingAbovePriceMinimum) { GenericPopupBuilder. Create("Confirm?", $"Purchase {numToBuyOrSell} for {SimGameState.GetCBillString(cbillTotal)}?"). AddButton("Cancel", null, true, (PlayerAction)null). AddButton("Accept", (Action)BuyCurrent, true, (PlayerAction)null). CancelOnEscape(). AddFader(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill, 0.0f, true). Render(); } else { BuyCurrent(); } return(false); } else { var cbillValue = selectedController.GetCBillValue(); var cbillTotal = cbillValue * numToBuyOrSell; Logger.Debug($"item value: {cbillValue}"); Logger.Debug($"item total: {cbillTotal}"); if (cbillTotal > minimumThreshold && ModSettings.WarnWhenSellingAbovePriceMinimum) { GenericPopupBuilder. Create("Confirm?", $"Sell {numToBuyOrSell} for {SimGameState.GetCBillString(cbillTotal)}?"). AddButton("Cancel", (Action)null, true, (PlayerAction)null). AddButton("Accept", (Action)SellCurrent, true, (PlayerAction)null). CancelOnEscape(). AddFader(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill, 0.0f, true). Render(); } else { SellCurrent(); } return(false); } }
public static void Postfix(SGCaptainsQuartersStatusScreen __instance, EconomyScale expenditureLevel, bool showMoraleChange, Transform ___SectionOneExpensesList, TextMeshProUGUI ___SectionOneExpensesField, SimGameState ___simState) { SimGameState simGameState = UnityGameInstance.BattleTechGame.Simulation; if (__instance == null || ___SectionOneExpensesList == null || ___SectionOneExpensesField == null || simGameState == null) { Mod.Log.Info?.Write($"SGCQSS:RD - skipping"); return; } // TODO: Add this to mech parts maybe? //float expenditureCostModifier = simGameState.GetExpenditureCostModifier(expenditureLevel); Mod.Log.Info?.Write($"SGCQSS:RD - entered. Parsing current keys."); List <KeyValuePair <string, int> > currentKeys = GetCurrentKeys(___SectionOneExpensesList, ___simState); // Extract the active mechs from the list, then re-add the updated price List <KeyValuePair <string, int> > filteredKeys = Helper.FilterActiveMechs(currentKeys, ___simState); List <KeyValuePair <string, int> > activeMechs = Helper.GetUpkeepLabels(___simState); filteredKeys.AddRange(activeMechs); // Add the new costs int activeMechCosts = Helper.CalculateTotalForUpkeep(___simState); double gearInventorySize = Helper.GetGearInventorySize(___simState); int gearStorageCost = Helper.CalculateTotalForGearCargo(___simState, gearInventorySize); string gearLabel = new Text(Mod.LocalizedText.Labels[ModText.LT_Label_Cargo_Gear], new object[] { gearInventorySize }).ToString(); filteredKeys.Add(new KeyValuePair <string, int>(gearLabel, gearStorageCost)); double mechPartsTonnage = Helper.CalculateTonnageForAllMechParts(___simState); int mechPartsStorageCost = Helper.CalculateTotalForMechPartsCargo(___simState, mechPartsTonnage); string mechPartsLabel = new Text(Mod.LocalizedText.Labels[ModText.LT_Label_Cargo_Mech_Parts], new object[] { mechPartsTonnage }).ToString(); filteredKeys.Add(new KeyValuePair <string, int>(mechPartsLabel, mechPartsStorageCost)); filteredKeys.Sort(new ExpensesSorter()); Mod.Log.Info?.Write($"SGCQSS:RD - Clearing items"); ClearListLineItems(___SectionOneExpensesList, ___simState); Mod.Log.Info?.Write($"SGCQSS:RD - Adding listLineItems"); int totalCost = 0; try { foreach (KeyValuePair <string, int> kvp in filteredKeys) { Mod.Log.Info?.Write($"SGCQSS:RD - Adding key: '{kvp.Key}' value: '{kvp.Value}'"); totalCost += kvp.Value; AddListLineItem(___SectionOneExpensesList, ___simState, kvp.Key, SimGameState.GetCBillString(kvp.Value)); } } catch (Exception e) { Mod.Log.Info?.Write($"SGCQSS:RD - failed to add lineItemParts due to: {e.Message}"); } // Update summary costs int newCosts = totalCost; string newCostsS = SimGameState.GetCBillString(newCosts); Mod.Log.Debug?.Write($"SGCQSS:RD - total:{newCosts} = activeMechs:{activeMechCosts} + gearStorage:{gearStorageCost} + partsStorage:{mechPartsStorageCost}"); try { ___SectionOneExpensesField.SetText(SimGameState.GetCBillString(newCosts)); Mod.Log.Debug?.Write($"SGCQSS:RD - updated "); } catch (Exception e) { Mod.Log.Info?.Write($"SGCQSS:RD - failed to update summary costs section due to: {e.Message}"); } }
public static void Postfix(TooltipPrefab_Chassis __instance, object data, TextMeshProUGUI ___descriptionText) { Mod.Log.Debug($"TP_C:SD - Init"); if (data != null && ___descriptionText != null) { ChassisDef chassisDef = (ChassisDef)data; double storageTons = Helper.CalculateChassisTonnage(chassisDef); // Calculate total tonnage costs SimGameState sgs = UnityGameInstance.BattleTechGame.Simulation; double totalTonnage = Helper.CalculateTonnageForAllMechParts(sgs); int storageCost = 0; if (totalTonnage > 0) { int totalCost = Helper.CalculateTotalForMechPartsCargo(sgs, totalTonnage); double tonnageFraction = storageTons / totalTonnage; storageCost = (int)Math.Ceiling(totalCost * tonnageFraction); } else { double factoredTonnage = Math.Ceiling(storageTons * Mod.Config.PartsFactor); double scaledTonnage = Math.Pow(factoredTonnage, Mod.Config.PartsExponent); storageCost = (int)(Mod.Config.PartsCostPerTon * scaledTonnage); } Text newDetails = new Text(chassisDef.Description.Details + $"\n\n<color=#FF0000>Cargo Cost:{SimGameState.GetCBillString(storageCost)} from {storageTons} tons</color>"); Mod.Log.Debug($" Setting details: {newDetails}u"); ___descriptionText.SetText(newDetails.ToString()); } else { Mod.Log.Debug($"TP_C:SD - Skipping"); } }
public static bool Prefix(CombatHUDRetreatEscMenu __instance, HBSDOTweenButton ___RetreatButton, CombatGameState ___Combat, CombatHUD ___HUD) { Mod.Log.Trace?.Write($"CHUDREM:ORBP entered"); Mod.Log.Debug?.Write($" RetreatButton pressed -> withdrawStarted:{ModState.WithdrawStarted} " + $"CurrentRound:{___Combat.TurnDirector.CurrentRound} CanWithdrawOn:{ModState.CanWithdrawOnRound} CanApproachOn:{ModState.CanApproachOnRound}"); if (ModState.WithdrawStarted && ModState.CanWithdrawOnRound == ___Combat.TurnDirector.CurrentRound) { Mod.Log.Debug?.Write($"Checking for combat damage and active enemies"); ModState.CombatDamage = Helper.CalculateCombatDamage(); if (ModState.CombatDamage > 0 && ___Combat.TurnDirector.DoAnyUnitsHaveContactWithEnemy) { int repairCost = (int)Math.Ceiling(ModState.CombatDamage) * Mod.Config.LeopardRepairCostPerDamage; void withdrawAction() { OnImmediateWithdraw(__instance.IsGoodFaithEffort()); } GenericPopupBuilder builder = GenericPopupBuilder.Create(GenericPopupType.Warning, $"Enemies are within weapons range! If you withdraw now the Leopard will take {SimGameState.GetCBillString(repairCost)} worth of damage.") .CancelOnEscape() .AddButton("Cancel") .AddButton("Withdraw", withdrawAction, true, null); builder.IsNestedPopupWithBuiltInFade = true; ___HUD.SelectionHandler.GenericPopup = builder.Render(); return(false); } else { Mod.Log.Info?.Write($" Immediate withdraw due to no enemies"); OnImmediateWithdraw(__instance.IsGoodFaithEffort()); return(false); } } else { return(true); } }
static void Postfix(SGCaptainsQuartersStatusScreen __instance) { try { ReflectionHelper.InvokePrivateMethode(__instance, "ClearListLineItems", new object[] { ReflectionHelper.GetPrivateField(__instance, "SectionOneExpensesList") }); Settings settings = Helper.LoadSettings(); SimGameState simState = (SimGameState)ReflectionHelper.GetPrivateField(__instance, "simState"); float expenditureCostModifier = simState.GetExpenditureCostModifier(simState.ExpenditureLevel); List <KeyValuePair <string, int> > list = new List <KeyValuePair <string, int> >(); int ongoingUpgradeCosts = 0; string key = (simState.CurDropship != DropshipType.Leopard) ? "Argo Operating Costs" : "Bank Loan Interest Payment"; int value = Mathf.RoundToInt(expenditureCostModifier * (float)simState.GetShipBaseMaintenanceCost()); list.Add(new KeyValuePair <string, int>(key, value)); foreach (ShipModuleUpgrade shipModuleUpgrade in simState.ShipUpgrades) { if (simState.CurDropship == DropshipType.Argo && shipModuleUpgrade.AdditionalCost > 0) { string name = shipModuleUpgrade.Description.Name; value = Mathf.RoundToInt(expenditureCostModifier * (float)shipModuleUpgrade.AdditionalCost); list.Add(new KeyValuePair <string, int>(name, value)); } } foreach (MechDef mechDef in simState.ActiveMechs.Values) { key = mechDef.Name; if (settings.CostByTons) { value = Mathf.RoundToInt(expenditureCostModifier * (float)mechDef.Chassis.Tonnage * settings.cbillsPerTon); if (settings.TonsAdditive) { value += Mathf.RoundToInt(expenditureCostModifier * Helper.CalculateCBillValue(mechDef) * settings.PercentageOfMechCost); } } else { value = Mathf.RoundToInt(expenditureCostModifier * Helper.CalculateCBillValue(mechDef) * settings.PercentageOfMechCost); } list.Add(new KeyValuePair <string, int>(key, value)); } list.Sort((KeyValuePair <string, int> a, KeyValuePair <string, int> b) => b.Value.CompareTo(a.Value)); list.ForEach(delegate(KeyValuePair <string, int> entry) { ongoingUpgradeCosts += entry.Value; ReflectionHelper.InvokePrivateMethode(__instance, "AddListLineItem", new object[] { ReflectionHelper.GetPrivateField(__instance, "SectionOneExpensesList"), entry.Key, SimGameState.GetCBillString(entry.Value) }); }); ReflectionHelper.InvokePrivateMethode(__instance, "SetField", new object[] { ReflectionHelper.GetPrivateField(__instance, "SectionOneExpensesField"), SimGameState.GetCBillString(ongoingUpgradeCosts) }, new Type[] { typeof(TextMeshProUGUI), typeof(string) }); } catch (Exception e) { Logger.LogError(e); } }
static void Postfix(SGCaptainsQuartersStatusScreen __instance) { try { SimGameState simState = (SimGameState)AccessTools.Field(typeof(SGCaptainsQuartersStatusScreen), "simState").GetValue(__instance); if (Fields.Deployment && (simState.DayRemainingInQuarter <= Fields.DeploymentRemainingDays)) { ReflectionHelper.InvokePrivateMethode(__instance, "AddListLineItem", new object[] { ReflectionHelper.GetPrivateField(__instance, "SectionOneExpensesList"), "Deployment Salary", SimGameState.GetCBillString(0 - Fields.DeploymentSalary) }); TextMeshProUGUI SectionOneExpensesField = (TextMeshProUGUI)ReflectionHelper.GetPrivateField(__instance, "SectionOneExpensesField"); int newTotal = int.Parse(SectionOneExpensesField.text.Replace("¢", "").Replace(",", "")); ReflectionHelper.InvokePrivateMethode(__instance, "SetField", new object[] { SectionOneExpensesField, SimGameState.GetCBillString(newTotal - Fields.DeploymentSalary) }, new Type[] { typeof(TextMeshProUGUI), typeof(string) }); } Fields.InvertCBills = false; SGFinancialForecastWidget FinanceWidget = (SGFinancialForecastWidget)AccessTools.Field(typeof(SGCaptainsQuartersStatusScreen), "FinanceWidget").GetValue(__instance); FinanceWidget.RefreshData(); TextMeshProUGUI EndOfQuarterFunds = (TextMeshProUGUI)AccessTools.Field(typeof(SGCaptainsQuartersStatusScreen), "EndOfQuarterFunds").GetValue(__instance); TextMeshProUGUI CurrentFunds = (TextMeshProUGUI)AccessTools.Field(typeof(SGCaptainsQuartersStatusScreen), "CurrentFunds").GetValue(__instance); if (simState.GetExpenditures(false) <= 0) { TextMeshProUGUI QuarterOperatingExpenses = (TextMeshProUGUI)AccessTools.Field(typeof(SGCaptainsQuartersStatusScreen), "QuarterOperatingExpenses").GetValue(__instance); UIColorRefTracker BR = QuarterOperatingExpenses.transform.parent.GetComponentsInChildren <UIColorRefTracker>().FirstOrDefault(x => x.name.Equals("BR")); BR.colorRef.UIColor = UIColor.Green; UIColorRefTracker BL = QuarterOperatingExpenses.transform.parent.GetComponentsInChildren <UIColorRefTracker>().FirstOrDefault(x => x.name.Equals("BL")); BL.colorRef.UIColor = UIColor.Green; UIColorRefTracker TL = QuarterOperatingExpenses.transform.parent.GetComponentsInChildren <UIColorRefTracker>().FirstOrDefault(x => x.name.Equals("TL")); TL.colorRef.UIColor = UIColor.Green; UIColorRefTracker TR = QuarterOperatingExpenses.transform.parent.GetComponentsInChildren <UIColorRefTracker>().FirstOrDefault(x => x.name.Equals("TR")); TR.colorRef.UIColor = UIColor.Green; UIColorRefTracker txt_opExpensesLabel = QuarterOperatingExpenses.transform.parent.GetComponentsInChildren <UIColorRefTracker>().FirstOrDefault(x => x.name.Equals("txt_opExpensesLabel")); txt_opExpensesLabel.colorRef.UIColor = UIColor.Green; UIColorRefTracker txt_opExpensesAmmount = QuarterOperatingExpenses.transform.parent.GetComponentsInChildren <UIColorRefTracker>().FirstOrDefault(x => x.name.Equals("txt_opExpensesAmmount")); txt_opExpensesAmmount.colorRef.UIColor = UIColor.Green; } ReflectionHelper.InvokePrivateMethode(__instance, "SetField", new object[] { EndOfQuarterFunds, SimGameState.GetCBillString(simState.Funds + simState.GetExpenditures(false)) }, new Type[] { typeof(TextMeshProUGUI), typeof(string) }); ReflectionHelper.InvokePrivateMethode(__instance, "SetField", new object[] { CurrentFunds, SimGameState.GetCBillString(simState.Funds) }, new Type[] { typeof(TextMeshProUGUI), typeof(string) }); } catch (Exception e) { Logger.LogError(e); } }
public static void Postfix(TooltipPrefab_Weapon __instance, object data, TextMeshProUGUI ___body) { Mod.Log.Debug($"TP_W:SD - Init - data:{data} body:{___body}"); SimGameState sgs = UnityGameInstance.BattleTechGame.Simulation; if (data != null && ___body != null && sgs != null) { WeaponDef weaponDef = (WeaponDef)data; float weaponStorageSize = Helper.CalculateGearStorageSize(weaponDef); // Calculate total gear storage size double totalSize = Helper.GetGearInventorySize(sgs); int storageCost = 0; if (totalSize > 0) { // Handle exponentiation of cost int totalCost = Helper.CalculateTotalForGearCargo(sgs, totalSize); double sizeFraction = weaponStorageSize / totalSize; storageCost = (int)Math.Ceiling(totalCost * sizeFraction); Mod.Log.Debug($" totalCost: {totalCost} storageSize: {weaponStorageSize} sizeFraction: {sizeFraction} fractionalCost: {storageCost}"); } else { // Assume no exponentiation when there is no gear double factoredSize = Math.Ceiling(weaponStorageSize * Mod.Config.GearFactor); double scaledUnits = Math.Pow(factoredSize, Mod.Config.GearExponent); storageCost = (int)(Mod.Config.GearCostPerUnit * scaledUnits); Mod.Log.Info($" totalUnits:{weaponStorageSize} x factor:{Mod.Config.GearFactor} = {factoredSize}"); } Text newDetails = new Text(weaponDef.Description.Details + $"\n\n<color=#FF0000>Cargo Cost:{SimGameState.GetCBillString(storageCost)} from {weaponStorageSize}u size</color>"); Mod.Log.Debug($" Setting details: {newDetails}u"); ___body.SetText(newDetails.ToString()); } else { Mod.Log.Debug($"TP_W:SD - Skipping"); } }
static bool Prefix(AAR_ContractObjectivesWidget __instance) { try { if (Fields.Deployment) { Settings settings = Helper.LoadSettings(); Contract theContract = (Contract)AccessTools.Field(typeof(AAR_ContractObjectivesWidget), "theContract").GetValue(__instance); foreach (MissionObjectiveResult missionObjectiveResult in theContract.MissionObjectiveResultList) { if (missionObjectiveResult.isPrimary) { foreach (SimGameEventResult result in missionObjectiveResult.simGameEventResultList) { result.Stats = null; } ReflectionHelper.InvokePrivateMethode(__instance, "AddObjective", new object[] { missionObjectiveResult }); } else if (missionObjectiveResult.status == ObjectiveStatus.Succeeded) { int Bonus = Mathf.RoundToInt(settings.BonusPercentage * Fields.DeploymentSalary); string missionObjectiveResultString = "Bonus For Secondary Objective: " + SimGameState.GetCBillString(Bonus); MissionObjectiveResult missionObjectiveResult2 = new MissionObjectiveResult(missionObjectiveResultString, "7facf07a-626d-4a3b-a1ec-b29a35ff1ac0", false, true, ObjectiveStatus.Succeeded, false); ReflectionHelper.InvokePrivateMethode(__instance, "AddObjective", new object[] { missionObjectiveResult2 }); } else { ReflectionHelper.InvokePrivateMethode(__instance, "AddObjective", new object[] { missionObjectiveResult }); } } return(false); } return(true); } catch (Exception e) { Logger.LogError(e); return(true); } }
public static void ShowHoldbackDialog(Contract contract, AAR_SalvageScreen salvageScreen) { List <string> heldbackItemsDesc = new List <string>(); foreach (SalvageDef sDef in ModState.HeldbackParts) { string localItemName = new Text(sDef.Description.Name).ToString(); string localItemAndQuantity = new Text( Mod.Config.DialogText[ModConfig.DT_ITEM_AND_QUANTITY], new object[] { localItemName, sDef.Count } ).ToString(); localItemAndQuantity = AppendExistingPartialCount(localItemAndQuantity, sDef); heldbackItemsDesc.Add(localItemAndQuantity); } string heldbackDescs = " -" + string.Join("\n -", heldbackItemsDesc.ToArray()); List <string> compItemsDesc = new List <string>(); foreach (SalvageDef sDef in ModState.CompensationParts) { string localItemName = new Text(sDef.Description.Name).ToString(); string localItemAndQuantity = new Text( Mod.Config.DialogText[ModConfig.DT_ITEM_AND_QUANTITY], new object[] { localItemName, sDef.Count } ).ToString(); compItemsDesc.Add(localItemAndQuantity); } string compDescs = " -" + string.Join("\n -", compItemsDesc.ToArray()); int acceptRepMod = LootMagnet.Random.Next(Mod.Config.Holdback.ReputationRange[0], Mod.Config.Holdback.ReputationRange[1]); int refuseRepMod = LootMagnet.Random.Next(Mod.Config.Holdback.ReputationRange[0], Mod.Config.Holdback.ReputationRange[1]); int disputeRepMod = LootMagnet.Random.Next(Mod.Config.Holdback.ReputationRange[0], Mod.Config.Holdback.ReputationRange[1]); Mod.Log.Debug($"Reputation modifiers - accept:{acceptRepMod} refuse:{refuseRepMod} dispute:{disputeRepMod}"); Dispute dispute = new Dispute(contract.InitialContractValue, contract.Name); void acceptAction() { AcceptAction(salvageScreen, acceptRepMod); } void refuseAction() { RefuseAction(salvageScreen, refuseRepMod); } void disputeAction() { DisputeAction(contract, salvageScreen, dispute); } string localDialogTitle = new Text(Mod.Config.DialogText[ModConfig.DT_DISPUTE_TITLE]).ToString(); string localDialogText = new Text( Mod.Config.DialogText[ModConfig.DT_DISPUTE_TEXT], new object[] { ModState.Employer, heldbackDescs, compDescs, refuseRepMod, acceptRepMod, SimGameState.GetCBillString(dispute.MRBFees), dispute.SuccessChance, Mod.Config.Holdback.DisputePicks[0], Mod.Config.Holdback.DisputePicks[1], (100 - dispute.SuccessChance), Mod.Config.Holdback.DisputePicks[0], Mod.Config.Holdback.DisputePicks[1], } ).ToString(); string localButtonRefuse = new Text(Mod.Config.DialogText[ModConfig.DT_BUTTON_REFUSE]).ToString(); string localButtonAccept = new Text(Mod.Config.DialogText[ModConfig.DT_BUTTON_ACCEPT]).ToString(); string localButtonDispute = new Text(Mod.Config.DialogText[ModConfig.DT_BUTTON_DISPUTE]).ToString(); GenericPopup gp = GenericPopupBuilder.Create(localDialogTitle, localDialogText) .AddButton(localButtonRefuse, refuseAction, true, null) .AddButton(localButtonAccept, acceptAction, true, null) .AddButton(localButtonDispute, disputeAction, true, null) .Render(); TextMeshProUGUI contentText = (TextMeshProUGUI)Traverse.Create(gp).Field("_contentText").GetValue(); contentText.alignment = TextAlignmentOptions.Left; }
public static bool Shop_Screen_ReceiveButtonPress_Prefix(SG_Shop_Screen __instance, string button, InventoryDataObject_SHOP ___selectedController, bool ___isInBuyingState, SimGameState ___simState) { Mod.Log.Debug($"SG_S_S:RBP entered with button:({button})"); State.Reset(); if (button != "Capitalism" || ___selectedController == null) { return(true); } else { int cBillValue = ___selectedController.GetCBillValue(); if (___isInBuyingState) { Mod.Log.Debug($"SG_S_S:RBP - processing a purchase."); if (___simState.InMechLabStore() && (___selectedController.GetItemType() == MechLabDraggableItemType.StorePart || ___selectedController.GetItemType() == MechLabDraggableItemType.SalvagePart)) { // TODO: Can we handle this better than HBS does? return(false); } Shop shop = ___selectedController.GetShop(); int price = shop.GetPrice(___selectedController.shopDefItem, Shop.PurchaseType.Normal, shop.ThisShopType); if (___selectedController.quantity > 1 || ___selectedController.shopDefItem.IsInfinite) { State.StoreIsBuying = true; if (___selectedController.shopDefItem.IsInfinite) { ___selectedController.quantity = 99; } BuyHelper buyHelper = new BuyHelper(__instance, ___selectedController, ___simState); int maxCanPurchase = (int)Math.Floor(___simState.Funds / (double)price); Mod.Log.Debug($"SG_S_S:RBP - maxCanPurchase:{maxCanPurchase} = funds:{___simState.Funds} / price:{price}."); int popupQuantity = maxCanPurchase < ___selectedController.quantity ? maxCanPurchase : ___selectedController.quantity; Mod.Log.Debug($"SG_S_S:RBP - maxCanPurchase:{maxCanPurchase} controllerQuantity:{___selectedController.quantity} -> popupQuantity:{popupQuantity}."); SG_Stores_MultiPurchasePopup orCreatePopupModule = LazySingletonBehavior <UIManager> .Instance.GetOrCreatePopupModule <SG_Stores_MultiPurchasePopup>(string.Empty); orCreatePopupModule.SetData(___simState, ___selectedController.shopDefItem, ___selectedController.GetName(), popupQuantity, price, buyHelper.BuyMultipleItems); } else { GenericPopupBuilder.Create("Confirm?", Strings.T("Purchase for {0}?", SimGameState.GetCBillString(price))) .AddButton("Cancel") .AddButton("Accept", __instance.BuyCurrentSelection) .CancelOnEscape() .AddFader(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill) .Render(); } } else { Mod.Log.Debug($"SG_S_S:RBP - processing a sale."); State.StoreIsSelling = true; int num = cBillValue; if (___selectedController.quantity > 1) { SG_Stores_MultiPurchasePopup orCreatePopupModule = LazySingletonBehavior <UIManager> .Instance.GetOrCreatePopupModule <SG_Stores_MultiPurchasePopup>(string.Empty); orCreatePopupModule.SetData(___simState, ___selectedController.shopDefItem, ___selectedController.GetName(), ___selectedController.quantity, num, __instance.SoldMultipleItems); } else if (num >= ___simState.Constants.Finances.ShopWarnBeforeSellingPriceMinimum) { GenericPopupBuilder.Create("Confirm?", Strings.T("Sell for {0}?", SimGameState.GetCBillString(num))) .AddButton("Cancel") .AddButton("Accept", __instance.SellCurrentSelection) .CancelOnEscape() .AddFader(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill) .Render(); } else { // Sell a single instance __instance.SellCurrentSelection(); } } return(false); } }