Client LuaCsForBarotrauma
Graph.cs
1 using Microsoft.Xna.Framework;
2 using Microsoft.Xna.Framework.Graphics;
3 using System;
4 using System.Linq;
5 
6 namespace Barotrauma
7 {
8  class Graph
9  {
10  private float[] values;
11 
12  public Graph(int arraySize = 100)
13  {
14  values = new float[arraySize];
15  }
16 
17  public float LargestValue()
18  {
19  float maxValue = 0.0f;
20  for (int i = 0; i < values.Length; i++)
21  {
22  if (values[i] > maxValue) maxValue = values[i];
23  }
24  return maxValue;
25  }
26 
27  public float Average()
28  {
29  return values.Length == 0 ? 0.0f : values.Average();
30  }
31 
32  public void Update(float newValue)
33  {
34  for (int i = values.Length - 1; i > 0; i--)
35  {
36  values[i] = values[i - 1];
37  }
38  values[0] = newValue;
39  }
40 
41  public delegate void GraphDelegate(SpriteBatch spriteBatch, float value, int order, Vector2 position);
42 
43  public void Draw(SpriteBatch spriteBatch, Rectangle rect, float? maxValue = null, float xOffset = 0, Color? color = null, GraphDelegate doForEachValue = null)
44  {
45  color ??= Color.White;
46  float graphMaxVal = 1.0f;
47  if (maxValue == null)
48  {
49  graphMaxVal = LargestValue();
50  }
51  else if (maxValue > 0.0f)
52  {
53  graphMaxVal = (float)maxValue;
54  }
55 
56  GUI.DrawRectangle(spriteBatch, rect, Color.White);
57 
58  if (values.Length == 0) { return; }
59 
60  float lineWidth = rect.Width / (float)(values.Length - 2);
61  float yScale = rect.Height / graphMaxVal;
62 
63  Vector2 prevPoint = new Vector2(rect.Right, rect.Bottom - (values[1] + (values[0] - values[1]) * xOffset) * yScale);
64  float currX = rect.Right - ((xOffset - 1.0f) * lineWidth);
65  for (int i = 1; i < values.Length - 1; i++)
66  {
67  float value = values[i];
68  currX -= lineWidth;
69  Vector2 newPoint = new Vector2(currX, rect.Bottom - value * yScale);
70  GUI.DrawLine(spriteBatch, prevPoint, newPoint - new Vector2(1.0f, 0), color.Value);
71  prevPoint = newPoint;
72  doForEachValue?.Invoke(spriteBatch, value, i, newPoint);
73  }
74  int lastIndex = values.Length - 1;
75  float lastValue = values[lastIndex];
76  Vector2 lastPoint = new Vector2(rect.X, rect.Bottom - (lastValue + (values[values.Length - 2] - lastValue) * xOffset) * yScale);
77  GUI.DrawLine(spriteBatch, prevPoint, lastPoint, color.Value);
78  doForEachValue?.Invoke(spriteBatch, lastValue, lastIndex, lastPoint);
79  }
80  }
81 }
Graph(int arraySize=100)
Definition: Graph.cs:12
delegate void GraphDelegate(SpriteBatch spriteBatch, float value, int order, Vector2 position)
float Average()
Definition: Graph.cs:27
void Draw(SpriteBatch spriteBatch, Rectangle rect, float? maxValue=null, float xOffset=0, Color? color=null, GraphDelegate doForEachValue=null)
Definition: Graph.cs:43
float LargestValue()
Definition: Graph.cs:17
void Update(float newValue)
Definition: Graph.cs:32