public MyGridJumpDriveSystem(MyCubeGrid grid)
        {
            m_grid = grid;

            SyncObject = new MySyncJumpDriveSystem(m_grid);
            m_soundEmitter = new MyEntity3DSoundEmitter(m_grid);
        }
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            ResourceSink = new MyResourceSinkComponent();
            ResourceSink.Init(
                MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup),
                BlockDefinition.PowerConsumptionMoving,
                UpdatePowerInput);

            base.Init(builder, cubeGrid);

            var ob = (MyObjectBuilder_AirtightDoorGeneric)builder;
            m_open.Value = ob.Open;
            m_currOpening = ob.CurrOpening;

            m_openingSpeed = BlockDefinition.OpeningSpeed;
            m_sound = new MySoundPair(BlockDefinition.Sound);
            m_subpartMovementDistance = BlockDefinition.SubpartMovementDistance;
	
			if (!Enabled || !ResourceSink.IsPoweredByType(MyResourceDistributorComponent.ElectricityId))
                UpdateDoorPosition();

            OnStateChange();

            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink.Update();
            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
			ResourceSink.Update();
        }
        internal void Init(Graphics.GUI.MyGuiControlTabPage infoPage, MyCubeGrid grid)
        {
            m_grid = grid;
            m_infoPage = infoPage;
            Debug.Assert(m_infoPage != null);

            RecreateControls();

            if (grid == null)
                return;
            grid.OnBlockAdded += grid_OnBlockAdded;
            grid.OnBlockRemoved += grid_OnBlockRemoved;
            grid.OnPhysicsChanged += grid_OnPhysicsChanged;
            grid.OnBlockOwnershipChanged += grid_OnBlockOwnershipChanged;

            if (MyFakes.ENABLE_TERMINAL_PROPERTIES)
            {
                var renameShipBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("RenameShipButton");
                if (renameShipBtn != null)
                    renameShipBtn.ButtonClicked += renameBtn_ButtonClicked;
            }

            var convertBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("ConvertBtn");
            if (convertBtn != null)
            {
                convertBtn.ButtonClicked += convertBtn_ButtonClicked;
            }
        }
Пример #4
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            PowerReceiver = new MyPowerReceiver(
                MyConsumerGroupEnum.Utility,
                false,
                BlockDefinition.RequiredPowerInput,
                this.CalculateRequiredPowerInput);
            PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged;
            PowerReceiver.Update();

            if (Physics != null)
            {
                Physics.Close();
            }

            var detectorShape = new HkBoxShape(new Vector3(cubeGrid.GridSize / 3.0f));
            var massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(detectorShape.HalfExtents, BlockDefinition.VirtualMass);
            Physics = new Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_DEFAULT);
            Physics.IsPhantom = false;
            Physics.CreateFromCollisionObject(detectorShape, Vector3.Zero, WorldMatrix, massProperties, MyPhysics.VirtualMassLayer);
            Physics.Enabled = IsWorking && cubeGrid.Physics != null && cubeGrid.Physics.Enabled;
            Physics.RigidBody.Activate();
            detectorShape.Base.RemoveReference();

            UpdateText();

            NeedsUpdate = MyEntityUpdateEnum.EACH_FRAME;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

        }
        /// <summary>
        /// Returns master grid
        /// </summary>
        public static MyCubeGrid GetMasterGrid(MyCubeGrid grid)
        {
            // Biggest grid does the sync
            var group = MyCubeGridGroups.Static.PhysicalDynamic.GetGroup(grid);

            if (group == null)
            {
                return grid;
            }

            float maxRadius = 0;
            MyCubeGrid biggestGrid = null;
            foreach (var node in group.Nodes)
            {
                // Static in never master
                if (node.NodeData.IsStatic)
                    continue;

                // Sort by radius, then by EntityId (to make stable sort of two same-size grids)
                var rad = node.NodeData.PositionComp.LocalVolume.Radius;
                if (rad > maxRadius || (rad == maxRadius && (biggestGrid == null || grid.EntityId > biggestGrid.EntityId)))
                {
                    maxRadius = rad;
                    biggestGrid = node.NodeData;
                }
            }

            return biggestGrid; // Only biggest grid does the sync
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            InitializeSinkComponent();
            base.Init(objectBuilder, cubeGrid);
            if (CubeGrid.CreatePhysics)
            {
            	// Put on my fake, because it does performance issues
                if (MyFakes.ENABLE_GRAVITY_PHANTOM)
                {
                        var shape = CreateFieldShape();
                        Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_KINEMATIC);
                        Physics.IsPhantom = true;
                        Physics.CreateFromCollisionObject(shape, PositionComp.LocalVolume.Center, WorldMatrix, null, Sandbox.Engine.Physics.MyPhysics.CollisionLayers.GravityPhantomLayer);
                        shape.Base.RemoveReference();
                        Physics.Enabled = IsWorking;
                }
                NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;

                SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
                ResourceSink.Update();
            }
            m_soundEmitter = new MyEntity3DSoundEmitter(this, true);
            m_baseIdleSound.Init("BlockGravityGen");
			
        }
Пример #7
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            m_cargoDefinition = (MyCargoContainerDefinition)MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId());
            var cargoBuilder = (MyObjectBuilder_CargoContainer)objectBuilder;
            m_containerType = cargoBuilder.ContainerType;

            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }

            // Backward compatibility - inventory component not defined in definition files and in entity container
            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(m_cargoDefinition.InventorySize.Volume, m_cargoDefinition.InventorySize, MyInventoryFlags.CanSend | MyInventoryFlags.CanReceive);
                Components.Add<MyInventoryBase>(inventory);
                
                if (m_containerType != null && MyFakes.RANDOM_CARGO_PLACEMENT && (cargoBuilder.Inventory == null || cargoBuilder.Inventory.Items.Count == 0))
                    SpawnRandomCargo();
            }

            //Backward compatibility
            if (cargoBuilder.Inventory != null && cargoBuilder.Inventory.Items.Count > 0)
                this.GetInventory().Init(cargoBuilder.Inventory);

            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");
            this.GetInventory().SetFlags(MyInventoryFlags.CanSend | MyInventoryFlags.CanReceive);
            m_conveyorEndpoint = new MyMultilineConveyorEndpoint(this);
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint));
            UpdateIsWorking();
        }
Пример #8
0
 protected override bool Activate(HashSet<MySlimBlock> targets)
 {
     m_otherGrid = null;
     if (targets.Count > 0)
     {
         m_otherGrid = targets.FirstElement().CubeGrid;
     }
     if (Sync.IsServer)
     {             
         float coefficient = (MyShipGrinderConstants.GRINDER_COOLDOWN_IN_MILISECONDS * 0.001f) / targets.Count;             
         foreach (var block in targets)
         {
             m_otherGrid = block.CubeGrid;
             block.DecreaseMountLevel(MySession.Static.GrinderSpeedMultiplier * MyShipGrinderConstants.GRINDER_AMOUNT_PER_SECOND * coefficient, Inventory);
             block.MoveItemsFromConstructionStockpile(Inventory);
            
             
             if (block.IsFullyDismounted)
             {
                 if (block.FatBlock is IMyInventoryOwner) EmptyBlockInventories(block.FatBlock as IMyInventoryOwner);
                 block.SpawnConstructionStockpile();
                 block.CubeGrid.RazeBlock(block.Min);
             }
         }
         
     }
     m_wantsToShake = targets.Count != 0;
     return targets.Count != 0;
 }
 public MyGridReflectorLightSystem(MyCubeGrid grid)
 {
     m_reflectors = new HashSet<MyReflectorLight>();
     m_reflectorsEnabled = MyMultipleEnabledEnum.NoObjects;
     m_grid = grid;
     m_grid.SyncObject.ReflectorStateChanged += SyncObject_ReflectorStateChanged;
 }
 public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
 {
     base.Init(objectBuilder, cubeGrid);
     MyObjectBuilder_UserControllableGun builder = (objectBuilder as MyObjectBuilder_UserControllableGun);
     m_shootingSaved = builder.IsLargeTurret ? builder.IsShootingFromTerminal : builder.IsShooting;
     NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;      
 }
Пример #11
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {             
            base.Init(objectBuilder, cubeGrid);

            MyDebug.AssertDebug(BlockDefinition.Id.TypeId == typeof(MyObjectBuilder_Reactor));
            m_reactorDefinition = BlockDefinition as MyReactorDefinition;
            MyDebug.AssertDebug(m_reactorDefinition != null);

            CurrentPowerOutput = 0;
            m_inventory = new MyInventory(m_reactorDefinition.InventoryMaxVolume, m_reactorDefinition.InventorySize, MyInventoryFlags.CanReceive, this);

            var obGenerator = (MyObjectBuilder_Reactor)objectBuilder;
            m_inventory.Init(obGenerator.Inventory);
            m_inventory.ContentsChanged += inventory_ContentsChanged;
            m_inventory.Constraint = m_reactorDefinition.InventoryConstraint;
            RefreshRemainingCapacity();

            UpdateText();

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;
            //if (MyFakes.SHOW_DAMAGE_EFFECTS && IsWorking)
            //    NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;

            m_baseIdleSound = BlockDefinition.PrimarySound;

            m_useConveyorSystem = obGenerator.UseConveyorSystem;

            if (IsWorking)
                OnStartWorking();
        }
Пример #12
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            m_cargoDefinition = (MyCargoContainerDefinition)MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId());
            var cargoBuilder = (MyObjectBuilder_CargoContainer)objectBuilder;
            m_containerType = cargoBuilder.ContainerType;

            if (!Components.Has<MyInventoryBase>())
            {
                m_inventory = new MyInventory(m_cargoDefinition.InventorySize.Volume, m_cargoDefinition.InventorySize, MyInventoryFlags.CanSend | MyInventoryFlags.CanReceive, this);
				if(MyFakes.ENABLE_MEDIEVAL_INVENTORY)
					Components.Add<MyInventoryBase>(m_inventory);

                if (m_containerType != null && MyFakes.RANDOM_CARGO_PLACEMENT && (cargoBuilder.Inventory == null || cargoBuilder.Inventory.Items.Count == 0))
                    SpawnRandomCargo();
                else
                    m_inventory.Init(cargoBuilder.Inventory);
            }
            else
            {
                m_inventory = Components.Get<MyInventoryBase>() as MyInventory;
				Debug.Assert(m_inventory != null);
                //m_inventory.Owner = this;
            }

            if(MyPerGameSettings.InventoryMass)
                m_inventory.ContentsChanged += Inventory_ContentsChanged;

            m_conveyorEndpoint = new MyMultilineConveyorEndpoint(this);
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint));
            UpdateIsWorking();
        }
