-
Notifications
You must be signed in to change notification settings - Fork 6
/
CoroBehaviour.cpp
119 lines (106 loc) · 2.22 KB
/
CoroBehaviour.cpp
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
#include "CoroBehaviour.h"
CoroBehaviour::~CoroBehaviour()
{
StopAllCoroutines();
ResumeCoroutines();
}
Coroutine* CoroBehaviour::StartCoroutine(Enumerator InEnumerator)
{
CoroPull Pull(InEnumerator);
if (Pull)
{
return PushCoroutine(new Coroutine(Pull));
}
return nullptr;
}
void CoroBehaviour::StopCoroutine(Coroutine* CoroutinePtr)
{
YieldInstruction* YieldReturnPtr = nullptr;
while (CoroutinePtr != nullptr)
{
YieldReturnPtr = CoroutinePtr->GetYieldReturn();
CoroutinePtr->End();
CoroutinePtr = CastAsCoroutine(YieldReturnPtr);
}
if (YieldReturnPtr != nullptr)
{
YieldReturnPtr->End();
}
}
void CoroBehaviour::StopAllCoroutines()
{
for (Coroutine* CoroutinePtr : Coroutines)
{
StopCoroutine(CoroutinePtr);
}
}
bool CoroBehaviour::HasCoroutines()
{
return !Coroutines.empty();
}
Coroutine* CoroBehaviour::CastAsCoroutine(YieldInstruction* YieldInstructionPtr)
{
if (YieldInstructionPtr == nullptr || YieldInstructionPtr->Type != TYPEID(Coroutine))
{
return nullptr;
}
return static_cast<Coroutine*>(YieldInstructionPtr);
}
bool CoroBehaviour::YieldCoroutine(Coroutine* CoroutinePtr)
{
YieldInstruction* YieldReturnPtr = CoroutinePtr->GetYieldReturn();
if (YieldReturnPtr != nullptr)
{
if (YieldReturnPtr->IsEnded())
{
delete YieldReturnPtr;
}
else
{
Coroutines.insert(CoroutinePtr);
return true;
}
}
return false;
}
Coroutine* CoroBehaviour::PushCoroutine(Coroutine* CoroutinePtr)
{
Coroutine* YieldReturnPtr = CastAsCoroutine(CoroutinePtr->GetYieldReturn());
if (YieldReturnPtr == nullptr)
{
Coroutines.insert(CoroutinePtr);
}
else
{
YieldReturnPtr->NextPtr = CoroutinePtr;
}
return CoroutinePtr;
}
Coroutine* CoroBehaviour::PopCoroutine(Coroutine* CoroutinePtr)
{
Coroutine* NextPtr = CoroutinePtr->NextPtr;
delete CoroutinePtr;
return NextPtr;
}
void CoroBehaviour::ResumeCoroutines()
{
std::set<Coroutine*> CoroutinesCopy;
CoroutinesCopy.swap(Coroutines);
for (Coroutine* CoroutinePtr : CoroutinesCopy)
{
if (YieldCoroutine(CoroutinePtr))
{
continue;
}
while (CoroutinePtr != nullptr)
{
CoroutinePtr->Resume();
if (!CoroutinePtr->IsEnded())
{
PushCoroutine(CoroutinePtr);
break;
}
CoroutinePtr = PopCoroutine(CoroutinePtr);
}
}
}