public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { m_cameraDummy = Matrix.Identity; m_characterDummy = Matrix.Identity; base.Init(objectBuilder, cubeGrid); var chamberOb = objectBuilder as MyObjectBuilder_CryoChamber; if (chamberOb.SteamId != null && chamberOb.SerialId != null) { m_currentPlayerId = new MyPlayer.PlayerId(chamberOb.SteamId.Value, chamberOb.SerialId.Value); } else { m_currentPlayerId = null; } var overlayTexture = BlockDefinition.OverlayTexture; if (!string.IsNullOrEmpty(overlayTexture)) { m_overlayTextureName = overlayTexture; } PowerReceiver = new MyPowerReceiver( MyConsumerGroupEnum.Utility, false, BlockDefinition.IdlePowerConsumption, this.CalculateRequiredPowerInput); PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged; NeedsUpdate |= Common.MyEntityUpdateEnum.BEFORE_NEXT_FRAME; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); var def = BlockDefinition as MyPoweredCargoContainerDefinition; var ob = objectBuilder as MyObjectBuilder_Collector; m_inventory = new MyInventory(def.InventorySize.Volume, def.InventorySize, MyInventoryFlags.CanSend, this); m_inventory.Init(ob.Inventory); m_inventory.ContentsChanged += Inventory_ContentChangedCallback; if (Sync.IsServer && CubeGrid.CreatePhysics) LoadDummies(); var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( MyStringHash.GetOrCompute(def.ResourceSinkGroup), MyEnergyConstants.MAX_REQUIRED_POWER_COLLECTOR, () => base.CheckIsWorking() ? ResourceSink.MaxRequiredInput : 0f); ResourceSink = sinkComp; ResourceSink.Update(); ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged; AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink,this)); SlimBlock.ComponentStack.IsFunctionalChanged += UpdateReceiver; base.EnabledChanged += UpdateReceiver; m_useConveyorSystem = ob.UseConveyorSystem; }
public MyCubeGridSystems(MyCubeGrid grid) { m_cubeGrid = grid; m_terminalSystem_GroupAdded = TerminalSystem_GroupAdded; m_terminalSystem_GroupRemoved = TerminalSystem_GroupRemoved; GyroSystem = new MyGridGyroSystem(m_cubeGrid); WeaponSystem = new MyGridWeaponSystem(); ReflectorLightSystem = new MyGridReflectorLightSystem(m_cubeGrid); if (MyFakes.ENABLE_WHEEL_CONTROLS_IN_COCKPIT) { WheelSystem = new MyGridWheelSystem(m_cubeGrid); } ConveyorSystem = new MyGridConveyorSystem(m_cubeGrid); LandingSystem = new MyGridLandingSystem(); ControlSystem = new MyGroupControlSystem(); CameraSystem = new MyGridCameraSystem(m_cubeGrid); if (MySession.Static.Settings.EnableOxygen) { GasSystem = new MyGridGasSystem(m_cubeGrid); } if (MyPerGameSettings.EnableJumpDrive) { JumpSystem = new MyGridJumpDriveSystem(m_cubeGrid); } if (MyPerGameSettings.EnableShipSoundSystem && (MyFakes.ENABLE_NEW_SMALL_SHIP_SOUNDS || MyFakes.ENABLE_NEW_LARGE_SHIP_SOUNDS) && MySandboxGame.IsDedicated == false) { ShipSoundComponent = new MyShipSoundComponent(); } m_blocksRegistered = true; }
public MyGridShape(MyCubeGrid grid) { m_grid = grid; if (MyPerGameSettings.Destruction) return; if (MyPerGameSettings.UseGridSegmenter) m_segmenter = new MyVoxelSegmentation(); if (!grid.IsStatic) { m_massElements = new Dictionary<Vector3I, HkMassElement>(); } try { m_blockCollector.Collect(grid, m_segmenter, MyVoxelSegmentationType.Simple, m_massElements); m_root = new HkGridShape(m_grid.GridSize, HkReferencePolicy.None); AddShapesFromCollector(); if (!m_grid.IsStatic) { UpdateMassProperties(); } } finally { m_blockCollector.Clear(); } }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); MyDebug.AssertDebug(BlockDefinition is MyRefineryDefinition); m_refineryDef = BlockDefinition as MyRefineryDefinition; InputInventory.Constraint = m_refineryDef.InputInventoryConstraint; bool removed = InputInventory.FilterItemsUsingConstraint(); Debug.Assert(!removed, "Inventory filter removed items which were present in the object builder."); InputInventory.ContentsChanged += inventory_OnContentsChanged; OutputInventory.Constraint = m_refineryDef.OutputInventoryConstraint; removed = OutputInventory.FilterItemsUsingConstraint(); Debug.Assert(!removed, "Inventory filter removed items which were present in the object builder."); OutputInventory.ContentsChanged += inventory_OnContentsChanged; m_queueNeedsRebuild = true; UpgradeValues.Add("Productivity", 0f); UpgradeValues.Add("Effectiveness", 1f); UpgradeValues.Add("PowerEfficiency", 1f); PowerReceiver.RequiredInputChanged += PowerReceiver_RequiredInputChanged; OnUpgradeValuesChanged += UpdateDetailedInfo; UpdateDetailedInfo(); }
public MyCubeGridSystems(MyCubeGrid grid) { m_cubeGrid = grid; m_terminalSystem_GroupAdded = TerminalSystem_GroupAdded; m_terminalSystem_GroupRemoved = TerminalSystem_GroupRemoved; GyroSystem = new MyGridGyroSystem(m_cubeGrid); WeaponSystem = new MyGridWeaponSystem(); ReflectorLightSystem = new MyGridReflectorLightSystem(m_cubeGrid); if (MyFakes.ENABLE_WHEEL_CONTROLS_IN_COCKPIT) { WheelSystem = new MyGridWheelSystem(m_cubeGrid); } ConveyorSystem = new MyGridConveyorSystem(m_cubeGrid); LandingSystem = new MyGridLandingSystem(); ControlSystem = new MyGroupControlSystem(); CameraSystem = new MyGridCameraSystem(m_cubeGrid); if (MySession.Static.Settings.EnableOxygen) { GasSystem = new MyGridGasSystem(m_cubeGrid); } if (MyPerGameSettings.EnableJumpDrive) { JumpSystem = new MyGridJumpDriveSystem(m_cubeGrid); } m_blocksRegistered = true; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { m_cameraDummy = Matrix.Identity; m_characterDummy = Matrix.Identity; base.Init(objectBuilder, cubeGrid); var chamberOb = objectBuilder as MyObjectBuilder_CryoChamber; if (chamberOb.SteamId != null && chamberOb.SerialId != null) { m_currentPlayerId = new MyPlayer.PlayerId(chamberOb.SteamId.Value, chamberOb.SerialId.Value); } else { m_currentPlayerId = null; } var overlayTexture = BlockDefinition.OverlayTexture; if (!string.IsNullOrEmpty(overlayTexture)) { m_overlayTextureName = overlayTexture; } var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup), BlockDefinition.IdlePowerConsumption, this.CalculateRequiredPowerInput); sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged; ResourceSink = sinkComp; NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; }
public MyCubeGridSystems(MyCubeGrid grid) { m_cubeGrid = grid; m_terminalSystem_GroupAdded = TerminalSystem_GroupAdded; m_terminalSystem_GroupRemoved = TerminalSystem_GroupRemoved; ThrustSystem = new MyGridThrustSystem(m_cubeGrid); GyroSystem = new MyGridGyroSystem(m_cubeGrid); WeaponSystem = new MyGridWeaponSystem(); ReflectorLightSystem = new MyGridReflectorLightSystem(m_cubeGrid); if (MyFakes.ENABLE_WHEEL_CONTROLS_IN_COCKPIT) { WheelSystem = new MyGridWheelSystem(m_cubeGrid); } ConveyorSystem = new MyGridConveyorSystem(m_cubeGrid); LandingSystem = new MyGridLandingSystem(); ControlSystem = new MyGroupControlSystem(); CameraSystem = new MyGridCameraSystem(m_cubeGrid); if (MySession.Static.Settings.EnableOxygen) { OxygenSystem = new MyGridOxygenSystem(m_cubeGrid); } JumpSystem = new MyGridJumpDriveSystem(m_cubeGrid); m_cubeGrid.SyncObject.PowerProducerStateChanged += SyncObject_PowerProducerStateChanged; m_blocksRegistered = true; }
protected void CubeGrid_OnGridSplit(MyCubeGrid grid1, MyCubeGrid grid2) { if (m_statorBlock != null) { m_statorBlock.OnGridSplit(); } }
public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid) { var rotorOb = builder as MyObjectBuilder_MotorRotor; base.Init(builder, cubeGrid); LoadDummies(); }
public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid) { base.Init(builder, cubeGrid); var ob = builder as MyObjectBuilder_PistonTop; m_pistonBlockId = ob.PistonBlockId; NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); var ob = (MyObjectBuilder_FunctionalBlock)objectBuilder; m_enabled = ob.Enabled; IsWorkingChanged += CubeBlock_IsWorkingChanged; }
public MyGridContactInfo(ref HkContactPointEvent evnt, MyCubeGrid grid) { Event = evnt; ContactPosition = grid.Physics.ClusterToWorld(evnt.ContactPoint.Position); m_currentEntity = grid; m_collidingEntity = Event.GetOtherEntity(grid) as MyEntity; m_currentBlock = null; m_otherBlock = null; ImpulseMultiplier = 1; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); var ob = (MyObjectBuilder_FunctionalBlock)objectBuilder; m_enabled = ob.Enabled; IsWorkingChanged += CubeBlock_IsWorkingChanged; m_baseIdleSound = BlockDefinition.PrimarySound; m_actionSound = BlockDefinition.ActionSound; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); var ob = (MyObjectBuilder_FunctionalBlock)objectBuilder; m_soundEmitter = new MyEntity3DSoundEmitter(this, true); m_enabled.Value = ob.Enabled; IsWorkingChanged += CubeBlock_IsWorkingChanged; m_baseIdleSound = BlockDefinition.PrimarySound; m_actionSound = BlockDefinition.ActionSound; }
internal MyGridPlacementSettings GetGridPlacementSettings(MyCubeGrid grid, bool isStatic) { switch (grid.GridSizeEnum) { case MyCubeSize.Large: return (isStatic) ? LargeStaticGrid : LargeGrid; case MyCubeSize.Small: return (isStatic) ? SmallStaticGrid : SmallGrid; default: Debug.Fail("Invalid branch."); return LargeGrid; } }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); //var boxshape = new HkBoxShape((LocalAABB.Max - LocalAABB.Min) / 2); //var boxshape = new HkBoxShape(new Vector3(0.43f, MyDefinitionManager.Static.GetCubeSize(MyCubeSize.Large) / 2.0f, 0.43f)); //Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE); //Physics.CreateFromCollisionObject((HkShape)boxshape, Vector3.Zero, WorldMatrix); //Physics.Enabled = true; //boxshape.Base.RemoveReference(); AddDebugRenderComponent(new MyDebugRenderComponentLadder(this)); }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { m_cameraDummy = Matrix.Identity; m_characterDummy = Matrix.Identity; base.Init(objectBuilder, cubeGrid); if (ResourceSink == null) { // we've already created ResourceSink in ancestor! var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup), BlockDefinition.IdlePowerConsumption, this.CalculateRequiredPowerInput); sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged; ResourceSink = sinkComp; } else { // override electricity settings ResourceSink.SetMaxRequiredInputByType(MyResourceDistributorComponent.ElectricityId, BlockDefinition.IdlePowerConsumption); ResourceSink.SetRequiredInputFuncByType(MyResourceDistributorComponent.ElectricityId, this.CalculateRequiredPowerInput); ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged; } var chamberOb = objectBuilder as MyObjectBuilder_CryoChamber; if (chamberOb.SteamId != null && chamberOb.SerialId != null) { m_currentPlayerId = new MyPlayer.PlayerId(chamberOb.SteamId.Value, chamberOb.SerialId.Value); } else { m_currentPlayerId = null; } var overlayTexture = BlockDefinition.OverlayTexture; if (!string.IsNullOrEmpty(overlayTexture)) { m_overlayTextureName = overlayTexture; } HorizonIndicatorEnabled = false; NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME; }
public override void Init(Common.ObjectBuilders.MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid) { base.Init(builder, cubeGrid); NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME; m_connectedBlocks = new Dictionary<ConveyorLinePosition, MyCubeBlock>(); m_dummies = new SortedDictionary<string,MyModelDummy>(Engine.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies); InitDummies(); SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; IsWorkingChanged += MyUpgradeModule_IsWorkingChanged; m_upgrades = BlockDefinition.Upgrades; UpdateIsWorking(); }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); IsWorkingChanged += OnIsWorkingChanged; NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME; InitializeConveyorEndpoint(); SourceComp.Init( BlockDefinition.ResourceSourceGroup, new MyResourceSourceInfo { ResourceTypeId = BlockDefinition.ProducedGas, DefinedOutput = BlockDefinition.MaxGasOutput, ProductionToCapacityMultiplier = 1, IsInfiniteCapacity = true, }); SourceComp.Enabled = IsWorking; ResourceSink.Init( BlockDefinition.ResourceSinkGroup, new MyResourceSinkInfo { ResourceTypeId = MyResourceDistributorComponent.ElectricityId, MaxRequiredInput = BlockDefinition.OperationalPowerConsumption, RequiredInputFunc = ComputeRequiredPower, }); ResourceSink.IsPoweredChanged += PowerReceiver_IsPoweredChanged; ResourceSink.Update(); GameLogic = new MySolarGameLogicComponent(); SolarComponent = GameLogic as MySolarGameLogicComponent; SolarComponent.Initialize(BlockDefinition.PanelOrientation, BlockDefinition.IsTwoSided, BlockDefinition.PanelOffset, this); AddDebugRenderComponent(new MyDebugRenderComponentSolarPanel(this)); SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_OnIsFunctionalChanged; UpdateVisual(); UpdateDisplay(); }
protected bool CheckVelocities() { if (m_forceWeld && m_topBlock == null && m_weldedEntityId.Value.HasValue) { if (MyEntities.TryGetEntityById<MyAttachableTopBlockBase>(m_weldedEntityId.Value.Value, out m_topBlock)) { m_topGrid = m_topBlock.CubeGrid; } } if (!MyFakes.WELD_ROTORS || Sync.IsServer == false) return false; if (m_topBlock == null || m_topGrid == null || m_topGrid.Physics == null) return false; var velSq = CubeGrid.Physics.LinearVelocity.LengthSquared(); if (m_forceWeld || velSq > m_weldSpeedSq) { if (m_welded) { return true; } if (m_topBlock != null && m_topGrid != null && MyWeldingGroups.Static.GetGroup(CubeGrid) != MyWeldingGroups.Static.GetGroup(m_topGrid)) { WeldGroup(); return true; } return false; } const float safeUnweldSpeedDif = 2 * 2; if (!m_forceWeld && velSq < m_weldSpeedSq - safeUnweldSpeedDif && m_welded) { UnweldGroup(); } if (m_welded) return true; return false; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { var ob = objectBuilder as MyObjectBuilder_Collector; var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup), BlockDefinition.RequiredPowerInput, ComputeRequiredPower); ResourceSink = sinkComp; base.Init(objectBuilder, cubeGrid); m_useConveyorSystem.Value = true; if (MyFakes.ENABLE_INVENTORY_FIX) { FixSingleInventory(); } if (this.GetInventory() == null) { MyInventory inventory = new MyInventory(BlockDefinition.InventorySize.Volume, BlockDefinition.InventorySize, MyInventoryFlags.CanSend); Components.Add<MyInventoryBase>(inventory); inventory.Init(ob.Inventory); } Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!"); if (Sync.IsServer && CubeGrid.CreatePhysics) LoadDummies(); ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged; AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink,this)); SlimBlock.ComponentStack.IsFunctionalChanged += UpdateReceiver; base.EnabledChanged += UpdateReceiver; m_useConveyorSystem.Value = ob.UseConveyorSystem; ResourceSink.Update(); NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { var def = BlockDefinition as MyPoweredCargoContainerDefinition; var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( MyStringHash.GetOrCompute(def.ResourceSinkGroup), MyEnergyConstants.MAX_REQUIRED_POWER_COLLECTOR, () => base.CheckIsWorking() ? ResourceSink.MaxRequiredInput : 0f); ResourceSink = sinkComp; ResourceSink.Update(); base.Init(objectBuilder, cubeGrid); var ob = objectBuilder as MyObjectBuilder_Collector; m_useConveyorSystem.Value = true; if (MyFakes.ENABLE_INVENTORY_FIX) { FixSingleInventory(); } if (this.GetInventory() == null) { Components.Add<MyInventoryBase>( new MyInventory(def.InventorySize.Volume, def.InventorySize, MyInventoryFlags.CanSend, this)); this.GetInventory().Init(ob.Inventory); } Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!"); if (Sync.IsServer && CubeGrid.CreatePhysics) LoadDummies(); ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged; AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink,this)); SlimBlock.ComponentStack.IsFunctionalChanged += UpdateReceiver; base.EnabledChanged += UpdateReceiver; m_useConveyorSystem.Value = ob.UseConveyorSystem; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); SolarPanelDefinition = BlockDefinition as MySolarPanelDefinition; IsWorkingChanged += OnIsWorkingChanged; NeedsUpdate = MyEntityUpdateEnum.EACH_100TH_FRAME; var sourceDataList = new List<MyResourceSourceInfo> { new MyResourceSourceInfo {ResourceTypeId = MyResourceDistributorComponent.ElectricityId, DefinedOutput = SolarPanelDefinition.MaxPowerOutput, IsInfiniteCapacity = true, ProductionToCapacityMultiplier = 60*60} }; SourceComp.Init(SolarPanelDefinition.ResourceSourceGroup, sourceDataList); GameLogic = new MySolarGameLogicComponent(); SolarComponent = GameLogic as MySolarGameLogicComponent; SolarComponent.Initialize(SolarPanelDefinition.PanelOrientation, SolarPanelDefinition.IsTwoSided, SolarPanelDefinition.PanelOffset, this); AddDebugRenderComponent(new Components.MyDebugRenderComponentSolarPanel(this)); }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { // Need to be initialized before base.Init because when loading world with producting refinery // it will be missing when recompute power and cause disappearing of refinery. UpgradeValues.Add("Productivity", 0f); UpgradeValues.Add("Effectiveness", 1f); UpgradeValues.Add("PowerEfficiency", 1f); base.Init(objectBuilder, cubeGrid); MyDebug.AssertDebug(BlockDefinition is MyRefineryDefinition); m_refineryDef = BlockDefinition as MyRefineryDefinition; if (InventoryAggregate.InventoryCount > 2) { Debug.Fail("Inventory aggregate has to many inventories, probably wrong save. If you continue the unused inventories will be removed. Save the world to correct it. Please report this is if problem prevail."); FixInputOutputInventories(m_refineryDef.InputInventoryConstraint, m_refineryDef.OutputInventoryConstraint); } InputInventory.Constraint = m_refineryDef.InputInventoryConstraint; bool removed = InputInventory.FilterItemsUsingConstraint(); Debug.Assert(!removed, "Inventory filter removed items which were present in the object builder."); OutputInventory.Constraint = m_refineryDef.OutputInventoryConstraint; removed = OutputInventory.FilterItemsUsingConstraint(); Debug.Assert(!removed, "Inventory filter removed items which were present in the object builder."); m_queueNeedsRebuild = true; m_baseIdleSound = BlockDefinition.PrimarySound; m_processSound = BlockDefinition.ActionSound; ResourceSink.RequiredInputChanged += PowerReceiver_RequiredInputChanged; OnUpgradeValuesChanged += UpdateDetailedInfo; UpdateDetailedInfo(); NeedsUpdate |= VRage.ModAPI.MyEntityUpdateEnum.EACH_100TH_FRAME; }
public void Init(MyCubeGrid grid) { PlayerOwnedBlocks = new Dictionary<long, int>(); PlayerOwnedValidBlocks = new Dictionary<long, int>(); BigOwners = new List<long>(); SmallOwners = new List<long>(); MaxBlocks = 0; gridEntityId = grid.EntityId; //Finds max blocks within owners: Slow! foreach (var block in grid.GetFatBlocks<MyCubeBlock>()) { var blockOwner = block.OwnerId; if (blockOwner == 0) continue; if (!PlayerOwnedBlocks.ContainsKey(blockOwner)) PlayerOwnedBlocks.Add(blockOwner, 0); PlayerOwnedBlocks[blockOwner]++; if (!IsValidBlock(block)) continue; if (!PlayerOwnedValidBlocks.ContainsKey(blockOwner)) PlayerOwnedValidBlocks.Add(blockOwner, 0); if (++PlayerOwnedValidBlocks[block.OwnerId] > MaxBlocks) MaxBlocks = PlayerOwnedValidBlocks[blockOwner]; } NeedRecalculateOwners = true; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); var def = BlockDefinition as MyCargoContainerDefinition; var ob = objectBuilder as MyObjectBuilder_Collector; m_inventory = new MyInventory(def.InventorySize.Volume, def.InventorySize, MyInventoryFlags.CanSend, this); m_inventory.Init(ob.Inventory); m_inventory.ContentsChanged += Inventory_ContentChangedCallback; if (Sync.IsServer && CubeGrid.CreatePhysics) LoadDummies(); PowerReceiver = new MyPowerReceiver( group: MyConsumerGroupEnum.Conveyors, isAdaptible: false, maxRequiredInput: MyEnergyConstants.MAX_REQUIRED_POWER_COLLECTOR, requiredInputFunc: () => base.CheckIsWorking() ? PowerReceiver.MaxRequiredInput : 0f); PowerReceiver.Update(); PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged; AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(PowerReceiver,this)); SlimBlock.ComponentStack.IsFunctionalChanged += UpdateReceiver; base.EnabledChanged += UpdateReceiver; m_useConveyorSystem = ob.UseConveyorSystem; }
private void GridSplit(MyCubeGrid unused, MyCubeGrid alsoUnused) { GridEvaluation(); }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { m_warheadDefinition = (MyWarheadDefinition)BlockDefinition; base.Init(objectBuilder, cubeGrid); var ob = (MyObjectBuilder_Warhead)objectBuilder; m_countdownMs = ob.CountdownMs; m_isArmed = ob.IsArmed; if (ob.IsCountingDown) StartCountdown(); this.IsWorkingChanged += MyWarhead_IsWorkingChanged; UseDamageSystem = true; }
public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid) { base.Init(builder, cubeGrid); ProfilerShort.Begin("FP.Init"); CheckConnectionAllowed = true; var ob = builder as MyObjectBuilder_FracturedBlock; if (ob.Shapes.Count == 0) { ProfilerShort.End(); if (ob.CreatingFracturedBlock) { return; } Debug.Fail("No relevant shape was found for fractured block. It was probably reexported and names changed."); throw new Exception("No relevant shape was found for fractured block. It was probably reexported and names changed."); } OriginalBlocks = new List <MyDefinitionId>(); Orientations = new List <MyBlockOrientation>(); var lst = new List <HkdShapeInstanceInfo>(); foreach (var def in ob.BlockDefinitions) { var blockDef = MyDefinitionManager.Static.GetCubeBlockDefinition(def); var model = blockDef.Model; if (VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes == null) { MyDestructionData.Static.LoadModelDestruction(model, blockDef, Vector3.One); } var shape = VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes[0]; var si = new HkdShapeInstanceInfo(shape, null, null); lst.Add(si); m_children.Add(si); shape.GetChildren(m_children); if (blockDef.BuildProgressModels != null) { foreach (var progress in blockDef.BuildProgressModels) { model = progress.File; if (VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes == null) { MyDestructionData.Static.LoadModelDestruction(model, blockDef, Vector3.One); } shape = VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes[0]; si = new HkdShapeInstanceInfo(shape, null, null); lst.Add(si); m_children.Add(si); shape.GetChildren(m_children); } } OriginalBlocks.Add(def); } foreach (var or in ob.BlockOrientations) { Orientations.Add(or); } if (ob.MultiBlocks.Count > 0) { MultiBlocks = new List <MultiBlockPartInfo>(); foreach (var mbpart in ob.MultiBlocks) { if (mbpart != null) { MultiBlocks.Add(new MultiBlockPartInfo() { MultiBlockDefinition = mbpart.MultiBlockDefinition, MultiBlockId = mbpart.MultiBlockId }); } else { MultiBlocks.Add(null); } } } m_shapes.AddRange(ob.Shapes); for (int i = 0; i < m_children.Count; i++) { var child = m_children[i]; Func <MyObjectBuilder_FracturedBlock.ShapeB, bool> x = s => s.Name == child.ShapeName; var result = m_shapes.Where(x); if (result.Count() > 0) { var found = result.First(); var m = Matrix.CreateFromQuaternion(found.Orientation); m.Translation = child.GetTransform().Translation; var si = new HkdShapeInstanceInfo(child.Shape.Clone(), m); if (found.Fixed) { si.Shape.SetFlagRecursively(HkdBreakableShape.Flags.IS_FIXED); } lst.Add(si); m_shapeInfos.Add(si); m_shapes.Remove(found); } else { child.GetChildren(m_children); } } if (m_shapeInfos.Count == 0) { m_children.Clear(); ProfilerShort.End(); Debug.Fail("No relevant shape was found for fractured block. It was probably reexported and names changed."); throw new Exception("No relevant shape was found for fractured block. It was probably reexported and names changed."); } foreach (var shape in m_shapeInfos) { if (!string.IsNullOrEmpty(shape.Shape.Name)) { Render.AddPiece(shape.Shape.Name, Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(shape.GetTransform().GetOrientation()))); } } if (CubeGrid.CreatePhysics) { HkdBreakableShape compound = new HkdCompoundBreakableShape(null, m_shapeInfos); ((HkdCompoundBreakableShape)compound).RecalcMassPropsFromChildren(); Shape = compound; var mp = new HkMassProperties(); compound.BuildMassProperties(ref mp); Shape = new HkdBreakableShape(compound.GetShape(), ref mp); compound.RemoveReference(); foreach (var si in m_shapeInfos) { var siRef = si; Shape.AddShape(ref siRef); } Shape.SetStrenght(MyDestructionConstants.STRENGTH); CreateMountPoints(); } m_children.Clear(); foreach (var si in m_shapeInfos) { si.Shape.RemoveReference(); } foreach (var si in lst) { si.RemoveReference(); } m_shapeInfos.Clear(); ProfilerShort.End(); }
public MyGridPositionVerificationStateGroup(MyCubeGrid grid) : base(grid) { m_grid = grid; }
public static void UpdateBeforeSimulation() { if (MySandboxGame.IsGameReady == false) { return; } ProfilerShort.Begin("MyEntities.UpdateBeforeSimulation"); System.Diagnostics.Debug.Assert(MyEntities.UpdateInProgress == false); MyEntities.UpdateInProgress = true; { ProfilerShort.Begin("Before first frame"); MyEntities.UpdateOnceBeforeFrame(); ProfilerShort.BeginNextBlock("Each update"); m_entitiesForUpdate.List.ApplyChanges(); m_entitiesForUpdate.Update(); MySimpleProfiler.Begin("Blocks"); m_entitiesForUpdate.Iterate((x) => { ProfilerShort.Begin(x.GetType().Name); if (x.MarkedForClose == false) { if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.Begin(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.Begin("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.Begin("&&GRID&&" + grid.DisplayName); } } x.UpdateBeforeSimulation(); if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.End(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.End("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.End("&&GRID&&" + grid.DisplayName); } } } ProfilerShort.End(); }); ProfilerShort.BeginNextBlock("10th update"); m_entitiesForUpdate10.List.ApplyChanges(); m_entitiesForUpdate10.Update(); m_entitiesForUpdate10.Iterate((x) => { ProfilerShort.Begin(x.GetType().Name); if (x.MarkedForClose == false) { if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.Begin(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.Begin("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.Begin("&&GRID&&" + grid.DisplayName); } } x.UpdateBeforeSimulation10(); if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.End(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.End("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.End("&&GRID&&" + grid.DisplayName); } } } ProfilerShort.End(); }); ProfilerShort.BeginNextBlock("100th update"); m_entitiesForUpdate100.List.ApplyChanges(); m_entitiesForUpdate100.Update(); m_entitiesForUpdate100.Iterate((x) => { ProfilerShort.Begin(x.GetType().Name); if (x.MarkedForClose == false) { if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.Begin(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.Begin("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.Begin("&&GRID&&" + grid.DisplayName); } } x.UpdateBeforeSimulation100(); if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.End(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.End("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.Begin("&&GRID&&" + grid.DisplayName); } } } ProfilerShort.End(); }); ProfilerShort.End(); } MySimpleProfiler.End("Blocks"); MyEntities.UpdateInProgress = false; ProfilerShort.End(); }
public bool IsWeaponAreaRestricted(MyStringHash subtype, MyOrientedBoundingBoxD cubeBoundingBox, MyCubeGrid myGrid, long ignoredEntity, GridAi gridAi, out MyOrientedBoundingBoxD restrictedBox, out BoundingSphereD restrictedSphere) { _tmpNearByBlocks.Clear(); GridAi ai; if (gridAi == null) { if (!GridToMasterAi.ContainsKey(myGrid)) { restrictedSphere = new BoundingSphereD(); restrictedBox = new MyOrientedBoundingBoxD(); return(false); } ai = GridToMasterAi[myGrid]; } else { ai = gridAi; } CalculateRestrictedShapes(subtype, cubeBoundingBox, out restrictedBox, out restrictedSphere); var queryRadius = Math.Max(restrictedBox.HalfExtent.AbsMax(), restrictedSphere.Radius); if (queryRadius < 0.01) { return(false); } var restriction = WeaponAreaRestrictions[subtype]; var checkBox = restriction.RestrictionBoxInflation > 0; var checkSphere = restriction.RestrictionRadius > 0; var querySphere = new BoundingSphereD(cubeBoundingBox.Center, queryRadius); myGrid.Hierarchy.QuerySphere(ref querySphere, _tmpNearByBlocks); foreach (var grid in ai.SubGrids) { if (grid == myGrid || !GridTargetingAIs.ContainsKey(grid)) { continue; } grid.Hierarchy.QuerySphere(ref querySphere, _tmpNearByBlocks); } for (int l = 0; l < _tmpNearByBlocks.Count; l++) { var cube = _tmpNearByBlocks[l] as MyCubeBlock; if (cube == null || cube.EntityId == ignoredEntity || !WeaponCoreBlockDefs.ContainsKey(cube.BlockDefinition.Id.SubtypeId.String)) { continue; } if (!restriction.CheckForAnyWeapon && cube.BlockDefinition.Id.SubtypeId != subtype) { continue; } if (checkBox) { var cubeBox = new MyOrientedBoundingBoxD(cube.PositionComp.LocalAABB, cube.PositionComp.WorldMatrixRef); if (restrictedBox.Contains(ref cubeBox) != ContainmentType.Disjoint) { return(true); } } if (checkSphere && restrictedSphere.Contains(cube.PositionComp.WorldAABB) != ContainmentType.Disjoint) { return(true); } } return(false); }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); this.IsLargeLight = cubeGrid.GridSizeEnum == MyCubeSize.Large; this.SyncObject = new MySyncLightingBlock(this); var builder = (MyObjectBuilder_LightingBlock)objectBuilder; MyModel lightModel = MyModels.GetModelOnlyDummies(BlockDefinition.Model); foreach (var pair in lightModel.Dummies) { if (!pair.Key.ToLower().Contains("light")) { continue; } m_lightLocalPosition = pair.Value.Matrix.Translation; break; } Vector4 color = (builder.ColorAlpha == -1) ? LightColorDef : new Vector4(builder.ColorRed, builder.ColorGreen, builder.ColorBlue, builder.ColorAlpha); float radius = RadiusBounds.Clamp((builder.Radius == -1f) ? RadiusBounds.Default : builder.Radius); float falloff = FalloffBounds.Clamp(builder.Falloff); m_blinkIntervalSeconds = BlinkIntervalSecondsBounds.Clamp((builder.BlinkIntervalSeconds == -1f) ? BlinkIntervalSecondsBounds.Default : builder.BlinkIntervalSeconds); m_blinkLength = BlinkLenghtBounds.Clamp((builder.BlinkLenght == -1f) ? BlinkLenghtBounds.Default : builder.BlinkLenght); m_blinkOffset = BlinkOffsetBounds.Clamp((builder.BlinkOffset == -1f) ? BlinkOffsetBounds.Default : builder.BlinkOffset); m_intesity = IntensityBounds.Clamp((builder.Intensity == -1f) ? IntensityBounds.Default : builder.Intensity); m_positionDirty = true; m_light = MyLights.AddLight(); InitLight(m_light, color, radius, falloff); m_light.ReflectorRange = ShortReflectorRangeDef; m_light.Range = radius; m_light.PointLightOffset = 0.5f; m_light.ReflectorOn = false; m_light.LightOn = false; m_light.GlareOn = false; UpdateIntensity(); UpdateLightPosition(); NeedsUpdate = MyEntityUpdateEnum.EACH_FRAME; Render.NeedsDrawFromParent = true; PowerReceiver = new MyPowerReceiver( MyConsumerGroupEnum.Utility, false, BlockDefinition.RequiredPowerInput, () => (Enabled && IsFunctional) ? PowerReceiver.MaxRequiredInput : 0f); PowerReceiver.Update(); AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(PowerReceiver, this)); PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged; SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; }
public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid) { m_defId = builder.GetId(); var def = MyDefinitionManager.Static.GetCubeBlockDefinition(m_defId) as MyShipDrillDefinition; var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( def.ResourceSinkGroup, ComputeMaxRequiredPower(), ComputeRequiredPower); ResourceSink = sinkComp; m_drillBase = new MyDrillBase(this, MyDrillConstants.DRILL_SHIP_DUST_EFFECT, MyDrillConstants.DRILL_SHIP_DUST_STONES_EFFECT, MyDrillConstants.DRILL_SHIP_SPARKS_EFFECT, new MyDrillSensorSphere(def.SensorRadius, def.SensorOffset), new MyDrillCutOut(def.SensorOffset, def.SensorRadius), HEAD_SLOWDOWN_TIME_IN_SECONDS, -0.4f, 0.4f, 1 ); base.Init(builder, cubeGrid); m_blockLength = def.Size.Z; m_cubeSideLength = MyDefinitionManager.Static.GetCubeSize(def.CubeSize); float inventoryVolume = def.Size.X * def.Size.Y * def.Size.Z * m_cubeSideLength * m_cubeSideLength * m_cubeSideLength * 0.5f; Vector3 inventorySize = new Vector3(def.Size.X, def.Size.Y, def.Size.Z * 0.5f); if (this.GetInventory() == null) { MyInventory inventory = new MyInventory(inventoryVolume, inventorySize, MyInventoryFlags.CanSend); Components.Add <MyInventoryBase>(inventory); } Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!"); this.GetInventory().Constraint = new MyInventoryConstraint(MySpaceTexts.ToolTipItemFilter_AnyOre) .AddObjectBuilderType(typeof(MyObjectBuilder_Ore)); SlimBlock.UsesDeformation = false; SlimBlock.DeformationRatio = def.DeformationRatio; // 3x times harder for destruction by high speed m_drillBase.OutputInventory = this.GetInventory(); m_drillBase.IgnoredEntities.Add(this); m_drillBase.OnWorldPositionChanged(WorldMatrix); m_wantsToCollect = false; AddDebugRenderComponent(new MyDebugRenderCompomentDrawDrillBase(m_drillBase)); ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged; ResourceSink.Update(); AddDebugRenderComponent(new MyDebugRenderComponentDrawPowerReciever(ResourceSink, this)); var obDrill = (MyObjectBuilder_Drill)builder; this.GetInventory().Init(obDrill.Inventory); SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; m_useConveyorSystem.Value = obDrill.UseConveyorSystem; UpdateDetailedInfo(); m_wantsToDrill = obDrill.Enabled; IsWorkingChanged += OnIsWorkingChanged; m_drillBase.m_drillMaterial = MyStringHash.GetOrCompute("ShipDrill"); m_drillBase.m_idleSoundLoop = new MySoundPair("ToolShipDrillIdle"); }
public override void OnCubeGridChanged(MyCubeGrid oldGrid) { base.OnCubeGridChanged(oldGrid); m_positionDirty = true; }
/// <summary> /// Updates limits on grid split /// </summary> /// <param name="from"></param> /// <param name="to"></param> private static void OnCreateSplit(ref MyCubeGrid from, ref MyCubeGrid to) { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } var toBlocks = new HashSet <MySlimBlock>(to.CubeBlocks); if (toBlocks.Count == 0) { Log.Warn("Could not update count after grid separation"); return; } foreach (var block in toBlocks) { if (block.BuiltBy == block.OwnerId) { Block.DecreaseCount(block.BlockDefinition, block.BuiltBy, 1, from.EntityId); } else { Block.DecreaseCount(block.BlockDefinition, block.BuiltBy, 1, from.EntityId); Block.DecreaseCount(block.BlockDefinition, block.OwnerId); } } var grid = from; if (grid == null) { return; } var removeSmallestGrid = false; var owners = new HashSet <long>(GridCache.GetOwners(from)); owners.UnionWith(GridCache.GetBuilders(grid)); if (owners.Count == 0) { return; } foreach (var owner in owners) { if (!Grid.CountViolation(grid, owner)) { continue; } removeSmallestGrid = true; break; } if (!removeSmallestGrid || BlockLimiterConfig.Instance.BlockType != BlockLimiterConfig.BlockingType.Hard) { return; } var grid1 = from; var grid2 = to; BlockLimiter.Instance.Torch.InvokeAsync(() => { Thread.Sleep(100); if (grid1.BlocksCount > grid2.BlocksCount) { grid2.SendGridCloseRequest(); UpdateLimits.GridLimit(grid1); } else { grid1.SendGridCloseRequest(); UpdateLimits.GridLimit(grid2); } }); }
private void BuildBlock(IMySlimBlock block, MyCubeBlock constructionBlock) { MyObjectBuilder_CubeBlock cubeBlock = block.GetObjectBuilder(); MyObjectBuilder_ProjectorBase projectorBuilder = null;// = (MyObjectBuilder_ProjectorBase)constructionBlock.GetObjectBuilderCubeBlock(); MyCubeGrid projectorGrid = null; MyCubeGrid blockGrid = (MyCubeGrid)block.CubeGrid; MyCubeBlock projector = null; foreach (var item in NaniteConstructionManager.ProjectorBlocks) { var projectorTest = item.Value as IMyProjector; if (projectorTest == null) { continue; } if (projectorTest.ProjectedGrid == null) { continue; } if (projectorTest.ProjectedGrid == block.CubeGrid) { projector = (MyCubeBlock)projectorTest; projectorGrid = projector.CubeGrid; projectorBuilder = (MyObjectBuilder_ProjectorBase)projector.GetObjectBuilderCubeBlock(); break; } } /* * Ingame.IMyGridTerminalSystem system = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid); * List<Ingame.IMyTerminalBlock> terminalBlocks = new List<Ingame.IMyTerminalBlock>(); * system.GetBlocks(terminalBlocks); * foreach(var item in terminalBlocks) * { * if (!(item is IMyFunctionalBlock) || !((IMyFunctionalBlock)item).Enabled) * continue; * * if (!(item is Ingame.IMyProjector)) * continue; * * var cube = (MyCubeBlock)item; * MyObjectBuilder_ProjectorBase testBuilder = (MyObjectBuilder_ProjectorBase)cube.GetObjectBuilderCubeBlock(); * if (testBuilder.ProjectedGrid == null) * continue; * * if(testBuilder.ProjectedGrid.DisplayName == blockGrid.DisplayName) * { * projector = cube; * projectorGrid = cube.CubeGrid; * projectorBuilder = testBuilder; * break; * } * } */ if (projectorBuilder == null) { Logging.Instance.WriteLine("PROBLEM Can not locate projector that is projecting target!"); return; } Quaternion quat = Quaternion.Identity; var orientation = block.Orientation; Matrix local; orientation.GetMatrix(out local); var gridOrientation = GetGridOrientation(projectorBuilder); if (gridOrientation != Matrix.Identity) { var afterRotation = Matrix.Multiply(local, gridOrientation); orientation = new MyBlockOrientation(ref afterRotation); } Quaternion projQuat = Quaternion.Identity; projector.Orientation.GetQuaternion(out projQuat); orientation.GetQuaternion(out quat); quat = Quaternion.Multiply(projQuat, quat); // Get real block max MyCubeBlockDefinition blockDefinition = (MyCubeBlockDefinition)block.BlockDefinition; Vector3I blockMax = block.Max; Vector3I blockMin = cubeBlock.Min; Vector3I position = block.Position; Vector3I min = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(blockMin)); Vector3I max = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(blockMax)); Vector3I pos = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(block.Position)); Vector3I projectedMin = new Vector3I(Math.Min(min.X, max.X), Math.Min(min.Y, max.Y), Math.Min(min.Z, max.Z)); Vector3I projectedMax = new Vector3I(Math.Max(min.X, max.X), Math.Max(min.Y, max.Y), Math.Max(min.Z, max.Z)); MyCubeGrid.MyBlockLocation location = new MyCubeGrid.MyBlockLocation(blockDefinition.Id, projectedMin, projectedMax, pos, quat, 0, constructionBlock.OwnerId); /* * MyObjectBuilder_CubeGrid originalGridBuilder = (MyObjectBuilder_CubeGrid)blockGrid.GetObjectBuilder(); * MyObjectBuilder_CubeBlock objectBuilder = null; * //Find original grid builder * foreach (var blockBuilder in originalGridBuilder.CubeBlocks) * { * if (blockBuilder.GetId() == blockDefinition.Id) * { * if ((Vector3I)blockBuilder.Min == blockMin) * { * objectBuilder = (MyObjectBuilder_CubeBlock)blockBuilder.Clone(); * objectBuilder.SetupForProjector(); * } * } * } */ MyObjectBuilder_CubeBlock objectBuilder = cubeBlock; objectBuilder.SetupForProjector(); var functionalBuilder = objectBuilder as MyObjectBuilder_FunctionalBlock; if (functionalBuilder != null && !functionalBuilder.Enabled) { functionalBuilder.Enabled = true; } var terminalBuilder = objectBuilder as MyObjectBuilder_TerminalBlock; if (terminalBuilder != null) { terminalBuilder.Owner = constructionBlock.OwnerId; } var shipConnector = objectBuilder as MyObjectBuilder_ShipConnector; if (shipConnector != null) { shipConnector.Connected = false; shipConnector.ConnectedEntityId = 0; shipConnector.MasterToSlaveGrid = null; shipConnector.MasterToSlaveTransform = null; } //if (objectBuilder == null) // objectBuilder = cubeBlock; location.EntityId = 0; // MyEntityIdentifier.AllocateId(); objectBuilder.EntityId = 0; objectBuilder.BuiltBy = constructionBlock.OwnerId; objectBuilder.ConstructionInventory = null; projector.CubeGrid.BuildBlockRequest(block.GetColorMask().PackHSVToUint(), location, objectBuilder, constructionBlock.EntityId, false, constructionBlock.OwnerId); }
protected virtual void CreateRotorGrid(out MyCubeGrid rotorGrid, out MyMotorRotor rotorBlock, long builtBy) { CreateRotorGrid(out rotorGrid, out rotorBlock, builtBy, MyDefinitionManager.Static.TryGetDefinitionGroup(MotorDefinition.RotorPart)); }
// Creates prefab, but won't add into scene // WorldMatrix is the matrix of the first grid in the prefab. The others will be transformed to keep their relative positions private void CreateGridsFromPrefab(List <MyCubeGrid> results, string prefabName, MatrixD worldMatrix, bool spawnAtOrigin = false, bool ignoreMemoryLimits = true) { var prefabDefinition = MyDefinitionManager.Static.GetPrefabDefinition(prefabName); Debug.Assert(prefabDefinition != null, "Could not spawn prefab named " + prefabName); if (prefabDefinition == null) { return; } MyObjectBuilder_CubeGrid[] gridObs = prefabDefinition.CubeGrids; Debug.Assert(gridObs.Count() != 0); if (gridObs.Count() == 0) { return; } MyEntities.RemapObjectBuilderCollection(gridObs); MatrixD translateToOriginMatrix; if (spawnAtOrigin) { Vector3D translation = Vector3D.Zero; if (prefabDefinition.CubeGrids[0].PositionAndOrientation.HasValue) { translation = prefabDefinition.CubeGrids[0].PositionAndOrientation.Value.Position; } translateToOriginMatrix = MatrixD.CreateWorld(-translation, Vector3D.Forward, Vector3D.Up); } else { translateToOriginMatrix = MatrixD.CreateWorld(-prefabDefinition.BoundingSphere.Center, Vector3D.Forward, Vector3D.Up); } List <MyCubeGrid> gridsToMove = new List <MyCubeGrid>(); bool needMove = true; Vector3D moveVector = new Vector3D(); bool ignoreMemoryLimitsPrevious = MyEntities.IgnoreMemoryLimits; MyEntities.IgnoreMemoryLimits = ignoreMemoryLimits; for (int i = 0; i < gridObs.Count(); ++i) { MyEntity entity = MyEntities.CreateFromObjectBuilder(gridObs[i]); MyCubeGrid cubeGrid = entity as MyCubeGrid; Debug.Assert(cubeGrid != null, "Could not create grid prefab!"); if (cubeGrid != null) { MatrixD originalGridMatrix = gridObs[i].PositionAndOrientation.HasValue ? gridObs[i].PositionAndOrientation.Value.GetMatrix() : MatrixD.Identity; MatrixD newWorldMatrix; newWorldMatrix = MatrixD.Multiply(originalGridMatrix, MatrixD.Multiply(translateToOriginMatrix, worldMatrix)); if (cubeGrid.IsStatic) { Debug.Assert(Vector3.IsZero(newWorldMatrix.Forward - Vector3.Forward, 0.001f), "Creating a static grid with orientation that is not identity"); Debug.Assert(Vector3.IsZero(newWorldMatrix.Up - Vector3.Up, 0.001f), "Creating a static grid with orientation that is not identity"); Vector3 rounded = default(Vector3I); if (MyPerGameSettings.BuildingSettings.StaticGridAlignToCenter) { rounded = Vector3I.Round(newWorldMatrix.Translation / cubeGrid.GridSize) * cubeGrid.GridSize; } else { rounded = Vector3I.Round(newWorldMatrix.Translation / cubeGrid.GridSize + 0.5f) * cubeGrid.GridSize - 0.5f * cubeGrid.GridSize; } moveVector = new Vector3D(rounded - newWorldMatrix.Translation); newWorldMatrix.Translation = rounded; cubeGrid.WorldMatrix = newWorldMatrix; needMove = false; if (MyPerGameSettings.Destruction) { Debug.Assert(cubeGrid.Physics != null && cubeGrid.Physics.Shape != null); if (cubeGrid.Physics != null && cubeGrid.Physics.Shape != null) { cubeGrid.Physics.Shape.RecalculateConnectionsToWorld(cubeGrid.GetBlocks()); } } } else { newWorldMatrix.Translation += moveVector; cubeGrid.WorldMatrix = newWorldMatrix; if (needMove) { gridsToMove.Add(cubeGrid); } } //if some mods are missing prefab can have 0 blocks, //we don't want to process this grid if (cubeGrid.CubeBlocks.Count > 0) { results.Add(cubeGrid); } } } foreach (var grid in gridsToMove) { MatrixD wmatrix = grid.WorldMatrix; wmatrix.Translation += moveVector; } MyEntities.IgnoreMemoryLimits = ignoreMemoryLimitsPrevious; }
public abstract void GetBlocksPlacementMaterials(HashSet <MyCubeGrid.MyBlockLocation> hashSet, MyCubeGrid grid);
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { SyncFlag = true; base.Init(objectBuilder, cubeGrid); var builder = (MyObjectBuilder_OxygenTank)objectBuilder; IsStockpiling = builder.IsStockpiling; InitializeConveyorEndpoint(); NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME; if (MyFakes.ENABLE_INVENTORY_FIX) { FixSingleInventory(); if (this.GetInventory() != null) { this.GetInventory().Constraint = BlockDefinition.InputInventoryConstraint; } } if (this.GetInventory() == null) { MyInventory inventory = new MyInventory(BlockDefinition.InventoryMaxVolume, BlockDefinition.InventorySize, MyInventoryFlags.CanReceive); inventory.Constraint = BlockDefinition.InputInventoryConstraint; Components.Add <MyInventoryBase>(inventory); inventory.Init(builder.Inventory); } Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!"); m_autoRefill = builder.AutoRefill; var sourceDataList = new List <MyResourceSourceInfo> { new MyResourceSourceInfo { ResourceTypeId = BlockDefinition.StoredGasId, DefinedOutput = 0.05f * BlockDefinition.Capacity }, }; SourceComp.Init(BlockDefinition.ResourceSourceGroup, sourceDataList); SourceComp.OutputChanged += Source_OutputChanged; SourceComp.Enabled = Enabled; var sinkDataList = new List <MyResourceSinkInfo> { new MyResourceSinkInfo { ResourceTypeId = MyResourceDistributorComponent.ElectricityId, MaxRequiredInput = BlockDefinition.OperationalPowerConsumption, RequiredInputFunc = ComputeRequiredPower }, new MyResourceSinkInfo { ResourceTypeId = BlockDefinition.StoredGasId, MaxRequiredInput = Capacity, RequiredInputFunc = ComputeRequiredGas }, }; ResourceSink.Init( BlockDefinition.ResourceSinkGroup, sinkDataList); ResourceSink.IsPoweredChanged += PowerReceiver_IsPoweredChanged; ResourceSink.CurrentInputChanged += Sink_CurrentInputChanged; m_lastOutputUpdateTime = MySession.Static.GameplayFrameCounter; m_lastInputUpdateTime = MySession.Static.GameplayFrameCounter; m_nextGasTransfer = 0f; ChangeFilledRatio(builder.FilledRatio); ResourceSink.Update(); AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint)); SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; IsWorkingChanged += MyOxygenTank_IsWorkingChanged; }
public abstract void GetBlockPlacementMaterials(MyCubeBlockDefinition definition, Vector3I position, MyBlockOrientation orientation, MyCubeGrid grid);
private bool HandleCutInput() { if (MyInput.Static.IsNewKeyPressed(MyKeys.X) && MyInput.Static.IsAnyCtrlKeyPressed()) { MyEntity entity = MyCubeGrid.GetTargetEntity(); if (entity == null) { return(false); } bool handled = false; if (entity is MyCubeGrid && m_clipboard.IsActive == false) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); bool cutGroup = !MyInput.Static.IsAnyShiftKeyPressed(); bool cutOverLg = MyInput.Static.IsAnyAltKeyPressed(); MyEntities.EnableEntityBoundingBoxDraw(entity, true); MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox( buttonType: MyMessageBoxButtonsType.YES_NO, messageText: MyTexts.Get(MyCommonTexts.MessageBoxTextAreYouSureToMoveGridToClipboard), messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionPleaseConfirm), callback: (v) => { if (v == MyGuiScreenMessageBox.ResultEnum.YES) { OnCutConfirm(entity as MyCubeGrid, cutGroup, cutOverLg); } MyEntities.EnableEntityBoundingBoxDraw(entity, false); })); handled = true; } else if (entity is MyVoxelMap && m_voxelClipboard.IsActive == false && MyPerGameSettings.GUI.VoxelMapEditingScreen == typeof(MyGuiScreenDebugSpawnMenu) // hack to disable this in ME ) { MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox( buttonType: MyMessageBoxButtonsType.YES_NO, messageText: MyTexts.Get(MySpaceTexts.MessageBoxTextAreYouSureToRemoveAsteroid), messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionPleaseConfirm), callback: (v) => { if (v == MyGuiScreenMessageBox.ResultEnum.YES) { OnCutAsteroidConfirm(entity as MyVoxelMap); } MyEntities.EnableEntityBoundingBoxDraw(entity, false); })); handled = true; } else if (entity is MyFloatingObject && !m_floatingObjectClipboard.IsActive) { MyEntities.EnableEntityBoundingBoxDraw(entity, true); MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox( buttonType: MyMessageBoxButtonsType.YES_NO, messageText: MyTexts.Get(MyCommonTexts.MessageBoxTextAreYouSureToMoveGridToClipboard), messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionPleaseConfirm), callback: (v) => { if (v == MyGuiScreenMessageBox.ResultEnum.YES) { OnCutFloatingObjectConfirm(entity as MyFloatingObject); handled = true; } MyEntities.EnableEntityBoundingBoxDraw(entity, false); })); handled = true; } if (handled) { return(true); } } return(false); }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { SyncFlag = true; var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( BlockDefinition.ResourceSinkGroup, BlockDefinition.RequiredPowerInput, this.CalculateRequiredPowerInput); ResourceSink = sinkComp; base.Init(objectBuilder, cubeGrid); m_items = new List <ToolbarItem>(2); for (int i = 0; i < 2; i++) { m_items.Add(new ToolbarItem() { EntityID = 0 }); } Toolbar = new MyToolbar(MyToolbarType.ButtonPanel, 2, 1); Toolbar.DrawNumbers = false; var builder = (MyObjectBuilder_SensorBlock)objectBuilder; m_fieldMin.Value = Vector3.Clamp(builder.FieldMin, new Vector3(-MaxRange), -Vector3.One); m_fieldMax.Value = Vector3.Clamp(builder.FieldMax, Vector3.One, new Vector3(MaxRange)); PlayProximitySound = builder.PlaySound; DetectPlayers = builder.DetectPlayers; DetectFloatingObjects = builder.DetectFloatingObjects; DetectSmallShips = builder.DetectSmallShips; DetectLargeShips = builder.DetectLargeShips; DetectStations = builder.DetectStations; DetectAsteroids = builder.DetectAsteroids; DetectOwner = builder.DetectOwner; DetectFriendly = builder.DetectFriendly; DetectNeutral = builder.DetectNeutral; DetectEnemy = builder.DetectEnemy; m_active.Value = builder.IsActive; Toolbar.Init(builder.Toolbar, this); for (int i = 0; i < 2; i++) { var item = Toolbar.GetItemAtIndex(i); if (item == null) { continue; } m_items.RemoveAt(i); m_items.Insert(i, ToolbarItem.FromItem(item)); } Toolbar.ItemChanged += Toolbar_ItemChanged; NeedsUpdate |= MyEntityUpdateEnum.EACH_10TH_FRAME; SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged; ResourceSink.RequiredInputChanged += Receiver_RequiredInputChanged; ResourceSink.Update(); m_fieldShape = GetHkShape(); OnClose += delegate(MyEntity self) { m_fieldShape.RemoveReference(); }; m_gizmoColor = new Vector4(0.35f, 0, 0, 0.5f); }
public MyOndraSimulator2(MyCubeGrid grid) { m_grid = grid; }
// Update all physics objects - AFTER physics simulation public static void UpdateAfterSimulation() { if (MySandboxGame.IsGameReady == false) { return; } VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("UpdateAfterSimulation"); { System.Diagnostics.Debug.Assert(MyEntities.UpdateInProgress == false); MyEntities.UpdateInProgress = true; ProfilerShort.Begin("UpdateAfter1"); m_entitiesForUpdate.List.ApplyChanges(); MySimpleProfiler.Begin("Blocks"); m_entitiesForUpdate.Iterate((x) => { ProfilerShort.Begin(x.GetType().Name); if (x.MarkedForClose == false) { if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.Begin(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.Begin("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.Begin("&&GRID&&" + grid.DisplayName); } } x.UpdateAfterSimulation(); if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.End(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.End("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.End("&&GRID&&" + grid.DisplayName); } } } ProfilerShort.End(); }); ProfilerShort.End(); ProfilerShort.Begin("UpdateAfter10"); m_entitiesForUpdate10.List.ApplyChanges(); m_entitiesForUpdate10.Iterate((x) => { ProfilerShort.Begin(x.GetType().Name); if (x.MarkedForClose == false) { if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.Begin(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.Begin("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.Begin("&&GRID&&" + grid.DisplayName); } } x.UpdateAfterSimulation10(); if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.End(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.End("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.End("&&GRID&&" + grid.DisplayName); } } } ProfilerShort.End(); }); ProfilerShort.End(); ProfilerShort.Begin("UpdateAfter100"); m_entitiesForUpdate100.List.ApplyChanges(); m_entitiesForUpdate100.Iterate((x) => { ProfilerShort.Begin(x.GetType().Name); if (x.MarkedForClose == false) { if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.Begin(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.Begin("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.Begin("&&GRID&&" + grid.DisplayName); } } x.UpdateAfterSimulation100(); if (ProfilePerBlock) { MyCubeBlock block = x as MyCubeBlock; if (block != null) { MySimpleProfiler.End(block.DefinitionDisplayNameText + (ProfilePerGrid ? $" - {block.CubeGrid.DisplayName}" : string.Empty)); if (ProfilePerGrid) { MySimpleProfiler.End("&&GRID&&" + block.CubeGrid.DisplayName); } } } if (ProfilePerGrid) { MyCubeGrid grid = x as MyCubeGrid; if (grid != null) { MySimpleProfiler.End("&&GRID&&" + grid.DisplayName); } } } ProfilerShort.End(); }); ProfilerShort.End(); MySimpleProfiler.End("Blocks"); MyEntities.UpdateInProgress = false; MyEntities.DeleteRememberedEntities(); } if (m_creationThread != null && MyMultiplayer.Static != null) { while (m_creationThread.ConsumeResult(MyMultiplayer.Static.ReplicationLayer.GetSimulationUpdateTime())) { ; // Add entities created asynchronously } } VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock(); }
public void Eject(string gridName = null) { ConcurrentBag <MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Group> gridGroups; if (gridName == null) { if (Context.Player == null) { Context.Respond("The console always has to pass a gridname!"); return; } IMyCharacter character = Context.Player.Character; if (character == null) { Context.Respond("You need to spawn into a character when not using gridname!"); return; } gridGroups = GridFinder.FindLookAtGridGroupMechanical(character); if (gridGroups.Count == 0) { Context.Respond("No grid in your line of sight found! Remember to NOT use spectator!"); return; } } else { gridGroups = GridFinder.FindGridGroupMechanical(gridName); if (gridGroups.Count == 0) { Context.Respond($"Grid with name '{gridName}' was not found!"); return; } if (gridGroups.Count > 1) { Context.Respond($"There were multiple grids with name '{gridName}' to prevent any mistakes this command will not be executed!"); return; } } var group = gridGroups.First(); int ejectedPlayersCount = 0; foreach (var node in group.Nodes) { MyCubeGrid grid = node.NodeData; foreach (var fatBlock in grid.GetFatBlocks()) { if (!(fatBlock is MyShipController shipController)) { continue; } if (shipController.Pilot != null) { shipController.Use(); ejectedPlayersCount++; } } } Context.Respond($"Ejected '{ejectedPlayersCount}' players from their seats."); }
private void ActivateCommon() { BoundingSphereD globalSphere = new BoundingSphereD(Vector3D.Transform(m_detectorSphere.Center, CubeGrid.WorldMatrix), m_detectorSphere.Radius); if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW) { MyRenderProxy.DebugDrawSphere(globalSphere.Center, (float)globalSphere.Radius, Color.Red.ToVector3(), 1.0f, false); } m_isActivatedOnSomething = false; ProfilerShort.Begin("Query"); var res = MyEntities.GetTopMostEntitiesInSphere(ref globalSphere); m_entitiesInContact.Clear(); foreach (MyEntity entity in res) { var rootEntity = entity.GetTopMostParent(); if (CanInteractWith(rootEntity)) { m_entitiesInContact.Add(rootEntity); } } res.Clear(); ProfilerShort.End(); //TODO:cache blocks on this grid foreach (var entry in m_entitiesInContact) { MyCubeGrid grid = entry as MyCubeGrid; MyCharacter character = entry as MyCharacter; if (grid != null) { m_tempBlocksBuffer.Clear(); grid.GetBlocksInsideSphere(ref globalSphere, m_tempBlocksBuffer); m_blocksToActivateOn.UnionWith(m_tempBlocksBuffer); } if (character != null && Sync.IsServer) { MyStringHash damageType = MyDamageType.Drill; if (this is IMyShipGrinder) { damageType = MyDamageType.Grind; } else if (this is IMyShipWelder) { damageType = MyDamageType.Weld; } if (globalSphere.Intersects(character.PositionComp.WorldAABB)) { character.DoDamage(20, damageType, true, attackerId: EntityId); } } } m_isActivatedOnSomething |= Activate(m_blocksToActivateOn); m_activateCounter++; m_lastTimeActivate = MySandboxGame.TotalGamePlayTimeInMilliseconds; PlayLoopSound(m_isActivatedOnSomething); m_blocksToActivateOn.Clear(); }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); m_cubeGrid = cubeGrid; NeedsUpdate |= VRage.ModAPI.MyEntityUpdateEnum.EACH_100TH_FRAME; MyDebug.AssertDebug(BlockDefinition is MyAssemblerDefinition); m_assemblerDef = BlockDefinition as MyAssemblerDefinition; if (InventoryAggregate.InventoryCount > 2) { Debug.Fail("Inventory aggregate has to many inventories, probably wrong save. If you continue the unused inventories will be removed. Save the world to correct it. Please report this is if problem prevail."); FixInputOutputInventories(m_assemblerDef.InputInventoryConstraint, m_assemblerDef.OutputInventoryConstraint); } InputInventory.Constraint = m_assemblerDef.InputInventoryConstraint; OutputInventory.Constraint = m_assemblerDef.OutputInventoryConstraint; bool removed = InputInventory.FilterItemsUsingConstraint(); Debug.Assert(!removed, "Inventory filter removed items which were present in the object builder."); var builder = (MyObjectBuilder_Assembler)objectBuilder; if (builder.OtherQueue != null) { m_otherQueue.Clear(); if (m_otherQueue.Capacity < builder.OtherQueue.Length) { m_otherQueue.Capacity = builder.OtherQueue.Length; } for (int i = 0; i < builder.OtherQueue.Length; ++i) { var item = builder.OtherQueue[i]; var blueprint = MyDefinitionManager.Static.TryGetBlueprintDefinitionByResultId(item.Id); if (blueprint != null) { m_otherQueue.Add(new QueueItem() { Blueprint = blueprint, Amount = item.Amount, }); } else { MySandboxGame.Log.WriteLine(string.Format("No blueprint that produces a single result with Id '{0}'", item.Id)); } } } CurrentProgress = builder.CurrentProgress; m_disassembleEnabled = builder.DisassembleEnabled; m_repeatAssembleEnabled = builder.RepeatAssembleEnabled; m_repeatDisassembleEnabled = builder.RepeatDisassembleEnabled; m_slave = builder.SlaveEnabled; UpdateInventoryFlags(); UpgradeValues.Add("Productivity", 0f); UpgradeValues.Add("PowerEfficiency", 1f); m_baseIdleSound = BlockDefinition.PrimarySound; m_processSound = BlockDefinition.ActionSound; OnUpgradeValuesChanged += UpdateDetailedInfo; ResourceSink.RequiredInputChanged += PowerReceiver_RequiredInputChanged; UpdateDetailedInfo(); }
public MySyncGrid(MyCubeGrid grid) : base(grid) { }
public static List <MyCubeGrid> FindGridList(string gridNameOrEntityId, MyCharacter character, bool includeConnectedGrids) { List <MyCubeGrid> grids = new List <MyCubeGrid>(); if (gridNameOrEntityId == null && character == null) { return(new List <MyCubeGrid>()); } if (includeConnectedGrids) { ConcurrentBag <MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group> groups; if (gridNameOrEntityId == null) { groups = FindLookAtGridGroup(character); } else { groups = FindGridGroup(gridNameOrEntityId); } if (groups.Count > 1) { return(null); } foreach (var group in groups) { foreach (var node in group.Nodes) { MyCubeGrid grid = node.NodeData; if (grid.Physics == null) { continue; } grids.Add(grid); } } } else { ConcurrentBag <MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Group> groups; if (gridNameOrEntityId == null) { groups = FindLookAtGridGroupMechanical(character); } else { groups = FindGridGroupMechanical(gridNameOrEntityId); } if (groups.Count > 1) { return(null); } foreach (var group in groups) { foreach (var node in group.Nodes) { MyCubeGrid grid = node.NodeData; if (grid.Physics == null) { continue; } grids.Add(grid); } } } return(grids); }
private void OwnershipChanged(MyCubeGrid unused) { GetOwnerType(); }
// This function uses RequiredMaterials, so call to Get...Materials has to precede it! public abstract void AfterGridCreated(MyCubeGrid grid, MyEntity builder);
public override void OnAddedToContainer() { base.OnAddedToContainer(); m_grid = Entity as MyCubeGrid; m_grid.OnBlockAdded += m_grid_OnBlockAdded; }
public override void OnAddedToContainer() { base.OnAddedToContainer(); m_grid = Container.Entity as MyCubeGrid; }
public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid) { base.Init(builder, cubeGrid); var ob = (MyObjectBuilder_AirtightDoorGeneric)builder; m_open = ob.Open; m_currOpening = ob.CurrOpening; m_openingSpeed = BlockDefinition.OpeningSpeed; m_sound = new MySoundPair(BlockDefinition.Sound); m_subpartMovementDistance = BlockDefinition.SubpartMovementDistance; PowerReceiver = new MyPowerReceiver(MyConsumerGroupEnum.Doors, false, BlockDefinition.PowerConsumptionMoving, () => UpdatePowerInput()); PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged; PowerReceiver.Update(); if (!Enabled || !PowerReceiver.IsPowered) UpdateDoorPosition(); OnStateChange(); SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; PowerReceiver.Update(); }
private static void InitGrid(MyCubeGrid grid) { Essentials.Log.Debug($"intializing on grid {grid.DisplayName}"); grid.OnBlockAdded += Grid_OnBlockAdded; grid.OnBlockRemoved += Grid_OnBlockRemoved; grid.OnMarkForClose += Grid_OnMarkForClose; foreach (var item in PluginSettings.Instance.PlayerBlockEnforcementItems) { switch (item.Mode) { case SettingsBlockEnforcementItem.EnforcementMode.Off: continue; case SettingsBlockEnforcementItem.EnforcementMode.BlockSubtypeId: foreach (var block in grid.CubeBlocks) { var fatBlock = block?.FatBlock as MyTerminalBlock; if (fatBlock == null || fatBlock.Closed) { continue; } if (!fatBlock.BlockDefinition.Id.SubtypeName.Contains(item.BlockSubtypeId)) { continue; } fatBlock.OwnershipChanged += FatBlock_OwnershipChanged; if (fatBlock.OwnerId == 0) { if (fatBlock.CubeGrid.BigOwners.Count > 0 && PluginSettings.Instance.PlayerBlockEnforcementChangeOwner) { MyAPIGateway.Utilities.InvokeOnGameThread(() => fatBlock.ChangeBlockOwnerRequest(fatBlock.CubeGrid.BigOwners.First(), MyOwnershipShareModeEnum.Faction)); } else if (PluginSettings.Instance.PlayerBlockEnforcementChangeOwner) { ChangeOwnershipToNearestPlayer(fatBlock); } } if (fatBlock.OwnerId != 0) { lock (BlockOwners) BlockOwners[fatBlock] = fatBlock.OwnerId; } } break; case SettingsBlockEnforcementItem.EnforcementMode.BlockTypeId: foreach (var block in grid.CubeBlocks) { var fatBlock = block?.FatBlock as MyTerminalBlock; if (fatBlock == null || fatBlock.Closed) { continue; } if (!fatBlock.BlockDefinition.Id.TypeId.ToString().Contains(item.BlockTypeId)) { continue; } fatBlock.OwnershipChanged += FatBlock_OwnershipChanged; if (fatBlock.OwnerId == 0) { if (fatBlock.CubeGrid.BigOwners.Count > 0 && PluginSettings.Instance.PlayerBlockEnforcementChangeOwner) { MyAPIGateway.Utilities.InvokeOnGameThread(() => fatBlock.ChangeBlockOwnerRequest(fatBlock.CubeGrid.BigOwners.First(), MyOwnershipShareModeEnum.Faction)); } else if (PluginSettings.Instance.PlayerBlockEnforcementChangeOwner) { ChangeOwnershipToNearestPlayer(fatBlock); } } if (fatBlock.OwnerId != 0) { lock (BlockOwners) BlockOwners[fatBlock] = fatBlock.OwnerId; } } break; } } }
public virtual void OnBlockOwnershipChanged(MyCubeGrid cubeGrid) { ConveyorSystem.FlagForRecomputation(); }
private bool CanBuildBlock(MyObjectBuilder_CubeBlock block, MyCubeGrid blockGrid, MyCubeBlock projector, MyCubeGrid projectorGrid, MyObjectBuilder_ProjectorBase projectorBuilder) { MyBlockOrientation blockOrientation = block.BlockOrientation; Matrix local; blockOrientation.GetMatrix(out local); var gridOrientation = GetGridOrientation(projectorBuilder); if (gridOrientation != Matrix.Identity) { var afterRotation = Matrix.Multiply(local, gridOrientation); blockOrientation = new MyBlockOrientation(ref afterRotation); } Quaternion blockOrientationQuat; blockOrientation.GetQuaternion(out blockOrientationQuat); Quaternion projQuat = Quaternion.Identity; projector.Orientation.GetQuaternion(out projQuat); blockOrientationQuat = Quaternion.Multiply(projQuat, blockOrientationQuat); MyCubeBlockDefinition blockDefinition; MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDefinition); // Get real block max Vector3I blockMax = Vector3I.Zero; Vector3I blockMin = block.Min; ComputeMax(blockDefinition, block.BlockOrientation, ref blockMin, out blockMax); var position = ComputePositionInGrid(new MatrixI(block.BlockOrientation), blockDefinition, blockMin); Vector3I projectedMin = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(block.Min)); Vector3I projectedMax = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(blockMax)); Vector3I blockPos = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(position)); Vector3I min = new Vector3I(Math.Min(projectedMin.X, projectedMax.X), Math.Min(projectedMin.Y, projectedMax.Y), Math.Min(projectedMin.Z, projectedMax.Z)); Vector3I max = new Vector3I(Math.Max(projectedMin.X, projectedMax.X), Math.Max(projectedMin.Y, projectedMax.Y), Math.Max(projectedMin.Z, projectedMax.Z)); projectedMin = min; projectedMax = max; if (!projectorGrid.CanAddCubes(projectedMin, projectedMax)) { IMySlimBlock slimBlock = (IMySlimBlock)blockGrid.GetCubeBlock(block.Min); if (slimBlock == null || slimBlock.FatBlock == null) { return(false); } Logging.Instance.WriteLine(string.Format("Can not add block: {0}: {1} - {2} {3} {4} {5}", slimBlock.FatBlock.EntityId, blockDefinition.Id, projectedMin, projectedMax, blockMin, blockMax)); //, slimBlock.FatBlock.EntityId)); return(false); } var mountPoints = blockDefinition.GetBuildProgressModelMountPoints(1.0f); bool isConnected = MyCubeGrid.CheckConnectivity(projectorGrid, blockDefinition, mountPoints, ref blockOrientationQuat, ref blockPos); if (isConnected) { if (projectorGrid.GetCubeBlock(blockPos) == null) { return(true); } else { return(false); } } else { return(false); } }