Пример #13
0
        public GridGroup( MyCubeGrid grid, GridLinkTypeEnum linkType = GridLinkTypeEnum.Logical )
        {
            _linkType = linkType;

            if ( grid.InScene )
            {
                List<MyCubeGrid> tmpList = new List<MyCubeGrid>( );

                //find the group containing this grid with the given link type
                Wrapper.GameAction( ( ) => tmpList = MyCubeGridGroups.Static.GetGroups( linkType ).GetGroupNodes( grid ) );

                _grids.UnionWith( tmpList );
            }
            //manually create a group for out of scene grids because they have a null group (yay Dusan fixed the crash)
            else
            {
                //use the old method to filter out grids with pistons or rotors, for safety
                HashSet<IMyEntity> thisEntity = new HashSet<IMyEntity>();
                HashSet<IMyEntity> returnSet = new HashSet<IMyEntity>();
                thisEntity.Add( (IMyEntity)grid );
                CubeGrids.GetGridsUnconnected( returnSet, thisEntity );

                if ( returnSet.Count > 0 )
                    _grids.Add( grid );
                else
                    return;
            }

            //populate our internal lists
            ComputeParent( );
            ComputeCubeBlocks( );
            ComputeFatBlocks( );
            ComputeSmallOwners( );
            ComputeBigOwners( );
        }
Пример #14
0
        public bool CheckPlayerExempt(ProtectedItem.ProtectionSettings settings, MyCubeGrid grid, ulong remoteUserId )
        {
            if ( settings.AllExempt )
                return true;

            if (settings.AdminExempt && PlayerManager.Instance.IsUserAdmin(remoteUserId))
                return true;

            long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId( remoteUserId );

            if (settings.BigOwnerExempt)
            {
                //fast check to see if the player's current live identity is an owner
                if (grid.BigOwners.Contains(playerId))
                    return true;

                //check old, dead identities. this is much slower
                var playerIds = PlayerMap.Instance.GetPlayerIdsFromSteamId(remoteUserId, false);

                foreach (var owner in grid.BigOwners)
                    if (playerIds.Contains(owner))
                        return true;
            }

            if ( settings.SmallOwnerExempt )
            {
                //fast check to see if the player's current live identity is an owner
                if ( grid.SmallOwners.Contains( playerId ) )
                    return true;

                //check old, dead identities. this is much slower
                var playerIds = PlayerMap.Instance.GetPlayerIdsFromSteamId( remoteUserId, false );

                foreach ( var owner in grid.SmallOwners )
                    if ( playerIds.Contains( owner ) )
                        return true;
            }

            if ( settings.FactionExempt && grid.BigOwners.Count > 0)
            {
                var fac = MySession.Static.Factions.GetPlayerFaction( grid.BigOwners[0] );
                if ( fac != null && fac.IsMember( playerId ) )
                    return true;
            }

            if (settings.Factions == null)
                return false;

            foreach ( var facId in settings.Factions )
            {
                var fac = MySession.Static.Factions.TryGetFactionById( facId );
                if ( fac != null && fac.IsMember( playerId ) )
                    return true;
            }

            //if ( settings.ExemptSteamIds.Contains( remoteUserId.ToString() ) )
            //    return true;

            return false;
        }
Пример #15
0
 public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
 {
     base.Init(builder, cubeGrid);
     this.NeedsUpdate = MyEntityUpdateEnum.EACH_100TH_FRAME;
     m_emissivitySet = false;
     AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorSegment(m_segment));
 }
        internal void Close()
        {
            foreach (var grid in m_infoGrids)
            {
                grid.OnAuthorshipChanged -= grid_OnAuthorshipChanged;
            }

            if (m_grid == null) return;
            if (m_infoPage == null) return;

            var convertBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("ConvertBtn");
            if (convertBtn != null)
                convertBtn.ButtonClicked -= convertBtn_ButtonClicked;

            var convertToStationBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("ConvertToStationBtn");
            if (convertToStationBtn != null)
                convertToStationBtn.ButtonClicked -= convertToStationBtn_ButtonClicked;

            m_grid.OnBlockAdded -= grid_OnBlockAdded;
            m_grid.OnBlockRemoved -= grid_OnBlockRemoved;
            m_grid.OnPhysicsChanged -= grid_OnPhysicsChanged;
            m_grid.OnBlockOwnershipChanged -= grid_OnBlockOwnershipChanged;

            m_grid = null;
            m_infoPage = null;
        }
 void grid_OnBlockOwnershipChanged(MyCubeGrid obj)
 {
     bool playerOwner = false;
     foreach(var owner in obj.BigOwners)
     {
         var faction = MySession.Static.Factions.GetPlayerFaction(owner);
         if(faction != null && !faction.IsEveryoneNpc())
         {
             playerOwner = true;
             break;
         }
     }
     foreach(var owner in obj.SmallOwners)
     {
         var faction = MySession.Static.Factions.GetPlayerFaction(owner);
         if (faction != null && !faction.IsEveryoneNpc())
         {
             playerOwner = true;
             break;
         }
     }
     if (playerOwner)
     {
         obj.Components.Remove<MyUpdateTriggerComponent>();
         obj.OnBlockOwnershipChanged -= grid_OnBlockOwnershipChanged;
     }
 }
        public void GridAdded(MyCubeGrid grid)
        {
            // CH: TODO: Don't add all grids immediately. E.g. copy-paste preview grids don't need to be added

            if (!GridCanHaveNavmesh(grid)) return;

            m_navigationMeshes.Add(grid, new MyGridNavigationMesh(grid, m_coordinator, 32, MyAIComponent.Static.Pathfinding.NextTimestampFunction));
            RegisterGridEvents(grid);
        }
 public void Init(MyCubeGrid mainGrid = null)
 {
     m_lastColorIndex = 0;
     m_colors.Clear();
     if (mainGrid != null)
     {
         m_colors.Add(mainGrid, Color.White);
     }
 }
Пример #20
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            var ob = objectBuilder as MyObjectBuilder_CompoundCubeBlock;

            if (ob.Blocks != null)
            {
                if (ob.BlockIds != null)
                {
                    Debug.Assert(ob.Blocks.Length == ob.BlockIds.Length);

                    for (int i = 0; i < ob.Blocks.Length; ++i)
                    {
                        ushort id = ob.BlockIds[i];
                        if (m_blocks.ContainsKey(id))
                        {
                            Debug.Fail("Block with the same id found");
                            continue;
                        }

                        var blockBuilder = ob.Blocks[i];
                        object objectBlock = MyCubeBlockFactory.CreateCubeBlock(blockBuilder);
                        MySlimBlock cubeBlock = objectBlock as MySlimBlock;
                        if (cubeBlock == null)
                            cubeBlock = new MySlimBlock();

                        cubeBlock.Init(blockBuilder, cubeGrid, objectBlock as MyCubeBlock);

                        cubeBlock.FatBlock.Hierarchy.Parent = Hierarchy;
                        m_blocks.Add(id, cubeBlock);
                    }

                    RefreshNextId();
                }
                else
                {
                    for (int i = 0; i < ob.Blocks.Length; ++i)
                    {
                        var blockBuilder = ob.Blocks[i];
                        object objectBlock = MyCubeBlockFactory.CreateCubeBlock(blockBuilder);
                        MySlimBlock cubeBlock = objectBlock as MySlimBlock;
                        if (cubeBlock == null)
                            cubeBlock = new MySlimBlock();

                        cubeBlock.Init(blockBuilder, cubeGrid, objectBlock as MyCubeBlock);

                        cubeBlock.FatBlock.Hierarchy.Parent = Hierarchy;
                        ushort id = CreateId(cubeBlock);
                        m_blocks.Add(id, cubeBlock);
                    }
                }
             }

            RefreshTemplates();
        }
		public static bool GetShapeCenter(HkShape shape, uint shapeKey, MyCubeGrid grid, ref Vector3D shapeCenter)
		{
            return false; //Disabled because of bad computing shapeCenter in relation with grid (alway around grid center).
                          //Called on grid part which has havok shape (only door?).
			bool shapeSet = true;

			switch (shape.ShapeType)
			{
				case HkShapeType.List:
					var listShape = (HkListShape)shape;
					shape = listShape.GetChildByIndex((int)shapeKey);
					break;
				case HkShapeType.Mopp:
					var moppShape = (HkMoppBvTreeShape)shape;
					shape = moppShape.ShapeCollection.GetShape(shapeKey, null);
					break;
				case HkShapeType.Box:
					var boxShape = (HkBoxShape)shape;
					shape = boxShape;
					break;
				case HkShapeType.ConvexTranslate:
					var convexTranslateShape = (HkConvexShape)shape;
					shape = convexTranslateShape;
					break;
				case HkShapeType.ConvexTransform:
					var convexTransformShape = (HkConvexTransformShape)shape;
					shape = convexTransformShape;
					break;
			/*	case HkShapeType.BvTree:
					var bvTreeShape = (HkBvTreeShape)shape;
					var iterator = bvTreeShape.Base.GetContainer();
					while (iterator.CurrentValue.IsContainer() && iterator.CurrentValue.ShapeType != HkShapeType.ConvexTranslate && iterator.CurrentValue.ShapeType != HkShapeType.ConvexTransform)
						iterator.Next();
					if (iterator.IsValid)
						shape = iterator.CurrentValue;
					else
						shapeSet = false;
					break;*/

				default:
					shapeSet = false;
					break;
			}

			if (shapeSet)
			{
				Vector4 min4, max4;
				shape.GetLocalAABB(0.05f, out min4, out max4);
				Vector3 worldMin = Vector3.Transform(new Vector3(min4), grid.PositionComp.WorldMatrix);
				Vector3 worldMax = Vector3.Transform(new Vector3(max4), grid.PositionComp.WorldMatrix);
				var worldAABB = new BoundingBoxD(worldMin, worldMax);

				shapeCenter = worldAABB.Center;
			}
			return shapeSet;
		}
Пример #22
0
 public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
 {
     base.Init(objectBuilder, cubeGrid);
     if (CubeGrid.GridSizeEnum == MyCubeSize.Large)
     {
         IDLE_SOUND.Init("ToolLrgGrindIdle");
         METAL_SOUND.Init("ToolLrgGrindMetal");
     }
     m_rotationSpeed = 0.0f;
 }
Пример #23
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;

            base.Init(objectBuilder, cubeGrid);

            m_missingComponents = new Dictionary<string, int>();

            var builder = (MyObjectBuilder_ShipWelder)objectBuilder;
            m_helpOthers = builder.HelpOthers;
        }
Пример #24
0
 public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
 {
     base.Init(objectBuilder, cubeGrid);
     MyObjectBuilder_UserControllableGun builder = (objectBuilder as MyObjectBuilder_UserControllableGun);
     this.m_isShooting = builder.IsLargeTurret ? builder.IsShootingFromTerminal : builder.IsShooting;
     if (m_isShooting)
     {
         NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;
     }
     SyncObject = new MySyncUserControllableGun(this);
 }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            var builder = objectBuilder as MyObjectBuilder_ConveyorTurretBase;
            var builder2 = objectBuilder as MyObjectBuilder_TurretBase; // Compatibility

            Debug.Assert(builder != null || builder2 != null, "Turret builder was incorrect!");

            if (builder != null)
                m_useConveyorSystem = builder.UseConveyorSystem;
        }
