public static void Postfix(
            MechLabLocationWidget __instance,
            MechComponentRef cRef,
            WeaponDef wDef,
            bool isOriginalLocation,
            bool canBeAdded,
            ref LocationDef ___chassisLocationDef)
        {
            try
            {
                if (cRef == null || wDef == null || ___chassisLocationDef.Hardpoints == null)
                {
                    return;
                }

                var hasOmni = ___chassisLocationDef.Hardpoints.Any(x => x.Omni);
                if (hasOmni)
                {
                    __instance.ShowHighlightFrame(true, (!isOriginalLocation) ? ((!canBeAdded) ? UIColor.GoldHalf : UIColor.Gold) : UIColor.Blue);
                }
            }
            catch (Exception e)
            {
                Control.mod.Logger.LogError(e);
            }
        }
Esempio n. 2
0
    private static void ModifyInventorySlots(ref LocationDef locationDef, ChassisLocations location, ValueChange <int> change)
    {
        if (locationDef.Location != location)
        {
            return;
        }

        var newValue = change.Change(locationDef.InventorySlots);

        if (!newValue.HasValue)
        {
            return;
        }

        if (location == ChassisLocations.CenterTorso)
        {
            newValue += MechLabSlotsFeature.settings.TopLeftWidget.Slots +
                        MechLabSlotsFeature.settings.TopRightWidget.Slots;
        }

        var info  = typeof(LocationDef).GetField("InventorySlots");
        var value = Convert.ChangeType(newValue, info.FieldType);
        var box   = (object)locationDef;

        info.SetValue(box, value);
        locationDef = (LocationDef)box;

        Control.Logger.Debug?.Log($"set InventorySlots={locationDef.InventorySlots} on location={location}");
    }
Esempio n. 3
0
        public void MapWith1Hostile()
        {
            _setup.TestMap = (new Map(new SetupOptions
            {
                Initialize = true,


                SectorDefs = new SectorDefs()
            }, this.Game.Write, this.Game.Config));


            var locationDef = new LocationDef(new Coordinate(0, 0), new Coordinate(1, 7));

            //add a ship
            var hostileShip = new Ship(FactionName.Klingon, "ship1", new Sector(locationDef), this.Game.Map, this.Game);

            _setup.TestMap.Regions[0].AddShip(hostileShip, _setup.TestMap.Regions[0].Sectors.Get(new Coordinate(1, 7)));

            var hostiles = _setup.TestMap.Regions.GetHostiles();

            Assert.AreEqual(1, hostiles.Count);

            var firstHostile = _setup.TestMap.Regions.GetHostiles()[0];

            Assert.AreEqual("Sector: 1, 7", firstHostile.Sector.ToString());

            Assert.AreEqual(1, _setup.TestMap.Regions.GetHostiles()[0].Sector.X);
            Assert.AreEqual(7, _setup.TestMap.Regions.GetHostiles()[0].Sector.Y);
        }
        static void Postfix(MechLabLocationWidget __instance, LocationLoadoutDef loadout)
        {
            LocationDef locationDef = ReflectionUtils.GetChassisLocationDef(__instance);

            __instance.currentArmor     = Math.Min(loadout.CurrentArmor, ArmorRules.MaxFrontArmor(locationDef, __instance.loadout, 0));
            __instance.currentRearArmor = Math.Min(loadout.CurrentRearArmor, ArmorRules.MaxRearArmor(locationDef, __instance.loadout, __instance.currentArmor));

            __instance.maxArmor     = ArmorRules.MaxFrontArmor(locationDef, __instance.loadout, __instance.currentRearArmor);
            __instance.maxRearArmor = ArmorRules.MaxRearArmor(locationDef, __instance.loadout, __instance.currentArmor);
            __instance.ModifyArmor(false, 0, false);
        }
