-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPreciseTimerClass.cpp
More file actions
114 lines (107 loc) · 2.28 KB
/
Copy pathPreciseTimerClass.cpp
File metadata and controls
114 lines (107 loc) · 2.28 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
#include <chrono>
#include "Async/Async.h"
#include "HAL/ThreadSafeBool.h"
UENUM(BlueprintType)
enum TimerInputType
{
Seconds UMETA(DisplayName = "Seconds"),
Milliseconds UMETA(DisplayName = "Milliseconds"),
Microseconds UMETA(DisplayName = "MicroSeconds"),
Nanoseconds UMETA(DisplayName = "NanoSeconds"),
};
DECLARE_DYNAMIC_DELEGATE(FPreciseTimerDelegate);
UCLASS(Blueprintable)
class UPreciseTimer :public UObject
{
GENERATED_BODY()
~UPreciseTimer()
{
bStop = true;
}
protected:
std::chrono::time_point<std::chrono::high_resolution_clock> StartTime, EndTime;
std::chrono::nanoseconds duration;
volatile bool bStop = false;
TimerInputType InType = TimerInputType::Nanoseconds;
public:
UFUNCTION(BlueprintCallable)
void StartTimer()
{
StartTime = std::chrono::high_resolution_clock::now();
}
void Tick(float Time, bool Looping, FPreciseTimerDelegate Call)
{
while (GetTimeElapsed() < Time &&!bStop)
{
}
if (Looping)
{
if (bStop)
{
ConditionalBeginDestroy();
}
else
{
if(Call.ExecuteIfBound())
StartTimerByFunction(Time, Looping, InType, Call);
else
ConditionalBeginDestroy();
}
}
else
{
Call.Execute();
ConditionalBeginDestroy();
}
}
UFUNCTION(BlueprintCallable)
void StartTimerByFunction(float Time, bool Looping,TimerInputType InputType, FPreciseTimerDelegate Call)
{
if (InType != InputType)
{
InType = InputType;
switch (InputType)
{
case Seconds:Time = Time * 1000000000;
break;
case Milliseconds: Time = Time * 1000000;
break;
case Microseconds:Time = Time * 1000;
break;
}
}
StartTimer();
Async(EAsyncExecution::Thread, [&]()
{
Tick(Time, Looping, Call);
});
}
UFUNCTION(BlueprintCallable)
void StopTimer()
{
bStop = true;
ConditionalBeginDestroy();
}
UFUNCTION(BlueprintCallable)
float GetTimeElapsed()
{
EndTime = std::chrono::high_resolution_clock::now();
duration = EndTime - StartTime;
return duration.count();
}
UFUNCTION(BlueprintPure)
float ToSeconds(float Value)
{
return Value / 1000000000;
}
UFUNCTION(BlueprintPure)
float ToMilliseconds(float Value)
{
return Value / 1000000;
}
UFUNCTION(BlueprintPure)
float ToMicroseconds(float Value)
{
return Value / 1000;
}
};