Пример #26
0
        public MyGridWheelSystem(MyCubeGrid grid)
        {
            m_wheels = new HashSet<MyMotorSuspension>();
            m_wheelsChanged = false;
            m_grid = grid;

			SinkComp = new MyResourceSinkComponent();
			SinkComp.Init(MyStringHash.GetOrCompute("Utility"), m_maxRequiredPowerInput, () => m_maxRequiredPowerInput);
            SinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;

            grid.OnPhysicsChanged += grid_OnPhysicsChanged;
        }
Пример #27
0
 public MyGridGyroSystem(MyCubeGrid grid)
 {
     m_grid = grid;
     m_gyros = new HashSet<MyGyro>();
     m_gyrosChanged = false;
     PowerReceiver = new MyPowerReceiver(
         MyConsumerGroupEnum.Gyro,
         true,
         m_maxRequiredPowerInput,
         () => m_maxRequiredPowerInput);
     PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged;
 }
Пример #28
0
        public MyGridGyroSystem(MyCubeGrid grid)
        {
            m_grid = grid;
            m_gyros = new HashSet<MyGyro>();
            m_gyrosChanged = false;
			ResourceSink = new MyResourceSinkComponent();
            ResourceSink.Init(
                MyStringHash.GetOrCompute("Gyro"),
                m_maxRequiredPowerInput,
                () => m_maxRequiredPowerInput);
            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);
            if (CubeGrid.GridSizeEnum == MyCubeSize.Large)
            {
                IDLE_SOUND.Init("ToolLrgGrindIdle");
                METAL_SOUND.Init("ToolLrgGrindMetal");
            }
            m_rotationSpeed = 0.0f;

            HeatUpFrames = MyShipGrinderConstants.GRINDER_HEATUP_FRAMES;
        }
Пример #30
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            MyDebug.AssertDebug(BlockDefinition.Id.TypeId == typeof(MyObjectBuilder_Reactor));
            m_reactorDefinition = BlockDefinition as MyReactorDefinition;
            MyDebug.AssertDebug(m_reactorDefinition != null);

            SourceComp.Init(
                m_reactorDefinition.ResourceSourceGroup,
                new MyResourceSourceInfo
                {
                    ResourceTypeId = MyResourceDistributorComponent.ElectricityId,
                    DefinedOutput = m_reactorDefinition.MaxPowerOutput,
                    ProductionToCapacityMultiplier = 60 * 60
                });
            SourceComp.HasCapacityRemainingChanged += (id, source) => UpdateIsWorking();
            SourceComp.OutputChanged += Source_OnOutputChanged;
            SourceComp.ProductionEnabledChanged += Source_ProductionEnabledChanged;
            SourceComp.Enabled = Enabled;

            base.Init(objectBuilder, cubeGrid);
         
            var obGenerator = (MyObjectBuilder_Reactor)objectBuilder;

            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }

            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(m_reactorDefinition.InventoryMaxVolume, m_reactorDefinition.InventorySize, MyInventoryFlags.CanReceive);
                Components.Add<MyInventoryBase>(inventory);
                inventory.Init(obGenerator.Inventory);
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            this.GetInventory().Constraint = m_reactorDefinition.InventoryConstraint;

            if (Sync.IsServer)
            {
                RefreshRemainingCapacity();
            }
            
            UpdateText();

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;

            m_useConveyorSystem.Value = obGenerator.UseConveyorSystem;
			UpdateMaxOutputAndEmissivity();
        }
Пример #31
0
        public static void DrawSemiTransparentBox(Vector3I minPosition, Vector3I maxPosition, MyCubeGrid grid, Color color, bool onlyWireframe = false, string lineMaterial = null,
                                                  Vector4?lineColor = null)
        {
            var          gridSize   = grid.GridSize;
            var          min        = (minPosition * gridSize) - new Vector3((gridSize / 2.0f) * SEMI_TRANSPARENT_BOX_MODIFIER);
            var          max        = (maxPosition * gridSize) + new Vector3((gridSize / 2.0f) * SEMI_TRANSPARENT_BOX_MODIFIER);
            BoundingBoxD boxr       = new BoundingBoxD(min, max);
            MatrixD      gridMatrix = grid.WorldMatrix;
            var          lColor     = Color.White;

            if (lineColor.HasValue)
            {
                lColor = lineColor.Value;
            }

            MySimpleObjectDraw.DrawTransparentBox(ref gridMatrix, ref boxr, ref lColor, MySimpleObjectRasterizer.Wireframe, 1, 0.04f, null, lineMaterial, false);
            if (!onlyWireframe)
            {
                Color faceColor = new Color(color * 0.2f, 0.3f);
                MySimpleObjectDraw.DrawTransparentBox(ref gridMatrix, ref boxr, ref faceColor, MySimpleObjectRasterizer.Solid, 0, 0.04f, "Square", null, true);
            }
        }
Пример #32
0
 /// <summary>
 /// Notifies about grid change with old grid in parameter (new grid is available in property).
 /// </summary>
 public virtual void OnCubeGridChanged(MyCubeGrid oldGrid)
 {
 }
Пример #33
0
        /// <summary>
        /// Returns true if this block can connect to another block (of the given type) in the given position.
        /// This is called only if CheckConnectionAllowed == true.
        /// If this method would return true for any position, set CheckConnectionAllowed to false to avoid
        /// unnecessary overhead. It is the block's responsibility to call CubeGrid.UpdateBlockNeighbors every time the
        /// conditions that are checked by this method change.
        /// </summary>
        public virtual bool ConnectionAllowed(ref Vector3I otherBlockPos, ref Vector3I faceNormal, MyCubeBlockDefinition def)
        {
            if (MyFakes.ENABLE_FRACTURE_COMPONENT && Components.Has <MyFractureComponentBase>())
            {
                MyFractureComponentCubeBlock fractureComponent = GetFractureComponent();

                if (fractureComponent == null || fractureComponent.MountPoints == null)
                {
                    return(true);
                }

                var other = CubeGrid.GetCubeBlock(otherBlockPos);
                if (other == null)
                {
                    return(true);
                }

                MyBlockOrientation or = other.Orientation;
                var position          = Position;
                Debug.Assert(m_tmpMountPoints.Count == 0);
                m_tmpMountPoints.Clear();

                if (other.FatBlock != null && other.FatBlock.Components.Has <MyFractureComponentBase>())
                {
                    MyFractureComponentCubeBlock otherFractureComponent = other.GetFractureComponent();
                    if (otherFractureComponent != null)
                    {
                        m_tmpMountPoints.AddRange(otherFractureComponent.MountPoints);
                    }
                }
                else if (other.FatBlock is MyCompoundCubeBlock)
                {
                    var lst = new List <MyCubeBlockDefinition.MountPoint>();
                    foreach (var b in (other.FatBlock as MyCompoundCubeBlock).GetBlocks())
                    {
                        MyFractureComponentCubeBlock blockInCompoundFractureComponent = b.GetFractureComponent();
                        if (blockInCompoundFractureComponent != null)
                        {
                            m_tmpMountPoints.AddRange(blockInCompoundFractureComponent.MountPoints);
                        }
                        else
                        {
                            var mountPoints = b.BlockDefinition.GetBuildProgressModelMountPoints(b.BuildLevelRatio);
                            lst.Clear();
                            MyCubeGrid.TransformMountPoints(lst, b.BlockDefinition, mountPoints, ref b.Orientation);
                            m_tmpMountPoints.AddRange(lst);
                        }
                    }
                }
                else
                {
                    var mountPoints = def.GetBuildProgressModelMountPoints(other.BuildLevelRatio);
                    MyCubeGrid.TransformMountPoints(m_tmpMountPoints, def, mountPoints, ref or);
                }

                bool result = MyCubeGrid.CheckMountPointsForSide(fractureComponent.MountPoints, ref SlimBlock.Orientation, ref position, BlockDefinition.Id, ref faceNormal, m_tmpMountPoints,
                                                                 ref or, ref otherBlockPos, def.Id);

                m_tmpMountPoints.Clear();

                return(result);
            }

            return(true);
        }
Пример #34
0
        /// <summary>
        /// Gets all cubes which are affected by bone.
        /// </summary>
        /// <param name="onlyExisting">Returns only cubes which were added to skeleton.</param>
        public void GetAffectedCubes(Vector3I cube, Vector3I boneOffset, List <Vector3I> resultList, MyCubeGrid grid)
        {
            Debug.Assert(BoneDensity == 2, "This algorithm requires BoneDensity to be 2");

            Vector3I dist = boneOffset - Vector3I.One;
            Vector3I sign = Vector3I.Sign(dist);

            dist *= sign;

            Vector3I offset;

            for (offset.X = 0; offset.X <= dist.X; offset.X++)
            {
                for (offset.Y = 0; offset.Y <= dist.Y; offset.Y++)
                {
                    for (offset.Z = 0; offset.Z <= dist.Z; offset.Z++)
                    {
                        var targetCube = cube + offset * sign;
                        if (grid.CubeExists(targetCube))
                        {
                            resultList.Add(targetCube);
                        }
                    }
                }
            }
        }
Пример #35
0
 protected static void CreateGridGroupLink(GridLinkTypeEnum type, long linkId, MyCubeGrid parent, MyCubeGrid child)
 {
     MyCubeGridGroups.Static.CreateLink(type, linkId, parent, child);
 }
Пример #36
0
        public static void FindNext(MyEntityCyclingOrder order, ref float metric, ref long entityId, bool findLarger, CyclingOptions options)
        {
            Metric current = new Metric()
            {
                Value = metric, EntityId = entityId
            };
            Metric start   = findLarger ? Metric.Max : Metric.Min;
            Metric result  = start;
            Metric extreme = start;

            foreach (var entity in MyEntities.GetEntities())
            {
                if (options.Enabled)
                {
                    MyCubeGrid grid = entity as MyCubeGrid;
                    if (options.OnlyLargeGrids && (grid == null || grid.GridSizeEnum != MyCubeSize.Large))
                    {
                        continue;
                    }

                    if (options.OnlySmallGrids && (grid == null || grid.GridSizeEnum != MyCubeSize.Small))
                    {
                        continue;
                    }
                }

                var newMetric = new Metric(GetMetric(order, entity), entity.EntityId);
                if (newMetric.Value == 0)
                {
                    continue;
                }

                if (findLarger)
                {
                    if (newMetric > current && newMetric < result)
                    {
                        result = newMetric;
                    }
                    if (newMetric < extreme)
                    {
                        extreme = newMetric;
                    }
                }
                else
                {
                    if (newMetric < current && newMetric > result)
                    {
                        result = newMetric;
                    }
                    if (newMetric > extreme)
                    {
                        extreme = newMetric;
                    }
                }
            }

            if (result == start)
            {
                result = extreme;
            }

            metric   = result.Value;
            entityId = result.EntityId;
        }
