-
Notifications
You must be signed in to change notification settings - Fork 2
/
P2PMultiplayerExtended.cpp
785 lines (657 loc) · 29.1 KB
/
P2PMultiplayerExtended.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
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
//
// Copyright (c) 2008-2018 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <Urho3D/Audio/Audio.h>
#include <Urho3D/Audio/Sound.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/Zone.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/IO/IOEvents.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/IO/MemoryBuffer.h>
#include <Urho3D/IO/VectorBuffer.h>
#include <Urho3D/Network/Network.h>
#include <Urho3D/Network/NetworkEvents.h>
#include <Urho3D/Network/HttpRequest.h>
#include <Urho3D/Network/Protocol.h>
#include <Urho3D/Physics/CollisionShape.h>
#include <Urho3D/Physics/PhysicsEvents.h>
#include <Urho3D/Physics/PhysicsWorld.h>
#include <Urho3D/Physics/RigidBody.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/LineEdit.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/Text3D.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/MessageBox.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/Core/CoreEvents.h>
#include "P2PMultiplayerExtended.h"
#include <Urho3D/DebugNew.h>
// Undefine Windows macro, as our Connection class has a function called SendMessage
#ifdef SendMessage
#undef SendMessage
#endif
#ifdef MessageBox
#undef MessageBox
#endif
URHO3D_DEFINE_APPLICATION_MAIN(P2PMultiplayer)
static String API_SEARCH_SESSION = "http://master.frameskippers.com/open";
static String API_NEW_SESSION = "http://master.frameskippers.com/new";
static String API_REMOVE_SESSION = "http://master.frameskippers.com/delete";
static String NAT_PUNCHTROUGH_SERVER = "nat.frameskippers.com";
static int NAT_PUNCHTROUGH_SERVER_PORT = 30123;
P2PMultiplayer::P2PMultiplayer(Context* context) :
Sample(context),
gameState_(GameState::IN_MENU)
{
Peer::RegisterObject(context);
}
void P2PMultiplayer::Start()
{
// Execute base class startup
Sample::Start();
// Enable OS cursor
GetSubsystem<Input>()->SetMouseVisible(true);
// Create the user interface
CreateUI();
CreateScene();
SetupViewport();
// Subscribe to UI and network events
SubscribeToEvents();
// Set the mouse mode to use in the sample
Sample::InitMouseMode(MM_FREE);
Init();
CreatePlayerListWindow();
}
void P2PMultiplayer::CreateUI()
{
SetLogoVisible(false); // We need the full rendering window
auto* graphics = GetSubsystem<Graphics>();
UIElement* root = GetSubsystem<UI>()->GetRoot();
auto* cache = GetSubsystem<ResourceCache>();
auto* uiStyle = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
// Set style to the UI root so that elements will inherit it
root->SetDefaultStyle(uiStyle);
int marginTop = 20;
searchGame_ = CreateButton("Search for session", 200, IntVector2(20, marginTop));
nickname_ = CreateLineEdit("User", 160, IntVector2(240, marginTop));
SetRandomSeed(Time::GetSystemTime());
nickname_->SetText(nickname_->GetText() + "_" + String(Random(1, 1000)));
marginTop += 80;
clientCount_ = CreateLabel("Connections: 0", IntVector2(20, marginTop));
statusMessage_ = CreateLabel("", IntVector2(20, -20));
SetStatusMessage("Started");
statusMessage_->SetAlignment(HA_LEFT, VA_BOTTOM);
String information = "R - Reset host";
information += "\nE - Disconnect";
information += "\nTAB - Show player list";
information += "\nWASD - move around";
information += "\nH - Toggle mouse visible/hidden";
information += "\nSpace - Jump";
info_ = CreateLabel(information, IntVector2(0, 50));
info_->SetHorizontalAlignment(HA_RIGHT);
// No viewports or scene is defined. However, the default zone's fog color controls the fill color
GetSubsystem<Renderer>()->GetDefaultZone()->SetFogColor(Color(0.0f, 0.0f, 0.1f));
}
void P2PMultiplayer::SubscribeToEvents()
{
SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(P2PMultiplayer, HandleUpdate));
SubscribeToEvent(searchGame_, "Released", URHO3D_HANDLER(P2PMultiplayer, HandleSearchSession));
SubscribeToEvent(E_CLIENTCONNECTED, URHO3D_HANDLER(P2PMultiplayer, HandleClientConnected));
SubscribeToEvent(E_CLIENTDISCONNECTED, URHO3D_HANDLER(P2PMultiplayer, HandleClientDisconnected));
SubscribeToEvent(E_P2PALLREADYCHANGED, URHO3D_HANDLER(P2PMultiplayer, HandleAllReadyChanged));
SubscribeToEvent(E_P2PNEWHOST, URHO3D_HANDLER(P2PMultiplayer, HandleNewHost));
SubscribeToEvent(E_NETWORKBANNED, URHO3D_HANDLER(P2PMultiplayer, HandleBanned));
SubscribeToEvent(E_CLIENTIDENTITY, URHO3D_HANDLER(P2PMultiplayer, HandleClientIdentity));
SubscribeToEvent(E_SERVERFULL, URHO3D_HANDLER(P2PMultiplayer, HandleServerFull));
GetSubsystem<Network>()->RegisterRemoteEvent("GameStart");
SubscribeToEvent("GameStart", URHO3D_HANDLER(P2PMultiplayer, HandleGameState));
}
void P2PMultiplayer::HandleSearchSession(StringHash eventType, VariantMap& eventData)
{
if (GetSubsystem<Network>()->IsServerRunning() || GetSubsystem<Network>()->IsConnectedHost()) {
URHO3D_LOGERROR("Already connected to session!");
return;
}
httpRequest_ = GetSubsystem<Network>()->MakeHttpRequest(API_SEARCH_SESSION);
}
void P2PMultiplayer::StartSession()
{
peers_.Clear();
VariantMap identity;
identity["Name"] = nickname_->GetText();
GetSubsystem<Network>()->StartSession(scene_, identity);
SetStatusMessage("Starting P2P session");
httpRequest_ = GetSubsystem<Network>()->MakeHttpRequest(API_NEW_SESSION + "?guid=" + GetSubsystem<Network>()->GetGUID() + "&state=" + String((int)gameState_) + "&peers=1");
SubscribeToEvent(E_P2PSESSIONSTARTED, URHO3D_HANDLER(P2PMultiplayer, HandleSessionStarted));
SubscribeToEvent(E_P2PSESSIONJOINED, URHO3D_HANDLER(P2PMultiplayer, HandleSessionJoined));
}
void P2PMultiplayer::JoinSession(const String& guid)
{
peers_.Clear();
VariantMap identity;
SetRandomSeed(Time::GetSystemTime());
identity["Name"] = nickname_->GetText();
GetSubsystem<Network>()->JoinSession(guid, scene_, identity);
SetStatusMessage("Joining " + guid + " P2P session");
}
void P2PMultiplayer::HandleSessionStarted(StringHash eventType, VariantMap& eventData)
{
UnsubscribeFromEvent(E_P2PSESSIONSTARTED);
SetStatusMessage("P2P Session started");
gameState_ = GameState::IN_LOBBY;
}
void P2PMultiplayer::HandleSessionJoined(StringHash eventType, VariantMap& eventData)
{
SetStatusMessage("Joined P2P Session");
gameState_ = GameState::IN_LOBBY;
}
void P2PMultiplayer::SetStatusMessage(const String& message)
{
String allMessages;
for (auto it = messages_.Begin(); it != messages_.End(); ++it) {
allMessages += (*it) + "\n";
}
statusMessage_->SetText("Status: " + allMessages);
messages_.Push(message);
if (messages_.Size() > 15) {
messages_.PopFront();
}
}
void P2PMultiplayer::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
auto input = GetSubsystem<Input>();
float timestep = eventData[P_TIMESTEP].GetFloat();
static float gametime;
gametime += timestep * 10;
if (GetSubsystem<UI>()->GetFocusElement() == nullptr) {
if (input->GetKeyPress(KEY_R)) {
GetSubsystem<Network>()->ResetHost();
}
if (input->GetKeyPress(KEY_TAB)) {
playerList_->SetVisible(!playerList_->IsVisible());
}
if (input->GetKeyPress(KEY_E) && GetSubsystem<Network>()->GetServerConnection()) {
GetSubsystem<Network>()->Disconnect(1000);
httpRequest_ = GetSubsystem<Network>()->MakeHttpRequest(API_REMOVE_SESSION + "?guid=" + GetSubsystem<Network>()->GetGUID());
peers_.Clear();
GetSubsystem<Input>()->SetMouseVisible(true);
GetSubsystem<Input>()->SetMouseGrabbed(false);
GetSubsystem<Input>()->SetMouseMode(MouseMode::MM_FREE);
SetStatusMessage("Disconnected");
UpdatePlayerList();
gameState_ = IN_MENU;
}
if (input->GetKeyPress(KEY_H)) {
if (input->IsMouseVisible()) {
input->SetMouseVisible(false);
input->SetMouseGrabbed(true);
input->SetMouseMode(MouseMode::MM_WRAP);
} else {
input->SetMouseVisible(true);
input->SetMouseGrabbed(false);
input->SetMouseMode(MouseMode::MM_FREE);
}
}
}
if (startGame_ && startCountdown_.GetMSec(false) > 5000) {
startGame_ = false;
InitPlayers();
}
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch and only move the camera
// when the cursor is hidden
IntVector2 mouseMove = input->GetMouseMove();
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
pitch_ = Clamp(pitch_, 1.0f, 90.0f);
if (gameState_ == IN_GAME) {
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
}
if (GetSubsystem<Network>()->GetServerConnection()) {
Controls controls;
// Copy mouse yaw
controls.yaw_ = yaw_;
controls.Set(CTRL_FORWARD, input->GetKeyDown(KEY_W));
controls.Set(CTRL_BACK, input->GetKeyDown(KEY_S));
controls.Set(CTRL_LEFT, input->GetKeyDown(KEY_A));
controls.Set(CTRL_RIGHT, input->GetKeyDown(KEY_D));
controls.Set(CTRL_JUMP, input->GetKeyDown(KEY_SPACE));
GetSubsystem<Network>()->GetServerConnection()->SetControls(controls);
}
if (timer_.GetMSec(false) > 1000) {
timer_.Reset();
if (startGame_) {
int timeRemaining = 5 - (int)(startCountdown_.GetMSec(false) / 1000);
SetStatusMessage("Countdown till start " + String(timeRemaining));
}
if (GetSubsystem<Network>()->GetClientConnections().Size() != peers_.Size() - 1) {
UpdateClientObjects();
}
clientCount_->SetText("Connections: " + String(GetSubsystem<Network>()->GetParticipantCount()));
if (GetSubsystem<Network>()->IsHostSystem() && GetSubsystem<Network>()->IsServerRunning()) {
httpRequest_ = GetSubsystem<Network>()->MakeHttpRequest(
API_NEW_SESSION + "?guid=" + GetSubsystem<Network>()->GetGUID() + "&state=" +
String((int) gameState_) + "&peers=" + String(GetSubsystem<Network>()->GetClientConnections().Size() + 1));
}
}
if (!httpRequest_.Null()) {
// Initializing HTTP request
if (httpRequest_->GetState() == HTTP_INITIALIZING) {
}
else if (httpRequest_->GetState() == HTTP_ERROR) {
URHO3D_LOGERROR("Master server returned error!");
SetStatusMessage("Master server returned error!");
}
else
{
if (httpRequest_->GetAvailableSize() > 0) {
message_ = httpRequest_->ReadString();
}
else
{
String url = httpRequest_->GetURL();
httpRequest_.Reset();
if (url == API_SEARCH_SESSION) {
URHO3D_LOGINFO("Search finished! " + message_);
SharedPtr<JSONFile> json(new JSONFile(context_));
json->FromString(message_);
message_.Clear();
JSONValue val = json->GetRoot().Get("guid");
if (val.IsNull()) {
URHO3D_LOGWARNING("No active sessions, starting new one");
new Urho3D::MessageBox(context_, "Creating new P2P session", "No active sessions");
StartSession();
}
else {
URHO3D_LOGWARNING("Found incomplete session, joining it");
new Urho3D::MessageBox(context_, "Joining other p2p session: " + val.GetString(), "Incomplete session found");
JoinSession(val.GetString());
}
} else if (url.Contains(API_NEW_SESSION)) {
}
}
}
}
if (gameState_ == IN_GAME) {
auto serverConnection = GetSubsystem<Network>()->GetServerConnection();
if (serverConnection) {
if (peers_[serverConnection] && peers_[serverConnection]->GetNode()) {
const float CAMERA_DISTANCE = 4.0f;
// Move camera some distance away from the ball
cameraNode_->SetPosition(peers_[serverConnection]->GetNode()->GetPosition() + cameraNode_->GetRotation() * Vector3::BACK * CAMERA_DISTANCE);
} else {
UpdateClientObjects();
}
}
}
}
void P2PMultiplayer::Init() {
GetSubsystem<Network>()->SetMode(NetworkMode::PEER_TO_PEER);
GetSubsystem<Network>()->SetNATServerInfo(NAT_PUNCHTROUGH_SERVER, NAT_PUNCHTROUGH_SERVER_PORT);
GetSubsystem<Network>()->SetUpdateFps(30);
//httpRequest_ = GetSubsystem<Network>()->MakeHttpRequest("http://frameskippers.com:82/guid.txt");
}
//
Button* P2PMultiplayer::CreateButton(const String& text, int width, IntVector2 position)
{
auto* cache = GetSubsystem<ResourceCache>();
auto* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
auto* button = GetSubsystem<UI>()->GetRoot()->CreateChild<Button>();
button->SetStyleAuto();
button->SetFixedWidth(width);
button->SetFixedHeight(30);
button->SetPosition(position);
auto* buttonText = button->CreateChild<Text>();
buttonText->SetFont(font, 12);
buttonText->SetAlignment(HA_CENTER, VA_CENTER);
buttonText->SetText(text);
return button;
}
LineEdit* P2PMultiplayer::CreateLineEdit(const String& placeholder, int width, IntVector2 pos)
{
auto* textEdit = GetSubsystem<UI>()->GetRoot()->CreateChild<LineEdit>("");
textEdit->SetStyleAuto();
textEdit->SetFixedWidth(width);
textEdit->SetFixedHeight(30);
textEdit->SetText(placeholder);
textEdit->SetPosition(pos);
return textEdit;
}
//
Text* P2PMultiplayer::CreateLabel(const String& text, IntVector2 pos)
{
auto* cache = GetSubsystem<ResourceCache>();
// Create log element to view latest logs from the system
auto* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
auto* label = GetSubsystem<UI>()->GetRoot()->CreateChild<Text>();
label->SetFont(font, 12);
label->SetColor(Color(0.0f, 1.0f, 0.0f));
label->SetPosition(pos);
label->SetText(text);
label->SetTextEffect(TextEffect::TE_STROKE);
return label;
}
void P2PMultiplayer::CreateScene()
{
scene_ = new Scene(context_);
auto* cache = GetSubsystem<ResourceCache>();
// Create octree and physics world with default settings. Create them as local so that they are not needlessly replicated
// when a client connects
scene_->CreateComponent<Octree>(LOCAL);
scene_->CreateComponent<PhysicsWorld>(LOCAL);
// All static scene content and the camera are also created as local, so that they are unaffected by scene replication and are
// not removed from the client upon connection. Create a Zone component first for ambient lighting & fog control.
Node* zoneNode = scene_->CreateChild("Zone", LOCAL);
auto* zone = zoneNode->CreateComponent<Zone>();
zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
zone->SetAmbientColor(Color(0.1f, 0.1f, 0.1f));
zone->SetFogStart(100.0f);
zone->SetFogEnd(300.0f);
// Create a directional light without shadows
Node* lightNode = scene_->CreateChild("DirectionalLight", LOCAL);
lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
auto* light = lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_DIRECTIONAL);
light->SetColor(Color(0.2f, 0.2f, 0.2f));
light->SetSpecularIntensity(1.0f);
// Create a "floor" consisting of several tiles. Make the tiles physical but leave small cracks between them
for (int y = -20; y <= 20; ++y)
{
for (int x = -20; x <= 20; ++x)
{
Node* floorNode = scene_->CreateChild("FloorTile", LOCAL);
floorNode->SetPosition(Vector3(x * 20.2f, -0.5f, y * 20.2f));
floorNode->SetScale(Vector3(20.0f, 1.0f, 20.0f));
auto* floorObject = floorNode->CreateComponent<StaticModel>();
floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
auto* body = floorNode->CreateComponent<RigidBody>();
body->SetFriction(1.0f);
body->SetRestitution(0.5);
auto* shape = floorNode->CreateComponent<CollisionShape>();
shape->SetBox(Vector3::ONE);
}
}
// Create the camera. Limit far clip distance to match the fog
// The camera needs to be created into a local node so that each client can retain its own camera, that is unaffected by
// network messages. Furthermore, because the client removes all replicated scene nodes when connecting to a server scene,
// the screen would become blank if the camera node was replicated (as only the locally created camera is assigned to a
// viewport in SetupViewports() below)
cameraNode_ = scene_->CreateChild("Camera", LOCAL);
auto* camera = cameraNode_->CreateComponent<Camera>();
camera->SetFarClip(300.0f);
// Set an initial position for the camera scene node above the plane
cameraNode_->SetPosition(Vector3(-10.0f, 10.0f, 10.0f));
cameraNode_->LookAt(Vector3(0, 0, 0));
}
void P2PMultiplayer::SetupViewport()
{
auto* renderer = GetSubsystem<Renderer>();
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
}
void P2PMultiplayer::HandleClientConnected(StringHash eventType, VariantMap& eventData)
{
using namespace ClientConnected;
// When a client connects, assign to scene to begin scene replication
auto* newConnection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
newConnection->SetScene(scene_);
SetStatusMessage("Client connected");
UpdatePlayerList();
}
void P2PMultiplayer::HandleClientDisconnected(StringHash eventType, VariantMap& eventData)
{
using namespace ClientConnected;
// // When a client disconnects, remove the controlled object
auto* connection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
DestroyPlayerNode(connection);
UpdateClientObjects();
SetStatusMessage("Client discconnected");
UpdatePlayerList();
}
void P2PMultiplayer::UpdateClientObjects()
{
PODVector<Node*> playerNodes;
scene_->GetNodesWithTag(playerNodes, "Player");
auto clients = GetSubsystem<Network>()->GetClientConnections();
for (auto it = clients.Begin(); it != clients.End(); ++it) {
for (auto it2 = playerNodes.Begin(); it2 != playerNodes.End(); ++it2) {
if ((*it2)->GetVar("GUID").GetString() == (*it)->GetGUID()) {
if (!peers_[(*it)]) {
peers_[(*it)] = new Peer(context_);
peers_[(*it)]->SetConnection((*it));
peers_[(*it)]->SetScene(scene_);
}
peers_[(*it)]->SetNode((*it2));
}
}
}
for (auto it2 = playerNodes.Begin(); it2 != playerNodes.End(); ++it2) {
if ((*it2)->GetVar("GUID").GetString() == GetSubsystem<Network>()->GetGUID()) {
if (!peers_[GetSubsystem<Network>()->GetServerConnection()]) {
peers_[GetSubsystem<Network>()->GetServerConnection()] = new Peer(context_);
peers_[GetSubsystem<Network>()->GetServerConnection()]->SetConnection(GetSubsystem<Network>()->GetServerConnection());
peers_[GetSubsystem<Network>()->GetServerConnection()]->SetScene(scene_);
}
peers_[GetSubsystem<Network>()->GetServerConnection()]->SetNode(*it2);
}
}
}
void P2PMultiplayer::HandleAllReadyChanged(StringHash eventType, VariantMap& eventData)
{
using namespace P2PAllReadyChanged;
_allReady = eventData[P_READY].GetBool();
if (_allReady) {
startGame_ = true;
startCountdown_.Reset();
} else {
if (startGame_) {
startGame_ = false;
SetStatusMessage("Countdown stopped! Not all players are ready!");
}
}
UpdatePlayerList();
}
void P2PMultiplayer::CreatePlayerNode(Connection* connection)
{
if (peers_[connection]) {
return;
}
peers_[connection] = new Peer(context_);
peers_[connection]->SetScene(scene_);
peers_[connection]->Create(connection);
}
void P2PMultiplayer::DestroyPlayerNode(Connection* connection)
{
if (peers_[connection]) {
peers_[connection]->DestroyNode();
peers_.Erase(connection);
}
}
void P2PMultiplayer::HandleNewHost(StringHash eventType, VariantMap& eventData)
{
using namespace P2PNewHost;
URHO3D_LOGINFOF("Host changed %s, %i => %s", eventData[P_ADDRESS].GetString().CString(), eventData[P_PORT].GetInt(), eventData[P_GUID].GetString().CString());
SetRandomSeed(Time::GetSystemTime());
String guid = eventData[P_GUID].GetString();
SetStatusMessage("New host elected: " + eventData[P_GUID].GetString());
if (guid != GetSubsystem<Network>()->GetGUID()) {
httpRequest_ = GetSubsystem<Network>()->MakeHttpRequest(API_REMOVE_SESSION + "?guid=" + GetSubsystem<Network>()->GetGUID());
}
UpdatePlayerList();
}
void P2PMultiplayer::HandleBanned(StringHash eventType, VariantMap& eventData)
{
GetSubsystem<Network>()->Disconnect(1000);
httpRequest_ = GetSubsystem<Network>()->MakeHttpRequest(API_REMOVE_SESSION + "?guid=" + GetSubsystem<Network>()->GetGUID());
peers_.Clear();
GetSubsystem<Input>()->SetMouseVisible(true);
GetSubsystem<Input>()->SetMouseGrabbed(false);
gameState_ = IN_MENU;
// GetSubsystem<Input>()->SetMouseMode(MouseMode::MM_FREE);
using namespace NetworkBanned;
URHO3D_LOGWARNING("We have been banned, reason: " + eventData[P_REASON].GetString());
SetStatusMessage("You are banned");
}
void P2PMultiplayer::HandleClientIdentity(StringHash eventType, VariantMap& eventData)
{
using namespace ClientIdentity;
auto connection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
// URHO3D_LOGINFO("Client identity: Client " + connection->GetGUID() + " => " + connection->GetIdentity()["Name"].GetString());
UpdatePlayerList();
}
void P2PMultiplayer::InitPlayers()
{
if (!GetSubsystem<Network>()->IsHostSystem()) {
return;
}
if (!_allReady) {
SetStatusMessage("Can't start, not all players are ready!");
return;
}
auto clients = GetSubsystem<Network>()->GetClientConnections();
for (auto it = clients.Begin(); it != clients.End(); ++it) {
CreatePlayerNode((*it));
}
if (GetSubsystem<Network>()->GetServerConnection()) {
CreatePlayerNode(GetSubsystem<Network>()->GetServerConnection());
}
SetStatusMessage("Initializing all players");
gameState_ = IN_GAME;
VariantMap data = GetEventDataMap();
data["GameState"] = gameState_;
GetSubsystem<Network>()->BroadcastRemoteEvent("GameStart", false, data);
playerList_->SetVisible(false);
}
void P2PMultiplayer::HandleGameState(StringHash eventType, VariantMap& eventData)
{
if (eventType == "GameStart") {
gameState_ = (GameState) eventData["GameState"].GetUInt();
SetStatusMessage("Game started!");
playerList_->SetVisible(false);
}
}
void P2PMultiplayer::UpdatePlayerList()
{
auto* cache = GetSubsystem<ResourceCache>();
auto* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
auto* label = GetSubsystem<UI>()->GetRoot()->CreateChild<Text>();
playerList_->RemoveAllChildren();
auto playerName = playerList_->CreateChild<Text>();
playerName->SetPosition(IntVector2(10, 10));
playerName->SetAlignment(HA_LEFT, VA_TOP);
playerName->SetText("Nickname");
playerName->SetFont(font, 12);
playerName->SetFontSize(16);
playerName->SetTextEffect(TextEffect::TE_SHADOW);
playerName->SetColor(Color::GRAY);
auto playerGuid = playerList_->CreateChild<Text>();
playerGuid->SetPosition(IntVector2(0, 10));
playerGuid->SetAlignment(HA_CENTER, VA_TOP);
playerGuid->SetText("Ping");
playerGuid->SetFont(font, 12);
playerGuid->SetFontSize(16);
playerGuid->SetTextEffect(TextEffect::TE_SHADOW);
playerGuid->SetColor(Color::GRAY);
auto playerStatus = playerList_->CreateChild<Text>();
playerStatus->SetPosition(IntVector2(-10, 10));
playerStatus->SetAlignment(HA_RIGHT, VA_TOP);
playerStatus->SetText("Ready status");
playerStatus->SetFont(font, 12);
playerStatus->SetFontSize(16);
playerStatus->SetTextEffect(TextEffect::TE_SHADOW);
playerStatus->SetColor(Color::GRAY);
int marginTop = 40;
auto connections = GetSubsystem<Network>()->GetClientConnections();
connections.Push(SharedPtr<Connection>(GetSubsystem<Network>()->GetServerConnection()));
for (auto it = connections.Begin(); it != connections.End(); ++it) {
if ((*it)) {
auto playerName = playerList_->CreateChild<Text>();
playerName->SetPosition(IntVector2(20, marginTop));
playerName->SetAlignment(HA_LEFT, VA_TOP);
playerName->SetText((*it)->GetIdentity()["Name"].GetString());
playerName->SetFont(font, 12);
playerName->SetTextEffect(TextEffect::TE_SHADOW);
if ((*it)->GetGUID() == GetSubsystem<Network>()->GetHostAddress()) {
playerName->SetText(playerName->GetText() + " [HOST]");
}
auto playerGuid = playerList_->CreateChild<Text>();
playerGuid->SetPosition(IntVector2(0, marginTop));
playerGuid->SetAlignment(HA_CENTER, VA_TOP);
playerGuid->SetText(String((*it)->GetLastPing()));
playerGuid->SetFont(font, 12);
playerGuid->SetTextEffect(TextEffect::TE_SHADOW);
if ((*it) == GetSubsystem<Network>()->GetServerConnection()) {
playerName->SetColor(Color::GREEN);
auto readyState = playerList_->CreateChild<Button>();
readyState->SetPosition(IntVector2(-20, marginTop - 5));
readyState->SetAlignment(HA_RIGHT, VA_TOP);
readyState->SetStyleAuto();
readyState->SetWidth(100);
readyState->SetHeight(30);
SubscribeToEvent(readyState, "Released", [&](StringHash eventType, VariantMap& eventData) {
GetSubsystem<Network>()->SetReady(!GetSubsystem<Network>()->GetReady());
});
auto playerStatus = readyState->CreateChild<Text>();
playerStatus->SetAlignment(HA_CENTER, VA_CENTER);
playerStatus->SetText((*it)->GetReady() ? "Ready" : "Not ready");
playerStatus->SetColor((*it)->GetReady() ? Color::GREEN : Color::RED);
playerStatus->SetFont(font, 12);
playerStatus->SetTextEffect(TextEffect::TE_SHADOW);
}
else {
auto playerStatus = playerList_->CreateChild<Text>();
playerStatus->SetPosition(IntVector2(-20, marginTop));
playerStatus->SetAlignment(HA_RIGHT, VA_TOP);
playerStatus->SetText((*it)->GetReady() ? "Ready" : "Not ready");
playerStatus->SetColor((*it)->GetReady() ? Color::GREEN : Color::RED);
playerStatus->SetFont(font, 12);
playerStatus->SetTextEffect(TextEffect::TE_SHADOW);
}
marginTop += 25;
}
}
}
void P2PMultiplayer::CreatePlayerListWindow()
{
playerList_ = GetSubsystem<UI>()->GetRoot()->CreateChild<Window>();
playerList_->SetStyleAuto();
playerList_->SetAlignment(HA_CENTER, VA_CENTER);
playerList_->SetSize(IntVector2(GetSubsystem<Graphics>()->GetWidth() - 200, GetSubsystem<Graphics>()->GetHeight() - 400));
playerList_->BringToFront();
}
void P2PMultiplayer::HandleServerFull(StringHash eventType, VariantMap& eventData)
{
UpdatePlayerList();
}