Lighting optimization (caching shadow vertices & only checking hulls in range if the position or range of the light changes), ragdoll optimization, itemcomponent optimization, dragging stunned/dead characters

This commit is contained in:
Regalis11
2015-10-11 21:04:42 +03:00
parent 0a96254696
commit 8df9133e84
25 changed files with 377 additions and 201 deletions
@@ -57,5 +57,6 @@ namespace Subsurface
public virtual void HoldItem(float deltaTime, Item item, Vector2[] handlePos, Vector2 holdPos, Vector2 aimPos, bool aim, float holdAngle) { } public virtual void HoldItem(float deltaTime, Item item, Vector2[] handlePos, Vector2 holdPos, Vector2 aimPos, bool aim, float holdAngle) { }
public virtual void DragCharacter(Character target) { }
} }
} }
+29 -9
View File
@@ -578,14 +578,14 @@ namespace Subsurface
maxDist = ConvertUnits.ToSimUnits(maxDist); maxDist = ConvertUnits.ToSimUnits(maxDist);
foreach (Character c in Character.CharacterList) foreach (Character c in CharacterList)
{ {
if (c == this) continue; if (c == this) continue;
if (Vector2.Distance(SimPosition, c.SimPosition) > maxDist) continue; if (Vector2.Distance(SimPosition, c.SimPosition) > maxDist) continue;
float dist = Vector2.Distance(mouseSimPos, c.SimPosition); float dist = Vector2.Distance(mouseSimPos, c.SimPosition);
if (dist < maxDist && closestCharacter==null || dist<closestDist) if (dist < maxDist && (closestCharacter==null || dist<closestDist))
{ {
closestCharacter = c; closestCharacter = c;
closestDist = dist; closestDist = dist;
@@ -596,6 +596,22 @@ namespace Subsurface
return closestCharacter; return closestCharacter;
} }
private void ToggleSelectedCharacter(Character selected)
{
if (selectedCharacter != null)
{
foreach (Limb limb in selectedCharacter.AnimController.Limbs)
{
limb.pullJoint.Enabled = false;
}
selectedCharacter = null;
}
else
{
selectedCharacter = selected;
}
}
/// <summary> /// <summary>
/// Control the character according to player input /// Control the character according to player input
/// </summary> /// </summary>
@@ -659,7 +675,7 @@ namespace Subsurface
closestCharacter = FindClosestCharacter(mouseSimPos); closestCharacter = FindClosestCharacter(mouseSimPos);
if (closestCharacter != null) if (closestCharacter != null)
{ {
if (closestCharacter != selectedCharacter) selectedCharacter = null; // if (closestCharacter != selectedCharacter) selectedCharacter = null;
if (!closestCharacter.IsHumanoid) closestCharacter = null; if (!closestCharacter.IsHumanoid) closestCharacter = null;
} }
@@ -697,22 +713,26 @@ namespace Subsurface
} }
else else
{ {
if (Vector2.Distance(selectedCharacter.SimPosition, SimPosition) > 2.0f) selectedCharacter = null; if (Vector2.Distance(selectedCharacter.SimPosition, SimPosition) > 2.0f ||
(!selectedCharacter.isDead && selectedCharacter.Stun <= 0.0f))
{
ToggleSelectedCharacter(selectedCharacter);
}
} }
if (GetInputState(InputType.Select)) if (GetInputState(InputType.Select))
{ {
if (selectedCharacter != null) if (selectedCharacter != null)
{ {
selectedCharacter = null; ToggleSelectedCharacter(selectedCharacter);
} }
else if (closestCharacter != null && closestCharacter.isDead && closestCharacter.IsHumanoid) else if (closestCharacter != null && closestCharacter.IsHumanoid &&
(closestCharacter.isDead || closestCharacter.AnimController.StunTimer > 0.0f))
{ {
selectedCharacter = closestCharacter; selectedCharacter = closestCharacter;
} }
} }
DisableControls = false; DisableControls = false;
} }
@@ -741,7 +761,7 @@ namespace Subsurface
public virtual void Update(Camera cam, float deltaTime) public virtual void Update(Camera cam, float deltaTime)
{ {
//AnimController.SimplePhysicsEnabled = (Character.controlled!=this && Vector2.Distance(cam.WorldViewCenter, Position)>5000.0f); AnimController.SimplePhysicsEnabled = (Character.controlled!=this && Vector2.Distance(cam.WorldViewCenter, Position)>5000.0f);
if (isDead) return; if (isDead) return;
@@ -825,7 +845,7 @@ namespace Subsurface
Vector2 pos = ConvertUnits.ToDisplayUnits(AnimController.Limbs[0].SimPosition); Vector2 pos = ConvertUnits.ToDisplayUnits(AnimController.Limbs[0].SimPosition);
pos.Y = -pos.Y; pos.Y = -pos.Y;
if (this == Character.controlled) return; if (this == controlled) return;
if (IsNetworkPlayer) if (IsNetworkPlayer)
{ {
+1 -1
View File
@@ -54,7 +54,7 @@ namespace Subsurface
//if (Vector2.Distance(selectedCharacter.SimPosition, SimPosition) > 2.0f) selectedCharacter = null; //if (Vector2.Distance(selectedCharacter.SimPosition, SimPosition) > 2.0f) selectedCharacter = null;
} }
if (character.ClosestCharacter != null && character.ClosestCharacter.IsDead) if (character.ClosestCharacter != null && (character.ClosestCharacter.IsDead || character.ClosestCharacter.Stun > 0.0f))
{ {
Vector2 startPos = character.Position + (character.ClosestCharacter.Position - character.Position) * 0.7f; Vector2 startPos = character.Position + (character.ClosestCharacter.Position - character.Position) * 0.7f;
startPos = cam.WorldToScreen(startPos); startPos = cam.WorldToScreen(startPos);
@@ -225,11 +225,9 @@ namespace Subsurface
RefLimb.body.Rotation + MathUtils.GetShortestAngle(RefLimb.body.Rotation, movementAngle) : RefLimb.body.Rotation + MathUtils.GetShortestAngle(RefLimb.body.Rotation, movementAngle) :
HeadAngle*Dir); HeadAngle*Dir);
RefLimb.pullJoint.Enabled = true; RefLimb.body.LinearVelocity = movement;
RefLimb.pullJoint.WorldAnchorB =
RefLimb.SimPosition + movement * 0.1f;
RefLimb.body.SmoothRotate(0.0f); //RefLimb.body.SmoothRotate(0.0f);
foreach (Limb l in Limbs) foreach (Limb l in Limbs)
{ {
@@ -36,66 +36,77 @@ namespace Subsurface
//if (inWater) stairs = null; //if (inWater) stairs = null;
if (onFloorTimer <= 0.0f && !SimplePhysicsEnabled)
{
Vector2 rayStart = colliderPos; // at the bottom of the player sprite Vector2 rayStart = colliderPos; // at the bottom of the player sprite
Vector2 rayEnd = rayStart - new Vector2(0.0f, TorsoPosition); Vector2 rayEnd = rayStart - new Vector2(0.0f, TorsoPosition);
if (stairs != null) rayEnd.Y -= 0.5f; if (stairs != null) rayEnd.Y -= 0.5f;
if (Anim != Animation.UsingConstruction) ResetPullJoints(); //do a raytrace straight down from the torso to figure
//out whether the ragdoll is standing on ground
//do a raytrace straight down from the torso to figure float closestFraction = 1;
//out whether the ragdoll is standing on ground Structure closestStructure = null;
float closestFraction = 1; GameMain.World.RayCast((fixture, point, normal, fraction) =>
Structure closestStructure = null;
GameMain.World.RayCast((fixture, point, normal, fraction) =>
{
switch (fixture.CollisionCategories)
{ {
case Physics.CollisionStairs: switch (fixture.CollisionCategories)
if (inWater && TargetMovement.Y < 0.5f) return -1; {
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; Structure structure = fixture.Body.UserData as Structure;
if (stairs == null && structure != null) if (structure != null) closestStructure = structure;
{ }
if (LowestLimb.SimPosition.Y < structure.SimPosition.Y) onFloorTimer = 0.05f;
{ return closestFraction;
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;
} }
, rayStart, rayEnd);
onGround = true; if (closestStructure != null && closestStructure.StairDirection != Direction.None)
if (fraction < closestFraction)
{ {
closestFraction = fraction; stairs = closestStructure;
}
Structure structure = fixture.Body.UserData as Structure; else
if (structure != null) closestStructure = structure; {
stairs = null;
} }
onFloorTimer = 0.05f;
return closestFraction;
}
, rayStart, rayEnd);
if (closestStructure != null && closestStructure.StairDirection != Direction.None) if (closestFraction == 1) //raycast didn't hit anything
{ {
stairs = closestStructure; floorY = (currentHull == null) ? -1000.0f : ConvertUnits.ToSimUnits(currentHull.Rect.Y - currentHull.Rect.Height);
} }
else else
{ {
stairs = null; floorY = rayStart.Y + (rayEnd.Y - rayStart.Y) * closestFraction;
}
} }
//the ragdoll "stays on ground" for 50 millisecs after separation //the ragdoll "stays on ground" for 50 millisecs after separation
if (onFloorTimer <= 0.0f) if (onFloorTimer <= 0.0f)
{ {
@@ -110,15 +121,6 @@ namespace Subsurface
onFloorTimer -= deltaTime; onFloorTimer -= deltaTime;
} }
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;
}
IgnorePlatforms = (TargetMovement.Y < 0.0f); IgnorePlatforms = (TargetMovement.Y < 0.0f);
@@ -131,11 +133,12 @@ namespace Subsurface
if (stunTimer > 0) if (stunTimer > 0)
{ {
//UpdateStruggling();
stunTimer -= deltaTime; stunTimer -= deltaTime;
return; return;
} }
if (Anim != Animation.UsingConstruction) ResetPullJoints();
if (TargetDir != dir) Flip(); if (TargetDir != dir) Flip();
if (SimplePhysicsEnabled) if (SimplePhysicsEnabled)
@@ -191,6 +194,10 @@ namespace Subsurface
Limb leftLeg = GetLimb(LimbType.LeftLeg); Limb leftLeg = GetLimb(LimbType.LeftLeg);
Limb rightLeg = GetLimb(LimbType.RightLeg); Limb rightLeg = GetLimb(LimbType.RightLeg);
if (character.SelectedCharacter != null) DragCharacter(character.SelectedCharacter);
float getUpSpeed = 0.3f; float getUpSpeed = 0.3f;
float walkCycleSpeed = head.LinearVelocity.X * walkAnimSpeed; float walkCycleSpeed = head.LinearVelocity.X * walkAnimSpeed;
if (stairs != null) if (stairs != null)
@@ -751,6 +758,27 @@ namespace Subsurface
// } // }
//} //}
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) public override void HoldItem(float deltaTime, Item item, Vector2[] handlePos, Vector2 holdPos, Vector2 aimPos, bool aim, float holdAngle)
{ {
//calculate the handle positions //calculate the handle positions
+1 -1
View File
@@ -141,7 +141,7 @@ namespace Subsurface
public static void ExecuteCommand(string command, GameMain game) public static void ExecuteCommand(string command, GameMain game)
{ {
#if !DEBUG #if !DEBUG
if (Game1.Client!=null) if (GameMain.Client!=null)
{ {
ThrowError("Console commands are disabled in multiplayer mode"); ThrowError("Console commands are disabled in multiplayer mode");
return; return;
+1 -1
View File
@@ -128,7 +128,7 @@ namespace Subsurface
World = new World(new Vector2(0, -9.82f)); World = new World(new Vector2(0, -9.82f));
FarseerPhysics.Settings.AllowSleep = true; FarseerPhysics.Settings.AllowSleep = true;
FarseerPhysics.Settings.ContinuousPhysics = false; FarseerPhysics.Settings.ContinuousPhysics = false;
FarseerPhysics.Settings.VelocityIterations = 2; FarseerPhysics.Settings.VelocityIterations = 1;
FarseerPhysics.Settings.PositionIterations = 1; FarseerPhysics.Settings.PositionIterations = 1;
} }
@@ -282,6 +282,12 @@ namespace Subsurface.Items.Components
private int loopingSoundIndex; private int loopingSoundIndex;
public void PlaySound(ActionType type, Vector2 position) public void PlaySound(ActionType type, Vector2 position)
{ {
if (loopingSound != null)
{
loopingSoundIndex = loopingSound.Sound.Loop(loopingSoundIndex, GetSoundVolume(loopingSound), position, loopingSound.Range);
return;
}
List<ItemSound> matchingSounds = sounds.FindAll(x => x.Type == type); List<ItemSound> matchingSounds = sounds.FindAll(x => x.Type == type);
if (matchingSounds.Count == 0) return; if (matchingSounds.Count == 0) return;
@@ -292,23 +298,17 @@ namespace Subsurface.Items.Components
itemSound = matchingSounds[index]; itemSound = matchingSounds[index];
} }
if (itemSound == null) return;
if (loopingSound!=null) if (itemSound.Loop)
{ {
loopingSoundIndex = loopingSound.Sound.Loop(loopingSoundIndex, GetSoundVolume(loopingSound), position, loopingSound.Range); loopingSound = itemSound;
} }
else if (itemSound!=null) else
{ {
if (itemSound.Loop) float volume = GetSoundVolume(itemSound);
{ if (volume == 0.0f) return;
loopingSound = itemSound; itemSound.Sound.Play(volume, itemSound.Range, position);
}
else
{
float volume = GetSoundVolume(itemSound);
if (volume == 0.0f) return;
itemSound.Sound.Play(volume, itemSound.Range, position);
}
} }
} }
@@ -12,6 +12,8 @@ namespace Subsurface.Items.Components
List<RelatedItem> containableItems; List<RelatedItem> containableItems;
public ItemInventory inventory; public ItemInventory inventory;
private bool hasStatusEffects;
//how many items can be contained //how many items can be contained
[HasDefaultValue(5, false)] [HasDefaultValue(5, false)]
public int Capacity public int Capacity
@@ -90,19 +92,21 @@ namespace Subsurface.Items.Components
inventory = new ItemInventory(this, capacity, hudPos, slotsPerRow); inventory = new ItemInventory(this, capacity, hudPos, slotsPerRow);
containableItems = new List<RelatedItem>(); containableItems = new List<RelatedItem>();
//itemPos = ToolBox.GetAttributeVector2(element, "ItemPos", Vector2.Zero);
//itemPos = ConvertUnits.ToSimUnits(itemPos);
//itemInterval = ToolBox.GetAttributeVector2(element, "ItemInterval", Vector2.Zero);
//itemInterval = ConvertUnits.ToSimUnits(itemInterval);
foreach (XElement subElement in element.Elements()) foreach (XElement subElement in element.Elements())
{ {
switch (subElement.Name.ToString().ToLower()) switch (subElement.Name.ToString().ToLower())
{ {
case "containable": case "containable":
RelatedItem containable = RelatedItem.Load(subElement); RelatedItem containable = RelatedItem.Load(subElement);
if (containable!=null) containableItems.Add(containable); if (containable == null) continue;
foreach (StatusEffect effect in containable.statusEffects)
{
if (effect.type == ActionType.OnContaining) hasStatusEffects = true;
}
containableItems.Add(containable);
break; break;
} }
} }
@@ -121,11 +125,12 @@ namespace Subsurface.Items.Components
public override void Update(float deltaTime, Camera cam) public override void Update(float deltaTime, Camera cam)
{ {
if (!hasStatusEffects) return;
foreach (Item contained in inventory.items) foreach (Item contained in inventory.items)
{ {
if (contained == null || contained.Condition<=0.0f) continue; if (contained == null || contained.Condition <= 0.0f) continue;
//if (contained.body != null) contained.body.Enabled = false;
if (contained.body!=null) contained.body.Enabled = false;
RelatedItem ri = containableItems.Find(x => x.MatchesItem(contained)); RelatedItem ri = containableItems.Find(x => x.MatchesItem(contained));
if (ri == null) continue; if (ri == null) continue;
@@ -136,16 +141,15 @@ namespace Subsurface.Items.Components
if (effect.Targets.HasFlag(StatusEffect.TargetType.Contained)) effect.Apply(ActionType.OnContaining, deltaTime, item, contained.AllPropertyObjects); if (effect.Targets.HasFlag(StatusEffect.TargetType.Contained)) effect.Apply(ActionType.OnContaining, deltaTime, item, contained.AllPropertyObjects);
} }
contained.ApplyStatusEffects(ActionType.OnContained, deltaTime); //contained.ApplyStatusEffects(ActionType.OnContained, deltaTime);
} }
} }
public override void Draw(SpriteBatch spriteBatch, bool editing) public override void Draw(SpriteBatch spriteBatch, bool editing)
{ {
base.Draw(spriteBatch); base.Draw(spriteBatch);
if (hideItems || (item.body!=null && !item.body.Enabled)) return; if (hideItems || (item.body != null && !item.body.Enabled)) return;
Vector2 transformedItemPos = itemPos; Vector2 transformedItemPos = itemPos;
Vector2 transformedItemInterval = itemInterval; Vector2 transformedItemInterval = itemInterval;
@@ -84,18 +84,17 @@ namespace Subsurface.Items.Components
{ {
base.Update(deltaTime, cam); base.Update(deltaTime, cam);
if (item.body != null) if (item.container != null)
{
light.Position = ConvertUnits.ToDisplayUnits(item.body.SimPosition);
}
Pickable pickable = item.GetComponent<Pickable>();
if (item.container!= null)
{ {
light.Color = Color.Transparent; light.Color = Color.Transparent;
return; return;
} }
if (item.body != null)
{
light.Position = ConvertUnits.ToDisplayUnits(item.body.SimPosition);
}
if (powerConsumption == 0.0f) if (powerConsumption == 0.0f)
{ {
voltage = 1.0f; voltage = 1.0f;
@@ -116,7 +115,6 @@ namespace Subsurface.Items.Components
} }
light.Color = lightColor * lightBrightness * (1.0f-Rand.Range(0.0f,Flicker)); light.Color = lightColor * lightBrightness * (1.0f-Rand.Range(0.0f,Flicker));
light.Range = range * (float)Math.Sqrt(lightBrightness); light.Range = range * (float)Math.Sqrt(lightBrightness);
voltage = 0.0f; voltage = 0.0f;
@@ -35,6 +35,8 @@ namespace Subsurface.Items.Components
Nodes = new List<Vector2>(); Nodes = new List<Vector2>();
connections = new Connection[2]; connections = new Connection[2];
IsActive = false;
} }
public override void Move(Vector2 amount) public override void Move(Vector2 amount)
+1 -1
View File
@@ -116,7 +116,7 @@ namespace Subsurface
items[i] = item; items[i] = item;
item.inventory = this; item.inventory = this;
if (item.body!=null) if (item.body != null)
{ {
item.body.Enabled = false; item.body.Enabled = false;
} }
+4 -2
View File
@@ -488,6 +488,8 @@ namespace Subsurface
} }
ic.WasUsed = false; ic.WasUsed = false;
if (container != null) ic.ApplyStatusEffects(ActionType.OnContained, deltaTime);
if (!ic.IsActive) continue; if (!ic.IsActive) continue;
if (condition > 0.0f) if (condition > 0.0f)
@@ -505,7 +507,7 @@ namespace Subsurface
if (body == null || !body.Enabled) return; if (body == null || !body.Enabled) return;
if (body.LinearVelocity.Length() > 0.001f) if (Math.Abs(body.LinearVelocity.X) > 0.01f || Math.Abs(body.LinearVelocity.Y) > 0.01f)
{ {
FindHull(); FindHull();
@@ -808,7 +810,7 @@ namespace Subsurface
if (body != null && body.UserData as Item != item) continue; if (body != null && body.UserData as Item != item) continue;
dist = Vector2.Distance(pickPosition, item.SimPosition); dist = Vector2.Distance(pickPosition, item.SimPosition);
if ((closest == null || dist < closestDist)) if (dist < item.prefab.PickDistance && (closest == null || dist < closestDist))
{ {
closest = item; closest = item;
closestDist = dist; closestDist = dist;
+10 -3
View File
@@ -50,6 +50,14 @@ namespace Subsurface
float lastSentVolume; float lastSentVolume;
public override string Name
{
get
{
return "Hull";
}
}
public override bool IsLinkable public override bool IsLinkable
{ {
get { return true; } get { return true; }
@@ -202,7 +210,7 @@ namespace Subsurface
waveY[(int)(position.X - rect.X) / WaveWidth] = 100.0f; waveY[(int)(position.X - rect.X) / WaveWidth] = 100.0f;
Volume = Volume + 1500.0f; Volume = Volume + 1500.0f;
} }
else if (PlayerInput.GetMouseState.RightButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed) else if (PlayerInput.RightButtonDown())
{ {
Volume = Volume - 1500.0f; Volume = Volume - 1500.0f;
} }
@@ -210,12 +218,11 @@ namespace Subsurface
} }
//update client hulls if the amount of water has changed by >10% //update client hulls if the amount of water has changed by >10%
if (Math.Abs(lastSentVolume-volume)>FullVolume*0.1f) if (Math.Abs(lastSentVolume - volume) > FullVolume * 0.1f)
{ {
new Networking.NetworkEvent(ID, false); new Networking.NetworkEvent(ID, false);
lastSentVolume = volume; lastSentVolume = volume;
} }
if (!update) return; if (!update) return;
float surfaceY = rect.Y - rect.Height + Volume / rect.Width; float surfaceY = rect.Y - rect.Height + Volume / rect.Width;
-31
View File
@@ -852,37 +852,6 @@ int currentTargetIndex = 1;
Color.White, 0.0f, Color.White, 0.0f,
Vector2.Zero, Vector2.Zero,
SpriteEffects.None, 0.0f); SpriteEffects.None, 0.0f);
//pos = startPosition;
//pos.X += Position.X;
//pos.Y = -pos.Y - Position.Y;
//spriteBatch.Draw(shaftTexture,
// new Rectangle((int)(pos.X - shaftWidth/2), (int)pos.Y, shaftWidth, 512),
// new Rectangle(0, 0, shaftWidth, 256),
// Color.White, 0.0f,
// Vector2.Zero,
// SpriteEffects.None, 0.0f);
//List<Vector2[]> edges = GetCellEdges(observerPosition, 1, false);
//foreach (VoronoiCell cell in cells)
//{
// for (int i = 0; i < cell.bodyVertices.Count - 1; i++)
// {
// Vector2 start = cell.bodyVertices[i];
// start.X += Position.X;
// start.Y = -start.Y - Position.Y;
// start.X += Rand.Range(-10.0f, 10.0f);
// Vector2 end = cell.bodyVertices[i + 1];
// end.X += Position.X;
// end.Y = -end.Y - Position.Y;
// end.X += Rand.Range(-10.0f, 10.0f);
// GUI.DrawLine(spriteBatch, start, end, (cell.body != null && cell.body.Enabled) ? Color.Red : Color.Red);
// }
//}
} }
public List<VoronoiCell> GetCells(Vector2 pos, int searchDepth = 2) public List<VoronoiCell> GetCells(Vector2 pos, int searchDepth = 2)
+64 -9
View File
@@ -5,12 +5,31 @@ using System.Linq;
namespace Subsurface.Lights namespace Subsurface.Lights
{ {
class CachedShadow
{
public VertexPositionColor[] ShadowVertices;
public VertexPositionTexture[] PenumbraVertices;
public Vector2 LightPos;
public CachedShadow(VertexPositionColor[] shadowVertices, VertexPositionTexture[] penumbraVertices, Vector2 lightPos)
{
ShadowVertices = shadowVertices;
PenumbraVertices = penumbraVertices;
LightPos = lightPos;
}
}
class ConvexHull class ConvexHull
{ {
public static List<ConvexHull> list = new List<ConvexHull>(); public static List<ConvexHull> list = new List<ConvexHull>();
static BasicEffect shadowEffect; static BasicEffect shadowEffect;
static BasicEffect penumbraEffect; static BasicEffect penumbraEffect;
private Dictionary<LightSource, CachedShadow> cachedShadows;
private Vector2[] vertices; private Vector2[] vertices;
private int primitiveCount; private int primitiveCount;
@@ -48,18 +67,13 @@ namespace Subsurface.Lights
penumbraEffect.Texture = TextureLoader.FromFile("Content/Lights/penumbra.png"); penumbraEffect.Texture = TextureLoader.FromFile("Content/Lights/penumbra.png");
} }
cachedShadows = new Dictionary<LightSource, CachedShadow>();
vertices = points; vertices = points;
primitiveCount = vertices.Length; primitiveCount = vertices.Length;
CalculateDimensions(); CalculateDimensions();
//indices = new short[primitiveCount * 3];
//for (int i = 0; i < primitiveCount; i++)
//{
// indices[3 * i] = (short)i;
// indices[3 * i + 1] = (short)((i + 1) % vertexCount);
// indices[3 * i + 2] = (short)vertexCount;
//}
backFacing = new bool[primitiveCount]; backFacing = new bool[primitiveCount];
Enabled = true; Enabled = true;
@@ -90,6 +104,8 @@ namespace Subsurface.Lights
public void Move(Vector2 amount) public void Move(Vector2 amount)
{ {
cachedShadows.Clear();
for (int i = 0; i < vertices.Count(); i++) for (int i = 0; i < vertices.Count(); i++)
{ {
vertices[i] += amount; vertices[i] += amount;
@@ -100,6 +116,8 @@ namespace Subsurface.Lights
public void SetVertices(Vector2[] points) public void SetVertices(Vector2[] points)
{ {
cachedShadows.Clear();
vertices = points; vertices = points;
} }
@@ -222,17 +240,54 @@ namespace Subsurface.Lights
} }
} }
public void DrawShadows(GraphicsDevice graphicsDevice, Camera cam, LightSource light, Matrix transform, bool los = true)
{
if (!Enabled) return;
CachedShadow cachedShadow = null;
if (cachedShadows.TryGetValue(light, out cachedShadow))
{
if (light.Position == cachedShadow.LightPos ||
Vector2.DistanceSquared(light.Position, cachedShadow.LightPos) < 1.0f)
{
shadowVertices = cachedShadow.ShadowVertices;
penumbraVertices = cachedShadow.PenumbraVertices;
}
else
{
CalculateShadowVertices(light.Position, los);
cachedShadow.LightPos = light.Position;
cachedShadow.ShadowVertices = shadowVertices;
cachedShadow.PenumbraVertices = penumbraVertices;
}
}
else
{
CalculateShadowVertices(light.Position, los);
cachedShadow = new CachedShadow(shadowVertices, penumbraVertices, light.Position);
cachedShadows.Add(light, cachedShadow);
}
DrawShadows(graphicsDevice, cam, transform, los);
}
public void DrawShadows(GraphicsDevice graphicsDevice, Camera cam, Vector2 lightSourcePos, Matrix transform, bool los = true) public void DrawShadows(GraphicsDevice graphicsDevice, Camera cam, Vector2 lightSourcePos, Matrix transform, bool los = true)
{ {
if (!Enabled) return; if (!Enabled) return;
CalculateShadowVertices(lightSourcePos, los); CalculateShadowVertices(lightSourcePos, los);
DrawShadows(graphicsDevice, cam, transform, los);
}
private void DrawShadows(GraphicsDevice graphicsDevice, Camera cam, Matrix transform, bool los = true)
{
shadowEffect.World = transform; shadowEffect.World = transform;
shadowEffect.CurrentTechnique.Passes[0].Apply(); shadowEffect.CurrentTechnique.Passes[0].Apply();
graphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, shadowVertices, 0, shadowVertices.Length - 2); graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, shadowVertices, 0, shadowVertices.Length - 2);
if (los) if (los)
{ {
@@ -240,7 +295,7 @@ namespace Subsurface.Lights
penumbraEffect.CurrentTechnique.Passes[0].Apply(); penumbraEffect.CurrentTechnique.Passes[0].Apply();
#if WINDOWS #if WINDOWS
graphicsDevice.DrawUserPrimitives<VertexPositionTexture>(PrimitiveType.TriangleList, penumbraVertices, 0, 2, VertexPositionTexture.VertexDeclaration); graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, penumbraVertices, 0, 2, VertexPositionTexture.VertexDeclaration);
#endif #endif
} }
} }
+30 -7
View File
@@ -57,12 +57,13 @@ namespace Subsurface.Lights
public void DrawLOS(GraphicsDevice graphics, Camera cam, Vector2 pos) public void DrawLOS(GraphicsDevice graphics, Camera cam, Vector2 pos)
{ {
if (!LosEnabled) return;
Rectangle camView = new Rectangle(cam.WorldView.X, cam.WorldView.Y - cam.WorldView.Height, cam.WorldView.Width, cam.WorldView.Height); Rectangle camView = new Rectangle(cam.WorldView.X, cam.WorldView.Y - cam.WorldView.Height, cam.WorldView.Width, cam.WorldView.Height);
Matrix shadowTransform = cam.ShaderTransform Matrix shadowTransform = cam.ShaderTransform
* Matrix.CreateOrthographic(GameMain.GraphicsWidth, GameMain.GraphicsHeight, -1, 1) * 0.5f; * Matrix.CreateOrthographic(GameMain.GraphicsWidth, GameMain.GraphicsHeight, -1, 1) * 0.5f;
if (!LosEnabled) return;
foreach (ConvexHull convexHull in ConvexHull.list) foreach (ConvexHull convexHull in ConvexHull.list)
{ {
if (!camView.Intersects(convexHull.BoundingBox)) continue; if (!camView.Intersects(convexHull.BoundingBox)) continue;
@@ -72,6 +73,14 @@ namespace Subsurface.Lights
} }
public void OnMapLoaded()
{
foreach (LightSource light in lights)
{
light.UpdateHullsInRange();
}
}
public void DrawLightmap(GraphicsDevice graphics, SpriteBatch spriteBatch, Camera cam) public void DrawLightmap(GraphicsDevice graphics, SpriteBatch spriteBatch, Camera cam)
{ {
Matrix shadowTransform = cam.ShaderTransform Matrix shadowTransform = cam.ShaderTransform
@@ -87,22 +96,22 @@ namespace Subsurface.Lights
foreach (LightSource light in lights) foreach (LightSource light in lights)
{ {
if (light.Color.A < 0.01f || light.Range < 0.01f) continue; if (light.Color.A < 0.01f || light.Range < 0.01f || light.hullsInRange.Count == 0) continue;
if (!MathUtils.CircleIntersectsRectangle(light.Position, light.Range, viewRect)) continue;
//clear alpha to 1 //clear alpha to 1
ClearAlphaToOne(graphics, spriteBatch); ClearAlphaToOne(graphics, spriteBatch);
if (!MathUtils.CircleIntersectsRectangle(light.Position, light.Range, viewRect)) continue;
//draw all shadows //draw all shadows
//write only to the alpha channel, which sets alpha to 0 //write only to the alpha channel, which sets alpha to 0
graphics.RasterizerState = RasterizerState.CullNone; graphics.RasterizerState = RasterizerState.CullNone;
graphics.BlendState = CustomBlendStates.WriteToAlpha; graphics.BlendState = CustomBlendStates.WriteToAlpha;
foreach (ConvexHull ch in ConvexHull.list) foreach (ConvexHull ch in light.hullsInRange)
{ {
if (!MathUtils.CircleIntersectsRectangle(light.Position, light.Range, ch.BoundingBox)) continue; //if (!MathUtils.CircleIntersectsRectangle(light.Position, light.Range, ch.BoundingBox)) continue;
//draw shadow //draw shadow
ch.DrawShadows(graphics, cam, light.Position, shadowTransform, false); ch.DrawShadows(graphics, cam, light, shadowTransform, false);
} }
//draw the light shape //draw the light shape
@@ -111,6 +120,20 @@ namespace Subsurface.Lights
light.Draw(spriteBatch); light.Draw(spriteBatch);
spriteBatch.End(); spriteBatch.End();
} }
//ClearAlphaToOne(graphics, spriteBatch);
//spriteBatch.Begin(SpriteSortMode.Immediate, CustomBlendStates.MultiplyWithAlpha, null, null, null, null, cam.Transform);
//foreach (LightSource light in lights)
//{
// if (light.Color.A < 0.01f || light.Range < 0.01f || light.hullsInRange.Count > 0) continue;
// if (!MathUtils.CircleIntersectsRectangle(light.Position, light.Range, viewRect)) continue;
// light.Draw(spriteBatch);
//}
//spriteBatch.End();
//clear alpha, to avoid messing stuff up later //clear alpha, to avoid messing stuff up later
ClearAlphaToOne(graphics, spriteBatch); ClearAlphaToOne(graphics, spriteBatch);
graphics.SetRenderTarget(null); graphics.SetRenderTarget(null);
+34 -4
View File
@@ -11,13 +11,26 @@ namespace Subsurface.Lights
{ {
private static Texture2D lightTexture; private static Texture2D lightTexture;
public List<ConvexHull> hullsInRange;
private Color color; private Color color;
private float range; private float range;
private Texture2D texture; private Texture2D texture;
public Vector2 Position; private Vector2 position;
public Vector2 Position
{
get { return position; }
set
{
if (position == value) return;
position = value;
UpdateHullsInRange();
}
}
public Color Color public Color Color
{ {
@@ -30,13 +43,19 @@ namespace Subsurface.Lights
get { return range; } get { return range; }
set set
{ {
range = MathHelper.Clamp(value, 0.0f, 2048.0f); float newRange = MathHelper.Clamp(value, 0.0f, 2048.0f);
if (range == newRange) return;
range = newRange;
UpdateHullsInRange();
} }
} }
public LightSource(Vector2 position, float range, Color color) public LightSource(Vector2 position, float range, Color color)
{ {
Position = position; hullsInRange = new List<ConvexHull>();
this.position = position;
this.range = range; this.range = range;
this.color = color; this.color = color;
@@ -50,10 +69,21 @@ namespace Subsurface.Lights
GameMain.LightManager.AddLight(this); GameMain.LightManager.AddLight(this);
} }
public void UpdateHullsInRange()
{
hullsInRange.Clear();
if (range < 1.0f) return;
foreach (ConvexHull ch in ConvexHull.list)
{
if (MathUtils.CircleIntersectsRectangle(position, range, ch.BoundingBox)) hullsInRange.Add(ch);
}
}
public void Draw(SpriteBatch spriteBatch) public void Draw(SpriteBatch spriteBatch)
{ {
Vector2 center = new Vector2(lightTexture.Width / 2, lightTexture.Height / 2); Vector2 center = new Vector2(lightTexture.Width / 2, lightTexture.Height / 2);
float scale = range / ((float)lightTexture.Width / 2.0f); float scale = range / (lightTexture.Width / 2.0f);
spriteBatch.Draw(lightTexture, new Vector2(Position.X, -Position.Y), null, color, 0, center, scale, SpriteEffects.None, 1); spriteBatch.Draw(lightTexture, new Vector2(Position.X, -Position.Y), null, color, 0, center, scale, SpriteEffects.None, 1);
} }
+40 -2
View File
@@ -192,6 +192,8 @@ namespace Subsurface
} }
} }
static Dictionary<string, float> timeElapsed = new Dictionary<string, float>();
/// <summary> /// <summary>
/// Call Update() on every object in Entity.list /// Call Update() on every object in Entity.list
/// </summary> /// </summary>
@@ -202,10 +204,46 @@ namespace Subsurface
item.Updated = false; item.Updated = false;
} }
for (int i = 0; i < mapEntityList.Count; i++) foreach (Hull hull in Hull.hullList)
{ {
mapEntityList[i].Update(cam, deltaTime); hull.Update(cam, deltaTime);
} }
foreach (Gap gap in Gap.GapList)
{
gap.Update(cam, deltaTime);
}
foreach (Item item in Item.itemList)
{
item.Update(cam, deltaTime);
}
//Stopwatch sw = new Stopwatch();
//for (int i = 0; i < mapEntityList.Count; i++)
//{
// sw.Restart();
// mapEntityList[i].Update(cam, deltaTime);
// sw.Stop();
// if (timeElapsed.ContainsKey(mapEntityList[i].Name))
// {
// float asd = 0.0f;
// timeElapsed.TryGetValue(mapEntityList[i].Name, out asd);
// asd += sw.ElapsedTicks;
// timeElapsed.Remove(mapEntityList[i].Name);
// timeElapsed.Add(mapEntityList[i].Name, asd);
// }
// else
// {
// timeElapsed.Add(mapEntityList[i].Name, sw.ElapsedTicks);
// }
//}
} }
public virtual void Update(Camera cam, float deltaTime) { } public virtual void Update(Camera cam, float deltaTime) { }
+2
View File
@@ -618,6 +618,8 @@ namespace Subsurface
} }
} }
GameMain.LightManager.OnMapLoaded();
ID = int.MaxValue-10; ID = int.MaxValue-10;
loaded = this; loaded = this;
+8
View File
@@ -29,6 +29,14 @@ namespace Subsurface
set { spawnType = value; } set { spawnType = value; }
} }
public override string Name
{
get
{
return "WayPoint";
}
}
public string[] IdCardTags public string[] IdCardTags
{ {
get { return idCardTags; } get { return idCardTags; }
+6 -1
View File
@@ -127,7 +127,12 @@ namespace Subsurface
&& mouseState.LeftButton == ButtonState.Released); && mouseState.LeftButton == ButtonState.Released);
} }
public static bool RightButtonClicked() public static bool RightButtonDown()
{
return mouseState.RightButton == ButtonState.Pressed;
}
public static bool RightButtonClicked()
{ {
return (oldMouseState.RightButton == ButtonState.Pressed return (oldMouseState.RightButton == ButtonState.Pressed
&& mouseState.RightButton == ButtonState.Released); && mouseState.RightButton == ButtonState.Released);
+3 -11
View File
@@ -158,7 +158,7 @@ namespace Subsurface
public void DrawMap(GraphicsDevice graphics, SpriteBatch spriteBatch) public void DrawMap(GraphicsDevice graphics, SpriteBatch spriteBatch)
{ {
GameMain.LightManager.DrawLightmap(graphics, spriteBatch, cam); if (GameMain.LightManager.LightingEnabled) GameMain.LightManager.DrawLightmap(graphics, spriteBatch, cam);
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
//1. draw the background, characters and the parts of the submarine that are behind them //1. draw the background, characters and the parts of the submarine that are behind them
@@ -268,16 +268,6 @@ namespace Subsurface
Hull.renderer.Render(graphics, cam, renderTargetAir, Cam.ShaderTransform); Hull.renderer.Render(graphics, cam, renderTargetAir, Cam.ShaderTransform);
spriteBatch.Begin(SpriteSortMode.BackToFront,
BlendState.AlphaBlend, SamplerState.LinearWrap,
null, null, null,
cam.Transform);
Submarine.DrawFront(spriteBatch);
spriteBatch.End();
if (GameMain.GameSession != null && GameMain.GameSession.Level != null) if (GameMain.GameSession != null && GameMain.GameSession.Level != null)
{ {
GameMain.GameSession.Level.Render(graphics, cam); GameMain.GameSession.Level.Render(graphics, cam);
@@ -303,6 +293,8 @@ namespace Subsurface
foreach (Character c in Character.CharacterList) c.DrawFront(spriteBatch); foreach (Character c in Character.CharacterList) c.DrawFront(spriteBatch);
Submarine.DrawFront(spriteBatch);
if (GameMain.GameSession != null && GameMain.GameSession.Level != null) if (GameMain.GameSession != null && GameMain.GameSession.Level != null)
{ {
GameMain.GameSession.Level.Draw(spriteBatch); GameMain.GameSession.Level.Draw(spriteBatch);
+1 -1
View File
@@ -148,7 +148,7 @@
<Compile Include="Source\FrameCounter.cs" /> <Compile Include="Source\FrameCounter.cs" />
<Compile Include="Source\GUI\GUIStyle.cs" /> <Compile Include="Source\GUI\GUIStyle.cs" />
<Compile Include="Source\GUI\GUITextBox.cs" /> <Compile Include="Source\GUI\GUITextBox.cs" />
<Compile Include="Source\Items\Components\Container.cs" /> <Compile Include="Source\Items\Components\ItemContainer.cs" />
<Compile Include="Source\Items\Components\Machines\Controller.cs" /> <Compile Include="Source\Items\Components\Machines\Controller.cs" />
<Compile Include="Source\Items\Components\Door.cs" /> <Compile Include="Source\Items\Components\Door.cs" />
<Compile Include="Source\Items\Components\Ladder.cs" /> <Compile Include="Source\Items\Components\Ladder.cs" />
+2 -8
View File
@@ -1,7 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013 # Visual Studio 14
VisualStudioVersion = 12.0.21005.1 VisualStudioVersion = 14.0.23107.0
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Subsurface", "Subsurface\Subsurface.csproj", "{008C0F83-E914-4966-9135-EA885059EDD8}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Subsurface", "Subsurface\Subsurface.csproj", "{008C0F83-E914-4966-9135-EA885059EDD8}"
EndProject EndProject
@@ -20,9 +20,6 @@ EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CrashReporter", "CrashReporter\CrashReporter.csproj", "{6BE950CD-9A34-49C9-939A-786AC89C287E}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CrashReporter", "CrashReporter\CrashReporter.csproj", "{6BE950CD-9A34-49C9-939A-786AC89C287E}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D32A29D8-AC7B-4189-B734-8ED9EB4120D0}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D32A29D8-AC7B-4189-B734-8ED9EB4120D0}"
ProjectSection(SolutionItems) = preProject
Performance1.psess = Performance1.psess
EndProjectSection
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -401,7 +398,4 @@ Global
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(Performance) = preSolution
HasPerformanceSessions = true
EndGlobalSection
EndGlobal EndGlobal