Skip to content

Commit

Permalink
Graf
Browse files Browse the repository at this point in the history
  • Loading branch information
SWCreeperKing committed Nov 14, 2021
1 parent 030f027 commit 092f5d9
Show file tree
Hide file tree
Showing 7 changed files with 163 additions and 23 deletions.
24 changes: 22 additions & 2 deletions RayWrapper/GeneralWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ public static Color MakeDarker(this Color color) =>
// AssembleRectFromVec(pos, textSize).Grow(4).Draw(new Color(0, 0, 0, 200));
// DrawTextEx(GameBox.Font, text, pos, fontSize, spacing, color);
// }

[Obsolete("Use an actual clamp i.e. Math.Clamp(), but I won't judge you if you REALLY WANT to use this")]
public static double Clamp<T>(this T n, T min, T max) =>
n switch
Expand All @@ -91,6 +90,9 @@ public static Color EditColor(this Color color, int r = 0, int g = 0, int b = 0,
public static void DrawLine(this Vector2 v1, Vector2 v2, Color color, float thickness = 3) =>
DrawLineEx(v1, v2, thickness, color);

public static void DrawBezLine(this Vector2 v1, Vector2 v2, Color color, float thickness = 3) =>
DrawLineBezier(v1, v2, thickness, color);

public static void DrawLine(this (Vector2 v1, Vector2 v2) l, Color color, float thickness = 3) =>
DrawLineEx(l.v1, l.v2, thickness, color);

Expand Down Expand Up @@ -122,6 +124,10 @@ public static void DrawArrAsLine(this Vector2[] array, Color color, int thicknes
for (var i = 1; i < array.Length; i++) array[i - 1].DrawLine(array[i], color, thickness);
}

public static void DrawArrAsBezLine(this Vector2[] array, Color color, int thickness = 3)
{
for (var i = 1; i < array.Length; i++) array[i - 1].DrawBezLine(array[i], color, thickness);
}

public static Texture2D Texture(this Image i) => LoadTextureFromImage(i);

Expand Down Expand Up @@ -153,7 +159,7 @@ public static bool IsVectInVects(this Vector2 vect, Vector2 pos, Vector2 size, f

public static Vector2 Size(this Image img) => img.Texture().Size();
public static Vector2 Size(this Texture2D t2d) => new(t2d.width, t2d.height);

public static void MaskDraw(this Vector2 pos, Vector2 size, Action draw)
{
maskingLayer++;
Expand All @@ -162,5 +168,19 @@ public static void MaskDraw(this Vector2 pos, Vector2 size, Action draw)
if (maskingLayer == 1) EndScissorMode();
maskingLayer--;
}

public static void DrawCircle(this Vector2 v2, float r, Color? color = null) =>
DrawCircleV(v2, r, color ?? Color.WHITE);

public static Vector2 FixVector(this Vector2 v2) => new Vector2(v2.X.Fix(), v2.Y.Fix());

public static bool IsFixable(this float f) => float.IsNaN(f) || float.IsInfinity(f);

public static float Fix(this float f) =>
f.IsFixable()
? float.IsNegative(f)
? float.MinValue
: float.MaxValue
: f;
}
}
94 changes: 88 additions & 6 deletions RayWrapper/Objs/Graph.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Raylib_cs;
using RayWrapper.Vars;