Esempio n. 5
0
        internal static void Postfix(
            MechLabLocationWidget __instance,
            ref LocationDef ___chassisLocationDef,

            ref int ___currentBallisticCount,
            ref int ___currentEnergyCount,
            ref int ___currentMissileCount,
            ref int ___currentSmallCount,

            ref int ___totalBallisticHardpoints,
            ref int ___totalEnergyHardpoints,
            ref int ___totalMissileHardpoints,
            ref int ___totalSmallHardpoints,

            ref MechLabHardpointElement[] ___hardpoints,
            ref List <MechLabItemSlotElement> ___localInventory)
        {
            try
            {
                var inventory  = ___localInventory.Select(x => x.ComponentRef.Def);
                var hardpoints = ___chassisLocationDef.Hardpoints;
                if (hardpoints == null)
                {
                    // how can this happen? is this from the properties widget?
                    //Control.mod.Logger.LogDebug($"hardpoints is null in location={__instance.loadout?.Location}");
                    return;
                }

                var calc = new HardpointOmniUsageCalculator(inventory, hardpoints);

                //Control.mod.Logger.Log(calc);

                ___currentBallisticCount = calc.Ballistic.VanillaUsage;
                ___currentEnergyCount    = calc.Energy.VanillaUsage;
                ___currentMissileCount   = calc.Missile.VanillaUsage;
                ___currentSmallCount     = calc.Small.VanillaUsage;

                ___totalBallisticHardpoints = calc.Ballistic.DynamicMax;
                ___totalEnergyHardpoints    = calc.Energy.DynamicMax;
                ___totalMissileHardpoints   = calc.Missile.DynamicMax;
                ___totalSmallHardpoints     = calc.Small.DynamicMax;

                ___hardpoints[0].SetData(calc.Ballistic.CategoryForLocationWidget, calc.Ballistic.HardpointString);
                ___hardpoints[1].SetData(calc.Energy.CategoryForLocationWidget, calc.Energy.HardpointString);
                ___hardpoints[2].SetData(calc.Missile.CategoryForLocationWidget, calc.Missile.HardpointString);
                ___hardpoints[3].SetData(calc.Small.CategoryForLocationWidget, calc.Small.HardpointString);
            }
            catch (Exception e)
            {
                Control.mod.Logger.LogError(e);
            }
        }
        static bool Prefix(MechLabLocationWidget __instance)
        {
            int   mod   = Mathf.FloorToInt(__instance.currentRearArmor) % 5;
            float delta = Math.Min(__instance.currentRearArmor, mod == 0 ? UnityGameInstance.BattleTechGame.MechStatisticsConstants.ARMOR_PER_STEP : mod);

            if (delta > 0)
            {
                LocationDef locationDef = ReflectionUtils.GetChassisLocationDef(__instance);
                __instance.currentRearArmor -= delta;
                __instance.maxArmor          = ArmorRules.MaxFrontArmor(locationDef, __instance.loadout, __instance.currentRearArmor);
                __instance.ModifyArmor(true, 0, true);
            }
            return(false);
        }
Esempio n. 7
0
 public static float MaxFrontArmor(LocationDef locationDef, LocationLoadoutDef loadout, float currentRearArmor)
 {
     if (locationDef.Location == ChassisLocations.Head && Control.settings.HeadMaxArmorOverride != null)
     {
         return(Control.settings.HeadMaxArmorOverride.Value);
     }
     else
     {
         float baseStructure = Control.settings.UseCurrentStructure ? loadout.CurrentInternalStructure : locationDef.InternalStructure;
         float maxFront      = baseStructure * Control.settings.StructureFrontLoadCapacityFactor;
         float maxTotal      = baseStructure * Control.settings.StructureTotalLoadCapacityFactor - currentRearArmor;
         return(Math.Max(0, Math.Min(maxFront, maxTotal)));
     }
 }
Esempio n. 8
0
 private bool parseLocations()
 {
     if (lastToken is CommandToken)
     {
         CommandToken ct = (CommandToken)lastToken;
         if (ct.isLocations())
         {
             if (getNextToken() is LeftBracket)
             {
                 Token num = getNextToken();
                 if (num is NumToken && getNextToken() is RightBracket && getNextToken() is Colon)
                 {
                     int locationsCount = num.toInt();
                     LocationDef.__setLocationsCountDoNotUseOutsideOfParser(locationsCount);
                     for (int i = 0; i < locationsCount; i++)
                     {
                         Token locName = getNextToken();
                         if (locName is NumToken)   // Unnamed location
                         {
                             LocationDef.__setLocationNameDontUseOutsideOfParser(i, "Location " + ((NumToken)locName).toInt());
                         }
                         else if (locName is StringToken)
                         {
                             LocationDef.__setLocationNameDontUseOutsideOfParser(i, ((StringToken)locName).toStringDef().ToString());
                         }
                         else if (locName is CommandToken)
                         {
                             if (((CommandToken)locName).isNoLocation())
                             {
                                 LocationDef.__setLocationNameDontUseOutsideOfParser(i, "No Location");
                             }
                             else
                             {
                                 throw new NotImplementedException();
                             }
                         }
                         else
                         {
                             throw new NotImplementedException();
                         }
                     }
                     return(true);
                 }
             }
         }
     }
     throw new NotImplementedException();
 }
