Chat.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Audio/Audio.h>
  4. #include <Urho3D/Audio/Sound.h>
  5. #include <Urho3D/Engine/Engine.h>
  6. #include <Urho3D/Graphics/Graphics.h>
  7. #include <Urho3D/Graphics/Zone.h>
  8. #include <Urho3D/Input/Input.h>
  9. #include <Urho3D/IO/IOEvents.h>
  10. #include <Urho3D/IO/Log.h>
  11. #include <Urho3D/IO/MemoryBuffer.h>
  12. #include <Urho3D/IO/VectorBuffer.h>
  13. #include <Urho3D/Network/Network.h>
  14. #include <Urho3D/Network/NetworkEvents.h>
  15. #include <Urho3D/Network/Protocol.h>
  16. #include <Urho3D/Resource/ResourceCache.h>
  17. #include <Urho3D/Scene/Scene.h>
  18. #include <Urho3D/UI/Button.h>
  19. #include <Urho3D/UI/Font.h>
  20. #include <Urho3D/UI/LineEdit.h>
  21. #include <Urho3D/UI/Text.h>
  22. #include <Urho3D/UI/UI.h>
  23. #include <Urho3D/UI/UIEvents.h>
  24. #include "Chat.h"
  25. #include <Urho3D/DebugNew.h>
  26. // Undefine Windows macro, as our Connection class has a function called SendMessage
  27. #ifdef SendMessage
  28. #undef SendMessage
  29. #endif
  30. // Identifier for the chat network messages
  31. const int MSG_CHAT = MSG_USER + 0;
  32. // UDP port we will use
  33. const unsigned short CHAT_SERVER_PORT = 2345;
  34. URHO3D_DEFINE_APPLICATION_MAIN(Chat)
  35. Chat::Chat(Context* context) :
  36. Sample(context)
  37. {
  38. }
  39. void Chat::Start()
  40. {
  41. // Execute base class startup
  42. Sample::Start();
  43. // Enable OS cursor
  44. GetSubsystem<Input>()->SetMouseVisible(true);
  45. // Create the user interface
  46. CreateUI();
  47. // Subscribe to UI and network events
  48. SubscribeToEvents();
  49. // Set the mouse mode to use in the sample
  50. Sample::InitMouseMode(MM_FREE);
  51. }
  52. void Chat::CreateUI()
  53. {
  54. SetLogoVisible(false); // We need the full rendering window
  55. auto* graphics = GetSubsystem<Graphics>();
  56. UIElement* root = GetSubsystem<UI>()->GetRoot();
  57. auto* cache = GetSubsystem<ResourceCache>();
  58. auto* uiStyle = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  59. // Set style to the UI root so that elements will inherit it
  60. root->SetDefaultStyle(uiStyle);
  61. auto* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
  62. chatHistoryText_ = root->CreateChild<Text>();
  63. chatHistoryText_->SetFont(font, 12);
  64. buttonContainer_ = root->CreateChild<UIElement>();
  65. buttonContainer_->SetFixedSize(graphics->GetWidth(), 20);
  66. buttonContainer_->SetPosition(0, graphics->GetHeight() - 20);
  67. buttonContainer_->SetLayoutMode(LM_HORIZONTAL);
  68. textEdit_ = buttonContainer_->CreateChild<LineEdit>();
  69. textEdit_->SetStyleAuto();
  70. sendButton_ = CreateButton("Send", 70);
  71. connectButton_ = CreateButton("Connect", 90);
  72. disconnectButton_ = CreateButton("Disconnect", 100);
  73. startServerButton_ = CreateButton("Start Server", 110);
  74. UpdateButtons();
  75. float rowHeight = chatHistoryText_->GetRowHeight();
  76. // Row height would be zero if the font failed to load
  77. if (rowHeight)
  78. {
  79. float numberOfRows = (graphics->GetHeight() - 100) / rowHeight;
  80. chatHistory_.Resize(static_cast<unsigned int>(numberOfRows));
  81. }
  82. // No viewports or scene is defined. However, the default zone's fog color controls the fill color
  83. GetSubsystem<Renderer>()->GetDefaultZone()->SetFogColor(Color(0.0f, 0.0f, 0.1f));
  84. }
  85. void Chat::SubscribeToEvents()
  86. {
  87. // Subscribe to UI element events
  88. SubscribeToEvent(textEdit_, E_TEXTFINISHED, URHO3D_HANDLER(Chat, HandleSend));
  89. SubscribeToEvent(sendButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleSend));
  90. SubscribeToEvent(connectButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleConnect));
  91. SubscribeToEvent(disconnectButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleDisconnect));
  92. SubscribeToEvent(startServerButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleStartServer));
  93. // Subscribe to log messages so that we can pipe them to the chat window
  94. SubscribeToEvent(E_LOGMESSAGE, URHO3D_HANDLER(Chat, HandleLogMessage));
  95. // Subscribe to network events
  96. SubscribeToEvent(E_NETWORKMESSAGE, URHO3D_HANDLER(Chat, HandleNetworkMessage));
  97. SubscribeToEvent(E_SERVERCONNECTED, URHO3D_HANDLER(Chat, HandleConnectionStatus));
  98. SubscribeToEvent(E_SERVERDISCONNECTED, URHO3D_HANDLER(Chat, HandleConnectionStatus));
  99. SubscribeToEvent(E_CONNECTFAILED, URHO3D_HANDLER(Chat, HandleConnectionStatus));
  100. }
  101. Button* Chat::CreateButton(const String& text, int width)
  102. {
  103. auto* cache = GetSubsystem<ResourceCache>();
  104. auto* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
  105. auto* button = buttonContainer_->CreateChild<Button>();
  106. button->SetStyleAuto();
  107. button->SetFixedWidth(width);
  108. auto* buttonText = button->CreateChild<Text>();
  109. buttonText->SetFont(font, 12);
  110. buttonText->SetAlignment(HA_CENTER, VA_CENTER);
  111. buttonText->SetText(text);
  112. return button;
  113. }
  114. void Chat::ShowChatText(const String& row)
  115. {
  116. chatHistory_.Erase(0);
  117. chatHistory_.Push(row);
  118. // Concatenate all the rows in history
  119. String allRows;
  120. for (const String& row : chatHistory_)
  121. allRows += row + "\n";
  122. chatHistoryText_->SetText(allRows);
  123. }
  124. void Chat::UpdateButtons()
  125. {
  126. auto* network = GetSubsystem<Network>();
  127. Connection* serverConnection = network->GetServerConnection();
  128. bool serverRunning = network->IsServerRunning();
  129. // Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time
  130. sendButton_->SetVisible(serverConnection != nullptr);
  131. connectButton_->SetVisible(!serverConnection && !serverRunning);
  132. disconnectButton_->SetVisible(serverConnection || serverRunning);
  133. startServerButton_->SetVisible(!serverConnection && !serverRunning);
  134. }
  135. void Chat::HandleLogMessage(StringHash /*eventType*/, VariantMap& eventData)
  136. {
  137. using namespace LogMessage;
  138. ShowChatText(eventData[P_MESSAGE].GetString());
  139. }
  140. void Chat::HandleSend(StringHash /*eventType*/, VariantMap& eventData)
  141. {
  142. String text = textEdit_->GetText();
  143. if (text.Empty())
  144. return; // Do not send an empty message
  145. auto* network = GetSubsystem<Network>();
  146. Connection* serverConnection = network->GetServerConnection();
  147. if (serverConnection)
  148. {
  149. // A VectorBuffer object is convenient for constructing a message to send
  150. VectorBuffer msg;
  151. msg.WriteString(text);
  152. // Send the chat message as in-order and reliable
  153. serverConnection->SendMessage(MSG_CHAT, true, true, msg);
  154. // Empty the text edit after sending
  155. textEdit_->SetText(String::EMPTY);
  156. }
  157. }
  158. void Chat::HandleConnect(StringHash /*eventType*/, VariantMap& eventData)
  159. {
  160. auto* network = GetSubsystem<Network>();
  161. String address = textEdit_->GetText().Trimmed();
  162. if (address.Empty())
  163. address = "localhost"; // Use localhost to connect if nothing else specified
  164. // Empty the text edit after reading the address to connect to
  165. textEdit_->SetText(String::EMPTY);
  166. // Connect to server, do not specify a client scene as we are not using scene replication, just messages.
  167. // At connect time we could also send identity parameters (such as username) in a VariantMap, but in this
  168. // case we skip it for simplicity
  169. network->Connect(address, CHAT_SERVER_PORT, nullptr);
  170. UpdateButtons();
  171. }
  172. void Chat::HandleDisconnect(StringHash /*eventType*/, VariantMap& eventData)
  173. {
  174. auto* network = GetSubsystem<Network>();
  175. Connection* serverConnection = network->GetServerConnection();
  176. // If we were connected to server, disconnect
  177. if (serverConnection)
  178. serverConnection->Disconnect();
  179. // Or if we were running a server, stop it
  180. else if (network->IsServerRunning())
  181. network->StopServer();
  182. UpdateButtons();
  183. }
  184. void Chat::HandleStartServer(StringHash /*eventType*/, VariantMap& eventData)
  185. {
  186. auto* network = GetSubsystem<Network>();
  187. network->StartServer(CHAT_SERVER_PORT);
  188. UpdateButtons();
  189. }
  190. void Chat::HandleNetworkMessage(StringHash /*eventType*/, VariantMap& eventData)
  191. {
  192. auto* network = GetSubsystem<Network>();
  193. using namespace NetworkMessage;
  194. int msgID = eventData[P_MESSAGEID].GetI32();
  195. if (msgID == MSG_CHAT)
  196. {
  197. const Vector<byte>& data = eventData[P_DATA].GetBuffer();
  198. // Use a MemoryBuffer to read the message data so that there is no unnecessary copying
  199. MemoryBuffer msg(data);
  200. String text = msg.ReadString();
  201. // If we are the server, prepend the sender's IP address and port and echo to everyone
  202. // If we are a client, just display the message
  203. if (network->IsServerRunning())
  204. {
  205. auto* sender = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
  206. text = sender->ToString() + " " + text;
  207. VectorBuffer sendMsg;
  208. sendMsg.WriteString(text);
  209. // Broadcast as in-order and reliable
  210. network->BroadcastMessage(MSG_CHAT, true, true, sendMsg);
  211. }
  212. ShowChatText(text);
  213. }
  214. }
  215. void Chat::HandleConnectionStatus(StringHash /*eventType*/, VariantMap& eventData)
  216. {
  217. UpdateButtons();
  218. }