This repository has been archived by the owner on Jan 18, 2022. It is now read-only.
/
SendCreatePlayerRequestSystem.cs
232 lines (197 loc) · 8.23 KB
/
SendCreatePlayerRequestSystem.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
using System;
using System.Collections.Generic;
using Improbable.Gdk.Core;
using Improbable.Gdk.Core.Commands;
using Improbable.Gdk.PlayerLifecycle;
using Improbable.Worker.CInterop;
using Improbable.Worker.CInterop.Query;
using Unity.Entities;
using UnityEngine;
using EntityQuery = Improbable.Worker.CInterop.Query.EntityQuery;
using Random = UnityEngine.Random;
namespace Improbable.Gdk.PlayerLifecycle
{
[DisableAutoCreation]
[AlwaysUpdateSystem]
[UpdateInGroup(typeof(SpatialOSUpdateGroup))]
public class SendCreatePlayerRequestSystem : ComponentSystem
{
private CommandSystem commandSystem;
private WorkerSystem workerSystem;
private ILogDispatcher logDispatcher;
private byte[] serializedArgumentsCache;
private bool playerCreationRequestQueued;
private long? playerCreationRequestId;
private int playerCreationRetries;
private Action<PlayerCreator.CreatePlayer.ReceivedResponse> playerCreationCallback;
private int playerCreatorQueryRetries;
private long? playerCreatorEntityQueryId;
private readonly List<EntityId> playerCreatorEntityIds = new List<EntityId>();
private readonly EntityQuery playerCreatorQuery = new EntityQuery
{
Constraint = new ComponentConstraint(PlayerCreator.ComponentId),
ResultType = new SnapshotResultType()
};
protected override void OnCreate()
{
base.OnCreate();
workerSystem = World.GetExistingSystem<WorkerSystem>();
commandSystem = World.GetExistingSystem<CommandSystem>();
logDispatcher = workerSystem.LogDispatcher;
SendPlayerCreatorEntityQuery();
if (PlayerLifecycleConfig.AutoRequestPlayerCreation)
{
RequestPlayerCreation();
}
}
private void SendPlayerCreatorEntityQuery()
{
playerCreatorEntityQueryId = commandSystem.SendCommand(new WorldCommands.EntityQuery.Request
{
EntityQuery = playerCreatorQuery
});
}
private void HandleEntityQueryResponses()
{
var entityQueryResponses = commandSystem.GetResponses<WorldCommands.EntityQuery.ReceivedResponse>();
for (var i = 0; i < entityQueryResponses.Count; i++)
{
ref readonly var response = ref entityQueryResponses[i];
if (response.RequestId != playerCreatorEntityQueryId)
{
continue;
}
playerCreatorEntityQueryId = null;
if (response.StatusCode == StatusCode.Success)
{
playerCreatorEntityIds.AddRange(response.Result.Keys);
}
else if (playerCreatorQueryRetries < PlayerLifecycleConfig.MaxPlayerCreatorQueryRetries)
{
++playerCreatorQueryRetries;
logDispatcher.HandleLog(LogType.Warning, new LogEvent(
$"Retrying player creator query, attempt {playerCreatorQueryRetries}.\n{response.Message}"
));
SendPlayerCreatorEntityQuery();
}
else
{
var retryText = playerCreatorQueryRetries == 0
? "1 attempt"
: $"{playerCreatorQueryRetries + 1} attempts";
logDispatcher.HandleLog(LogType.Error, new LogEvent(
$"Unable to find player creator after {retryText}."
));
}
break;
}
}
/// <summary>
/// Queues a request for player creation, if none are currently in progress. If player creation entities
/// have already been found, the request is sent in the next tick.
/// </summary>
/// <param name="serializedArguments">A serialized byte array of arbitrary player creation arguments.</param>
/// <param name="callback">
/// An action to be invoked when the worker receives a response to the player creation request.
/// </param>
public void RequestPlayerCreation(byte[] serializedArguments = null,
Action<PlayerCreator.CreatePlayer.ReceivedResponse> callback = null)
{
if (playerCreationRequestId.HasValue)
{
logDispatcher.HandleLog(LogType.Warning, new LogEvent(
$"Unable to perform player creation request as one has already been requested."
));
return;
}
playerCreationRetries = 0;
serializedArgumentsCache = serializedArguments;
playerCreationCallback = callback;
playerCreationRequestQueued = true;
}
// We only enter this method if playerCreatorEntityIds.Count is greater than 0, meaning that there will
// always be at least one element in the list of Player Creator entity IDs.
private void SendCreatePlayerRequest()
{
// Here we construct our CreatePlayer request, and choose a random Player Creator entity to send it to.
playerCreationRequestId = commandSystem.SendCommand(new PlayerCreator.CreatePlayer.Request(
playerCreatorEntityIds[Random.Range(0, playerCreatorEntityIds.Count)],
new CreatePlayerRequest(serializedArgumentsCache)
));
playerCreationRequestQueued = false;
}
private void RetryCreatePlayerRequest()
{
if (playerCreationRetries < PlayerLifecycleConfig.MaxPlayerCreationRetries)
{
++playerCreationRetries;
logDispatcher.HandleLog(LogType.Warning, new LogEvent(
$"Retrying player creation request, attempt {playerCreationRetries}."
));
SendCreatePlayerRequest();
}
else
{
var retryText = playerCreationRetries == 0
? "1 attempt"
: $"{playerCreationRetries + 1} attempts";
logDispatcher.HandleLog(LogType.Error, new LogEvent(
$"Unable to create player after {retryText}."
));
}
}
private void HandlePlayerCreation()
{
if (playerCreationRequestQueued)
{
SendCreatePlayerRequest();
}
if (!playerCreationRequestId.HasValue)
{
return;
}
var responses = commandSystem.GetResponses<PlayerCreator.CreatePlayer.ReceivedResponse>();
for (var i = 0; i < responses.Count; i++)
{
ref readonly var response = ref responses[i];
if (response.RequestId != playerCreationRequestId)
{
continue;
}
// Clears the player creation request ID to indicate that we have received a
// response for the player creation request that we last sent.
playerCreationRequestId = null;
playerCreationCallback?.Invoke(response);
switch (response.StatusCode)
{
case StatusCode.Success:
playerCreationCallback = null;
break;
case StatusCode.AuthorityLost:
case StatusCode.InternalError:
case StatusCode.Timeout:
RetryCreatePlayerRequest();
break;
default:
playerCreationCallback = null;
logDispatcher.HandleLog(LogType.Error, new LogEvent(
$"Create player request failed: {response.Message}"
));
break;
}
break;
}
}
protected override void OnUpdate()
{
if (playerCreatorEntityIds.Count > 0)
{
HandlePlayerCreation();
}
else
{
HandleEntityQueryResponses();
}
}
}
}