private void PlaceAreaMarker() { Vector3D cameraPos, cameraDir; if (MySession.GetCameraControllerEnum() == Common.ObjectBuilders.MyCameraControllerEnum.ThirdPersonSpectator || MySession.GetCameraControllerEnum() == Common.ObjectBuilders.MyCameraControllerEnum.Entity) { var headMatrix = MySession.ControlledEntity.GetHeadMatrix(true, true); cameraPos = headMatrix.Translation; cameraDir = headMatrix.Forward; } else { cameraPos = MySector.MainCamera.Position; cameraDir = MySector.MainCamera.WorldMatrix.Forward; } List <MyPhysics.HitInfo> hitInfos = new List <MyPhysics.HitInfo>(); MyPhysics.CastRay(cameraPos, cameraPos + cameraDir * 100, hitInfos, MyPhysics.ObjectDetectionCollisionLayer); if (hitInfos.Count == 0) { return; } MyPhysics.HitInfo?closestValidHit = null; foreach (var hitInfo in hitInfos) { var ent = hitInfo.HkHitInfo.GetHitEntity(); if (ent is MyCubeGrid) { closestValidHit = hitInfo; break; } else if (ent is MyVoxelMap) { closestValidHit = hitInfo; break; } } if (closestValidHit.HasValue) { MyAreaMarkerDefinition definition = AreaMarkerDefinition; Debug.Assert(definition != null, "Area marker definition cannot be null!"); if (definition == null) { return; } Vector3D position = closestValidHit.Value.Position; var forward = Vector3D.Reject(cameraDir, Vector3D.Up); if (Vector3D.IsZero(forward)) { forward = Vector3D.Forward; } var positionAndOrientation = new MyPositionAndOrientation(position, Vector3D.Normalize(forward), Vector3D.Up); MyObjectBuilder_AreaMarker objectBuilder = (MyObjectBuilder_AreaMarker)MyObjectBuilderSerializer.CreateNewObject(definition.Id); objectBuilder.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene; objectBuilder.PositionAndOrientation = positionAndOrientation; if (objectBuilder.IsSynced) { MySyncCreate.RequestEntityCreate(objectBuilder); } else { MyAreaMarker flag = MyEntityFactory.CreateEntity <MyAreaMarker>(objectBuilder); flag.Init(objectBuilder); MyEntities.Add(flag); } } }
public virtual void Close() { //Logging.Instance.WriteLine(string.Format("Close")); int pos = 0; try { if (m_performanceFriendly) { /* if (Sync.IsClient) * NaniteConstructionManager.ParticleManager.RemoveParticle(m_cubeEntityId, m_position); * else * m_constructionBlock.SendRemoveParticleEffect(m_cubeEntityId, m_position); */ if (m_isGrinder && m_removed) { TransferRemainingComponents(); Logging.Instance.WriteLine(string.Format("GRINDING completed. Target block: {0} - (EntityID: {1} Elapsed: {2})", m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.GetType().Name : m_targetBlock.GetType().Name, m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.EntityId : 0, m_completeTime + m_waitTime)); } m_completed = true; return; } if (m_constructionBlock != null && m_constructionBlock.ConstructionBlock != null) { var toolInventory = ((MyEntity)m_tool).GetInventory(0); // Since grinding in creative gives no components. Insert hack. if (MyAPIGateway.Session.CreativeMode && m_tool is Sandbox.ModAPI.Ingame.IMyShipGrinder) { MyObjectBuilder_CubeBlock block = (MyObjectBuilder_CubeBlock)m_targetBlock.GetObjectBuilder(); MyCubeBlockDefinition blockDefinition; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDefinition)) { foreach (var item in blockDefinition.Components) { var inventoryItem = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.DeconstructItem.Id); toolInventory.AddItems(item.Count, inventoryItem); } } } if (toolInventory.GetItemsCount() > 0) { TransferFromTarget((MyCubeBlock)m_tool); } } m_completed = true; if (m_tool != null) { m_tool.Enabled = false; } if (!m_toolEntity.Closed) { m_toolEntity.Close(); } } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("Close() {1}: {0}", ex.ToString(), pos)); } }
static MyWorldGenerator() { if (MyFakes.TEST_PREFABS_FOR_INCONSISTENCIES) { string prefabDir = Path.Combine(MyFileSystem.ContentPath, "Data", "Prefabs"); var prefabFiles = Directory.GetFiles(prefabDir); foreach (var prefabFile in prefabFiles) { if (Path.GetExtension(prefabFile) != ".sbc") { continue; } MyObjectBuilder_CubeGrid result = null; var fsPath = Path.Combine(MyFileSystem.ContentPath, prefabFile); MyObjectBuilderSerializer.DeserializeXML <MyObjectBuilder_CubeGrid>(fsPath, out result); if (result == null) { continue; } foreach (var block in result.CubeBlocks) { if (block.IntegrityPercent == 0.0f) { Debug.Assert(false, "Inconsistent block in prefab file " + prefabFile); break; } } } string worldDir = Path.Combine(MyFileSystem.ContentPath, "Worlds"); var worldDirs = Directory.GetDirectories(worldDir); foreach (var dir in worldDirs) { var files = Directory.GetFiles(dir); foreach (var file in files) { if (Path.GetExtension(file) != ".sbs") { continue; } MyObjectBuilder_Sector result = null; var fsPath = Path.Combine(MyFileSystem.ContentPath, file); MyObjectBuilderSerializer.DeserializeXML <MyObjectBuilder_Sector>(fsPath, out result); Debug.Assert(result != null, "Unloadable world: " + file); foreach (var obj in result.SectorObjects) { if (obj.TypeId == typeof(MyObjectBuilder_CubeGrid)) { var grid = (MyObjectBuilder_CubeGrid)obj; foreach (var block in grid.CubeBlocks) { if (block.IntegrityPercent == 0.0f) { Debug.Assert(false, "Inconsistent block in save " + file); break; } } } } } } } }
public static MyEntity SpawnRandomLarge(Vector3 position, Vector3 direction) { MyPhysicalInventoryItem i = new MyPhysicalInventoryItem(400 * (MyFixedPoint)MyUtils.GetRandomFloat(0f, 25f), MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone")); return(Spawn(ref i, position, direction * (MIN_SPEED + MyUtils.GetRandomInt(MIN_SPEED / 2)))); }
private static void SendWorldData(ulong steamId) { try { MemoryStream ms = new MemoryStream( ); if (MyAPIGateway.Session != null) { DateTime start = DateTime.Now; ApplicationLog.BaseLog.Info("...responding to user: {0}", steamId); SendPreamble(steamId, 1); SendFlush(steamId); // Let's sleep for 5 seconds and let plugins know we're online -- let's not after all, causing sync issues //Thread.Sleep(5000); MyObjectBuilder_World myObjectBuilderWorld = null; lock ( m_inGame ) { if (!m_inGame.Contains(steamId)) { ApplicationLog.BaseLog.Info("Cancelled send to user: {0}", steamId); return; } } // This is probably safe to do outside of the game instance, but let's just make sure. SandboxGameAssemblyWrapper.Instance.GameAction(() => { myObjectBuilderWorld = MyAPIGateway.Session.GetWorld( ); }); if (replaceData) { for (int r = myObjectBuilderWorld.Sector.SectorObjects.Count - 1; r >= 0; r--) { MyObjectBuilder_EntityBase entity = (MyObjectBuilder_EntityBase)myObjectBuilderWorld.Sector.SectorObjects[r]; if (!(entity is MyObjectBuilder_CubeGrid) && !(entity is MyObjectBuilder_VoxelMap) && !(entity is MyObjectBuilder_Character)) { continue; } if ((entity is MyObjectBuilder_CubeGrid) && ((MyObjectBuilder_CubeGrid)entity).DisplayName.Contains("CommRelay")) { continue; } /* * if (!(entity is MyObjectBuilder_CubeGrid)) * continue; * * if ((entity.PersistentFlags & MyPersistentEntityFlags2.InScene) == MyPersistentEntityFlags2.InScene) * continue; */ myObjectBuilderWorld.Sector.SectorObjects.RemoveAt(r); } myObjectBuilderWorld.Sector.Encounters = null; myObjectBuilderWorld.VoxelMaps.Dictionary.Clear( ); myObjectBuilderWorld.Checkpoint.Settings.ProceduralDensity = 0f; myObjectBuilderWorld.Checkpoint.Settings.ProceduralSeed = 0; // Check if this is OK? //myObjectBuilderWorld.Checkpoint.ConnectedPlayers.Dictionary.Clear(); myObjectBuilderWorld.Checkpoint.DisconnectedPlayers.Dictionary.Clear( ); long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(steamId); MyObjectBuilder_Toolbar blankToolbar = new MyObjectBuilder_Toolbar( ); foreach (KeyValuePair <MyObjectBuilder_Checkpoint.PlayerId, MyObjectBuilder_Player> p in myObjectBuilderWorld.Checkpoint.AllPlayersData.Dictionary) { if (p.Value.EntityCameraData != null) { p.Value.EntityCameraData.Clear( ); } if (p.Value.CameraData != null) { p.Value.CameraData.Dictionary.Clear( ); } if (p.Key.ClientId == steamId) { continue; } p.Value.Toolbar = null; p.Value.CharacterCameraData = null; } for (int r = myObjectBuilderWorld.Checkpoint.Gps.Dictionary.Count - 1; r >= 0; r--) { KeyValuePair <long, MyObjectBuilder_Gps> p = myObjectBuilderWorld.Checkpoint.Gps.Dictionary.ElementAt(r); if (p.Key == playerId) { continue; } myObjectBuilderWorld.Checkpoint.Gps.Dictionary.Remove(p.Key); } myObjectBuilderWorld.Checkpoint.ChatHistory.RemoveAll(x => x.IdentityId != playerId); long factionId = 0; if (myObjectBuilderWorld.Checkpoint.Factions.Players.Dictionary.ContainsKey(playerId)) { factionId = myObjectBuilderWorld.Checkpoint.Factions.Players.Dictionary[playerId]; myObjectBuilderWorld.Checkpoint.FactionChatHistory.RemoveAll(x => x.FactionId1 != factionId && x.FactionId2 != factionId); myObjectBuilderWorld.Checkpoint.Factions.Requests.RemoveAll(x => x.FactionId != factionId); } else { myObjectBuilderWorld.Checkpoint.FactionChatHistory.Clear( ); myObjectBuilderWorld.Checkpoint.Factions.Requests.Clear( ); } foreach (MyObjectBuilder_Faction faction in myObjectBuilderWorld.Checkpoint.Factions.Factions) { if (faction.FactionId != factionId) { faction.PrivateInfo = ""; } } } // This will modify the world data to remove voxels and turn off procedural for the player. The // server controls procedural anyway, and doesn't require the user to know about it. If we don't // turn it off, the objects will still generate on the server. Possible issue: turning on voxel // management + procedural encounters may be an issue, as I don't think the server sends procedural // encounters to the client. This may be a gotcha issue when it comes to using this option if (WorldVoxelModify) { for (int r = myObjectBuilderWorld.Sector.SectorObjects.Count - 1; r >= 0; r--) { MyObjectBuilder_EntityBase entity = (MyObjectBuilder_EntityBase)myObjectBuilderWorld.Sector.SectorObjects[r]; if (!(entity is MyObjectBuilder_VoxelMap)) { continue; } myObjectBuilderWorld.Sector.SectorObjects.RemoveAt(r); } myObjectBuilderWorld.Sector.Encounters = null; myObjectBuilderWorld.VoxelMaps.Dictionary.Clear(); myObjectBuilderWorld.Checkpoint.Settings.ProceduralDensity = 0f; myObjectBuilderWorld.Checkpoint.Settings.ProceduralSeed = 0; } MyObjectBuilder_Checkpoint checkpoint = myObjectBuilderWorld.Checkpoint; checkpoint.WorkshopId = null; checkpoint.CharacterToolbar = null; DateTime cs = DateTime.Now; MyObjectBuilderSerializer.SerializeXML(ms, myObjectBuilderWorld, MyObjectBuilderSerializer.XmlCompression.Gzip, null); /* * MemoryStream vms = new MemoryStream(); * MyObjectBuilderSerializer.SerializeXML(vms, myObjectBuilderWorld, MyObjectBuilderSerializer.XmlCompression.Uncompressed, null); * FileStream file = new FileStream("e:\\temp\\test.txt", FileMode.Create); * vms.WriteTo(file); * file.Close(); */ ApplicationLog.BaseLog.Info("...response construction took {0}ms (cp - {1}ms) size - {2} bytes", (DateTime.Now - start).TotalMilliseconds, (DateTime.Now - cs).TotalMilliseconds, ms.Length); } TransferWorld(ms, steamId); } catch (Exception ex) { ApplicationLog.BaseLog.Error(ex, "SendWorldData Error: {0}", ex); } }
public static MyEntity SpawnInWorldOrLootBag(this MyPhysicalInventoryItem thisItem, MyEntity owner, ref MyEntity lootBagEntity) { Debug.Assert(Sandbox.Game.Multiplayer.Sync.IsServer); MyDefinitionBase itemDefinition = thisItem.GetItemDefinition(); Debug.Assert(itemDefinition != null); if (itemDefinition == null) { return(null); } MyEntity spawnedItem = null; Vector3 upDir = -MyGravityProviderSystem.CalculateNaturalGravityInPoint(owner.PositionComp.WorldMatrix.Translation); if (upDir == Vector3.Zero) { upDir = Vector3.Up; } else { upDir.Normalize(); } if (itemDefinition is MyCubeBlockDefinition) { MyCubeBlockDefinition blockDef = itemDefinition as MyCubeBlockDefinition; if (MyDefinitionManager.Static.GetLootBagDefinition() != null) { // New code which tries to spawn item with "MyEntities.FindFreePlace" and if there is no such position then loot bag is spawn and item is moved into it. MyModel blockModel = MyModels.GetModelOnlyData(blockDef.Model); BoundingBox box = blockModel.BoundingBox; box.Inflate(0.15f); // Inflate with value that is higher than half size of small grid so it will eliminate problems with block center offsets. float radius = box.HalfExtents.Max(); var baseSpawnPosition = owner.PositionComp.WorldMatrix.Translation; if (owner is MyCharacter) { baseSpawnPosition += owner.PositionComp.WorldMatrix.Up + owner.PositionComp.WorldMatrix.Forward; } else { baseSpawnPosition += upDir; } for (int gridIndex = 0; gridIndex < thisItem.Amount; ++gridIndex) { Vector3D?spawnPos = null; if (lootBagEntity == null && (spawnPos = MyEntities.FindFreePlace(baseSpawnPosition, radius, maxTestCount: 50, testsPerDistance: 5, stepSize: 0.25f)) != null) { MatrixD transform = owner.PositionComp.WorldMatrix; transform.Translation = spawnPos.Value; var blockBuilder = MyObjectBuilderSerializer.CreateNewObject(blockDef.Id) as MyObjectBuilder_CubeBlock; blockBuilder.Min = blockDef.Size / 2 - blockDef.Size + Vector3I.One; blockBuilder.EntityId = MyEntityIdentifier.AllocateId(); var newGrid = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>(); newGrid.PositionAndOrientation = new MyPositionAndOrientation(transform); newGrid.GridSizeEnum = blockDef.CubeSize; newGrid.PersistentFlags |= MyPersistentEntityFlags2.InScene; newGrid.EntityId = MyEntityIdentifier.AllocateId(); newGrid.CubeBlocks.Add(blockBuilder); var entity = MyEntities.CreateFromObjectBuilderAndAdd(newGrid); spawnedItem = spawnedItem ?? entity; } else { AddItemToLootBag(owner, new MyPhysicalInventoryItem(1, thisItem.Content), ref lootBagEntity); } } } else { // Old code used in SE (when no loot bag definition is defined). float spawnRadius = MyUtils.GetRandomFloat(Math.Max(0.25f, ITEM_SPAWN_RADIUS), ITEM_SPAWN_RADIUS); Vector3D randomizer = MyUtils.GetRandomVector3CircleNormalized() * spawnRadius + Vector3D.Up * 0.25f; int yOffset = 0; MyModel m = MyModels.GetModelOnlyData(blockDef.Model); float sizeY = m.BoundingBoxSize.Y + 0.05f; BoundingBox box = m.BoundingBox; for (int gridIndex = 0; gridIndex < thisItem.Amount; ++gridIndex) { var newGrid = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>(); MatrixD transform = owner.PositionComp.WorldMatrix * MatrixD.CreateTranslation(randomizer + new Vector3D(0, yOffset * sizeY, 0)); if (!GetNonPenetratingTransformPosition(ref box, ref transform)) { randomizer = MyUtils.GetRandomVector3CircleNormalized() * 0.25f + Vector3D.Up * 0.25f; transform = owner.PositionComp.WorldMatrix * MatrixD.CreateTranslation(randomizer + new Vector3D(0, yOffset * sizeY, 0)); } newGrid.PositionAndOrientation = new MyPositionAndOrientation(transform); newGrid.GridSizeEnum = blockDef.CubeSize; newGrid.PersistentFlags |= MyPersistentEntityFlags2.InScene; newGrid.EntityId = MyEntityIdentifier.AllocateId(); var newBlock = MyObjectBuilderSerializer.CreateNewObject(blockDef.Id) as MyObjectBuilder_CubeBlock; newBlock.EntityId = MyEntityIdentifier.AllocateId(); newGrid.CubeBlocks.Add(newBlock); var entity = MyEntities.CreateFromObjectBuilderAndAdd(newGrid); spawnedItem = spawnedItem ?? entity; if ((gridIndex + 1) % 10 == 0) { spawnRadius = MyUtils.GetRandomFloat(Math.Max(0.25f, ITEM_SPAWN_RADIUS), ITEM_SPAWN_RADIUS); randomizer = MyUtils.GetRandomVector3CircleNormalized() * spawnRadius + Vector3D.Up * 0.25f; yOffset = 0; } else { yOffset++; } } } } else if (itemDefinition is MyPhysicalItemDefinition) { MyPhysicalItemDefinition floatingObjectDefinition = itemDefinition as MyPhysicalItemDefinition; MyFixedPoint amount = thisItem.Amount; bool canStack = thisItem.Content.CanStack(thisItem.Content); MyFixedPoint stackSize = canStack ? amount : 1; MyFixedPoint maxStackAmount = MyFixedPoint.MaxValue; MyComponentDefinition compDef = null; if (MyDefinitionManager.Static.TryGetComponentDefinition(thisItem.Content.GetId(), out compDef)) { maxStackAmount = compDef.MaxStackAmount; stackSize = MyFixedPoint.Min(stackSize, maxStackAmount); } if (MyDefinitionManager.Static.GetLootBagDefinition() != null) { // New code which tries to spawn item with "MyEntities.FindFreePlace" and if there is no such position then loot bag is spawn and item is moved into it. MyModel model = MyModels.GetModelOnlyData(floatingObjectDefinition.Model); BoundingBox box = model.BoundingBox; float radius = box.HalfExtents.Max(); var baseSpawnPosition = owner.PositionComp.WorldMatrix.Translation; if (owner is MyCharacter) { baseSpawnPosition += owner.PositionComp.WorldMatrix.Up + owner.PositionComp.WorldMatrix.Forward; } else { baseSpawnPosition += upDir; } while (amount > 0) { MyFixedPoint spawnAmount = stackSize; amount -= stackSize; if (amount < 0) { spawnAmount = amount + stackSize; } Vector3D?spawnPos = null; if (lootBagEntity == null && (spawnPos = MyEntities.FindFreePlace(baseSpawnPosition, radius, maxTestCount: 50, testsPerDistance: 5, stepSize: 0.25f)) != null) { MatrixD worldMat = owner.PositionComp.WorldMatrix; worldMat.Translation = spawnPos.Value; var entity = MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(spawnAmount, thisItem.Content), worldMat); spawnedItem = spawnedItem ?? entity; } else { AddItemToLootBag(owner, new MyPhysicalInventoryItem(spawnAmount, thisItem.Content), ref lootBagEntity); } } } else { // Old code used in SE (when no loot bag definition is defined). while (amount > 0) { MyFixedPoint spawnAmount = stackSize; amount -= stackSize; if (amount < 0) { spawnAmount = amount + stackSize; } float spawnRadius = MyUtils.GetRandomFloat(Math.Max(0.25f, ITEM_SPAWN_RADIUS), ITEM_SPAWN_RADIUS); Vector3D randomizer = MyUtils.GetRandomVector3CircleNormalized() * spawnRadius + Vector3D.Up * 0.25f; var worldMat = owner.PositionComp.WorldMatrix * MatrixD.CreateTranslation(randomizer); var entity = MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(spawnAmount, thisItem.Content), worldMat); spawnedItem = spawnedItem ?? entity; } } } return(spawnedItem); }
public override MyObjectBuilder_DefinitionBase GetObjectBuilder() { var ob = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_HandItemDefinition>(); ob.Id = Id; ob.LeftHandOrientation = Quaternion.CreateFromRotationMatrix(LeftHand); ob.LeftHandPosition = LeftHand.Translation; ob.RightHandOrientation = Quaternion.CreateFromRotationMatrix(RightHand); ob.RightHandPosition = RightHand.Translation; ob.ItemOrientation = Quaternion.CreateFromRotationMatrix(ItemLocation); ob.ItemPosition = ItemLocation.Translation; ob.ItemWalkingOrientation = Quaternion.CreateFromRotationMatrix(ItemWalkingLocation); ob.ItemWalkingPosition = ItemWalkingLocation.Translation; ob.BlendTime = BlendTime; ob.XAmplitudeOffset = XAmplitudeOffset; ob.YAmplitudeOffset = YAmplitudeOffset; ob.ZAmplitudeOffset = ZAmplitudeOffset; ob.XAmplitudeScale = XAmplitudeScale; ob.YAmplitudeScale = YAmplitudeScale; ob.ZAmplitudeScale = ZAmplitudeScale; ob.RunMultiplier = RunMultiplier; ob.ItemWalkingOrientation3rd = Quaternion.CreateFromRotationMatrix(ItemWalkingLocation3rd); ob.ItemWalkingPosition3rd = ItemWalkingLocation3rd.Translation; ob.ItemOrientation3rd = Quaternion.CreateFromRotationMatrix(ItemLocation3rd); ob.ItemPosition3rd = ItemLocation3rd.Translation; ob.AmplitudeMultiplier3rd = AmplitudeMultiplier3rd; ob.SimulateLeftHand = SimulateLeftHand; ob.SimulateRightHand = SimulateRightHand; ob.FingersAnimation = FingersAnimation; ob.ItemShootOrientation = Quaternion.CreateFromRotationMatrix(ItemShootLocation); ob.ItemShootPosition = ItemShootLocation.Translation; ob.ItemShootOrientation3rd = Quaternion.CreateFromRotationMatrix(ItemShootLocation3rd); ob.ItemShootPosition3rd = ItemShootLocation3rd.Translation; ob.ShootBlend = ShootBlend; ob.MuzzlePosition = MuzzlePosition; ob.ShootScatter = ShootScatter; ob.ScatterSpeed = ScatterSpeed; ob.PhysicalItemId = PhysicalItemId; ob.LightColor = LightColor; ob.LightFalloff = LightFalloff; ob.LightRadius = LightRadius; ob.LightGlareSize = LightGlareSize; ob.LightIntensityLower = LightIntensityLower; ob.LightIntensityUpper = LightIntensityUpper; ob.ShakeAmountTarget = ShakeAmountTarget; ob.ShakeAmountNoTarget = ShakeAmountNoTarget; return(ob); }
public void Buy(string orderNumber) { if (!CheckIsPlayer(out var player)) { return; } if (!Plugin.PurchaseOrders.TryGetValue(orderNumber, out var purchaseOrder)) { Respond("No such purchase order"); return; } var sellerIdentityId = purchaseOrder.SellerIdentityId; var isSelfOrder = sellerIdentityId == player.IdentityId; if (!Config.CanRepurchaseOwnOrder && isSelfOrder) { Respond("Can't repurchase your own order"); return; } var sellerNotExist = !MySession.Static.Players.HasIdentity(sellerIdentityId); if (sellerNotExist) { Log.Error($"Seller {sellerIdentityId} of order <{orderNumber}> not exists!"); } else if (!Config.CanRepurchaseFactionOrder && !isSelfOrder && MySession.Static.Factions.GetPlayerFaction(sellerIdentityId)?.IsMember(player.IdentityId) == true) { Respond("Can't repurchase your faction order"); return; } if (!player.TryGetBalanceInfo(out var balance) || balance < purchaseOrder.Price) { Respond($"No enough money, need {purchaseOrder.Price} but you only have {balance}"); return; } if (!MyDefinitionId.TryParse(purchaseOrder.ItemType, purchaseOrder.ItemSubType, out var definitionId) || !MyDefinitionManager.Static.TryGetPhysicalItemDefinition(definitionId, out _)) { Respond( $"The order <{orderNumber}> contains invalid DefinitionId, may cause by mod changing or data corruption, please contact GM" ); return; } var playerInventory = GetPlayerInventory(); var canAddToPlayerInventory = playerInventory?.ComputeAmountThatFits(definitionId) ?? MyFixedPoint.Zero; var cargoInventory = GetAimedHavePermissionCargoInventory(); var canAddToCargoInventory = cargoInventory?.ComputeAmountThatFits(definitionId) ?? MyFixedPoint.Zero; //totalCanAdd may overflow if (canAddToCargoInventory < purchaseOrder.Amount && canAddToPlayerInventory < purchaseOrder.Amount && canAddToPlayerInventory + canAddToCargoInventory < purchaseOrder.Amount) { Respond("No enough inventory space"); return; } MyFixedPoint addToPlayerInventory; MyFixedPoint addToCargoInventory; if (canAddToCargoInventory > purchaseOrder.Amount) { addToCargoInventory = purchaseOrder.Amount; addToPlayerInventory = MyFixedPoint.Zero; } else { addToCargoInventory = canAddToCargoInventory; addToPlayerInventory = purchaseOrder.Amount - canAddToCargoInventory; } if (!Plugin.TryFinishOrder(orderNumber, out _)) { Respond("No such purchase order"); return; } player.RequestChangeBalance(-purchaseOrder.Price); var objectBuilder = MyObjectBuilderSerializer.CreateNewObject(definitionId); playerInventory?.AddItems(addToPlayerInventory, objectBuilder); cargoInventory?.AddItems(addToCargoInventory, objectBuilder); Respond($"You bought {definitionId} ({purchaseOrder.Amount}) for ${purchaseOrder.Price}"); var tax = (long)(Config.IllegalTaxRateDouble * purchaseOrder.Price); var s = $"<{orderNumber}> purchased by '{player.DisplayName}' for ${purchaseOrder.Price}(tax ${tax})"; if (Config.BroadcastOnBuy) { SendMessage($"The order {s}"); } if (sellerNotExist) { return; } MyBankingSystem.ChangeBalance(sellerIdentityId, purchaseOrder.Price - tax); if (!Config.BroadcastOnBuy && Config.NotifySellerOnBuy && MySession.Static.Players.TryGetPlayerId(sellerIdentityId, out var sellerPlayerId) && MySession.Static.Players.IsPlayerOnline(ref sellerPlayerId)) { SendMessage( $"Your order {s}", sellerPlayerId.SteamId ); } }
public static void FillInventoryWithDefaults(MyObjectBuilder_Inventory inventory, MyScenarioDefinition scenario) { if (inventory.Items == null) { inventory.Items = new List <MyObjectBuilder_InventoryItem>(); } else { inventory.Items.Clear(); } if (scenario != null && MySession.Static.Settings.SpawnWithTools) { MyStringId[] guns; if (MySession.Static.CreativeMode) { guns = scenario.CreativeModeWeapons;// new string[] { "AngleGrinderItem", "AutomaticRifleItem", "HandDrillItem", "WelderItem" }; } else { guns = scenario.SurvivalModeWeapons;// new string[] { "AngleGrinderItem", "HandDrillItem", "WelderItem" }; } uint itemId = 0; if (guns != null) { foreach (var gun in guns) { var inventoryItem = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_InventoryItem>(); inventoryItem.Amount = 1; inventoryItem.PhysicalContent = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_PhysicalGunObject>(gun.ToString()); inventoryItem.ItemId = itemId++; inventory.Items.Add(inventoryItem); } inventory.nextItemId = itemId; } MyScenarioDefinition.StartingItem[] items; if (MySession.Static.CreativeMode) { items = scenario.CreativeModeComponents; } else { items = scenario.SurvivalModeComponents; } if (items != null) { foreach (var item in items) { var inventoryItem = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_InventoryItem>(); inventoryItem.Amount = item.amount; inventoryItem.PhysicalContent = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Component>(item.itemName.ToString()); inventoryItem.ItemId = itemId++; inventory.Items.Add(inventoryItem); } inventory.nextItemId = itemId; } MyScenarioDefinition.StartingPhysicalItem[] physicalItems; if (MySession.Static.CreativeMode) { physicalItems = scenario.CreativeModePhysicalItems; } else { physicalItems = scenario.SurvivalModePhysicalItems; } if (physicalItems != null) { foreach (var item in physicalItems) { var inventoryItem = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_InventoryItem>(); inventoryItem.Amount = item.amount; if (item.itemType.ToString().Equals("Ore")) { inventoryItem.PhysicalContent = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>(item.itemName.ToString()); } else if (item.itemType.ToString().Equals("Ingot")) { inventoryItem.PhysicalContent = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ingot>(item.itemName.ToString()); } else if (item.itemType.ToString().Equals("OxygenBottle")) { inventoryItem.Amount = 1; inventoryItem.PhysicalContent = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_OxygenContainerObject>(item.itemName.ToString()); (inventoryItem.PhysicalContent as MyObjectBuilder_GasContainerObject).GasLevel = (float)item.amount; } else if (item.itemType.ToString().Equals("GasBottle")) { inventoryItem.Amount = 1; inventoryItem.PhysicalContent = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_GasContainerObject>(item.itemName.ToString()); (inventoryItem.PhysicalContent as MyObjectBuilder_GasContainerObject).GasLevel = (float)item.amount; } inventoryItem.ItemId = itemId++; inventory.Items.Add(inventoryItem); } inventory.nextItemId = itemId; } if (MySession.Static.CreativeMode) { items = scenario.CreativeModeAmmoItems; } else { items = scenario.SurvivalModeAmmoItems; } if (items != null) { foreach (var item in items) { var inventoryItem = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_InventoryItem>(); inventoryItem.Amount = item.amount; inventoryItem.PhysicalContent = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_AmmoMagazine>(item.itemName.ToString()); inventoryItem.ItemId = itemId++; inventory.Items.Add(inventoryItem); } inventory.nextItemId = itemId; } MyObjectBuilder_InventoryItem[] inventoryItems = MySession.Static.CreativeMode ? scenario.CreativeInventoryItems : scenario.SurvivalInventoryItems; if (inventoryItems != null) { foreach (var ob in inventoryItems) { var item = ob.Clone() as MyObjectBuilder_InventoryItem; item.ItemId = itemId++; inventory.Items.Add(item); } inventory.nextItemId = itemId; } } }
public static MyObjectBuilder_ToolbarItem ObjectBuilderFromDefinition(MyDefinitionBase defBase) { if (defBase is MyConsumableItemDefinition) { MyObjectBuilder_ToolbarItemConsumable consumableData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemConsumable>(); consumableData.DefinitionId = defBase.Id; return(consumableData); } else if ((defBase is MyPhysicalItemDefinition) && (defBase.Id.TypeId == typeof(MyObjectBuilder_PhysicalGunObject))) { MyObjectBuilder_ToolbarItemWeapon weaponData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemWeapon>(); weaponData.DefinitionId = defBase.Id; return(weaponData); } else if (defBase is MyCubeBlockDefinition) { MyCubeBlockDefinition blockDef = defBase as MyCubeBlockDefinition; MyObjectBuilder_ToolbarItemCubeBlock cubeData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemCubeBlock>(); cubeData.DefinitionId = defBase.Id; return(cubeData); } else if (defBase is MyAnimationDefinition) { var animData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemAnimation>(); animData.DefinitionId = defBase.Id; return(animData); } else if (defBase is MyVoxelHandDefinition) { var vhData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemVoxelHand>(); vhData.DefinitionId = defBase.Id; return(vhData); } else if (defBase is MyPrefabThrowerDefinition) { var ptData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemPrefabThrower>(); ptData.DefinitionId = defBase.Id; return(ptData); } else if (defBase is MyBotDefinition) { var bdData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemBot>(); bdData.DefinitionId = defBase.Id; return(bdData); } else if (defBase is MyAiCommandDefinition) { var acData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemAiCommand>(); acData.DefinitionId = defBase.Id; return(acData); } else if (defBase.Id.TypeId == typeof(MyObjectBuilder_RopeDefinition)) { var ob = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemRope>(); ob.DefinitionId = defBase.Id; return(ob); } else if (defBase is MyAreaMarkerDefinition) { var acData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemAreaMarker>(); acData.DefinitionId = defBase.Id; return(acData); } else if (defBase is MyGridCreateToolDefinition) { var gctool = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemCreateGrid>(); gctool.DefinitionId = defBase.Id; return(gctool); } return(new MyObjectBuilder_ToolbarItemEmpty()); }
internal void TakeRequiredComponents(MyEntity inventoryOwner) { if (MyAPIGateway.Session.CreativeMode) { return; } if (!inventoryOwner.HasInventory) { return; } // Ignore reactors if (inventoryOwner is Sandbox.ModAPI.Ingame.IMyReactor) { return; } if (inventoryOwner is IMyCubeBlock && ((IMyCubeBlock)inventoryOwner).BlockDefinition.SubtypeName.Contains("Nanite")) { return; } int inventoryIndex = inventoryOwner.InventoryCount - 1; //if (inventoryOwner is Sandbox.ModAPI.Ingame.IMyAssembler) // inventoryIndex = 1; IMyInventory constructionInventory = GetConstructionInventory(); IMyInventory inventory = (IMyInventory)inventoryOwner.GetInventoryBase(inventoryIndex); if (constructionInventory == null || inventory == null) { return; } if (((Sandbox.Game.MyInventory)inventory).GetItemsCount() < 1) { return; } //if (!constructionInventory.IsConnectedTo(inventory)) // return; IMyTerminalBlock terminalOwner = inventoryOwner as IMyTerminalBlock; MyRelationsBetweenPlayerAndBlock relation = ((IMyTerminalBlock)m_constructionBlock).GetUserRelationToOwner(terminalOwner.OwnerId); if (relation == MyRelationsBetweenPlayerAndBlock.Enemies) { return; } foreach (var inventoryItem in inventory.GetItems().ToList()) { foreach (var componentNeeded in ComponentsRequired.ToList()) { if (inventoryItem.Content.TypeId != typeof(MyObjectBuilder_Component)) { continue; } if (componentNeeded.Value <= 0) { continue; } if ((int)inventoryItem.Amount <= 0f) { continue; } if (inventoryItem.Content.SubtypeName == componentNeeded.Key) { if (inventoryItem.Amount >= componentNeeded.Value) { var validAmount = GetMaxComponentAmount(componentNeeded.Key, (float)constructionInventory.MaxVolume - (float)constructionInventory.CurrentVolume); var amount = Math.Min(componentNeeded.Value, validAmount); if (!constructionInventory.CanItemsBeAdded((int)amount, new SerializableDefinitionId(typeof(MyObjectBuilder_Component), componentNeeded.Key))) { continue; } inventory.RemoveItemsOfType((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); constructionInventory.AddItems((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); ComponentsRequired[componentNeeded.Key] -= (int)amount; } else { var validAmount = GetMaxComponentAmount(componentNeeded.Key, (float)constructionInventory.MaxVolume - (float)constructionInventory.CurrentVolume); var amount = Math.Min((float)inventoryItem.Amount, validAmount); if (!constructionInventory.CanItemsBeAdded((int)amount, new SerializableDefinitionId(typeof(MyObjectBuilder_Component), componentNeeded.Key))) { continue; } inventory.RemoveItemsOfType((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); constructionInventory.AddItems((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); ComponentsRequired[componentNeeded.Key] -= (int)amount; } continue; } } } }
// receiving messages private void LiveDebugging_ReceivedMessageHandler(MyExternalDebugStructures.CommonMsgHeader messageHeader, IntPtr messageData) { MyExternalDebugStructures.ACReloadInGameMsg msgReload; if (MyExternalDebugStructures.ReadMessageFromPtr(ref messageHeader, messageData, out msgReload)) { try { string acContentPath = msgReload.ACContentAddress; string acAddress = msgReload.ACAddress; string acName = msgReload.ACName; MyObjectBuilder_Definitions allDefinitions; // = null; // load animation controller definition from SBC file if (MyObjectBuilderSerializer.DeserializeXML(acAddress, out allDefinitions) && allDefinitions.Definitions != null && allDefinitions.Definitions.Length > 0) { var firstDef = allDefinitions.Definitions[0]; MyModContext context = new MyModContext(); context.Init("AnimationControllerDefinition", acAddress, acContentPath); MyAnimationControllerDefinition animationControllerDefinition = new MyAnimationControllerDefinition(); animationControllerDefinition.Init(firstDef, context); MyStringHash animSubtypeNameHash = MyStringHash.GetOrCompute(acName); // post process and update in def. manager MyAnimationControllerDefinition originalAnimationControllerDefinition = MyDefinitionManagerBase.Static.GetDefinition <MyAnimationControllerDefinition>( animSubtypeNameHash); var postprocessor = MyDefinitionManagerBase.GetPostProcessor(typeof(MyObjectBuilder_AnimationControllerDefinition)); if (postprocessor != null) { MyDefinitionPostprocessor.Bundle originalBundle = new MyDefinitionPostprocessor.Bundle { Context = MyModContext.BaseGame, Definitions = new Dictionary <MyStringHash, MyDefinitionBase> { { animSubtypeNameHash, originalAnimationControllerDefinition } }, Set = new MyDefinitionSet() }; originalBundle.Set.AddDefinition(originalAnimationControllerDefinition); MyDefinitionPostprocessor.Bundle overridingBundle = new MyDefinitionPostprocessor.Bundle { Context = context, Definitions = new Dictionary <MyStringHash, MyDefinitionBase> { { animSubtypeNameHash, animationControllerDefinition } }, Set = new MyDefinitionSet() }; overridingBundle.Set.AddDefinition(animationControllerDefinition); // postprocess -> override existing definition in memory postprocessor.AfterLoaded(ref overridingBundle); postprocessor.OverrideBy(ref originalBundle, ref overridingBundle); } // swap animation controller for each entity foreach (var component in m_skinnedEntityComponents) { if (component != null && component.SourceId.SubtypeName == acName) { component.Clear(); component.InitFromDefinition(originalAnimationControllerDefinition); // reload from original def that was modified by postprocessor if (component.ReloadBonesNeeded != null) { component.ReloadBonesNeeded(); } } } } } catch (Exception e) { MyLog.Default.WriteLine(e); } } }
/// <summary> /// Gets a session snapshot customized for an individual player. Removes data that player does not need, /// which improves download times, and fixes some exploits. /// </summary> /// <param name="steamId"></param> /// <returns></returns> private static MyObjectBuilder_Checkpoint GetClientCheckpoint(ulong steamId) { Log.Info($"Saving checkpoint..."); var cpid = new MyObjectBuilder_Checkpoint.PlayerId(steamId); var ppid = new MyPlayer.PlayerId(steamId); if (_checkpoint == null) { _checkpoint = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Checkpoint>(); _cameraSettings = new List <CameraControllerSettings>(); var settings = MyObjectBuilderSerializer.Clone(MySession.Static.Settings) as MyObjectBuilder_SessionSettings; bGps = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Gps>(); bGps.Entries = new List <MyObjectBuilder_Gps.Entry>(); settings.ScenarioEditMode |= MySession.Static.PersistentEditMode; _checkpoint.SessionName = MySession.Static.Name; _checkpoint.Description = MySession.Static.Description; _checkpoint.PromotedUsers = new SerializableDictionary <ulong, MyPromoteLevel>(MySession.Static.PromotedUsers); _checkpoint.CreativeTools = new HashSet <ulong>(); _checkpoint.Settings = settings; //We're replacing the call to MySession.GetWorld, so Torch can't inject the torch mod. Do it here instead _checkpoint.Mods = MySession.Static.Mods.ToList(); _checkpoint.Mods.AddRange(SessionManager.OverrideMods); _checkpoint.Scenario = MySession.Static.Scenario.Id; _checkpoint.WorldBoundaries = MySession.Static.WorldBoundaries; _checkpoint.PreviousEnvironmentHostility = MySession.Static.PreviousEnvironmentHostility; _checkpoint.RequiresDX = MySession.Static.RequiresDX; _checkpoint.CustomSkybox = MySession.Static.CustomSkybox; _checkpoint.GameDefinition = MySession.Static.GameDefinition.Id; _checkpoint.Gps = new SerializableDictionary <long, MyObjectBuilder_Gps>(); _checkpoint.RespawnCooldowns = new List <MyObjectBuilder_Checkpoint.RespawnCooldownItem>(); _checkpoint.ControlledEntities = new SerializableDictionary <long, MyObjectBuilder_Checkpoint.PlayerId>(); _checkpoint.ChatHistory = new List <MyObjectBuilder_ChatHistory>(); _checkpoint.FactionChatHistory = new List <MyObjectBuilder_FactionChatHistory>(); _checkpoint.AppVersion = MyFinalBuildConstants.APP_VERSION; _checkpoint.SessionComponents = new List <MyObjectBuilder_SessionComponent>(); _checkpoint.AllPlayersData = new SerializableDictionary <MyObjectBuilder_Checkpoint.PlayerId, MyObjectBuilder_Player>(); _checkpoint.AllPlayersColors = new SerializableDictionary <MyObjectBuilder_Checkpoint.PlayerId, List <Vector3> >(); _checkpoint.Identities = new List <MyObjectBuilder_Identity>(); _checkpoint.Clients = new List <MyObjectBuilder_Client>(); _checkpoint.NonPlayerIdentities = new List <long>(); _checkpoint.CharacterToolbar = null; } _checkpoint.CreativeTools.Clear(); //Pool.DeallocateCollection(_checkpoint.Gps.Dictionary.Values); _checkpoint.Gps.Dictionary.Clear(); //Pool.DeallocateAndClear(bGps.Entries); bGps.Entries.Clear(); //Pool.DeallocateAndClear(_checkpoint.RespawnCooldowns); _checkpoint.RespawnCooldowns.Clear(); Pool.DeallocateAndClear(_checkpoint.ChatHistory); _checkpoint.ControlledEntities.Dictionary.Clear(); Pool.DeallocateAndClear(_checkpoint.FactionChatHistory); _checkpoint.SessionComponents.Clear(); Pool.DeallocateCollection(_checkpoint.AllPlayersData.Dictionary.Values); _checkpoint.AllPlayersData.Dictionary.Clear(); _checkpoint.AllPlayersColors.Dictionary.Clear(); Pool.DeallocateAndClear(_checkpoint.Identities); Pool.DeallocateAndClear(_checkpoint.Clients); _checkpoint.NonPlayerIdentities.Clear(); Pool.DeallocateAndClear(_cameraSettings); if (MySession.Static.CreativeToolsEnabled(steamId)) { _checkpoint.CreativeTools.Add(steamId); } //checkpoint.Briefing = Briefing; //checkpoint.BriefingVideo = BriefingVideo; _checkpoint.LastSaveTime = DateTime.Now; _checkpoint.WorkshopId = MySession.Static.WorkshopId; _checkpoint.ElapsedGameTime = MySession.Static.ElapsedGameTime.Ticks; _checkpoint.InGameTime = MySession.Static.InGameTime; //checkpoint.CharacterToolbar = MyToolbarComponent.CharacterToolbar.GetObjectBuilder(); //TODO _checkpoint.CustomLoadingScreenImage = MySession.Static.CustomLoadingScreenImage; _checkpoint.CustomLoadingScreenText = EssentialsPlugin.Instance.Config.LoadingText ?? MySession.Static.CustomLoadingScreenText; _checkpoint.SessionComponentDisabled = MySession.Static.SessionComponentDisabled; _checkpoint.SessionComponentEnabled = MySession.Static.SessionComponentEnabled; // checkpoint.PlayerToolbars = Toolbars.GetSerDictionary(); //Sync.Players.SavePlayers(_checkpoint); ConcurrentDictionary <MyPlayer.PlayerId, MyPlayer> m_players = Players_Getter(MySession.Static.Players); ConcurrentDictionary <MyPlayer.PlayerId, long> m_playerIdentityIds = PlayerIdentities_Getter(MySession.Static.Players); foreach (MyPlayer p in m_players.Values) { var id = new MyObjectBuilder_Checkpoint.PlayerId { ClientId = p.Id.SteamId, SerialId = p.Id.SerialId }; var playerOb = Pool.AllocateOrCreate <MyObjectBuilder_Player>(); playerOb.DisplayName = p.DisplayName; playerOb.IdentityId = p.Identity.IdentityId; playerOb.Connected = true; playerOb.ForceRealPlayer = p.IsRealPlayer; if (playerOb.BuildColorSlots == null) { playerOb.BuildColorSlots = new List <Vector3>(); } else { playerOb.BuildColorSlots.Clear(); } foreach (Vector3 color in p.BuildColorSlots) { playerOb.BuildColorSlots.Add(color); } _checkpoint.AllPlayersData.Dictionary.Add(id, playerOb); } foreach (KeyValuePair <MyPlayer.PlayerId, long> identityPair in m_playerIdentityIds) { if (m_players.ContainsKey(identityPair.Key)) { continue; } var id = new MyObjectBuilder_Checkpoint.PlayerId { ClientId = identityPair.Key.SteamId, SerialId = identityPair.Key.SerialId }; MyIdentity identity = MySession.Static.Players.TryGetIdentity(identityPair.Value); var playerOb = Pool.AllocateOrCreate <MyObjectBuilder_Player>(); playerOb.DisplayName = identity?.DisplayName; playerOb.IdentityId = identityPair.Value; playerOb.Connected = false; if (MyCubeBuilder.AllPlayersColors != null) { MyCubeBuilder.AllPlayersColors.TryGetValue(identityPair.Key, out playerOb.BuildColorSlots); } _checkpoint.AllPlayersData.Dictionary.Add(id, playerOb); } if (MyCubeBuilder.AllPlayersColors != null) { foreach (KeyValuePair <MyPlayer.PlayerId, List <Vector3> > colorPair in MyCubeBuilder.AllPlayersColors) { //TODO: check if the player exists in m_allIdentities if (m_players.ContainsKey(colorPair.Key) || m_playerIdentityIds.ContainsKey(colorPair.Key)) { continue; } var id = new MyObjectBuilder_Checkpoint.PlayerId { ClientId = colorPair.Key.SteamId, SerialId = colorPair.Key.SerialId }; _checkpoint.AllPlayersColors.Dictionary.Add(id, colorPair.Value); } } _checkpoint.AllPlayersData.Dictionary.TryGetValue(cpid, out MyObjectBuilder_Player player); if (player != null) { //Toolbars.SaveToolbars(checkpoint); MyToolbar toolbar = MySession.Static.Toolbars.TryGetPlayerToolbar(ppid); if (toolbar != null) { player.Toolbar = toolbar.GetObjectBuilder(); } else if (EssentialsPlugin.Instance.Config.EnableToolbarOverride) { player.Toolbar = EssentialsPlugin.Instance.Config.DefaultToolbar; } //MySession.Static.Cameras.SaveCameraCollection(checkpoint); player.EntityCameraData = _cameraSettings; Dictionary <MyPlayer.PlayerId, Dictionary <long, MyEntityCameraSettings> > d = EntityCameraSettings; if (d.TryGetValue(ppid, out Dictionary <long, MyEntityCameraSettings> camera)) { foreach (KeyValuePair <long, MyEntityCameraSettings> cameraSetting in camera) { var set = Pool.AllocateOrCreate <CameraControllerSettings>(); set.Distance = cameraSetting.Value.Distance; set.IsFirstPerson = cameraSetting.Value.IsFirstPerson; set.HeadAngle = cameraSetting.Value.HeadAngle; set.EntityId = cameraSetting.Key; player.EntityCameraData.Add(set); } } //Gpss.SaveGpss(checkpoint); foreach (IMyGps igps in MyAPIGateway.Session.GPS.GetGpsList(player.IdentityId)) { var gps = igps as MyGps; if (!gps.IsLocal) { if (gps.EntityId == 0 || MyEntities.GetEntityById(gps.EntityId) != null) { var builder = new MyObjectBuilder_Gps.Entry { name = gps.Name, description = gps.Description, coords = gps.Coords, isFinal = gps.DiscardAt == null, showOnHud = gps.ShowOnHud, alwaysVisible = gps.AlwaysVisible, color = gps.GPSColor, entityId = gps.EntityId, DisplayName = gps.DisplayName }; bGps.Entries.Add(builder); } } } _checkpoint.Gps.Dictionary.Add(player.IdentityId, bGps); } if (MyFakes.ENABLE_MISSION_TRIGGERS) { //usually empty, so meh _checkpoint.MissionTriggers = MySessionComponentMissionTriggers.Static.GetObjectBuilder(); } //bunch of allocations in here, but can't replace the logic easily because private types _checkpoint.Factions = MySession.Static.Factions.GetObjectBuilder(); //ok for now, clients need to know about dead identities. Might filter out those that own no blocks. //amount of data per ID is low, and admins usually clean them, so meh //_checkpoint.Identities = Sync.Players.SaveIdentities(); foreach (MyIdentity identity in MySession.Static.Players.GetAllIdentities()) { if (MySession.Static.Players.TryGetPlayerId(identity.IdentityId, out MyPlayer.PlayerId id)) { MyPlayer p = MySession.Static.Players.GetPlayerById(id); if (p != null) { identity.LastLogoutTime = DateTime.Now; } } var objectBuilder = Pool.AllocateOrCreate <MyObjectBuilder_Identity>(); objectBuilder.IdentityId = identity.IdentityId; objectBuilder.DisplayName = identity.DisplayName; objectBuilder.CharacterEntityId = identity.Character?.EntityId ?? 0; objectBuilder.Model = identity.Model; objectBuilder.ColorMask = identity.ColorMask; objectBuilder.BlockLimitModifier = identity.BlockLimits.BlockLimitModifier; objectBuilder.LastLoginTime = identity.LastLoginTime; objectBuilder.LastLogoutTime = identity.LastLogoutTime; objectBuilder.SavedCharacters = identity.SavedCharacters; objectBuilder.RespawnShips = identity.RespawnShips; objectBuilder.LastDeathPosition = identity.LastDeathPosition; _checkpoint.Identities.Add(objectBuilder); } Sync.Players.RespawnComponent.SaveToCheckpoint(_checkpoint); //count for these is low, and the store is internal, so removing unnecessary entries is cheaper than reflection (probably?) _checkpoint.RespawnCooldowns.RemoveAll(i => i.PlayerSteamId != steamId); //checkpoint.ControlledEntities = Sync.Players.SerializeControlledEntities(); foreach (KeyValuePair <long, MyPlayer.PlayerId> entry in MySession.Static.Players.ControlledEntities) { if (entry.Value.SteamId == steamId) { _checkpoint.ControlledEntities.Dictionary.Add(entry.Key, cpid); } } //checkpoint.SpectatorPosition = new MyPositionAndOrientation(ref spectatorMatrix); //checkpoint.SpectatorIsLightOn = MySpectatorCameraController.Static.IsLightOn; //checkpoint.SpectatorCameraMovement = MySpectator.Static.SpectatorCameraMovement; //checkpoint.SpectatorDistance = (float)MyThirdPersonSpectator.Static.GetViewerDistance(); //checkpoint.CameraController = cameraControllerEnum; //if (cameraControllerEnum == MyCameraControllerEnum.Entity) // checkpoint.CameraEntity = ((MyEntity)CameraController).EntityId; //if (ControlledEntity != null) //{ // checkpoint.ControlledObject = ControlledEntity.Entity.EntityId; // if (ControlledEntity is MyCharacter) // { // Debug.Assert(LocalCharacter == null || !(LocalCharacter.IsUsing is MyCockpit), "Character in cockpit cannot be controlled entity"); // } //} //else _checkpoint.ControlledObject = -1; //SaveChatHistory(checkpoint); /* * if (player != null && MySession.Static.ChatHistory.TryGetValue(player.IdentityId, out MyChatHistory playerChat)) * { * var builder = Pool.AllocateOrCreate<MyObjectBuilder_ChatHistory>(); * builder.IdentityId = playerChat.IdentityId; * if (builder.PlayerChatHistory != null) * Pool.DeallocateAndClear(builder.PlayerChatHistory); * else * builder.PlayerChatHistory = new List<MyObjectBuilder_PlayerChatHistory>(); * foreach (MyPlayerChatHistory chat in playerChat.PlayerChatHistory.Values) * { * var cb = Pool.AllocateOrCreate<MyObjectBuilder_PlayerChatHistory>(); * if (cb.Chat != null) * Pool.DeallocateAndClear(cb.Chat); * else * cb.Chat = new List<MyObjectBuilder_PlayerChatItem>(); * cb.IdentityId = chat.IdentityId; * foreach (MyPlayerChatItem m in chat.Chat) * { * var mb = Pool.AllocateOrCreate<MyObjectBuilder_PlayerChatItem>(); * mb.Text = m.Text; * mb.IdentityIdUniqueNumber = MyEntityIdentifier.GetIdUniqueNumber(m.IdentityId); * mb.TimestampMs = (long)m.Timestamp.TotalMilliseconds; * mb.Sent = m.Sent; * cb.Chat.Add(mb); * } * builder.PlayerChatHistory.Add(cb); * } * * if (builder.GlobalChatHistory == null) * builder.GlobalChatHistory = Pool.AllocateOrCreate<MyObjectBuilder_GlobalChatHistory>(); * if (builder.GlobalChatHistory.Chat != null) * Pool.DeallocateAndClear(builder.GlobalChatHistory.Chat); * else * builder.GlobalChatHistory.Chat = new List<MyObjectBuilder_GlobalChatItem>(); * * foreach (MyGlobalChatItem g in playerChat.GlobalChatHistory.Chat) * { * var gb = Pool.AllocateOrCreate<MyObjectBuilder_GlobalChatItem>(); * gb.Text = g.Text; * gb.Font = g.AuthorFont; * if (g.IdentityId == 0) * { * gb.IdentityIdUniqueNumber = 0; * gb.Author = g.Author; * } * else * { * gb.IdentityIdUniqueNumber = MyEntityIdentifier.GetIdUniqueNumber(g.IdentityId); * gb.Author = string.Empty; * } * builder.GlobalChatHistory.Chat.Add(gb); * } * * _checkpoint.ChatHistory.Add(builder); * } * * if (player != null) * { * IMyFaction pfac = MySession.Static.Factions.TryGetPlayerFaction(player.IdentityId); * if (pfac != null) * { * foreach (MyFactionChatHistory history in MySession.Static.FactionChatHistory) * { * if (history.FactionId1 == pfac.FactionId || history.FactionId2 == pfac.FactionId) * { * var builder = Pool.AllocateOrCreate<MyObjectBuilder_FactionChatHistory>(); * if (builder.Chat != null) * Pool.DeallocateAndClear(builder.Chat); * else * builder.Chat = new List<MyObjectBuilder_FactionChatItem>(); * * builder.FactionId1 = history.FactionId1; * builder.FactionId2 = history.FactionId2; * * foreach (MyFactionChatItem fc in history.Chat) * { * if (fc.PlayersToSendTo != null && fc.PlayersToSendTo.Count > 0) * { * var fb = Pool.AllocateOrCreate<MyObjectBuilder_FactionChatItem>(); * fb.Text = fc.Text; * fb.IdentityIdUniqueNumber = MyEntityIdentifier.GetIdUniqueNumber(fc.IdentityId); * fb.TimestampMs = (long)fc.Timestamp.TotalMilliseconds; * if (fb.PlayersToSendToUniqueNumber != null) * fb.PlayersToSendToUniqueNumber.Clear(); * else * fb.PlayersToSendToUniqueNumber = new List<long>(); * if (fb.IsAlreadySentTo != null) * fb.IsAlreadySentTo.Clear(); * else * fb.IsAlreadySentTo = new List<bool>(); * foreach (KeyValuePair<long, bool> pair in fc.PlayersToSendTo) * { * fb.PlayersToSendToUniqueNumber.Add(MyEntityIdentifier.GetIdUniqueNumber(pair.Key)); * fb.IsAlreadySentTo.Add(pair.Value); * } * builder.Chat.Add(fb); * } * } * } * } * } * } */ //_checkpoint.Clients = SaveMembers_Imp(MySession.Static, false); if (MyMultiplayer.Static.Members.Count() > 1) { foreach (ulong member in MyMultiplayer.Static.Members) { var ob = Pool.AllocateOrCreate <MyObjectBuilder_Client>(); ob.SteamId = member; ob.Name = MyMultiplayer.Static.GetMemberName(member); ob.IsAdmin = MySession.Static.IsUserAdmin(member); _checkpoint.Clients.Add(ob); } } //_checkpoint.NonPlayerIdentities = Sync.Players.SaveNpcIdentities(); foreach (long npc in MySession.Static.Players.GetNPCIdentities()) { _checkpoint.NonPlayerIdentities.Add(npc); } //SaveSessionComponentObjectBuilders(checkpoint); CachingDictionary <Type, MySessionComponentBase> compDic = SessionComponents_Getter(MySession.Static); foreach (KeyValuePair <Type, MySessionComponentBase> entry in compDic) { //literally dozens of MB of duplicated garbage. Ignore all of it. //TODO: Keen fixed the duplication but this shouldn't exist at all. Rexxar has a plan //if (entry.Value is MyProceduralWorldGenerator) // continue; MyObjectBuilder_SessionComponent ob = entry.Value.GetObjectBuilder(); if (ob != null) { _checkpoint.SessionComponents.Add(ob); } } _checkpoint.ScriptManagerData = MySession.Static.ScriptManager.GetObjectBuilder(); //skipped on DS //GatherVicinityInformation(checkpoint); //if (OnSavingCheckpoint != null) // OnSavingCheckpoint(checkpoint); Log.Info("Done."); return(_checkpoint); }
public override void Init(MyObjectBuilder_EntityBase objectBuilder) { m_physicalItemId = new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), "HandDrillItem"); if (objectBuilder.SubtypeName != null && objectBuilder.SubtypeName.Length > 0) { m_physicalItemId = new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), objectBuilder.SubtypeName + "Item"); } PhysicalObject = (MyObjectBuilder_PhysicalGunObject)MyObjectBuilderSerializer.CreateNewObject(m_physicalItemId); (PositionComp as MyPositionComponent).WorldPositionChanged = WorldPositionChanged; m_handItemDefId = objectBuilder.GetId(); var definition = MyDefinitionManager.Static.TryGetHandItemDefinition(ref m_handItemDefId); m_speedMultiplier = 1f / (definition as MyHandDrillDefinition).SpeedMultiplier; m_drillBase = new MyDrillBase(this, MyDrillConstants.DRILL_HAND_DUST_EFFECT, MyDrillConstants.DRILL_HAND_DUST_STONES_EFFECT, MyDrillConstants.DRILL_HAND_SPARKS_EFFECT, new MyDrillSensorRayCast(-0.5f, 2.15f), new MyDrillCutOut(1.0f, 0.35f * (definition as MyHandDrillDefinition).DistanceMultiplier), SPIKE_SLOWDOWN_TIME_IN_SECONDS, floatingObjectSpawnOffset: -0.25f, floatingObjectSpawnRadius: 1.4f * 0.25f ); m_drillBase.VoxelHarvestRatio = MyDrillConstants.VOXEL_HARVEST_RATIO * (definition as MyHandDrillDefinition).HarvestRatioMultiplier; AddDebugRenderComponent(new Components.MyDebugRenderCompomentDrawDrillBase(m_drillBase)); base.Init(objectBuilder); m_physItemDef = MyDefinitionManager.Static.GetPhysicalItemDefinition(m_physicalItemId); Init(null, m_physItemDef.Model, null, null, null); Render.CastShadows = true; Render.NeedsResolveCastShadow = false; m_spike = Subparts["Spike"]; m_spikeBasePos = m_spike.PositionComp.LocalMatrix.Translation; m_drillBase.IgnoredEntities.Add(this); m_drillBase.OnWorldPositionChanged(PositionComp.WorldMatrix); PhysicalObject.GunEntity = (MyObjectBuilder_EntityBase)objectBuilder.Clone(); PhysicalObject.GunEntity.EntityId = this.EntityId; NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME; m_oreDetectorBase.DetectionRadius = 20; m_oreDetectorBase.OnCheckControl = OnCheckControl; var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( MyStringHash.GetOrCompute("Utility"), MyEnergyConstants.REQUIRED_INPUT_HAND_DRILL, () => m_tryingToDrill ? SinkComp.MaxRequiredInputByType(MyResourceDistributorComponent.ElectricityId) : 0f); SinkComp = sinkComp; foreach (ToolSound toolSound in definition.ToolSounds) { if (toolSound.type == null || toolSound.subtype == null || toolSound.sound == null) { continue; } if (toolSound.type.Equals("Main")) { if (toolSound.subtype.Equals("Idle")) { m_drillBase.m_idleSoundLoop = new MySoundPair(toolSound.sound); } if (toolSound.subtype.Equals("Soundset")) { m_drillBase.m_drillMaterial = MyStringHash.GetOrCompute(toolSound.sound); } } } }
private bool WormholeTransferInFile(FileInfo fileInfo, Utilities.TransferFileInfo fileTransferInfo, Vector3D gatePosition, BoundingSphereD gate) { Log.Info("processing filetransfer:" + fileTransferInfo.createLogString()); var playerid = MySession.Static.Players.TryGetIdentityId(fileTransferInfo.steamUserId); // defaults to 0 if (playerid <= 0) { Log.Error("couldn't find player with steam id: " + fileTransferInfo.steamUserId); return(false); } if (!MyObjectBuilderSerializer.DeserializeXML(fileInfo.FullName, out MyObjectBuilder_Definitions myObjectBuilder_Definitions)) { Log.Error("error deserializing xml: " + fileInfo.FullName); return(true); // if we cant deserializing the file, we still needs the file to be deleted. } var shipBlueprints = myObjectBuilder_Definitions.ShipBlueprints; if (shipBlueprints == null) { Log.Error("can't find any blueprints in xml: " + fileInfo.FullName); return(true); // Again we need ti to be deleted. } foreach (var shipBlueprint in shipBlueprints) { var grids = shipBlueprint.CubeGrids; if (grids == null || grids.Length == 0) { continue; } var pos = Utilities.FindFreePos(gate, Utilities.FindGridsRadius(grids)); if (pos == null) { Log.Warn("no free space available for grid '" + shipBlueprint.DisplayName + "' at wormhole '" + fileTransferInfo.destinationWormhole + "'"); continue; } if (Utilities.UpdateGridsPositionAndStop(grids, pos)) { foreach (var mygrid in grids) { // takeover ownership foreach (MyObjectBuilder_CubeBlock block in mygrid.CubeBlocks) { block.BuiltBy = playerid; block.Owner = playerid; } foreach (MyObjectBuilder_Cockpit cockpit in mygrid.CubeBlocks.Where(block => block is MyObjectBuilder_Cockpit)) { if (cockpit.Pilot == null || !Config.PlayerRespawn) { cockpit.Pilot = null; continue; } // cannot retreive steamId from cockpit.Pilot anylonger. Looking in the servers player cache if a player with the given steamId exists. List <IMyPlayer> players = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players); var player = (from a in players where a.IdentityId == (cockpit.Pilot.OwningPlayerIdentityId) select a).FirstOrDefault(); // If no player was found it will continue if (player == null) { Log.Info("No active playerinstance for the pilot"); return(false); } long pilotIdentityId = MyAPIGateway.Multiplayer.Players.TryGetIdentityId(player.SteamUserId); cockpit.Pilot.OwningPlayerIdentityId = pilotIdentityId; var pilotIdentity = MySession.Static.Players.TryGetIdentity(pilotIdentityId); if (pilotIdentity.Character != null) { // if there is a character, kill it if (Config.ThisIp != null && Config.ThisIp != "") { ModCommunication.SendMessageTo(new JoinServerMessage(Config.ThisIp), player.SteamUserId); } KillCharacter(player.SteamUserId); } pilotIdentity.PerformFirstSpawn(); pilotIdentity.SavedCharacters.Clear(); pilotIdentity.SavedCharacters.Add(cockpit.Pilot.EntityId); MyAPIGateway.Multiplayer.Players.SetControlledEntity(player.SteamUserId, cockpit.Pilot as VRage.ModAPI.IMyEntity); } } } List <MyObjectBuilder_EntityBase> objectBuilderList = new List <MyObjectBuilder_EntityBase>(grids.ToList()); MyEntities.RemapObjectBuilderCollection(objectBuilderList); if (objectBuilderList.Count > 1) { if (MyEntities.Load(objectBuilderList, out _)) { fileInfo.Delete(); } } else { foreach (var ob in objectBuilderList) { if (MyEntities.CreateFromObjectBuilderParallel(ob, true) != null) { fileInfo.Delete(); } } } MyVisualScriptLogicProvider.CreateLightning(gatePosition); } return(true); }
public bool StartServer(string instanceName = "", string overridePath = "", bool useConsole = true) { try { Sandbox.Engine.Platform.Game.IsDedicated = true; MyFileSystem.Reset( ); //Prepare the parameters bool isUsingInstance = instanceName != string.Empty; object[] methodParams = { instanceName, overridePath, isUsingInstance, useConsole }; //Initialize config SpaceEngineersGame.SetupPerGameSettings(); SpaceEngineersGame.SetupBasicGameInfo(); MyPerGameSettings.SendLogToKeen = DedicatedServer.SendLogToKeen; MyPerServerSettings.GameName = MyPerGameSettings.GameName; MyPerServerSettings.GameNameSafe = MyPerGameSettings.GameNameSafe; MyPerServerSettings.GameDSName = MyPerServerSettings.GameNameSafe + "Dedicated"; MyPerServerSettings.GameDSDescription = "Your place for space engineering, destruction and exploring."; MyPerServerSettings.AppId = 0x3bc72; MyObjectBuilderSerializer.UnregisterAssembliesAndSerializers( ); //Start the server MethodInfo dedicatedServerRunMainMethod = InternalType.GetMethod(DedicatedServerRunMainMethod, BindingFlags.Static | BindingFlags.NonPublic); dedicatedServerRunMainMethod.Invoke(null, methodParams); return(true); } catch (Win32Exception ex) { ApplicationLog.BaseLog.Error(ex); return(false); } catch (ExternalException ex) { ApplicationLog.BaseLog.Error(ex); return(false); } catch (TargetInvocationException ex) { //Generally, we won't log this, since it will always be thrown on server stop. if (ExtenderOptions.IsDebugging) { ApplicationLog.BaseLog.Error(ex); } //ApplicationLog.BaseLog.Trace( ex ); return(false); } catch (Exception ex) { ApplicationLog.BaseLog.Error(ex); return(false); } /* * finally * { * _instance = null; * Reset(); * if (_domain != null) * { * AppDomain.Unload(_domain); * } * * GC.Collect(); * GC.WaitForPendingFinalizers(); * } */ }
private void FinishAssembling(MyBlueprintDefinitionBase blueprint) { var amountMult = (MyFixedPoint)(1.0f / MySession.Static.AssemblerEfficiencyMultiplier); for (int i = 0; i < blueprint.Prerequisites.Length; ++i) { var item = blueprint.Prerequisites[i]; InputInventory.RemoveItemsOfType(item.Amount * amountMult, item.Id); } foreach (var res in blueprint.Results) { MyObjectBuilder_PhysicalObject resOb = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(res.Id.TypeId, res.Id.SubtypeName); OutputInventory.AddItems(res.Amount, resOb); } }
//public readonly static Dictionary<long, IMyCubeGrid> Grids = new Dictionary<long, IMyCubeGrid>(); public static void DeconstructGrid(IMyInventory inventory, ref IMyCubeGrid SelectedGrid, ref List <MyObjectBuilder_InventoryItem> Items) { Items.Clear(); var Blocks = new List <IMySlimBlock>(); SelectedGrid.GetBlocks(Blocks); MyObjectBuilder_PhysicalObject physicalObjBuilder; MyPhysicalInventoryItem phys; MyObjectBuilder_CubeBlock Obj; var InvItems = new List <VRage.Game.ModAPI.Ingame.MyInventoryItem>(); MyDefinitionId Id; foreach (var block in Blocks) { block.FullyDismount(inventory); Obj = block.GetObjectBuilder(); if (Obj.ConstructionStockpile != null) { for (var i = 0; i < Obj.ConstructionStockpile.Items.Count(); i++) { phys = new MyPhysicalInventoryItem(Obj.ConstructionStockpile.Items[i].Amount, Obj.ConstructionStockpile.Items[i].PhysicalContent); Id = phys.Content.GetObjectId(); if (!TempItems.ContainsKey(Id)) { TempItems.Add(Id, phys); } else { TempItems[Id] = new MyPhysicalInventoryItem(phys.Amount + TempItems[Id].Amount, phys.Content); } } } if (block.FatBlock != null && block.FatBlock.HasInventory) { InvItems.Clear(); block.FatBlock.GetInventory().GetItems(InvItems); for (var i = 0; i < InvItems.Count; i++) { physicalObjBuilder = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject((MyDefinitionId)InvItems[i].Type); phys = new MyPhysicalInventoryItem(InvItems[i].Amount, physicalObjBuilder); Id = phys.Content.GetObjectId(); if (!TempItems.ContainsKey(Id)) { TempItems.Add(Id, phys); } else { TempItems[Id] = new MyPhysicalInventoryItem(phys.Amount + TempItems[Id].Amount, phys.Content); } } } } foreach (var item in TempItems) { Items.Add(item.Value.GetObjectBuilder()); } TempItems.Clear(); }
public static MyEntity Spawn(this MyPhysicalInventoryItem thisItem, MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null) { if (amount < 0) { return(null); } if (thisItem.Content == null) { Debug.Fail("Can not spawn item with null content!"); return(null); } if (thisItem.Content is MyObjectBuilder_BlockItem) { Debug.Assert(MyFixedPoint.IsIntegral(amount), "Spawning fractional number of grids!"); bool isBlock = typeof(MyObjectBuilder_CubeBlock).IsAssignableFrom(thisItem.Content.GetObjectId().TypeId); Debug.Assert(isBlock, "Block item does not contain block!?!?@&*#%!"); if (!isBlock) { return(null); } var blockItem = thisItem.Content as MyObjectBuilder_BlockItem; MyCubeBlockDefinition blockDefinition; MyDefinitionManager.Static.TryGetCubeBlockDefinition(blockItem.BlockDefId, out blockDefinition); Debug.Assert(blockDefinition != null, "Block definition not found"); if (blockDefinition == null) { return(null); } var builder = MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid; builder.GridSizeEnum = blockDefinition.CubeSize; builder.IsStatic = false; builder.PersistentFlags |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled; builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix); var block = MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock; System.Diagnostics.Debug.Assert(block != null, "Block couldn't been created, maybe wrong definition id? DefID: " + blockItem.BlockDefId); if (block != null) { block.Min = blockDefinition.Size / 2 - blockDefinition.Size + Vector3I.One; builder.CubeBlocks.Add(block); MyCubeGrid firstGrid = null; for (int i = 0; i < amount; ++i) { builder.EntityId = MyEntityIdentifier.AllocateId(); block.EntityId = MyEntityIdentifier.AllocateId(); MyCubeGrid newGrid = MyEntities.CreateFromObjectBuilder(builder) as MyCubeGrid; firstGrid = firstGrid ?? newGrid; MyEntities.Add(newGrid); } return(firstGrid); } return(null); } else { MyPhysicalItemDefinition itemDefinition = null; if (MyDefinitionManager.Static.TryGetPhysicalItemDefinition(thisItem.Content.GetObjectId(), out itemDefinition)) { return(MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(amount, thisItem.Content), worldMatrix, owner != null ? owner.Physics : null)); } return(null); } }
public override bool HandleCommand(ulong userId, string[] words) { if (!words.Any()) { Communication.SendPrivateInformation(userId, GetHelp()); return(true); } if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1 && userId != 0) { Communication.SendPrivateInformation(userId, "Error occurred while processing this command. (1)"); return(true); } Regex rgx = new Regex("[^a-zA-Z0-9]"); string userName = PlayerMap.Instance.GetPlayerNameFromSteamId(userId); if (userId == 0) { userName = "******"; } if (userName == "") { return(true); } string cleanUserName = rgx.Replace(userName, "").ToLower(); string modPath = MyFileSystem.ModsPath; if (!Directory.Exists(modPath)) { Communication.SendPrivateInformation(userId, "Error occurred while processing this command. (2)"); return(true); } string exportPath = Path.Combine(modPath, "Exports"); if (!Directory.Exists(exportPath)) { Directory.CreateDirectory(exportPath); } string userExportPath = Path.Combine(exportPath, cleanUserName); if (!Directory.Exists(userExportPath)) { Directory.CreateDirectory(userExportPath); } string shipName = string.Join(" ", words); HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); long playerId = 0; if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count > 0 && userId != 0) { playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First(); } bool found = false; int count = 0; foreach (IMyEntity entity in entities) { IMyCubeGrid grid = (IMyCubeGrid)entity; if (grid.DisplayName.ToLower().Contains(shipName.ToLower())) { if (grid.BigOwners.Contains(playerId) || PlayerManager.Instance.IsUserAdmin(userId) || userId == 0) { count++; } } } if (count > 1) { Communication.SendPrivateInformation(userId, string.Format("More than one ship was detected to have the name '{0}'. Only the first one found will be exported. Please name your ships uniquely before exporting.", shipName)); } found = false; foreach (IMyEntity entity in entities) { IMyCubeGrid grid = (IMyCubeGrid)entity; if (grid.DisplayName.ToLower().Contains(shipName.ToLower())) { if (grid.BigOwners.Contains(playerId) || PlayerManager.Instance.IsUserAdmin(userId) || userId == 0) { string cleanShipName = rgx.Replace(shipName, ""); MyObjectBuilderSerializer.SerializeXML(new FileInfo(string.Format("{0}\\{1}.sbc", userExportPath, cleanShipName)).FullName, false, entity.GetObjectBuilder( )); Communication.SendPrivateInformation(userId, string.Format("Exported the ship '{0}' to a file on the server.", shipName)); found = true; break; } } } if (!found) { Communication.SendPrivateInformation(userId, string.Format("Unable to find a ship by the name '{0}' that exists or belongs to you!", shipName)); } return(true); }
public override bool HandleCommand(ulong userId, string[] words) { if (!PluginSettings.Instance.DockingEnabled) { return(false); } if (words.Length < 1) { Communication.SendPrivateInformation(userId, GetHelp()); return(true); } if (m_undocking) { Communication.SendPrivateInformation(userId, string.Format("Server is busy, try again")); return(true); } m_undocking = true; try { String pylonName = String.Join(" ", words); if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1) { Communication.SendPrivateInformation(userId, string.Format("Unable to find player Id: {0}", userId)); return(true); } long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First( ); Dictionary <String, List <IMyCubeBlock> > testList; List <IMyCubeBlock> beaconList; DockingZone.FindByName(pylonName, out testList, out beaconList, playerId); if (beaconList.Count == 4) { foreach (IMyCubeBlock entity in beaconList) { if (!Entity.CheckOwnership(entity, playerId)) { Communication.SendPrivateInformation(userId, string.Format("You do not have permission to use '{0}'. You must either own all the beacons or they must be shared with faction.", pylonName)); return(true); } } IMyCubeBlock e = beaconList.First( ); IMyCubeGrid parent = (IMyCubeGrid)e.Parent; long[] beaconListIds = beaconList.Select(p => p.EntityId).ToArray( ); long ownerId = beaconList.First( ).OwnerId; List <DockingItem> dockingItems = Docking.Instance.Find(d => d.PlayerId == ownerId && d.TargetEntityId == parent.EntityId && d.DockingBeaconIds.Intersect(beaconListIds).Count( ) == 4); if (dockingItems.Count < 1) { Communication.SendPrivateInformation(userId, string.Format("You have no ships docked in docking zone '{0}'.", pylonName)); return(true); } DockingItem dockingItem = dockingItems.First( ); // Figure out center of docking area, and other distance information double maxDistance = 99; Vector3D vPos = new Vector3D(0, 0, 0); foreach (IMyCubeBlock b in beaconList) { Vector3D beaconPos = Entity.GetBlockEntityPosition(b); vPos += beaconPos; } vPos = vPos / 4; foreach (IMyCubeBlock b in beaconList) { Vector3D beaconPos = Entity.GetBlockEntityPosition(b); maxDistance = Math.Min(maxDistance, Vector3D.Distance(vPos, beaconPos)); } List <IMySlimBlock> blocks = new List <IMySlimBlock>( ); parent.GetBlocks(blocks); foreach (IMySlimBlock slim_cbe in blocks) { if (slim_cbe is IMyCubeBlock) { IMyCubeBlock cbe = slim_cbe.FatBlock; if (cbe.GetObjectBuilderCubeBlock( ) is MyObjectBuilder_Cockpit) { MyObjectBuilder_Cockpit c = (MyObjectBuilder_Cockpit)cbe.GetObjectBuilderCubeBlock( ); if (c.Pilot != null) { Communication.SendPrivateInformation(userId, string.Format( "Carrier ship has a pilot. The carrier should be unpiloted and fully stopped before undocking. (Sometimes this can lag a bit. Wait 10 seconds and try again)", pylonName)); return(true); } } } } String dockedShipFileName = Essentials.PluginPath + String.Format("\\Docking\\docked_{0}_{1}_{2}.sbc", ownerId, dockingItem.TargetEntityId, dockingItem.DockedEntityId); // Load Entity From File and add to game FileInfo fileInfo = new FileInfo(dockedShipFileName); //CubeGridEntity cubeGrid = new CubeGridEntity(fileInfo); MyObjectBuilder_CubeGrid cubeGrid; MyObjectBuilderSerializer.DeserializeXML(dockedShipFileName, out cubeGrid); // Rotate our ship relative to our saved rotation and the new carrier rotation cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( )) * dockingItem.SaveQuat).GetOrientation( )); // Move our ship relative to the new carrier position and orientation Quaternion newQuat = Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( )); Vector3D rotatedPos = Vector3D.Transform(dockingItem.SavePos, newQuat); //cubeGrid.Position = rotatedPos + parent.GetPosition(); cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(rotatedPos + parent.GetPosition( ), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up); // Add object to world cubeGrid.EntityId = BaseEntity.GenerateEntityId( ); cubeGrid.LinearVelocity = Vector3.Zero; cubeGrid.AngularVelocity = Vector3.Zero; bool undock = false; Wrapper.GameAction(() => { try { MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(cubeGrid); List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>( ); addList.Add(cubeGrid); MyAPIGateway.Multiplayer.SendEntitiesCreated(addList); undock = true; } catch (Exception Ex) { Log.Info(string.Format("Error undocking ship: {0}", Ex.ToString( ))); Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error.")); } }); if (!undock) { return(true); } //SectorObjectManager.Instance.AddEntity(cubeGrid); // Remove the docking file File.Delete(dockedShipFileName); Docking.Instance.Remove(dockingItem); Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", dockingItem.DockedName, pylonName)); /* * // Queue for cooldown * DockingCooldownItem cItem = new DockingCooldownItem(); * cItem.Name = pylonName; * cItem.startTime = DateTime.Now; * * lock (m_cooldownList) * m_cooldownList.Add(cItem); * * IMyEntity gridEntity = MyAPIGateway.Entities.GetEntityById(dockingItem.DockedEntityId); * IMyCubeGrid cubeGrid = (IMyCubeGrid)gridEntity; * * Quaternion q = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation()) * dockingItem.SaveQuat; * Quaternion newQuat = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation()); * Vector3 parentPosition = parent.GetPosition(); * Vector3 rotatedPos = Vector3.Transform(dockingItem.savePos, newQuat); * Vector3 position = rotatedPos + parentPosition; * Matrix positionMatrix = Matrix.CreateFromQuaternion(q); * * cubeGrid.ChangeGridOwnership(playerId, MyOwnershipShareModeEnum.None); * gridEntity.SetPosition(dockingItem.savePos); * * gridEntity.WorldMatrix = positionMatrix; * gridEntity.SetPosition(position); * * // We need to update again, as this doesn't seem to sync properly? I set world matrix, and setposition, and it doesn't go where it should, and I * // have to bump into it for it to show up, it's mega weird. * * if (PluginDocking.Settings.DockingItems == null) * throw new Exception("DockingItems is null"); * * // Remove from docked items * PluginDocking.Settings.DockingItems.Remove(dockingItem); * * // Notify user * Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", gridEntity.DisplayName, pylonName)); */ // Queue for cooldown /* * DockingCooldownItem cItem = new DockingCooldownItem(); * cItem.name = pylonName; * cItem.startTime = DateTime.Now; * PluginDocking.CooldownList.Add(cItem); */ } else if (beaconList.Count > 4) // Too many beacons, must be 4 { Communication.SendPrivateInformation(userId, string.Format("Too many beacons with the name or another zone with the name '{0}'. Place only 4 beacons to create a zone or try a different zone name.", pylonName)); } else // Can't find docking zone { Communication.SendPrivateInformation(userId, string.Format("Can not locate docking zone '{0}'. There must be 4 beacons with the name '{0}' to create a docking zone. Beacons must be fully built!", pylonName)); } } catch (NullReferenceException ex) { Log.Error(ex); } finally { m_undocking = false; } return(true); }
public static bool WriteSpaceEngineersFilePB <T>(T myObject, string filename, bool compress) where T : MyObjectBuilder_Base { return(MyObjectBuilderSerializer.SerializePB(filename, compress, myObject)); }
public static MyEntity SpawnRandomStaticSmall(Vector3 position) { MyPhysicalInventoryItem i = new MyPhysicalInventoryItem(4 * (MyFixedPoint)MyUtils.GetRandomFloat(0f, 100f), MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone")); return(Spawn(ref i, position, Vector3.Zero)); }
/// <returns>True if it sucessfully deserialized the file.</returns> public static bool TryReadSpaceEngineersFile <T>(string filename, out T outObject, out bool isCompressed, out string errorInformation, bool snapshot = false, bool specificExtension = false) where T : MyObjectBuilder_Base { string protoBufFile = null; if (specificExtension) { if ((Path.GetExtension(filename) ?? string.Empty).EndsWith(SpaceEngineersConsts.ProtobuffersExtension, StringComparison.OrdinalIgnoreCase)) { protoBufFile = filename; } } else { if ((Path.GetExtension(filename) ?? string.Empty).EndsWith(SpaceEngineersConsts.ProtobuffersExtension, StringComparison.OrdinalIgnoreCase)) { protoBufFile = filename; } else { protoBufFile = filename + SpaceEngineersConsts.ProtobuffersExtension; } } if (protoBufFile != null && File.Exists(protoBufFile)) { var tempFilename = protoBufFile; if (snapshot) { // Snapshot used for Report on Dedicated servers to prevent locking of the orginal file whilst reading it. tempFilename = TempfileUtil.NewFilename(); File.Copy(protoBufFile, tempFilename); } using (var fileStream = new FileStream(tempFilename, FileMode.Open, FileAccess.Read)) { var b1 = fileStream.ReadByte(); var b2 = fileStream.ReadByte(); isCompressed = (b1 == 0x1f && b2 == 0x8b); } bool retCode; try { // A failure to load here, will only mean it falls back to try and read the xml file instead. // So a file corruption could easily have been covered up. retCode = MyObjectBuilderSerializer.DeserializePB <T>(tempFilename, out outObject); } catch (InvalidCastException ex) { outObject = null; errorInformation = string.Format(Res.ErrorLoadFileError, filename, ex.AllMessages()); return(false); } if (retCode && outObject != null) { errorInformation = null; return(true); } return(TryReadSpaceEngineersFileXml(filename, out outObject, out isCompressed, out errorInformation, snapshot)); } return(TryReadSpaceEngineersFileXml(filename, out outObject, out isCompressed, out errorInformation, snapshot)); }
/// <summary> /// Find the physical object of the specified name or partial name. /// </summary> /// <param name="itemName">The name of the physical object to find.</param> /// <param name="objectBuilder">The object builder of the physical object, ready for use.</param> /// <param name="options">Returns a list of potential matches if there was more than one of the same or partial name.</param> /// <returns>Returns true if a single exact match was found.</returns> public static bool FindPhysicalParts(string itemName, out MyObjectBuilder_Base objectBuilder, out Dictionary <string, MyDefinitionBase> options) { BuildComponentLists(); itemName = itemName.Trim(); var itemNames = itemName.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // prefix the search term with 'ore' to find this ore name. if (itemNames.Length > 1 && itemNames[0].Equals("ore", StringComparison.InvariantCultureIgnoreCase)) { var findName = itemName.Substring(4).Trim(); var exactMatchOres = _oreList.Where(ore => ore.Value.Id.SubtypeName.Equals(findName, StringComparison.InvariantCultureIgnoreCase)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (exactMatchOres.Count == 1) { objectBuilder = new MyObjectBuilder_Ore() { SubtypeName = exactMatchOres.First().Value.Id.SubtypeName }; options = new Dictionary <string, MyDefinitionBase>(); return(true); } if (exactMatchOres.Count > 1) { objectBuilder = null; options = exactMatchOres; return(false); } var partialMatchOres = _oreList.Where(ore => ore.Value.Id.SubtypeName.IndexOf(findName, StringComparison.InvariantCultureIgnoreCase) >= 0).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (partialMatchOres.Count == 1) { objectBuilder = new MyObjectBuilder_Ore() { SubtypeName = partialMatchOres.First().Value.Id.SubtypeName }; options = new Dictionary <string, MyDefinitionBase>(); return(true); } if (partialMatchOres.Count > 1) { objectBuilder = null; options = partialMatchOres; return(false); } objectBuilder = null; options = new Dictionary <string, MyDefinitionBase>(); return(false); } // prefix the search term with 'ingot' to find this ingot name. if (itemNames.Length > 1 && itemNames[0].Equals("ingot", StringComparison.InvariantCultureIgnoreCase)) { var findName = itemName.Substring(6).Trim(); var exactMatchIngots = _ingotList.Where(ingot => ingot.Value.Id.SubtypeName.Equals(findName, StringComparison.InvariantCultureIgnoreCase)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (exactMatchIngots.Count == 1) { objectBuilder = new MyObjectBuilder_Ingot() { SubtypeName = exactMatchIngots.First().Value.Id.SubtypeName }; options = new Dictionary <string, MyDefinitionBase>(); return(true); } if (exactMatchIngots.Count > 1) { objectBuilder = null; options = exactMatchIngots; return(false); } var partialMatchIngots = _ingotList.Where(ingot => ingot.Value.Id.SubtypeName.IndexOf(findName, StringComparison.InvariantCultureIgnoreCase) >= 0).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (partialMatchIngots.Count == 1) { objectBuilder = new MyObjectBuilder_Ingot() { SubtypeName = partialMatchIngots.First().Value.Id.SubtypeName }; options = new Dictionary <string, MyDefinitionBase>(); return(true); } if (partialMatchIngots.Count > 1) { objectBuilder = null; options = partialMatchIngots; return(false); } objectBuilder = null; options = new Dictionary <string, MyDefinitionBase>(); return(false); } // full name match. var res = _physicalItemNames.FirstOrDefault(s => s.Key != null && s.Key.Equals(itemName, StringComparison.InvariantCultureIgnoreCase)); // need a good method for finding partial name matches. if (res.Key == null) { var matches = _physicalItemNames.Where(s => s.Key != null && s.Key.StartsWith(itemName, StringComparison.InvariantCultureIgnoreCase)).Distinct().ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (matches.Count == 1) { res = matches.FirstOrDefault(); } else { matches = _physicalItemNames.Where(s => s.Key != null && s.Key.IndexOf(itemName, StringComparison.InvariantCultureIgnoreCase) >= 0).Distinct().ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (matches.Count == 1) { res = matches.FirstOrDefault(); } else if (matches.Count > 1) { objectBuilder = null; options = matches; return(false); } } } if (res.Key != null) { if (res.Value != null) { objectBuilder = MyObjectBuilderSerializer.CreateNewObject(res.Value.Id.TypeId, res.Value.Id.SubtypeName); options = new Dictionary <string, MyDefinitionBase>(); return(true); } } objectBuilder = null; options = new Dictionary <string, MyDefinitionBase>(); return(false); }
public static MyObjectBuilder_CubeBlock CreateObjectBuilder(MyCubeBlock cubeBlock) { MyObjectBuilder_CubeBlock objectBuilder = (MyObjectBuilder_CubeBlock)MyObjectBuilderSerializer.CreateNewObject(cubeBlock.BlockDefinition.Id); return(objectBuilder); }
private void TransferRemainingComponents() { MyObjectBuilder_CubeBlock block; try { if (m_targetBlock.FatBlock == null) { block = m_targetBlock.GetObjectBuilder(); } else { block = m_targetBlock.FatBlock.GetObjectBuilderCubeBlock(); } } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("ERROR getting cubeblock object builder (1): {0} {1} - {2}", m_targetBlock.IsDestroyed, m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.GetType().Name : m_targetBlock.GetType().Name, ex.ToString())); return; } MyCubeBlockDefinition blockDefinition; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDefinition)) { Dictionary <string, MyTuple <int, MyPhysicalItemDefinition> > components = new Dictionary <string, MyTuple <int, MyPhysicalItemDefinition> >(); foreach (var item in blockDefinition.Components) { var inventoryItem = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.DeconstructItem.Id); if (!components.ContainsKey(item.DeconstructItem.Id.SubtypeName)) { components.Add(item.DeconstructItem.Id.SubtypeName, new MyTuple <int, MyPhysicalItemDefinition>(item.Count, item.DeconstructItem)); } else { components[item.DeconstructItem.Id.SubtypeName] = new MyTuple <int, MyPhysicalItemDefinition>(components[item.DeconstructItem.Id.SubtypeName].Item1 + item.Count, item.DeconstructItem); } } foreach (var item in m_missingComponents) { if (components.ContainsKey(item.Key)) { components[item.Key] = new MyTuple <int, MyPhysicalItemDefinition>(components[item.Key].Item1 - item.Value, components[item.Key].Item2); } if (components[item.Key].Item1 <= 0) { components.Remove(item.Key); } } foreach (var item in components) { TransferFromItem((MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.Value.Item2.Id), item.Value.Item1); } } foreach (var item in m_inventory) { MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(item.Value.Item1, item.Value.Item2), Vector3D.Transform(m_targetBlock.Position * m_targetBlock.CubeGrid.GridSize, m_targetBlock.CubeGrid.WorldMatrix), m_targetBlock.CubeGrid.WorldMatrix.Forward, m_targetBlock.CubeGrid.WorldMatrix.Up); } }
private void WormholeTransferOutFile(string sendto, IMyCubeGrid grid, IMyJumpDrive WormholeDrive, Vector3D gatepoint, List <IMyJumpDrive> WormholeDrives) { if (!Config.JumpDriveSubid.Split(',').Any(s => s.Trim() == WormholeDrive.BlockDefinition.SubtypeId) && !Config.WorkWithAllJD) { return; } Request request = default; try { request = MyAPIGateway.Utilities.SerializeFromXML <Request>(WormholeDrive.CustomData); } catch { } string pickeddestination = default; if (request != null) { if (request.PluginRequest) { if (request.Destination != null) { if (sendto.Split(',').Any(s => s.Trim() == request.Destination.Trim())) { pickeddestination = request.Destination.Trim(); } } Request reply = new Request { PluginRequest = false, Destination = null, Destinations = sendto.Split(',').Select(s => s.Trim()).ToArray() }; WormholeDrive.CustomData = MyAPIGateway.Utilities.SerializeToXML <Request>(reply); } } else { Request reply = new Request { PluginRequest = false, Destination = null, Destinations = sendto.Split(',').Select(s => s.Trim()).ToArray() }; WormholeDrive.CustomData = MyAPIGateway.Utilities.SerializeToXML <Request>(reply); } if (Config.AutoSend && sendto.Split(',').Length == 1) { pickeddestination = sendto.Split(',')[0].Trim(); } if (pickeddestination == null) { return; } if (!WormholeDrive.IsWorking || WormholeDrive.CurrentStoredPower != WormholeDrive.MaxStoredPower) { return; } var playerInCharge = MyAPIGateway.Players.GetPlayerControllingEntity(grid); if (playerInCharge == null || !Utilities.HasRightToMove(playerInCharge, grid as MyCubeGrid)) { return; } WormholeDrive.CurrentStoredPower = 0; foreach (var DisablingWormholeDrive in WormholeDrives) { if (Config.JumpDriveSubid.Split(',').Any(s => s.Trim() == DisablingWormholeDrive.BlockDefinition.SubtypeId) || Config.WorkWithAllJD) { DisablingWormholeDrive.Enabled = false; } } List <MyCubeGrid> grids = Utilities.FindGridList(grid.EntityId.ToString(), playerInCharge as MyCharacter, Config.IncludeConnectedGrids); if (grids == null) { return; } if (grids.Count == 0) { return; } MyVisualScriptLogicProvider.CreateLightning(gatepoint); //NEED TO DROP ENEMY GRIDS if (Config.WormholeGates.Any(s => s.Name.Trim() == pickeddestination.Split(':')[0])) { foreach (WormholeGate internalwormhole in Config.WormholeGates) { if (internalwormhole.Name.Trim() == pickeddestination.Split(':')[0].Trim()) { var box = WormholeDrive.GetTopMostParent().WorldAABB; var togatepoint = new Vector3D(internalwormhole.X, internalwormhole.Y, internalwormhole.Z); var togate = new BoundingSphereD(togatepoint, Config.RadiusGate); Utilities.UpdateGridsPositionAndStopLive(WormholeDrive.GetTopMostParent(), Utilities.FindFreePos(togate, (float)(Vector3D.Distance(box.Center, box.Max) + 50))); MyVisualScriptLogicProvider.CreateLightning(togatepoint); } } } else { var destination = pickeddestination.Split(':'); if (3 != destination.Length) { throw new ArgumentException("failed parsing destination '" + destination + "'"); } var transferFileInfo = new Utilities.TransferFileInfo { destinationWormhole = destination[0], steamUserId = playerInCharge.SteamUserId, playerName = playerInCharge.DisplayName, gridName = grid.DisplayName, time = DateTime.Now }; Log.Info("creating filetransfer:" + transferFileInfo.ToString()); var filename = transferFileInfo.createFileName(); List <MyObjectBuilder_CubeGrid> objectBuilders = new List <MyObjectBuilder_CubeGrid>(); foreach (MyCubeGrid mygrid in grids) { if (!(mygrid.GetObjectBuilder(true) is MyObjectBuilder_CubeGrid objectBuilder)) { throw new ArgumentException(mygrid + " has a ObjectBuilder thats not for a CubeGrid"); } objectBuilders.Add(objectBuilder); } MyObjectBuilder_ShipBlueprintDefinition definition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ShipBlueprintDefinition>(); definition.Id = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)), filename); definition.CubeGrids = objectBuilders.Select(x => (MyObjectBuilder_CubeGrid)x.Clone()).ToArray(); HashSet <ulong> sittingPlayerSteamIds = new HashSet <ulong>(); foreach (MyObjectBuilder_CubeGrid cubeGrid in definition.CubeGrids) { foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.CubeBlocks) { cubeBlock.Owner = 0L; cubeBlock.BuiltBy = 0L; if (!Config.ExportProjectorBlueprints) { if (cubeBlock is MyObjectBuilder_ProjectorBase projector) { projector.ProjectedGrids = null; } } if (cubeBlock is MyObjectBuilder_Cockpit cockpit) { if (cockpit.Pilot != null) { List <IMyPlayer> players = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players); var player = (from a in players where a.IdentityId == (cockpit.Pilot.OwningPlayerIdentityId) select a).FirstOrDefault(); var playerSteamId = player.SteamUserId; sittingPlayerSteamIds.Add(playerSteamId); ModCommunication.SendMessageTo(new JoinServerMessage(destination[1] + ":" + destination[2]), playerSteamId); } } } } MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>(); builderDefinition.ShipBlueprints = new[] { definition }; foreach (var playerSteamId in sittingPlayerSteamIds) { KillCharacter(playerSteamId); } if (MyObjectBuilderSerializer.SerializeXML(Utilities.CreateBlueprintPath(Path.Combine(Config.Folder, admingatesfolder), filename), false, builderDefinition)) { if (Config.GridBackup && !MyObjectBuilderSerializer.SerializeXML(Utilities.CreateBlueprintPath(Path.Combine(Config.Folder, backupFolder), filename), false, builderDefinition)) { Log.Error("Failed to save backup of jumping ship"); } // Saves the game if enabled in config. if (Config.SaveOnExit) { grids.ForEach(b => b.Close()); // (re)Starts the task if it has never been started o´r is done if ((saveOnExitTask is null) || saveOnExitTask.IsCompleted) { saveOnExitTask = Torch.Save(); } } else { grids.ForEach(b => b.Close()); } DirectoryInfo gridDirsent = new DirectoryInfo(Config.Folder + "/" + admingatesconfirmsentfolder); //creates just in case fir send gridDirsent.Create(); File.Create(Utilities.CreateBlueprintPath(gridDirsent.FullName, filename)); } } }
public override void Export(FileInfo fileInfo) { MyObjectBuilderSerializer.SerializeXML(fileInfo.FullName, false, ObjectBuilder); }
private void UnmountInternal(float unmountAmount, MyConstructionStockpile outputStockpile = null, bool damageItems = false, bool useDefaultDeconstructEfficiency = 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_PhysicalObject componentBuilder = null; var scrapBuilder = MyFloatingObject.ScrapBuilder; while (unmountAmount * GetDeconstructionEfficiency(groupIndex, damageItems || useDefaultDeconstructEfficiency) >= 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 = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(m_blockDefinition.Components[groupIndex].DeconstructItem.Id); //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 || useDefaultDeconstructEfficiency); topIntegrity -= unmountAmount * GetDeconstructionEfficiency(groupIndex, damageItems || useDefaultDeconstructEfficiency); if (topIntegrity < MOUNT_THRESHOLD) { Integrity += MOUNT_THRESHOLD - topIntegrity; topIntegrity = MOUNT_THRESHOLD; } Debug.Assert(Integrity >= MOUNT_THRESHOLD, "Integrity inconsistent after a dismount of component stack"); }