Chat.cpp 10 KB

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