Пример #37
0
        public void UpdateBroadcastersInRange(HashSet <MyDataBroadcaster> relayedBroadcasters, long localPlayerId, HashSet <long> gridsQueued)
        {
            m_broadcastersInRange.Clear();

            if (!MyFakes.ENABLE_RADIO_HUD || !Enabled)
            {
                return;
            }

            if (Parent is IMyComponentOwner <MyDataBroadcaster> )
            {
                MyDataBroadcaster radioBroadcaster;
                if ((Parent as IMyComponentOwner <MyDataBroadcaster>).GetComponent(out radioBroadcaster))
                {
                    relayedBroadcasters.Add(radioBroadcaster);
                }
            }

            //add all from same grid:
            MyCubeGrid grid = Parent.GetTopMostParent() as MyCubeGrid;

            if (grid != null && //astronaut has no grid
                !gridsQueued.Contains(grid.EntityId))
            {
                gridsQueued.Add(grid.EntityId);
                foreach (var block in grid.GetFatBlocks <MyCubeBlock>())
                {
                    if (block is IMyComponentOwner <MyDataBroadcaster> )
                    {
                        MyDataBroadcaster broadcaster;
                        if ((block as IMyComponentOwner <MyDataBroadcaster>).GetComponent(out broadcaster))
                        {
                            MyIDModule module;
                            if ((block as IMyComponentOwner <MyIDModule>).GetComponent(out module))
                            {
                                if ((block as MyTerminalBlock).HasPlayerAccess(localPlayerId) && module.Owner != 0 &&
                                    !relayedBroadcasters.Contains(broadcaster))
                                {
                                    relayedBroadcasters.Add(broadcaster);
                                    if (!CanIUseIt(broadcaster, localPlayerId))
                                    {
                                        continue;
                                    }
                                    if (broadcaster.Parent is IMyComponentOwner <MyDataReceiver> )
                                    {
                                        MyDataReceiver radioReceiver;
                                        if ((broadcaster.Parent as IMyComponentOwner <MyDataReceiver>).GetComponent(out radioReceiver))
                                        {
                                            radioReceiver.UpdateBroadcastersInRange(relayedBroadcasters, localPlayerId, gridsQueued);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //
            GetAllBroadcastersInMyRange(ref relayedBroadcasters, localPlayerId, gridsQueued);
        }
Пример #38
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);
            MyObjectBuilder_CompoundCubeBlock block = objectBuilder as MyObjectBuilder_CompoundCubeBlock;

            if (block.Blocks != null)
            {
                if (block.BlockIds == null)
                {
                    for (int i = 0; i < block.Blocks.Length; i++)
                    {
                        MyObjectBuilder_CubeBlock builder = block.Blocks[i];
                        object      obj3   = MyCubeBlockFactory.CreateCubeBlock(builder);
                        MySlimBlock block5 = obj3 as MySlimBlock;
                        if (block5 == null)
                        {
                            block5 = new MySlimBlock();
                        }
                        block5.Init(builder, cubeGrid, obj3 as MyCubeBlock);
                        block5.FatBlock.HookMultiplayer();
                        block5.FatBlock.Hierarchy.Parent = base.Hierarchy;
                        ushort key = this.CreateId(block5);
                        this.m_mapIdToBlock.Add(key, block5);
                        this.m_blocks.Add(block5);
                    }
                }
                else
                {
                    int index = 0;
                    while (true)
                    {
                        if (index >= block.Blocks.Length)
                        {
                            this.RefreshNextId();
                            break;
                        }
                        ushort key = block.BlockIds[index];
                        if (!this.m_mapIdToBlock.ContainsKey(key))
                        {
                            MyObjectBuilder_CubeBlock builder = block.Blocks[index];
                            object      obj2   = MyCubeBlockFactory.CreateCubeBlock(builder);
                            MySlimBlock block3 = obj2 as MySlimBlock;
                            if (block3 == null)
                            {
                                block3 = new MySlimBlock();
                            }
                            block3.Init(builder, cubeGrid, obj2 as MyCubeBlock);
                            if (block3.FatBlock != null)
                            {
                                block3.FatBlock.HookMultiplayer();
                                block3.FatBlock.Hierarchy.Parent = base.Hierarchy;
                                this.m_mapIdToBlock.Add(key, block3);
                                this.m_blocks.Add(block3);
                            }
                        }
                        index++;
                    }
                }
            }
            this.RefreshTemplates();
            base.AddDebugRenderComponent(new MyDebugRenderComponentCompoundBlock(this));
        }
Пример #39
0
        public static void FindNext(MyEntityCyclingOrder order, ref float metric, ref long entityId, bool findLarger, CyclingOptions options)
        {
            Metric metric2 = new Metric {
                Value    = metric,
                EntityId = entityId
            };
            Metric metric3 = findLarger ? Metric.Max : Metric.Min;
            Metric metric4 = metric3;
            Metric metric5 = metric3;

            foreach (MyEntity entity in MyEntities.GetEntities())
            {
                if (options.Enabled)
                {
                    MyCubeGrid grid = entity as MyCubeGrid;
                    if (options.OnlyLargeGrids)
                    {
                        if (grid == null)
                        {
                            continue;
                        }
                        if (grid.GridSizeEnum != MyCubeSize.Large)
                        {
                            continue;
                        }
                    }
                    if (options.OnlySmallGrids && ((grid == null) || (grid.GridSizeEnum != MyCubeSize.Small)))
                    {
                        continue;
                    }
                }
                Metric metric7 = new Metric(GetMetric(order, entity), entity.EntityId);
                if (metric7.Value != 0f)
                {
                    if (findLarger)
                    {
                        if ((metric7 > metric2) && (metric7 < metric4))
                        {
                            metric4 = metric7;
                        }
                        if (metric7 < metric5)
                        {
                            metric5 = metric7;
                        }
                    }
                    else
                    {
                        if ((metric7 < metric2) && (metric7 > metric4))
                        {
                            metric4 = metric7;
                        }
                        if (metric7 > metric5)
                        {
                            metric5 = metric7;
                        }
                    }
                }
            }
            if (metric4 == metric3)
            {
                metric4 = metric5;
            }
            metric   = metric4.Value;
            entityId = metric4.EntityId;
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            var ob = objectBuilder as MyObjectBuilder_CompoundCubeBlock;

            if (ob.Blocks != null)
            {
                if (ob.BlockIds != null)
                {
                    Debug.Assert(ob.Blocks.Length == ob.BlockIds.Length);

                    for (int i = 0; i < ob.Blocks.Length; ++i)
                    {
                        ushort id = ob.BlockIds[i];
                        if (m_mapIdToBlock.ContainsKey(id))
                        {
                            Debug.Fail("Block with the same id found");
                            continue;
                        }

                        var         blockBuilder = ob.Blocks[i];
                        object      objectBlock  = MyCubeBlockFactory.CreateCubeBlock(blockBuilder);
                        MySlimBlock cubeBlock    = objectBlock as MySlimBlock;
                        if (cubeBlock == null)
                        {
                            cubeBlock = new MySlimBlock();
                        }

                        cubeBlock.Init(blockBuilder, cubeGrid, objectBlock as MyCubeBlock);

                        if (cubeBlock.FatBlock != null)
                        {
                            cubeBlock.FatBlock.HookMultiplayer();

                            cubeBlock.FatBlock.Hierarchy.Parent = Hierarchy;
                            m_mapIdToBlock.Add(id, cubeBlock);
                            m_blocks.Add(cubeBlock);
                        }
                    }

                    RefreshNextId();
                }
                else
                {
                    for (int i = 0; i < ob.Blocks.Length; ++i)
                    {
                        var         blockBuilder = ob.Blocks[i];
                        object      objectBlock  = MyCubeBlockFactory.CreateCubeBlock(blockBuilder);
                        MySlimBlock cubeBlock    = objectBlock as MySlimBlock;
                        if (cubeBlock == null)
                        {
                            cubeBlock = new MySlimBlock();
                        }

                        cubeBlock.Init(blockBuilder, cubeGrid, objectBlock as MyCubeBlock);
                        cubeBlock.FatBlock.HookMultiplayer();

                        cubeBlock.FatBlock.Hierarchy.Parent = Hierarchy;
                        ushort id = CreateId(cubeBlock);
                        m_mapIdToBlock.Add(id, cubeBlock);
                        m_blocks.Add(cubeBlock);
                    }
                }
            }

            Debug.Assert(m_mapIdToBlock.Count == m_blocks.Count);

            RefreshTemplates();

            AddDebugRenderComponent(new MyDebugRenderComponentCompoundBlock(this));
        }
Пример #41
0
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            var          doorDefinition = BlockDefinition as MyDoorDefinition;
            MyStringHash resourceSinkGroup;

            if (doorDefinition != null)
            {
                MaxOpen           = doorDefinition.MaxOpen;
                m_openSound       = new MySoundPair(doorDefinition.OpenSound);
                m_closeSound      = new MySoundPair(doorDefinition.CloseSound);
                resourceSinkGroup = MyStringHash.GetOrCompute(doorDefinition.ResourceSinkGroup);
            }
            else
            {
                MaxOpen           = 1.2f;
                m_openSound       = new MySoundPair("BlockDoorSmallOpen");
                m_closeSound      = new MySoundPair("BlockDoorSmallClose");
                resourceSinkGroup = MyStringHash.GetOrCompute("Doors");
            }

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                resourceSinkGroup,
                MyEnergyConstants.MAX_REQUIRED_POWER_DOOR,
                () => (Enabled && IsFunctional) ? sinkComp.MaxRequiredInput : 0f);
            sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;


            ResourceSink = sinkComp;

            base.Init(builder, cubeGrid);

            //m_subpartsSize = 0.5f * (0.5f * SlimBlock.CubeGrid.GridSize - 0.3f);


            var ob = (MyObjectBuilder_Door)builder;

            m_open.Value = ob.State;
            if (ob.Opening == -1)
            {
                m_currOpening.Value = IsFunctional ? 0 : MaxOpen;
                m_open.Value        = !IsFunctional;
            }
            else
            {
                m_currOpening.Value = ob.Opening;
            }


            if (!Enabled || !ResourceSink.IsPowered)
            {
                UpdateSlidingDoorsPosition();
            }

            OnStateChange();

            if (m_open)
            {
                // required when reinitializing a door after the armor beneath it is destroyed
                if (Open && (m_currOpening == MaxOpen))
                {
                    UpdateSlidingDoorsPosition();
                }
            }
            sinkComp.Update();
            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
        }
Пример #42
0
        private void DebugDrawVertexNames()
        {
            //VRageRender.MyRenderProxy.DebugDrawText2D(new Vector2(10, 0), "Voxel names searching", Color.Yellow, 0.5f);
            LineD line = new LineD(IntersectionStart, IntersectionStart + IntersectionDirection * 500);
            MyIntersectionResultLineTriangleEx?intersection =
                MyEntities.GetIntersectionWithLine(ref line, MySession.Static.LocalCharacter, null, false, true, true,
                                                   VRage.Game.Components.IntersectionFlags.ALL_TRIANGLES, 0, false);


            if (intersection.HasValue)
            {
                if (intersection.Value.Entity is MyVoxelBase)
                {
                    MyVoxelBase voxels = (MyVoxelBase)intersection.Value.Entity;
                    Vector3D    point  = intersection.Value.IntersectionPointInWorldSpace;
                    if (intersection.Value.Entity is MyPlanet)
                    {
                        MyRenderProxy.DebugDrawText2D(new Vector2(20, 20), "Type: planet/moon", Color.Yellow,
                                                      DEBUG_SCALE);
                        MyRenderProxy.DebugDrawText2D(new Vector2(20, 30),
                                                      "Terrain: " + voxels.GetMaterialAt(ref point), Color.Yellow, DEBUG_SCALE);
                    }
                    else
                    {
                        MyRenderProxy.DebugDrawText2D(new Vector2(20, 20), "Type: asteroid", Color.Yellow,
                                                      DEBUG_SCALE);
                        MyRenderProxy.DebugDrawText2D(new Vector2(20, 30),
                                                      "Terrain: " + voxels.GetMaterialAt(ref point), Color.Yellow, DEBUG_SCALE);
                    }
                    MyRenderProxy.DebugDrawText2D(new Vector2(20, 40),
                                                  "Object size: " + voxels.SizeInMetres, Color.Yellow, DEBUG_SCALE);

                    //location

                    /*
                     * VRageRender.MyRenderProxy.DebugDrawText2D(new Vector2(20, 50), "Location:", Color.Yellow, 0.5f);
                     * VRageRender.MyRenderProxy.DebugDrawText2D(new Vector2(30, 60), "x " + Math.Round(point.X, 3).ToString(), Color.Yellow, 0.5f);
                     * VRageRender.MyRenderProxy.DebugDrawText2D(new Vector2(30, 70), "y " + Math.Round(point.Y, 3).ToString(), Color.Yellow, 0.5f);
                     * VRageRender.MyRenderProxy.DebugDrawText2D(new Vector2(30, 80), "z " + Math.Round(point.Z, 3).ToString(), Color.Yellow, 0.5f);*/
                }
                else if (intersection.Value.Entity is MyCubeGrid)
                {
                    MyCubeGrid grid = (MyCubeGrid)intersection.Value.Entity;
                    MyRenderProxy.DebugDrawText2D(new Vector2(20, 20), "Detected grid object", Color.Yellow, DEBUG_SCALE);
                    MyRenderProxy.DebugDrawText2D(new Vector2(20, 30), String.Format("Grid name: {0}", grid.DisplayName), Color.Yellow,
                                                  DEBUG_SCALE);
                    int row = 4;

                    MyIntersectionResultLineTriangleEx?t;
                    MySlimBlock block;
                    if (grid.GetIntersectionWithLine(ref line, out t, out block) && t.HasValue && block != null)
                    {
                        if (block.FatBlock != null)
                        {
                            DebugDrawModelTextures(block.FatBlock, ref row);
                        }
                        else
                        {
                            DebugDrawBareBlockInfo(block, ref row);
                        }
                    }
                }
                else
                {
                    MyRenderProxy.DebugDrawText2D(new Vector2(20, 20), "Unknown object detected", Color.Yellow,
                                                  DEBUG_SCALE);
                }
            }
            else
            {
                MyRenderProxy.DebugDrawText2D(new Vector2(20, 20), "Nothing detected nearby", Color.Yellow, DEBUG_SCALE);
            }
        }
Пример #43
0
 public static void DrawSemiTransparentBox(MyCubeGrid grid, MySlimBlock block, Color color, bool onlyWireframe = false, string lineMaterial = null, Vector4?lineColor = null)
 {
     DrawSemiTransparentBox(block.Min, block.Max, grid, color, onlyWireframe: onlyWireframe, lineMaterial: lineMaterial, lineColor: lineColor);
 }
Пример #44
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            PostBaseInit();

            //MyDebug.AssertDebug(objectBuilder.TypeId == typeof(MyObjectBuilder_Cockpit));
            var def = MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId());

            m_isLargeCockpit       = (def.CubeSize == MyCubeSize.Large);
            m_cockpitInteriorModel = BlockDefinition.InteriorModel;
            m_cockpitGlassModel    = BlockDefinition.GlassModel;

            NeedsUpdate = MyEntityUpdateEnum.EACH_100TH_FRAME;

            MyObjectBuilder_Cockpit cockpitOb = (MyObjectBuilder_Cockpit)objectBuilder;

            if (cockpitOb.Pilot != null)
            {
                MyEntity    pilotEntity;
                MyCharacter pilot = null;
                if (MyEntities.TryGetEntityById(cockpitOb.Pilot.EntityId, out pilotEntity))
                { //Pilot already exists, can be the case after cube grid split
                    pilot = (MyCharacter)pilotEntity;
                    if (pilot.IsUsing is MyShipController && pilot.IsUsing != this)
                    {
                        System.Diagnostics.Debug.Assert(false, "Pilot already sits on another place!");
                        pilot = null;
                    }
                }
                else
                {
                    pilot = (MyCharacter)MyEntities.CreateFromObjectBuilder(cockpitOb.Pilot);
                }

                if (pilot != null)
                {
                    AttachPilot(pilot, storeOriginalPilotWorld: false, calledFromInit: true);
                    if (cockpitOb.PilotRelativeWorld.HasValue)
                    {
                        m_pilotRelativeWorld = cockpitOb.PilotRelativeWorld.Value.GetMatrix();
                    }
                    else
                    {
                        m_pilotRelativeWorld = null;
                    }

                    m_singleWeaponMode = cockpitOb.UseSingleWeaponMode;
                }

                IsInFirstPersonView = cockpitOb.IsInFirstPersonView;
            }

            if (cockpitOb.Autopilot != null)
            {
                MyAutopilotBase autopilot = MyAutopilotFactory.CreateAutopilot(cockpitOb.Autopilot);
                autopilot.Init(cockpitOb.Autopilot);
                AttachAutopilot(autopilot, updateSync: false);
            }

            m_pilotGunDefinition = cockpitOb.PilotGunDefinition;

            // backward compatibility check for automatic rifle without subtype
            if (m_pilotGunDefinition.HasValue)
            {
                if (m_pilotGunDefinition.Value.TypeId == typeof(MyObjectBuilder_AutomaticRifle) &&
                    string.IsNullOrEmpty(m_pilotGunDefinition.Value.SubtypeName))
                {
                    m_pilotGunDefinition = new MyDefinitionId(typeof(MyObjectBuilder_AutomaticRifle), "RifleGun");
                }
            }

            if (!string.IsNullOrEmpty(m_cockpitInteriorModel))
            {
                if (MyModels.GetModelOnlyDummies(m_cockpitInteriorModel).Dummies.ContainsKey("head"))
                {
                    m_headLocalPosition = MyModels.GetModelOnlyDummies(m_cockpitInteriorModel).Dummies["head"].Matrix.Translation;
                }
            }
            else
            {
                if (MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies.ContainsKey("head"))
                {
                    m_headLocalPosition = MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies["head"].Matrix.Translation;
                }
            }

            AddDebugRenderComponent(new Components.MyDebugRenderComponentCockpit(this));

            InitializeConveyorEndpoint();

            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint));

            m_oxygenLevel = cockpitOb.OxygenLevel;
        }