Esempio n. 9
0
        public static float MaxRearArmor(LocationDef locationDef, LocationLoadoutDef loadout, float currentFrontArmor)
        {
            float baseStructure = Control.settings.UseCurrentStructure ? loadout.CurrentInternalStructure : locationDef.InternalStructure;
            float maxRear;

            if (locationDef.Location == ChassisLocations.CenterTorso || locationDef.Location == ChassisLocations.LeftTorso || locationDef.Location == ChassisLocations.RightTorso)
            {
                maxRear = baseStructure * Control.settings.StructureRearLoadCapacityFactor;
            }
            else
            {
                maxRear = 0;
            }
            float maxTotal = baseStructure * Control.settings.StructureTotalLoadCapacityFactor - currentFrontArmor;

            return(Math.Max(0, Math.Min(maxRear, maxTotal)));
        }
Esempio n. 10
0
 /// <summary>
 /// Updates the collection of Location definition objects to be displayed in the area view
 /// </summary>
 /// <returns></returns>
 internal LocationDisplays LocationOverlays(){
     var iconDefs = new LocationDisplays();
     LocationDef icon;
     double xcoord;
     double ycoord;
     foreach( Location location in region.Locations.Values){
         icon = new LocationDef();            
         icon.Description = String.Format("Location {0}", location.Name);
         //set icon coordinates for map display
         var coords = scaleToView(location.Position.XPosition, location.Position.YPosition);
         xcoord = coords.Key;
         ycoord = coords.Value;
         icon.X = xcoord - 6;
         icon.Y = ycoord - 6;
         icon.BackingLocation = location;
         iconDefs.Add(icon);               
     }
     return iconDefs;            
 }
Esempio n. 11
0
 public LocationDef toLocationDef()
 {
     if (this is NumToken)
     {
         int index = this.toInt();
         return(LocationDef.getByIndex(index));
     }
     else if (this is StringToken)
     {
         foreach (LocationDef location in LocationDef.AllLocations)
         {
             if (location.LocationName.Equals(this.content))
             {
                 return(location);
             }
         }
     }
     throw new NotImplementedException();
 }
Esempio n. 12
0
        public void Remove1Hostile()
        {
            _setup.TestMap = (new Map(new SetupOptions
            {
                AddNebulae = false,
                Initialize = true,
                SectorDefs = new SectorDefs()
            }, this.Game.Write, this.Game.Config));

            var locationDef = new LocationDef(new Coordinate(0, 0), new Coordinate(1, 7));

            //add a ship
            var hostileShip = new Ship(FactionName.Klingon, "ship1", new Sector(locationDef), this.Game.Map, this.Game);

            _setup.TestMap.Regions[0].AddShip(hostileShip, _setup.TestMap.Regions[0].Sectors.Get(new Coordinate(1, 7)));

            _setup.TestMap.Regions.RemoveShip(hostileShip.Name);

            Assert.AreEqual(0, _setup.TestMap.Regions.GetHostiles().Count);
        }
Esempio n. 13
0
        internal static void ModifyInventorySlots(ref LocationDef locationDef, ChassisLocations location, int currentSlots, int newSlots)
        {
            if (locationDef.Location != location)
            {
                return;
            }

            if (locationDef.InventorySlots != currentSlots)
            {
                return;
            }

            var info  = typeof(LocationDef).GetField("InventorySlots");
            var value = Convert.ChangeType(newSlots, info.FieldType);
            var box   = (object)locationDef;

            info.SetValue(box, value);
            locationDef = (LocationDef)box;

            //Control.mod.Logger.LogDebug("ModifyInventorySlots InventorySlots=" + locationDef.InventorySlots);
        }
        private static void ModifyInventorySlots(ref LocationDef locationDef, ChassisLocations location, ValueChange <int> change)
        {
            if (locationDef.Location != location)
            {
                return;
            }

            var newValue = change.Change(locationDef.InventorySlots);

            if (newValue < 1)
            {
                return;
            }

            var info  = typeof(LocationDef).GetField("InventorySlots");
            var value = Convert.ChangeType(newValue, info.FieldType);
            var box   = (object)locationDef;

            info.SetValue(box, value);
            locationDef = (LocationDef)box;

            //Control.mod.Logger.LogDebug("ModifyInventorySlots InventorySlots=" + locationDef.InventorySlots);
        }
