This repository was archived by the owner on Aug 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUtil.cs
More file actions
443 lines (392 loc) · 16.7 KB
/
Util.cs
File metadata and controls
443 lines (392 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
using BuildPlate_Editor.Maths;
using Microsoft.Win32;
using Newtonsoft.Json;
using OpenTK;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SystemPlus;
namespace BuildPlate_Editor
{
public static class Util
{
public static readonly int CoreCount = Environment.ProcessorCount;
public static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions() { MaxDegreeOfParallelism = CoreCount };
public const float PI = (float)Math.PI;
public static string Base64Encode(string normal)
{
var plainTextBytes = Encoding.UTF8.GetBytes(normal);
return Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64)
{
var base64EncodedBytes = Convert.FromBase64String(base64);
return Encoding.UTF8.GetString(base64EncodedBytes);
}
public static T JsonDeserialize<T>(string json)
{
TextReader reader = new StringReader(json);
T value = (T)JsonSerializer.CreateDefault().Deserialize(reader, typeof(T));
reader.Dispose();
return value;
}
public static string JsonSerialize<T>(T value)
{
StringBuilder builder = new StringBuilder();
TextWriter writer = new StringWriter(builder);
JsonSerializer.CreateDefault().Serialize(writer, value);
writer.Dispose();
return builder.ToString();
}
public static int Normalized(this int i)
{
int value = Math.Min(Math.Max(i, -1), 1);
if (value == 0)
value = 1;
return value;
}
// Borrowed from here: https://keithmaggio.wordpress.com/2011/02/15/math-magician-lerp-slerp-and-nlerp/
public static Vector3 Slerp(Vector3 start, Vector3 end, float percent)
{
// Dot product - the cosine of the angle between 2 vectors.
float dot = Vector3.Dot(start, end);
// Clamp it to be in the range of Acos()
// This may be unnecessary, but floating point
// precision can be a fickle mistress.
dot = MathPlus.Clamp(dot, -1.0f, 1.0f);
// Acos(dot) returns the angle between start and end,
// And multiplying that by percent returns the angle between
// start and the final result.
float theta = (float)Math.Acos(dot) * percent;
Vector3 RelativeVec = end - start * dot;
RelativeVec.Normalize();
// Orthonormal basis
// The final result.
return (start * (float)Math.Cos(theta)) + (RelativeVec * (float)Math.Sin(theta));
}
public static void Sort(ref int smaller, ref int bigger)
{
if (smaller > bigger) {
int i = bigger;
bigger = smaller;
smaller = i;
}
}
public static void Sort(ref Vector3i smaller, ref Vector3i bigger)
{
Sort(ref smaller.X, ref bigger.X);
Sort(ref smaller.Y, ref bigger.Y);
Sort(ref smaller.Z, ref bigger.Z);
}
public static int GetRotDiff(int rot1, int rot2)
{
while (rot1 < rot2) {
rot1++;
rot2++;
rot1 %= 4;
rot2 %= 4;
}
int diff = rot2 - rot1;
return diff;
}
public static void CubeTex(int _tex, Vector3 pos, Vector3 size, ref List<Vertex> verts, ref List<uint> tris)
{
uint tex = (uint)_tex;
for (int p = 0; p < 6; p++) {
uint firstVertIndex = (uint)verts.Count;
verts.Add(new Vertex(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 0]] * size - size / 2f, VoxelData.voxelUvs[0], tex));
verts.Add(new Vertex(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 1]] * size - size / 2f, VoxelData.voxelUvs[1], tex));
verts.Add(new Vertex(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 2]] * size - size / 2f, VoxelData.voxelUvs[2], tex));
verts.Add(new Vertex(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 3]] * size - size / 2f, VoxelData.voxelUvs[3], tex));
tris.Add(firstVertIndex);
tris.Add(firstVertIndex + 1);
tris.Add(firstVertIndex + 2);
tris.Add(firstVertIndex + 2);
tris.Add(firstVertIndex + 1);
tris.Add(firstVertIndex + 3);
}
}
public static void CubeTex(int _tex, Vector3 pos, Vector3 size, ref List<Vertex> verts, ref List<uint> tris, Vector2[] uvs)
{
uint tex = (uint)_tex;
for (int p = 0; p < 6; p++) {
uint firstVertIndex = (uint)verts.Count;
verts.Add(new Vertex(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 0]] * size - size / 2f, uvs[0], tex));
verts.Add(new Vertex(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 1]] * size - size / 2f, uvs[1], tex));
verts.Add(new Vertex(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 2]] * size - size / 2f, uvs[2], tex));
verts.Add(new Vertex(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 3]] * size - size / 2f, uvs[3], tex));
tris.Add(firstVertIndex);
tris.Add(firstVertIndex + 1);
tris.Add(firstVertIndex + 2);
tris.Add(firstVertIndex + 2);
tris.Add(firstVertIndex + 1);
tris.Add(firstVertIndex + 3);
}
}
public static T2[] ForArray<T1, T2>(this IEnumerator<T1> e, Func<T1, T2> func)
{
List<T2> list = new List<T2>();
while (e.MoveNext())
list.Add(func(e.Current));
e.Reset();
return list.ToArray();
}
public static T2[] ForArray<T1, T2>(this List<T1> list, Func<T1, T2> func)
{
T2[] array = new T2[list.Count];
for (int i = 0; i < list.Count; i++)
array[i] = func(list[i]);
return array;
}
public static T2[] ForArray<T1, T2>(this T1[] _array, Func<T1, T2> func)
{
T2[] array = new T2[_array.Length];
for (int i = 0; i < _array.Length; i++)
array[i] = func(_array[i]);
return array;
}
public static T[] Cloned<T>(this T[] array)
{
T[] newArray = new T[array.Length];
Array.Copy(array, newArray, array.Length);
return newArray;
}
public static Vector2 Swaped(this Vector2 v) => new Vector2(v.Y, v.X);
// needs admin
public static void SetAssociationWithExtension(string Extension, string key, string OpenWith, string FileDescription)
{
RegistryKey key1 = Registry.LocalMachine.CreateSubKey($@"SOFTWARE\Classes\{Extension}");
key1.SetValue("", $"{Extension.Replace(".", "")}.Document");
key1.Flush();
RegistryKey key2 = Registry.LocalMachine.CreateSubKey($@"SOFTWARE\Classes\{key}.Document");
key2.SetValue("", FileDescription);
key2.Flush();
RegistryKey key3 = Registry.LocalMachine.CreateSubKey($@"SOFTWARE\Classes\{key}.Document\Shell\Open\Command");
key3.SetValue("", $"\"{OpenWith}\" %1");
key3.Flush();
RegistryKey key4 = Registry.LocalMachine.CreateSubKey($@"SOFTWARE\Classes\{key}.Document\Shell\Edit\Command");
key4.SetValue("", $"\"{OpenWith}\" %1");
key4.Flush();
}
public static void Exit(EXITCODE code, Exception ex = null, string message = null)
{
if (code == EXITCODE.Normal)
Environment.Exit((int)code);
string exceptionMessage = "None";
if (ex != null)
exceptionMessage = $"\n Type: {ex.GetType()}\n Source: {ex.Source}\n StackTrace: {ex.StackTrace}";
string exitMessage = "None";
if (message != null)
exitMessage = message;
Console.WriteLine($"\nExited with Code: {(int)code}, ExitCodeName: {Enum.GetName(typeof(EXITCODE), code)}");
if (ex != null)
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Exception: {exceptionMessage}");
Console.ResetColor();
if (message != null)
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Message: {exitMessage}");
Console.ResetColor();
Console.WriteLine("Press any key to close...");
Console.ReadKey(true);
Environment.Exit((int)code);
}
public static float Width = 1280f;
public static float Height = 720f;
public static Vector2 NormalToGL(float x, float y)
=> new Vector2((x * 2f) - 1f, (y * 2f) - 1f);
public static Vector2 NormalToGL(Vector2 pos)
=> NormalToGL(pos.X, pos.Y);
public static Vector2 GLToNormal(float x, float y)
=> new Vector2((x + 1f) / 2f, (y + 1f) / 2f);
public static Vector2 GLToNormal(Vector2 pos)
=> GLToNormal(pos.X, pos.Y);
public static Vector2 PixelToNormal(int x, int y)
=> new Vector2((float)x / Width, (float)y / Height);
public static Vector2 PixelToNormal(Vector2i pos)
=> PixelToNormal(pos.X, pos.Y);
public static Vector2 PixelToGL(int x, int y)
=> new Vector2(((float)x / Width) * 2f - 1f, ((float)y / Height) * 2f - 1f);
public static Vector2 PixelToGL(Vector2i pos)
=> PixelToGL(pos.X, pos.Y);
public static char ToLower(this char c) => c.ToString().ToLower()[0];
public static void SetXLow(this Vector2[] array, float x)
{
for (int i = 0; i < array.Length; i++)
if (array[i].X < 0.5f)
array[i] = new Vector2(x, array[i].Y);
}
public static void SetXHigh(this Vector2[] array, float x)
{
for (int i = 0; i < array.Length; i++)
if (array[i].X >= 0.5f)
array[i] = new Vector2(x, array[i].Y);
}
public static void SetYLow(this Vector2[] array, float y)
{
for (int i = 0; i < array.Length; i++)
if (array[i].Y < 0.5f)
array[i] = new Vector2(array[i].X, y);
}
public static void SetYHigh(this Vector2[] array, float y)
{
for (int i = 0; i < array.Length; i++)
if (array[i].Y >= 0.5f)
array[i] = new Vector2(array[i].X, y);
}
public static void SetXLow(this Vector3[] array, float x)
{
for (int i = 0; i < array.Length; i++)
if (array[i].X < 0.5f)
array[i] = new Vector3(x, array[i].Y, array[i].Z);
}
public static void SetXHigh(this Vector3[] array, float x)
{
for (int i = 0; i < array.Length; i++)
if (array[i].X >= 0.5f)
array[i] = new Vector3(x, array[i].Y, array[i].Z);
}
public static void SetZLow(this Vector3[] array, float z)
{
for (int i = 0; i < array.Length; i++)
if (array[i].Z < 0.5f)
array[i] = new Vector3(array[i].X, array[i].Y, z);
}
public static void SetZHigh(this Vector3[] array, float z)
{
for (int i = 0; i < array.Length; i++)
if (array[i].Z >= 0.5f)
array[i] = new Vector3(array[i].X, array[i].Y, z);
}
public static void FlipX(this Vector2[] array)
{
float low = 0f;
float high = 1f;
for (int i = 0; i < array.Length; i++)
if (array[i].X < 0.5f)
low = array[i].X;
else
high = array[i].X;
for (int i = 0; i < array.Length; i++)
if (array[i].X < 0.5f)
array[i] = new Vector2(high, array[i].Y);
else
array[i] = new Vector2(low, array[i].Y);
}
public static void FlipY(this Vector2[] array)
{
float low = 0f;
float high = 1f;
for (int i = 0; i < array.Length; i++)
if (array[i].Y < 0.5f)
low = array[i].Y;
else
high = array[i].Y;
for (int i = 0; i < array.Length; i++)
if (array[i].Y < 0.5f)
array[i] = new Vector2(array[i].X, high);
else
array[i] = new Vector2(array[i].X, low);
}
// Set Foregroun
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);
public static void SetConsoleForeground()
{
string originalTitle = Console.Title;
string uniqueTitle = Guid.NewGuid().ToString();
Console.Title = uniqueTitle;
Thread.Sleep(20);
IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);
if (handle == IntPtr.Zero) {
Console.WriteLine("Oops, cant find main window.");
return;
}
Console.Title = originalTitle;
int c = 0;
while (true) {
Thread.Sleep(20);
if (SetForegroundWindow(handle))
return;
c++;
if (c > 100)
return;
}
}
public static void SetOpenTKForeground()
{
string originalTitle = Program.Window.Title;
string uniqueTitle = Guid.NewGuid().ToString();
Program.Window.Title = uniqueTitle;
Thread.Sleep(20);
IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);
if (handle == IntPtr.Zero) {
Console.WriteLine("Oops, cant find main window.");
return;
}
Program.Window.Title = originalTitle;
int c = 0;
while (true) {
Thread.Sleep(20);
if (SetForegroundWindow(handle))
return;
c++;
if (c > 100)
return;
}
}
[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.Dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr parentHandle, Win32Callback callback, IntPtr lParam);
public delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam);
public static List<IntPtr> GetRootWindowsOfProcess(int pid)
{
List<IntPtr> rootWindows = GetChildWindows(IntPtr.Zero);
List<IntPtr> dsProcRootWindows = new List<IntPtr>();
foreach (IntPtr hWnd in rootWindows) {
uint lpdwProcessId;
GetWindowThreadProcessId(hWnd, out lpdwProcessId);
if (lpdwProcessId == pid)
dsProcRootWindows.Add(hWnd);
}
return dsProcRootWindows;
}
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
GCHandle listHandle = GCHandle.Alloc(result);
try {
Win32Callback childProc = new Win32Callback(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
}
finally {
if (listHandle.IsAllocated)
listHandle.Free();
}
return result;
}
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
GCHandle gch = GCHandle.FromIntPtr(pointer);
List<IntPtr> list = gch.Target as List<IntPtr>;
if (list == null) {
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
}
list.Add(handle);
// You can modify this to check to see if you want to cancel the operation, then return a null here
return true;
}
}
}