Пример #45
0
 public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
 {
     base.Init(objectBuilder, cubeGrid);
 }
Пример #46
0
        protected virtual void InitSubBlocks()
        {
            if (!MyFakes.ENABLE_SUBBLOCKS)
            {
                return;
            }

            if (m_subBlocksInitialized)
            {
                return;
            }

            //  if (!Sync.IsServer)
            //    return;

            try
            {
                MyCubeBlockDefinition subBlockDefinition;
                MatrixD subBlockMatrix;
                Vector3 dummyPosition;

                var finalModel = Sandbox.Engine.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model);
                foreach (var dummy in finalModel.Dummies)
                {
                    if (!MyCubeBlock.GetSubBlockDataFromDummy(BlockDefinition, dummy.Key, dummy.Value, true, out subBlockDefinition, out subBlockMatrix, out dummyPosition))
                    {
                        continue;
                    }

                    string dummyName = dummy.Key.Substring(DUMMY_SUBBLOCK_ID.Length);

                    MySlimBlock        subblock = null;
                    MyCubeGrid         subgrid  = null;
                    MySubBlockLoadInfo subBlockLoadInfo;
                    if (m_subBlockIds.TryGetValue(dummyName, out subBlockLoadInfo))
                    {
                        MyEntity entity;
                        if (MyEntities.TryGetEntityById(subBlockLoadInfo.GridId, out entity))
                        {
                            subgrid = entity as MyCubeGrid;
                            if (subgrid != null)
                            {
                                subblock = subgrid.GetCubeBlock(subBlockLoadInfo.SubBlockPosition);
                                Debug.Assert(subblock != null, "Cannot find subblock in subgrid!");
                                if (subblock == null)
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                Debug.Assert(false, "Loaded entity is not grid!");
                                continue;
                            }
                        }
                        else
                        {
                            Debug.Assert(false, "Cannot load subgrid!");
                            continue;
                        }
                    }

                    if (!m_subBlocksLoaded)
                    {
                        if (subgrid == null)
                        {
                            Debug.Assert(!subBlockMatrix.IsMirrored());
                            Matrix subGridWorldMatrix = subBlockMatrix * PositionComp.LocalMatrix * CubeGrid.WorldMatrix;

                            //TODO: Try to find better way how to sync entity ID of subblocks..
                            subgrid = MyCubeBuilder.SpawnDynamicGrid(subBlockDefinition, subGridWorldMatrix, CubeGrid.EntityId + CubeGrid.BlocksCount * 128 + SubBlocks.Count * 16);
                            if (subgrid != null)
                            {
                                subblock = subgrid.GetCubeBlock(Vector3I.Zero);
                            }
                        }

                        if (subgrid == null)
                        {
                            Debug.Assert(false, "SubGrid has not been set!");
                            continue;
                        }

                        if (subblock == null || subblock.FatBlock == null)
                        {
                            Debug.Assert(false, "Fatblock cannot be null for subblocks!");
                            continue;
                        }
                    }

                    if (subblock != null)
                    {
                        SubBlocks.Add(dummyName, subblock);
                        subblock.FatBlock.SubBlockName = dummyName;
                        subblock.FatBlock.OwnerBlock   = SlimBlock;
                        subblock.FatBlock.OnClosing   += SubBlock_OnClosing;
                        Debug.Assert(SlimBlock != null);
                    }
                }
            }
            finally
            {
                m_subBlockIds.Clear();

                m_subBlocksInitialized = true;
            }
        }
Пример #47
0
        public Vector3 GetDefinitionOffsetWithNeighbours(Vector3I cubePos, Vector3I bonePos, MyCubeGrid grid)
        {
            Vector3I boneOffset = GetCubeBoneOffset(cubePos, bonePos);

            if (m_tempAffectedCubes == null)
            {
                m_tempAffectedCubes = new List <Vector3I>();
            }

            m_tempAffectedCubes.Clear();
            GetAffectedCubes(cubePos, boneOffset, m_tempAffectedCubes, grid);

            Vector3 offset        = Vector3.Zero;
            int     affectedCount = 0;

            foreach (var cube in m_tempAffectedCubes)
            {
                var cubeBlock = grid.GetCubeBlock(cube);
                if (cubeBlock != null && cubeBlock.BlockDefinition.Skeleton != null)
                {
                    Vector3I currentBoneOffset = GetCubeBoneOffset(cube, bonePos);

                    var defOffset = GetDefinitionOffset(cubeBlock, currentBoneOffset);
                    if (defOffset != null)
                    {
                        offset += defOffset.Value;
                        affectedCount++;
                    }
                }
            }

            if (affectedCount == 0)
            {
                return(offset);
            }
            return(offset / affectedCount);
        }
