void CreateBreakableShapeFromCollisionShapes(MyModel model, Vector3 defaultSize, MyPhysicalModelDefinition modelDef) { // Make box half edge length of the grid so fractured block is smaller than not fractured, also good for compounds HkShape shape; if (model.HavokCollisionShapes != null && model.HavokCollisionShapes.Length > 0) { if (model.HavokCollisionShapes.Length > 1) { shape = HkListShape.Create(model.HavokCollisionShapes, model.HavokCollisionShapes.Length, HkReferencePolicy.None); } else { shape = model.HavokCollisionShapes[0]; shape.AddReference(); } } else { //modelDef.Size * (modelDef.CubeSize == MyCubeSize.Large ? 2.5f : 0.25f) shape = new HkBoxShape(defaultSize * 0.5f, MyPerGameSettings.PhysicsConvexRadius); } var boxBreakable = new HkdBreakableShape(shape); boxBreakable.Name = model.AssetName; boxBreakable.SetMass(modelDef.Mass); model.HavokBreakableShapes = new HkdBreakableShape[] { boxBreakable }; shape.RemoveReference(); }
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; }
public void GetFracturesInBox(ref BoundingBoxD searchBox, List <MyFracturedPiece> output) { var activeFractures = m_piecesTimesOfDeath.Keys; Debug.Assert(m_rigidList.Count == 0); m_rigidList.Clear(); HkShape shape = new HkBoxShape(searchBox.HalfExtents); try { var center = searchBox.Center; MyPhysics.GetPenetrationsShape(shape, ref center, ref Quaternion.Identity, m_rigidList, MyPhysics.NotCollideWithStaticLayer); foreach (var rigidBody in m_rigidList) { var fracture = rigidBody.GetCollisionEntity() as MyFracturedPiece; if (fracture != null && m_piecesTimesOfDeath.ContainsKey(fracture)) { output.Add(fracture); } } } finally { m_rigidList.Clear(); shape.RemoveReference(); } }
private HkBvShape CreateFieldShape(Vector3 extents) { var phantom = new HkPhantomCallbackShape(phantom_Enter, phantom_Leave); var detectorShape = new HkBoxShape(extents); return(new HkBvShape(detectorShape, phantom, HkReferencePolicy.TakeOwnership)); }
public virtual void CreatePhysicsShape(out HkShape shape, out HkMassProperties massProperties, float mass) { HkBoxShape shape2 = new HkBoxShape(((((MyEntity)base.Entity).Render.GetModel().BoundingBox.Max - ((MyEntity)base.Entity).Render.GetModel().BoundingBox.Min) / 2f) * base.Entity.PositionComp.Scale.Value); Vector3 translation = (((MyEntity)base.Entity).Render.GetModel().BoundingBox.Max + ((MyEntity)base.Entity).Render.GetModel().BoundingBox.Min) / 2f; shape = (HkShape) new HkTransformShape((HkShape)shape2, ref translation, ref Quaternion.Identity); massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(shape2.HalfExtents, mass); massProperties.CenterOfMass = translation; }
public virtual void CreatePhysicsShape(out HkShape shape, ref HkMassProperties massProperties) { var boxShape = new HkBoxShape(((((MyEntity)Entity).Render.GetModel().BoundingBox.Max - ((MyEntity)Entity).Render.GetModel().BoundingBox.Min) / 2) * Entity.PositionComp.Scale.Value); var pos = ((((MyEntity)Entity).Render.GetModel().BoundingBox.Max + ((MyEntity)Entity).Render.GetModel().BoundingBox.Min) / 2); shape = new HkTransformShape(boxShape, ref pos, ref Quaternion.Identity); //shape = boxShape; massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(boxShape.HalfExtents, boxShape.HalfExtents.Volume * 0.5f); massProperties.CenterOfMass = pos; }
public virtual void CreatePhysicsShape(out HkShape shape, ref HkMassProperties massProperties) { var boxShape = new HkBoxShape(((((MyEntity)Entity).Render.GetModel().BoundingBox.Max - ((MyEntity)Entity).Render.GetModel().BoundingBox.Min) / 2) * Entity.PositionComp.Scale.Value); var pos = ((((MyEntity)Entity).Render.GetModel().BoundingBox.Max + ((MyEntity)Entity).Render.GetModel().BoundingBox.Min) / 2); shape = new HkTransformShape(boxShape, ref pos, ref Quaternion.Identity); //shape = boxShape; massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(boxShape.HalfExtents, boxShape.HalfExtents.Volume * 0.5f); massProperties.CenterOfMass = pos; }
private void AddBox(Vector3I minPos, Vector3I maxPos, ref Vector3 min, ref Vector3 max) { Vector3 translation = (min + max) * 0.5f; HkBoxShape shape = new HkBoxShape((max - translation) - 0f, MyPerGameSettings.PhysicsConvexRadius); HkConvexTranslateShape shape2 = new HkConvexTranslateShape((HkConvexShape)shape, translation, HkReferencePolicy.TakeOwnership); this.Shapes.Add((HkShape)shape2); ShapeInfo item = new ShapeInfo { Count = 1, Min = minPos, Max = maxPos }; this.ShapeInfos.Add(item); }
private void AddBox(Vector3I minPos, Vector3I maxPos, ref Vector3 min, ref Vector3 max) { Vector3 center = (min + max) / 2.0f; Vector3 halfExtent = max - center; halfExtent -= BOX_SHRINK; HkBoxShape boxShape = new HkBoxShape(halfExtent, MyPerGameSettings.PhysicsConvexRadius); var shape = new HkConvexTranslateShape(boxShape, center, HkReferencePolicy.TakeOwnership); Shapes.Add(shape); ShapeInfos.Add(new ShapeInfo() { Count = 1, Min = minPos, Max = maxPos }); }
internal static void InitBoxPhysics(this IMyEntity entity, Matrix worldMatrix, MyStringHash materialType, Vector3 center, Vector3 size, float mass, float linearDamping, float angularDamping, ushort collisionLayer, RigidBodyFlag rbFlag) { float single1 = mass; mass = ((rbFlag & RigidBodyFlag.RBF_STATIC) != RigidBodyFlag.RBF_DEFAULT) ? 0f : single1; HkMassProperties properties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(size / 2f, mass); MyPhysicsBody body1 = new MyPhysicsBody(null, rbFlag); body1.MaterialType = materialType; body1.AngularDamping = angularDamping; body1.LinearDamping = linearDamping; MyPhysicsBody body = body1; HkBoxShape shape = new HkBoxShape(size * 0.5f); body.CreateFromCollisionObject((HkShape)shape, center, worldMatrix, new HkMassProperties?(properties), 15); shape.Base.RemoveReference(); entity.Physics = body; }
public static void InitBoxPhysics(this IMyEntity entity, MyStringHash materialType, Vector3 center, Vector3 size, float mass, float linearDamping, float angularDamping, ushort collisionLayer, RigidBodyFlag rbFlag) { System.Diagnostics.Debug.Assert(size.Length() > 0); mass = (rbFlag & RigidBodyFlag.RBF_STATIC) != 0 ? 0 : mass; var massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(size / 2, mass); var physics = new Sandbox.Engine.Physics.MyPhysicsBody(entity, rbFlag) { MaterialType = materialType, AngularDamping = angularDamping, LinearDamping = linearDamping }; HkBoxShape shape = new HkBoxShape(size * 0.5f); physics.CreateFromCollisionObject((HkShape)shape, center, entity.PositionComp.WorldMatrix, massProperties); shape.Base.RemoveReference(); entity.Physics = physics; }
private void InitInternal() { float?scale = null; base.Init(null, this.m_definition.Model, null, scale, null); base.Render.ColorMaskHsv = this.m_definition.ColorHSV; base.Render.Transparency = 0.25f; base.Render.AddRenderObjects(); MyRenderProxy.ChangeMaterialTexture(base.Render.RenderObjectIDs[0], "BotFlag", this.m_definition.ColorMetalTexture, null, this.m_definition.AddMapsTexture, null); this.m_localActivationMatrix = MatrixD.CreateScale(base.PositionComp.LocalAABB.HalfExtents * 2f) * MatrixD.CreateTranslation(base.PositionComp.LocalAABB.Center); HkBoxShape shape = new HkBoxShape((Vector3)this.m_localActivationMatrix.Scale); MyPhysicsBody body = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE); base.Physics = body; HkMassProperties?massProperties = null; body.CreateFromCollisionObject((HkShape)shape, Vector3.Zero, base.WorldMatrix, massProperties, 0x18); body.Enabled = true; base.Components.Add <MyPlaceArea>(new MySpherePlaceArea(10f, this.m_definition.Id.SubtypeId)); this.AddHudMarker(); }
internal static void InitBoxPhysics(this IMyEntity entity, Matrix worldMatrix, MyStringHash materialType, Vector3 center, Vector3 size, float mass, float linearDamping, float angularDamping, ushort collisionLayer, RigidBodyFlag rbFlag) { mass = (rbFlag & RigidBodyFlag.RBF_STATIC) != 0 ? 0 : mass; var massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(size / 2, mass); var physicsBody = new Sandbox.Engine.Physics.MyPhysicsBody(null, rbFlag) { MaterialType = materialType, AngularDamping = angularDamping, LinearDamping = linearDamping }; //BoxShape shape = new BoxShape(size * 0.5f); HkBoxShape shape = new HkBoxShape(size * 0.5f); physicsBody.CreateFromCollisionObject((HkShape)shape, center, worldMatrix, massProperties); shape.Base.RemoveReference(); entity.Physics = physicsBody; //return physicsBody; }
public static void InitBoxPhysics(this IMyEntity entity, MyStringHash materialType, Vector3 center, Vector3 size, float mass, float linearDamping, float angularDamping, ushort collisionLayer, RigidBodyFlag rbFlag) { System.Diagnostics.Debug.Assert(size.Length() > 0); mass = (rbFlag & RigidBodyFlag.RBF_STATIC) != 0 ? 0 : mass; var massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(size / 2, mass); var physics = new Sandbox.Engine.Physics.MyPhysicsBody(entity, rbFlag) { MaterialType = materialType, AngularDamping = angularDamping, LinearDamping = linearDamping }; HkBoxShape shape = new HkBoxShape(size * 0.5f); physics.CreateFromCollisionObject((HkShape)shape, center, entity.PositionComp.WorldMatrix, massProperties); shape.Base.RemoveReference(); entity.Physics = physics; }
internal static void InitBoxPhysics(this IMyEntity entity, Matrix worldMatrix, MyStringHash materialType, Vector3 center, Vector3 size, float mass, float linearDamping, float angularDamping, ushort collisionLayer, RigidBodyFlag rbFlag) { mass = (rbFlag & RigidBodyFlag.RBF_STATIC) != 0 ? 0 : mass; var massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(size / 2, mass); var physicsBody = new Sandbox.Engine.Physics.MyPhysicsBody(null, rbFlag) { MaterialType = materialType, AngularDamping = angularDamping, LinearDamping = linearDamping }; //BoxShape shape = new BoxShape(size * 0.5f); HkBoxShape shape = new HkBoxShape(size * 0.5f); physicsBody.CreateFromCollisionObject((HkShape)shape, center, worldMatrix, massProperties); shape.Base.RemoveReference(); entity.Physics = physicsBody; //return physicsBody; }
private void InitInternal() { base.Init(null, m_definition.Model, null, null); Render.ColorMaskHsv = m_definition.ColorHSV; Render.Transparency = 0.25f; Render.AddRenderObjects(); List <MyTextureChange> textureChanges = new List <MyTextureChange>(); textureChanges.Add(new MyTextureChange { TextureName = m_definition.ColorMetalTexture, MaterialSlot = "ColorMetalTexture" }); textureChanges.Add(new MyTextureChange { TextureName = m_definition.AddMapsTexture, MaterialSlot = "AddMapsTexture" }); VRageRender.MyRenderProxy.ChangeMaterialTexture(Render.RenderObjectIDs[0], "BotFlag", textureChanges); // TODO: change the material name m_localActivationMatrix = MatrixD.CreateScale(this.PositionComp.LocalAABB.HalfExtents * 2.0f) * MatrixD.CreateTranslation(this.PositionComp.LocalAABB.Center); var shape = new HkBoxShape(m_localActivationMatrix.Scale); Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE); Physics.CreateFromCollisionObject(shape, Vector3.Zero, WorldMatrix, null, MyPhysics.ObjectDetectionCollisionLayer); Physics.Enabled = true; Components.Add <MyPlaceArea>(new MySpherePlaceArea(10.0f, m_definition.Id.SubtypeId)); // TODO: Add radius to the definition MyHud.LocationMarkers.RegisterMarker(this, new MyHudEntityParams() { FlagsEnum = MyHudIndicatorFlagsEnum.SHOW_TEXT, Text = m_definition.DisplayNameEnum.HasValue ? MyTexts.Get(m_definition.DisplayNameEnum.Value) : new StringBuilder(), TargetMode = MyRelationsBetweenPlayerAndBlock.Neutral, MaxDistance = 200.0f, MustBeDirectlyVisible = true }); }
private void InitInternal() { base.Init(null, m_definition.Model, null, null); Render.ColorMaskHsv = m_definition.ColorHSV; Render.Transparency = 0.25f; Render.AddRenderObjects(); List<MyTextureChange> textureChanges = new List<MyTextureChange>(); textureChanges.Add(new MyTextureChange { TextureName = m_definition.ColorMetalTexture, MaterialSlot = "ColorMetalTexture" }); textureChanges.Add(new MyTextureChange { TextureName = m_definition.AddMapsTexture, MaterialSlot = "AddMapsTexture" }); VRageRender.MyRenderProxy.ChangeMaterialTexture(Render.RenderObjectIDs[0], "BotFlag", textureChanges); // TODO: change the material name m_localActivationMatrix = MatrixD.CreateScale(this.PositionComp.LocalAABB.HalfExtents * 2.0f) * MatrixD.CreateTranslation(this.PositionComp.LocalAABB.Center); var shape = new HkBoxShape(m_localActivationMatrix.Scale); Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE); Physics.CreateFromCollisionObject(shape, Vector3.Zero, WorldMatrix, null, MyPhysics.ObjectDetectionCollisionLayer); Physics.Enabled = true; Components.Add<MyPlaceArea>(new MySpherePlaceArea(10.0f, m_definition.Id.SubtypeId)); // TODO: Add radius to the definition AddHudMarker(); }
private void InitInternal() { base.Init(null, m_definition.Model, null, null); Render.ColorMaskHsv = m_definition.ColorHSV; Render.Transparency = 0.25f; Render.AddRenderObjects(); List<MyTextureChange> textureChanges = new List<MyTextureChange>(); textureChanges.Add(new MyTextureChange { TextureName = m_definition.ColorMetalTexture, MaterialSlot = "ColorMetalTexture" }); textureChanges.Add(new MyTextureChange { TextureName = m_definition.AddMapsTexture, MaterialSlot = "AddMapsTexture" }); VRageRender.MyRenderProxy.ChangeMaterialTexture(Render.RenderObjectIDs[0], "BotFlag", textureChanges); // TODO: change the material name m_localActivationMatrix = MatrixD.CreateScale(this.PositionComp.LocalAABB.HalfExtents * 2.0f) * MatrixD.CreateTranslation(this.PositionComp.LocalAABB.Center); var shape = new HkBoxShape(m_localActivationMatrix.Scale); var physicsBody = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE); Physics = physicsBody; physicsBody.CreateFromCollisionObject(shape, Vector3.Zero, WorldMatrix, null, MyPhysics.CollisionLayers.ObjectDetectionCollisionLayer); physicsBody.Enabled = true; Components.Add<MyPlaceArea>(new MySpherePlaceArea(10.0f, m_definition.Id.SubtypeId)); // TODO: Add radius to the definition AddHudMarker(); }
private void InitDeadBodyPhysics() { Vector3 velocity = Vector3.Zero; RadioBroadcaster.BroadcastRadius = 5; if (Physics != null) { velocity = Physics.LinearVelocity; Physics.Enabled = false; Physics.Close(); Physics = null; } //if (Physics == null) { var massProperties = new HkMassProperties(); massProperties.Mass = 500; HkShape shape; // CH: Need to rethink this. It does not belong here, but I don't want to add "DeadCharacterBodyCenterOfMass" to the character definition either... // MZ: See ticket "Correct dying for characters", https://app.asana.com/0/64822442925263/75411538582998 // dead body shape can now be specified in character's SBC if (Definition.DeadBodyShape != null) { HkBoxShape bshape = new HkBoxShape(PositionComp.LocalAABB.HalfExtents * Definition.DeadBodyShape.BoxShapeScale); massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(bshape.HalfExtents, massProperties.Mass); massProperties.CenterOfMass = bshape.HalfExtents * Definition.DeadBodyShape.RelativeCenterOfMass; shape = bshape; Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEFAULT); Vector3D offset = PositionComp.LocalAABB.HalfExtents * Definition.DeadBodyShape.RelativeShapeTranslation; MatrixD pos = MatrixD.CreateTranslation(offset); Physics.CreateFromCollisionObject(shape, PositionComp.LocalVolume.Center + offset, pos, massProperties, MyPhysics.CollisionLayers.FloatingObjectCollisionLayer); Physics.Friction = Definition.DeadBodyShape.Friction; Physics.RigidBody.MaxAngularVelocity = MathHelper.PiOver2; Physics.LinearVelocity = velocity; shape.RemoveReference(); Physics.Enabled = true; } else // no special definition => use AABB { HkBoxShape bshape = new HkBoxShape(PositionComp.LocalAABB.HalfExtents); massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(bshape.HalfExtents, massProperties.Mass); massProperties.CenterOfMass = new Vector3(bshape.HalfExtents.X, 0, 0); shape = bshape; Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEFAULT); Physics.CreateFromCollisionObject(shape, PositionComp.LocalVolume.Center, MatrixD.Identity, massProperties, MyPhysics.CollisionLayers.FloatingObjectCollisionLayer); Physics.Friction = 0.5f; Physics.RigidBody.MaxAngularVelocity = MathHelper.PiOver2; Physics.LinearVelocity = velocity; shape.RemoveReference(); Physics.Enabled = true; } } NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; }
/// <summary> /// Returns true if the given small block connects to large one. /// </summary> /// <param name="smallBlock">small block</param> /// <param name="smallBlockWorldAabb">small block world AABB</param> /// <param name="largeBlock">large block</param> /// <param name="largeBlockWorldAabb">large block wotld AABB</param> /// <returns>true when connected</returns> private bool SmallBlockConnectsToLarge(MySlimBlock smallBlock, ref BoundingBoxD smallBlockWorldAabb, MySlimBlock largeBlock, ref BoundingBoxD largeBlockWorldAabb) { Debug.Assert(smallBlock.BlockDefinition.CubeSize == MyCubeSize.Small); Debug.Assert(largeBlock.BlockDefinition.CubeSize == MyCubeSize.Large); Debug.Assert(!(smallBlock.FatBlock is MyCompoundCubeBlock)); Debug.Assert(!(largeBlock.FatBlock is MyCompoundCubeBlock)); BoundingBoxD smallBlockWorldAabbReduced = smallBlockWorldAabb; smallBlockWorldAabbReduced.Inflate(-smallBlock.CubeGrid.GridSize / 4); // Small block aabb penetrates large block aabb (large timbers). bool penetratesAabbs = largeBlockWorldAabb.Contains(smallBlockWorldAabbReduced) == ContainmentType.Intersects; if (!penetratesAabbs) { Vector3D centerToCenter = smallBlockWorldAabb.Center - largeBlockWorldAabb.Center; Vector3I addDir = Base6Directions.GetIntVector(Base6Directions.GetClosestDirection(centerToCenter)); // Check small grid mount points Quaternion smallBlockRotation; smallBlock.Orientation.GetQuaternion(out smallBlockRotation); smallBlockRotation = Quaternion.CreateFromRotationMatrix(smallBlock.CubeGrid.WorldMatrix) * smallBlockRotation; if (!MyCubeGrid.CheckConnectivitySmallBlockToLargeGrid(largeBlock.CubeGrid, smallBlock.BlockDefinition, ref smallBlockRotation, ref addDir)) { return(false); } } BoundingBoxD smallBlockWorldAabbInflated = smallBlockWorldAabb; smallBlockWorldAabbInflated.Inflate(2 * smallBlock.CubeGrid.GridSize / 3); // Trim small block aabb with large block aabb. BoundingBoxD intersectedBox = smallBlockWorldAabbInflated.Intersect(largeBlockWorldAabb); Vector3D intersectedBoxCenter = intersectedBox.Center; HkShape shape = new HkBoxShape((Vector3)intersectedBox.HalfExtents); Quaternion largeRotation; largeBlock.Orientation.GetQuaternion(out largeRotation); largeRotation = Quaternion.CreateFromRotationMatrix(largeBlock.CubeGrid.WorldMatrix) * largeRotation; Vector3D largeTranslation; largeBlock.ComputeWorldCenter(out largeTranslation); bool result = false; try { if (largeBlock.FatBlock != null) { MyModel model = largeBlock.FatBlock.Model; if (model != null) { HkShape[] shapes = model.HavokCollisionShapes; if (shapes == null || shapes.Length == 0) { return(false); } for (int i = 0; i < shapes.Length; ++i) { result = MyPhysics.IsPenetratingShapeShape(shape, ref intersectedBoxCenter, ref Quaternion.Identity, shapes[i], ref largeTranslation, ref largeRotation); if (result) { break; } } } else { HkShape shapeLarge = new HkBoxShape(largeBlock.BlockDefinition.Size * largeBlock.CubeGrid.GridSize / 2); result = MyPhysics.IsPenetratingShapeShape(shape, ref intersectedBoxCenter, ref Quaternion.Identity, shapeLarge, ref largeTranslation, ref largeRotation); shapeLarge.RemoveReference(); } } else { HkShape shapeLarge = new HkBoxShape(largeBlock.BlockDefinition.Size * largeBlock.CubeGrid.GridSize / 2); result = MyPhysics.IsPenetratingShapeShape(shape, ref intersectedBoxCenter, ref Quaternion.Identity, shapeLarge, ref largeTranslation, ref largeRotation); shapeLarge.RemoveReference(); } } finally { shape.RemoveReference(); } return(result); }
public MyCharacterProxy(bool isDynamic, bool isCapsule, float characterWidth, float characterHeight, float crouchHeight, float ladderHeight, float headSize, float headHeight, Vector3 position, Vector3 up, Vector3 forward, float mass, MyPhysicsBody body, bool isOnlyVertical, float maxSlope, float maxImpulse, float maxSpeedRelativeToShip, float?maxForce = new float?(), HkRagdoll ragDoll = null) { this.m_isDynamic = isDynamic; this.m_physicsBody = body; this.m_mass = mass; this.m_maxImpulse = maxImpulse; this.m_maxSpeedRelativeToShip = maxSpeedRelativeToShip; if (!isCapsule) { HkBoxShape shape = new HkBoxShape(new Vector3(characterWidth / 2f, characterHeight / 2f, characterWidth / 2f)); if (!this.m_isDynamic) { this.CharacterPhantom = new HkSimpleShapePhantom((HkShape)shape, 0x12); } this.m_characterShape = (HkShape)shape; } else { this.m_characterShape = CreateCharacterShape(characterHeight, characterWidth, characterHeight + headHeight, headSize, 0f, 0f, false); this.m_characterCollisionShape = CreateCharacterShape(characterHeight * 0.9f, characterWidth * 0.9f, (characterHeight * 0.9f) + headHeight, headSize * 0.9f, 0f, 0f, false); this.m_crouchShape = CreateCharacterShape(characterHeight, characterWidth, characterHeight + headHeight, headSize, 0f, 1f, false); if (!this.m_isDynamic) { this.CharacterPhantom = new HkSimpleShapePhantom(this.m_characterShape, 0x12); } } if (!this.m_isDynamic) { HkCharacterProxyCinfo characterProxyCinfo = new HkCharacterProxyCinfo { StaticFriction = 1f, DynamicFriction = 1f, ExtraDownStaticFriction = 1000f, MaxCharacterSpeedForSolver = 10000f, RefreshManifoldInCheckSupport = true, Up = up, Forward = forward, UserPlanes = 4, MaxSlope = MathHelper.ToRadians(maxSlope), Position = position, CharacterMass = mass, CharacterStrength = 100f, ShapePhantom = this.CharacterPhantom }; this.CharacterProxy = new HkCharacterProxy(characterProxyCinfo); characterProxyCinfo.Dispose(); } else { HkCharacterRigidBodyCinfo characterRigidBodyCinfo = new HkCharacterRigidBodyCinfo { Shape = this.m_characterShape, CrouchShape = this.m_crouchShape, Friction = 0f, MaxSlope = MathHelper.ToRadians(maxSlope), Up = up, Mass = mass, CollisionFilterInfo = 0x12, MaxLinearVelocity = 1000000f, MaxForce = (maxForce != null) ? maxForce.Value : 100000f, AllowedPenetrationDepth = MyFakes.ENABLE_LIMITED_CHARACTER_BODY ? 0.3f : 0.1f, JumpHeight = 0.8f }; float maxCharacterSpeed = MyGridPhysics.ShipMaxLinearVelocity() + this.m_maxSpeedRelativeToShip; this.CharacterRigidBody = new HkCharacterRigidBody(characterRigidBodyCinfo, maxCharacterSpeed, body); this.m_maxCharacterSpeedSq = maxCharacterSpeed * maxCharacterSpeed; this.CharacterRigidBody.GetRigidBody().ContactPointCallbackEnabled = true; this.CharacterRigidBody.GetRigidBody().ContactPointCallback -= new ContactPointEventHandler(this.RigidBody_ContactPointCallback); this.CharacterRigidBody.GetRigidBody().ContactPointCallback += new ContactPointEventHandler(this.RigidBody_ContactPointCallback); this.CharacterRigidBody.GetRigidBody().ContactPointCallbackDelay = 0; Matrix inertiaTensor = this.CharacterRigidBody.GetHitRigidBody().InertiaTensor; inertiaTensor.M11 = 1000f; inertiaTensor.M22 = 1000f; inertiaTensor.M33 = 1000f; this.CharacterRigidBody.GetHitRigidBody().InertiaTensor = inertiaTensor; characterRigidBodyCinfo.Dispose(); } }
public override bool HandleInput() { bool handled = false; if (m_gridDebugInfo) { LineD line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 1000); MyCubeGrid grid; Vector3I cubePos; double distance; if (MyCubeGrid.GetLineIntersection(ref line, out grid, out cubePos, out distance)) { var gridMatrix = grid.WorldMatrix; var boxMatrix = Matrix.CreateTranslation(cubePos * grid.GridSize) * gridMatrix; var block = grid.GetCubeBlock(cubePos); MyRenderProxy.DebugDrawText2D(new Vector2(), cubePos.ToString(), Color.White, 0.7f); MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(new Vector3(grid.GridSize) + new Vector3(0.15f)) * boxMatrix, Color.Red.ToVector3(), 0.2f, true, true); //int[, ,] bones = grid.Skeleton.AddCubeBones(cubePos); //Vector3 closestBone = Vector3.Zero; //Vector3I closestPoint = Vector3I.Zero; //float closestPointDist = float.MaxValue; //int closestBoneIndex = 0; //for (int x = -1; x <= 1; x += 1) //{ // for (int y = -1; y <= 1; y += 1) // { // for (int z = -1; z <= 1; z += 1) // { // int boneIndex = bones[x + 1, y + 1, z + 1]; // Vector3 bone = grid.Skeleton[boneIndex]; // var pos = boxMatrix.Translation + new Vector3(grid.GridSize / 2) * new Vector3(x, y, z); // //MyRenderProxy.DebugDrawSphere(pos, 0.2f, Color.Blue.ToVector3(), 1.0f, false); // MyRenderProxy.DebugDrawText3D(pos, String.Format("{0:G2}, {1:G2}, {2:G2}", bone.X, bone.Y, bone.Z), Color.White, 0.5f, false); // var dist = MyUtils.GetPointLineDistance(ref line, ref pos); // if (dist < closestPointDist) // { // closestPointDist = dist; // closestPoint = new Vector3I(x, y, z); // closestBoneIndex = boneIndex; // closestBone = bone; // } // } // } //} //MyRenderProxy.DebugDrawText3D(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f, String.Format("{0:G2}, {1:G2}, {2:G2}", closestBone.X, closestBone.Y, closestBone.Z), Color.Red, 0.5f, false); //var bonePos = grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]]; //MyRenderProxy.DebugDrawSphere(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f + bonePos, 0.5f, Color.Red.ToVector3(), 0.4f, true, true); //if (input.IsNewKeyPressed(Keys.P) && block != null) //{ // if (input.IsAnyShiftKeyPressed()) // { // grid.ResetBlockSkeleton(block); // } // else // { // grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]] = Vector3.Zero; // grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One); // //grid.SetBlockDirty(block); // } // handled = true; //} //// Move bones to center by 0.1f //if (input.IsNewKeyPressed(Keys.OemOpenBrackets)) //{ // int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]; // grid.Skeleton[index] -= Vector3.Sign(grid.Skeleton[index]) * 0.1f; // grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One); // //grid.SetBlockDirty(block); // handled = true; //} //// Reduce max offset by 0.1f //if (input.IsNewKeyPressed(Keys.OemCloseBrackets)) //{ // int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]; // var old = Vector3.Abs(grid.Skeleton[index]); // var max = new Vector3(Math.Max(Math.Max(old.X, old.Y), old.Z)); // if (max.X > 0.1f) // { // grid.Skeleton[index] = Vector3.Clamp(grid.Skeleton[index], -max + 0.1f, max - 0.1f); // } // else // { // grid.Skeleton[index] = Vector3.Zero; // } // grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One); // //grid.SetBlockDirty(block); // handled = true; //} } } if (MyInput.Static.IsAnyAltKeyPressed()) { return(handled); } bool shift = MyInput.Static.IsAnyShiftKeyPressed(); bool ctrl = MyInput.Static.IsAnyCtrlKeyPressed(); //if (input.IsNewKeyPressed(Keys.I)) //{ // foreach (var grid in MyEntities.GetEntities().OfType<MyCubeGrid>()) // { // foreach (var block in grid.GetBlocks().ToArray()) // { // grid.DetectMerge(block.Min, block.Max); // } // } // handled = true; //} // Disabled since it is common to have normal control bound to O key. // If you ever need this again, bind it to something more complicated, like key combination. //if (input.IsNewKeyPressed(Keys.O)) //{ // m_gridDebugInfo = !m_gridDebugInfo; // handled = true; //} //for (int i = 0; i <= 9; i++) //{ // if (MyInput.Static.IsNewKeyPressed((Keys)(((int)Keys.D0) + i))) // { // string name = "Slot" + i.ToString(); // if (ctrl) // { // MySession.Static.Name = name; // MySession.Static.WorldID = MySession.Static.GetNewWorldId(); // MySession.Static.Save(name); // } // else if (shift) // { // var path = MyLocalCache.GetSessionSavesPath(name, false, false); // if (System.IO.Directory.Exists(path)) // { // MySession.Static.Unload(); // MySession.Static.Load(path); // } // } // handled = true; // } //} //if (MyInput.Static.IsNewKeyPressed(Keys.End)) //{ // MyMeteorShower.MeteorWave(null); //} // Disabled for god sake! //if (MyInput.Static.IsNewKeyPressed(Keys.PageUp) && MyInput.Static.IsAnyCtrlKeyPressed()) //{ // MyReloadTestComponent.Enabled = true; //} //if (MyInput.Static.IsNewKeyPressed(Keys.PageDown) && MyInput.Static.IsAnyCtrlKeyPressed()) //{ // MyReloadTestComponent.Enabled = false; //} if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad6)) { var view = MySession.Static.CameraController.GetViewMatrix(); var inv = Matrix.Invert(view); //MyPhysicalInventoryItem item = new MyPhysicalInventoryItem(100, var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone"); var item = new MyPhysicalInventoryItem(1, oreBuilder); var obj = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * 1.0f, inv.Forward, inv.Up); obj.Physics.LinearVelocity = inv.Forward * 50; } if (false && MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9)) { List <HkShape> trShapes = new List <HkShape>(); List <HkConvexShape> shapes = new List <HkConvexShape>(); List <Matrix> matrices = new List <Matrix>(); var grid = new HkGridShape(2.5f, HkReferencePolicy.None); const short size = 50; for (short x = 0; x < size; x++) { for (short y = 0; y < size; y++) { for (short z = 0; z < size; z++) { var box = new HkBoxShape(Vector3.One); grid.AddShapes(new System.Collections.Generic.List <HkShape>() { box }, new Vector3S(x, y, z), new Vector3S(x, y, z)); trShapes.Add(new HkConvexTranslateShape(box, new Vector3(x, y, z), HkReferencePolicy.None)); shapes.Add(box); matrices.Add(Matrix.CreateTranslation(new Vector3(x, y, z))); } } } var emptyGeom = new HkGeometry(new List <Vector3>(), new List <int>()); var list = new HkListShape(trShapes.ToArray(), trShapes.Count, HkReferencePolicy.None); var compressedBv = new HkBvCompressedMeshShape(emptyGeom, shapes, matrices, HkWeldingType.None); var mopp = new HkMoppBvTreeShape(list, HkReferencePolicy.None); HkShapeBuffer buf = new HkShapeBuffer(); //HkShapeContainerIterator i = compressedBv.GetIterator(buf); //int count = 0; // will be 125000 //while (i.IsValid) //{ // count++; // i.Next(); //} buf.Dispose(); var info = new HkRigidBodyCinfo(); info.Mass = 10; info.CalculateBoxInertiaTensor(Vector3.One, 10); info.MotionType = HkMotionType.Dynamic; info.QualityType = HkCollidableQualityType.Moving; info.Shape = compressedBv; var body = new HkRigidBody(info); //MyPhysics.HavokWorld.AddRigidBody(body); } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad7)) { foreach (var g in MyEntities.GetEntities().OfType <MyCubeGrid>()) { foreach (var s in g.CubeBlocks.Select(s => s.FatBlock).Where(s => s != null).OfType <MyMotorStator>()) { if (s.Rotor != null) { var q = Quaternion.CreateFromAxisAngle(s.Rotor.WorldMatrix.Up, MathHelper.ToRadians(45)); s.Rotor.CubeGrid.WorldMatrix = MatrixD.CreateFromQuaternion(q) * s.Rotor.CubeGrid.WorldMatrix; } } } } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad8)) { var view = MySession.Static.CameraController.GetViewMatrix(); var inv = Matrix.Invert(view); var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone"); var obj = new MyObjectBuilder_FloatingObject() { Item = new MyObjectBuilder_InventoryItem() { PhysicalContent = oreBuilder, Amount = 1000 } }; obj.PositionAndOrientation = new MyPositionAndOrientation(inv.Translation + 2.0f * inv.Forward, inv.Forward, inv.Up); obj.PersistentFlags = MyPersistentEntityFlags2.InScene; var e = MyEntities.CreateFromObjectBuilderAndAdd(obj); e.Physics.LinearVelocity = Vector3.Normalize(inv.Forward) * 50.0f; } if (MyInput.Static.IsNewKeyPressed(MyKeys.Divide)) { } if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply)) { MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW; MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true; var grids = MyEntities.GetEntities().OfType <MyCubeGrid>(); foreach (var g in grids) { if (!g.IsStatic)// || g.GetBlocks().Count < 800) //to compute only castle { continue; } g.CreateStructuralIntegrity(); } } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1)) { var e = MyEntities.GetEntities().OfType <MyCubeGrid>().FirstOrDefault(); if (e != null) { e.Physics.RigidBody.MaxLinearVelocity = 1000; if (e.Physics.RigidBody2 != null) { e.Physics.RigidBody2.MaxLinearVelocity = 1000; } e.Physics.LinearVelocity = new Vector3(1000, 0, 0); } } if (MyInput.Static.IsNewKeyPressed(MyKeys.Decimal)) { MyPrefabManager.Static.SpawnPrefab("respawnship", MySector.MainCamera.Position, MySector.MainCamera.ForwardVector, MySector.MainCamera.UpVector); } if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply) && MyInput.Static.IsAnyShiftKeyPressed()) { GC.Collect(2); } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5)) { Thread.Sleep(250); } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9)) { var obj = MySession.Static.ControlledEntity != null ? MySession.Static.ControlledEntity.Entity : null; if (obj != null) { const float dist = 5.0f; obj.PositionComp.SetPosition(obj.PositionComp.GetPosition() + obj.WorldMatrix.Forward * dist); } } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad4)) { MyEntity invObject = MySession.Static.ControlledEntity as MyEntity; if (invObject != null && invObject.HasInventory) { MyFixedPoint amount = 20000; var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone"); MyInventory inventory = invObject.GetInventory(0) as MyInventory; System.Diagnostics.Debug.Assert(inventory != null, "Null or unexpected type returned!"); inventory.AddItems(amount, oreBuilder); } handled = true; } //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad8)) //{ // var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2; // var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid); // grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up); // grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>(); // grid.GridSizeEnum = MyCubeSize.Large; // var block = new MyObjectBuilder_CubeBlock(); // block.BlockOrientation = MyBlockOrientation.Identity; // block.Min = Vector3I.Zero; // //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock")); // block.SubtypeName = "LargeBlockArmorBlock"; // grid.CubeBlocks.Add(block); // grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20; // grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene; // var x = MyEntities.CreateFromObjectBuilderAndAdd(grid); //} //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad9)) //{ // var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2; // var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid); // grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up); // grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>(); // grid.GridSizeEnum = MyCubeSize.Large; // var block = new MyObjectBuilder_CubeBlock(); // block.BlockOrientation = MyBlockOrientation.Identity; // block.Min = Vector3I.Zero; // //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock")); // block.SubtypeName = "LargeBlockGyro"; // grid.CubeBlocks.Add(block); // grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20; // grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene; // var x = MyEntities.CreateFromObjectBuilderAndAdd(grid); //} if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Delete)) { int count = MyEntities.GetEntities().OfType <MyFloatingObject>().Count(); foreach (var obj in MyEntities.GetEntities().OfType <MyFloatingObject>()) { if (obj == MySession.Static.ControlledEntity) { MySession.Static.SetCameraController(MyCameraControllerEnum.Spectator); } obj.Close(); } handled = true; } if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Decimal)) { foreach (var obj in MyEntities.GetEntities()) { if (obj != MySession.Static.ControlledEntity && (MySession.Static.ControlledEntity == null || obj != MySession.Static.ControlledEntity.Entity.Parent) && obj != MyCubeBuilder.Static.FindClosestGrid()) { obj.Close(); } } handled = true; } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9) || MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5)) { //MyCubeGrid.UserCollisions = input.IsNewKeyPressed(Keys.NumPad9); var body = MySession.Static.ControlledEntity.Entity.GetTopMostParent().Physics; if (body.RigidBody != null) { //body.AddForce(Engine.Physics.MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, new Vector3(0, 0, 10 * body.Mass), null, null); body.RigidBody.ApplyLinearImpulse(body.Entity.WorldMatrix.Forward * body.Mass * 2); } handled = true; } //if (input.IsNewKeyPressed(Keys.J) && input.IsAnyCtrlKeyPressed()) //{ // MyGlobalInputComponent.CopyCurrentGridToClipboard(); // MyEntity addedEntity = MyGlobalInputComponent.PasteEntityFromClipboard(); // if (addedEntity != null) // { // Vector3 pos = addedEntity.GetPosition(); // pos.Z += addedEntity.WorldVolume.Radius * 1.5f; // addedEntity.SetPosition(pos); // } // handled = true; //} if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.OemComma)) { foreach (var e in MyEntities.GetEntities().OfType <MyFloatingObject>().ToArray()) { e.Close(); } } return(handled); }
private MyEntity FindBody(out Vector3D pivot) { pivot = Vector3D.Zero; if (CubeGrid.Physics == null) { return(null); } Quaternion orientation; Vector3 halfExtents; foreach (var m in m_lockPositions) { GetBoxFromMatrix(m, out halfExtents, out pivot, out orientation); HkBoxShape boxShape; try { halfExtents *= new Vector3(2.0f, 1.0f, 2.0f); orientation.Normalize(); MyPhysics.GetPenetrationsBox(ref halfExtents, ref pivot, ref orientation, m_penetrations, MyPhysics.CollisionLayers.DefaultCollisionLayer); boxShape = new HkBoxShape(halfExtents); Matrix tranform = Matrix.CreateFromQuaternion(orientation); //tranform.Translation = pivot; //MyOrientedBoundingBoxD obb = new MyOrientedBoundingBoxD(new BoundingBoxD(-halfExtents, halfExtents),tranform); //tranform.Translation = Vector3D.Zero; //MyRenderProxy.DebugDrawOBB(obb, Color.Red, 1, false, false); foreach (var obj in m_penetrations) { var entity = MyPhysicsExtensions.GetCollisionEntity(obj) as MyEntity; if (entity == null)// || entity.Parent != null) { continue; } if (entity.GetPhysicsBody().WeldInfo.Children.Count > 0) { Matrix t2; foreach (var child in entity.GetPhysicsBody().WeldInfo.Children) { var childEnt = child.Entity as MyEntity; t2 = childEnt.GetPhysicsBody().WeldInfo.Transform *entity.Physics.RigidBody.GetRigidBodyMatrix(); t2.Translation = entity.Physics.ClusterToWorld(t2.Translation); //obb = new MyOrientedBoundingBoxD((BoundingBoxD)childEnt.PositionComp.LocalAABB, t2); //MyRenderProxy.DebugDrawOBB(obb, Color.Green, 1, false, false); t2.Translation = t2.Translation - pivot; if (MyPhysics.IsPenetratingShapeShape(boxShape, ref tranform, child.WeldedRigidBody.GetShape(), ref t2)) { if ( CanAttachTo(obj, child.Entity as MyEntity)) { return(child.Entity as MyEntity); } } } t2 = entity.Physics.RigidBody.GetRigidBodyMatrix(); t2.Translation = entity.Physics.ClusterToWorld(t2.Translation) - pivot; if (MyPhysics.IsPenetratingShapeShape(boxShape, ref tranform, entity.GetPhysicsBody().GetShape(), ref t2) && CanAttachTo(obj, entity)) { return(entity); } } else if (CanAttachTo(obj, entity)) { return(entity); } } } finally { boxShape.Base.RemoveReference(); m_penetrations.Clear(); } } return(null); }
public MyCharacterProxy(bool isDynamic, bool isCapsule, float characterWidth, float characterHeight, float crouchHeight, float ladderHeight, float headSize, float headHeight, Vector3 position, Vector3 up, Vector3 forward, float mass, MyPhysicsBody body, bool isOnlyVertical, float maxSlope, float maxImpulse, HkRagdoll ragDoll = null) { m_isDynamic = isDynamic; m_physicsBody = body; m_mass = mass; m_maxImpulse = maxImpulse; if (isCapsule) { m_characterShape = CreateCharacterShape(characterHeight, characterWidth, characterHeight + headHeight, headSize, 0, 0); m_characterCollisionShape = CreateCharacterShape(characterHeight * 0.9f, characterWidth * 0.9f, characterHeight * 0.9f + headHeight, headSize * 0.9f, 0, 0); m_crouchShape = CreateCharacterShape(characterHeight, characterWidth, characterHeight + headHeight, headSize, 0.0f, 1.0f); if (!m_isDynamic) CharacterPhantom = new HkSimpleShapePhantom(m_characterShape, MyPhysics.CharacterCollisionLayer); } else { HkBoxShape box = new HkBoxShape(new Vector3(characterWidth / 2.0f, characterHeight / 2.0f, characterWidth / 2.0f)); if (!m_isDynamic) CharacterPhantom = new HkSimpleShapePhantom((HkShape)box, MyPhysics.CharacterCollisionLayer); m_characterShape = box; } if (!m_isDynamic) { HkCharacterProxyCinfo characterProxyInfo = new HkCharacterProxyCinfo(); characterProxyInfo.StaticFriction = 1; characterProxyInfo.DynamicFriction = 1; characterProxyInfo.ExtraDownStaticFriction = 1000; //characterProxyInfo.ContactAngleSensitivity = 20; //characterProxyInfo.KeepContactTolerance = 1f; characterProxyInfo.MaxCharacterSpeedForSolver = 10000; characterProxyInfo.RefreshManifoldInCheckSupport = true; characterProxyInfo.Up = up; characterProxyInfo.Forward = forward; characterProxyInfo.UserPlanes = 4; characterProxyInfo.MaxSlope = MathHelper.ToRadians(maxSlope); characterProxyInfo.Position = position; characterProxyInfo.CharacterMass = mass; characterProxyInfo.CharacterStrength = 100; characterProxyInfo.ShapePhantom = CharacterPhantom; CharacterProxy = new HkCharacterProxy(characterProxyInfo); characterProxyInfo.Dispose(); } else { HkCharacterRigidBodyCinfo characterRBCInfo = new HkCharacterRigidBodyCinfo(); characterRBCInfo.Shape = m_characterShape; characterRBCInfo.CrouchShape = m_crouchShape; characterRBCInfo.Friction = 0; characterRBCInfo.MaxSlope = MathHelper.ToRadians(maxSlope); characterRBCInfo.Up = up; characterRBCInfo.Mass = mass; characterRBCInfo.CollisionFilterInfo = MyPhysics.CharacterCollisionLayer; //characterRBCInfo.UnweldingHeightOffsetFactor = 100; characterRBCInfo.MaxLinearVelocity = 1000000; characterRBCInfo.MaxForce = 100000; characterRBCInfo.AllowedPenetrationDepth = 0.1f; characterRBCInfo.JumpHeight = 0.8f; CharacterRigidBody = new HkCharacterRigidBody(characterRBCInfo, MyGridPhysics.ShipMaxLinearVelocity(), body, isOnlyVertical); CharacterRigidBody.GetRigidBody().ContactPointCallbackEnabled = true; CharacterRigidBody.GetRigidBody().ContactPointCallback += RigidBody_ContactPointCallback; CharacterRigidBody.GetRigidBody().ContactPointCallbackDelay = 0; //CharacterRigidBody.GetHitRigidBody().ContactPointCallbackEnabled = true; //CharacterRigidBody.GetHitRigidBody().ContactPointCallback += RigidBody_ContactPointCallback; //CharacterRigidBody.GetHitRigidBody().ContactPointCallbackDelay = 0; //CharacterRigidBody.SetSupportDistance(10); //CharacterRigidBody.SetHardSupportDistance(10); characterRBCInfo.Dispose(); } }
private MyEntity FindBody(out Vector3D pivot) { pivot = Vector3D.Zero; if (CubeGrid.Physics == null) return null; Quaternion orientation; Vector3 halfExtents; foreach (var m in m_lockPositions) { GetBoxFromMatrix(m, out halfExtents, out pivot, out orientation); try { halfExtents *= new Vector3(2.0f, 1.0f, 2.0f); orientation.Normalize(); MyPhysics.GetPenetrationsBox(ref halfExtents, ref pivot, ref orientation, m_penetrations, MyPhysics.ObjectDetectionCollisionLayer); var boxShape = new HkBoxShape(halfExtents); Matrix tranform = Matrix.CreateFromQuaternion(orientation); //tranform.Translation = pivot; //MyOrientedBoundingBoxD obb = new MyOrientedBoundingBoxD(new BoundingBoxD(-halfExtents, halfExtents),tranform); //tranform.Translation = Vector3D.Zero; //MyRenderProxy.DebugDrawOBB(obb, Color.Red, 1, false, false); foreach (var obj in m_penetrations) { var entity = obj.GetCollisionEntity() as MyEntity; if (entity == null) continue; if(entity.Physics.WeldInfo.Children.Count > 0) { Matrix t2; foreach(var child in entity.Physics.WeldInfo.Children) { var childEnt = child.Entity as MyEntity; t2 = childEnt.Physics.WeldInfo.Transform * entity.Physics.RigidBody.GetRigidBodyMatrix(); t2.Translation = entity.Physics.ClusterToWorld(t2.Translation); //obb = new MyOrientedBoundingBoxD((BoundingBoxD)childEnt.PositionComp.LocalAABB, t2); //MyRenderProxy.DebugDrawOBB(obb, Color.Green, 1, false, false); t2.Translation = t2.Translation -pivot; if(MyPhysics.IsPenetratingShapeShape(boxShape, ref tranform, child.WeldedRigidBody.GetShape(), ref t2) ) if( CanAttachTo(obj, child.Entity as MyEntity)) { return child.Entity as MyEntity; } } t2 = entity.Physics.RigidBody.GetRigidBodyMatrix(); t2.Translation = entity.Physics.ClusterToWorld(t2.Translation) - pivot; if (MyPhysics.IsPenetratingShapeShape(boxShape, ref tranform, entity.Physics.GetShape(), ref t2) && CanAttachTo(obj, entity)) { return entity; } } else if(CanAttachTo(obj, entity)) return entity; } } finally { m_penetrations.Clear(); } } return null; }
public static unsafe void DrawCollisionShape(HkShape shape, MatrixD worldMatrix, float alpha, ref int shapeIndex, string customText = null, bool isPhantom = false) { Color color = GetShapeColor(shape.ShapeType, ref shapeIndex, isPhantom); if (isPhantom) { alpha *= alpha; } color.A = (byte)(alpha * 255f); bool smooth = true; float num = 0.02f; float num2 = 1.035f; bool flag2 = false; HkShapeType shapeType = shape.ShapeType; switch (shapeType) { case HkShapeType.Sphere: { float radius = ((HkSphereShape)shape).Radius; MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, alpha, true, smooth, true, false); if (isPhantom) { MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, 1f, true, false, true, false); MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, 1f, true, false, false, false); } flag2 = true; goto TR_0003; } case HkShapeType.Cylinder: { HkCylinderShape shape4 = (HkCylinderShape)shape; MyRenderProxy.DebugDrawCylinder(worldMatrix, shape4.VertexA, shape4.VertexB, shape4.Radius, color, alpha, true, smooth, false); flag2 = true; goto TR_0003; } case HkShapeType.Triangle: { HkTriangleShape shape12 = (HkTriangleShape)shape; MyRenderProxy.DebugDrawTriangle(shape12.Pt0, shape12.Pt1, shape12.Pt2, Color.Green, false, false, false); goto TR_0003; } case HkShapeType.Box: { HkBoxShape shape5 = (HkBoxShape)shape; MyRenderProxy.DebugDrawOBB(MatrixD.CreateScale((shape5.HalfExtents * 2f) + new Vector3(num)) * worldMatrix, color, alpha, true, smooth, true, false); if (isPhantom) { MyRenderProxy.DebugDrawOBB(Matrix.CreateScale((shape5.HalfExtents * 2f) + new Vector3(num)) * worldMatrix, color, 1f, true, false, true, false); MyRenderProxy.DebugDrawOBB(Matrix.CreateScale((shape5.HalfExtents * 2f) + new Vector3(num)) * worldMatrix, color, 1f, true, false, false, false); } flag2 = true; goto TR_0003; } case HkShapeType.Capsule: { HkCapsuleShape shape3 = (HkCapsuleShape)shape; MyRenderProxy.DebugDrawCapsule(Vector3.Transform(shape3.VertexA, worldMatrix), Vector3.Transform(shape3.VertexB, worldMatrix), shape3.Radius, color, true, smooth, false); flag2 = true; goto TR_0003; } case HkShapeType.ConvexVertices: { Vector3 vector; ((HkConvexVerticesShape)shape).GetGeometry(DebugGeometry, out vector); Vector3D vectord2 = Vector3D.Transform(vector, worldMatrix.GetOrientation()); MatrixD xd = worldMatrix; xd = MatrixD.CreateScale((double)num2) * xd; MatrixD *xdPtr1 = (MatrixD *)ref xd; xdPtr1.Translation -= vectord2 * (num2 - 1f); DrawGeometry(DebugGeometry, xd, color, true, true); flag2 = true; goto TR_0003; } case HkShapeType.TriSampledHeightFieldCollection: case HkShapeType.TriSampledHeightFieldBvTree: case HkShapeType.SampledHeightField: case HkShapeType.ExtendedMesh: case HkShapeType.Transform: case HkShapeType.CompressedMesh: case HkShapeType.Collection: case HkShapeType.User0: case HkShapeType.User1: case HkShapeType.User2: goto TR_0003; case HkShapeType.List: { HkShapeContainerIterator iterator = ((HkListShape)shape).GetIterator(); while (iterator.IsValid) { DrawCollisionShape(iterator.CurrentValue, worldMatrix, alpha, ref shapeIndex, customText, false); iterator.Next(); } goto TR_0003; } case HkShapeType.Mopp: DrawCollisionShape((HkShape)((HkMoppBvTreeShape)shape).ShapeCollection, worldMatrix, alpha, ref shapeIndex, customText, false); goto TR_0003; case HkShapeType.ConvexTranslate: { HkConvexTranslateShape shape7 = (HkConvexTranslateShape)shape; DrawCollisionShape((HkShape)shape7.ChildShape, Matrix.CreateTranslation(shape7.Translation) * worldMatrix, alpha, ref shapeIndex, customText, false); goto TR_0003; } case HkShapeType.ConvexTransform: { HkConvexTransformShape shape8 = (HkConvexTransformShape)shape; DrawCollisionShape((HkShape)shape8.ChildShape, shape8.Transform * worldMatrix, alpha, ref shapeIndex, customText, false); goto TR_0003; } case HkShapeType.StaticCompound: { HkStaticCompoundShape shape11 = (HkStaticCompoundShape)shape; if (DebugDrawFlattenHierarchy) { HkShapeContainerIterator iterator2 = shape11.GetIterator(); while (iterator2.IsValid) { if (shape11.IsShapeKeyEnabled(iterator2.CurrentShapeKey)) { object[] objArray1 = new object[4]; object[] objArray2 = new object[4]; objArray2[0] = customText ?? string.Empty; object[] local2 = objArray2; local2[1] = "-"; local2[2] = iterator2.CurrentShapeKey; local2[3] = "-"; string str = string.Concat(local2); DrawCollisionShape(iterator2.CurrentValue, worldMatrix, alpha, ref shapeIndex, str, false); } iterator2.Next(); } } else { for (int i = 0; i < shape11.InstanceCount; i++) { string str2; bool flag3 = shape11.IsInstanceEnabled(i); if (flag3) { object[] objArray3 = new object[4]; object[] objArray4 = new object[4]; objArray4[0] = customText ?? string.Empty; object[] local4 = objArray4; local4[1] = "<"; local4[2] = i; local4[3] = ">"; str2 = string.Concat(local4); } else { object[] objArray5 = new object[4]; object[] objArray6 = new object[4]; objArray6[0] = customText ?? string.Empty; object[] local6 = objArray6; local6[1] = "("; local6[2] = i; local6[3] = ")"; str2 = string.Concat(local6); } if (flag3) { DrawCollisionShape(shape11.GetInstance(i), shape11.GetInstanceTransform(i) * worldMatrix, alpha, ref shapeIndex, str2, false); } } } goto TR_0003; } case HkShapeType.BvCompressedMesh: break; case HkShapeType.BvTree: { HkGridShape shape13 = (HkGridShape)shape; if (HkGridShapeCellDebugDraw && !shape13.Base.IsZero) { float cellSize = shape13.CellSize; int shapeInfoCount = shape13.GetShapeInfoCount(); for (int i = 0; i < shapeInfoCount; i++) { try { Vector3S vectors; Vector3S vectors2; shape13.GetShapeInfo(i, out vectors, out vectors2, m_tmpShapeList); Vector3 position = (Vector3)(((vectors2 * cellSize) + (vectors * cellSize)) / 2f); Color color2 = color; if (vectors == vectors2) { color2 = new Color(1f, 0.2f, 0.1f); } MyRenderProxy.DebugDrawOBB((Matrix.CreateScale((((vectors2 * cellSize) - (vectors * cellSize)) + (Vector3.One * cellSize)) + new Vector3(num)) * Matrix.CreateTranslation(position)) * worldMatrix, color2, alpha, true, smooth, true, false); } finally { m_tmpShapeList.Clear(); } } } else { MyRenderMessageDebugDrawTriangles msgInterface = MyRenderProxy.PrepareDebugDrawTriangles(); try { using (HkShapeBuffer buffer = new HkShapeBuffer()) { HkShapeContainerIterator iterator3 = ((HkBvTreeShape)shape).GetIterator(buffer); while (iterator3.IsValid) { HkShape currentValue = iterator3.CurrentValue; if (currentValue.ShapeType != HkShapeType.Triangle) { DrawCollisionShape(currentValue, worldMatrix, alpha, ref shapeIndex, null, false); } else { HkTriangleShape shape17 = (HkTriangleShape)currentValue; msgInterface.AddTriangle(shape17.Pt0, shape17.Pt1, shape17.Pt2); } iterator3.Next(); } goto TR_0003; } } finally { msgInterface.Color = color; MyRenderProxy.DebugDrawTriangles(msgInterface, new MatrixD?(worldMatrix), false, false, false, false); } break; } goto TR_0003; } default: if (shapeType == HkShapeType.Bv) { HkBvShape shape19 = (HkBvShape)shape; DrawCollisionShape(shape19.BoundingVolumeShape, worldMatrix, alpha, ref shapeIndex, null, true); DrawCollisionShape(shape19.ChildShape, worldMatrix, alpha, ref shapeIndex, null, false); } else if (shapeType == HkShapeType.PhantomCallback) { MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, "Phantom", Color.Green, 0.75f, false, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, -1, false); } goto TR_0003; } if (MyDebugDrawSettings.DEBUG_DRAW_TRIANGLE_PHYSICS) { ((HkBvCompressedMeshShape)shape).GetGeometry(DebugGeometry); DrawGeometry(DebugGeometry, worldMatrix, Color.Green, false, false); flag2 = true; } TR_0003: if (flag2 && (customText != null)) { color.A = 0xff; MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, customText, color, 0.8f, false, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, -1, false); } }
private void AddBox(Vector3I minPos, Vector3I maxPos, ref Vector3 min, ref Vector3 max) { Vector3 center = (min + max) / 2.0f; Vector3 halfExtent = max - center; halfExtent -= BOX_SHRINK; HkBoxShape boxShape = new HkBoxShape(halfExtent, MyPerGameSettings.PhysicsConvexRadius); var shape = new HkConvexTranslateShape(boxShape, center, HkReferencePolicy.TakeOwnership); Shapes.Add(shape); ShapeInfos.Add(new ShapeInfo() { Count = 1, Min = minPos, Max = maxPos }); }
public override bool HandleInput() { bool handled = false; if (m_gridDebugInfo) { LineD line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 1000); MyCubeGrid grid; Vector3I cubePos; double distance; if (MyCubeGrid.GetLineIntersection(ref line, out grid, out cubePos, out distance)) { var gridMatrix = grid.WorldMatrix; var boxMatrix = Matrix.CreateTranslation(cubePos * grid.GridSize) * gridMatrix; var block = grid.GetCubeBlock(cubePos); MyRenderProxy.DebugDrawText2D(new Vector2(), cubePos.ToString(), Color.White, 0.7f); MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(new Vector3(grid.GridSize) + new Vector3(0.15f)) * boxMatrix, Color.Red.ToVector3(), 0.2f, true, true); //int[, ,] bones = grid.Skeleton.AddCubeBones(cubePos); //Vector3 closestBone = Vector3.Zero; //Vector3I closestPoint = Vector3I.Zero; //float closestPointDist = float.MaxValue; //int closestBoneIndex = 0; //for (int x = -1; x <= 1; x += 1) //{ // for (int y = -1; y <= 1; y += 1) // { // for (int z = -1; z <= 1; z += 1) // { // int boneIndex = bones[x + 1, y + 1, z + 1]; // Vector3 bone = grid.Skeleton[boneIndex]; // var pos = boxMatrix.Translation + new Vector3(grid.GridSize / 2) * new Vector3(x, y, z); // //MyRenderProxy.DebugDrawSphere(pos, 0.2f, Color.Blue.ToVector3(), 1.0f, false); // MyRenderProxy.DebugDrawText3D(pos, String.Format("{0:G2}, {1:G2}, {2:G2}", bone.X, bone.Y, bone.Z), Color.White, 0.5f, false); // var dist = MyUtils.GetPointLineDistance(ref line, ref pos); // if (dist < closestPointDist) // { // closestPointDist = dist; // closestPoint = new Vector3I(x, y, z); // closestBoneIndex = boneIndex; // closestBone = bone; // } // } // } //} //MyRenderProxy.DebugDrawText3D(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f, String.Format("{0:G2}, {1:G2}, {2:G2}", closestBone.X, closestBone.Y, closestBone.Z), Color.Red, 0.5f, false); //var bonePos = grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]]; //MyRenderProxy.DebugDrawSphere(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f + bonePos, 0.5f, Color.Red.ToVector3(), 0.4f, true, true); //if (input.IsNewKeyPressed(Keys.P) && block != null) //{ // if (input.IsAnyShiftKeyPressed()) // { // grid.ResetBlockSkeleton(block); // } // else // { // grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]] = Vector3.Zero; // grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One); // //grid.SetBlockDirty(block); // } // handled = true; //} //// Move bones to center by 0.1f //if (input.IsNewKeyPressed(Keys.OemOpenBrackets)) //{ // int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]; // grid.Skeleton[index] -= Vector3.Sign(grid.Skeleton[index]) * 0.1f; // grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One); // //grid.SetBlockDirty(block); // handled = true; //} //// Reduce max offset by 0.1f //if (input.IsNewKeyPressed(Keys.OemCloseBrackets)) //{ // int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]; // var old = Vector3.Abs(grid.Skeleton[index]); // var max = new Vector3(Math.Max(Math.Max(old.X, old.Y), old.Z)); // if (max.X > 0.1f) // { // grid.Skeleton[index] = Vector3.Clamp(grid.Skeleton[index], -max + 0.1f, max - 0.1f); // } // else // { // grid.Skeleton[index] = Vector3.Zero; // } // grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One); // //grid.SetBlockDirty(block); // handled = true; //} } } if (MyInput.Static.IsAnyAltKeyPressed()) return handled; bool shift = MyInput.Static.IsAnyShiftKeyPressed(); bool ctrl = MyInput.Static.IsAnyCtrlKeyPressed(); //if (input.IsNewKeyPressed(Keys.I)) //{ // foreach (var grid in MyEntities.GetEntities().OfType<MyCubeGrid>()) // { // foreach (var block in grid.GetBlocks().ToArray()) // { // grid.DetectMerge(block.Min, block.Max); // } // } // handled = true; //} // Disabled since it is common to have normal control bound to O key. // If you ever need this again, bind it to something more complicated, like key combination. //if (input.IsNewKeyPressed(Keys.O)) //{ // m_gridDebugInfo = !m_gridDebugInfo; // handled = true; //} //for (int i = 0; i <= 9; i++) //{ // if (MyInput.Static.IsNewKeyPressed((Keys)(((int)Keys.D0) + i))) // { // string name = "Slot" + i.ToString(); // if (ctrl) // { // MySession.Static.Name = name; // MySession.Static.WorldID = MySession.GetNewWorldId(); // MySession.Static.Save(name); // } // else if (shift) // { // var path = MyLocalCache.GetSessionSavesPath(name, false, false); // if (System.IO.Directory.Exists(path)) // { // MySession.Static.Unload(); // MySession.Load(path); // } // } // handled = true; // } //} //if (MyInput.Static.IsNewKeyPressed(Keys.End)) //{ // MyMeteorShower.MeteorWave(null); //} // Disabled for god sake! //if (MyInput.Static.IsNewKeyPressed(Keys.PageUp) && MyInput.Static.IsAnyCtrlKeyPressed()) //{ // MyReloadTestComponent.Enabled = true; //} //if (MyInput.Static.IsNewKeyPressed(Keys.PageDown) && MyInput.Static.IsAnyCtrlKeyPressed()) //{ // MyReloadTestComponent.Enabled = false; //} if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad6)) { var view = MySession.Static.CameraController.GetViewMatrix(); var inv = Matrix.Invert(view); //MyPhysicalInventoryItem item = new MyPhysicalInventoryItem(100, var oreBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Ore>("Stone"); var item = new MyPhysicalInventoryItem(1, oreBuilder); var obj = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * 1.0f, inv.Forward, inv.Up); obj.Physics.LinearVelocity = inv.Forward * 50; } if (false && MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9)) { List<HkShape> trShapes = new List<HkShape>(); List<HkConvexShape> shapes = new List<HkConvexShape>(); List<Matrix> matrices = new List<Matrix>(); var grid = new HkGridShape(2.5f, HkReferencePolicy.None); const short size = 50; for (short x = 0; x < size; x++) { for (short y = 0; y < size; y++) { for (short z = 0; z < size; z++) { var box = new HkBoxShape(Vector3.One); grid.AddShapes(new System.Collections.Generic.List<HkShape>() { box }, new Vector3S(x, y, z), new Vector3S(x, y, z)); trShapes.Add(new HkConvexTranslateShape(box, new Vector3(x, y, z), HkReferencePolicy.None)); shapes.Add(box); matrices.Add(Matrix.CreateTranslation(new Vector3(x, y, z))); } } } var emptyGeom = new HkGeometry(new List<Vector3>(), new List<int>()); var list = new HkListShape(trShapes.ToArray(), trShapes.Count, HkReferencePolicy.None); var compressedBv = new HkBvCompressedMeshShape(emptyGeom, shapes, matrices, HkWeldingType.None); var mopp = new HkMoppBvTreeShape(list, HkReferencePolicy.None); HkShapeBuffer buf = new HkShapeBuffer(); //HkShapeContainerIterator i = compressedBv.GetIterator(buf); //int count = 0; // will be 125000 //while (i.IsValid) //{ // count++; // i.Next(); //} buf.Dispose(); var info = new HkRigidBodyCinfo(); info.Mass = 10; info.CalculateBoxInertiaTensor(Vector3.One, 10); info.MotionType = HkMotionType.Dynamic; info.QualityType = HkCollidableQualityType.Moving; info.Shape = compressedBv; var body = new HkRigidBody(info); //MyPhysics.HavokWorld.AddRigidBody(body); } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad7)) { foreach (var g in MyEntities.GetEntities().OfType<MyCubeGrid>()) { foreach (var s in g.CubeBlocks.Select(s => s.FatBlock).Where(s => s != null).OfType<MyMotorStator>()) { if (s.Rotor != null) { var q = Quaternion.CreateFromAxisAngle(s.Rotor.WorldMatrix.Up, MathHelper.ToRadians(45)); s.Rotor.CubeGrid.WorldMatrix = MatrixD.CreateFromQuaternion(q) * s.Rotor.CubeGrid.WorldMatrix; } } } } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad8)) { var view = MySession.Static.CameraController.GetViewMatrix(); var inv = Matrix.Invert(view); var oreBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Ore>("Stone"); var obj = new MyObjectBuilder_FloatingObject() { Item = new MyObjectBuilder_InventoryItem() { Content = oreBuilder, Amount = 1000 } }; obj.PositionAndOrientation = new MyPositionAndOrientation(inv.Translation + 2.0f * inv.Forward, inv.Forward, inv.Up); obj.PersistentFlags = MyPersistentEntityFlags2.InScene; var e = MyEntities.CreateFromObjectBuilderAndAdd(obj); e.Physics.LinearVelocity = Vector3.Normalize(inv.Forward) * 50.0f; } if (MyInput.Static.IsNewKeyPressed(MyKeys.Divide)) { } if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply)) { MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW; MyStructuralIntegrity.Enabled = true; MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true; var grids = MyEntities.GetEntities().OfType<MyCubeGrid>(); foreach (var g in grids) { if (!g.IsStatic)// || g.GetBlocks().Count < 800) //to compute only castle continue; g.CreateStructuralIntegrity(); } } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1)) { var e = MyEntities.GetEntities().OfType<MyCubeGrid>().FirstOrDefault(); if (e != null) { e.Physics.RigidBody.MaxLinearVelocity = 1000; if (e.Physics.RigidBody2 != null) e.Physics.RigidBody2.MaxLinearVelocity = 1000; e.Physics.LinearVelocity = new Vector3(1000, 0, 0); } } if (MyInput.Static.IsNewKeyPressed(MyKeys.Decimal)) { MyPrefabManager.Static.SpawnPrefab("respawnship", MySector.MainCamera.Position, MySector.MainCamera.ForwardVector, MySector.MainCamera.UpVector); } if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply) && MyInput.Static.IsAnyShiftKeyPressed()) { GC.Collect(2); } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5)) { Thread.Sleep(250); } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9)) { var obj = MySession.ControlledEntity != null ? MySession.ControlledEntity.Entity : null; if (obj != null) { const float dist = 5.0f; obj.PositionComp.SetPosition(obj.PositionComp.GetPosition() + obj.WorldMatrix.Forward * dist); } } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad4)) { IMyInventoryOwner invObject = MySession.ControlledEntity as IMyInventoryOwner; if (invObject != null) { MyFixedPoint amount = 20000; var oreBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Ore>("Stone"); MyInventory inventory = invObject.GetInventory(0); inventory.AddItems(amount, oreBuilder); } handled = true; } //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad8)) //{ // var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2; // var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid); // grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up); // grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>(); // grid.GridSizeEnum = MyCubeSize.Large; // var block = new MyObjectBuilder_CubeBlock(); // block.BlockOrientation = MyBlockOrientation.Identity; // block.Min = Vector3I.Zero; // //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock")); // block.SubtypeName = "LargeBlockArmorBlock"; // grid.CubeBlocks.Add(block); // grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20; // grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene; // var x = MyEntities.CreateFromObjectBuilderAndAdd(grid); //} //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad9)) //{ // var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2; // var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid); // grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up); // grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>(); // grid.GridSizeEnum = MyCubeSize.Large; // var block = new MyObjectBuilder_CubeBlock(); // block.BlockOrientation = MyBlockOrientation.Identity; // block.Min = Vector3I.Zero; // //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock")); // block.SubtypeName = "LargeBlockGyro"; // grid.CubeBlocks.Add(block); // grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20; // grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene; // var x = MyEntities.CreateFromObjectBuilderAndAdd(grid); //} if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Delete)) { int count = MyEntities.GetEntities().OfType<MyFloatingObject>().Count(); foreach (var obj in MyEntities.GetEntities().OfType<MyFloatingObject>()) { if (obj == MySession.ControlledEntity) { MySession.SetCameraController(MyCameraControllerEnum.Spectator); } obj.Close(); } handled = true; } if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Decimal)) { foreach (var obj in MyEntities.GetEntities()) { if (obj != MySession.ControlledEntity && (MySession.ControlledEntity == null || obj != MySession.ControlledEntity.Entity.Parent) && obj != MyCubeBuilder.Static.FindClosestGrid()) obj.Close(); } handled = true; } if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9) || MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5)) { //MyCubeGrid.UserCollisions = input.IsNewKeyPressed(Keys.NumPad9); var body = MySession.ControlledEntity.Entity.GetTopMostParent().Physics; if (body.RigidBody != null) { //body.AddForce(Engine.Physics.MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, new Vector3(0, 0, 10 * body.Mass), null, null); body.RigidBody.ApplyLinearImpulse(body.Entity.WorldMatrix.Forward * body.Mass * 2); } handled = true; } //if (input.IsNewKeyPressed(Keys.J) && input.IsAnyCtrlKeyPressed()) //{ // MyGlobalInputComponent.CopyCurrentGridToClipboard(); // MyEntity addedEntity = MyGlobalInputComponent.PasteEntityFromClipboard(); // if (addedEntity != null) // { // Vector3 pos = addedEntity.GetPosition(); // pos.Z += addedEntity.WorldVolume.Radius * 1.5f; // addedEntity.SetPosition(pos); // } // handled = true; //} if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.OemComma)) { foreach (var e in MyEntities.GetEntities().OfType<MyFloatingObject>().ToArray()) e.Close(); } return handled; }
private HkBvShape CreateFieldShape(Vector3 extents) { var phantom = new HkPhantomCallbackShape(phantom_Enter, phantom_Leave); var detectorShape = new HkBoxShape(extents); return new HkBvShape(detectorShape, phantom, HkReferencePolicy.TakeOwnership); }
private void InitInternal() { base.Init(null, m_definition.Model, null, null); Render.ColorMaskHsv = m_definition.ColorHSV; Render.Transparency = 0.25f; Render.AddRenderObjects(); List<MyTextureChange> textureChanges = new List<MyTextureChange>(); textureChanges.Add(new MyTextureChange { TextureName = m_definition.ColorMetalTexture, MaterialSlot = "ColorMetalTexture" }); textureChanges.Add(new MyTextureChange { TextureName = m_definition.AddMapsTexture, MaterialSlot = "AddMapsTexture" }); VRageRender.MyRenderProxy.ChangeMaterialTexture(Render.RenderObjectIDs[0], "BotFlag", textureChanges); // TODO: change the material name m_localActivationMatrix = MatrixD.CreateScale(this.PositionComp.LocalAABB.HalfExtents * 2.0f) * MatrixD.CreateTranslation(this.PositionComp.LocalAABB.Center); var shape = new HkBoxShape(m_localActivationMatrix.Scale); Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE); Physics.CreateFromCollisionObject(shape, Vector3.Zero, WorldMatrix, null, MyPhysics.ObjectDetectionCollisionLayer); Physics.Enabled = true; Components.Add<MyPlaceArea>(new MySpherePlaceArea(10.0f, m_definition.Id.SubtypeId)); // TODO: Add radius to the definition MyHud.LocationMarkers.RegisterMarker(this, new MyHudEntityParams() { FlagsEnum = MyHudIndicatorFlagsEnum.SHOW_TEXT, Text = m_definition.DisplayNameEnum.HasValue ? MyTexts.Get(m_definition.DisplayNameEnum.Value) : new StringBuilder(), TargetMode = MyRelationsBetweenPlayerAndBlock.Neutral, MaxDistance = 200.0f, MustBeDirectlyVisible = true } ); }
protected Vector3D? GetFreeSpacePlacementPosition(bool copyPaste, out bool buildAllowed) { Vector3D? freePlacementIntersectionPoint = null; buildAllowed = false; float gridSize = PreviewGrids[0].GridSize; double shortestDistance = double.MaxValue; double? currentRayInts = GetCurrentRayIntersection(); if (currentRayInts.HasValue) shortestDistance = currentRayInts.Value; Vector3D worldRefPointOffset = Vector3D.Zero; if (copyPaste) { Matrix firstGridOrientation = GetFirstGridOrientationMatrix(); worldRefPointOffset = Vector3.TransformNormal(m_dragPointToPositionLocal, firstGridOrientation); } Vector3D worldRefPoint = PreviewGrids[0].GridIntegerToWorld(Vector3I.Zero); Matrix blockWorlTransform; foreach (var block in PreviewGrids[0].GetBlocks()) { Vector3 halfExt = block.BlockDefinition.Size * PreviewGrids[0].GridSize * 0.5f; Vector3 minLocal = block.Min * PreviewGrids[0].GridSize - Vector3.Half * PreviewGrids[0].GridSize; Vector3 maxLocal = block.Max * PreviewGrids[0].GridSize + Vector3.Half * PreviewGrids[0].GridSize; block.Orientation.GetMatrix(out blockWorlTransform); blockWorlTransform.Translation = 0.5f * (minLocal + maxLocal); blockWorlTransform = blockWorlTransform * PreviewGrids[0].WorldMatrix; Vector3D offset = blockWorlTransform.Translation + worldRefPointOffset - worldRefPoint; HkShape shape = new HkBoxShape(halfExt); Vector3D rayStart = MyCubeBuilder.IntersectionStart + offset; double castPlaneDistanceToRayStart = DistanceFromCharacterPlane(ref rayStart); rayStart -= castPlaneDistanceToRayStart * MyCubeBuilder.IntersectionDirection; Vector3D rayEnd = MyCubeBuilder.IntersectionStart + (m_dragDistance - castPlaneDistanceToRayStart) * MyCubeBuilder.IntersectionDirection + offset; MatrixD matrix = blockWorlTransform; matrix.Translation = rayStart; try { float? dist = MyPhysics.CastShape(rayEnd, shape, ref matrix, MyPhysics.CollisionLayerWithoutCharacter); if (dist.HasValue && dist.Value != 0f) { Vector3D intersectionPoint = rayStart + dist.Value * (rayEnd - rayStart); const bool debugDraw = false; if (debugDraw) { Color green = Color.Green; BoundingBoxD localAABB = new BoundingBoxD(-halfExt, halfExt); MatrixD drawMatrix = matrix; drawMatrix.Translation = intersectionPoint; MySimpleObjectDraw.DrawTransparentBox(ref drawMatrix, ref localAABB, ref green, MySimpleObjectRasterizer.Wireframe, 1, 0.04f); } double fixedDistance = DistanceFromCharacterPlane(ref intersectionPoint) - castPlaneDistanceToRayStart; if (fixedDistance <= 0) { fixedDistance = 0; shortestDistance = 0; break; } if (fixedDistance < shortestDistance) shortestDistance = fixedDistance; buildAllowed = true; } } finally { shape.RemoveReference(); } } float boxRadius = (float)PreviewGrids[0].PositionComp.WorldAABB.HalfExtents.Length(); float dragDistance = 1.5f * boxRadius; if (shortestDistance < dragDistance) { shortestDistance = dragDistance; buildAllowed = false; } if (shortestDistance < m_dragDistance) freePlacementIntersectionPoint = MyCubeBuilder.IntersectionStart + shortestDistance * MyCubeBuilder.IntersectionDirection; return freePlacementIntersectionPoint; }
private HkBvShape CreateDetectorShape(Vector3 extents, Mode mode) { if (mode == Mode.Ejector) { var phantom = new HkPhantomCallbackShape(phantom_EnterEjector, phantom_LeaveEjector); var detectorShape = new HkBoxShape(extents); return new HkBvShape(detectorShape, phantom, HkReferencePolicy.TakeOwnership); } else { var phantom = new HkPhantomCallbackShape(phantom_EnterConnector, phantom_LeaveConnector); var detectorShape = new HkSphereShape(extents.AbsMax()); return new HkBvShape(detectorShape, phantom, HkReferencePolicy.TakeOwnership); } }
/// <summary> /// Casts preview grids aabbs and get shortest distance. Returns shortest intersection or null. /// </summary> protected Vector3D? GetFreeSpacePlacementPositionGridAabbs(bool copyPaste, out bool buildAllowed) { Vector3D? freePlacementIntersectionPoint = null; buildAllowed = true; float gridSize = PreviewGrids[0].GridSize; double shortestDistance = double.MaxValue; double? currentRayInts = GetCurrentRayIntersection(); if (currentRayInts.HasValue) shortestDistance = currentRayInts.Value; Vector3D worldRefPointOffset = Vector3D.Zero; if (copyPaste) { Matrix firstGridOrientation = GetFirstGridOrientationMatrix(); worldRefPointOffset = Vector3.TransformNormal(m_dragPointToPositionLocal, firstGridOrientation); } Vector3D worldRefPoint = PreviewGrids[0].GridIntegerToWorld(Vector3I.Zero); foreach (var grid in PreviewGrids) { Vector3 halfExt = grid.PositionComp.LocalAABB.HalfExtents; Vector3 minLocal = grid.Min * grid.GridSize - Vector3.Half * grid.GridSize; Vector3 maxLocal = grid.Max * grid.GridSize + Vector3.Half * grid.GridSize; MatrixD gridWorlTransform = MatrixD.Identity; gridWorlTransform.Translation = 0.5f * (minLocal + maxLocal); gridWorlTransform = gridWorlTransform * grid.WorldMatrix; Vector3I size = grid.Max - grid.Min + Vector3I.One; Vector3 sizeOffset = Vector3I.Abs((size % 2) - Vector3I.One) * 0.5 * grid.GridSize; sizeOffset = Vector3.TransformNormal(sizeOffset, grid.WorldMatrix); Vector3D offset = gridWorlTransform.Translation + worldRefPointOffset - worldRefPoint /*- sizeOffset*/;// Vector3.Zero;// gridWorlTransform.Translation + worldRefPointOffset - worldRefPoint; HkShape shape = new HkBoxShape(halfExt); Vector3D rayStart = MyCubeBuilder.IntersectionStart + offset; double castPlaneDistanceToRayStart = DistanceFromCharacterPlane(ref rayStart); rayStart -= castPlaneDistanceToRayStart * MyCubeBuilder.IntersectionDirection; Vector3D rayEnd = MyCubeBuilder.IntersectionStart + (m_dragDistance - castPlaneDistanceToRayStart) * MyCubeBuilder.IntersectionDirection + offset; MatrixD matrix = gridWorlTransform; matrix.Translation = rayStart; try { float? dist = MyPhysics.CastShape(rayEnd, shape, ref matrix, MyPhysics.CollisionLayerWithoutCharacter); if (dist.HasValue && dist.Value != 0f) { Vector3D intersectionPoint = rayStart + dist.Value * (rayEnd - rayStart); const bool debugDraw = true; if (debugDraw) { Color green = Color.Green; BoundingBoxD localAABB = new BoundingBoxD(-halfExt, halfExt); localAABB.Inflate(0.03f); MatrixD drawMatrix = matrix; drawMatrix.Translation = intersectionPoint; MySimpleObjectDraw.DrawTransparentBox(ref drawMatrix, ref localAABB, ref green, MySimpleObjectRasterizer.Wireframe, 1, 0.04f); } double fixedDistance = DistanceFromCharacterPlane(ref intersectionPoint) - castPlaneDistanceToRayStart; if (fixedDistance <= 0) { fixedDistance = 0; shortestDistance = 0; buildAllowed = false; break; } if (fixedDistance < shortestDistance) shortestDistance = fixedDistance; } else { buildAllowed = false; } } finally { shape.RemoveReference(); } } if (shortestDistance != 0 && shortestDistance < m_dragDistance) freePlacementIntersectionPoint = MyCubeBuilder.IntersectionStart + shortestDistance * MyCubeBuilder.IntersectionDirection; else buildAllowed = false; return freePlacementIntersectionPoint; }
private Vector3D GetFreeSpacePlacementPosition(out bool valid) { valid = false; float gridSize = MyDefinitionManager.Static.GetCubeSize(CurrentBlockDefinition.CubeSize); Vector3 halfExt = CurrentBlockDefinition.Size * gridSize * 0.5f; MatrixD matrix = m_gizmo.SpaceDefault.m_worldMatrixAdd; Vector3D rayStart = IntersectionStart; Vector3D rayEnd = FreePlacementTarget; matrix.Translation = rayStart; HkShape shape = new HkBoxShape(halfExt); double distance = double.MaxValue; try { float? dist = MyPhysics.CastShape(rayEnd, shape, ref matrix, MyPhysics.CollisionLayerWithoutCharacter); if (dist.HasValue && dist.Value != 0f) { Vector3D intersectionPoint = rayStart + dist.Value * (rayEnd - rayStart); const bool debugDraw = false; if (debugDraw) { Color green = Color.Green; BoundingBoxD localAABB = new BoundingBoxD(-halfExt, halfExt); MatrixD drawMatrix = matrix; drawMatrix.Translation = intersectionPoint; MySimpleObjectDraw.DrawTransparentBox(ref drawMatrix, ref localAABB, ref green, MySimpleObjectRasterizer.Wireframe, 1, 0.04f); } Vector3D startToIntersection = intersectionPoint - IntersectionStart; distance = startToIntersection.Length(); valid = true; } } finally { shape.RemoveReference(); } float lowLimit = LowLimitDistanceForDynamicMode(); if (distance < lowLimit) { distance = lowLimit; valid = false; } if (distance > IntersectionDistance) { distance = IntersectionDistance; valid = false; } return IntersectionStart + distance * IntersectionDirection; }
public MyCharacterProxy(bool isDynamic, bool isCapsule, float characterWidth, float characterHeight, float crouchHeight, float ladderHeight, float headSize, float headHeight, Vector3 position, Vector3 up, Vector3 forward, float mass, MyPhysicsBody body, bool isOnlyVertical, float maxSlope, float maxImpulse, float maxSpeedRelativeToShip, float?maxForce = null, HkRagdoll ragDoll = null) { m_isDynamic = isDynamic; m_physicsBody = body; m_mass = mass; m_maxImpulse = maxImpulse; m_maxSpeedRelativeToShip = maxSpeedRelativeToShip; if (isCapsule) { m_characterShape = CreateCharacterShape(characterHeight, characterWidth, characterHeight + headHeight, headSize, 0, 0); m_characterCollisionShape = CreateCharacterShape(characterHeight * 0.9f, characterWidth * 0.9f, characterHeight * 0.9f + headHeight, headSize * 0.9f, 0, 0); m_crouchShape = CreateCharacterShape(characterHeight, characterWidth, characterHeight + headHeight, headSize, 0.0f, 1.0f); if (!m_isDynamic) { CharacterPhantom = new HkSimpleShapePhantom(m_characterShape, MyPhysics.CollisionLayers.CharacterCollisionLayer); } } else { HkBoxShape box = new HkBoxShape(new Vector3(characterWidth / 2.0f, characterHeight / 2.0f, characterWidth / 2.0f)); if (!m_isDynamic) { CharacterPhantom = new HkSimpleShapePhantom((HkShape)box, MyPhysics.CollisionLayers.CharacterCollisionLayer); } m_characterShape = box; } if (!m_isDynamic) { HkCharacterProxyCinfo characterProxyInfo = new HkCharacterProxyCinfo(); characterProxyInfo.StaticFriction = 1; characterProxyInfo.DynamicFriction = 1; characterProxyInfo.ExtraDownStaticFriction = 1000; //characterProxyInfo.ContactAngleSensitivity = 20; //characterProxyInfo.KeepContactTolerance = 1f; characterProxyInfo.MaxCharacterSpeedForSolver = 10000; characterProxyInfo.RefreshManifoldInCheckSupport = true; characterProxyInfo.Up = up; characterProxyInfo.Forward = forward; characterProxyInfo.UserPlanes = 4; characterProxyInfo.MaxSlope = MathHelper.ToRadians(maxSlope); characterProxyInfo.Position = position; characterProxyInfo.CharacterMass = mass; characterProxyInfo.CharacterStrength = 100; characterProxyInfo.ShapePhantom = CharacterPhantom; CharacterProxy = new HkCharacterProxy(characterProxyInfo); characterProxyInfo.Dispose(); } else { HkCharacterRigidBodyCinfo characterRBCInfo = new HkCharacterRigidBodyCinfo(); characterRBCInfo.Shape = m_characterShape; characterRBCInfo.CrouchShape = m_crouchShape; characterRBCInfo.Friction = 0; characterRBCInfo.MaxSlope = MathHelper.ToRadians(maxSlope); characterRBCInfo.Up = up; characterRBCInfo.Mass = mass; characterRBCInfo.CollisionFilterInfo = MyPhysics.CollisionLayers.CharacterCollisionLayer; //characterRBCInfo.UnweldingHeightOffsetFactor = 100; characterRBCInfo.MaxLinearVelocity = 1000000; characterRBCInfo.MaxForce = maxForce.HasValue ? maxForce.Value : 100000; characterRBCInfo.AllowedPenetrationDepth = MyFakes.ENABLE_LIMITED_CHARACTER_BODY ? 0.3f : 0.1f; characterRBCInfo.JumpHeight = 0.8f; bool shouldLimitSpeed = Sync.IsServer; float maxCharacterSpeed = shouldLimitSpeed ? (MyGridPhysics.ShipMaxLinearVelocity() + m_maxSpeedRelativeToShip) : MyGridPhysics.MAX_SHIP_SPEED; CharacterRigidBody = new HkCharacterRigidBody(characterRBCInfo, maxCharacterSpeed, body, isOnlyVertical); CharacterRigidBody.GetRigidBody().ContactPointCallbackEnabled = true; CharacterRigidBody.GetRigidBody().ContactPointCallback += RigidBody_ContactPointCallback; CharacterRigidBody.GetRigidBody().ContactPointCallbackDelay = 0; //CharacterRigidBody.GetHitRigidBody().ContactPointCallbackEnabled = true; //CharacterRigidBody.GetHitRigidBody().ContactPointCallback += RigidBody_ContactPointCallback; //CharacterRigidBody.GetHitRigidBody().ContactPointCallbackDelay = 0; //CharacterRigidBody.SetSupportDistance(10); //CharacterRigidBody.SetHardSupportDistance(10); characterRBCInfo.Dispose(); } }
public virtual void CreatePhysicsShape(out HkShape shape, ref HkMassProperties massProperties) { var boxShape = new HkBoxShape(((((MyEntity)Entity).Render.GetModel().BoundingBox.Max - ((MyEntity)Entity).Render.GetModel().BoundingBox.Min) / 2) * Entity.PositionComp.Scale.Value); shape = boxShape; massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(boxShape.HalfExtents, massProperties.Mass); }
/// <summary> /// Casts preview grids aabbs and get shortest distance. Returns shortest intersection or null. /// </summary> protected Vector3D?GetFreeSpacePlacementPositionGridAabbs(bool copyPaste, out bool buildAllowed) { Vector3D?freePlacementIntersectionPoint = null; buildAllowed = true; float gridSize = PreviewGrids[0].GridSize; double shortestDistance = double.MaxValue; double?currentRayInts = MyCubeBuilder.GetCurrentRayIntersection(); if (currentRayInts.HasValue) { shortestDistance = currentRayInts.Value; } Vector3D worldRefPointOffset = Vector3D.Zero; if (copyPaste) { Matrix firstGridOrientation = GetFirstGridOrientationMatrix(); worldRefPointOffset = Vector3.TransformNormal(m_dragPointToPositionLocal, firstGridOrientation); } Vector3D worldRefPoint = PreviewGrids[0].GridIntegerToWorld(Vector3I.Zero); foreach (var grid in PreviewGrids) { Vector3 halfExt = grid.PositionComp.LocalAABB.HalfExtents; Vector3 minLocal = grid.Min * grid.GridSize - Vector3.Half * grid.GridSize; Vector3 maxLocal = grid.Max * grid.GridSize + Vector3.Half * grid.GridSize; MatrixD gridWorlTransform = MatrixD.Identity; gridWorlTransform.Translation = 0.5f * (minLocal + maxLocal); gridWorlTransform = gridWorlTransform * grid.WorldMatrix; Vector3I size = grid.Max - grid.Min + Vector3I.One; Vector3 sizeOffset = Vector3I.Abs((size % 2) - Vector3I.One) * 0.5 * grid.GridSize; sizeOffset = Vector3.TransformNormal(sizeOffset, grid.WorldMatrix); Vector3D offset = gridWorlTransform.Translation + worldRefPointOffset - worldRefPoint /*- sizeOffset*/;// Vector3.Zero;// gridWorlTransform.Translation + worldRefPointOffset - worldRefPoint; HkShape shape = new HkBoxShape(halfExt); Vector3D rayStart = MyCubeBuilder.IntersectionStart + offset; double castPlaneDistanceToRayStart = DistanceFromCharacterPlane(ref rayStart); rayStart -= castPlaneDistanceToRayStart * MyCubeBuilder.IntersectionDirection; Vector3D rayEnd = MyCubeBuilder.IntersectionStart + (m_dragDistance - castPlaneDistanceToRayStart) * MyCubeBuilder.IntersectionDirection + offset; MatrixD matrix = gridWorlTransform; matrix.Translation = rayStart; try { float?dist = MyPhysics.CastShape(rayEnd, shape, ref matrix, MyPhysics.CollisionLayers.CollisionLayerWithoutCharacter); if (dist.HasValue && dist.Value != 0f) { Vector3D intersectionPoint = rayStart + dist.Value * (rayEnd - rayStart); const bool debugDraw = true; if (debugDraw) { Color green = Color.Green; BoundingBoxD localAABB = new BoundingBoxD(-halfExt, halfExt); localAABB.Inflate(0.03f); MatrixD drawMatrix = matrix; drawMatrix.Translation = intersectionPoint; MySimpleObjectDraw.DrawTransparentBox(ref drawMatrix, ref localAABB, ref green, MySimpleObjectRasterizer.Wireframe, 1, 0.04f); } double fixedDistance = DistanceFromCharacterPlane(ref intersectionPoint) - castPlaneDistanceToRayStart; if (fixedDistance <= 0) { fixedDistance = 0; shortestDistance = 0; buildAllowed = false; break; } if (fixedDistance < shortestDistance) { shortestDistance = fixedDistance; } } else { buildAllowed = false; } } finally { shape.RemoveReference(); } } if (shortestDistance != 0 && shortestDistance < m_dragDistance) { freePlacementIntersectionPoint = MyCubeBuilder.IntersectionStart + shortestDistance * MyCubeBuilder.IntersectionDirection; } else { buildAllowed = false; } return(freePlacementIntersectionPoint); }
void CreateBreakableShapeFromCollisionShapes(MyModel model, Vector3 defaultSize, MyPhysicalModelDefinition modelDef) { // Make box half edge length of the grid so fractured block is smaller than not fractured, also good for compounds HkShape shape; if (model.HavokCollisionShapes != null && model.HavokCollisionShapes.Length > 0) { if (model.HavokCollisionShapes.Length > 1) { shape = HkListShape.Create(model.HavokCollisionShapes, model.HavokCollisionShapes.Length, HkReferencePolicy.None); } else { shape = model.HavokCollisionShapes[0]; shape.AddReference(); } } else { //modelDef.Size * (modelDef.CubeSize == MyCubeSize.Large ? 2.5f : 0.25f) shape = new HkBoxShape(defaultSize * 0.5f, MyPerGameSettings.PhysicsConvexRadius); } var boxBreakable = new HkdBreakableShape(shape); boxBreakable.Name = model.AssetName; boxBreakable.SetMass(modelDef.Mass); model.HavokBreakableShapes = new HkdBreakableShape[] { boxBreakable }; shape.RemoveReference(); }
private unsafe void AddPhysicalShape(HkShape shape, Matrix rdWorldMatrix) { switch (shape.ShapeType) { case HkShapeType.Sphere: { HkSphereShape shape7 = (HkSphereShape)shape; m_icosphereMesh.AddTrianglesToWorldVertices(rdWorldMatrix.Translation, shape7.Radius); return; } case HkShapeType.Cylinder: case HkShapeType.Triangle: case HkShapeType.TriSampledHeightFieldCollection: case HkShapeType.TriSampledHeightFieldBvTree: break; case HkShapeType.Box: { HkBoxShape shape2 = (HkBoxShape)shape; Vector3D min = new Vector3D((double)-shape2.HalfExtents.X, (double)-shape2.HalfExtents.Y, (double)-shape2.HalfExtents.Z); Vector3D max = new Vector3D((double)shape2.HalfExtents.X, (double)shape2.HalfExtents.Y, (double)shape2.HalfExtents.Z); BoundingBoxD bbox = new BoundingBoxD(min, max); this.BoundingBoxToTranslatedTriangles(bbox, rdWorldMatrix); return; } case HkShapeType.Capsule: return; case HkShapeType.ConvexVertices: { Vector3 vector; HkConvexVerticesShape shape9 = (HkConvexVerticesShape)shape; HkGeometry geometry = new HkGeometry(); shape9.GetGeometry(geometry, out vector); int triangleIndex = 0; while (true) { int num2; int num3; int num4; int num5; if (triangleIndex >= geometry.TriangleCount) { int vertexIndex = 0; while (true) { if (vertexIndex >= geometry.VertexCount) { WorldVerticesInfo worldVertices = m_worldVertices; worldVertices.VerticesMaxValue += geometry.VertexCount; break; } Vector3 vertex = geometry.GetVertex(vertexIndex); Vector3 *vectorPtr1 = (Vector3 *)ref vertex; Vector3.Transform(ref (Vector3) ref vectorPtr1, ref rdWorldMatrix, out vertex); m_worldVertices.Vertices.Add(vertex); vertexIndex++; } break; } geometry.GetTriangle(triangleIndex, out num2, out num3, out num4, out num5); m_worldVertices.Triangles.Add(m_worldVertices.VerticesMaxValue + num2); m_worldVertices.Triangles.Add(m_worldVertices.VerticesMaxValue + num3); m_worldVertices.Triangles.Add(m_worldVertices.VerticesMaxValue + num4); triangleIndex++; } break; } case HkShapeType.List: { HkShapeContainerIterator iterator = ((HkListShape)shape).GetIterator(); while (iterator.IsValid) { this.AddPhysicalShape(iterator.CurrentValue, rdWorldMatrix); iterator.Next(); } return; } case HkShapeType.Mopp: { HkMoppBvTreeShape shape4 = (HkMoppBvTreeShape)shape; this.AddPhysicalShape((HkShape)shape4.ShapeCollection, rdWorldMatrix); return; } case HkShapeType.ConvexTranslate: { HkConvexTranslateShape shape6 = (HkConvexTranslateShape)shape; Matrix matrix = Matrix.CreateTranslation(shape6.Translation); this.AddPhysicalShape((HkShape)shape6.ChildShape, matrix * rdWorldMatrix); return; } case HkShapeType.ConvexTransform: { HkConvexTransformShape shape5 = (HkConvexTransformShape)shape; this.AddPhysicalShape((HkShape)shape5.ChildShape, shape5.Transform * rdWorldMatrix); return; } default: return; } }
protected Vector3D?GetFreeSpacePlacementPosition(bool copyPaste, out bool buildAllowed) { Vector3D?freePlacementIntersectionPoint = null; buildAllowed = false; float gridSize = PreviewGrids[0].GridSize; double shortestDistance = double.MaxValue; double?currentRayInts = GetCurrentRayIntersection(); if (currentRayInts.HasValue) { shortestDistance = currentRayInts.Value; } Vector3D worldRefPointOffset = Vector3D.Zero; if (copyPaste) { Matrix firstGridOrientation = GetFirstGridOrientationMatrix(); worldRefPointOffset = Vector3.TransformNormal(m_dragPointToPositionLocal, firstGridOrientation); } Vector3D worldRefPoint = PreviewGrids[0].GridIntegerToWorld(Vector3I.Zero); Matrix blockWorlTransform; foreach (var block in PreviewGrids[0].GetBlocks()) { Vector3 halfExt = block.BlockDefinition.Size * PreviewGrids[0].GridSize * 0.5f; Vector3 minLocal = block.Min * PreviewGrids[0].GridSize - Vector3.Half * PreviewGrids[0].GridSize; Vector3 maxLocal = block.Max * PreviewGrids[0].GridSize + Vector3.Half * PreviewGrids[0].GridSize; block.Orientation.GetMatrix(out blockWorlTransform); blockWorlTransform.Translation = 0.5f * (minLocal + maxLocal); blockWorlTransform = blockWorlTransform * PreviewGrids[0].WorldMatrix; Vector3D offset = blockWorlTransform.Translation + worldRefPointOffset - worldRefPoint; HkShape shape = new HkBoxShape(halfExt); Vector3D rayStart = MyCubeBuilder.IntersectionStart + offset; double castPlaneDistanceToRayStart = DistanceFromCharacterPlane(ref rayStart); rayStart -= castPlaneDistanceToRayStart * MyCubeBuilder.IntersectionDirection; Vector3D rayEnd = MyCubeBuilder.IntersectionStart + (m_dragDistance - castPlaneDistanceToRayStart) * MyCubeBuilder.IntersectionDirection + offset; MatrixD matrix = blockWorlTransform; matrix.Translation = rayStart; try { float?dist = MyPhysics.CastShape(rayEnd, shape, ref matrix, MyPhysics.CollisionLayerWithoutCharacter); if (dist.HasValue && dist.Value != 0f) { Vector3D intersectionPoint = rayStart + dist.Value * (rayEnd - rayStart); const bool debugDraw = false; if (debugDraw) { Color green = Color.Green; BoundingBoxD localAABB = new BoundingBoxD(-halfExt, halfExt); MatrixD drawMatrix = matrix; drawMatrix.Translation = intersectionPoint; MySimpleObjectDraw.DrawTransparentBox(ref drawMatrix, ref localAABB, ref green, MySimpleObjectRasterizer.Wireframe, 1, 0.04f); } double fixedDistance = DistanceFromCharacterPlane(ref intersectionPoint) - castPlaneDistanceToRayStart; if (fixedDistance <= 0) { fixedDistance = 0; shortestDistance = 0; break; } if (fixedDistance < shortestDistance) { shortestDistance = fixedDistance; } buildAllowed = true; } } finally { shape.RemoveReference(); } } float boxRadius = (float)PreviewGrids[0].PositionComp.WorldAABB.HalfExtents.Length(); float dragDistance = 1.5f * boxRadius; if (shortestDistance < dragDistance) { shortestDistance = dragDistance; buildAllowed = false; } if (shortestDistance < m_dragDistance) { freePlacementIntersectionPoint = MyCubeBuilder.IntersectionStart + shortestDistance * MyCubeBuilder.IntersectionDirection; } return(freePlacementIntersectionPoint); }
public void GetFracturesInBox(ref BoundingBoxD searchBox, List<MyFracturedPiece> output) { Debug.Assert(m_rigidList.Count == 0); m_rigidList.Clear(); HkShape shape = new HkBoxShape(searchBox.HalfExtents); try { var center = searchBox.Center; MyPhysics.GetPenetrationsShape(shape, ref center, ref Quaternion.Identity, m_rigidList, MyPhysics.CollisionLayers.NotCollideWithStaticLayer); foreach (var rigidBody in m_rigidList) { var fracture = rigidBody.GetCollisionEntity() as MyFracturedPiece; if (fracture != null /*&& m_piecesTimesOfDeath.ContainsKey(fracture)*/) output.Add(fracture); } } finally { m_rigidList.Clear(); shape.RemoveReference(); } }