-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathSpawnManagerMotif.cs
256 lines (220 loc) · 8.26 KB
/
SpawnManagerMotif.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* Licensed under the Oculus SDK License Agreement (the "License");
* you may not use the Oculus SDK except in compliance with the License,
* which is provided at the time of installation or download, or which
* otherwise accompanies this software in either electronic or hard copy form.
*
* You may obtain a copy of the License at
*
* https://developer.oculus.com/licenses/oculussdk/
*
* Unless required by applicable law or agreed to in writing, the Oculus SDK
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if FUSION2
using Fusion;
using UnityEngine;
using System.Collections;
using Meta.XR.MultiplayerBlocks.Fusion;
/// <summary>
/// Manages the spawn locations for players in a multiplayer session. Controls the
/// queuing system for players waiting for an available spawn location and ensures
/// avatars are placed correctly at available locations.
/// </summary>
public class SpawnManagerMotif : NetworkBehaviour
{
[Tooltip("Stores the PlayerRef of players occupying each spawn location.")]
[Networked, Capacity(8)] public NetworkArray<PlayerRef> OccupyingPlayers => default;
/// <summary>
/// Stores the predefined spawn locations in the game scene.
/// Each position in the array corresponds to a spawn point where players can be placed.
/// </summary>
[Networked, Capacity(8)] private NetworkArray<Vector3> SpawnLocations => default;
/// <summary>
/// Tracks whether each spawn location is currently occupied by a player.
/// A true value means the location is occupied, false means it is available.
/// </summary>
[Networked, Capacity(8)] private NetworkArray<NetworkBool> LocationOccupied => default;
/// <summary>
/// Tracks players waiting to be placed at a spawn location. The array is used to
/// manage the queue for players waiting to occupy a location.
/// </summary>
[Networked, Capacity(8)] private NetworkArray<PlayerRef> QueuedPlayers => default;
[Tooltip("The player's camera rig that will be positioned at spawn locations.")]
[SerializeField] private Transform cameraRig;
[Tooltip("The object in the scene that avatars will interact with or face.")]
[SerializeField] private GameObject objectOfInterest;
public GameObject ObjectOfInterest => objectOfInterest;
public bool HasSpawned { get; private set; }
public override void Spawned()
{
base.Spawned();
HasSpawned = true;
FusionBBEvents.OnSceneLoadDone += OnLoaded;
}
public override void Despawned(NetworkRunner runner, bool hasState)
{
base.Despawned(runner, hasState);
FusionBBEvents.OnSceneLoadDone -= OnLoaded;
}
private void OnLoaded(NetworkRunner runner)
{
InitializeSpawnLocations();
}
private void InitializeSpawnLocations()
{
var spawnPoints = objectOfInterest.GetComponentsInChildren<SpawnPointMotif>();
for (var i = 0; i < SpawnLocations.Length; i++)
{
if (i < spawnPoints.Length)
{
SpawnLocations.Set(i, spawnPoints[i].transform.position);
LocationOccupied.Set(i, false);
OccupyingPlayers.Set(i, default);
}
else
{
SpawnLocations.Set(i, Vector3.zero);
}
}
}
/// <summary>
/// This method is called by <see cref="AvatarSpawnerHandlerMotif"/> class, whenever a new player joins
/// the experience. After the player's avatar entity is spawned, we want to place the player in a spawn
/// queue before they are requesting a spawn location. This approach is used to prevent players from
/// joining at the exact same time, which could lead to our system assigning them the same spawn location.
/// </summary>
public IEnumerator EnqueuePlayerForSpawn(PlayerRef player, AvatarBehaviourFusion avatarObject)
{
AddPlayerToQueue(player);
yield return StartCoroutine(ProcessSpawnQueue(player, avatarObject));
}
private void AddPlayerToQueue(PlayerRef player)
{
for (var i = 0; i < QueuedPlayers.Length; i++)
{
if (QueuedPlayers.Get(i) != PlayerRef.None)
{
continue;
}
RequestModifyQueueRpc(i, player);
return;
}
}
private IEnumerator ProcessSpawnQueue(PlayerRef player, NetworkBehaviour avatarObject)
{
// The random delay is introduced to prevent multiple clients from attempting to occupy the same spawn location
// simultaneously. Without this, clients could fetch the same location at the exact same time, causing conflicts.
// This delay helps stagger their requests slightly, reducing the likelihood of this race condition.
var randomDelay = Random.Range(0.1f, 2.0f);
yield return new WaitForSeconds(randomDelay);
while (IsAnotherPlayerAheadInQueue(player))
{
yield return new WaitForEndOfFrame();
yield return null;
}
for (var i = 0; i < SpawnLocations.Length; i++)
{
if (LocationOccupied.Get(i))
{
continue;
}
RequestOccupyLocationRpc(i, player);
RequestRemovePlayerFromQueueRpc(player);
MoveAvatarToLocation(avatarObject, SpawnLocations.Get(i));
break;
}
}
private bool IsAnotherPlayerAheadInQueue(PlayerRef player)
{
foreach (var queuedPlayer in QueuedPlayers)
{
if (queuedPlayer != PlayerRef.None && queuedPlayer.PlayerId < player.PlayerId)
{
return true;
}
}
return false;
}
private void MoveAvatarToLocation(NetworkBehaviour avatarObject, Vector3 location)
{
if (!avatarObject.HasStateAuthority)
{
return;
}
cameraRig.position = location;
var directionToLook = objectOfInterest.transform.position - cameraRig.position;
directionToLook.y = 0;
cameraRig.rotation = Quaternion.LookRotation(directionToLook);
}
[Rpc(RpcSources.All, RpcTargets.StateAuthority)]
private void RequestModifyQueueRpc(int queueIndex, PlayerRef player)
{
QueuedPlayers.Set(queueIndex, player);
}
[Rpc(RpcSources.All, RpcTargets.StateAuthority)]
private void RequestOccupyLocationRpc(int locationIndex, PlayerRef player)
{
if (LocationOccupied.Get(locationIndex))
{
return;
}
OccupyingPlayers.Set(locationIndex, player);
LocationOccupied.Set(locationIndex, true);
}
[Rpc(RpcSources.All, RpcTargets.StateAuthority)]
private void RequestRemovePlayerFromQueueRpc(PlayerRef player)
{
for (var i = 0; i < QueuedPlayers.Length; i++)
{
if (QueuedPlayers.Get(i) != player)
{
continue;
}
ShiftQueueLeftRpc(i);
return;
}
}
[Rpc(RpcSources.All, RpcTargets.StateAuthority)]
private void ShiftQueueLeftRpc(int startIndex)
{
for (var i = startIndex; i < QueuedPlayers.Length - 1; i++)
{
QueuedPlayers.Set(i, QueuedPlayers.Get(i + 1));
}
QueuedPlayers.Set(QueuedPlayers.Length - 1, PlayerRef.None);
}
[Rpc(RpcSources.All, RpcTargets.StateAuthority)]
public void ReleaseLocationRpc(int locationIndex, PlayerRef player)
{
if (OccupyingPlayers.Get(locationIndex) != player)
{
return;
}
LocationOccupied.Set(locationIndex, false);
OccupyingPlayers.Set(locationIndex, default);
}
private void OnDrawGizmos()
{
if (!HasSpawned)
{
return;
}
for (var i = 0; i < SpawnLocations.Length; i++)
{
if (SpawnLocations.Get(i) == Vector3.zero)
{
continue;
}
Gizmos.color = LocationOccupied.Get(i) ? Color.green : Color.blue;
Gizmos.DrawSphere(SpawnLocations.Get(i), 0.1f);
}
}
}
#endif