Пример #48
0
 public static HashSet <MyDataReceiver> GetGridRadioReceivers(MyCubeGrid grid)
 {
     return(GetGridRadioReceivers(grid, MySession.LocalPlayerId));
 }
Пример #49
0
        public void RemoveUnusedBones(MyCubeGrid grid)
        {
            ProfilerShort.Begin("RemoveUnusedBones");
            if (m_tmpRemovedCubes.Count != 0)
            {
                Debug.Assert(m_testedCubes.Count == 0);
                Debug.Assert(m_usedBones.Count == 0);

                foreach (var cube in m_tmpRemovedCubes)
                {
                    if (grid.CubeExists(cube))
                    {
                        if (!m_testedCubes.Contains(cube))
                        {
                            m_testedCubes.Add(cube);
                            AddUsedBones(cube);
                        }
                        continue;
                    }

                    Vector3I centerBonePos = cube * BoneDensity + Vector3I.One;
                    Vector3I dir, neighbor;

                    // Iterate over all the neighbors of the cube and check whether they are present in the grid
                    for (int x = -1; x <= 1; ++x)
                    {
                        for (int y = -1; y <= 1; ++y)
                        {
                            for (int z = -1; z <= 1; ++z)
                            {
                                dir.X    = x;
                                dir.Y    = y;
                                dir.Z    = z;
                                neighbor = cube + dir;

                                if (grid.CubeExists(neighbor) && !m_testedCubes.Contains(neighbor))
                                {
                                    m_testedCubes.Add(neighbor);
                                    AddUsedBones(neighbor);
                                }
                            }
                        }
                    }
                }

                foreach (var cube in m_tmpRemovedCubes)
                {
                    Vector3I pos = cube * BoneDensity;
                    for (int x = 0; x <= BoneDensity; ++x)
                    {
                        for (int y = 0; y <= BoneDensity; ++y)
                        {
                            for (int z = 0; z <= BoneDensity; ++z)
                            {
                                if (!m_usedBones.Contains(pos))
                                {
                                    ClearBone(ref pos);
                                }

                                pos.Z++;
                            }
                            pos.Y++;
                            pos.Z -= BoneDensity + 1;
                        }
                        pos.X++;
                        pos.Y -= BoneDensity + 1;
                    }
                }

                m_testedCubes.Clear();
                m_usedBones.Clear();
                m_tmpRemovedCubes.Clear();
            }
            ProfilerShort.End();
        }
Пример #50
0
        Color DrawSymmetryPlane(MySymmetrySettingModeEnum plane, MyCubeGrid localGrid, Vector3 center)
        {
            var localGridBB = localGrid.PositionComp.LocalAABB;

            float sizeMultiplier = 1.0f;
            float sizeOffset     = localGrid.GridSize;

            Vector3 l0 = Vector3.Zero;
            Vector3 l1 = Vector3.Zero;
            Vector3 l2 = Vector3.Zero;
            Vector3 l3 = Vector3.Zero;

            float alpha = 0.3f;
            Color color = Color.Gray;

            switch (plane)
            {
            case MySymmetrySettingModeEnum.XPlane:
            case MySymmetrySettingModeEnum.XPlaneOdd:
            {
                color = new Color(1.0f, 0, 0, alpha);

                center.X -= localGridBB.Center.X + (plane == MySymmetrySettingModeEnum.XPlaneOdd ? localGrid.GridSize * 0.5f : 0);
                center.Y  = 0;
                center.Z  = 0;

                l0 = new Vector3(0, localGridBB.HalfExtents.Y * sizeMultiplier + sizeOffset, localGridBB.HalfExtents.Z * sizeMultiplier + sizeOffset) + localGridBB.Center + center;
                l1 = new Vector3(0, -localGridBB.HalfExtents.Y * sizeMultiplier - sizeOffset, localGridBB.HalfExtents.Z * sizeMultiplier + sizeOffset) + localGridBB.Center + center;
                l2 = new Vector3(0, localGridBB.HalfExtents.Y * sizeMultiplier + sizeOffset, -localGridBB.HalfExtents.Z * sizeMultiplier - sizeOffset) + localGridBB.Center + center;
                l3 = new Vector3(0, -localGridBB.HalfExtents.Y * sizeMultiplier - sizeOffset, -localGridBB.HalfExtents.Z * sizeMultiplier - sizeOffset) + localGridBB.Center + center;
            }
            break;

            case MySymmetrySettingModeEnum.YPlane:
            case MySymmetrySettingModeEnum.YPlaneOdd:
            {
                color = new Color(0.0f, 1.0f, 0, alpha);

                center.X  = 0;
                center.Y -= localGridBB.Center.Y + (plane == MySymmetrySettingModeEnum.YPlaneOdd ? localGrid.GridSize * 0.5f : 0);
                center.Z  = 0;

                l0 = new Vector3(localGridBB.HalfExtents.X * sizeMultiplier + sizeOffset, 0, localGridBB.HalfExtents.Z * sizeMultiplier + sizeOffset) + localGridBB.Center + center;
                l1 = new Vector3(-localGridBB.HalfExtents.X * sizeMultiplier - sizeOffset, 0, localGridBB.HalfExtents.Z * sizeMultiplier + sizeOffset) + localGridBB.Center + center;
                l2 = new Vector3(localGridBB.HalfExtents.X * sizeMultiplier + sizeOffset, 0, -localGridBB.HalfExtents.Z * sizeMultiplier - sizeOffset) + localGridBB.Center + center;
                l3 = new Vector3(-localGridBB.HalfExtents.X * sizeMultiplier - sizeOffset, 0, -localGridBB.HalfExtents.Z * sizeMultiplier - sizeOffset) + localGridBB.Center + center;
            }
            break;

            case MySymmetrySettingModeEnum.ZPlane:
            case MySymmetrySettingModeEnum.ZPlaneOdd:
            {
                color = new Color(0.0f, 0, 1.0f, alpha);

                center.X  = 0;
                center.Y  = 0;
                center.Z -= localGridBB.Center.Z - (plane == MySymmetrySettingModeEnum.ZPlaneOdd ? localGrid.GridSize * 0.5f : 0);

                l0 = new Vector3(localGridBB.HalfExtents.X * sizeMultiplier + sizeOffset, localGridBB.HalfExtents.Y * sizeMultiplier + sizeOffset, 0) + localGridBB.Center + center;
                l1 = new Vector3(-localGridBB.HalfExtents.X * sizeMultiplier - sizeOffset, localGridBB.HalfExtents.Y * sizeMultiplier + sizeOffset, 0) + localGridBB.Center + center;
                l2 = new Vector3(localGridBB.HalfExtents.X * sizeMultiplier + sizeOffset, -localGridBB.HalfExtents.Y * sizeMultiplier - sizeOffset, 0) + localGridBB.Center + center;
                l3 = new Vector3(-localGridBB.HalfExtents.X * sizeMultiplier - sizeOffset, -localGridBB.HalfExtents.Y * sizeMultiplier - sizeOffset, 0) + localGridBB.Center + center;
            }
            break;
            }

            Vector3 p0 = Vector3.Transform(l0, (Matrix)CurrentGrid.WorldMatrix);
            Vector3 p1 = Vector3.Transform(l1, (Matrix)CurrentGrid.WorldMatrix);
            Vector3 p2 = Vector3.Transform(l2, (Matrix)CurrentGrid.WorldMatrix);
            Vector3 p3 = Vector3.Transform(l3, (Matrix)CurrentGrid.WorldMatrix);

            VRageRender.MyRenderProxy.DebugDrawTriangle(p0, p1, p2, color, true, true);
            VRageRender.MyRenderProxy.DebugDrawTriangle(p2, p1, p3, color, true, true);

            return(color);
        }
Пример #51
0
        /// <summary>
        /// Returns true when bone was changed.
        /// When new bone offset length is smaller than epsilon, it will remove bone.
        /// Factor is used as t paramter in a lerp. This is because the default position
        /// for a bone may not be 0
        /// </summary>
        public bool MultiplyBone(ref Vector3I pos, float factor, ref Vector3I cubePos, MyCubeGrid cubeGrid, float epsilon = 0.005f)
        {
            Vector3 value;

            if (Bones.TryGetValue(pos, out value))
            {
                var offset = GetDefinitionOffsetWithNeighbours(cubePos, pos, cubeGrid);

                factor = 1f - factor;

                if (factor < 0.1f)
                {
                    factor = 0.1f;
                }

                var newBone = Vector3.Lerp(value, offset, factor);
                if (newBone.LengthSquared() < epsilon * epsilon)
                {
                    Bones.Remove(pos);
                }
                else
                {
                    Bones[pos] = newBone;
                }
                return(true);
            }
            return(false);
        }
Пример #52
0
        protected bool GetBlockAddPosition(float gridSize, bool placingSmallGridOnLargeStatic, out MySlimBlock intersectedBlock, out Vector3D intersectedBlockPos, out Vector3D intersectExactPos, out Vector3I addPositionBlock, out Vector3I addDirectionBlock, out ushort?compoundBlockId)
        {
            Vector3I vectori;

            intersectedBlock    = null;
            intersectedBlockPos = new Vector3D();
            Vector3 vector = new Vector3();

            intersectExactPos = vector;
            addDirectionBlock = new Vector3I();
            addPositionBlock  = new Vector3I();
            compoundBlockId   = 0;
            if (this.CurrentVoxelBase != null)
            {
                Vector3I intVector = Base6Directions.GetIntVector(Base6Directions.GetClosestDirection(this.m_hitInfo.Value.HkHitInfo.Normal));
                Vector3D worldPos  = IntersectionStart + ((IntersectionDistance * this.m_hitInfo.Value.HkHitInfo.HitFraction) * Vector3D.Normalize(IntersectionDirection));
                addPositionBlock    = MyCubeGrid.StaticGlobalGrid_WorldToUGInt(worldPos + (((0.1f * Vector3.Half) * intVector) * gridSize), gridSize, CubeBuilderDefinition.BuildingSettings.StaticGridAlignToCenter);
                addDirectionBlock   = intVector;
                intersectedBlockPos = (Vector3D)(addPositionBlock - intVector);
                intersectExactPos   = MyCubeGrid.StaticGlobalGrid_WorldToUG(worldPos, gridSize, CubeBuilderDefinition.BuildingSettings.StaticGridAlignToCenter);
                intersectExactPos   = ((Vector3D.One - Vector3.Abs((Vector3)intVector)) * intersectExactPos) + ((intersectedBlockPos + (0.5f * intVector)) * Vector3.Abs((Vector3)intVector));
                return(true);
            }
            Vector3D?nullable = this.GetIntersectedBlockData(ref this.m_invGridWorldMatrix, out intersectExactPos, out intersectedBlock, out compoundBlockId);

            if (nullable == null)
            {
                return(false);
            }
            intersectedBlockPos = nullable.Value;
            if (!this.GetCubeAddAndRemovePositions(Vector3I.Round(intersectedBlockPos), placingSmallGridOnLargeStatic, out addPositionBlock, out addDirectionBlock, out vectori))
            {
                return(false);
            }
            if (!placingSmallGridOnLargeStatic)
            {
                if (!MyFakes.ENABLE_BLOCK_PLACING_ON_INTERSECTED_POSITION)
                {
                    if (this.CurrentGrid.CubeExists(addPositionBlock))
                    {
                        return(false);
                    }
                }
                else
                {
                    Vector3I vectori3 = Vector3I.Round(intersectedBlockPos);
                    if (vectori3 != vectori)
                    {
                        if (this.m_hitInfo != null)
                        {
                            Vector3I intVector = Base6Directions.GetIntVector(Base6Directions.GetClosestDirection(this.m_hitInfo.Value.HkHitInfo.Normal));
                            addDirectionBlock = intVector;
                        }
                        vectori          = vectori3;
                        addPositionBlock = (Vector3I)(vectori + addDirectionBlock);
                    }
                }
            }
            if (placingSmallGridOnLargeStatic)
            {
                vectori = Vector3I.Round(intersectedBlockPos);
            }
            intersectedBlockPos = (Vector3D)vectori;
            intersectedBlock    = this.CurrentGrid.GetCubeBlock(vectori);
            return(intersectedBlock != null);
        }
