private void RecreateConstraints(VRage.Game.Entity.MyEntity obj, bool refreshInPlace) { if ((((((obj != null) && !obj.MarkedForClose) && (obj.GetPhysicsBody() != null)) && (!obj.IsPreview && (base.CubeGrid.Projector == null))) && ((this.m_leftSubpart == null) || (!this.m_leftSubpart.MarkedForClose && !this.m_leftSubpart.Closed))) && ((this.m_rightSubpart == null) || (!this.m_rightSubpart.MarkedForClose && !this.m_rightSubpart.Closed))) { Matrix?nullable; MyCubeGridRenderCell orAddCell = base.CubeGrid.RenderData.GetOrAddCell((Vector3)(base.Position * base.CubeGrid.GridSize), true); if (this.m_leftSubpart != null) { nullable = null; this.m_leftSubpart.Render.SetParent(0, orAddCell.ParentCullObject, nullable); } if (this.m_rightSubpart != null) { nullable = null; this.m_rightSubpart.Render.SetParent(0, orAddCell.ParentCullObject, nullable); } base.DisposeSubpartConstraint(ref this.m_leftConstraint, ref this.m_leftConstraintData); base.DisposeSubpartConstraint(ref this.m_rightConstraint, ref this.m_rightConstraintData); if ((base.InScene && (base.CubeGrid.Physics != null)) && (base.CubeGrid.Physics.IsInWorld || ((MyPhysicsBody)base.CubeGrid.Physics).IsInWorldWelded())) { this.CreateConstraints(); } if (obj.Physics != null) { this.UpdateHavokCollisionSystemID(obj.GetPhysicsBody().HavokCollisionSystemID, refreshInPlace); } this.UpdateSlidingDoorsPosition(); } }
private void CubeGrid_OnPhysicsChanged(VRage.Game.Entity.MyEntity obj) { if (((this.m_subparts != null) && (this.m_subparts.Count != 0)) && ((obj.Physics != null) && (this.m_subparts[0].Physics != null))) { base.NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; } }
private void UpdateHavokCollisionSystemID(VRage.Game.Entity.MyEntity obj) { if ((((obj != null) && (!obj.MarkedForClose && (obj.GetPhysicsBody() != null))) && (this.m_subparts[0].GetPhysicsBody() != null)) && (obj.GetPhysicsBody().HavokCollisionSystemID != this.m_subparts[0].GetPhysicsBody().HavokCollisionSystemID)) { this.UpdateHavokCollisionSystemID(obj.GetPhysicsBody().HavokCollisionSystemID); } }
protected void SerializeActive(BitStream stream, MyEntity entity) { if (stream.Writing) { if (entity.Physics.RigidBody != null && entity.Physics.RigidBody.IsActive) stream.WriteBool(true); else stream.WriteBool(false); } else { // reading bool isActive = stream.ReadBool(); if (entity != null && entity.Physics != null) { HkRigidBody rb = entity.Physics.RigidBody; if (rb != null) { if (isActive) rb.Activate(); else rb.Deactivate(); } } } }
protected void CreateSubpartConstraint(VRage.Game.Entity.MyEntity subpart, out HkFixedConstraintData constraintData, out HkConstraint constraint) { constraintData = null; constraint = null; if (base.CubeGrid.Physics != null) { HkRigidBody rigidBody; uint info = HkGroupFilter.CalcFilterInfo(subpart.GetPhysicsBody().RigidBody.Layer, base.CubeGrid.GetPhysicsBody().HavokCollisionSystemID, 1, 1); subpart.Physics.RigidBody.SetCollisionFilterInfo(info); subpart.Physics.Enabled = true; constraintData = new HkFixedConstraintData(); constraintData.SetSolvingMethod(HkSolvingMethod.MethodStabilized); constraintData.SetInertiaStabilizationFactor(1f); if ((base.CubeGrid.Physics.RigidBody2 == null) || !base.CubeGrid.Physics.Flags.HasFlag(RigidBodyFlag.RBF_DOUBLED_KINEMATIC)) { rigidBody = base.CubeGrid.Physics.RigidBody; } else { rigidBody = base.CubeGrid.Physics.RigidBody2; } constraint = new HkConstraint(rigidBody, subpart.Physics.RigidBody, constraintData); constraint.WantRuntime = true; } }
private void MyOreDetector_OnClose(VRage.Game.Entity.MyEntity obj) { if (this.m_oreDetectorComponent != null) { this.m_oreDetectorComponent.DiscardNextQuery(); } }
protected override void UnloadData() { EntitySelectedForDebug = null; m_skinnedEntityComponents.Clear(); m_skinnedEntityComponentsToAdd.Clear(); m_skinnedEntityComponentsToRemove.Clear(); }
public void GotoFailed() { this.HasGotoFailed = true; if (this.m_currentTarget == MyAiTargetEnum.CHARACTER) { this.AddUnreachableEntity(this.m_targetEntity, 0x4e20); } else if (this.m_currentTarget == MyAiTargetEnum.CUBE) { VRage.Game.Entity.MyEntity targetEntity = this.m_targetEntity; MySlimBlock cubeBlock = this.GetCubeBlock(); if ((cubeBlock != null) && (cubeBlock.FatBlock != null)) { this.AddUnreachableEntity(cubeBlock.FatBlock, 0xea60); } } else if ((this.m_targetEntity != null) && (this.m_targetEntity is MyTrees)) { this.AddUnreachableTree(this.m_targetEntity, this.m_targetTreeId, 0x4e20); } else if ((this.m_targetEntity != null) && (this.m_currentTarget != MyAiTargetEnum.VOXEL)) { this.AddUnreachableEntity(this.m_targetEntity, 0x4e20); } this.UnsetTarget(); }
public void RemoveTrigger(MyEntity entity, MyTriggerComponent trigger) { if (m_updateLock) m_removeCacheTrigger.Add(new MyTuple<MyEntity, MyTriggerComponent>(entity, trigger)); else RemoveTriggerCached(entity, trigger); }
protected void EnableDetectorsInArea(Vector3D from) { this.GatherDetectorsInArea(from); for (int i = 0; i < m_detectableEntities.Count; i++) { MyUseObjectsComponentBase base2; VRage.Game.Entity.MyEntity entity = m_detectableEntities[i]; MyCompoundCubeBlock block = entity as MyCompoundCubeBlock; if (block != null) { foreach (MySlimBlock block2 in block.GetBlocks()) { if (block2.FatBlock != null) { m_detectableEntities.Add(block2.FatBlock); } } } if (entity.Components.TryGet <MyUseObjectsComponentBase>(out base2) && (base2.DetectorPhysics != null)) { base2.PositionChanged(base2.Container.Get <MyPositionComponentBase>()); base2.DetectorPhysics.Enabled = true; } } }
public virtual void Init(MyObjectBuilder_AiTarget builder) { this.m_currentTarget = builder.CurrentTarget; this.m_targetEntity = null; if (builder.EntityId == null) { this.m_currentTarget = MyAiTargetEnum.NO_TARGET; } else if (!Sandbox.Game.Entities.MyEntities.TryGetEntityById(builder.EntityId.Value, out this.m_targetEntity, false)) { this.m_currentTarget = MyAiTargetEnum.NO_TARGET; } this.m_targetCube = builder.TargetCube; this.SetMTargetPosition(builder.TargetPosition); this.m_compoundId = builder.CompoundId; if (builder.UnreachableEntities != null) { foreach (MyObjectBuilder_AiTarget.UnreachableEntitiesData data in builder.UnreachableEntities) { VRage.Game.Entity.MyEntity entity = null; if (Sandbox.Game.Entities.MyEntities.TryGetEntityById(data.UnreachableEntityId, out entity, false)) { this.m_unreachableEntities.Add(entity, MySandboxGame.TotalGamePlayTimeInMilliseconds + data.Timeout); } } } }
public static MyEntity Spawn(this MyPhysicalInventoryItem thisItem, MyFixedPoint amount, BoundingBoxD box, MyEntity owner = null) { if(amount < 0) { return null; } MatrixD spawnMatrix = MatrixD.Identity; spawnMatrix.Translation = box.Center; var entity = Spawn(thisItem, amount, spawnMatrix, owner); if (entity == null) return null; var size = entity.PositionComp.LocalVolume.Radius; var halfSize = box.Size / 2 - new Vector3(size); halfSize = Vector3.Max(halfSize, Vector3.Zero); box = new BoundingBoxD(box.Center - halfSize, box.Center + halfSize); var pos = MyUtils.GetRandomPosition(ref box); Vector3 forward = MyUtils.GetRandomVector3Normalized(); Vector3 up = MyUtils.GetRandomVector3Normalized(); while (forward == up) up = MyUtils.GetRandomVector3Normalized(); Vector3 right = Vector3.Cross(forward, up); up = Vector3.Cross(right, forward); entity.WorldMatrix = MatrixD.CreateWorld(pos, forward, up); return entity; }
void m_entity_OnClose(MyEntity obj) { if (m_shotSmoke != null) { MyParticlesManager.RemoveParticleEffect(m_shotSmoke); m_shotSmoke = null; } }
public MyGridContactInfo(ref HkContactPointEvent evnt, MyCubeGrid grid) { Event = evnt; ContactPosition = grid.Physics.ClusterToWorld(evnt.ContactPoint.Position); m_currentEntity = grid; m_collidingEntity = Event.GetOtherEntity(grid) as MyEntity; m_currentBlock = null; m_otherBlock = null; ImpulseMultiplier = 1; }
private void Clear() { this.m_currentTarget = MyAiTargetEnum.NO_TARGET; this.m_targetEntity = null; this.m_targetCube = Vector3I.Zero; this.m_targetPosition = Vector3D.Zero; this.m_targetInVoxelCoord = Vector3I.Zero; this.m_compoundId = null; this.m_targetTreeId = 0; }
protected virtual void UnsetTargetEntity() { if (this.IsTargetGridOrBlock(this.m_currentTarget) && (this.m_targetEntity is MyCubeGrid)) { (this.m_targetEntity as MyCubeGrid).OnBlockRemoved -= new Action <MySlimBlock>(this.BlockRemoved); } this.m_compoundId = null; this.m_targetEntity = null; this.m_currentTarget = MyAiTargetEnum.NO_TARGET; }
public override void Init(MyEntity entity, MyLargeTurretBase turretBase) { base.Init(entity, turretBase); // backward compatibility with old mods/models if (!m_gunBase.HasDummies) { Vector3 muzzleVec = -Entity.PositionComp.WorldMatrix.Forward * 0.8f; m_gunBase.AddMuzzleMatrix(MyAmmoType.HighSpeed, Matrix.CreateTranslation(muzzleVec)); } }
public static object CreateCubeBlock(MyObjectBuilder_CubeBlock builder) { object local1 = m_objectFactory.CreateInstance(builder.TypeId); VRage.Game.Entity.MyEntity entity = local1 as VRage.Game.Entity.MyEntity; if (entity != null) { MyEntityFactory.AddScriptGameLogic(entity, builder.TypeId, builder.SubtypeName); } return(local1); }
public override void LoadData() { EntitySelectedForDebug = null; m_skinnedEntityComponents.Clear(); m_skinnedEntityComponentsToAdd.Clear(); m_skinnedEntityComponentsToRemove.Clear(); MySessionComponentAnimationSystem.Static = this; if (!MySessionComponentExtDebug.Static.IsHandlerRegistered(LiveDebugging_ReceivedMessageHandler)) MySessionComponentExtDebug.Static.ReceivedMsg += LiveDebugging_ReceivedMessageHandler; }
static bool ValidatePosition(MyEntity entity, Vector3D position) { float positionTolerancy = Math.Max(entity.PositionComp.MaximalSize * 0.1f, 0.1f); float smallSpeed = 0.1f; if (entity.m_serverLinearVelocity == Vector3.Zero || entity.m_serverLinearVelocity.Length() < smallSpeed) // some tolerancy of position for not moving objects positionTolerancy = Math.Max(entity.PositionComp.MaximalSize * 0.5f, 1.0f); if ((position - entity.PositionComp.GetPosition()).Length() < positionTolerancy) return false; return true; }
public void SetTargetTree(ref MyEnvironmentItems.ItemInfo targetTree, long treesId) { VRage.Game.Entity.MyEntity entity; if (Sandbox.Game.Entities.MyEntities.TryGetEntityById(treesId, out entity, false)) { this.UnsetTarget(); this.SetMTargetPosition(targetTree.Transform.Position); this.m_targetEntity = entity; this.m_targetTreeId = targetTree.LocalId; this.SetTargetEntity(entity); } }
private void RemoveTriggerCached(MyEntity entity, MyTriggerComponent trigger) { if (m_triggers.ContainsKey(entity) && m_triggers[entity].Contains(trigger)) { if (m_triggers[entity].Count == 1) { m_triggers[entity].Clear(); m_triggers.Remove(entity); } else m_triggers[entity].Remove(trigger); } }
public override bool EntityCanPaste(VRage.Game.Entity.MyEntity pastingEntity) { if (base.CopiedGrids.Count < 1) { return(false); } if (MySession.Static.CreativeToolsEnabled(Sync.MyId)) { return(true); } MyCubeBuilder.BuildComponent.GetMultiBlockPlacementMaterials(this.m_multiBlockDefinition); return(MyCubeBuilder.BuildComponent.HasBuildingMaterials(pastingEntity, false)); }
public void UpdateHudParams(VRage.Game.Entity.MyEntity entity) { if (Sync.IsServer) { List <MyObjectBuilder_HudEntityParams> list = new List <MyObjectBuilder_HudEntityParams>(); foreach (MyHudEntityParams @params in entity.GetHudParams(false)) { list.Add(@params.GetObjectBuilder()); } EndpointId targetEndpoint = new EndpointId(); MyMultiplayer.RaiseEvent <MyDataBroadcaster, List <MyObjectBuilder_HudEntityParams> >(this, x => new Action <List <MyObjectBuilder_HudEntityParams> >(x.OnUpdateHudParams), list, targetEndpoint); } }
private void CubeGrid_OnClosing(VRage.Game.Entity.MyEntity entity) { MyCubeGrid grid = (MyCubeGrid)entity; if (grid.GridSizeEnum == MyCubeSize.Small) { this.RemoveSmallGridConnections(grid); } else { this.RemoveLargeGridConnections(grid); } }
public IMyPath FindPathGlobal(Vector3D begin, IMyDestinationShape end, VRage.Game.Entity.MyEntity relativeEntity) { Vector3D vectord; float num; IMyEntity entity; MyRDPath path = new MyRDPath(this, begin, end); if (!path.GetNextTarget(begin, out vectord, out num, out entity)) { path = null; } return(path); }
public bool IsEntityReachable(VRage.Game.Entity.MyEntity entity) { if (entity == null) { return(false); } bool flag = true; if (entity.Parent != null) { flag &= this.IsEntityReachable(entity.Parent); } return(flag && !this.m_unreachableEntities.ContainsKey(entity)); }
public bool IsTreeReachable(VRage.Game.Entity.MyEntity entity, int treeId) { if (entity == null) { return(false); } bool flag = true; if (entity.Parent != null) { flag &= this.IsEntityReachable(entity.Parent); } return(flag && !this.m_unreachableTrees.ContainsKey(new Tuple <VRage.Game.Entity.MyEntity, int>(entity, treeId))); }
protected MyBehaviorTreeState HasTargetArea([BTIn] ref MyBBMemoryTarget inTarget) { if ((inTarget != null) && (inTarget.EntityId != null)) { VRage.Game.Entity.MyEntity entity = null; if (Sandbox.Game.Entities.MyEntities.TryGetEntityById(inTarget.EntityId.Value, out entity, false)) { MyPlaceArea component = null; if (entity.Components.TryGet <MyPlaceArea>(out component)) { return(MyBehaviorTreeState.SUCCESS); } } } return(MyBehaviorTreeState.FAILURE); }
private void DisablePhysicsRecursively(VRage.Game.Entity.MyEntity entity) { if ((entity.Physics != null) && entity.Physics.Enabled) { entity.Physics.Enabled = false; } MyFloatingObject obj2 = entity as MyFloatingObject; if (obj2 != null) { obj2.NeedsUpdate = MyEntityUpdateEnum.NONE; } foreach (MyHierarchyComponentBase base2 in entity.Hierarchy.Children) { this.DisablePhysicsRecursively(base2.Container.Entity as VRage.Game.Entity.MyEntity); } }
public void QueueEntity(MyEntity entity) { long time = Time(); time += EntityPreserveTime; m_entities.Insert(new EntityReference { Entity = entity }, time); m_index.Add(entity.EntityId); if (UpdateOrder == MyUpdateOrder.NoUpdate) { SetUpdateOrder(MyUpdateOrder.AfterSimulation); } }
private void RemoveUnreachableTrees(VRage.Game.Entity.MyEntity entity) { entity.OnClosing -= new Action <VRage.Game.Entity.MyEntity>(this.RemoveUnreachableTrees); using (MyUtils.ReuseCollection <Tuple <VRage.Game.Entity.MyEntity, int> >(ref m_tmpTrees)) { foreach (Tuple <VRage.Game.Entity.MyEntity, int> tuple in this.m_unreachableTrees.Keys) { if (tuple.Item1 == entity) { m_tmpTrees.Add(tuple); } } foreach (Tuple <VRage.Game.Entity.MyEntity, int> tuple2 in m_tmpTrees) { this.RemoveUnreachableTree(tuple2); } } }
protected virtual void SetTargetEntity(VRage.Game.Entity.MyEntity entity) { switch (entity) { case (MyCubeBlock _): { ushort?compoundId = null; this.SetTargetBlock((entity as MyCubeBlock).SlimBlock, compoundId); break; } case (null): break; default: this.UnsetTargetEntity(); break; } }
public virtual void Init(MyEntity entity, MyLargeTurretBase turretBase) { m_entity = entity; m_turretBase = turretBase; m_gunBase = turretBase.GunBase as MyGunBase; // Check for the dummy cubes for the muzzle flash positions: if (m_entity.Model != null) { if (m_entity.Model.Dummies.ContainsKey("camera")) { CameraDummy = m_entity.Model.Dummies["camera"]; } m_gunBase.LoadDummies(m_entity.Model.Dummies); } m_entity.OnClose += m_entity_OnClose; }
public void GetSupportingEntities(List <VRage.Game.Entity.MyEntity> outEntities) { if (this.CharacterRigidBody != null) { using (List <HkRigidBody> .Enumerator enumerator = this.CharacterRigidBody.GetSupportInfo().GetEnumerator()) { while (enumerator.MoveNext()) { MyPhysicsBody userObject = (MyPhysicsBody)enumerator.Current.UserObject; if (userObject != null) { VRage.Game.Entity.MyEntity item = (VRage.Game.Entity.MyEntity)userObject.Entity; if ((item != null) && !item.MarkedForClose) { outEntities.Add(item); } } } } } }
private void MyEntities_OnEntityAdd(VRage.Game.Entity.MyEntity obj) { MyCubeGrid cubeGrid = obj as MyCubeGrid; if (cubeGrid != null) { List <MyNavmeshManager> list; MyPlanet key = this.GetPlanet(cubeGrid.PositionComp.WorldAABB.Center); if ((key != null) && this.m_planetManagers.TryGetValue(key, out list)) { bool flag = false; foreach (MyNavmeshManager manager in list) { flag |= manager.InvalidateArea(cubeGrid.PositionComp.WorldAABB); } if (flag) { this.AddToTrackedGrids(cubeGrid); } } } }
private float GetObserverAngularVelocityDiff() { MyGridPhysics physics = base.CubeGrid.Physics; if ((physics != null) && (physics.LinearVelocity.LengthSquared() > 16f)) { IMyControllableEntity controlledEntity = MySession.Static.ControlledEntity; if (controlledEntity != null) { VRage.Game.Entity.MyEntity entity = controlledEntity.Entity; if (entity != null) { MyPhysicsComponentBase base2 = entity.GetTopMostParent(null).Physics; if (base2 != null) { return((physics.AngularVelocity - base2.AngularVelocity).Length()); } } } } return(0f); }
private void MyEntities_OnEntityRemove(VRage.Game.Entity.MyEntity obj) { MyCubeGrid item = obj as MyCubeGrid; if ((item != null) && this.m_grids.Remove(item)) { List <MyNavmeshManager> list; item.OnBlockAdded -= new Action <MySlimBlock>(this.Grid_OnBlockAdded); item.OnBlockRemoved -= new Action <MySlimBlock>(this.Grid_OnBlockRemoved); MyPlanet key = this.GetPlanet(item.PositionComp.WorldAABB.Center); if ((key != null) && this.m_planetManagers.TryGetValue(key, out list)) { using (List <MyNavmeshManager> .Enumerator enumerator = list.GetEnumerator()) { while (enumerator.MoveNext()) { enumerator.Current.InvalidateArea(item.PositionComp.WorldAABB); } } } } }
public static void TakeMaterialsFromBuilder(List<MyObjectBuilder_CubeGrid> blocksToBuild, MyEntity builder) { Debug.Assert(blocksToBuild.Count == 1); if (blocksToBuild.Count == 0) return; // Search for multiblock definition. var firstBlock = blocksToBuild[0].CubeBlocks.FirstOrDefault(); Debug.Assert(firstBlock != null); if (firstBlock == null ) return; MyDefinitionId multiBlockDefId; var compound = firstBlock as MyObjectBuilder_CompoundCubeBlock; if (compound != null) { Debug.Assert(compound.Blocks != null && compound.Blocks.Length > 0 && compound.Blocks[0].MultiBlockDefinition != null); if (compound.Blocks == null || compound.Blocks.Length == 0 || compound.Blocks[0].MultiBlockDefinition == null) return; multiBlockDefId = compound.Blocks[0].MultiBlockDefinition.Value; } else { Debug.Assert(firstBlock.MultiBlockDefinition != null); if (firstBlock.MultiBlockDefinition == null) return; multiBlockDefId = firstBlock.MultiBlockDefinition.Value; } MyMultiBlockDefinition multiBlockDefinition = MyDefinitionManager.Static.TryGetMultiBlockDefinition(multiBlockDefId); Debug.Assert(multiBlockDefinition != null); if (multiBlockDefinition == null) return; MyCubeBuilder.BuildComponent.GetMultiBlockPlacementMaterials(multiBlockDefinition); MyCubeBuilder.BuildComponent.AfterSuccessfulBuild(builder, instantBuild: false); }
public virtual bool IsMemoryTargetValid(MyBBMemoryTarget targetMemory) { if (targetMemory != null) { switch (targetMemory.TargetType) { case MyAiTargetEnum.GRID: case MyAiTargetEnum.ENTITY: { VRage.Game.Entity.MyEntity entity = null; return(Sandbox.Game.Entities.MyEntities.TryGetEntityById(targetMemory.EntityId.Value, out entity, false) && this.IsEntityReachable(entity)); } case MyAiTargetEnum.CUBE: case MyAiTargetEnum.COMPOUND_BLOCK: { MyCubeGrid grid = null; if (!Sandbox.Game.Entities.MyEntities.TryGetEntityById <MyCubeGrid>(targetMemory.EntityId.Value, out grid, false)) { return(false); } MySlimBlock cubeBlock = grid.GetCubeBlock(targetMemory.BlockPosition); return((cubeBlock != null) ? ((cubeBlock.FatBlock == null) ? this.IsEntityReachable(grid) : this.IsEntityReachable(cubeBlock.FatBlock)) : false); } case MyAiTargetEnum.CHARACTER: { MyCharacter character = null; return(Sandbox.Game.Entities.MyEntities.TryGetEntityById <MyCharacter>(targetMemory.EntityId.Value, out character, false) && this.IsEntityReachable(character)); } case MyAiTargetEnum.ENVIRONMENT_ITEM: case MyAiTargetEnum.VOXEL: return(true); } } return(false); }
public override bool GetIntersectionWithAABB(ref BoundingBoxD aabb) { base.Hierarchy.GetChildrenRecursive(this.m_children); using (HashSet <VRage.ModAPI.IMyEntity> .Enumerator enumerator = this.m_children.GetEnumerator()) { while (true) { if (!enumerator.MoveNext()) { break; } VRage.Game.Entity.MyEntity current = (VRage.Game.Entity.MyEntity)enumerator.Current; MyModel model2 = current.Model; if ((model2 != null) && model2.GetTrianglePruningStructure().GetIntersectionWithAABB(current, ref aabb)) { return(true); } } } MyModel model = base.Model; return((model != null) && model.GetTrianglePruningStructure().GetIntersectionWithAABB(this, ref aabb)); }
private DamageImpactEnum GetDamageFromHit(HkRigidBody collidingBody, MyEntity collidingEntity, ref HkContactPointEvent value) { if (collidingBody.LinearVelocity.Length() < MyPerGameSettings.CharacterDamageHitObjectMinVelocity) return DamageImpactEnum.NoDamage; if (collidingEntity == ManipulatedEntity) return DamageImpactEnum.NoDamage; if (collidingBody.HasProperty(HkCharacterRigidBody.MANIPULATED_OBJECT)) return DamageImpactEnum.NoDamage; var mass = (MyPerGameSettings.Destruction ? MyDestructionHelper.MassFromHavok(collidingBody.Mass) : collidingBody.Mass); if (mass < MyPerGameSettings.CharacterDamageHitObjectMinMass) return DamageImpactEnum.NoDamage; // Get the objects energies to calculate the damage - must be higher above treshold float objectEnergy = Math.Abs(value.SeparatingVelocity) * mass; if (objectEnergy > MyPerGameSettings.CharacterDamageHitObjectDeadlyEnergy) return DamageImpactEnum.DeadlyDamage; if (objectEnergy > MyPerGameSettings.CharacterDamageHitObjectCriticalEnergy) return DamageImpactEnum.CriticalDamage; if (objectEnergy > MyPerGameSettings.CharacterDamageHitObjectMediumEnergy) return DamageImpactEnum.MediumDamage; if (objectEnergy > MyPerGameSettings.CharacterDamageHitObjectSmallEnergy) return DamageImpactEnum.SmallDamage; return DamageImpactEnum.NoDamage; }
private DamageImpactEnum GetDamageFromFall(HkRigidBody collidingBody, MyEntity collidingEntity, ref HkContactPointEvent value) { //if (m_currentMovementState != MyCharacterMovementEnum.Falling || m_currentMovementState != MyCharacterMovementEnum.Jump) return DamageImpactEnum.NoDamage; //if (!collidingBody.IsFixed && collidingBody.Mass < Physics.Mass * 50) return DamageImpactEnum.NoDamage; float dotProd = Vector3.Dot(value.ContactPoint.Normal, Vector3.Normalize(Physics.HavokWorld.Gravity)); bool falledOnEntity = dotProd <= 0.0f; if (!falledOnEntity) return DamageImpactEnum.NoDamage; if (Math.Abs(value.SeparatingVelocity * dotProd) < MyPerGameSettings.CharacterDamageMinVelocity) return DamageImpactEnum.NoDamage; if (Math.Abs(value.SeparatingVelocity * dotProd) > MyPerGameSettings.CharacterDamageDeadlyDamageVelocity) return DamageImpactEnum.DeadlyDamage; if (Math.Abs(value.SeparatingVelocity * dotProd) > MyPerGameSettings.CharacterDamageMediumDamageVelocity) return DamageImpactEnum.MediumDamage; return DamageImpactEnum.SmallDamage; }
public virtual bool SetTargetFromMemory(MyBBMemoryTarget memoryTarget) { if (memoryTarget.TargetType == MyAiTargetEnum.POSITION) { if (memoryTarget.Position == null) { return(false); } this.SetTargetPosition(memoryTarget.Position.Value); return(true); } if (memoryTarget.TargetType == MyAiTargetEnum.ENVIRONMENT_ITEM) { if (memoryTarget.TreeId == null) { return(false); } MyEnvironmentItems.ItemInfo targetTree = new MyEnvironmentItems.ItemInfo { LocalId = memoryTarget.TreeId.Value, Transform = { Position = memoryTarget.Position.Value } }; this.SetTargetTree(ref targetTree, memoryTarget.EntityId.Value); return(true); } if (memoryTarget.TargetType == MyAiTargetEnum.NO_TARGET) { if (memoryTarget.TargetType == MyAiTargetEnum.NO_TARGET) { this.UnsetTarget(); return(true); } this.UnsetTarget(); return(false); } if (memoryTarget.EntityId == null) { return(false); } VRage.Game.Entity.MyEntity entity = null; if (!Sandbox.Game.Entities.MyEntities.TryGetEntityById(memoryTarget.EntityId.Value, out entity, false)) { this.UnsetTarget(); return(false); } if ((memoryTarget.TargetType == MyAiTargetEnum.CUBE) || (memoryTarget.TargetType == MyAiTargetEnum.COMPOUND_BLOCK)) { MySlimBlock cubeBlock = (entity as MyCubeGrid).GetCubeBlock(memoryTarget.BlockPosition); if (cubeBlock == null) { return(false); } if (memoryTarget.TargetType == MyAiTargetEnum.COMPOUND_BLOCK) { MySlimBlock block = (cubeBlock.FatBlock as MyCompoundCubeBlock).GetBlock(memoryTarget.CompoundId.Value); if (block == null) { return(false); } cubeBlock = block; this.m_compoundId = memoryTarget.CompoundId; } ushort?compoundId = null; this.SetTargetBlock(cubeBlock, compoundId); } else if (memoryTarget.TargetType == MyAiTargetEnum.ENTITY) { if ((memoryTarget.Position == null) || !(entity is MyFracturedPiece)) { this.SetMTargetPosition(entity.PositionComp.GetPosition()); } else { this.SetMTargetPosition(memoryTarget.Position.Value); } this.SetTargetEntity(entity); this.m_targetEntity = entity; } else if (memoryTarget.TargetType != MyAiTargetEnum.VOXEL) { this.SetTargetEntity(entity); } else { MyVoxelMap voxelMap = entity as MyVoxelMap; if (memoryTarget.Position == null) { return(false); } if (voxelMap == null) { return(false); } this.SetTargetVoxel(memoryTarget.Position.Value, voxelMap); this.m_targetEntity = voxelMap; } return(true); }
private void AddUnreachableTree(VRage.Game.Entity.MyEntity entity, int treeId, int timeout) { this.m_unreachableTrees[new Tuple <VRage.Game.Entity.MyEntity, int>(entity, treeId)] = MySandboxGame.TotalGamePlayTimeInMilliseconds + timeout; entity.OnClosing -= new Action <VRage.Game.Entity.MyEntity>(this.RemoveUnreachableTrees); entity.OnClosing += new Action <VRage.Game.Entity.MyEntity>(this.RemoveUnreachableTrees); }
public virtual bool EntityCanPaste(MyEntity pastingEntity) { if (m_copiedGrids.Count < 1) return false; if (MySession.Static.IsAdminModeEnabled(Sync.MyId)) { return true; } MyCubeBuilder.BuildComponent.GetGridSpawnMaterials(m_copiedGrids[0]); return MyCubeBuilder.BuildComponent.HasBuildingMaterials(pastingEntity); }
private void DisablePhysicsRecursively(MyEntity entity) { if (entity.Physics != null && entity.Physics.Enabled) entity.Physics.Enabled = false; var block = entity as MyCubeBlock; if (block != null && block.UseObjectsComponent.DetectorPhysics != null && block.UseObjectsComponent.DetectorPhysics.Enabled) block.UseObjectsComponent.DetectorPhysics.Enabled = false; if (block != null) block.NeedsUpdate = MyEntityUpdateEnum.NONE; foreach (var child in entity.Hierarchy.Children) DisablePhysicsRecursively(child.Container.Entity as MyEntity); }
void previewGrid_OnClose(MyEntity obj) { m_previewGrids.Remove(obj as MyCubeGrid); if (m_previewGrids.Count == 0) { //TODO: show some notification that the paste failed // Deactivation commented out because during clipboard moving grid can be hidden (it is closed, see Hide) and deactivation is not wanted. //Deactivate(); } }
bool GetPropertiesFromEntity(MyEntity entity,ref Vector3D position1, out Quaternion rotation2, out Vector3 posDiff, out HkShape? shape2) { rotation2 = new Quaternion(); posDiff = Vector3.Zero; shape2 = null; if (entity.Physics == null || !entity.Physics.Enabled) { return false; } if (entity.Physics.RigidBody != null) { shape2 = entity.Physics.RigidBody.GetShape(); var worldMatrix = entity.WorldMatrix; rotation2 = Quaternion.CreateFromForwardUp(worldMatrix.Forward, worldMatrix.Up); posDiff = entity.PositionComp.GetPosition() - position1; if (entity is MyVoxelBase) { var voxel = entity as MyVoxelBase; posDiff -= voxel.Size / 2; } } else if (entity.GetPhysicsBody().CharacterProxy != null) { shape2 = entity.GetPhysicsBody().CharacterProxy.GetShape(); var worldMatrix = entity.WorldMatrix; rotation2 = Quaternion.CreateFromForwardUp(worldMatrix.Forward, worldMatrix.Up); posDiff = entity.PositionComp.GetPosition() - position1; } else { return false; } return true; }
void gunEntity_OnClose(MyEntity obj) { if (m_currentWeapon == obj) m_currentWeapon = null; }
private void EquipWeapon(IMyHandheldGunObject<MyDeviceBase> newWeapon, bool showNotification = false) { // Debug.Assert(newWeapon != null); if (newWeapon == null) return; MyEntity gunEntity = (MyEntity)newWeapon; gunEntity.Render.CastShadows = true; gunEntity.Render.NeedsResolveCastShadow = false; gunEntity.Save = false; gunEntity.OnClose += gunEntity_OnClose; MyEntities.Add(gunEntity); m_handItemDefinition = null; m_currentWeapon = newWeapon; m_currentWeapon.OnControlAcquired(this); UseAnimationForWeapon |= m_currentWeapon.ForceAnimationInsteadOfIK; if (WeaponEquiped != null) WeaponEquiped(m_currentWeapon); MyAnalyticsHelper.ReportActivityStart(this, "item_equip", "character", "toolbar_item_usage", m_currentWeapon.GetType().Name); // CH:TODO: The hand item definitions should be changed to handheld gun object definitions and should be taken according to m_currentWeapon typeId if (m_currentWeapon.PhysicalObject != null) { var handItemId = m_currentWeapon.PhysicalObject.GetId(); m_handItemDefinition = MyDefinitionManager.Static.TryGetHandItemForPhysicalItem(handItemId); System.Diagnostics.Debug.Assert(m_handItemDefinition != null, "Create definition for this hand item!"); } else if (m_currentWeapon.DefinitionId.TypeId == typeof(MyObjectBuilder_CubePlacer)) { var gunID = new MyDefinitionId(typeof(MyObjectBuilder_CubePlacer)); m_handItemDefinition = MyDefinitionManager.Static.TryGetHandItemDefinition(ref gunID); System.Diagnostics.Debug.Assert(m_handItemDefinition != null, "Create definition for this hand item!"); } //Setup correct worldmatrix to weapon //CalculateDependentMatrices(); if (m_handItemDefinition != null && !string.IsNullOrEmpty(m_handItemDefinition.FingersAnimation)) { string animationSubtype; if (!m_characterDefinition.AnimationNameToSubtypeName.TryGetValue(m_handItemDefinition.FingersAnimation, out animationSubtype)) { animationSubtype = m_handItemDefinition.FingersAnimation; } var def = MyDefinitionManager.Static.TryGetAnimationDefinition(animationSubtype); if (!def.LeftHandItem.TypeId.IsNull) { m_currentWeapon.OnControlReleased(); (m_currentWeapon as MyEntity).Close(); //no dual wielding now m_currentWeapon = null; } PlayCharacterAnimation(m_handItemDefinition.FingersAnimation, MyBlendOption.Immediate, def.Loop ? MyFrameOption.Loop : MyFrameOption.PlayOnce, 1.0f, 1, false, null); if (UseNewAnimationSystem) { TriggerCharacterAnimationEvent("equip_left_tool", true); TriggerCharacterAnimationEvent("equip_right_tool", true); TriggerCharacterAnimationEvent(m_handItemDefinition.Id.SubtypeName.ToLower(), true); TriggerCharacterAnimationEvent(m_handItemDefinition.FingersAnimation.ToLower(), true); } if (!def.LeftHandItem.TypeId.IsNull) { if (m_leftHandItem != null) { (m_leftHandItem as IMyHandheldGunObject<Sandbox.Game.Weapons.MyDeviceBase>).OnControlReleased(); m_leftHandItem.Close(); } // CH: TODO: The entity id is not synced, but it never was in this place. It should be fixed later long handItemId = MyEntityIdentifier.AllocateId(); uint? inventoryItemId = null; var builder = GetObjectBuilderForWeapon(def.LeftHandItem, ref inventoryItemId, handItemId); var leftHandItem = CreateGun(builder, inventoryItemId); if (leftHandItem != null) { m_leftHandItem = leftHandItem as MyEntity; leftHandItem.OnControlAcquired(this); UpdateLeftHandItemPosition(); MyEntities.Add(m_leftHandItem); } } } else if (m_handItemDefinition != null) { if (UseNewAnimationSystem) { TriggerCharacterAnimationEvent("equip_left_tool", true); TriggerCharacterAnimationEvent("equip_right_tool", true); TriggerCharacterAnimationEvent(m_handItemDefinition.Id.SubtypeName.ToLower(), true); } } else { StopFingersAnimation(0); } var consumer = gunEntity.Components.Get<MyResourceSinkComponent>(); if (consumer != null && SuitRechargeDistributor != null) SuitRechargeDistributor.AddSink(consumer); if (showNotification) { var notificationUse = new MyHudNotification(MySpaceTexts.NotificationUsingWeaponType, 2000); notificationUse.SetTextFormatArguments(MyDeviceBase.GetGunNotificationName(newWeapon.DefinitionId)); MyHud.Notifications.Add(notificationUse); } Static_CameraAttachedToChanged(null, null); if (!(IsUsing is MyCockpit)) MyHud.Crosshair.ResetToDefault(clear: false); }
protected void cubeGrid_OnPhysicsChanged(MyEntity obj) { cubeGrid_OnPhysicsChanged(); if (Sync.IsServer) { m_topAndBottomSamePhysicsBody.Value = false; if (m_welded == false && m_isWelding == false) { Reattach(); } } }
private DamageImpactEnum GetDamageFromSqueeze(HkRigidBody collidingBody, MyEntity collidingEntity, ref HkContactPointEvent value) { if (collidingBody.IsFixed || collidingBody.Mass < MyPerGameSettings.CharacterSqueezeMinMass) return DamageImpactEnum.NoDamage; if (value.ContactProperties.IsNew) return DamageImpactEnum.NoDamage; // the object has to be moving towards the character even slowly and that also the character is not moving away from it Vector3 direction = Physics.CharacterProxy.GetHitRigidBody().Position - collidingBody.Position; Vector3 gravity = MyGravityProviderSystem.CalculateTotalGravityInPoint(PositionComp.WorldAABB.Center) + Physics.HavokWorld.Gravity; direction.Normalize(); gravity.Normalize(); float resultToPlayer = Vector3.Dot(direction, gravity); if (resultToPlayer < 0.5f) return DamageImpactEnum.NoDamage; if (m_squeezeDamageTimer > 0) { m_squeezeDamageTimer -= VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS; return DamageImpactEnum.NoDamage; } m_squeezeDamageTimer = MyPerGameSettings.CharacterSqueezeDamageDelay; if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW && MyDebugDrawSettings.DEBUG_DRAW_SHOW_DAMAGE) { MatrixD worldMatrix = collidingEntity.Physics.GetWorldMatrix(); int index = 2; MyPhysicsDebugDraw.DrawCollisionShape(collidingBody.GetShape(), worldMatrix, 1, ref index); VRageRender.MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, "SQUEEZE, MASS:" + collidingBody.Mass, Color.Yellow, 2, false); } if (collidingBody.Mass > MyPerGameSettings.CharacterSqueezeDeadlyDamageMass) return DamageImpactEnum.DeadlyDamage; if (collidingBody.Mass > MyPerGameSettings.CharacterSqueezeCriticalDamageMass) return DamageImpactEnum.CriticalDamage; if (collidingBody.Mass > MyPerGameSettings.CharacterSqueezeMediumDamageMass) return DamageImpactEnum.MediumDamage; return DamageImpactEnum.SmallDamage; }
private unsafe void RasterSectorsForCollision(MyEntity entity) { if (!(entity is MyCubeGrid)) return; BoundingBoxD range = entity.PositionComp.WorldAABB; range.Inflate(8); range.Translate(-PlanetTranslation); Vector2I top = new Vector2I(1 << m_clipmaps[0].Depth) - 1; Vector3D* pos = stackalloc Vector3D[8]; range.GetCornersUnsafe(pos); // bitmask for faces, 7th bit is simple bit int markedFaces = 0; int firstFace = 0; for (var i = 0; i < 8; ++i) { Vector3D copy = pos[i]; int index = MyPlanetCubemapHelper.FindCubeFace(ref copy); firstFace = index; index = 1 << index; if ((markedFaces & ~index) != 0) markedFaces |= 0x40; markedFaces |= index; } // This way we can ensure a single code path. int startFace = 0; int endFace = 5; // If we only encounter one face we narrow it down. if ((markedFaces & 0x40) == 0) { startFace = endFace = firstFace; } for (int face = startFace; face <= endFace; ++face) { if (((1 << face) & markedFaces) == 0) continue; // Offset var offset = 1 << m_clipmaps[face].Depth - 1; BoundingBox2D bounds = BoundingBox2D.CreateInvalid(); for (int i = 0; i < 8; ++i) { Vector3D copy = pos[i]; Vector2D normCoords; MyPlanetCubemapHelper.ProjectForFace(ref copy, face, out normCoords); bounds.Include(normCoords); } bounds.Min += 1; bounds.Min *= offset; bounds.Max += 1; bounds.Max *= offset; // Calculate bounds in sectors. var start = new Vector2I((int)bounds.Min.X, (int)bounds.Min.Y); var end = new Vector2I((int)bounds.Max.X, (int)bounds.Max.Y); Vector2I.Max(ref start, ref Vector2I.Zero, out start); Vector2I.Min(ref end, ref top, out end); for (int x = start.X; x <= end.X; ++x) for (int y = start.Y; y <= end.Y; ++y) { long sect = MyPlanetSectorId.MakeSectorId(x, y, face); List<MyOrientedBoundingBoxD> boxes; if (!m_obstructorsPerSector.TryGetValue(sect, out boxes)) { boxes = new List<MyOrientedBoundingBoxD>(); m_obstructorsPerSector.Add(sect, boxes); } var bb = entity.PositionComp.LocalAABB; bb.Inflate(8); // inflate by 8m to increase the likellyhood of overlap with trees' roots. boxes.Add(new MyOrientedBoundingBoxD((BoundingBoxD)bb, entity.PositionComp.WorldMatrix)); } } }
void inventory_OnContentsChanged(MyInventoryBase inventory) { if (this != MySession.Static.LocalCharacter) { return; } // Switch away from the weapon if we don't have it; Cube placer is an exception if (m_currentWeapon != null && WeaponTakesBuilderFromInventory(m_currentWeapon.DefinitionId) && inventory != null && inventory is MyInventory && !(inventory as MyInventory).ContainItems(1, m_currentWeapon.PhysicalObject)) SwitchToWeapon(null); // The same needs to be done with the m_leftHandItems, otherwise HandTorch if (LeftHandItem != null && !CanSwitchToWeapon(LeftHandItem.DefinitionId)) { LeftHandItem.OnControlReleased(); m_leftHandItem.Close(); m_leftHandItem = null; } }
private bool ShouldDetect(MyEntity entity) { if (entity == null) return false; if (entity == CubeGrid) return false; if (DetectPlayers) { if (entity is Character.MyCharacter) return ShouldDetectRelation((entity as Character.MyCharacter).GetRelationTo(OwnerId)); if (entity is MyGhostCharacter) return ShouldDetectRelation((entity as IMyControllableEntity).ControllerInfo.Controller.Player.GetRelationTo(OwnerId)); } if (DetectFloatingObjects) if (entity is MyFloatingObject) return true; var grid = entity as MyCubeGrid; //GR: if grids are logically connected(not physically causes issues with detecting ships with landing gears) return false (mostly for not detecting Piston and Rotor top parts) if ( grid != null && MyCubeGridGroups.Static.Logical.HasSameGroup(grid, CubeGrid) ) return false; if (DetectSmallShips) if (grid != null && grid.GridSizeEnum == MyCubeSize.Small) return ShouldDetectGrid(grid); if (DetectLargeShips) if (grid != null && grid.GridSizeEnum == MyCubeSize.Large && !grid.IsStatic) return ShouldDetectGrid(grid); if (DetectStations) if (grid != null && grid.GridSizeEnum == MyCubeSize.Large && grid.IsStatic) return ShouldDetectGrid(grid); if (DetectAsteroids) if (entity is MyVoxelBase) return true; return false; }
// This is real initialization of this class!!! Instead of constructor. public virtual void Init(StringBuilder displayName, string model, MyEntity parentObject, float? scale, string modelCollision = null) { ProfilerShort.Begin("MyEntity.Init(...models...)"); MarkedForClose = false; Closed = false; this.Render.PersistentFlags = MyPersistentEntityFlags2.CastShadows; this.DisplayName = displayName != null ? displayName.ToString() : null; RefreshModels(model, modelCollision); if (parentObject != null) { parentObject.Hierarchy.AddChild(this, false, false); } PositionComp.Scale = scale; AllocateEntityID(); ProfilerShort.End(); }
private void CloseInternal() { if (m_currentWeapon != null) { ((MyEntity)m_currentWeapon).Close(); m_currentWeapon = null; } if (m_leftHandItem != null) { m_leftHandItem.Close(); m_leftHandItem = null; } RemoveNotifications(); RadioBroadcaster.Enabled = false; if (MyToolbarComponent.CharacterToolbar != null) MyToolbarComponent.CharacterToolbar.ItemChanged -= Toolbar_ItemChanged; }
public void UnequipWeapon() { if (m_leftHandItem != null && m_leftHandItem is IMyHandheldGunObject<MyDeviceBase>) { (m_leftHandItem as IMyHandheldGunObject<MyDeviceBase>).OnControlReleased(); m_leftHandItem.Close(); // no dual wielding now m_leftHandItem = null; TriggerCharacterAnimationEvent("unequip_left_tool", true); } if (m_currentWeapon != null) { var weaponEntity = m_currentWeapon as MyEntity; SaveAmmoToWeapon(); m_currentWeapon.OnControlReleased(); var weaponSink = weaponEntity.Components.Get<MyResourceSinkComponent>(); if (weaponSink != null) SuitRechargeDistributor.RemoveSink(weaponSink); weaponEntity.OnClose -= gunEntity_OnClose; MyEntities.Remove(weaponEntity); weaponEntity.Close(); var useAnimationInsteadOfIK = MyPerGameSettings.CheckUseAnimationInsteadOfIK(m_currentWeapon); m_currentWeapon = null; if (ControllerInfo.IsLocallyHumanControlled() && MySector.MainCamera != null) { MySector.MainCamera.Zoom.ResetZoom(); } if (useAnimationInsteadOfIK) { StopUpperAnimation(0.2f); SwitchAnimation(m_currentMovementState, false); } TriggerCharacterAnimationEvent("unequip_left_tool", true); TriggerCharacterAnimationEvent("unequip_right_tool", true); MyAnalyticsHelper.ReportActivityEnd(this, "item_equip"); } if (m_currentShotTime <= 0) { //Otherwise all upper players keep updating StopUpperAnimation(0); StopFingersAnimation(0); } //MyHud.Crosshair.Hide(); m_currentWeapon = null; StopFingersAnimation(0); }
private void SetTransparencyForSubparts(MyEntity renderEntity, float transparency) { if (renderEntity.Subparts == null) return; foreach (var subpart in renderEntity.Subparts) { subpart.Value.Render.Transparency = transparency; subpart.Value.Render.RemoveRenderObjects(); subpart.Value.Render.AddRenderObjects(); SetTransparencyForSubparts(subpart.Value, transparency); } }