Esempio n. 15
0
        public static void CritComponentInLocations(this AbstractActor target, ActivatableComponent activatable, MechComponent component)
        {
            List <MechComponent> components = new List <MechComponent>();
            Mech          mech             = target as Mech;
            Vehicle       vehicle          = target as Vehicle;
            Turret        turret           = target as Turret;
            HashSet <int> affectedLocation = new HashSet <int>();

            if (mech != null)
            {
                if (mech.FakeVehicle() == false)
                {
                    foreach (ChassisLocations loc in activatable.FailCritLocations)
                    {
                        LocationDef locDef = mech.MechDef.Chassis.GetLocationDef(loc);
                        if ((locDef.InternalStructure <= 1.0f) && (locDef.MaxArmor == 0f))
                        {
                            continue;
                        }
                        affectedLocation.Add((int)loc);
                    }
                }
                else
                {
                    foreach (VehicleChassisLocations vloc in activatable.FailCritVehicleLocations)
                    {
                        ChassisLocations loc    = vloc.FakeVehicleLocation();
                        LocationDef      locDef = mech.MechDef.Chassis.GetLocationDef(loc);
                        if ((locDef.InternalStructure <= 1.0f) && (locDef.MaxArmor <= 0f))
                        {
                            continue;
                        }
                        affectedLocation.Add((int)loc);
                    }
                }
            }
            else if (vehicle != null)
            {
                foreach (VehicleChassisLocations vloc in activatable.FailCritVehicleLocations)
                {
                    VehicleLocationDef locDef = vehicle.VehicleDef.Chassis.GetLocationDef(vloc);
                    if ((locDef.InternalStructure <= 1.0f) && (locDef.MaxArmor <= 0f))
                    {
                        continue;
                    }
                    affectedLocation.Add((int)vloc);
                }
            }
            else if (turret != null)
            {
                affectedLocation.Add((int)BuildingLocation.Structure);
            }
            if (activatable.FailDamageToInstalledLocation)
            {
                affectedLocation.Add(component.Location);
            }
            HashSet <string> excludeTags = new HashSet <string>();
            HashSet <string> onlyTags    = new HashSet <string>();

            foreach (string tag in activatable.FailCritExcludeComponentsTags)
            {
                excludeTags.Add(tag);
            }
            foreach (string tag in activatable.FailCritOnlyComponentsTags)
            {
                onlyTags.Add(tag);
            }
            Log.Debug?.TWL(0, "CritComponentsInLocations:" + target.DisplayName);
            foreach (int loc in affectedLocation)
            {
                List <MechComponent> locComps = target.GetComponentsInLocation(loc, excludeTags, onlyTags);
                components.AddRange(locComps);
            }
            for (int t = 0; t < components.Count; ++t)
            {
                Log.Debug?.WL(1, "[" + t + "]" + components[t].defId + " location:" + components[t].Location);
            }
            int           slotRoll = Random.Range(0, components.Count);
            MechComponent critComp = components[slotRoll];
            WeaponHitInfo fakeHit  = new WeaponHitInfo(-1, -1, -1, -1, target.GUID, target.GUID, 1, null, null, null, null, null, null, null, null, null, null, null);

            fakeHit.toHitRolls = new float[1] {
                1.0f
            };
            fakeHit.locationRolls = new float[1] {
                1.0f
            };
            fakeHit.dodgeRolls = new float[1] {
                0.0f
            };
            fakeHit.dodgeSuccesses = new bool[1] {
                false
            };
            fakeHit.hitLocations = new int[1] {
                critComp.Location
            };
            fakeHit.hitVariance = new int[1] {
                0
            };
            fakeHit.hitQualities = new AttackImpactQuality[1] {
                AttackImpactQuality.Solid
            };
            fakeHit.attackDirections = new AttackDirection[1] {
                AttackDirection.FromArtillery
            };
            fakeHit.hitPositions = new Vector3[1] {
                target.GameRep.GetHitPosition(critComp.Location)
            };
            fakeHit.secondaryTargetIds = new string[1] {
                null
            };
            fakeHit.secondaryHitLocations = new int[1] {
                0
            };
            critComp.CritComponent(ref fakeHit);
        }