Пример #53
0
        public static MyDetectedEntityInfo Create(MyEntity entity, long sensorOwner, Vector3D?hitPosition = new Vector3D?())
        {
            MyDetectedEntityType             type;
            MyRelationsBetweenPlayerAndBlock neutral;
            string displayName;

            if (entity == null)
            {
                return(new MyDetectedEntityInfo());
            }
            MatrixD      zero     = MatrixD.Zero;
            Vector3      velocity = (Vector3)Vector3D.Zero;
            int          totalGamePlayTimeInMilliseconds = MySandboxGame.TotalGamePlayTimeInMilliseconds;
            BoundingBoxD worldAABB = entity.PositionComp.WorldAABB;

            if (entity.Physics != null)
            {
                zero     = entity.Physics.GetWorldMatrix().GetOrientation();
                velocity = entity.Physics.LinearVelocity;
            }
            MyCubeGrid topMostParent = entity.GetTopMostParent(null) as MyCubeGrid;

            if (topMostParent != null)
            {
                type    = (topMostParent.GridSizeEnum != MyCubeSize.Small) ? MyDetectedEntityType.LargeGrid : MyDetectedEntityType.SmallGrid;
                neutral = (topMostParent.BigOwners.Count != 0) ? MyIDModule.GetRelation(sensorOwner, topMostParent.BigOwners[0], MyOwnershipShareModeEnum.Faction, MyRelationsBetweenPlayerAndBlock.Enemies, MyRelationsBetweenFactions.Enemies, MyRelationsBetweenPlayerAndBlock.FactionShare) : MyRelationsBetweenPlayerAndBlock.NoOwnership;
                if ((neutral == MyRelationsBetweenPlayerAndBlock.Owner) || (neutral == MyRelationsBetweenPlayerAndBlock.FactionShare))
                {
                    displayName = topMostParent.DisplayName;
                }
                else
                {
                    displayName = (topMostParent.GridSizeEnum != MyCubeSize.Small) ? MyTexts.GetString(MySpaceTexts.DetectedEntity_LargeGrid) : MyTexts.GetString(MySpaceTexts.DetectedEntity_SmallGrid);
                }
                zero = topMostParent.WorldMatrix.GetOrientation();
                return(new MyDetectedEntityInfo(topMostParent.EntityId, displayName, type, hitPosition, zero, topMostParent.Physics.LinearVelocity, neutral, worldAABB, (long)totalGamePlayTimeInMilliseconds));
            }
            MyCharacter character = entity as MyCharacter;

            if (character != null)
            {
                type    = !character.IsPlayer ? MyDetectedEntityType.CharacterOther : MyDetectedEntityType.CharacterHuman;
                neutral = MyIDModule.GetRelation(sensorOwner, character.GetPlayerIdentityId(), MyOwnershipShareModeEnum.Faction, MyRelationsBetweenPlayerAndBlock.Enemies, MyRelationsBetweenFactions.Enemies, MyRelationsBetweenPlayerAndBlock.FactionShare);
                if ((neutral == MyRelationsBetweenPlayerAndBlock.Owner) || (neutral == MyRelationsBetweenPlayerAndBlock.FactionShare))
                {
                    displayName = character.DisplayNameText;
                }
                else
                {
                    displayName = !character.IsPlayer ? MyTexts.GetString(MySpaceTexts.DetectedEntity_CharacterOther) : MyTexts.GetString(MySpaceTexts.DetectedEntity_CharacterHuman);
                }
                return(new MyDetectedEntityInfo(entity.EntityId, displayName, type, hitPosition, zero, velocity, neutral, character.Model.BoundingBox.Transform(character.WorldMatrix), (long)totalGamePlayTimeInMilliseconds));
            }
            neutral = MyRelationsBetweenPlayerAndBlock.Neutral;
            MyFloatingObject obj2 = entity as MyFloatingObject;

            if (obj2 != null)
            {
                displayName = obj2.Item.Content.SubtypeName;
                return(new MyDetectedEntityInfo(entity.EntityId, displayName, MyDetectedEntityType.FloatingObject, hitPosition, zero, velocity, neutral, worldAABB, (long)totalGamePlayTimeInMilliseconds));
            }
            MyInventoryBagEntity entity2 = entity as MyInventoryBagEntity;

            if (entity2 != null)
            {
                displayName = entity2.DisplayName;
                return(new MyDetectedEntityInfo(entity.EntityId, displayName, MyDetectedEntityType.FloatingObject, hitPosition, zero, velocity, neutral, worldAABB, (long)totalGamePlayTimeInMilliseconds));
            }
            MyPlanet planet = entity as MyPlanet;

            if (planet != null)
            {
                displayName = MyTexts.GetString(MySpaceTexts.DetectedEntity_Planet);
                return(new MyDetectedEntityInfo(entity.EntityId, displayName, MyDetectedEntityType.Planet, hitPosition, zero, velocity, neutral, BoundingBoxD.CreateFromSphere(new BoundingSphereD(planet.PositionComp.GetPosition(), (double)planet.MaximumRadius)), (long)totalGamePlayTimeInMilliseconds));
            }
            MyVoxelPhysics physics = entity as MyVoxelPhysics;

            if (physics != null)
            {
                displayName = MyTexts.GetString(MySpaceTexts.DetectedEntity_Planet);
                return(new MyDetectedEntityInfo(entity.EntityId, displayName, MyDetectedEntityType.Planet, hitPosition, zero, velocity, neutral, BoundingBoxD.CreateFromSphere(new BoundingSphereD(physics.Parent.PositionComp.GetPosition(), (double)physics.Parent.MaximumRadius)), (long)totalGamePlayTimeInMilliseconds));
            }
            if (entity is MyVoxelMap)
            {
                displayName = MyTexts.GetString(MySpaceTexts.DetectedEntity_Asteroid);
                return(new MyDetectedEntityInfo(entity.EntityId, displayName, MyDetectedEntityType.Asteroid, hitPosition, zero, velocity, neutral, worldAABB, (long)totalGamePlayTimeInMilliseconds));
            }
            if (entity is MyMeteor)
            {
                displayName = MyTexts.GetString(MySpaceTexts.DetectedEntity_Meteor);
                return(new MyDetectedEntityInfo(entity.EntityId, displayName, MyDetectedEntityType.Meteor, hitPosition, zero, velocity, neutral, worldAABB, (long)totalGamePlayTimeInMilliseconds));
            }
            if (entity is MyMissile)
            {
                return(new MyDetectedEntityInfo(entity.EntityId, entity.DisplayName, MyDetectedEntityType.Missile, hitPosition, zero, velocity, neutral, worldAABB, (long)totalGamePlayTimeInMilliseconds));
            }
            Vector3D?nullable    = null;
            MatrixD  orientation = new MatrixD();
            Vector3  vector2     = new Vector3();

            return(new MyDetectedEntityInfo(0L, string.Empty, MyDetectedEntityType.Unknown, nullable, orientation, vector2, MyRelationsBetweenPlayerAndBlock.NoOwnership, new BoundingBoxD(), (long)MySandboxGame.TotalGamePlayTimeInMilliseconds));
        }
Пример #54
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            var sourceDataList = new List <MyResourceSourceInfo>
            {
                new MyResourceSourceInfo {
                    ResourceTypeId = MyResourceDistributorComponent.ElectricityId, DefinedOutput = BlockDefinition.MaxPowerOutput, ProductionToCapacityMultiplier = 60 * 60
                }
            };

            SourceComp.Init(BlockDefinition.ResourceSourceGroup, sourceDataList);
            SourceComp.HasCapacityRemainingChanged += (id, source) => UpdateIsWorking();
            SourceComp.ProductionEnabledChanged    += Source_ProductionEnabledChanged;

            var batteryBuilder = (MyObjectBuilder_BatteryBlock)objectBuilder;

            SourceComp.SetProductionEnabledByType(MyResourceDistributorComponent.ElectricityId, batteryBuilder.ProducerEnabled);

            MaxStoredPower = BlockDefinition.MaxStoredPower;

            ResourceSink.Init(
                BlockDefinition.ResourceSinkGroup,
                BlockDefinition.RequiredPowerInput,
                Sink_ComputeRequiredPower);

            base.Init(objectBuilder, cubeGrid);

            ResourceSink.Update();

            MyDebug.AssertDebug(BlockDefinition != null);
            MyDebug.AssertDebug(BlockDefinition.Id.TypeId == typeof(MyObjectBuilder_BatteryBlock));

            if (batteryBuilder.CurrentStoredPower >= 0)
            {
                CurrentStoredPower = batteryBuilder.CurrentStoredPower;
            }
            else
            {
                CurrentStoredPower = BlockDefinition.InitialStoredPowerRatio * BlockDefinition.MaxStoredPower;
            }

            m_storedPower.Value = CurrentStoredPower;


            SemiautoEnabled = batteryBuilder.SemiautoEnabled;
            OnlyRecharge    = !batteryBuilder.ProducerEnabled;
            OnlyDischarge   = batteryBuilder.OnlyDischargeEnabled;
            UpdateMaxOutputAndEmissivity();

            UpdateText();

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
            IsWorkingChanged += MyBatteryBlock_IsWorkingChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;

            m_lastUpdateTime = MySession.Static.GameplayFrameCounter;

            if (IsWorking)
            {
                OnStartWorking();
            }
        }
