private static void ProcessParachute(MyObjectBuilder_CubeBlock block, Options options, MyCubeSize size) { // Doesn't have it's own inventory, needs supporting function to add inventory if (!options.Restock) { return; } try { List <MyDefinitionId> parachuteMaterialList = GetItemDefinitionList(block); if (parachuteMaterialList == null) { return; } MyObjectBuilder_Component parachuteMaterial = new MyObjectBuilder_Component { SubtypeName = parachuteMaterialList[0].SubtypeName }; MyPhysicalItemDefinition parachuteMaterialDefinition = MyDefinitionManager.Static.GetPhysicalItemDefinition(parachuteMaterial.GetId()); //AddToInventory(block.ComponentContainer, parachuteMaterial, (int)(GetMaxVolume(block, size) / parachuteMaterialDefinition.Volume)); AddToInventory(block.ComponentContainer, parachuteMaterial, GetAmount(GetMaxVolume(block, size), parachuteMaterialDefinition.Volume), true); } catch (Exception e) { Core.GeneralLog.WriteToLog("MyObjectBuilder_Parachute", $"Exception! {e}"); } }
private readonly int probabilityRangeStart, probabilityRangeEnd; // Start (inclusive) to end (exclusive) private IronComponent(string subtypeId, float ironValue, int probabilityRangeStart, int probabilityRangeEnd) { SubtypeId = subtypeId; IronValue = ironValue; this.probabilityRangeStart = probabilityRangeStart; this.probabilityRangeEnd = probabilityRangeEnd; ObjectBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Component>(subtypeId); }
private void AwardPoints(ZoneBlock zone, IMyFaction faction, int enemies, bool displayHeader) { if (!MyAPIGateway.Multiplayer.IsServer) { return; } string planetName = zone.GetClosestPlanet(); if (!Planets.Any(description => description.Name == planetName)) { PlanetDescription p = new PlanetDescription() { Name = planetName, Scores = new List <ScoreDescription>() }; Planets.Add(p); } long facId = faction.FactionId; PlanetDescription planet = Planets.Find(w => w.Name == planetName); IMyCubeGrid kothGrid = (zone.Entity as IMyCubeBlock).CubeGrid; if (!planet.Scores.Any(s => s.FactionId == facId)) { planet.Scores.Add(new ScoreDescription() { FactionId = facId, FactionName = faction.Name, FactionTag = faction.Tag, Points = 1, PlanetId = planetName, GridName = kothGrid.DisplayName }); } int total = GetTotalScore(planet); ScoreDescription score = planet.Scores.Find(s => s.FactionId == facId); int current = score.Points; int points; if (zone.PointsOnCap.Value == 0) { points = (int)(((float)(total - current) / (float)total) * 5f * enemies) + 1 + enemies; } else { points = zone.PointsOnCap.Value; } planet.Scores.Find(s => s.FactionId == facId).Points += points; zone.PointsEarnedSincePrize += points; if (zone.AwardPointsAsCredits.Value) { faction.RequestChangeBalance(points * zone.CreditsPerPoint.Value); } if (zone.PointsEarnedSincePrize >= zone.PointsForPrize.Value) { zone.PointsEarnedSincePrize -= zone.PointsForPrize.Value; IMyCargoContainer prizebox = null; List <IMySlimBlock> temp = new List <IMySlimBlock>(); kothGrid.GetBlocks(temp, s => { if (prizebox == null && s.FatBlock != null && s.FatBlock is IMyCargoContainer && s.FatBlock.BlockDefinition.SubtypeId == "Prizebox") { prizebox = s.FatBlock as IMyCargoContainer; } return(false); }); if (zone.UseComponentReward.Value) { string prizeType = (zone.AdvancedComponentSelection.Value) ? zone.PrizeComponentSubtypeId.Value : zone.SelectedComponentString.Value; int amount = zone.PrizeAmountComponent.Value; MyDefinitionId definitionId = new MyDefinitionId(typeof(MyObjectBuilder_Component), prizeType); MyObjectBuilder_Component content = (MyObjectBuilder_Component)MyObjectBuilderSerializer.CreateNewObject(definitionId); MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem { Amount = amount, Content = content }; if (zone.SpawnIntoPrizeBox.Value) { if (prizebox == null) { Tools.Log(MyLogSeverity.Error, $"Could not find prize box on grid: {kothGrid.DisplayName} - {kothGrid.EntityId}"); } else if (prizebox.GetInventory().CanItemsBeAdded(amount, definitionId)) { prizebox.GetInventory().AddItems(amount, inventoryItem.Content); } } else { if (zone.Entity.GetInventory().CanItemsBeAdded(amount, definitionId)) { zone.Entity.GetInventory().AddItems(amount, inventoryItem.Content); } } } if (zone.UseIngotReward.Value) { string prizeType = (zone.AdvancedIngotSelection.Value) ? zone.PrizeIngotSubtypeId.Value : zone.SelectedIngotString.Value; int amount = zone.PrizeAmountIngot.Value; MyDefinitionId definitionId = new MyDefinitionId(typeof(MyObjectBuilder_Ingot), prizeType); MyObjectBuilder_Ingot content = (MyObjectBuilder_Ingot)MyObjectBuilderSerializer.CreateNewObject(definitionId); MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem { Amount = amount, Content = content }; if (zone.SpawnIntoPrizeBox.Value) { if (prizebox == null) { Tools.Log(MyLogSeverity.Error, $"Could not find prize box on grid: {kothGrid.DisplayName} - {kothGrid.EntityId}"); } else if (prizebox.GetInventory().CanItemsBeAdded(amount, definitionId)) { prizebox.GetInventory().AddItems(amount, inventoryItem.Content); } } else { if (zone.Entity.GetInventory().CanItemsBeAdded(amount, definitionId)) { zone.Entity.GetInventory().AddItems(amount, inventoryItem.Content); } } } if (zone.UseOreReward.Value) { string prizeType = (zone.AdvancedOreSelection.Value) ? zone.PrizeOreSubtypeId.Value : zone.SelectedOreString.Value; int amount = zone.PrizeAmountOre.Value; MyDefinitionId definitionId = new MyDefinitionId(typeof(MyObjectBuilder_Ore), prizeType); MyObjectBuilder_Ore content = (MyObjectBuilder_Ore)MyObjectBuilderSerializer.CreateNewObject(definitionId); MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem { Amount = amount, Content = content }; if (zone.SpawnIntoPrizeBox.Value) { if (prizebox == null) { Tools.Log(MyLogSeverity.Error, $"Could not find prize box on grid: {kothGrid.DisplayName} - {kothGrid.EntityId}"); } else if (prizebox.GetInventory().CanItemsBeAdded(amount, definitionId)) { prizebox.GetInventory().AddItems(amount, inventoryItem.Content); } } else { if (zone.Entity.GetInventory().CanItemsBeAdded(amount, definitionId)) { zone.Entity.GetInventory().AddItems(amount, inventoryItem.Content); } } } } StringBuilder message = new StringBuilder(); if (displayHeader && zone.IsLocationNamed.Value) { if (zone.EncampmentMode.Value) { message.Append($"{kothGrid.DisplayName} on {planetName} Encampment Payout"); } else { message.Append($"{kothGrid.DisplayName} on {planetName} under attack"); } } byte[] bytes = Encoding.ASCII.GetBytes(message.ToString()); MyAPIGateway.Multiplayer.SendMessageToServer(8008, bytes); Network.Say(message.ToString()); message.Clear(); if (zone.AwardPointsAsCredits.Value) { message.Append($"{faction.Name} Scored {points} Points! ({points * zone.CreditsPerPoint.Value} credits)"); } else { message.Append($"{faction.Name} Scored {points} Points!"); } SaveData(); //NEXUS: if nexus is initialized, broadcast the message to nexus (and all other sectors in that way) //NEXUS: KotH should work normally if nexus is not initialized if (nexusInit) { //NEXUS: sends the message this sector displays in the chat to all the other sectors byte[] nexMessage = Encoding.ASCII.GetBytes(message.ToString()); Nexus.SendMessageToAllServers(nexMessage); //NEXUS: score is broadcasted to other sectors, this basically triggers the save not just on this sector but on all the others with the same score var serializedScore = MyAPIGateway.Utilities.SerializeToBinary <List <PlanetDescription> >(Planets); Nexus2.SendMessageToAllServers(serializedScore); } bytes = Encoding.ASCII.GetBytes(message.ToString()); MyAPIGateway.Multiplayer.SendMessageToServer(8008, bytes); Network.Say(message.ToString()); }
private void UnmountInternal(float unmountAmount, MyConstructionStockpile outputStockpile = null, bool damageItems = false) { // We don't have to update functional state in this function, because it is done in the caller functions. // If you start using this function anywhere else, don't forget to update functional state yourself! float topIntegrity = GetTopComponentIntegrity(); int groupIndex = (int)m_topGroupIndex; int compIndex = (int)m_topComponentIndex; // Continue removing components, until the to be removed component's health is larger than unmountAmount MyObjectBuilder_Component componentBuilder = null; var scrapBuilder = MyFloatingObject.ScrapBuilder; while (unmountAmount * GetDeconstructionEfficiency(groupIndex, damageItems) >= topIntegrity) { Integrity -= topIntegrity; unmountAmount -= topIntegrity; // In creative mode, the outputInventory should normally be null. // However, if we load the game from the realistic mode, it would not be necessarilly null. if (outputStockpile != null && MySession.Static.SurvivalMode) { bool doDamage = damageItems && MyFakes.ENABLE_DAMAGED_COMPONENTS; if (!damageItems || (doDamage && MyRandom.Instance.NextFloat() <= m_blockDefinition.Components[groupIndex].Definition.DropProbability)) { componentBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Component>(); componentBuilder.SubtypeName = m_blockDefinition.Components[groupIndex].Definition.Id.SubtypeName; if (doDamage) { componentBuilder.Flags |= MyItemFlags.Damaged; } if (!outputStockpile.AddItems(1, componentBuilder)) { // TODO: Throw the items into space (although this branch should probably not happen) } } MyComponentDefinition destroyedComponentDefinition = m_blockDefinition.Components[groupIndex].Definition; if (MyFakes.ENABLE_SCRAP && damageItems && (MyRandom.Instance.NextFloat() < destroyedComponentDefinition.DropProbability)) { outputStockpile.AddItems((int)(0.8f * destroyedComponentDefinition.Mass), scrapBuilder); } } compIndex--; if (compIndex < 0) { groupIndex--; if (groupIndex < 0) { SetTopIndex(0, 0); Integrity = 0.0f; return; } else { compIndex = m_blockDefinition.Components[groupIndex].Count - 1; } } topIntegrity = m_blockDefinition.Components[groupIndex].Definition.MaxIntegrity; SetTopIndex(groupIndex, compIndex); } // Damage the remaining component Integrity -= unmountAmount * GetDeconstructionEfficiency(groupIndex, damageItems); topIntegrity -= unmountAmount * GetDeconstructionEfficiency(groupIndex, damageItems); if (topIntegrity < MOUNT_THRESHOLD) { Integrity += MOUNT_THRESHOLD - topIntegrity; topIntegrity = MOUNT_THRESHOLD; } Debug.Assert(Integrity >= MOUNT_THRESHOLD, "Integrity inconsistent after a dismount of component stack"); }
/// <summary> /// Attempts to place count of a physical object in inventory of grid /// Will place as many of the object as possible in each inventory until /// nothing remains to place. Returns number remaining to place. /// </summary> public static int placeInCargo(this IMyCubeGrid grid, SerializableDefinitionId def, MyObjectBuilder_Component builder, int count) { if (count <= 0) { return(0); } int remaining = count; var containers = new List <IMySlimBlock>(); grid.GetBlocks(containers, x => x.FatBlock != null && x.FatBlock as Interfaces.IMyInventoryOwner != null ); if (containers.Count == 0) { return(remaining); } foreach (IMySlimBlock block in containers) { if (remaining == 0) { break; } var inventoryOwner = block.FatBlock as Interfaces.IMyInventoryOwner; var inventory = inventoryOwner.GetInventory(0) as IMyInventory; if (inventory == null) { // log error, invOwner existed but not inventory>? continue; } if (inventory.CanItemsBeAdded((VRage.MyFixedPoint)remaining, def)) { // Add all the items if it has enough space inventory.AddItems(remaining, builder); remaining = 0; } else { // Add them incrementally if there's some space // I would prefer to do some math to tell how many we can add, // instead of just continually looping through with 1. // But the logic to get the volume of a component // is surprisingly complex without access to the Adapter // and we'd need to check the inventory's supported types while (remaining > 0 && inventory.CanItemsBeAdded((VRage.MyFixedPoint) 1, def)) { inventory.AddItems(1, builder); remaining--; } } } return(remaining); }
/// <summary> /// Attempts to place count of a physical object in inventory of grid /// Will place as many of the object as possible in each inventory until /// nothing remains to place. Returns number remaining to place. /// </summary> public static int placeInCargo(this IMyCubeGrid grid, SerializableDefinitionId def, MyObjectBuilder_Component builder, int count) { if (count <= 0) return 0; int remaining = count; var containers = new List<IMySlimBlock>(); grid.GetBlocks(containers, x => x.FatBlock != null && x.FatBlock as Interfaces.IMyInventoryOwner != null ); if (containers.Count == 0) return remaining; foreach (IMySlimBlock block in containers) { if (remaining == 0) break; var inventoryOwner = block.FatBlock as Interfaces.IMyInventoryOwner; var inventory = inventoryOwner.GetInventory(0) as IMyInventory; if (inventory == null) { // log error, invOwner existed but not inventory>? continue; } if (inventory.CanItemsBeAdded((VRage.MyFixedPoint)remaining, def)) { // Add all the items if it has enough space inventory.AddItems(remaining, builder); remaining = 0; } else { // Add them incrementally if there's some space // I would prefer to do some math to tell how many we can add, // instead of just continually looping through with 1. // But the logic to get the volume of a component // is surprisingly complex without access to the Adapter // and we'd need to check the inventory's supported types while (remaining > 0 && inventory.CanItemsBeAdded((VRage.MyFixedPoint)1, def)) { inventory.AddItems(1, builder); remaining--; } } } return remaining; }
/// <summary> /// Starts up the core on the server /// </summary> public override void initialize() { if (MyAPIGateway.Session == null || m_Initialized) return; if (s_Logger == null) s_Logger = new Logger("Conquest Core", "Server"); log("Conquest core (Server) started"); s_TokenBuilder = new MyObjectBuilder_Component() { SubtypeName = "ShipLicense" }; s_TokenDef = new VRage.ObjectBuilders.SerializableDefinitionId( typeof(MyObjectBuilder_InventoryItem), "ShipLicense"); s_Sorter = new GridSorter(); s_Settings = ConquestSettings.getInstance(); s_DelayedSettingWrite = s_Settings.WriteFailed; // Start round timer m_RoundTimer = new MyTimer(s_Settings.CPPeriod * 1000, roundEnd); m_RoundTimer.Start(); log("Round timer started"); // Start save timer m_SaveTimer = new MyTimer(Constants.SaveInterval * 1000, saveTimer); m_SaveTimer.Start(); log("Save timer started"); m_MailMan = new RequestProcessor(); // If the server is a player (non-dedicated) they also need to receive notifications if (!MyAPIGateway.Utilities.IsDedicated) { m_LocalReceiver = new ResponseProcessor(false); m_MailMan.localMsgSent += m_LocalReceiver.incomming; m_CmdProc = new CommandProcessor(m_LocalReceiver); m_CmdProc.initialize(); m_LocalReceiver.requestSettings(); } // Subscribe events GridEnforcer.OnPlacementViolation += eventPlacementViolation; GridEnforcer.OnCleanupViolation += eventCleanupViolation; GridEnforcer.OnCleanupTimerStart += eventCleanupTimerStart; GridEnforcer.OnCleanupTimerEnd += eventCleanupTimerEnd; m_Initialized = true; }