Esempio n. 16
0
        public static void Postfix(ChassisDef __instance)
        {
            try
            {
                if (!Control.settings.HardpointFix.AutoFixChassisDefWeaponHardpointCounts)
                {
                    return;
                }

                var hardpointDataDef = __instance.HardpointDataDef;
                if (hardpointDataDef == null)
                {
                    return;
                }

                if (ChassisDefLocationsLocationsCache.ContainsKey(__instance.Description.Id))
                {
                    return;
                }

                var hardpointCounts = new Dictionary <ChassisLocations, HardpointCounter>();
                foreach (var hardpointData in hardpointDataDef.HardpointData)
                {
                    var location = VHLUtils.GetLocationByString(hardpointData.location);
                    var counter  = new HardpointCounter(hardpointData.weapons);
                    hardpointCounts[location] = counter;
                }

                var adapter             = new ChassisDefAdapter(__instance);
                var chassisLocationDefs = adapter.Locations;
                for (var i = 0; i < chassisLocationDefs.Length; i++)
                {
                    var            locationDef = chassisLocationDefs[i];
                    HardpointDef[] hardpointDefs;
                    if (hardpointCounts.ContainsKey(locationDef.Location))
                    {
                        var counter = hardpointCounts[locationDef.Location];
                        hardpointDefs = counter.HardpointsDefs;
                    }
                    else
                    {
                        hardpointDefs = new HardpointDef[0];
                    }

                    chassisLocationDefs[i] = new LocationDef(
                        hardpointDefs,
                        locationDef.Location,
                        locationDef.Tonnage,
                        locationDef.InventorySlots,
                        locationDef.MaxArmor,
                        locationDef.MaxRearArmor,
                        locationDef.InternalStructure
                        );
                }

                ChassisDefLocationsLocationsCache[__instance.Description.Id] = chassisLocationDefs;

                adapter.refreshLocationReferences();
            }
            catch (Exception e)
            {
                Control.mod.Logger.LogError(e);
            }
        }