namespace RayWrapper.Objs
{
public class Graph : GameObject
{
public Rectangle rect;
public Graph(Rectangle rect) => this.rect = rect;

// todo: eventually
public readonly Vector2 neg = new(-1, -1);

public override Vector2 Position
{
Expand All @@ -19,16 +19,98 @@ public override Vector2 Position

public override Vector2 Size => rect.Size();

public Rectangle rect;
public ColorModule lineColor = Color.DARKBLUE;
public int thickness = 3;
public int range = -1;
public bool useBezier = false;
public Actionable<float> maxConstraint = float.MaxValue;
public Actionable<float> minConstraint = float.MinValue;

private readonly List<Vector2> _values = new();
private readonly Dictionary<Vector2, Vector2> _realVal = new();
private Vector2[] _cacheValues;
private Vector2 closest = new(-1, -1);

public Graph(Rectangle rect) => this.rect = rect;

protected override void UpdateCall()
{
if (!rect.IsMouseIn())
{
closest = neg;
return;
}

var mouse = GameBox.mousePos;
closest = _cacheValues.Select(v2 => (pos: v2, dist: Vector2.Distance(mouse, v2))).OrderBy(t => t.dist)
.First().pos;
}

protected override void RenderCall()
{
var grow = rect.Grow(4);
if (_cacheValues.Length < 2) return;
grow.MaskDraw(() =>
{
if (useBezier) _cacheValues.DrawArrAsBezLine(lineColor, thickness);
else _cacheValues.DrawArrAsLine(lineColor, thickness);
});
grow.DrawHallowRect(Color.BLACK);
if (closest == neg) return;
closest.DrawCircle(3);
if (_realVal.ContainsKey(closest)) GameBox.tooltip.Add(_realVal[closest].ToString());
}

public void UpdateVal()
{
if (_values.Count < 1) return;
var val = (range != -1 && _values.Count > range
? _values.ToArray()[(_values.Count - range)..]
: (IEnumerable<Vector2>)_values).ToList();
var minC = (float) minConstraint;
var maxC = (float) maxConstraint;
var minCalc = val.Where(v2 => v2.X > minC && v2.Y > minC);
var maxCalc = val.Where(v2 => v2.X < maxC && v2.Y < maxC);
var min = new Vector2(minCalc.Min(v => v.X), minCalc.Min(v => v.Y));
var max = new Vector2(maxCalc.Max(v => v.X), maxCalc.Max(v => v.Y));
var size = max - min;
var scaling = size / rect.Size();
_cacheValues = val.Select(v2 =>
(v2 - min) / scaling * new Vector2(1, -1) + rect.Pos() + new Vector2(0, rect.height))
.ToArray();
for (var i = 0; i < val.Count; i++)
if (!_realVal.ContainsKey(_cacheValues[i]))
_realVal.Add(_cacheValues[i], val[i]);
}

public void UpdateGraphValues()
public void NewVal(params Vector2[] v)
{
Clear();
AddVal(v);
}

public void AddVal(params Vector2[] v)
{
_values.AddRange(v.Select(v => v.FixVector()));
UpdateVal();
}

public void RemoveVal(Vector2 v)
{
_values.Remove(v);
UpdateVal();
}

public void Clear()
{
_values.Clear();
UpdateVal();
}

public void ExecuteFunction(Func<float, Vector2> func, int start = 0, int count = 500, float dx = .1f) =>
NewVal(Enumerable.Range(start, count).Select(i => func.Invoke(i * dx)).ToArray());

public int Amount() => _values.Count;
}
}
12 changes: 9 additions & 3 deletions RayWrapper/Objs/ListView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,13 @@ public override Vector2 Position
public Func<int, Color> backColors;
public Func<int, Color> fontColors;
public Func<int, string> itemProcessing;
public Func<int, string> indivTooltip;
public Action click;
public Action outsideClick;
public bool randomPitch = true;
public bool showTooltip = true;
public bool rememberLast = true;
public bool useSelection = true;
public bool selectedToggle;

private readonly Label[] _labels;
Expand Down Expand Up @@ -65,7 +67,7 @@ public ListView(Vector2 pos, int width, Func<int, string> itemProcessing, Func<i
for (var i = 0; i < _labels.Length; i++)
_labels[i] = new Label(new Rectangle(0, 0, _bounds.width, labelHeight))
{
useBaseHover = new Actionable<bool>(() => _individualClick is not null)
useBaseHover = new Actionable<bool>(() => _individualClick is not null), updateReturnIfNonVis = true
};
_bar.OnMoveEvent += UpdateLabels;
UpdateLabels(0);
Expand Down Expand Up @@ -96,20 +98,22 @@ private void UpdateLabels(float value)
var strictVal = (int)value;
var labelPadding = _labelHeight + _padding;
var y = _bounds.Pos().Y - labelPadding * (value - strictVal);
foreach (var l in _labels) l.backColor = l.fontColor = new ColorModule(Transparent);
foreach (var l in _labels) l.isVisible = false;

for (var i = 0; i < Math.Min(_labels.Length, arrayLength.Invoke() - strictVal); i++)
{
var notI = i;
var place = strictVal + notI;
var l = _labels[i];
l.isVisible = true;
l.text = new Actionable<string>(() =>this[place]);
if (_individualClick is not null)
l.clicked = () =>
{
_individualClick(place);
if (!useSelection) return;
if (_lastSelect == place && selectedToggle) _lastSelect = -1;
else _lastSelect = place;
_individualClick(place);
};
l.Position = new Vector2(_bounds.x, y + labelPadding * i);
l.backColor =
Expand All @@ -119,6 +123,8 @@ private void UpdateLabels(float value)
: backColors?.Invoke(place) ?? (Color)backColor);
l.fontColor =
new ColorModule(fontColors?.Invoke(place) ?? (Color)fontColor);
if (indivTooltip is null) continue;
l.tooltip = indivTooltip.Invoke(place);
}
}

