private static void DoOperationClient(PaintOperation data) { MyVoxelBase target; if (!MyEntities.TryGetEntityById(data.VoxelId, out target)) { return; } var miningDef = MyDefinitionManager.Get <MyVoxelMiningDefinition>(data.MiningId); if (miningDef == null) { return; } var filter = new bool[256]; for (var i = 0; i < filter.Length; i++) { filter[i] = miningDef.MiningEntries.ContainsKey(i); } PaintVoxels(target, data.Position, data.Radius, data.Plane, data.Material, filter, null); }
public VoxelPlacementDefinition(MyObjectBuilder_VoxelMiningDefinition.MiningDef ob, NamedLogger log) { Material = MyDefinitionManager.Get <MyVoxelMaterialDefinition>(ob.VoxelMaterial); if (Material == null) { log.Warning($"Could not find voxel material definition {ob.VoxelMaterial}"); Material = MyVoxelMaterialDefinition.Default; } Volume = ob.VolumeAttribute; var replacementItems = new Dictionary <MyDefinitionId, int>(); foreach (var item in ob.MinedItems) { MyObjectBuilderType type; try { type = MyObjectBuilderType.Parse(item.Type); } catch { log.Warning($"Can not parse defined builder type {item.Type}"); continue; } var key = new MyDefinitionId(type, MyStringHash.GetOrCompute(item.Subtype)); replacementItems[key] = item.Amount; } Items = replacementItems; }
public override bool Check(MyDefinitionId itemId) { var def = MyDefinitionManager.Get <MyInventoryItemDefinition>(itemId); if (def == null) { return(false); } switch (_equality) { case MrzEqualityResult.Equal: return(Math.Abs(def.Mass - _mass) < MrzUtils.Epsilon); case MrzEqualityResult.NotEqual: return(Math.Abs(def.Mass - _mass) > MrzUtils.Epsilon); case MrzEqualityResult.Less: return(def.Mass < _mass); case MrzEqualityResult.Greater: return(def.Mass > _mass); case MrzEqualityResult.LessOrEqual: return(def.Mass <= _mass); case MrzEqualityResult.GreateOrEqual: return(def.Mass >= _mass); default: return(false); } }
public MiningEntry(MyObjectBuilder_VoxelMiningDefinition_MiningDef item) { var dictionary = new Dictionary <MyDefinitionId, int>(); if (item.MinedItems != null) { foreach (MyObjectBuilder_VoxelMiningDefinition_MinedItem minedItem in item.MinedItems) { var sid = new SerializableDefinitionId { TypeIdString = minedItem.Type, SubtypeName = minedItem.Subtype }; dictionary[sid] = minedItem.Amount; } } MinedItems = dictionary; var num = item.Volume.HasValue ? Math.Max(item.Volume.Value, 1) : 64; var materialDefinition = MyDefinitionManager.Get <MyVoxelMaterialDefinition>(item.VoxelMaterial); if (materialDefinition == null || materialDefinition.Index == byte.MaxValue) { MySession.Static.Log.Warning($"Cannot find voxel material {item.VoxelMaterial}"); Material = MyVoxelMaterialDefinition.Default; Volume = 64; } else { Material = materialDefinition; Volume = num; } }
public static void PrepareWeatherDefinition(MyDefinitionManager __instance, ref MyWeatherEffectDefinition __result, ref string subtype) { if (__result != null) { var weatherDefinition = __result; if (LightningManagerPlugin.Config.LightningCharacterHitIntervalMax != -1) { weatherDefinition.LightningCharacterHitIntervalMax = LightningManagerPlugin.Config.LightningCharacterHitIntervalMax; } if (LightningManagerPlugin.Config.LightningCharacterHitIntervalMin != -1) { weatherDefinition.LightningCharacterHitIntervalMin = LightningManagerPlugin.Config.LightningCharacterHitIntervalMin; } if (LightningManagerPlugin.Config.LightningGridHitIntervalMax != -1) { weatherDefinition.LightningGridHitIntervalMax = LightningManagerPlugin.Config.LightningGridHitIntervalMax; } if (LightningManagerPlugin.Config.LightningGridHitIntervalMin != -1) { weatherDefinition.LightningGridHitIntervalMin = LightningManagerPlugin.Config.LightningGridHitIntervalMin; } if (LightningManagerPlugin.Config.LightningIntervalMax != -1) { weatherDefinition.LightningIntervalMax = LightningManagerPlugin.Config.LightningIntervalMax; } if (LightningManagerPlugin.Config.LightningIntervalMin != -1) { weatherDefinition.LightningIntervalMin = LightningManagerPlugin.Config.LightningIntervalMin; } } }
public void Unblit(out IGradeShape fillShape, out IGradeShape excavateShape) { fillShape = excavateShape = null; var def = MyDefinitionManager.Get <RailGradeComponentDefinition>(Definition); if (def == null) { return; } if (def.Support.HasValue) { var s = def.Support.Value; fillShape = CompositeGradeShape.Composite(Edges .Select(e => def.Support.Value.CreateShape(e, false)).ToArray()); } if (def.Excavate.HasValue) { var s = def.Excavate.Value; excavateShape = CompositeGradeShape.Composite(Edges .Select(e => def.Excavate.Value.CreateShape(e, true)).ToArray()); } }
public void Start() { _definitionManager = MyDefinitionManager.Static; _itemValues.Clear(); CalculateUniversalPrices(); }
public MyDefinitionId Decode(int idx) { if (idx < _definitionPalette.Count) { return(_definitionPalette[idx]); } this.GetLogger().Warning($"Trying to decode invalid palette item {idx}; palette is {string.Join(", ", _definitionPalette)}"); return(MyDefinitionManager.GetOfType <MyInventoryItemDefinition>().FirstOrDefault()?.Id ?? default(MyDefinitionId)); }
public static T Definition <T>(MyDefinitionId definition, string msg) where T : MyDefinitionBase { var res = MyDefinitionManager.Get <T>(definition); if (res == null) { Warn($"ASSERT: Failed to find {definition}. {msg}"); } return(res); }
/// <summary> /// Returns a random item id associated with this tag. If no items belong to this tag, or the tag is null, null is returned. /// </summary> /// <param name="tag"></param> /// <returns></returns> public static MyDefinitionId?GetRandomItemFromTag(MyStringHash tag) { var tagDef = MyDefinitionManager.Get <MyItemTagDefinition>(tag); if (tagDef?.Items == null || tagDef.Items.Count == 0) { return(null); } var index = MyRandom.Instance.Next(tagDef.Items.Count); return(tagDef.Items[index].Id); }
private void NotifyInventoryInteractionSuccess(long entityId, SerializableDefinitionId id, int amount) { if (MySession.Static.PlayerEntity == null || MySession.Static.PlayerEntity.EntityId != entityId) { return; } var text = MyTexts.GetString(_definition.SuccessNotification); var itemDefinition = MyDefinitionManager.Get <MyInventoryItemDefinition>(id); _successNotification.Text = string.Format(text, itemDefinition?.DisplayNameText ?? id.ToString(), amount); _successNotification?.Show(); }
public static MyPhysicalItemDefinition GetDefinition(this MyDefinitionManager definitionManager, string typeId, string subtypeName) { MyPhysicalItemDefinition definition = null; MyObjectBuilderType result; if (MyObjectBuilderType.TryParse(typeId, out result)) { var id = new MyDefinitionId(result, subtypeName); MyDefinitionManager.Static.TryGetPhysicalItemDefinition(id, out definition); } return(definition); }
private void EnsureMemorized() { if (_hasMemorized) { return; } _memorizedModifier = MyDefinitionManager.Get <EquiModifierBaseDefinition>(_modifierId); if (_memorizedModifier == null) { MyDefinitionErrors.Add(_owner.Package, $"Failed to find modifier {_modifierId} for {_owner.Id}", LogSeverity.Critical); } _memorizedData = _memorizedModifier?.CreateData(_modifierData); _hasMemorized = true; }
private void TrySpawnEquipment(long deltaFrames) { _spawned = true; MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::{Entity.EntityId}"); var inventory = this.Get <MyInventoryBase>(_definition.Inventory) ?? this.Get <MyInventoryBase>(); if (inventory == null) { return; } MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Inventory {_definition.Inventory}"); var loot = MyDefinitionManager.Get <MyLootTableDefinition>(_definition.LootTable); if (loot == null) { return; } MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Loot table {_definition.LootTable}"); var oldItems = inventory.Items.ToList <MyInventoryItem>(); MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Old count:{oldItems.Count}"); inventory.GenerateContent(loot); var newItems = inventory.Items; MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::New count:{newItems.Count}"); for (var i = 0; i < newItems.Count; i++) { var newItem = newItems.ItemAt(i); if (i >= oldItems.Count) { MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Activating {newItem.DefinitionId}"); MyItemActivateHelper.ActivateItem(Entity, inventory, newItem); continue; } var oldItem = oldItems[i]; if (newItem.Amount > oldItem.Amount) { MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Activating {newItem.DefinitionId}"); MyItemActivateHelper.ActivateItem(Entity, inventory, newItem); } } }
public override void Activate(MyEntityStatComponent owner) { base.Activate(owner); if (owner.Entity == null || _activatedComponentDefinition == null) { return; // can't do anything about this } // Component exists? { MyEntityComponent existingComponent; MyMultiComponent existingMulti; if (owner.Entity.Components.TryGet(_definition.AddedComponent.TypeId, _definition.AddedComponent.SubtypeId, out existingComponent)) { return; } if (owner.Entity.Components.TryGet(_definition.AddedComponent.TypeId, out existingComponent)) { existingMulti = existingComponent as MyMultiComponent; if (existingMulti == null || existingMulti.SubtypeId == _definition.AddedComponent.SubtypeId) { return; } } } if (_activatedComponent == null) { // _activatedComponent = MyEntityComponent.Factory.CreateInstance(_definition.AddedComponent.TypeId); if (_definition.AddedComponent.TypeId == typeof(MyObjectBuilder_PhantomEffectComponent)) { _activatedComponent = new MyPhantomEffectComponent(); } else { throw new Exception("Invalid component type " + _definition.AddedComponent.TypeId); } var def = MyDefinitionManager.Get <MyEntityComponentDefinition>(_definition.AddedComponent); if (def != null) { _activatedComponent.Init(def); } } if (_activatedComponent.Entity == null) { owner.Entity.Components.Add(_activatedComponent); } }
private static void spawnBarbarian(Vector3D position) { var newPos = MyEntities.FindFreePlace(position, 1f, 200, 5, 5f); if (!newPos.HasValue) { return; } var botPosition = newPos.Value; var botDefinition = (MyAgentDefinition)MyDefinitionManager.Get <MyBotDefinition>(barbarianId); var createdEntity = MySession.Static.Scene.CreateEntity(botDefinition.BotEntity); createdEntity.PositionComp.SetWorldMatrix(MatrixD.CreateWorld(botPosition)); botDefinition.RaiseBeforeBotSpawned(createdEntity); MySession.Static.Scene.ActivateEntity(createdEntity); botDefinition.AfterBotSpawned(createdEntity); }
public static MyDefinitionBase GetDefinitionAny(this MyDefinitionManager mgr, MyDefinitionId id) { foreach (var getter in _defGetters) { try { var res = getter(mgr, id); if (res != null) { return(res); } } catch { // ignored } } return(null); }
public override void Init(MyEntity holder, MyHandItem item, MyHandItemBehaviorDefinition definition) { base.Init(holder, item, definition); var def = (MrzVoxelPainterBehaviorDefinition)definition; _mining = MyDefinitionManager.Get <MyVoxelMiningDefinition>(def.Mining); for (var i = 0; i < _filter.Length; i++) { _filter[i] = _mining.MiningEntries.ContainsKey(i); } var material = MyDefinitionManager.Get <MyVoxelMaterialDefinition>(def.PaintMaterial); _fillMaterial = material?.Index ?? (byte)0; _inventory = holder.Get <MyInventoryBase>(MyCharacterConstants.MainInventory); _wrongToolMessage = MrzUtils.CreateNotification(string.Format(def.WrongToolMessage, Item.GetDefinition().DisplayNameText), MrzUtils.NotificationType.Error); }
public override bool Check(MyDefinitionId itemId) { var def = MyDefinitionManager.Get <MyInventoryItemDefinition>(itemId); if (def == null) { return(false); } var itemSize = def.Size; if (def is MyBlockItemDefinition) { MrzUtils.ShowNotificationDebug($"Original mass: {itemSize}"); itemSize *= _blockSize; MrzUtils.ShowNotificationDebug($"Corrected mass: {itemSize}"); } switch (_equality) { case MrzEqualityResult.Equal: return(itemSize == _size); case MrzEqualityResult.NotEqual: return(itemSize != _size); case MrzEqualityResult.Less: return(itemSize.IsLessThan(_size)); case MrzEqualityResult.Greater: return(itemSize.IsGreaterThan(_size)); case MrzEqualityResult.LessOrEqual: return(itemSize.IsLessOrEqual(_size)); case MrzEqualityResult.GreateOrEqual: return(itemSize.IsGreaterOrEqual(_size)); default: return(false); } }
/// <summary> /// Bendy component definition for the given entity container ID /// </summary> /// <param name="entityDef">container ID</param> /// <returns>Definition, or null if none exists</returns> public static BendyComponentDefinition DefinitionFor(MyDefinitionId entityDef) { var containerDef = MyDefinitionManager.Get <MyContainerDefinition>(entityDef); if (containerDef?.Components == null) { return(null); } foreach (var k in containerDef.Components) { var def = k.Definition as BendyComponentDefinition; if (def != null) { return(def); } } return(null); }
public int RemoveItemFuzzy(MyDefinitionId id, int amount) { if (id.TypeId != typeof(MyObjectBuilder_ItemTagDefinition)) { return(RemoveItem(id, amount)); } var def = MyDefinitionManager.Get <MyItemTagDefinition>(id); var removed = 0; foreach (var k in def.Items) { var removedPart = RemoveItem(k.Id, amount); amount -= removedPart; removed += removedPart; if (amount <= 0) { break; } } return(removed); }
public static MyDefinitionBase GetDefinition(this MyDefinitionManager definitionManager, string typeId, string subtypeName) { MyObjectBuilderType result; if (!MyObjectBuilderType.TryParse(typeId, out result)) { return(null); } var id = new MyDefinitionId(result, subtypeName); try { return(MyDefinitionManager.Static.GetDefinition(id)); } catch { // If a item as been removed, like a mod, // or the mod has broken and failed to load, this will return null. return(null); } }
/// <summary> /// Add items of the definition id specified. /// /// If Id is an item, simply add the items. /// If Id is a tag, add a random item with that tag. /// If Id is loot table, add results of that loot table. /// </summary> /// <param name="inventory"></param> /// <param name="id"></param> /// <param name="amount"></param> /// <returns>True if item added, false if item didn't fit</returns> public static bool AddItemsFuzzyOrLoot(this MyInventoryBase inventory, MyDefinitionId id, int amount = 1) { var result = true; if (id.TypeId == typeof(MyObjectBuilder_LootTableDefinition)) { var lootTableDefinition = MyDefinitionManager.Get <MyLootTableDefinition>(id); for (var i = 0; i < amount; i++) { inventory.GenerateContent(lootTableDefinition); } } else if (id.TypeId == typeof(MyObjectBuilder_ItemTagDefinition)) { result = inventory.AddItemsWithTag(id.SubtypeId, amount, true); } else { result = inventory.AddItems(id, amount); } return(result); }
private void OnPhysicsChanged(MyPhysicsComponentBase obj) { if (!obj.Enabled) { return; } var objectMass = obj.Mass; var myMass = objectMass; if (objectMass <= 0) { objectMass = 1f; } var block = Container.Get <MyBlockComponent>(); if (block != null) { var blockDef = MyDefinitionManager.Get <MyBlockDefinition>(block.DefinitionId); if (blockDef != null) { myMass = blockDef.Mass; } } var ratio = MathHelper.Clamp((Definition.MassInfluence ?? myMass) / objectMass, 0, 1); if (Definition.LinearDamping.HasValue) { obj.LinearDamping = MathHelper.Lerp(DefaultLinearDamping, Definition.LinearDamping.Value, ratio); } if (Definition.AngularDamping.HasValue) { obj.AngularDamping = MathHelper.Lerp(DefaultAngularDamping, Definition.AngularDamping.Value, ratio); } }
protected override void Init(MyObjectBuilder_DefinitionBase def) { base.Init(def); var ob = (MyObjectBuilder_EquiHarvestableComponentDefinition)def; _lootTableByTag.Clear(); _lootTableByItem.Clear(); if (ob.Entries == null) { return; } foreach (var k in ob.Entries) { if (string.IsNullOrWhiteSpace(k.From)) { MyDefinitionErrors.Add(Package, $"{Id} has an entry with no from state", LogSeverity.Warning); continue; } if (k.Harvesters == null || k.Harvesters.Length == 0) { MyDefinitionErrors.Add(Package, $"{Id} has an entry with no harvesters", LogSeverity.Warning); continue; } MyLootTableDefinition lootTable = null; if (k.LootTable.HasValue) { lootTable = MyDefinitionManager.Get <MyLootTableDefinition>(k.LootTable.Value); if (lootTable == null) { MyDefinitionErrors.Add(Package, $"{Id} has an entry from {k.From} referring to missing loot table {k.LootTable}", LogSeverity.Warning); continue; } } foreach (var item in k.Harvesters) { if (!item.IsValid()) { MyDefinitionErrors.Add(Package, $"{Id} has an entry with an invalid harvester", LogSeverity.Warning); } } var sourceState = MyStringHash.GetOrCompute(k.From); var destState = MyStringHash.GetOrCompute(k.To); var data = new Data(lootTable, destState, k.RequiresPermission, k.ActionHint ?? "Harvest", MyStringHash.GetOrCompute(k.ActionIcon ?? "Pickup_Item")); foreach (var item in k.Harvesters) { if (!item.IsValid()) { continue; } if (!string.IsNullOrWhiteSpace(item.Tag)) { _lootTableByTag[new TagKey(sourceState, MyStringHash.GetOrCompute(item.Tag))] = data; } else { _lootTableByItem[new DefinitionKey(sourceState, item)] = data; } } } }
protected override void Hit() { if (!MyAPIGateway.Session.IsServerDecider()) { return; } var player = MyAPIGateway.Players.GetPlayerControllingEntity(Holder); if (player == null) { return; } if (!HasPermission(MyPermissionsConstants.Mining)) { player.ShowNotification("You don't have permission to terraform here.", 2000, null, new Vector4(1, 0, 0, 1)); return; } bool isExcavating = ActiveAction == MyHandItemActionEnum.Primary; var radius = isExcavating ? Definition.ExcavateRadius : Definition.FillRadius; uint availableForDeposit; StringBuilder requiredMaterials = null; if (isExcavating) { availableForDeposit = 0; } else { availableForDeposit = Definition.FillVolume; var andHead = -1; var missing = 0; if (!player.IsCreative()) { foreach (var item in Definition.FillMaterial.MinedItems) { var amount = 0; foreach (var inv in Holder.Components.GetComponents <MyInventoryBase>()) { amount += inv.GetItemAmountFuzzy(item.Key); } amount = amount * Definition.FillMaterial.Volume / item.Value; if (amount == 0) { if (requiredMaterials == null) { requiredMaterials = new StringBuilder("You require "); } var itemDef = MyDefinitionManager.Get <MyInventoryItemDefinition>(item.Key); andHead = requiredMaterials.Length; missing++; requiredMaterials.Append(itemDef?.DisplayNameOf() ?? item.Key.ToString()).Append(", "); } availableForDeposit = (uint)Math.Min(availableForDeposit, amount); } } if (missing > 0 && requiredMaterials != null) { if (andHead != -1 && missing >= 2) { requiredMaterials.Insert(andHead, "and "); } requiredMaterials.Remove(requiredMaterials.Length - 2, 2); } } var availableForExcavate = isExcavating ? Definition.ExcavateVolume : 0; uint totalDeposited; uint totalExcavated; bool triedToChange; bool intersectedDynamic; var result = RailGraderSystem.DoGrading(_gradeComponents, Target.Position, radius, availableForDeposit, availableForExcavate, _excavated, Definition.FillMaterial.Material.Index, out totalDeposited, out totalExcavated, testDynamic: true, triedToChange: out triedToChange, intersectedDynamic: out intersectedDynamic); #region Give Items var ranOutOfInventorySpace = false; if (triedToChange && isExcavating && !player.IsCreative()) { for (var i = 0; i < _excavated.Length; i++) { if (_excavated[i] == 0) { continue; } MyVoxelMiningDefinition.MiningEntry einfo; if (Definition.ExcavateDefinition == null || !Definition.ExcavateDefinition.MiningEntries.TryGetValue(i, out einfo)) { continue; } var outputInventory = Holder.GetInventory(MyCharacterConstants.MainInventory); var count = (int)Math.Floor(_excavated[i] / (float)einfo.Volume); if (count == 0) { continue; } _excavated[i] -= (uint)Math.Max(0, count * einfo.Volume); foreach (var k in einfo.MinedItems) { var amount = k.Value * count; if (outputInventory != null && outputInventory.AddItems(k.Key, amount)) { continue; } ranOutOfInventorySpace = true; var pos = MyAPIGateway.Entities.FindFreePlace(Target.Position, radius) ?? Target.Position; MySession.Static.Components.Get <MyFloatingObjects>() ?.Spawn(MyInventoryItem.Create(k.Key, amount), MatrixD.CreateTranslation(pos), null); } } } if (ranOutOfInventorySpace) { player.ShowNotification("Inventory is full", color: new Vector4(1, 0, 0, 1)); } #endregion #region Take Items _depositAccumulation += (int)totalDeposited; if (!player.IsCreative()) { if (_depositAccumulation > 0 && !isExcavating && Definition.FillMaterial.MinedItems != null) { int amnt = (int)Math.Floor(_depositAccumulation / (float)Definition.FillMaterial.Volume); _depositAccumulation -= amnt * Definition.FillMaterial.Volume; if (amnt > 0) { foreach (var k in Definition.FillMaterial.MinedItems) { var required = amnt * k.Value; if (required == 0) { return; } foreach (var inv in Holder.Components.GetComponents <MyInventoryBase>()) { var count = Math.Min(required, inv.GetItemAmountFuzzy(k.Key)); if (count > 0 && inv.RemoveItemsFuzzy(k.Key, count)) { required -= count; } } } } } } #endregion if (totalDeposited > 0 || totalExcavated > 0) { var duraCost = (int)Math.Round(totalDeposited * Definition.FillDurabilityPerVol + totalExcavated * Definition.ExcavateDurabilityPerVol); if (duraCost > 0) { UpdateDurability(-duraCost); } GraderUsed?.Invoke(this, _gradeComponents, totalDeposited, totalExcavated); RailGraderSystem.RaiseDoGrade(_gradeComponents, Target.Position, radius, availableForDeposit, availableForExcavate, Definition.FillMaterial.Material.Index, totalExcavated, totalDeposited); return; } if (!isExcavating && intersectedDynamic && triedToChange) { player.ShowNotification("Cannot fill where there are players or dynamic grids", color: new Vector4(1, 0, 0, 1)); } if (!isExcavating && requiredMaterials != null && triedToChange) { player.ShowNotification(requiredMaterials?.ToString(), color: new Vector4(1, 0, 0, 1)); } }
public override void Init(MyEntityEffectDefinition definition, long applicantEntityId) { base.Init(definition, applicantEntityId); _definition = (EquiComponentEffectDefinition)definition; _activatedComponentDefinition = MyDefinitionManager.Get <MyEntityComponentDefinition>(_definition.AddedComponent); }
public static List <MyGasProperties> GetGasDefinitions(this MyDefinitionManager definitionManager) { return(definitionManager.GetAllDefinitions().Where(e => e.Id.TypeId == typeof(VRage.Game.ObjectBuilders.Definitions.MyObjectBuilder_GasProperties)).Cast <MyGasProperties>().ToList()); }
private static void PlaceEdge(EdgePlacerConfig cfg, Vector3D[] segments) { MyEntity holderEntity; MyEntities.TryGetEntityById(cfg.EntityPlacing, out holderEntity); var holderPlayer = holderEntity != null?MyAPIGateway.Players.GetPlayerControllingEntity(holderEntity) : null; var def = DefinitionFor(cfg.Placed); if (def == null) { MyEventContext.ValidationFailed(); return; } #region Validation if (!MyEventContext.Current.IsLocallyInvoked) { if (holderEntity == null || holderPlayer == null || MyEventContext.Current.Sender.Value != holderPlayer.SteamUserId) { MyEventContext.ValidationFailed(); return; } if (MyAreaPermissionSystem.Static != null) { foreach (var pos in segments) { if (MyAreaPermissionSystem.Static.HasPermission(holderPlayer.IdentityId, pos, MyPermissionsConstants.Build)) { continue; } holderPlayer.ShowNotification("You cannot build here", 2000, null, new Vector4(1, 0, 0, 1)); MyEventContext.ValidationFailed(); return; } } var validPlacedType = false; foreach (var item in holderEntity.GetInventory(MyCharacterConstants.MainInventory).Items) { if (item == null) { continue; } var itemDef = MyDefinitionManager.Get <MyInventoryItemDefinition>(item.DefinitionId) as MyHandItemDefinition; if (itemDef == null) { continue; } foreach (var behaviorDef in itemDef.Behaviors) { var placeDef = behaviorDef as EdgePlacerBehaviorDefinition; if (placeDef == null || placeDef.Placed != cfg.Placed) { continue; } validPlacedType = true; break; } if (validPlacedType) { break; } } if (!validPlacedType) { MyEventContext.ValidationFailed(); MySession.Static.Log.Warning( $"{holderPlayer} tried to place {cfg.Placed}, but has no item that can place it"); return; } var layer = MySession.Static.Components.Get <BendyController>().GetOrCreateLayer(def.Layer); var annotated = AnnotateNodes(layer, segments); var tmp = new List <string>(); if (!ValidatePath(def, layer, annotated, tmp)) { holderPlayer.ShowNotification(string.Join("\n", tmp)); MyEventContext.ValidationFailed(); return; } } #endregion var graph = MySession.Static.Components.Get <BendyController>().GetOrCreateLayer(def.Layer); for (var i = 1; i < segments.Length; i++) { var nextNode = graph.GetOrCreateNode(segments[i - 1]); var prevNode = graph.GetOrCreateNode(segments[i]); if (graph.GetEdge(prevNode, nextNode) != null) { continue; } var obContainer = new MyObjectBuilder_ComponentContainer(); var worldMatrix = MatrixD.CreateWorld((prevNode.Position + nextNode.Position) / 2, Vector3D.Normalize(nextNode.Position - prevNode.Position), Vector3D.Normalize(nextNode.Up + prevNode.Up)); var worldMatrixInv = MatrixD.Invert(worldMatrix); ((ICollection <MyObjectBuilder_EntityComponent>)obContainer.Components).Add( new MyObjectBuilder_BendyComponent() { Overrides = new[] { new MyObjectBuilder_BendyComponent.NodePose { Index = 0, Position = (Vector3)Vector3D.Transform(prevNode.Position, worldMatrixInv), Up = (Vector3)Vector3D.Transform(prevNode.Up, worldMatrixInv) }, new MyObjectBuilder_BendyComponent.NodePose { Index = 1, Position = (Vector3)Vector3D.Transform(nextNode.Position, worldMatrixInv), Up = (Vector3)Vector3D.Transform(nextNode.Up, worldMatrixInv) } } }); var entOb = new MyObjectBuilder_EntityBase() { EntityDefinitionId = (MyDefinitionId)cfg.Placed, PersistentFlags = MyPersistentEntityFlags2.InScene, PositionAndOrientation = new MyPositionAndOrientation(worldMatrix), SubtypeName = cfg.Placed.SubtypeId, ComponentContainer = obContainer }; var entity = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(entOb); if (holderPlayer != null && holderPlayer.IsCreative()) { entity.Components.Get <ConstructableComponent>()?.InstallFromCreative(); ConstructableComponentDefinition.CcComponent test; int test2; entity.Components.Get <ConstructableComponent>() ?.IncreaseIntegrity(1e9f, out test, out test2); } entity.Components.Get <BendyPhysicsComponent>()?.DestroyEnvItems(); EntityAdded?.Invoke(holderEntity, holderPlayer, entity); } }
public static MyDefinitionBase GetDefinition(this MyDefinitionManager definitionManager, MyObjectBuilderType typeId, string subTypeId) { return(definitionManager.GetAllDefinitions().FirstOrDefault(e => e.Id.TypeId == typeId && e.Id.SubtypeName == subTypeId)); }