Esempio n. 17
0
            public static bool Prefix(MechBayPanel __instance, MechBayMechUnitElement mechElement)
            {
                Logger.LogDebug("We are repairing, yes?");
                Logger.Log("We are repairing, yes?");
                if (!Core.Settings.RepairRearm)
                {
                    return(true);
                }

                var     sim     = UnityGameInstance.BattleTechGame.Simulation;
                MechDef mechDef = mechElement.MechDef;
                WorkOrderEntry_MechLab workOrderEntry_MechLab = __instance.Sim.GetWorkOrderEntryForMech(mechDef);
                bool flag = false;

                for (int i = 0; i < mechDef.Inventory.Length; i++)
                {
                    MechComponentRef mechComponentRef = mechDef.Inventory[i];
                    if (mechComponentRef.DamageLevel != ComponentDamageLevel.Functional && mechComponentRef.DamageLevel
                        != ComponentDamageLevel.Installing && !MechValidationRules.MechComponentUnderMaintenance(mechComponentRef, MechValidationLevel.MechLab, workOrderEntry_MechLab))
                    {
                        flag = true;
                        break;
                    }
                }
                if (!mechDef.IsDamaged && !flag)
                {
                    return(false);
                }
                List <ChassisLocations> list = new List <ChassisLocations>();

                __instance.pendingWorkOrderNew = false;
                __instance.pendingWorkOrderEntriesToAdd.Clear();
                if (workOrderEntry_MechLab == null)
                {
                    workOrderEntry_MechLab = new WorkOrderEntry_MechLab(WorkOrderType.MechLabGeneric, "MechLab-BaseWorkOrder", Strings.T("Modify 'Mech - {0}", new object[]
                    {
                        mechDef.Description.Name
                    }), mechDef.GUID, 0, Strings.T(__instance.Sim.Constants.Story.GeneralMechWorkOrderCompletedText, new object[]
                    {
                        mechDef.Description.Name
                    }));
                    workOrderEntry_MechLab.SetMechDef(mechDef);
                    __instance.pendingWorkOrderNew = true;
                }
                __instance.pendingWorkOrder = workOrderEntry_MechLab;
                if (!MechValidationRules.MechStructureUnderMaintenance(ChassisLocations.Head, MechValidationLevel.MechLab, workOrderEntry_MechLab) && mechDef.Head.CurrentInternalStructure < mechDef.Chassis.Head.InternalStructure)
                {
                    list.Add(ChassisLocations.Head);
                }
                if (!MechValidationRules.MechStructureUnderMaintenance(ChassisLocations.CenterTorso, MechValidationLevel.MechLab, workOrderEntry_MechLab) && mechDef.CenterTorso.CurrentInternalStructure < mechDef.Chassis.CenterTorso.InternalStructure)
                {
                    list.Add(ChassisLocations.CenterTorso);
                }
                if (!MechValidationRules.MechStructureUnderMaintenance(ChassisLocations.LeftTorso, MechValidationLevel.MechLab, workOrderEntry_MechLab) && mechDef.LeftTorso.CurrentInternalStructure < mechDef.Chassis.LeftTorso.InternalStructure)
                {
                    list.Add(ChassisLocations.LeftTorso);
                }
                if (!MechValidationRules.MechStructureUnderMaintenance(ChassisLocations.RightTorso, MechValidationLevel.MechLab, workOrderEntry_MechLab) && mechDef.RightTorso.CurrentInternalStructure < mechDef.Chassis.RightTorso.InternalStructure)
                {
                    list.Add(ChassisLocations.RightTorso);
                }
                if (!MechValidationRules.MechStructureUnderMaintenance(ChassisLocations.LeftLeg, MechValidationLevel.MechLab, workOrderEntry_MechLab) && mechDef.LeftLeg.CurrentInternalStructure < mechDef.Chassis.LeftLeg.InternalStructure)
                {
                    list.Add(ChassisLocations.LeftLeg);
                }
                if (!MechValidationRules.MechStructureUnderMaintenance(ChassisLocations.RightLeg, MechValidationLevel.MechLab, workOrderEntry_MechLab) && mechDef.RightLeg.CurrentInternalStructure < mechDef.Chassis.RightLeg.InternalStructure)
                {
                    list.Add(ChassisLocations.RightLeg);
                }
                if (!MechValidationRules.MechStructureUnderMaintenance(ChassisLocations.LeftArm, MechValidationLevel.MechLab, workOrderEntry_MechLab) && mechDef.LeftArm.CurrentInternalStructure < mechDef.Chassis.LeftArm.InternalStructure)
                {
                    list.Add(ChassisLocations.LeftArm);
                }
                if (!MechValidationRules.MechStructureUnderMaintenance(ChassisLocations.RightArm, MechValidationLevel.MechLab, workOrderEntry_MechLab) && mechDef.RightArm.CurrentInternalStructure < mechDef.Chassis.RightArm.InternalStructure)
                {
                    list.Add(ChassisLocations.RightArm);
                }
                if (list.Count < 1 && !flag)
                {
                    GenericPopupBuilder.Create("Repair Already Ordered", string.Format("A repair order has already been queued for " +
                                                                                       "{0}", mechDef.Name)).AddFader(new UIColorRef?(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill), 0f, true).Render();
                    __instance.OnRepairAllCancelled();
                    return(false);
                }
                int num  = 0;
                int num2 = 0;

                for (int j = 0; j < list.Count; j++)
                {
                    LocationDef        chassisLocationDef = mechDef.GetChassisLocationDef(list[j]);
                    LocationLoadoutDef locationLoadoutDef = mechDef.GetLocationLoadoutDef(list[j]);
                    int structureCount = Mathf.RoundToInt(Mathf.Max(0f, chassisLocationDef.InternalStructure - locationLoadoutDef.CurrentInternalStructure));
                    WorkOrderEntry_RepairMechStructure workOrderEntry_RepairMechStructure = __instance.Sim.CreateMechRepairWorkOrder(mechDef.GUID, list[j], structureCount);
                    __instance.pendingWorkOrderEntriesToAdd.Add(workOrderEntry_RepairMechStructure);
                    num  += workOrderEntry_RepairMechStructure.GetCost();
                    num2 += workOrderEntry_RepairMechStructure.GetCBillCost();
                }
                StringBuilder stringBuilder = new StringBuilder();
                int           num3          = 0;

                for (int k = 0; k < mechDef.Inventory.Length; k++)
                {
                    MechComponentRef mechComponentRef2 = mechDef.Inventory[k];
                    if (string.IsNullOrEmpty(mechComponentRef2.SimGameUID))
                    {
                        mechComponentRef2.SetSimGameUID(__instance.Sim.GenerateSimGameUID());
                    }
                    if (mechComponentRef2.DamageLevel == ComponentDamageLevel.Destroyed)
                    {
                        if (num3 < 1)
                        {
                            stringBuilder.Append("\n\nThe following components have been Destroyed. If you continue with the Repair, " +
                                                 "replacement Components will NOT be installed. If you want to replace them with identical or " +
                                                 "different Components, you must Refit the 'Mech.\n\n");
                        }
                        if (num3 < 5)
                        {
                            stringBuilder.Append(mechComponentRef2.MountedLocation.ToString());
                            stringBuilder.Append(": ");
                            stringBuilder.Append(mechComponentRef2.Def.Description.Name);
                            stringBuilder.Append("\n");
                        }
                        num3++;
                        WorkOrderEntry_InstallComponent workOrderEntry_InstallComponent = sim.CreateComponentInstallWorkOrder(__instance.selectedMech.MechDef.GUID,
                                                                                                                              mechComponentRef2, ChassisLocations.None, mechComponentRef2.MountedLocation);
                        __instance.pendingWorkOrderEntriesToAdd.Insert(0, workOrderEntry_InstallComponent);
                        num  += workOrderEntry_InstallComponent.GetCost();
                        num2 += workOrderEntry_InstallComponent.GetCBillCost();
                    }
                    else if (mechComponentRef2.DamageLevel != ComponentDamageLevel.Functional && mechComponentRef2.DamageLevel != ComponentDamageLevel.Installing)
                    {
                        WorkOrderEntry_RepairComponent workOrderEntry_RepairComponent = __instance.Sim.CreateComponentRepairWorkOrder(mechComponentRef2, true);
                        __instance.pendingWorkOrderEntriesToAdd.Add(workOrderEntry_RepairComponent);
                        num  += workOrderEntry_RepairComponent.GetCost();
                        num2 += workOrderEntry_RepairComponent.GetCBillCost();
                    }
                }

                foreach (var foo in __instance.pendingWorkOrderEntriesToAdd)
                {
                    Logger.LogDebug(foo.ID);
                }
                Logger.LogDebug("Armor Repair Section");
                float armorLoss = 1;
                bool  armorTag  = false;

                foreach (var tag in mechDef.MechTags)
                {
                    Logger.LogDebug(tag);
                    if (tag.StartsWith("XLRPArmor"))
                    {
                        armorTag = true;
                        string[] parsedString = tag.Split('_');
                        armorLoss = float.Parse(parsedString[1]);
                    }
                    Logger.LogDebug(armorLoss.ToString());
                }
                if (armorTag)
                {
                    if (!mechDef.MechTags.Contains("XLRP_Armor_Repairing"))
                    {
                        mechDef.MechTags.Add("XLRP_Armor_Repairing");
                    }
                    int brokenArmor = (int)((1 - armorLoss) * mechDef.MechDefAssignedArmor);
                    int frontArmor  = (int)(mechDef.MechDefAssignedArmor - mechDef.CenterTorso.AssignedRearArmor -
                                            mechDef.LeftTorso.AssignedRearArmor - mechDef.RightTorso.AssignedRearArmor);
                    int rearArmor = (int)(mechDef.CenterTorso.AssignedRearArmor +
                                          mechDef.LeftTorso.AssignedRearArmor + mechDef.RightTorso.AssignedRearArmor);
                    Logger.LogDebug($"brokenAmor: {brokenArmor}, frontArmor: {frontArmor}, rearArmor: {rearArmor}");
                    WorkOrderEntry_ModifyMechArmor subEntry = sim.CreateMechArmorModifyWorkOrder(__instance.selectedMech.MechDef.GUID,
                                                                                                 ChassisLocations.All, brokenArmor, frontArmor, rearArmor);

                    __instance.pendingWorkOrderEntriesToAdd.Add(subEntry);
                    num  += subEntry.GetCost();
                    num2 += subEntry.GetCBillCost();
                }

                num = Mathf.Max(1, Mathf.CeilToInt((float)num / (float)__instance.Sim.MechTechSkill));
                if (num3 > 5)
                {
                    stringBuilder.Append(Strings.T("...\nAnd {0} additional destroyed components.\n", new object[]
                    {
                        num3 - 5
                    }));
                }
                string body = Strings.T("Repairing {0} will cost {1:n0} C-Bills and take {2} Days.{3}\n\nProceed?", new object[]
                {
                    mechDef.Name,
                    num2,
                    num,
                    stringBuilder.ToString()
                });

                GenericPopupBuilder.Create("Repair 'Mech?", body).AddButton("Cancel", new Action(__instance.OnRepairAllCancelled), true, null).
                AddButton("Repair", new Action(__instance.OnRepairAllAccepted), true, null).AddFader(new UIColorRef?(LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.PopupBackfill), 0f, true).Render();
                return(false);
            }