Expand Down
2 changes: 2 additions & 0 deletions RayWrapper/Vars/GameObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public abstract class GameObject : GameObjReg

public float FullLength => Position.X + Size.X;
public float FullHeight => Position.Y + Size.Y;
public bool updateReturnIfNonVis;

private Rectangle _rect = Zero;
private Vector2 _freezeV2 = Vector2.Zero;
Expand All @@ -25,6 +26,7 @@ public void Update()
isDebugTool) debugContext = null;
else if (_rect.IsMouseIn() && IsMouseButtonPressed(MouseButton.MOUSE_MIDDLE_BUTTON) &&
isDebugTool) debugContext = this;
if (updateReturnIfNonVis && !isVisible) return;
UpdateCall();
UpdateReg();
}
Expand Down
8 changes: 8 additions & 0 deletions RayWrapper/Vars/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,14 @@ public static void RayLog(TraceLogLevel logLevel, string text, IntPtr args) =>
_ => throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null)
}, RayForm($"from raylib: {text}", args));

public static void Log(string text) => Log(Debug, text);

public static T LogReturn<T>(T t)
{
Log(t.ToString());
return t;
}

public static void Log(Level level, string text)
{
if (level == Error) hasError = true;
Expand Down
18 changes: 7 additions & 11 deletions RayWrapper/Vars/NumberClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public enum Format
Engineering,
}

public static readonly float Version = .25f;
public static readonly float Version = .26f;
public static bool CutOff1E = true; // format; 1e1e30 => 1ee30
public static int SciStaticLeng = 4;
public static Format format = Format.Scientific;
Expand All @@ -32,6 +32,8 @@ public enum Format
public static readonly NumberClass One = new(1);
public static readonly NumberClass Zero = new();

private static readonly Regex RegReplace = new Regex(@"e(1|1.0*)e");

public double mantissa;
public double exponent;

Expand Down Expand Up @@ -66,18 +68,12 @@ public NumberClass(string s)

