-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUtil.cs
1189 lines (1000 loc) · 34.8 KB
/
Util.cs
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This file is released under the MIT License: https://opensource.org/licenses/MIT
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Godot;
using Godot.Collections;
public static class Util
{
private const bool SERIALIZATION_DEBUG_PRINT = false;
public static readonly RandomNumberGenerator rng = new RandomNumberGenerator();
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> array)
{
var ret = new HashSet<T>();
foreach (var v in array)
{
ret.Add(v);
}
return ret;
}
public static Godot.Collections.Array VecToArray(Vector2 vector2)
{
return new Godot.Collections.Array(){
vector2.X,
vector2.Y
};
}
public static Vector2 ArrayToVec(Godot.Collections.Array array)
{
return new Vector2(
(float)array[0],
(float)array[1]
);
}
private static ConditionalWeakTable<Node, System.Collections.Generic.Dictionary<object, Node>> findChildByPredicateCache = new ConditionalWeakTable<Node, System.Collections.Generic.Dictionary<object, Node>>();
public static T FindChildByPredicate<T>(this Node node, Predicate<T> predicate, int maxRecursionDepth = 10, object immutableCacheKey = null, Node initialNode = null) where T : Node
{
if (node == null) return null;
if (immutableCacheKey != null && initialNode == null)
{
initialNode = node;
var dict = findChildByPredicateCache.GetOrCreateValue(node);
Node ret;
if (dict.TryGetValue(immutableCacheKey, out ret) && ret.IsInstanceValid() && ret.IsInsideTree())
{
return (T)ret;
}
}
var c = node.GetChildCount();
for (int i = 0; i < c; ++i)
{
var n = node.GetChild(i);
if (n is T)
{
if (predicate.Invoke((T)n))
{
if (immutableCacheKey != null)
{
var dict = findChildByPredicateCache.GetOrCreateValue(initialNode);
dict[immutableCacheKey] = (T)n;
}
return (T)n;
}
}
}
if (maxRecursionDepth > 0)
{
for (int i = 0; i < c; ++i)
{
var n = node.GetChild(i);
var ret = n.FindChildByPredicate<T>(predicate, maxRecursionDepth - 1, immutableCacheKey, initialNode);
if (ret != null) return ret;
}
}
return null;
}
private static ConditionalWeakTable<Node, System.Collections.Generic.Dictionary<Type, Node>> findChildByTypeCache = new ConditionalWeakTable<Node, System.Collections.Generic.Dictionary<Type, Node>>();
public static T FindChildByType<T>(this Node node, int maxRecursionDepth = 10, Node initialNode = null) where T : Node
{
if (node == null) return null;
if (initialNode == null)
{
initialNode = node;
var dict = findChildByTypeCache.GetOrCreateValue(node);
Node ret;
if (dict.TryGetValue(typeof(T), out ret) && ret.IsInstanceValid() && ret.IsInsideTree())
{
return (T)ret;
}
}
var c = node.GetChildCount();
for (int i = 0; i < c; ++i)
{
var n = node.GetChild(i);
if (n is T)
{
var dict = findChildByTypeCache.GetOrCreateValue(initialNode);
dict[typeof(T)] = (T)n;
return (T)n;
}
}
if (maxRecursionDepth > 0)
{
for (int i = 0; i < c; ++i)
{
var n = node.GetChild(i);
var ret = n.FindChildByType<T>(maxRecursionDepth - 1, initialNode);
if (ret != null) return ret;
}
}
return null;
}
public static IEnumerable<T> FindChildrenByType<T>(this Node node, int maxRecursionDepth = 10) where T : class
{
var c = node.GetChildCount();
for (int i = 0; i < c; ++i)
{
var n = node.GetChild(i);
if (n is T)
{
yield return ((T)(object)n);
}
if (maxRecursionDepth > 0)
{
foreach (var nn in n.FindChildrenByType<T>(maxRecursionDepth - 1))
{
yield return nn;
}
}
}
}
public static IEnumerable<T> FindChildrenByPredicate<T>(this Node node, Func<T, bool> predicate, int maxRecursionDepth = 10) where T : class
{
var c = node.GetChildCount();
for (int i = 0; i < c; ++i)
{
var n = node.GetChild(i);
if (n is T typedNode)
{
if (predicate(typedNode)) yield return typedNode;
}
if (maxRecursionDepth > 0)
{
foreach (var nn in n.FindChildrenByPredicate<T>(predicate, maxRecursionDepth - 1))
{
yield return nn;
}
}
}
}
private static ConditionalWeakTable<Node, System.Collections.Generic.Dictionary<string, Node>> findChildByNameCache = new ConditionalWeakTable<Node, System.Collections.Generic.Dictionary<string, Node>>();
public static T FindChildByName<T>(this Node node, string name, int maxRecursionDepth = 10, Node initialNode = null) where T : Node
{
if (node == null || name == null) return null;
if (initialNode == null)
{
initialNode = node;
var dict = findChildByNameCache.GetOrCreateValue(node);
Node ret;
if (dict.TryGetValue(name, out ret) && ret.IsInstanceValid() && ret.IsInsideTree())
{
return (T)ret;
}
}
var c = node.GetChildCount();
for (int i = 0; i < c; ++i)
{
var n = node.GetChild(i);
if (n.Name == name)
{
if (n is T)
{
var dict = findChildByNameCache.GetOrCreateValue(initialNode);
dict[name] = (T)n;
return (T)n;
}
else
{
GD.Print($"Node {name} is of unexpected type {n.GetType()}");
}
}
}
if (maxRecursionDepth > 0)
{
for (int i = 0; i < c; ++i)
{
var n = node.GetChild(i);
var ret = n.FindChildByName<T>(name, maxRecursionDepth - 1, initialNode);
if (ret != null) return ret;
}
}
return null;
}
public static byte[] ObjToBytes<T>(T obj)
{
MemoryStream ms = new MemoryStream();
ObjToBytes(obj, typeof(T), ms);
return ms.ToArray();
}
public static byte[] ObjToBytes(object obj, Type type)
{
MemoryStream ms = new MemoryStream();
ObjToBytes(obj, type, ms);
return ms.ToArray();
}
private static void WriteAll(MemoryStream memoryStream, byte[] bytes)
{
memoryStream.Write(bytes, 0, bytes.Length);
}
private static void ObjToBytes(object obj, Type type, MemoryStream mem)
{
SerializationLog($"Serializing a {type}");
if (type == typeof(System.Int32)) { WriteAll(mem, BitConverter.GetBytes((int)obj)); return; }
if (type == typeof(long) || type == typeof(System.Int64)) { WriteAll(mem, BitConverter.GetBytes((long)obj)); return; }
if (type == typeof(ulong)) { WriteAll(mem, BitConverter.GetBytes((ulong)obj)); return; }
if (type == typeof(short)) { WriteAll(mem, BitConverter.GetBytes((short)obj)); return; }
if (type == typeof(ushort)) { WriteAll(mem, BitConverter.GetBytes((ushort)obj)); return; }
if (type == typeof(float))
{
//Console.WriteLine($"It is a {type} / {obj.GetType()}");
SerializationLog($"The single is {(Half)(float)obj}");
WriteAll(mem, BitConverter.GetBytes((Half)(float)obj));
return;
}
if (type == typeof(double)) { WriteAll(mem, BitConverter.GetBytes((double)obj)); return; }
if (type == typeof(Half)) { WriteAll(mem, BitConverter.GetBytes((Half)obj)); return; }
if (type.IsEnum)
{
WriteAll(mem, BitConverter.GetBytes((int)obj));
return;
}
if (type == typeof(string))
{
if (obj == null)
{
WriteAll(mem, BitConverter.GetBytes(-1));
return;
}
byte[] rawBytes = ((string)obj).ToUtf8Buffer();
WriteAll(mem, BitConverter.GetBytes(rawBytes.Length));
WriteAll(mem, rawBytes);
return;
}
if (type == typeof(byte))
{
WriteAll(mem, new byte[] { (byte)obj });
return;
}
if (type == typeof(sbyte))
{
WriteAll(mem, new byte[] { unchecked((byte)(sbyte)obj) });
return;
}
if (type == typeof(bool))
{
WriteAll(mem, BitConverter.GetBytes((bool)obj));
return;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
WriteAll(mem, BitConverter.GetBytes(((System.Collections.IList)obj).Count));
foreach (var o in ((System.Collections.IList)obj))
{
ObjToBytes(o, type.GenericTypeArguments[0], mem);
}
return;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
WriteAll(mem, new byte[] { (byte)(obj != null ? 1 : 0) });
if (obj != null)
{
WriteAll(mem, ObjToBytes(obj, type.GetGenericArguments()[0]));
}
return;
}
if (type.IsArray)
{
if (obj == null)
{
WriteAll(mem, BitConverter.GetBytes(-1));
return;
}
WriteAll(mem, BitConverter.GetBytes(((System.Collections.IList)obj).Count));
foreach (var o in ((System.Collections.IList)obj))
{
ObjToBytes(o, type.GetElementType(), mem);
}
return;
}
SerializationLog($"Seems it's some kind of object {obj.GetType()}");
foreach (var field in obj.GetType().GetFields())
{
SerializationLog($"Descending into {field.Name}");
object fieldValue = field.GetValue(obj);
ObjToBytes(fieldValue, field.FieldType, mem);
}
}
public static T BytesToObj<T>(byte[] bytes)
{
MemoryStream mem = new MemoryStream(bytes);
return (T)BytesToObj(mem, typeof(T));
}
public static object BytesToObj(byte[] bytes, Type type)
{
MemoryStream mem = new MemoryStream(bytes);
return BytesToObj(mem, type);
}
private static object BytesToObj(MemoryStream mem, Type type)
{
byte[] buffer = new byte[8];
SerializationLog($"Deserializing a {type}");
if (type == typeof(int))
{
mem.Read(buffer, 0, 4);
return BitConverter.ToInt32(buffer, 0);
}
if (type == typeof(long))
{
mem.Read(buffer, 0, 8);
return BitConverter.ToInt64(buffer, 0);
}
if (type == typeof(ulong))
{
mem.Read(buffer, 0, 8);
return BitConverter.ToUInt64(buffer, 0);
}
if (type == typeof(short))
{
mem.Read(buffer, 0, 2);
return BitConverter.ToInt16(buffer, 0);
}
if (type == typeof(ushort))
{
mem.Read(buffer, 0, 2);
return BitConverter.ToUInt16(buffer, 0);
}
if (type == typeof(float))
{
mem.Read(buffer, 0, 2);
SerializationLog($"The single is {BitConverter.ToSingle(buffer, 0)}");
return (float)BitConverter.ToHalf(buffer, 0);
}
if (type == typeof(Half))
{
mem.Read(buffer, 0, 2);
return BitConverter.ToHalf(buffer, 0);
}
if (type == typeof(int))
{
mem.Read(buffer, 0, 8);
return BitConverter.ToDouble(buffer, 0);
}
if (type == typeof(byte))
{
mem.Read(buffer, 0, 1);
return buffer[0];
}
if (type == typeof(sbyte))
{
mem.Read(buffer, 0, 1);
return unchecked((sbyte)buffer[0]);
}
if (type.IsEnum)
{
mem.Read(buffer, 0, 4);
return BitConverter.ToInt32(buffer, 0);
}
if (type == typeof(string))
{
mem.Read(buffer, 0, 4);
var len = BitConverter.ToInt32(buffer, 0);
if (len == -1) return null;
buffer = new byte[len];
mem.Read(buffer, 0, len);
return Encoding.UTF8.GetString(buffer);
}
if (type == typeof(bool))
{
mem.Read(buffer, 0, 1);
return BitConverter.ToBoolean(buffer, 0);
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
mem.Read(buffer, 0, 4);
var len = BitConverter.ToInt32(buffer, 0);
if (len == -1) return null;
System.Collections.IList ret = (System.Collections.IList)Activator.CreateInstance(type);
for (int i = 0; i < len; ++i)
{
ret.Add(BytesToObj(mem, type.GenericTypeArguments[0]));
}
return ret;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
mem.Read(buffer, 0, 1);
if (buffer[0] == 1)
{
SerializationLog($"Creating non-null Nullable with type {type.GetGenericArguments()[0]}");
return Activator.CreateInstance(type, BytesToObj(mem, type.GetGenericArguments()[0]));
}
else
{
return Activator.CreateInstance(type);
}
}
if (type.IsArray)
{
mem.Read(buffer, 0, 4);
var len = BitConverter.ToInt32(buffer, 0);
if (len == -1) return null;
AT.True(len < 2_000_000_000);
AT.True(len >= 0);
System.Collections.IList ret = (System.Collections.IList)Activator.CreateInstance(type, len);
for (int i = 0; i < len; ++i)
{
ret[i] = BytesToObj(mem, type.GetElementType());
}
return ret;
}
SerializationLog($"Seems it's some kind of object");
if (!type.IsSealed) GD.Print($"Warning: {type} should be sealed");
var inst = Activator.CreateInstance(type);
foreach (var field in type.GetFields())
{
SerializationLog($"Descending into {field.Name}");
field.SetValue(inst, BytesToObj(mem, field.FieldType));
}
return inst;
}
public static string ToHex(this byte[] bytes)
{
StringBuilder ret = new StringBuilder();
foreach (var b in bytes)
{
ret.AppendFormat("{0:x2} ", b);
}
return ret.ToString();
}
public static string ToMixedHex(this byte[] bytes)
{
StringBuilder ret = new StringBuilder();
foreach (var b in bytes)
{
if ((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || b == ' ' || b == '_')
ret.AppendFormat("{0} ", (char)b);
else
ret.AppendFormat("{0:x2} ", b);
}
return ret.ToString();
}
#pragma warning disable
private static void SerializationLog(string txt)
{
if (SERIALIZATION_DEBUG_PRINT)
{
GD.Print(txt);
}
}
private static Random _RootRand = new Random();
[ThreadStatic] private static Random _Rand;
private static Random Rand
{
get
{
if (_Rand == null)
{
lock (_RootRand)
{
_Rand = new Random(_RootRand.Next());
}
}
return _Rand;
}
}
public static int RandInt(int minInclusive, int maxExclusive)
{
return Rand.Next(minInclusive, maxExclusive);
}
public static long RandLong(long minInclusive, long maxExclusive)
{
return Rand.NextInt64(minInclusive, maxExclusive);
}
public static long RandLong()
{
return Rand.NextInt64();
}
[Obsolete("Use Random() instead")]
public static float random()
{
return (float)Rand.NextDouble();
}
public static float Random()
{
return (float)Rand.NextDouble();
}
public static float RandF(float min, float max)
{
return Random() * (max - min) + min;
}
public static bool RandChance(float chance)
{
return Random() <= chance;
}
public static bool RandChanceMil(int chancePerMil)
{
return RandInt(0, 1000) < chancePerMil;
}
public static Vector3 GetGlobalLocation(this Node3D node)
{
return node.GlobalTransform.Origin;
}
public static void SetGlobalLocation(this Node3D node, Vector3 globalLocation)
{
var t = node.GlobalTransform;
t.Origin = globalLocation;
node.GlobalTransform = t;
}
/*public static void CreateRegularTimer(this Node node, string targetMethodName, float interval, Timer.TimerProcessMode mode = Timer.TimerProcessMode.Idle)
{
Timer uploadTimer = new Timer();
uploadTimer.OneShot = false;
uploadTimer.Autostart = true;
uploadTimer.Connect("timeout", node, targetMethodName);
uploadTimer.WaitTime = interval;
uploadTimer.ProcessMode = mode;
node.AddChild(uploadTimer);
}*/
/**
* Determines if this object is still valid (aka it has not been disposed)
* Because Godot uses reference counting, this should always be called on objects that are
* referenced from other objects
*/
public static bool IsInstanceValid(this Godot.GodotObject obj)
{
return Godot.GodotObject.IsInstanceValid(obj);
}
/**
* Determines if the UI has the focus. Generally in game input shouldn't happen
* as long as the UI has focus
*/
public static bool IsUIFocused(this Node node)
{
var control = node.GetTree().CurrentScene.FindChildByPredicate<Control>(it => it.HasFocus());
return control != null;
}
public static T FindParentByType<T>(this Node node)
{
while (true)
{
var parent = node.GetParentOrNull<Node>();
if (parent == null) return default(T);
if (parent is T typedParent)
{
return typedParent;
}
node = parent;
}
}
public static T FindParentByName<T>(this Node node, string name)
{
while (true)
{
var parent = node.GetParentOrNull<Node>();
if (parent == null) return default(T);
if (parent is T typedParent && parent.Name == name)
{
return typedParent;
}
node = parent;
}
}
public static T FindParentByPredicate<T>(this Node node, Func<T, bool> predicate)
{
while (true)
{
var parent = node.GetParentOrNull<Node>();
if (parent == null) return default(T);
if (parent is T typedParent && predicate(typedParent))
{
return typedParent;
}
node = parent;
}
}
public static void SpawnOneShotParticleSystem2D(string system, Node contextNode, Vector2 location)
{
ResourceLoadMonitor.ThreadedInstantiateAsync<GpuParticles2D>(system, contextNode)
.Then(res => SpawnOneShotParticleSystem2D(res, contextNode, location));
}
public static void SpawnOneShotParticleSystem2D(GpuParticles2D particles, Node contextNode, Vector2 location)
{
if (particles == null) return;
contextNode.GetTree().CurrentScene.AddChild(particles);
particles.GlobalPosition = location;
particles.OneShot = true;
particles.Emitting = true;
var timer = new Timer();
timer.Autostart = true;
timer.WaitTime = 5;
timer.Connect("timeout", new Callable(particles, "queue_free"));
particles.AddChild(timer);
}
public static void SpawnOneShotParticleSystem(PackedScene system, Node contextNode, Vector3 location)
{
if (system == null) return;
var particles = system.Instantiate<GpuParticles3D>();
contextNode.GetTree().CurrentScene.AddChild(particles);
particles.SetGlobalLocation(location);
particles.OneShot = true;
particles.Emitting = true;
var timer = new Timer();
timer.Autostart = true;
timer.WaitTime = 5;
timer.Connect("timeout", new Callable(particles, "queue_free"));
particles.AddChild(timer);
}
public static void SpawnOneShotCPUParticleSystem(PackedScene system, Node contextNode, Vector3 location)
{
if (system == null) return;
var particles = system.Instantiate<CpuParticles3D>();
contextNode.GetTree().CurrentScene.AddChild(particles);
particles.SetGlobalLocation(location);
particles.OneShot = true;
particles.Emitting = true;
var timer = new Timer();
timer.Autostart = true;
timer.WaitTime = 5;
timer.Connect("timeout", new Callable(particles, "queue_free"));
particles.AddChild(timer);
}
public static void SpawnOneShotSound(string resName, Node contextNode, Vector3 location, float volume = 15f, float pitchMod = 1f)
{
var t = AT.TimeLimit();
ResourceLoadMonitor.StartLoading<AudioStream>(resName, contextNode, (audioStream) =>
{
Util.SpawnOneShotSound(audioStream, contextNode, location, volume, pitchMod);
}, _ => { });
t.Limit(0.001f);
}
public static void SpawnOneShotSound(AudioStream sample, Node contextNode, Vector3 location, float volume = 15f, float pitchMod = 1f)
{
if (sample == null) return;
var r = contextNode.GetTree().CurrentScene;
var c = r.GetChildCount();
var existingCount = 0;
AudioStreamPlayer3D availExisting = null;
for (int i = 0; i < c; ++i)
{
var n = r.GetChild(i);
if (n is AudioStreamPlayer3D)
{
existingCount++;
if (!((AudioStreamPlayer3D)n).Playing)
{
availExisting = (AudioStreamPlayer3D)n;
break;
}
}
}
if (availExisting == null && existingCount < 10)
{
availExisting = new AudioStreamPlayer3D();
contextNode.GetTree().CurrentScene.AddChild(availExisting);
}
if (availExisting != null)
{
availExisting.SetGlobalLocation(location);
availExisting.Stream = sample;
availExisting.VolumeDb = volume;
availExisting.AttenuationModel = AudioStreamPlayer3D.AttenuationModelEnum.InverseSquareDistance;
availExisting.DopplerTracking = AudioStreamPlayer3D.DopplerTrackingEnum.PhysicsStep;
availExisting.PitchScale = pitchMod;
availExisting.Play();
}
}
public static void SpawnOneShotSound(string resName, Node contextNode, Vector2 location, float volume = 15f, float pitchMod = 1f, float falloffRate = 0.5f)
{
ResourceLoadMonitor.StartLoading<AudioStream>(resName, contextNode, (audioStream) =>
{
Util.SpawnOneShotSound(audioStream, contextNode, location, volume, pitchMod, falloffRate);
}, _ => { });
}
public static void SpawnOneShotSound(AudioStream sample, Node contextNode, Vector2 location, float volume = 15f, float pitchMod = 1f, float falloffRate = 0.5f)
{
if (sample == null) return;
var r = contextNode.GetTree().CurrentScene;
var c = r.GetChildCount();
var existingCount = 0;
AudioStreamPlayer2D availExisting = null;
for (int i = 0; i < c; ++i)
{
var n = r.GetChild(i);
if (n is AudioStreamPlayer2D)
{
existingCount++;
if (!((AudioStreamPlayer2D)n).Playing)
{
availExisting = (AudioStreamPlayer2D)n;
break;
}
}
}
if (availExisting == null && existingCount < 10)
{
availExisting = new AudioStreamPlayer2D();
contextNode.GetTree().CurrentScene.AddChild(availExisting);
}
if (availExisting != null)
{
availExisting.GlobalPosition = location;
availExisting.Stream = sample;
availExisting.VolumeDb = volume - contextNode.GetTree().Root.GetCamera2D().GlobalPosition.DistanceTo(location) * falloffRate;
availExisting.PitchScale = pitchMod;
availExisting.Play();
}
}
public static void SpawnOneShotSound(string resName, Node contextNode, float volumeOffset = 0.0f)
{
Util.SpawnOneShotSound((AudioStream)GD.Load(resName), contextNode, volumeOffset);
}
public static void SpawnOneShotSound(AudioStream sample, Node contextNode, float volumeOffset = 0.0f)
{
if (sample == null) return;
var r = contextNode.GetTree().CurrentScene;
var c = r.GetChildCount();
var existingCount = 0;
AudioStreamPlayer availExisting = null;
for (int i = 0; i < c; ++i)
{
var n = r.GetChild(i);
if (n is AudioStreamPlayer)
{
existingCount++;
if (!((AudioStreamPlayer)n).Playing)
{
availExisting = (AudioStreamPlayer)n;
break;
}
}
}
if (availExisting == null && existingCount < 10)
{
availExisting = new AudioStreamPlayer();
contextNode.GetTree().CurrentScene.AddChild(availExisting);
}
if (availExisting != null)
{
availExisting.Stream = sample;
availExisting.VolumeDb = volumeOffset;
availExisting.Play();
}
}
public static T Clamp<T>(T initial, T min, T max) where T : IComparable<T>
{
if (initial.CompareTo(max) > 0) initial = max;
if (initial.CompareTo(min) < 0) initial = min;
return initial;
}
public static string TitleCase(this string str)
{
return str.Substr(0, 1).ToUpper() + str.Substr(1, 1000).ToLower();
}
public static T Choice<T>(IReadOnlyList<T> list)
{
if (list.Count == 0) return default(T);
return list[rng.RandiRange(0, list.Count - 1)];
}
public static T Choice<T>(IEnumerable<T> enumerable)
{
var n = 0;
var ret = default(T);
foreach (var it in enumerable)
{
if (RandInt(0, ++n) == 0) ret = it;
}
return ret;
}
public static IEnumerable<T> Single<T>(T v)
{
yield return v;
}
public static void TakeScreenshot(Node ctx)
{
var image = ctx.GetViewport().GetTexture().GetImage();
Task.Run(() =>
{
var dir = Godot.DirAccess.Open("user://");
dir.MakeDir("screenshots");
image.SavePng($"user://screenshots/{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.png");
}).HandleError();
}
public static int Square(int n)
{
return n * n;
}
public static float Square(float n)
{
return n * n;
}
public static IReadOnlyCollection<T> GetEnumValues<T>() where T : Enum
{
return (IReadOnlyCollection<T>)Enum.GetValues(typeof(T));
}
public static Error Connect(this Node node, string signal, Action @delegate)
{
return node.Connect(signal, Callable.From(@delegate));
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> it)
{
return it.OrderBy(it2 => GD.Randi());
}
public static T[,] ToMultiDimArray<T>(this IEnumerable<T[]> it)
{
int dimension = -1;
foreach (var it2 in it)
{
if (dimension == -1)
dimension = it2.Length;
else if (dimension != it2.Length)
throw new Exception();
}
var ret = new T[it.Count(), dimension];
var i = 0;
foreach (var it2 in it)
{
for (var j = 0; j < dimension; ++j)
{