Esempio n. 18
0
        public static void ArmorDamage(this AbstractActor target, ActivatableComponent activatable, MechComponent component)
        {
            Mech          mech             = target as Mech;
            Vehicle       vehicle          = target as Vehicle;
            Turret        turret           = target as Turret;
            HashSet <int> affectedLocation = new HashSet <int>();

            if (mech != null)
            {
                if (mech.FakeVehicle() == false)
                {
                    foreach (ChassisLocations loc in activatable.FailCritLocations)
                    {
                        LocationDef locDef = mech.MechDef.Chassis.GetLocationDef(loc);
                        if ((locDef.InternalStructure <= 1.0f) && (locDef.MaxArmor == 0f))
                        {
                            continue;
                        }
                        affectedLocation.Add((int)loc);
                    }
                }
                else
                {
                    foreach (VehicleChassisLocations vloc in activatable.FailCritVehicleLocations)
                    {
                        ChassisLocations loc    = vloc.FakeVehicleLocation();
                        LocationDef      locDef = mech.MechDef.Chassis.GetLocationDef(loc);
                        if ((locDef.InternalStructure <= 1.0f) && (locDef.MaxArmor <= 0f))
                        {
                            continue;
                        }
                        affectedLocation.Add((int)loc);
                    }
                }
            }
            else if (vehicle != null)
            {
                foreach (VehicleChassisLocations vloc in activatable.FailCritVehicleLocations)
                {
                    VehicleLocationDef locDef = vehicle.VehicleDef.Chassis.GetLocationDef(vloc);
                    if ((locDef.InternalStructure <= 1.0f) && (locDef.MaxArmor <= 0f))
                    {
                        continue;
                    }
                    affectedLocation.Add((int)vloc);
                }
            }
            else if (turret != null)
            {
                affectedLocation.Add((int)BuildingLocation.Structure);
            }
            if (activatable.FailDamageToInstalledLocation)
            {
                affectedLocation.Add(component.Location);
            }
            HashSet <string> excludeTags = new HashSet <string>();
            HashSet <string> onlyTags    = new HashSet <string>();

            foreach (string tag in activatable.FailCritExcludeComponentsTags)
            {
                excludeTags.Add(tag);
            }
            foreach (string tag in activatable.FailCritOnlyComponentsTags)
            {
                onlyTags.Add(tag);
            }
            target.ArmorDamage(affectedLocation.ToList(), activatable.FailArmorDamage, activatable.FailCrit, excludeTags, onlyTags);
        }
            public static void Postfix(
                MechLabLocationWidget __instance,
                MechComponentDef newComponentDef,
                MechLabPanel ___mechLab,
                LocationDef ___chassisLocationDef,
                List <MechLabItemSlotElement> ___localInventory,
                TextMeshProUGUI ___locationName,
                ref bool __result)
            {
                try
                {
                    if (__result)
                    {
                        ChassisLocations location           = ___chassisLocationDef.Location;
                        MechDef          mechDef            = ___mechLab.activeMechDef;
                        HardpointInfo    stockHardpointInfo = GetStockHardpointsByLocation(mechDef, location);
                        HardpointInfo    localHardpointInfo = ___localInventory
                                                              .Select(x => x.ComponentRef.Def)
                                                              .Concat(new[] { newComponentDef })
                                                              .Select(x => new HardpointInfo(x))
                                                              .Aggregate((x, y) => x + y);

                        _harmonyManager.DebugLog("Hardpoint info: " + localHardpointInfo.NumMissileTubes + ", " +
                                                 stockHardpointInfo.NumMissileTubes + ", " +
                                                 localHardpointInfo.NumEnergyLarge + ", " +
                                                 stockHardpointInfo.NumEnergyLarge);

                        if (localHardpointInfo.NumMissileTubes > stockHardpointInfo.NumMissileTubes)
                        {
                            __instance.SetDropErrorMessage(
                                "Cannot add {0} to {1}: Over allocated {2}/{3} missile tubes.",
                                newComponentDef.Description.Name,
                                ___locationName.text,
                                localHardpointInfo.NumMissileTubes,
                                stockHardpointInfo.NumMissileTubes);
                            __result = false;
                        }
                        else if (localHardpointInfo.NumEnergyLarge > stockHardpointInfo.NumEnergyLarge)
                        {
                            __instance.SetDropErrorMessage(
                                "Cannot add {0} to {1}: Over allocated {2}/{3} large energy weapons.",
                                newComponentDef.Description.Name,
                                ___locationName.text,
                                localHardpointInfo.NumEnergyLarge,
                                stockHardpointInfo.NumEnergyLarge);
                            __result = false;
                        }
                        else
                        {
                            int allowedJumpJets = mechDef.AllowedJumpJets();
                            int currentJumpJets = localHardpointInfo.NumJumpJets;
                            if (currentJumpJets > allowedJumpJets)
                            {
                                __instance.SetDropErrorMessage(
                                    "Cannot add {0} to {1}: Over allocated {2}/{3} jump jets.",
                                    newComponentDef.Description.Name,
                                    ___locationName.text,
                                    localHardpointInfo.NumEnergyLarge,
                                    stockHardpointInfo.NumEnergyLarge);
                                __result = false;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _harmonyManager.Log(e);
                }
            }
Esempio n. 20
0
 public bool parse(ref int lastReadPosition, ref int lastReadPositionEnd)
 {
     LocationDef.__setLocationsCountDoNotUseOutsideOfParser(256); // Safe keeping
     return(parse(false, ref lastReadPosition, ref lastReadPositionEnd));
 }