private void Update()
{
switch (mantissa)
{
case <= 0.0009 and > -0.0009:
mantissa = exponent = 0;
return;
case < 1 and > 0 when exponent == 0:
return;
}
mantissa = Math.Round(mantissa, 5);

var isNeg = mantissa < 0;
if (isNeg) mantissa = -mantissa;
var log = (long)Math.Log10(mantissa);
if (log < 0) log = (long)Math.Max(0, Math.Min(log, exponent));
mantissa /= Math.Pow(10, log);
if (isNeg) mantissa = -mantissa;
exponent += log;
Expand Down Expand Up @@ -221,7 +217,7 @@ public string FormatNc(Format format)
var useMan = !IsMantissaUseless(); // if take mantissa or leave it

// does not catch engineering but w.e. is probs fine
string CutOff1Check(string s) => !CutOff1E ? s : Regex.Replace(s, @"e(1|1.0*)e", "ee");
string CutOff1Check(string s) => !CutOff1E ? s : RegReplace.Replace(s, "ee");

// get proper format
// can be #.000 or #.###
Expand All @@ -241,7 +237,7 @@ string GetFormatFromCount(int count, bool optional = false) =>
case Format.ScientificStatic:
// format to keep numclass the same leng
formatExponent = new NumberClass(exponent).FormatNc(Format.Scientific);
formatMantissa = useMan ? $"{mantissa.ToString(GetFormatFromCount(SciStaticLeng, false))}" : "";
formatMantissa = useMan ? $"{mantissa.ToString(GetFormatFromCount(SciStaticLeng))}" : "";
return CutOff1Check($"{formatMantissa}e{formatExponent}");
default:
formatMantissa = useMan
Expand Down
28 changes: 27 additions & 1 deletion RayWrapperTester/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@ class Program : GameLoop
private ListView _lv;
private DropDown _dd;

private Graph graf;

private Func<float, Vector2>[] grafFunc =
{
dx => new Vector2(dx * 10, (float)Math.Sin(dx)),
dx => new Vector2((float)(dx * Math.Cos(dx)), (float)(dx * Math.Sin(dx))),
dx => new Vector2(dx, (float)Math.Log(dx)),
dx => new Vector2(dx, (float)Math.Exp(dx)),
dx => new Vector2(dx / 5f - 5, (float)Math.Tan(dx / 5f - 5)),
dx => new Vector2(dx, (float)Math.Sin(Math.Pow(dx, 2)))
};

private int currGraf;

private string yes =
"What the fuck did you just fucking say about me, you little bitch? I'll have you know I graduated top of my class in the Navy Seals, and I've been involved in numerous secret raids on Al-Quaeda, and I have over 300 confirmed kills. I am trained in gorilla warfare and I'm the top sniper in the entire US armed forces. You are nothing to me but just another target. I will wipe you the fuck out with precision the likes of which has never been seen before on this Earth, mark my fucking words. You think you can get away with saying that shit to me over the Internet? Think again, fucker. As we speak I am contacting my secret network of spies across the USA and your IP is being traced right now so you better prepare for the storm, maggot. The storm that wipes out the pathetic little thing you call your life. You're fucking dead, kid. I can be anywhere, anytime, and I can kill you in over seven hundred ways, and that's just with my bare hands. Not only am I extensively trained in unarmed combat, but I have access to the entire arsenal of the United States Marine Corps and I will use it to its full extent to wipe your miserable ass off the face of the continent, you little shit. If only you could have known what unholy retribution your little \"clever\" comment was about to bring down upon you, maybe you would have held your fucking tongue. But you couldn't, you didn't, and now you're paying the price, you goddamn idiot. I will shit fury all over you and you will drown in it. You're fucking dead, kiddo.";

Expand Down Expand Up @@ -180,11 +194,18 @@ public override void Init()
{
ClearBackground(RED);
bRend.Render();
GameBox.tooltip.Add($"{mousePos}");
tooltip.Add($"{mousePos}");
// mousePos.DrawToolTipAtPoint($"{mousePos}", BLUE);
});
}));

graf = new(new Rectangle(50, 100, 1000, 400));
_tbv.AddTab("Graphy", graf,
new Text(new Actionable<string>(() => $"A: {graf.Amount()}"), new Vector2(120, 520)));
graf.minConstraint = new Actionable<float>(() => currGraf == 4 ? -6 : float.MinValue);
graf.maxConstraint = new Actionable<float>(() => currGraf == 4 ? 6 : float.MaxValue);
graf.ExecuteFunction(grafFunc[0]);

RegisterGameObj(_tbv);

// W: [(%, 16)] H: [(!, 24)]
Expand Down Expand Up @@ -214,6 +235,11 @@ public override void UpdateLoop()
if (IsKeyDown(KeyboardKey.KEY_UP)) _l.Position += new Vector2(0, -3);
else if (IsKeyDown(KeyboardKey.KEY_DOWN)) _l.Position += new Vector2(0, 3);
if (IsKeyPressed(KeyboardKey.KEY_SPACE)) _tbv.Closable = !_tbv.Closable;

if (!IsKeyPressed(KeyboardKey.KEY_R)) return;
currGraf++;
currGraf %= grafFunc.Length;
graf.ExecuteFunction(grafFunc[currGraf]);
}

public override void RenderLoop()
Expand Down

0 comments on commit 092f5d9

Please sign in to comment.