Пример #55
0
 protected static bool BreakGridGroupLink(GridLinkTypeEnum type, long linkId, MyCubeGrid parent, MyCubeGrid child)
 {
     return(MyCubeGridGroups.Static.BreakLink(type, linkId, parent, child));
 }
Пример #56
0
        protected bool GetBlockAddPosition(float gridSize, bool placingSmallGridOnLargeStatic, out MySlimBlock intersectedBlock, out Vector3D intersectedBlockPos, out Vector3D intersectExactPos,
                                           out Vector3I addPositionBlock, out Vector3I addDirectionBlock, out ushort?compoundBlockId)
        {
            intersectedBlock    = null;
            intersectedBlockPos = new Vector3D();
            intersectExactPos   = new Vector3();
            addDirectionBlock   = new Vector3I();
            addPositionBlock    = new Vector3I();
            compoundBlockId     = null;

            if (CurrentVoxelMap != null)
            {
                Vector3 hitInfoNormal = m_hitInfo.Value.HkHitInfo.Normal;
                Base6Directions.Direction closestDir = Base6Directions.GetClosestDirection(hitInfoNormal);
                Vector3I hitNormal = Base6Directions.GetIntVector(closestDir);

                double distance = IntersectionDistance * m_hitInfo.Value.HkHitInfo.HitFraction;

                Vector3D rayStart     = IntersectionStart;
                Vector3D rayDir       = Vector3D.Normalize(IntersectionDirection);
                Vector3D intersection = rayStart + distance * rayDir;

                // Get cube block placement position (add little threshold to hit normal direction to avoid wavy surfaces).
                addPositionBlock    = MyCubeGrid.StaticGlobalGrid_WorldToUGInt(intersection + 0.1f * Vector3.Half * hitNormal * gridSize, gridSize, MyPerGameSettings.BuildingSettings.StaticGridAlignToCenter);
                addDirectionBlock   = hitNormal;
                intersectedBlockPos = addPositionBlock - hitNormal;

                // Exact intersection in uniform grid coords.
                intersectExactPos = MyCubeGrid.StaticGlobalGrid_WorldToUG(intersection, gridSize, MyPerGameSettings.BuildingSettings.StaticGridAlignToCenter);
                // Project exact intersection to cube face of intersected block.
                intersectExactPos = ((Vector3.One - Vector3.Abs(hitNormal)) * intersectExactPos) + ((intersectedBlockPos + 0.5f * hitNormal) * Vector3.Abs(hitNormal));

                //Vector3 position = MyCubeGrid.StaticWorldGrid_UGToWorld(addPositionBlock);
                //Vector3 halfExtent = new Vector3(gridSize * 0.5f);
                //BoundingBox cubeBox = new BoundingBox(-halfExtent, halfExtent);

                //Matrix matrix = Matrix.CreateTranslation(position);
                //Vector4 blue = Color.Blue.ToVector4();
                //MySimpleObjectDraw.DrawTransparentBox(ref matrix, ref cubeBox, ref blue, MySimpleObjectRasterizer.Wireframe, 1, 0.04f);

                return(true);
            }

            Vector3D?intersectedObjectPos = GetIntersectedBlockData(ref m_invGridWorldMatrix, out intersectExactPos, out intersectedBlock, out compoundBlockId);

            if (intersectedObjectPos == null)
            {
                return(false);
            }

            intersectedBlockPos = intersectedObjectPos.Value;

            Vector3I removePos;

            if (!GetCubeAddAndRemovePositions(Vector3I.Round(intersectedBlockPos), placingSmallGridOnLargeStatic, out addPositionBlock, out addDirectionBlock, out removePos))
            {
                return(false);
            }

            if (!placingSmallGridOnLargeStatic)
            {
                if (MyFakes.ENABLE_BLOCK_PLACING_ON_INTERSECTED_POSITION)
                {
                    Vector3I newRemovepos = Vector3I.Round(intersectedBlockPos);

                    if (newRemovepos != removePos)
                    {
                        if (m_hitInfo.HasValue)
                        {
                            Vector3 hitInfoNormal = m_hitInfo.Value.HkHitInfo.Normal;
                            Base6Directions.Direction closestDir = Base6Directions.GetClosestDirection(hitInfoNormal);
                            Vector3I hitNormal = Base6Directions.GetIntVector(closestDir);
                            addDirectionBlock = hitNormal;
                        }
                        removePos        = newRemovepos;
                        addPositionBlock = removePos + addDirectionBlock;
                    }
                }
                else
                {
                    if (CurrentGrid.CubeExists(addPositionBlock))
                    {
                        return(false);
                    }
                }
            }

            if (placingSmallGridOnLargeStatic)
            {
                removePos = Vector3I.Round(intersectedBlockPos);
            }

            intersectedBlockPos = removePos;
            intersectedBlock    = CurrentGrid.GetCubeBlock(removePos);
            if (intersectedBlock == null)
            {
                Debug.Assert(false, "No intersected block");
                return(false);
            }

            return(true);
        }
Пример #57
0
 /// <summary>
 /// Breaks link between parent and child, you can set child to null to find it by linkId.
 /// Returns true when link was removed, returns false when link was not found.
 /// </summary>
 public bool BreakLink(GridLinkTypeEnum type, long linkId, MyCubeGrid parent, MyCubeGrid child = null)
 {
     PhysicalDynamic.BreakLink(linkId, parent, child);
     return(GetGroups(type).BreakLink(linkId, parent, child));
 }
Пример #58
0
        public static MyTrashRemovalFlags GetTrashState(MyCubeGrid grid, MyTrashRemovalSettings settings)
        {
            float metric;

            return(GetTrashState(grid, settings, out metric, true));
        }
Пример #59
0
        public virtual void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            //objectBuilder.PersistentFlags |= MyPersistentEntityFlags2.CastShadows;
            // Ensure that if we went from not serializing to serializing, we have a valid entity id.
            if (builder.EntityId == 0)
            {
                EntityId = MyEntityIdentifier.AllocateId();
            }
            else if (builder.EntityId != 0)
            {
                EntityId = builder.EntityId;
            }

            NumberInGrid        = cubeGrid.BlockCounter.GetNextNumber(builder.GetId());
            Render.ColorMaskHsv = builder.ColorMaskHSV;

            if (BlockDefinition.ContainsComputer())
            {
                m_IDModule = new MyIDModule();

                if (MySession.Static.Settings.ResetOwnership && Sync.IsServer)
                {
                    m_IDModule.Owner     = 0;
                    m_IDModule.ShareMode = MyOwnershipShareModeEnum.None;
                }
                else
                {
                    if ((int)builder.ShareMode == -1)
                    {
                        builder.ShareMode = MyOwnershipShareModeEnum.None;
                    }

                    var ownerType = MyEntityIdentifier.GetIdObjectType(builder.Owner);
                    if (builder.Owner != 0 && ownerType != MyEntityIdentifier.ID_OBJECT_TYPE.NPC && ownerType != MyEntityIdentifier.ID_OBJECT_TYPE.SPAWN_GROUP)
                    {
                        System.Diagnostics.Debug.Assert(ownerType == MyEntityIdentifier.ID_OBJECT_TYPE.IDENTITY, "Old save detected, reseting owner to Nobody, please resave.");

                        if (!Sync.Players.HasIdentity(builder.Owner))
                        {
                            builder.Owner = 0; //reset, it was old version
                        }
                    }

                    m_IDModule.Owner     = builder.Owner;
                    m_IDModule.ShareMode = builder.ShareMode;
                }
            }

            if (MyFakes.ENABLE_SUBBLOCKS)
            {
                if (builder.SubBlocks != null)
                {
                    foreach (var subblockInfo in builder.SubBlocks)
                    {
                        m_subBlockIds.Add(subblockInfo.SubGridName, new MySubBlockLoadInfo()
                        {
                            GridId = subblockInfo.SubGridId, SubBlockPosition = subblockInfo.SubBlockPosition
                        });
                    }

                    m_subBlocksLoaded = m_subBlockIds.Count > 0;

                    if (BlockDefinition.SubBlockDefinitions != null && BlockDefinition.SubBlockDefinitions.Count > 0 && m_subBlockIds.Count == 0)
                    {
                        m_subBlocksInitialized = true;
                        m_subBlocksLoaded      = true;
                    }

                    // Set update flag for InitSubBlocks
                    NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
                }
            }


            base.Init(null);
            base.Render.PersistentFlags |= MyPersistentEntityFlags2.CastShadows;
            Init();
            AddDebugRenderComponent(new MyDebugRenderComponentCubeBlock(this));
        }
Пример #60
0
        public static float GetMetric(MyEntityCyclingOrder order, MyEntity entity)
        {
            MyCubeGrid             grid    = entity as MyCubeGrid;
            MyPhysicsComponentBase physics = entity.Physics;

            switch (order)
            {
            case MyEntityCyclingOrder.Characters:
                return((entity is MyCharacter) ? ((float)1) : ((float)0));

            case MyEntityCyclingOrder.BiggestGrids:
                return((grid != null) ? ((float)grid.GetBlocks().Count) : ((float)0));

            case MyEntityCyclingOrder.Fastest:
                if (physics == null)
                {
                    return(0f);
                }
                return((float)Math.Round((double)physics.LinearVelocity.Length(), 2));

            case MyEntityCyclingOrder.BiggestDistanceFromPlayers:
                if ((entity is MyVoxelBase) || (entity is MySafeZone))
                {
                    return(0f);
                }
                return(GetPlayerDistance(entity));

            case MyEntityCyclingOrder.MostActiveDrills:
                return(GetActiveBlockCount <MyShipDrill>(grid, false));

            case MyEntityCyclingOrder.MostActiveReactors:
                return(GetActiveBlockCount <MyReactor>(grid, false));

            case MyEntityCyclingOrder.MostActiveProductionBuildings:
                return(GetActiveBlockCount <MyProductionBlock>(grid, false));

            case MyEntityCyclingOrder.MostActiveSensors:
                return(GetActiveBlockCount <MySensorBlock>(grid, false));

            case MyEntityCyclingOrder.MostActiveThrusters:
                return(GetActiveBlockCount <MyThrust>(grid, false));

            case MyEntityCyclingOrder.MostWheels:
                return(GetActiveBlockCount <MyMotorSuspension>(grid, true));

            case MyEntityCyclingOrder.StaticObjects:
                int num1;
                if (((entity.Physics == null) || (entity.Physics.IsPhantom || (entity.Physics.AngularVelocity.AbsMax() >= 0.05f))) || (entity.Physics.LinearVelocity.AbsMax() >= 0.05f))
                {
                    num1 = 0;
                }
                else
                {
                    num1 = 1;
                }
                return((float)num1);

            case MyEntityCyclingOrder.FloatingObjects:
                return((entity is MyFloatingObject) ? ((float)1) : ((float)0));

            case MyEntityCyclingOrder.Planets:
                return((entity is MyPlanet) ? ((float)1) : ((float)0));

            case MyEntityCyclingOrder.OwnerLoginTime:
                return(GetOwnerLoginTime(grid));
            }
            return(0f);
        }