Crew commands

This commit is contained in:
Regalis
2015-11-26 23:04:02 +02:00
parent f1e1b0b4f0
commit c9cc94f701
19 changed files with 406 additions and 69 deletions
@@ -0,0 +1,60 @@
using System.Xml.Linq;
using FarseerPhysics;
using Microsoft.Xna.Framework;
namespace Barotrauma
{
class AnimController : Ragdoll
{
public enum Animation { None, Climbing, UsingConstruction, Struggle };
public Animation Anim;
public Direction TargetDir;
protected Character character;
protected float walkSpeed, swimSpeed;
//how large impacts the Character can take before being stunned
//protected float impactTolerance;
protected float stunTimer;
protected float walkPos;
protected readonly Vector2 stepSize;
protected readonly float legTorque;
public float StunTimer
{
get { return stunTimer; }
set
{
if (!MathUtils.IsValid(value)) return;
stunTimer = value;
}
}
public AnimController(Character character, XElement element)
: base(character, element)
{
this.character = character;
stepSize = ToolBox.GetAttributeVector2(element, "stepsize", Vector2.One);
stepSize = ConvertUnits.ToSimUnits(stepSize);
//stepOffset = ToolBox.GetAttributeVector2(element, "stepoffset", Vector2.One);
//stepOffset = ConvertUnits.ToSimUnits(stepOffset);
//impactTolerance = ToolBox.GetAttributeFloat(element, "impacttolerance", 10.0f);
legTorque = ToolBox.GetAttributeFloat(element, "legtorque", 0.0f);
}
public virtual void UpdateAnim(float deltaTime) { }
public virtual void HoldItem(float deltaTime, Item item, Vector2[] handlePos, Vector2 holdPos, Vector2 aimPos, bool aim, float holdAngle) { }
public virtual void DragCharacter(Character target) { }
}
}
@@ -0,0 +1,444 @@
using System;
using System.Linq;
using System.Xml.Linq;
using FarseerPhysics;
using FarseerPhysics.Dynamics.Joints;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace Barotrauma
{
class FishAnimController : AnimController
{
//amplitude and wave length of the "sine wave" swimming animation
//if amplitude = 0, sine wave animation isn't used
private float waveAmplitude;
private float waveLength;
private bool rotateTowardsMovement;
private bool flip;
private float flipTimer;
private float? footRotation;
public FishAnimController(Character character, XElement element)
: base(character, element)
{
waveAmplitude = ConvertUnits.ToSimUnits(ToolBox.GetAttributeFloat(element, "waveamplitude", 0.0f));
waveLength = ConvertUnits.ToSimUnits(ToolBox.GetAttributeFloat(element, "wavelength", 0.0f));
flip = ToolBox.GetAttributeBool(element, "flip", false);
walkSpeed = ToolBox.GetAttributeFloat(element, "walkspeed", 1.0f);
swimSpeed = ToolBox.GetAttributeFloat(element, "swimspeed", 1.0f);
float footRot = ToolBox.GetAttributeFloat(element,"footrotation", float.NaN);
if (float.IsNaN(footRot))
{
footRotation = null;
}
else
{
footRotation = MathHelper.ToRadians(footRot);
}
rotateTowardsMovement = ToolBox.GetAttributeBool(element, "rotatetowardsmovement", true);
}
public override void UpdateAnim(float deltaTime)
{
if (character.IsDead)
{
UpdateDying(deltaTime);
return;
}
ResetPullJoints();
if (strongestImpact > 0.0f)
{
stunTimer = MathHelper.Clamp(strongestImpact * 0.5f, stunTimer, 5.0f);
strongestImpact = 0.0f;
}
if (stunTimer>0.0f)
{
//UpdateStruggling(deltaTime);
stunTimer -= deltaTime;
return;
}
else if (SimplePhysicsEnabled)
{
UpdateSimpleAnim();
}
else
{
if (inWater)
{
UpdateSineAnim(deltaTime);
}
else
{
UpdateWalkAnim(deltaTime);
}
}
if (flip)
{
//targetDir = (movement.X > 0.0f) ? Direction.Right : Direction.Left;
if (movement.X > 0.1f && movement.X > Math.Abs(movement.Y)*0.5f)
{
TargetDir = Direction.Right;
}
else if (movement.X < -0.1f && movement.X < -Math.Abs(movement.Y)*0.5f)
{
TargetDir = Direction.Left;
}
}
else
{
Limb head = GetLimb(LimbType.Head);
float rotation = MathUtils.WrapAngleTwoPi(head.Rotation);
rotation = MathHelper.ToDegrees(rotation);
if (rotation < 0.0f) rotation += 360;
if (rotation > 20 && rotation < 160)
{
TargetDir = Direction.Left;
}
else if (rotation > 200 && rotation < 340)
{
TargetDir = Direction.Right;
}
}
//if (stunTimer > gameTime.TotalGameTime.TotalMilliseconds) return;
flipTimer += deltaTime;
if (TargetDir != dir)
{
if (flipTimer>1.0f)
{
Flip();
if (flip) Mirror();
flipTimer = 0.0f;
}
}
}
void UpdateSineAnim(float deltaTime)
{
movement = TargetMovement*swimSpeed;
if (movement.LengthSquared() < 0.00001f) return;
if (!inWater) movement.Y = Math.Min(0.0f, movement.Y);
float movementAngle = MathUtils.VectorToAngle(movement) - MathHelper.PiOver2;
Limb tail = GetLimb(LimbType.Tail);
if (tail != null && waveAmplitude > 0.0f)
{
walkPos -= movement.Length();
float waveRotation = (float)Math.Sin(walkPos / waveLength) * waveAmplitude;
float angle = MathUtils.GetShortestAngle(tail.body.Rotation, movementAngle + waveRotation);
tail.body.ApplyTorque(angle * tail.Mass);
//limbs[tailIndex].body.ApplyTorque((Math.Sign(angle) + Math.Max(Math.Min(angle * 10.0f, 10.0f), -10.0f)) * limbs[tailIndex].body.Mass);
//limbs[tailIndex].body.ApplyTorque(-limbs[tailIndex].body.AngularVelocity * 0.5f * limbs[tailIndex].body.Mass);
}
Vector2 steerForce = Vector2.Zero;
Limb head = GetLimb(LimbType.Head);
if (head != null)
{
float angle = (rotateTowardsMovement) ?
head.body.Rotation+ MathUtils.GetShortestAngle(head.body.Rotation, movementAngle) :
HeadAngle*Dir;
head.body.SmoothRotate(angle, 25.0f);
//rotate head towards the angle of movement
//float torque = (Math.Sign(angle)*10.0f + MathHelper.Clamp(angle * 10.0f, -10.0f, 10.0f));
//angular drag
//torque -= head.body.AngularVelocity * 0.5f;
//head.body.ApplyTorque(torque * head.body.Mass);
//the movement vector if going to the direction of the head
//Vector2 headMovement = new Vector2(
// (float)Math.Cos(head.body.Rotation - MathHelper.PiOver2),
// (float)Math.Sin(head.body.Rotation - MathHelper.PiOver2));
//headMovement *= movement.Length();
//the movement angle is between direction of the head and the direction
//where the Character is actually trying to go
//current * (float)alpha + previous * (1.0f - (float)alpha);
steerForce = (movement+correctionMovement) * 50.0f - head.LinearVelocity * 30.0f;
// force += (headMovement - movement) * Math.Min(head.LinearVelocity.Length()/movement.Length(), 1.0f);
if (!inWater) steerForce.Y = 0.0f;
}
for (int i = 0; i < Limbs.Count(); i++)
{
if (steerForce!=Vector2.Zero)
Limbs[i].body.ApplyForce(steerForce * Limbs[i].SteerForce * Limbs[i].Mass);
if (Limbs[i].type != LimbType.Torso) continue;
float dist = (Limbs[0].SimPosition - Limbs[i].SimPosition).Length();
Vector2 limbPos = Limbs[0].SimPosition - Vector2.Normalize(movement) * dist;
Limbs[i].body.ApplyForce(((limbPos - Limbs[i].SimPosition) * 3.0f - Limbs[i].LinearVelocity * 3.0f) * Limbs[i].Mass);
}
if (!inWater)
{
UpdateWalkAnim(deltaTime);
}
else
{
floorY = Limbs[0].SimPosition.Y;
}
}
void UpdateSimpleAnim()
{
movement = MathUtils.SmoothStep(movement, TargetMovement*swimSpeed, 1.0f);
if (movement == Vector2.Zero) return;
float movementAngle = MathUtils.VectorToAngle(movement) - MathHelper.PiOver2;
RefLimb.body.SmoothRotate(
(rotateTowardsMovement) ?
RefLimb.body.Rotation + MathUtils.GetShortestAngle(RefLimb.body.Rotation, movementAngle) :
HeadAngle*Dir);
RefLimb.body.LinearVelocity = movement;
//RefLimb.body.SmoothRotate(0.0f);
foreach (Limb l in Limbs)
{
if (l == RefLimb) continue;
l.body.SetTransform(RefLimb.SimPosition, RefLimb.Rotation);
}
}
void UpdateWalkAnim(float deltaTime)
{
movement = MathUtils.SmoothStep(movement, TargetMovement * walkSpeed, 0.2f);
if (movement == Vector2.Zero) return;
IgnorePlatforms = (TargetMovement.Y < -Math.Abs(TargetMovement.X));
Limb colliderLimb;
float colliderHeight;
Limb torso = GetLimb(LimbType.Torso);
Limb head = GetLimb(LimbType.Head);
if (torso != null)
{
colliderLimb = torso;
colliderHeight = TorsoPosition;
colliderLimb.body.SmoothRotate(TorsoAngle * Dir, 10.0f);
}
else
{
colliderLimb = head;
colliderHeight = HeadPosition;
if (onGround) colliderLimb.body.SmoothRotate(HeadAngle * Dir, 100.0f);
}
Vector2 colliderPos = colliderLimb.SimPosition;
Vector2 rayStart = colliderPos;
Vector2 rayEnd = rayStart - new Vector2(0.0f, colliderHeight);
if (stairs != null) rayEnd.Y -= 0.5f;
//do a raytrace straight down from the torso to figure
//out whether the ragdoll is standing on ground
float closestFraction = 1;
//Structure closestStructure = null;
GameMain.World.RayCast((fixture, point, normal, fraction) =>
{
//other limbs and bodies with no collision detection are ignored
if (fixture == null ||
fixture.CollisionCategories == Physics.CollisionCharacter ||
fixture.CollisionCategories == Physics.CollisionNone ||
fixture.CollisionCategories == Physics.CollisionMisc) return -1;
Structure structure = fixture.Body.UserData as Structure;
if (structure != null)
{
if (structure.StairDirection != Direction.None && (stairs == null)) return -1;
if (structure.IsPlatform && (IgnorePlatforms || stairs != null)) return -1;
}
onGround = true;
onFloorTimer = 0.05f;
if (fraction < closestFraction) closestFraction = fraction;
return 1;
}
, rayStart, rayEnd);
//the ragdoll "stays on ground" for 50 millisecs after separation
if (onFloorTimer <= 0.0f)
{
onGround = false;
}
else
{
onFloorTimer -= deltaTime;
}
if (!onGround) return;
if (closestFraction == 1) //raycast didn't hit anything
floorY = (currentHull == null) ? -1000.0f : ConvertUnits.ToSimUnits(currentHull.Rect.Y - currentHull.Rect.Height);
else
floorY = rayStart.Y + (rayEnd.Y - rayStart.Y) * closestFraction;
if (Math.Abs(colliderPos.Y - floorY) < colliderHeight * 1.2f)
{
colliderLimb.Move(new Vector2(colliderPos.X + movement.X * 0.2f, floorY + colliderHeight), 5.0f);
}
float walkCycleSpeed = head.LinearVelocity.X * 0.05f;
walkPos -= walkCycleSpeed;
Vector2 transformedStepSize = new Vector2(
(float)Math.Cos(walkPos) * stepSize.X * 3.0f,
(float)Math.Sin(walkPos) * stepSize.Y * 2.0f);
foreach (Limb limb in Limbs)
{
switch (limb.type)
{
case LimbType.LeftFoot:
case LimbType.RightFoot:
Vector2 footPos = new Vector2(limb.SimPosition.X, colliderPos.Y - colliderHeight);
if (limb.RefJointIndex>-1)
{
RevoluteJoint refJoint = limbJoints[limb.RefJointIndex];
footPos.X = refJoint.WorldAnchorA.X;
}
footPos.X += limb.StepOffset.X * Dir;
footPos.Y += limb.StepOffset.Y;
if (limb.type == LimbType.LeftFoot)
{
limb.Move(footPos +new Vector2(
transformedStepSize.X + movement.X * 0.1f,
(transformedStepSize.Y > 0.0f) ? transformedStepSize.Y : 0.0f),
8.0f);
}
else if (limb.type == LimbType.RightFoot)
{
limb.Move(footPos +new Vector2(
-transformedStepSize.X + movement.X * 0.1f,
(-transformedStepSize.Y > 0.0f) ? -transformedStepSize.Y : 0.0f),
8.0f);
}
if (footRotation!=null) limb.body.SmoothRotate((float)footRotation*Dir, 50.0f);
break;
case LimbType.LeftLeg:
case LimbType.RightLeg:
if (legTorque!=0.0f) limb.body.ApplyTorque(limb.Mass*legTorque*Dir);
break;
}
}
}
void UpdateDying(float deltaTime)
{
Limb head = GetLimb(LimbType.Head);
Limb tail = GetLimb(LimbType.Tail);
if (head != null) head.body.ApplyTorque(head.Mass * Dir * (float)Math.Sin(walkPos) * 5.0f);
if (tail != null) tail.body.ApplyTorque(tail.Mass * -Dir * (float)Math.Sin(walkPos) * 5.0f);
walkPos += deltaTime * 5.0f;
Vector2 centerOfMass = GetCenterOfMass();
foreach (Limb limb in Limbs)
{
if (limb.type == LimbType.Head || limb.type == LimbType.Tail) continue;
limb.body.ApplyForce((centerOfMass - limb.SimPosition) * (float)Math.Sin(walkPos) * limb.Mass * 10.0f);
}
}
public override void Flip()
{
base.Flip();
foreach (Limb l in Limbs)
{
if (!l.DoesFlip) continue;
l.body.SetTransform(l.SimPosition,
-l.body.Rotation);
}
}
private void Mirror()
{
float leftX = Limbs[0].SimPosition.X, rightX = Limbs[0].SimPosition.X;
for (int i = 1; i < Limbs.Count(); i++ )
{
if (Limbs[i].SimPosition.X < leftX)
{
leftX = Limbs[i].SimPosition.X;
}
else if (Limbs[i].SimPosition.X > rightX)
{
rightX = Limbs[i].SimPosition.X;
}
}
float midX = GetCenterOfMass().X;
foreach (Limb l in Limbs)
{
Vector2 newPos = new Vector2(midX - (l.SimPosition.X - midX), l.SimPosition.Y);
if (Submarine.CheckVisibility(l.SimPosition, newPos)!=null)
{
Vector2 diff = newPos - l.SimPosition;
l.body.SetTransform(
l.SimPosition + Submarine.LastPickedFraction * diff * 0.8f, l.body.Rotation);
}
else
{
l.body.SetTransform(newPos, l.body.Rotation);
}
}
}
}
}
@@ -0,0 +1,974 @@
using System;
using System.Linq;
using System.Xml.Linq;
using FarseerPhysics;
using Microsoft.Xna.Framework;
using Barotrauma.Items.Components;
namespace Barotrauma
{
class HumanoidAnimController : AnimController
{
private bool aiming;
private float walkAnimSpeed;
private float movementLerp;
private float thighTorque;
public HumanoidAnimController(Character character, XElement element)
: base(character, element)
{
walkAnimSpeed = ToolBox.GetAttributeFloat(element, "walkanimspeed", 4.0f);
walkAnimSpeed = MathHelper.ToRadians(walkAnimSpeed);
movementLerp = ToolBox.GetAttributeFloat(element, "movementlerp", 0.4f);
thighTorque = ToolBox.GetAttributeFloat(element, "thightorque", -5.0f);
}
public override void UpdateAnim(float deltaTime)
{
if (character.IsDead) return;
Vector2 colliderPos = GetLimb(LimbType.Torso).SimPosition;
//if (inWater) stairs = null;
if (onFloorTimer <= 0.0f && !SimplePhysicsEnabled)
{
Vector2 rayStart = colliderPos; // at the bottom of the player sprite
Vector2 rayEnd = rayStart - new Vector2(0.0f, TorsoPosition);
if (stairs != null) rayEnd.Y -= 0.5f;
//do a raytrace straight down from the torso to figure
//out whether the ragdoll is standing on ground
float closestFraction = 1;
Structure closestStructure = null;
GameMain.World.RayCast((fixture, point, normal, fraction) =>
{
switch (fixture.CollisionCategories)
{
case Physics.CollisionStairs:
if (inWater && TargetMovement.Y < 0.5f) return -1;
Structure structure = fixture.Body.UserData as Structure;
if (stairs == null && structure != null)
{
if (LowestLimb.SimPosition.Y < structure.SimPosition.Y)
{
return -1;
}
else
{
stairs = structure;
}
}
break;
case Physics.CollisionPlatform:
Structure platform = fixture.Body.UserData as Structure;
if (IgnorePlatforms || LowestLimb.Position.Y < platform.Rect.Y) return -1;
break;
case Physics.CollisionWall:
break;
default:
return -1;
}
onGround = true;
if (fraction < closestFraction)
{
closestFraction = fraction;
Structure structure = fixture.Body.UserData as Structure;
if (structure != null) closestStructure = structure;
}
onFloorTimer = 0.05f;
return closestFraction;
}
, rayStart, rayEnd);
if (closestStructure != null && closestStructure.StairDirection != Direction.None)
{
stairs = closestStructure;
}
else
{
stairs = null;
}
if (closestFraction == 1) //raycast didn't hit anything
{
floorY = (currentHull == null) ? -1000.0f : ConvertUnits.ToSimUnits(currentHull.Rect.Y - currentHull.Rect.Height);
}
else
{
floorY = rayStart.Y + (rayEnd.Y - rayStart.Y) * closestFraction;
}
}
//the ragdoll "stays on ground" for 50 millisecs after separation
if (onFloorTimer <= 0.0f)
{
onGround = false;
if (GetLimb(LimbType.Torso).inWater) inWater = true;
//TODO: joku järkevämpi systeemi
//if (!inWater && lastTimeOnFloor + 200 < gameTime.TotalGameTime.Milliseconds)
// stunTimer = Math.Max(stunTimer, (float)gameTime.TotalGameTime.TotalMilliseconds + 100.0f);
}
else
{
onFloorTimer -= deltaTime;
}
//stun (= disable the animations) if the ragdoll receives a large enough impact
if (strongestImpact > 0.0f)
{
character.StartStun(MathHelper.Min(strongestImpact * 0.5f, 5.0f));
}
strongestImpact = 0.0f;
if (stunTimer > 0)
{
stunTimer -= deltaTime;
return;
}
if (Anim != Animation.UsingConstruction) ResetPullJoints();
if (TargetDir != dir) Flip();
if (SimplePhysicsEnabled)
{
UpdateStandingSimple();
return;
}
switch (Anim)
{
case Animation.Climbing:
UpdateClimbing();
break;
case Animation.UsingConstruction:
break;
default:
if (inWater)
UpdateSwimming();
else
UpdateStanding();
break;
}
foreach (Limb limb in Limbs)
{
limb.Disabled = false;
}
aiming = false;
}
void UpdateStanding()
{
Vector2 handPos;
//if you're allergic to magic numbers, stop reading now
Limb leftFoot = GetLimb(LimbType.LeftFoot);
Limb rightFoot = GetLimb(LimbType.RightFoot);
Limb head = GetLimb(LimbType.Head);
Limb torso = GetLimb(LimbType.Torso);
Limb waist = GetLimb(LimbType.Waist);
Limb leftHand = GetLimb(LimbType.LeftHand);
Limb rightHand = GetLimb(LimbType.RightHand);
Limb leftLeg = GetLimb(LimbType.LeftLeg);
Limb rightLeg = GetLimb(LimbType.RightLeg);
if (character.SelectedCharacter != null) DragCharacter(character.SelectedCharacter);
float getUpSpeed = 0.3f;
float walkCycleSpeed = head.LinearVelocity.X * walkAnimSpeed;
if (stairs != null)
{
TargetMovement = new Vector2(MathHelper.Clamp(TargetMovement.X, -1.5f, 1.5f), TargetMovement.Y);
if ((TargetMovement.X > 0.0f && stairs.StairDirection == Direction.Right) ||
TargetMovement.X < 0.0f && stairs.StairDirection == Direction.Left)
{
TargetMovement *= 1.7f;
walkCycleSpeed *= 1.7f;
}
else
{
TargetMovement /= 1.0f;
walkCycleSpeed *= 1.5f;
}
}
Vector2 colliderPos = new Vector2(torso.SimPosition.X, floorY);
float walkPosX = (float)Math.Cos(walkPos);
float walkPosY = (float)Math.Sin(walkPos);
float runningModifier = (float)Math.Max(Math.Min(Math.Abs(TargetMovement.X),3.0f) / 1.5f, 1.0);
Vector2 stepSize = new Vector2(
this.stepSize.X * walkPosX * runningModifier,
this.stepSize.Y * walkPosY * runningModifier * runningModifier);
float footMid = waist.SimPosition.X;// (leftFoot.SimPosition.X + rightFoot.SimPosition.X) / 2.0f;
if (Math.Abs(TargetMovement.X)>1.0f)
{
int limbsInWater = 0;
foreach (Limb limb in Limbs)
{
if (limb.inWater) limbsInWater++;
}
float slowdownFactor = (float)limbsInWater / (float)Limbs.Count();
TargetMovement = Vector2.Normalize(TargetMovement) * Math.Max(TargetMovement.Length() - slowdownFactor, 1.0f);
}
movement = MathUtils.SmoothStep(movement, TargetMovement, movementLerp);
movement.Y = 0.0f;
bool legsUp = false;
for (int i = 0; i < 2; i++)
{
Limb leg = GetLimb((i == 0) ? LimbType.LeftThigh : LimbType.RightThigh);// : leftLeg;
if (leg.SimPosition.Y < torso.SimPosition.Y) continue;
leg.body.ApplyTorque(Dir * leg.Mass * 10.0f);
legsUp = true;
}
if (legsUp || LowestLimb == null) return;
if (!onGround || (LowestLimb.SimPosition.Y - floorY > 0.5f && stairs == null)) return;
getUpSpeed = getUpSpeed * Math.Max(head.SimPosition.Y - colliderPos.Y, 0.1f);
if (stairs != null)
{
if (LowestLimb.SimPosition.Y < stairs.SimPosition.Y) IgnorePlatforms = true;
torso.pullJoint.Enabled = true;
torso.pullJoint.WorldAnchorB = new Vector2(
MathHelper.SmoothStep(torso.SimPosition.X, footMid + movement.X * 0.35f, getUpSpeed * 0.8f),
MathHelper.SmoothStep(torso.SimPosition.Y, colliderPos.Y + TorsoPosition - Math.Abs(walkPosX * 0.05f), getUpSpeed * 2.0f));
head.pullJoint.Enabled = true;
head.pullJoint.WorldAnchorB = new Vector2(
MathHelper.SmoothStep(head.SimPosition.X, footMid + movement.X * 0.4f, getUpSpeed * 0.8f),
MathHelper.SmoothStep(head.SimPosition.Y, colliderPos.Y + HeadPosition - Math.Abs(walkPosX * 0.05f), getUpSpeed * 2.0f));
waist.pullJoint.Enabled = true;
waist.pullJoint.WorldAnchorB = waist.SimPosition;// +movement * 0.3f;
}
else
{
torso.pullJoint.Enabled = true;
torso.pullJoint.WorldAnchorB =
MathUtils.SmoothStep(torso.SimPosition,
new Vector2(footMid + movement.X * 0.3f, colliderPos.Y + TorsoPosition), getUpSpeed);
head.pullJoint.Enabled = true;
head.pullJoint.WorldAnchorB =
MathUtils.SmoothStep(head.SimPosition,
new Vector2(footMid + movement.X * 0.3f, colliderPos.Y + HeadPosition), getUpSpeed*1.2f);
waist.pullJoint.Enabled = true;
waist.pullJoint.WorldAnchorB = waist.SimPosition + movement * 0.1f;
//MathUtils.SmoothStep(waist.SimPosition,
//new Vector2(footMid + movement.X * 0.4f, colliderPos.Y + HeadPosition), getUpSpeed);
}
//moving horizontally
if (TargetMovement.X != 0.0f)
{
//progress the walking animation
walkPos -= (walkCycleSpeed / runningModifier) * 0.8f;
MoveLimb(leftFoot,
colliderPos + new Vector2(
stepSize.X,
(stepSize.Y > 0.0f) ? stepSize.Y : -0.15f),
15.0f, true);
MoveLimb(rightFoot,
colliderPos + new Vector2(
-stepSize.X,
(-stepSize.Y > 0.0f) ? -stepSize.Y : -0.15f),
15.0f, true);
leftFoot.body.SmoothRotate(leftLeg.body.Rotation + MathHelper.PiOver2 * Dir * 1.6f, 20.0f * runningModifier);
rightFoot.body.SmoothRotate(rightLeg.body.Rotation + MathHelper.PiOver2 * Dir * 1.6f, 20.0f * runningModifier);
if (runningModifier > 1.0f)
{
if (walkPosY > 0.0f)
{
GetLimb(LimbType.LeftThigh).body.ApplyTorque(-walkPosY * Dir * Math.Abs(movement.X) * thighTorque);
}
else
{
GetLimb(LimbType.RightThigh).body.ApplyTorque(walkPosY * Dir * Math.Abs(movement.X) * thighTorque);
}
}
if (legTorque > 0.0f)
{
if (Math.Sign(walkPosX) != Math.Sign(movement.X))
{
GetLimb(LimbType.LeftLeg).body.ApplyTorque(-walkPosY * Dir * Math.Abs(movement.X) * legTorque / runningModifier);
}
else
{
GetLimb(LimbType.RightLeg).body.ApplyTorque(walkPosY * Dir * Math.Abs(movement.X) * legTorque / runningModifier);
}
}
//calculate the positions of hands
handPos = torso.SimPosition;
handPos.X = -walkPosX * 0.4f;
float lowerY = -1.0f + (runningModifier - 1.0f) * 0.8f;
handPos.Y = lowerY + (float)(Math.Abs(Math.Sin(walkPos - Math.PI * 1.5f) * 0.15 * runningModifier));
Vector2 posAddition = new Vector2(-movement.X * 0.015f * runningModifier, 0.0f);
if (!rightHand.Disabled)
{
HandIK(rightHand, torso.SimPosition + posAddition +
new Vector2(
-handPos.X,
(Math.Sign(walkPosX) == Math.Sign(Dir)) ? handPos.Y : lowerY), 0.7f*runningModifier);
}
if (!leftHand.Disabled)
{
HandIK(leftHand, torso.SimPosition + posAddition +
new Vector2(
handPos.X,
(Math.Sign(walkPosX) == Math.Sign(-Dir)) ? handPos.Y : lowerY), 0.7f * runningModifier);
}
}
else
{
float movementFactor = (movement.X / 4.0f) * movement.X * Math.Sign(movement.X);
Vector2 footPos = new Vector2(
colliderPos.X,
colliderPos.Y - 0.2f);
MoveLimb(leftFoot, footPos, 2.5f);
MoveLimb(rightFoot, footPos, 2.5f);
leftFoot.body.SmoothRotate(Dir * MathHelper.PiOver2, 5.0f);
rightFoot.body.SmoothRotate(Dir * MathHelper.PiOver2, 5.0f);
if (!rightHand.Disabled)
{
rightHand.body.SmoothRotate(0.0f, 5.0f);
var rightArm = GetLimb(LimbType.RightArm);
rightArm.body.SmoothRotate(0.0f, 20.0f);
}
if (!leftHand.Disabled)
{
leftHand.body.SmoothRotate(0.0f, 5.0f);
var leftArm = GetLimb(LimbType.LeftArm);
leftArm.body.SmoothRotate(0.0f, 20.0f);
}
}
}
void UpdateStandingSimple()
{
movement = MathUtils.SmoothStep(movement, TargetMovement, movementLerp);
if (inWater && movement.LengthSquared() > 0.00001f)
{
movement = Vector2.Normalize(movement);
}
RefLimb.pullJoint.Enabled = true;
RefLimb.pullJoint.WorldAnchorB =
RefLimb.SimPosition + movement * 0.15f;
RefLimb.body.SmoothRotate(0.0f);
foreach (Limb l in Limbs)
{
if (l == RefLimb) continue;
l.body.SetTransform(RefLimb.SimPosition, RefLimb.Rotation);
}
//new Vector2(movement.X, floorY + HeadPosition), 0.5f);
}
void UpdateSwimming()
{
IgnorePlatforms = true;
Vector2 footPos, handPos;
float surfaceLimiter = 1.0f;
Limb head = GetLimb(LimbType.Head);
if (currentHull != null && (currentHull.Rect.Y - currentHull.Surface > 50.0f) && !head.inWater)
{
surfaceLimiter = (ConvertUnits.ToDisplayUnits(head.SimPosition.Y) - surfaceY);
surfaceLimiter = Math.Max(1.0f, surfaceLimiter);
if (surfaceLimiter > 20.0f) return;
}
Limb torso = GetLimb(LimbType.Torso);
Limb leftHand = GetLimb(LimbType.LeftHand);
Limb rightHand = GetLimb(LimbType.RightHand);
Limb leftFoot = GetLimb(LimbType.LeftFoot);
Limb rightFoot = GetLimb(LimbType.RightFoot);
Limb leftLeg = GetLimb(LimbType.LeftLeg);
Limb rightLeg = GetLimb(LimbType.RightLeg);
float rotation = MathHelper.WrapAngle(torso.Rotation);
rotation = MathHelper.ToDegrees(rotation);
if (rotation < 0.0f) rotation += 360;
if (!character.IsNetworkPlayer && !aiming)
{
if (rotation > 20 && rotation < 170)
TargetDir = Direction.Left;
else if (rotation > 190 && rotation < 340)
TargetDir = Direction.Right;
}
float targetSpeed = TargetMovement.Length();
if (targetSpeed > 0.0f) TargetMovement /= targetSpeed;
if (targetSpeed > 0.1f)
{
if (!aiming)
{
torso.body.SmoothRotate(MathUtils.VectorToAngle(TargetMovement) - MathHelper.PiOver2);
}
}
else
{
if (aiming)
{
Vector2 mousePos = ConvertUnits.ToSimUnits(character.CursorPosition);
Vector2 diff = (mousePos - torso.SimPosition) * Dir;
TargetMovement = new Vector2(0.0f, -0.1f);
torso.body.SmoothRotate(MathUtils.VectorToAngle(diff));
}
}
if (TargetMovement == Vector2.Zero) return;
movement = MathUtils.SmoothStep(movement, TargetMovement, 0.3f);
//dont try to move upwards if head is already out of water
if (surfaceLimiter > 1.0f && TargetMovement.Y > 0.0f)
{
if (TargetMovement.X == 0.0f)
{
head.body.ApplyForce(head.Mass * new Vector2(-Dir * 5.1f, -5.0f));
torso.body.ApplyForce(torso.Mass * new Vector2(-Dir * 5.1f, -15.0f));
leftFoot.body.ApplyForce(leftFoot.Mass * new Vector2(0.0f, -80.0f));
rightFoot.body.ApplyForce(rightFoot.Mass * new Vector2(0.0f, -80.0f));
}
else
{
TargetMovement = new Vector2(
(float)Math.Sqrt(targetSpeed * targetSpeed - TargetMovement.Y * TargetMovement.Y)
* Math.Sign(TargetMovement.X),
Math.Max(TargetMovement.Y, TargetMovement.Y * 0.2f));
head.body.ApplyTorque(Dir * 0.1f);
}
movement.Y = movement.Y - (surfaceLimiter - 1.0f) * 0.01f;
}
movement.Y -= 0.05f;
head.body.ApplyForce((new Vector2(movement.X,
movement.Y / surfaceLimiter + 0.2f) - head.body.LinearVelocity * 0.2f) *
30.0f * head.body.Mass);
torso.body.ApplyForce((new Vector2(movement.X,
movement.Y / surfaceLimiter + 0.2f) - torso.body.LinearVelocity * 0.2f) * 10.0f * torso.body.Mass);
walkPos += movement.Length() * 0.15f;
footPos = (leftFoot.SimPosition + rightFoot.SimPosition) / 2.0f;
var rightThigh = GetLimb(LimbType.RightThigh);
var leftThigh = GetLimb(LimbType.LeftThigh);
rightThigh.body.SmoothRotate(torso.Rotation + (float)Math.Sin(walkPos) * 0.3f, 2.0f);
leftThigh.body.SmoothRotate(torso.Rotation - (float)Math.Sin(walkPos) * 0.3f, 2.0f);
Vector2 transformedFootPos = new Vector2((float)Math.Sin(walkPos) * 0.5f, 0.0f);
transformedFootPos = Vector2.Transform(
transformedFootPos,
Matrix.CreateRotationZ(torso.body.Rotation));
if (Math.Abs(MathUtils.GetShortestAngle(torso.Rotation, rightThigh.Rotation)) < 0.3f)
{
MoveLimb(rightFoot, footPos - transformedFootPos, 1.0f);
}
if (Math.Abs(MathUtils.GetShortestAngle(torso.Rotation, leftThigh.Rotation)) < 0.3f)
{
MoveLimb(leftFoot, footPos + transformedFootPos, 1.0f);
}
handPos = (torso.SimPosition + head.SimPosition) / 2.0f;
//if (!rightHand.Disabled) rightHand.body.ApplyTorque(leftHand.body.Mass * Dir);
//if (!leftHand.Disabled) leftHand.body.ApplyTorque(leftHand.body.Mass * Dir);
//at the surface, not moving sideways -> hands just float around
if (!headInWater && TargetMovement.X == 0.0f && TargetMovement.Y > 0)
{
handPos.X = handPos.X + Dir * 0.6f;
float wobbleAmount = 0.05f;
if (!rightHand.Disabled)
{
MoveLimb(rightHand, new Vector2(
handPos.X + (float)Math.Sin(walkPos / 1.5f) * wobbleAmount,
handPos.Y + (float)Math.Sin(walkPos / 3.5f) * wobbleAmount - 0.0f), 1.5f);
}
if (!leftHand.Disabled)
{
MoveLimb(leftHand, new Vector2(
handPos.X + (float)Math.Sin(walkPos / 2.0f) * wobbleAmount,
handPos.Y + (float)Math.Sin(walkPos / 3.0f) * wobbleAmount - 0.0f), 1.5f);
}
return;
}
handPos += head.LinearVelocity * 0.1f;
float handCyclePos = walkPos / 2.0f;
float handPosX = (float)Math.Cos(handCyclePos * Dir) * 0.4f;
float handPosY = (float)Math.Sin(handCyclePos) * 1.0f;
handPosY = MathHelper.Clamp(handPosY, -0.8f, 0.8f);
Matrix rotationMatrix = Matrix.CreateRotationZ(torso.Rotation);
if (!rightHand.Disabled)
{
Vector2 rightHandPos = new Vector2(-handPosX, -handPosY);
rightHandPos.X = (Dir == 1.0f) ? Math.Max(0.2f, rightHandPos.X) : Math.Min(-0.2f, rightHandPos.X);
rightHandPos = Vector2.Transform(rightHandPos, rotationMatrix);
//MoveLimb(rightHand, handPos + rightHandPos, 1.5f);
HandIK(rightHand, handPos + rightHandPos, 0.5f);
}
if (!leftHand.Disabled)
{
Vector2 leftHandPos = new Vector2(handPosX, handPosY);
leftHandPos.X = (Dir == 1.0f) ? Math.Max(0.2f, leftHandPos.X) : Math.Min(-0.2f, leftHandPos.X);
leftHandPos = Vector2.Transform(leftHandPos, rotationMatrix);
//MoveLimb(leftHand, handPos + leftHandPos,1.5f);
HandIK(leftHand, handPos + leftHandPos, 0.5f);
}
}
void UpdateClimbing()
{
if (character.SelectedConstruction == null || character.SelectedConstruction.GetComponent<Ladder>() == null)
{
Anim = Animation.None;
return;
}
onGround = false;
IgnorePlatforms = true;
movement = MathUtils.SmoothStep(movement, TargetMovement, 0.3f);
Vector2 footPos, handPos;
Limb leftFoot = GetLimb(LimbType.LeftFoot);
Limb rightFoot = GetLimb(LimbType.RightFoot);
Limb head = GetLimb(LimbType.Head);
Limb torso = GetLimb(LimbType.Torso);
Limb waist = GetLimb(LimbType.Waist);
Limb leftHand = GetLimb(LimbType.LeftHand);
Limb rightHand = GetLimb(LimbType.RightHand);
Vector2 ladderSimPos = ConvertUnits.ToSimUnits(
character.SelectedConstruction.Rect.X + character.SelectedConstruction.Rect.Width / 2.0f,
character.SelectedConstruction.Rect.Y);
MoveLimb(head, new Vector2(ladderSimPos.X - 0.27f * Dir, head.SimPosition.Y + 0.05f), 10.5f);
MoveLimb(torso, new Vector2(ladderSimPos.X - 0.27f * Dir, torso.SimPosition.Y), 10.5f);
MoveLimb(waist, new Vector2(ladderSimPos.X - 0.35f * Dir, waist.SimPosition.Y), 10.5f);
float stepHeight = ConvertUnits.ToSimUnits(30.0f);
handPos = new Vector2(
ladderSimPos.X,
head.SimPosition.Y + 0.0f + movement.Y * 0.1f - ladderSimPos.Y);
MoveLimb(leftHand,
new Vector2(handPos.X,
MathUtils.Round(handPos.Y - stepHeight, stepHeight * 2.0f) + stepHeight + ladderSimPos.Y),
5.2f);
MoveLimb(rightHand,
new Vector2(handPos.X,
MathUtils.Round(handPos.Y, stepHeight * 2.0f) + ladderSimPos.Y),
5.2f);
leftHand.body.ApplyTorque(Dir * 2.0f);
rightHand.body.ApplyTorque(Dir * 2.0f);
footPos = new Vector2(
handPos.X - Dir * 0.05f,
head.SimPosition.Y - stepHeight * 2.7f - ladderSimPos.Y - 0.7f);
//if (movement.Y < 0) footPos.Y += 0.05f;
MoveLimb(leftFoot,
new Vector2(footPos.X,
MathUtils.Round(footPos.Y + stepHeight, stepHeight * 2.0f) - stepHeight + ladderSimPos.Y),
15.5f, true);
MoveLimb(rightFoot,
new Vector2(footPos.X,
MathUtils.Round(footPos.Y, stepHeight * 2.0f) + ladderSimPos.Y),
15.5f, true);
//apply torque to the legs to make the knees bend
Limb leftLeg = GetLimb(LimbType.LeftLeg);
Limb rightLeg = GetLimb(LimbType.RightLeg);
leftLeg.body.ApplyTorque(Dir * -8.0f);
rightLeg.body.ApplyTorque(Dir * -8.0f);
//apply forces to the head and the torso to move the Character up/down
float movementFactor = (handPos.Y / stepHeight) * (float)Math.PI;
movementFactor = 0.8f + (float)Math.Abs(Math.Sin(movementFactor));
Vector2 climbForce = new Vector2(0.0f, movement.Y + 0.4f) * movementFactor;
torso.body.ApplyForce(climbForce * 40.0f * torso.Mass);
head.body.SmoothRotate(0.0f);
Rectangle trigger = character.SelectedConstruction.Prefab.Triggers.FirstOrDefault();
if (trigger == null)
{
character.SelectedConstruction = null;
return;
}
trigger = character.SelectedConstruction.TransformTrigger(trigger);
//stop climbing if:
// - going too fast (can't grab a ladder while falling)
// - moving sideways
// - reached the top or bottom of the ladder
if (Math.Abs(torso.LinearVelocity.Y) > 5.0f ||
TargetMovement.X != 0.0f ||
(TargetMovement.Y < 0.0f && ConvertUnits.ToSimUnits(trigger.Height) + handPos.Y < HeadPosition * 1.5f) ||
(TargetMovement.Y > 0.0f && handPos.Y > 0.3f))
{
Anim = Animation.None;
character.SelectedConstruction = null;
IgnorePlatforms = false;
}
}
//float punchTimer;
//bool punching;
//public void Punch()
//{
// if (punchTimer < 0.01f) punching = true;
// Limb rightHand = GetLimb(LimbType.RightHand);
// Limb head = GetLimb(LimbType.Head);
// Vector2 diff = Vector2.Normalize(Character.CursorPosition - RefLimb.Position);
// rightHand.body.ApplyLinearImpulse(diff * 20.0f);
// head.body.ApplyLinearImpulse(diff * 5.0f);
// head.body.ApplyTorque(Dir*100.0f);
//}
//public void Block(float deltaTime)
//{
// Limb head = GetLimb(LimbType.Head);
// Limb torso = GetLimb(LimbType.Torso);
// Limb leftHand = GetLimb(LimbType.LeftHand);
// Limb leftFoot = GetLimb(LimbType.LeftFoot);
// Limb rightHand = GetLimb(LimbType.RightHand);
// Vector2 pos = head.SimPosition;
// rightHand.Disabled = true;
// leftHand.Disabled = true;
// HandIK(leftHand, pos + new Vector2(0.25f*Dir, 0.0f));
// if (punching)
// {
// punchTimer += deltaTime*10.0f;
// if (punchTimer>2.0f)
// {
// punching = false;
// }
// }
// else
// {
// punchTimer = MathHelper.Lerp(punchTimer, 0.0f, 0.3f);
// HandIK(rightHand, pos + new Vector2((0.3f + punchTimer) * Dir, 0.1f));
// }
//}
public override void DragCharacter(Character target)
{
Limb leftHand = GetLimb(LimbType.LeftHand);
Limb rightHand = GetLimb(LimbType.RightHand);
leftHand.Disabled = true;
rightHand.Disabled = true;
Limb targetLimb = target.AnimController.GetLimb(LimbType.LeftHand);
leftHand.pullJoint.Enabled = true;
leftHand.pullJoint.WorldAnchorB = targetLimb.SimPosition;
rightHand.pullJoint.Enabled = true;
rightHand.pullJoint.WorldAnchorB = targetLimb.SimPosition;
targetLimb.pullJoint.Enabled = true;
targetLimb.pullJoint.WorldAnchorB = leftHand.SimPosition;
target.AnimController.IgnorePlatforms = IgnorePlatforms;
}
public override void HoldItem(float deltaTime, Item item, Vector2[] handlePos, Vector2 holdPos, Vector2 aimPos, bool aim, float holdAngle)
{
Holdable holdable = item.GetComponent<Holdable>();
//calculate the handle positions
Matrix itemTransfrom = Matrix.CreateRotationZ(item.body.Rotation);
Vector2[] transformedHandlePos = new Vector2[2];
transformedHandlePos[0] = Vector2.Transform(handlePos[0], itemTransfrom);
transformedHandlePos[1] = Vector2.Transform(handlePos[1], itemTransfrom);
Limb head = GetLimb(LimbType.Head);
Limb torso = GetLimb(LimbType.Torso);
Limb leftHand = GetLimb(LimbType.LeftHand);
Limb rightHand = GetLimb(LimbType.RightHand);
Vector2 itemPos = aim ? aimPos : holdPos;
float itemAngle;
if (stunTimer <= 0.0f && aim && itemPos != Vector2.Zero)
{
Vector2 mousePos = ConvertUnits.ToSimUnits(character.CursorPosition);
Vector2 diff = (mousePos - torso.SimPosition) * Dir;
holdAngle = MathUtils.VectorToAngle(new Vector2(diff.X, diff.Y * Dir)) - torso.body.Rotation * Dir;
//holdAngle = MathHelper.Clamp(MathUtils.WrapAnglePi(holdAngle), -1.3f, 1.0f);
itemAngle = (torso.body.Rotation + holdAngle * Dir);
if (holdable.ControlPose)
{
head.body.SmoothRotate(itemAngle);
if (TargetMovement == Vector2.Zero && inWater)
{
torso.body.AngularVelocity -= torso.body.AngularVelocity * 0.1f;
torso.body.ApplyForce(torso.body.LinearVelocity * -0.5f);
}
aiming = true;
}
}
else
{
itemAngle = (torso.body.Rotation + holdAngle * Dir);
}
Vector2 shoulderPos = limbJoints[2].WorldAnchorA;
Vector2 transformedHoldPos = shoulderPos;
if (itemPos == Vector2.Zero)
{
if (character.SelectedItems[1] == item)
{
transformedHoldPos = leftHand.pullJoint.WorldAnchorA - transformedHandlePos[1];
itemAngle = (leftHand.Rotation + (holdAngle - MathHelper.PiOver2) * Dir);
}
if (character.SelectedItems[0] == item)
{
transformedHoldPos = rightHand.pullJoint.WorldAnchorA - transformedHandlePos[0];
itemAngle = (rightHand.Rotation + (holdAngle - MathHelper.PiOver2) * Dir);
}
}
else
{
if (character.SelectedItems[0] == item)
{
rightHand.Disabled = true;
}
if (character.SelectedItems[1] == item)
{
leftHand.Disabled = true;
}
itemPos.X = itemPos.X * Dir;
Matrix torsoTransform = Matrix.CreateRotationZ(itemAngle);
transformedHoldPos += Vector2.Transform(itemPos, torsoTransform);
}
item.body.ResetDynamics();
Vector2 currItemPos = (character.SelectedItems[0]==item) ?
rightHand.pullJoint.WorldAnchorA - transformedHandlePos[0] :
leftHand.pullJoint.WorldAnchorA - transformedHandlePos[1];
item.SetTransform(currItemPos, itemAngle);
//item.SetTransform(MathUtils.SmoothStep(item.body.SimPosition, transformedHoldPos + bodyVelocity, 0.5f), itemAngle);
for (int i = 0; i < 2; i++)
{
if (character.SelectedItems[i] != item) continue;
if (itemPos == Vector2.Zero) continue;
Limb hand = (i == 0) ? rightHand : leftHand;
HandIK(hand, transformedHoldPos + transformedHandlePos[i]);
}
}
private void HandIK(Limb hand, Vector2 pos, float force = 1.0f)
{
Vector2 shoulderPos = limbJoints[2].WorldAnchorA;
Limb arm = (hand.type == LimbType.LeftHand) ? GetLimb(LimbType.LeftArm) : GetLimb(LimbType.RightArm);
//hand length
float a = 37.0f;
//arm length
float b = 28.0f;
//distance from shoulder to holdpos
float c = ConvertUnits.ToDisplayUnits(Vector2.Distance(pos, shoulderPos));
c = MathHelper.Clamp(a + b - 1, b - a, c);
float ang2 = MathUtils.VectorToAngle(pos - shoulderPos) + MathHelper.PiOver2;
float armAngle = MathUtils.SolveTriangleSSS(a, b, c);
float handAngle = MathUtils.SolveTriangleSSS(b, a, c);
arm.body.SmoothRotate((ang2 - armAngle * Dir), 20.0f * force);
hand.body.SmoothRotate((ang2 + handAngle * Dir), 100.0f * force);
}
public override Vector2 EstimateCurrPosition(Vector2 prevPosition, float timePassed)
{
timePassed = MathHelper.Clamp(timePassed, 0.0f, 1.0f);
Vector2 targetMovement = character.GetTargetMovement();
Vector2 currPosition = prevPosition + targetMovement * timePassed/1000.0f;
return currPosition;
}
public override void Flip()
{
base.Flip();
walkPos = -walkPos;
Limb torso = GetLimb(LimbType.Torso);
Vector2 difference;
Matrix torsoTransform = Matrix.CreateRotationZ(torso.Rotation);
for (int i = 0; i < character.SelectedItems.Length; i++)
{
if (character.SelectedItems[i] != null)
{
difference = character.SelectedItems[i].body.SimPosition - torso.SimPosition;
difference = Vector2.Transform(difference, torsoTransform);
difference.Y = -difference.Y;
character.SelectedItems[i].body.SetTransform(
torso.SimPosition + Vector2.Transform(difference, -torsoTransform),
MathUtils.WrapAngleTwoPi(-character.SelectedItems[i].body.Rotation));
}
}
foreach (Limb limb in Limbs)
{
switch (limb.type)
{
case LimbType.LeftHand:
case LimbType.LeftArm:
case LimbType.RightHand:
case LimbType.RightArm:
difference = limb.body.SimPosition - torso.SimPosition;
difference = Vector2.Transform(difference, torsoTransform);
difference.Y = -difference.Y;
TrySetLimbPosition(limb, limb.SimPosition, torso.SimPosition + Vector2.Transform(difference, -torsoTransform));
limb.body.SetTransform(limb.body.SimPosition, -limb.body.Rotation);
break;
default:
if (!inWater) limb.body.SetTransform(limb.body.SimPosition,
MathUtils.WrapAnglePi(limb.body.Rotation * (limb.DoesFlip ? -1.0f : 1.0f)));
break;
}
}
}
}
}
@@ -0,0 +1,851 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using FarseerPhysics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Contacts;
using FarseerPhysics.Dynamics.Joints;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Barotrauma.Networking;
namespace Barotrauma
{
class Ragdoll
{
public static List<Ragdoll> list = new List<Ragdoll>();
protected Hull currentHull;
public Limb[] Limbs;
private Dictionary<LimbType, Limb> limbDictionary;
public RevoluteJoint[] limbJoints;
private bool simplePhysicsEnabled;
private Character character;
private Limb lowestLimb;
protected float strongestImpact;
float headPosition, headAngle;
float torsoPosition, torsoAngle;
protected double onFloorTimer;
//the movement speed of the ragdoll
public Vector2 movement;
//the target speed towards which movement is interpolated
private Vector2 targetMovement;
//a movement vector that overrides targetmovement if trying to steer
//a Character to the position sent by server in multiplayer mode
protected Vector2 correctionMovement;
protected float floorY;
protected float surfaceY;
protected bool inWater, headInWater;
public bool onGround;
private bool ignorePlatforms;
private Limb refLimb;
protected Structure stairs;
protected Direction dir;
//private byte ID;
public Limb LowestLimb
{
get { return lowestLimb; }
}
public Limb RefLimb
{
get
{
return refLimb;
}
}
public float Mass
{
get;
private set;
}
public bool SimplePhysicsEnabled
{
get { return simplePhysicsEnabled; }
set
{
if (value == simplePhysicsEnabled) return;
simplePhysicsEnabled = value;
foreach (Limb limb in Limbs)
{
limb.body.Enabled = !simplePhysicsEnabled;
}
foreach (RevoluteJoint joint in limbJoints)
{
joint.Enabled = !simplePhysicsEnabled;
}
refLimb.body.Enabled = true;
}
}
public Vector2 TargetMovement
{
get
{
return (correctionMovement == Vector2.Zero) ? targetMovement : correctionMovement;
}
set
{
if (!MathUtils.IsValid(value)) return;
targetMovement.X = MathHelper.Clamp(value.X, -3.0f, 3.0f);
targetMovement.Y = MathHelper.Clamp(value.Y, -3.0f, 3.0f);
}
}
public float HeadPosition
{
get { return headPosition; }
}
public float HeadAngle
{
get { return headAngle; }
}
public float TorsoPosition
{
get { return torsoPosition; }
}
public float TorsoAngle
{
get { return torsoAngle; }
}
public float Dir
{
get { return ((dir == Direction.Left) ? -1.0f : 1.0f); }
}
public bool InWater
{
get { return inWater; }
}
public bool HeadInWater
{
get { return headInWater; }
}
public Hull CurrentHull
{
get { return currentHull;}
}
public bool IgnorePlatforms
{
get { return ignorePlatforms; }
set
{
if (ignorePlatforms == value) return;
ignorePlatforms = value;
UpdateCollisionCategories();
}
}
public float StrongestImpact
{
get { return strongestImpact; }
set { strongestImpact = Math.Max(value, strongestImpact); }
}
public Structure Stairs
{
get { return stairs; }
}
public Ragdoll(Character character, XElement element)
{
list.Add(this);
this.character = character;
dir = Direction.Right;
//int limbAmount = ;
Limbs = new Limb[element.Elements("limb").Count()];
limbJoints = new RevoluteJoint[element.Elements("joint").Count()];
limbDictionary = new Dictionary<LimbType, Limb>();
headPosition = ToolBox.GetAttributeFloat(element, "headposition", 50.0f);
headPosition = ConvertUnits.ToSimUnits(headPosition);
headAngle = MathHelper.ToRadians(ToolBox.GetAttributeFloat(element, "headangle", 0.0f));
torsoPosition = ToolBox.GetAttributeFloat(element, "torsoposition", 50.0f);
torsoPosition = ConvertUnits.ToSimUnits(torsoPosition);
torsoAngle = MathHelper.ToRadians(ToolBox.GetAttributeFloat(element, "torsoangle", 0.0f));
foreach (XElement subElement in element.Elements())
{
switch (subElement.Name.ToString())
{
case "limb":
byte ID = Convert.ToByte(subElement.Attribute("id").Value);
Limb limb = new Limb(character, subElement);
limb.body.FarseerBody.OnCollision += OnLimbCollision;
Limbs[ID] = limb;
Mass += limb.Mass;
if (!limbDictionary.ContainsKey(limb.type)) limbDictionary.Add(limb.type, limb);
break;
case "joint":
Byte limb1ID = Convert.ToByte(subElement.Attribute("limb1").Value);
Byte limb2ID = Convert.ToByte(subElement.Attribute("limb2").Value);
Vector2 limb1Pos = ToolBox.GetAttributeVector2(subElement, "limb1anchor", Vector2.Zero);
limb1Pos = ConvertUnits.ToSimUnits(limb1Pos);
Vector2 limb2Pos = ToolBox.GetAttributeVector2(subElement, "limb2anchor", Vector2.Zero);
limb2Pos = ConvertUnits.ToSimUnits(limb2Pos);
RevoluteJoint joint = new RevoluteJoint(Limbs[limb1ID].body.FarseerBody, Limbs[limb2ID].body.FarseerBody, limb1Pos, limb2Pos);
joint.CollideConnected = false;
if (subElement.Attribute("lowerlimit")!=null)
{
joint.LimitEnabled = true;
joint.LowerLimit = float.Parse(subElement.Attribute("lowerlimit").Value) * ((float)Math.PI / 180.0f);
joint.UpperLimit = float.Parse(subElement.Attribute("upperlimit").Value) * ((float)Math.PI / 180.0f);
}
joint.MotorEnabled = true;
joint.MaxMotorTorque = 0.25f;
GameMain.World.AddJoint(joint);
for (int i = 0; i < limbJoints.Length; i++ )
{
if (limbJoints[i] != null) continue;
limbJoints[i] = joint;
break;
}
break;
}
}
refLimb = GetLimb(LimbType.Torso);
if (refLimb == null) refLimb = GetLimb(LimbType.Head);
if (refLimb == null) DebugConsole.ThrowError("Character ''" + character + "'' doesn't have a head or torso!");
foreach (var joint in limbJoints)
{
joint.BodyB.SetTransform(
joint.BodyA.Position+joint.LocalAnchorA-joint.LocalAnchorB,
(joint.LowerLimit+joint.UpperLimit)/2.0f);
}
float startDepth = 0.1f;
float increment = 0.001f;
foreach (Character otherCharacter in Character.CharacterList)
{
if (otherCharacter==character) continue;
startDepth+=increment;
}
foreach (Limb limb in Limbs)
{
limb.sprite.Depth = startDepth + limb.sprite.Depth * 0.0001f;
}
FindLowestLimb();
}
public bool OnLimbCollision(Fixture f1, Fixture f2, Contact contact)
{
Structure structure = f2.Body.UserData as Structure;
//always collides with bodies other than structures
if (structure == null)
{
CalculateImpact(f1, f2, contact);
return true;
}
if (structure.IsPlatform)
{
if (ignorePlatforms) return false;
//the collision is ignored if the lowest limb is under the platform
if (lowestLimb==null || lowestLimb.Position.Y < structure.Rect.Y) return false;
}
else if (structure.StairDirection!=Direction.None && lowestLimb != null)
{
float stairPosY = structure.StairDirection == Direction.Right ?
lowestLimb.Position.X - structure.Rect.X : structure.Rect.Width - (lowestLimb.Position.X - structure.Rect.X);
if (lowestLimb.Position.Y < structure.Rect.Y - structure.Rect.Height + stairPosY) return false;
if (targetMovement.Y < 0.5f)
{
if (inWater || lowestLimb.Position.Y < structure.Rect.Y - structure.Rect.Height + 50.0f)
{
stairs = null;
return false;
}
}
if (targetMovement.Y >= 0.0f && lowestLimb.SimPosition.Y > ConvertUnits.ToSimUnits(structure.Rect.Y - Submarine.GridSize.Y * 8.0f))
{
//stairs = null;
//return false;
}
Limb limb = f1.Body.UserData as Limb;
if (limb != null)// && (limb.type == LimbType.LeftFoot || limb.type == LimbType.RightFoot))
{
if (contact.Manifold.LocalNormal.Y >= 0.0f)
{
if (limb.SimPosition.Y < lowestLimb.SimPosition.Y+0.2f)
{
stairs = structure;
return true;
}
}
else
{
stairs = null;
return false;
}
}
}
CalculateImpact(f1, f2, contact);
return true;
}
private void CalculateImpact(Fixture f1, Fixture f2, Contact contact)
{
Vector2 normal = contact.Manifold.LocalNormal;
Vector2 avgVelocity = Vector2.Zero;
foreach (Limb limb in Limbs)
{
avgVelocity += limb.LinearVelocity;
}
avgVelocity = avgVelocity / Limbs.Count();
float impact = Vector2.Dot((f1.Body.LinearVelocity + avgVelocity) / 2.0f, -normal);
if (GameMain.Server != null) impact = impact / 2.0f;
Limb l = (Limb)f1.Body.UserData;
float volume = stairs == null ? impact/5.0f : impact;
volume= Math.Min(impact, 1.0f);
if (impact > 0.8f && l.HitSound != null && l.soundTimer <= 0.0f) l.HitSound.Play(volume, impact * 100.0f, l.body.FarseerBody);
if (impact > l.impactTolerance)
{
character.Health -= (impact - l.impactTolerance * 0.1f);
strongestImpact = Math.Max(strongestImpact, impact - l.impactTolerance);
SoundPlayer.PlayDamageSound(DamageSoundType.LimbBlunt, strongestImpact, l.body.FarseerBody);
if (Character.Controlled == character) GameMain.GameScreen.Cam.Shake = strongestImpact;
}
}
public virtual void Draw(SpriteBatch spriteBatch)
{
if (simplePhysicsEnabled) return;
foreach (Limb limb in Limbs)
{
limb.Draw(spriteBatch);
}
}
public void DebugDraw(SpriteBatch spriteBatch)
{
if (!GameMain.DebugDraw || !character.Enabled) return;
if (simplePhysicsEnabled) return;
foreach (Limb limb in Limbs)
{
if (limb.pullJoint != null)
{
Vector2 pos = ConvertUnits.ToDisplayUnits(limb.pullJoint.WorldAnchorA);
pos.Y = -pos.Y;
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)pos.Y, 5, 5), Color.Red, true, 0.01f);
if (limb.AnimTargetPos == Vector2.Zero) continue;
Vector2 pos2 = ConvertUnits.ToDisplayUnits(limb.AnimTargetPos);
pos2.Y = -pos2.Y;
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos2.X, (int)pos2.Y, 5, 5), Color.Blue, true, 0.01f);
GUI.DrawLine(spriteBatch, pos, pos2, Color.Green);
}
}
foreach (RevoluteJoint joint in limbJoints)
{
Vector2 pos = ConvertUnits.ToDisplayUnits(joint.WorldAnchorA);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)-pos.Y, 5, 5), Color.White, true);
pos = ConvertUnits.ToDisplayUnits(joint.WorldAnchorB);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)-pos.Y, 5, 5), Color.White, true);
}
foreach (Limb limb in Limbs)
{
if (limb.body.TargetPosition != Vector2.Zero)
{
Vector2 pos = ConvertUnits.ToDisplayUnits(limb.body.TargetPosition);
pos.Y = -pos.Y;
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X - 10, (int)pos.Y - 10, 20, 20), Color.Cyan, false, 0.01f);
GUI.DrawLine(spriteBatch, pos, new Vector2(limb.Position.X, -limb.Position.Y), limb==RefLimb ? Color.Orange : Color.Cyan);
}
}
}
public virtual void Flip()
{
dir = (dir == Direction.Left) ? Direction.Right : Direction.Left;
for (int i = 0; i < limbJoints.Count(); i++)
{
float lowerLimit = -limbJoints[i].UpperLimit;
float upperLimit = -limbJoints[i].LowerLimit;
limbJoints[i].LowerLimit = lowerLimit;
limbJoints[i].UpperLimit = upperLimit;
limbJoints[i].LocalAnchorA = new Vector2(-limbJoints[i].LocalAnchorA.X, limbJoints[i].LocalAnchorA.Y);
limbJoints[i].LocalAnchorB = new Vector2(-limbJoints[i].LocalAnchorB.X, limbJoints[i].LocalAnchorB.Y);
}
for (int i = 0; i < Limbs.Count(); i++)
{
if (Limbs[i] == null) continue;
Vector2 spriteOrigin = Limbs[i].sprite.Origin;
spriteOrigin.X = Limbs[i].sprite.SourceRect.Width - spriteOrigin.X;
Limbs[i].sprite.Origin = spriteOrigin;
Limbs[i].Dir = Dir;
if (Limbs[i].pullJoint == null) continue;
Limbs[i].pullJoint.LocalAnchorA =
new Vector2(
-Limbs[i].pullJoint.LocalAnchorA.X,
Limbs[i].pullJoint.LocalAnchorA.Y);
}
}
public Vector2 GetCenterOfMass()
{
Vector2 centerOfMass = Vector2.Zero;
foreach (Limb limb in Limbs)
{
centerOfMass += limb.Mass * limb.SimPosition;
}
centerOfMass /= Mass;
return centerOfMass;
}
/// <summary>
///
/// </summary>
/// <param name="pullFromCenter">if false, force is applied to the position of pullJoint</param>
protected void MoveLimb(Limb limb, Vector2 pos, float amount, bool pullFromCenter = false)
{
limb.Move(pos, amount, pullFromCenter);
}
public void ResetPullJoints()
{
for (int i = 0; i < Limbs.Count(); i++)
{
if (Limbs[i] == null || Limbs[i].pullJoint == null) continue;
Limbs[i].pullJoint.Enabled = false;
}
}
public static void UpdateAll(Camera cam, float deltaTime)
{
foreach (Ragdoll r in list)
{
r.Update(cam, deltaTime);
}
}
public void FindHull()
{
Hull newHull = Hull.FindHull(
ConvertUnits.ToDisplayUnits(refLimb.SimPosition),
currentHull);
if (newHull == currentHull) return;
currentHull = newHull;
UpdateCollisionCategories();
}
private void UpdateCollisionCategories()
{
Category wall = currentHull == null ?
Physics.CollisionLevel | Physics.CollisionWall
: Physics.CollisionWall;
Category collisionCategory = (ignorePlatforms) ?
wall | Physics.CollisionProjectile | Physics.CollisionStairs
: wall | Physics.CollisionProjectile | Physics.CollisionPlatform | Physics.CollisionStairs;
foreach (Limb limb in Limbs)
{
if (limb.ignoreCollisions) continue;
try
{
limb.body.CollidesWith = collisionCategory;
}
catch (Exception e)
{
DebugConsole.ThrowError("Failed to update ragdoll limb collisioncategories", e);
}
}
}
public void Update(Camera cam, float deltaTime)
{
if (!character.Enabled) return;
UpdateNetPlayerPosition();
Vector2 flowForce = Vector2.Zero;
FindLowestLimb();
FindHull();
//ragdoll isn't in any room -> it's in the water
if (currentHull == null)
{
inWater = true;
headInWater = true;
}
else
{
flowForce = GetFlowForce();
inWater = false;
headInWater = false;
if (currentHull.Volume > currentHull.FullVolume * 0.95f ||
ConvertUnits.ToSimUnits(currentHull.Surface) - floorY > HeadPosition * 0.95f)
inWater = true;
}
foreach (Limb limb in Limbs)
{
Vector2 limbPosition = ConvertUnits.ToDisplayUnits(limb.SimPosition);
//find the room which the limb is in
//the room where the ragdoll is in is used as the "guess", meaning that it's checked first
Hull limbHull = Hull.FindHull(limbPosition, currentHull);
bool prevInWater = limb.inWater;
limb.inWater = false;
if (limbHull == null)
{
//limb isn't in any room -> it's in the water
limb.inWater = true;
}
else if (limbHull.Volume > 0.0f && Submarine.RectContains(limbHull.Rect, limbPosition))
{
if (limbPosition.Y < limbHull.Surface)
{
limb.inWater = true;
if (flowForce.Length() > 0.01f)
{
limb.body.ApplyForce(flowForce);
if (flowForce.Length() > 15.0f) surfaceY = limbHull.Surface;
}
surfaceY = limbHull.Surface;
if (limb.type == LimbType.Head)
{
headInWater = true;
surfaceY = limbHull.Surface;
}
}
//the limb has gone through the surface of the water
if (Math.Abs(limb.LinearVelocity.Y) > 5.0f && inWater != prevInWater)
{
//create a splash particle
GameMain.ParticleManager.CreateParticle("watersplash",
new Vector2(limb.Position.X, limbHull.Surface),
new Vector2(0.0f, Math.Abs(-limb.LinearVelocity.Y * 10.0f)),
0.0f, limbHull);
GameMain.ParticleManager.CreateParticle("bubbles",
new Vector2(limb.Position.X, limbHull.Surface),
limb.LinearVelocity*0.001f,
0.0f, limbHull);
//if the Character dropped into water, create a wave
if (limb.LinearVelocity.Y<0.0f)
{
//1.0 when the limb is parallel to the surface of the water
// = big splash and a large impact
float parallel = (float)Math.Abs(Math.Sin(limb.Rotation));
Vector2 impulse = Vector2.Multiply(limb.LinearVelocity, -parallel * limb.Mass);
//limb.body.ApplyLinearImpulse(impulse);
int n = (int)((limbPosition.X - limbHull.Rect.X) / Hull.WaveWidth);
limbHull.WaveVel[n] = Math.Min(impulse.Y * 1.0f, 5.0f);
StrongestImpact = ((impulse.Length() * 0.5f) - limb.impactTolerance);
}
}
}
limb.Update(deltaTime);
}
}
public void SetPosition(Vector2 simPosition)
{
Vector2 moveAmount = simPosition - refLimb.SimPosition;
foreach (Limb limb in Limbs)
{
if (limb==refLimb)
{
limb.body.SetTransform(simPosition, limb.Rotation);
continue;
}
//check visibility from the new position of RefLimb to the new position of this limb
Vector2 movePos = limb.SimPosition + moveAmount;
TrySetLimbPosition(limb, simPosition, movePos);
}
}
protected void TrySetLimbPosition(Limb limb, Vector2 original, Vector2 simPosition)
{
if (original == simPosition) return;
Body body = Submarine.CheckVisibility(original, simPosition);
Vector2 movePos = simPosition;
//if there's something in between the limbs
if (body != null)
{
//move the limb close to the position where the raycast hit something
movePos = original + ((simPosition - original) * Submarine.LastPickedFraction * 0.9f);
}
limb.body.SetTransform(movePos, limb.Rotation);
}
public void SetRotation(float rotation)
{
float rotateAmount = rotation - refLimb.Rotation;
Matrix rotationMatrix = Matrix.CreateRotationZ(rotateAmount);
refLimb.body.SetTransform(refLimb.SimPosition, rotation);
foreach (Limb limb in Limbs)
{
if (limb == refLimb) continue;
Vector2 newPos = limb.SimPosition - refLimb.SimPosition;
newPos = Vector2.Transform(newPos, rotationMatrix);
TrySetLimbPosition(limb, refLimb.SimPosition, refLimb.SimPosition + newPos);
limb.body.SetTransform(limb.SimPosition, limb.Rotation + rotateAmount);
}
}
private void UpdateNetPlayerPosition()
{
if (refLimb.body.TargetPosition == Vector2.Zero)
{
correctionMovement = Vector2.Zero;
return;
}
//if the limb is closer than alloweddistance, just ignore the difference
float allowedDistance = NetConfig.AllowedRagdollDistance * ((inWater) ? 2.0f : 1.0f);
float dist = Vector2.Distance(refLimb.body.SimPosition, refLimb.body.TargetPosition);
//if the limb is further away than resetdistance, all limbs are immediately snapped to their targetpositions
bool resetAll = dist > NetConfig.ResetRagdollDistance;
Vector2 diff = (refLimb.body.TargetPosition - refLimb.body.SimPosition);
if (diff == Vector2.Zero || diff.Length() < allowedDistance)
{
refLimb.body.TargetPosition = Vector2.Zero;
foreach (Limb limb in Limbs)
{
limb.body.TargetPosition = Vector2.Zero;
}
correctionMovement = Vector2.Zero;
return;
}
else
{
if (inWater)
{
//foreach (Limb limb in Limbs)
//{
// //if (limb.body.TargetPosition == Vector2.Zero) continue;
// limb.body.SetTransform(limb.SimPosition + Vector2.Normalize(diff) * 0.1f, limb.Rotation);
//}
correctionMovement =
Vector2.Lerp(targetMovement, Vector2.Normalize(diff) * MathHelper.Clamp(dist * 8.0f, 0.1f, 8.0f), 0.2f);
}
else
{
correctionMovement =
Vector2.Lerp(targetMovement, Vector2.Normalize(diff) * MathHelper.Clamp(dist * 5.0f, 0.1f, 5.0f), 0.2f);
if (Math.Abs(correctionMovement.Y) < 0.1f) correctionMovement.Y = 0.0f;
}
}
if (resetAll)
{
System.Diagnostics.Debug.WriteLine("reset ragdoll limb positions");
SetPosition(refLimb.body.TargetPosition);
if (character is AICharacter) SetRotation(refLimb.body.TargetRotation);
//foreach (Limb limb in Limbs)
//{
// if (limb.body.TargetPosition == Vector2.Zero)
// {
// limb.body.SetTransform(limb.body.SimPosition + diff, limb.body.Rotation);
// continue;
// }
// limb.body.LinearVelocity = limb.body.TargetVelocity;
// limb.body.AngularVelocity = limb.body.TargetAngularVelocity;
// limb.body.SetTransform(limb.body.TargetPosition, limb.body.TargetRotation);
// limb.body.TargetPosition = Vector2.Zero;
//}
}
}
public virtual Vector2 EstimateCurrPosition(Vector2 prevPosition, float timePassed)
{
return prevPosition;
}
private Vector2 GetFlowForce()
{
Vector2 limbPos = ConvertUnits.ToDisplayUnits(Limbs[0].SimPosition);
Vector2 force = Vector2.Zero;
foreach (MapEntity e in MapEntity.mapEntityList)
{
Gap gap = e as Gap;
if (gap == null || gap.FlowTargetHull != currentHull || gap.LerpedFlowForce == Vector2.Zero) continue;
Vector2 gapPos = gap.SimPosition;
float dist = Vector2.Distance(limbPos, gapPos);
force += Vector2.Normalize(gap.LerpedFlowForce) * (Math.Max(gap.LerpedFlowForce.Length() - dist, 0.0f) / 500.0f);
}
if (force.Length() > 20.0f) return force;
return force;
}
public Limb GetLimb(LimbType limbType)
{
Limb limb = null;
limbDictionary.TryGetValue(limbType, out limb);
return limb;
}
public void FindLowestLimb()
{
//find the lowest limb
lowestLimb = null;
foreach (Limb limb in Limbs)
{
if (lowestLimb == null)
lowestLimb = limb;
else if (limb.SimPosition.Y < lowestLimb.SimPosition.Y)
lowestLimb = limb;
}
}
public void Remove()
{
foreach (Limb l in Limbs) l.Remove();
foreach (RevoluteJoint joint in limbJoints)
{
GameMain.World.RemoveJoint(joint);
}
}
}
}