Sample.inl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. //
  2. // Copyright (c) 2008-2015 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/Engine/Application.h>
  23. #include <Urho3D/Graphics/Camera.h>
  24. #include <Urho3D/Engine/Console.h>
  25. #include <Urho3D/UI/Cursor.h>
  26. #include <Urho3D/Engine/DebugHud.h>
  27. #include <Urho3D/Engine/Engine.h>
  28. #include <Urho3D/IO/FileSystem.h>
  29. #include <Urho3D/Graphics/Graphics.h>
  30. #include <Urho3D/Input/Input.h>
  31. #include <Urho3D/Input/InputEvents.h>
  32. #include <Urho3D/Graphics/Renderer.h>
  33. #include <Urho3D/Resource/ResourceCache.h>
  34. #include <Urho3D/Scene/Scene.h>
  35. #include <Urho3D/Scene/SceneEvents.h>
  36. #include <Urho3D/UI/Sprite.h>
  37. #include <Urho3D/Graphics/Texture2D.h>
  38. #include <Urho3D/Core/Timer.h>
  39. #include <Urho3D/UI/UI.h>
  40. #include <Urho3D/Resource/XMLFile.h>
  41. Sample::Sample(Context* context) :
  42. Application(context),
  43. yaw_(0.0f),
  44. pitch_(0.0f),
  45. touchEnabled_(false),
  46. screenJoystickIndex_(M_MAX_UNSIGNED),
  47. screenJoystickSettingsIndex_(M_MAX_UNSIGNED),
  48. paused_(false)
  49. {
  50. }
  51. void Sample::Setup()
  52. {
  53. // Modify engine startup parameters
  54. engineParameters_["WindowTitle"] = GetTypeName();
  55. engineParameters_["LogName"] = GetSubsystem<FileSystem>()->GetAppPreferencesDir("urho3d", "logs") + GetTypeName() + ".log";
  56. engineParameters_["FullScreen"] = false;
  57. engineParameters_["Headless"] = false;
  58. engineParameters_["Sound"] = false;
  59. }
  60. void Sample::Start()
  61. {
  62. if (GetPlatform() == "Android" || GetPlatform() == "iOS")
  63. // On mobile platform, enable touch by adding a screen joystick
  64. InitTouchInput();
  65. else if (GetSubsystem<Input>()->GetNumJoysticks() == 0)
  66. // On desktop platform, do not detect touch when we already got a joystick
  67. SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(Sample, HandleTouchBegin));
  68. // Create logo
  69. CreateLogo();
  70. // Set custom window Title & Icon
  71. SetWindowTitleAndIcon();
  72. // Create console and debug HUD
  73. CreateConsoleAndDebugHud();
  74. // Subscribe key down event
  75. SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(Sample, HandleKeyDown));
  76. // Subscribe scene update event
  77. SubscribeToEvent(E_SCENEUPDATE, URHO3D_HANDLER(Sample, HandleSceneUpdate));
  78. }
  79. void Sample::Stop()
  80. {
  81. engine_->DumpResources(true);
  82. }
  83. void Sample::InitTouchInput()
  84. {
  85. touchEnabled_ = true;
  86. ResourceCache* cache = GetSubsystem<ResourceCache>();
  87. Input* input = GetSubsystem<Input>();
  88. XMLFile* layout = cache->GetResource<XMLFile>("UI/ScreenJoystick_Samples.xml");
  89. const String& patchString = GetScreenJoystickPatchString();
  90. if (!patchString.Empty())
  91. {
  92. // Patch the screen joystick layout further on demand
  93. SharedPtr<XMLFile> patchFile(new XMLFile(context_));
  94. if (patchFile->FromString(patchString))
  95. layout->Patch(patchFile);
  96. }
  97. screenJoystickIndex_ = input->AddScreenJoystick(layout, cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
  98. input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, true);
  99. }
  100. void Sample::SetLogoVisible(bool enable)
  101. {
  102. if (logoSprite_)
  103. logoSprite_->SetVisible(enable);
  104. }
  105. void Sample::CreateLogo()
  106. {
  107. // Get logo texture
  108. ResourceCache* cache = GetSubsystem<ResourceCache>();
  109. Texture2D* logoTexture = cache->GetResource<Texture2D>("Textures/LogoLarge.png");
  110. if (!logoTexture)
  111. return;
  112. // Create logo sprite and add to the UI layout
  113. UI* ui = GetSubsystem<UI>();
  114. logoSprite_ = ui->GetRoot()->CreateChild<Sprite>();
  115. // Set logo sprite texture
  116. logoSprite_->SetTexture(logoTexture);
  117. int textureWidth = logoTexture->GetWidth();
  118. int textureHeight = logoTexture->GetHeight();
  119. // Set logo sprite scale
  120. logoSprite_->SetScale(256.0f / textureWidth);
  121. // Set logo sprite size
  122. logoSprite_->SetSize(textureWidth, textureHeight);
  123. // Set logo sprite hot spot
  124. logoSprite_->SetHotSpot(0, textureHeight);
  125. // Set logo sprite alignment
  126. logoSprite_->SetAlignment(HA_LEFT, VA_BOTTOM);
  127. // Make logo not fully opaque to show the scene underneath
  128. logoSprite_->SetOpacity(0.75f);
  129. // Set a low priority for the logo so that other UI elements can be drawn on top
  130. logoSprite_->SetPriority(-100);
  131. }
  132. void Sample::SetWindowTitleAndIcon()
  133. {
  134. ResourceCache* cache = GetSubsystem<ResourceCache>();
  135. Graphics* graphics = GetSubsystem<Graphics>();
  136. Image* icon = cache->GetResource<Image>("Textures/UrhoIcon.png");
  137. graphics->SetWindowIcon(icon);
  138. graphics->SetWindowTitle("Urho3D Sample");
  139. }
  140. void Sample::CreateConsoleAndDebugHud()
  141. {
  142. // Get default style
  143. ResourceCache* cache = GetSubsystem<ResourceCache>();
  144. XMLFile* xmlFile = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  145. // Create console
  146. Console* console = engine_->CreateConsole();
  147. console->SetDefaultStyle(xmlFile);
  148. console->GetBackground()->SetOpacity(0.8f);
  149. // Create debug HUD.
  150. DebugHud* debugHud = engine_->CreateDebugHud();
  151. debugHud->SetDefaultStyle(xmlFile);
  152. }
  153. void Sample::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  154. {
  155. using namespace KeyDown;
  156. int key = eventData[P_KEY].GetInt();
  157. // Close console (if open) or exit when ESC is pressed
  158. if (key == KEY_ESC)
  159. {
  160. Console* console = GetSubsystem<Console>();
  161. if (console->IsVisible())
  162. console->SetVisible(false);
  163. else
  164. engine_->Exit();
  165. }
  166. // Toggle console with F1
  167. else if (key == KEY_F1)
  168. GetSubsystem<Console>()->Toggle();
  169. // Toggle debug HUD with F2
  170. else if (key == KEY_F2)
  171. {
  172. DebugHud* debugHud = GetSubsystem<DebugHud>();
  173. if (debugHud->GetMode() == 0 || debugHud->GetMode() == DEBUGHUD_SHOW_ALL_MEMORY)
  174. debugHud->SetMode(DEBUGHUD_SHOW_ALL);
  175. else
  176. debugHud->SetMode(DEBUGHUD_SHOW_NONE);
  177. }
  178. else if (key == KEY_F3)
  179. {
  180. DebugHud* debugHud = GetSubsystem<DebugHud>();
  181. if (debugHud->GetMode() == 0 || debugHud->GetMode() == DEBUGHUD_SHOW_ALL)
  182. debugHud->SetMode(DEBUGHUD_SHOW_ALL_MEMORY);
  183. else
  184. debugHud->SetMode(DEBUGHUD_SHOW_NONE);
  185. }
  186. // Common rendering quality controls, only when UI has no focused element
  187. else if (!GetSubsystem<UI>()->GetFocusElement())
  188. {
  189. Renderer* renderer = GetSubsystem<Renderer>();
  190. // Preferences / Pause
  191. if (key == KEY_SELECT && touchEnabled_)
  192. {
  193. paused_ = !paused_;
  194. Input* input = GetSubsystem<Input>();
  195. if (screenJoystickSettingsIndex_ == M_MAX_UNSIGNED)
  196. {
  197. // Lazy initialization
  198. ResourceCache* cache = GetSubsystem<ResourceCache>();
  199. screenJoystickSettingsIndex_ = input->AddScreenJoystick(cache->GetResource<XMLFile>("UI/ScreenJoystickSettings_Samples.xml"), cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
  200. }
  201. else
  202. input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, paused_);
  203. }
  204. // Texture quality
  205. else if (key == '1')
  206. {
  207. int quality = renderer->GetTextureQuality();
  208. ++quality;
  209. if (quality > QUALITY_HIGH)
  210. quality = QUALITY_LOW;
  211. renderer->SetTextureQuality(quality);
  212. }
  213. // Material quality
  214. else if (key == '2')
  215. {
  216. int quality = renderer->GetMaterialQuality();
  217. ++quality;
  218. if (quality > QUALITY_HIGH)
  219. quality = QUALITY_LOW;
  220. renderer->SetMaterialQuality(quality);
  221. }
  222. // Specular lighting
  223. else if (key == '3')
  224. renderer->SetSpecularLighting(!renderer->GetSpecularLighting());
  225. // Shadow rendering
  226. else if (key == '4')
  227. renderer->SetDrawShadows(!renderer->GetDrawShadows());
  228. // Shadow map resolution
  229. else if (key == '5')
  230. {
  231. int shadowMapSize = renderer->GetShadowMapSize();
  232. shadowMapSize *= 2;
  233. if (shadowMapSize > 2048)
  234. shadowMapSize = 512;
  235. renderer->SetShadowMapSize(shadowMapSize);
  236. }
  237. // Shadow depth and filtering quality
  238. else if (key == '6')
  239. {
  240. int quality = renderer->GetShadowQuality();
  241. ++quality;
  242. if (quality > SHADOWQUALITY_HIGH_24BIT)
  243. quality = SHADOWQUALITY_LOW_16BIT;
  244. renderer->SetShadowQuality(quality);
  245. }
  246. // Occlusion culling
  247. else if (key == '7')
  248. {
  249. bool occlusion = renderer->GetMaxOccluderTriangles() > 0;
  250. occlusion = !occlusion;
  251. renderer->SetMaxOccluderTriangles(occlusion ? 5000 : 0);
  252. }
  253. // Instancing
  254. else if (key == '8')
  255. renderer->SetDynamicInstancing(!renderer->GetDynamicInstancing());
  256. // Take screenshot
  257. else if (key == '9')
  258. {
  259. Graphics* graphics = GetSubsystem<Graphics>();
  260. Image screenshot(context_);
  261. graphics->TakeScreenShot(screenshot);
  262. // Here we save in the Data folder with date and time appended
  263. screenshot.SavePNG(GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Screenshot_" +
  264. Time::GetTimeStamp().Replaced(':', '_').Replaced('.', '_').Replaced(' ', '_') + ".png");
  265. }
  266. }
  267. }
  268. void Sample::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  269. {
  270. // Move the camera by touch, if the camera node is initialized by descendant sample class
  271. if (touchEnabled_ && cameraNode_)
  272. {
  273. Input* input = GetSubsystem<Input>();
  274. for (unsigned i = 0; i < input->GetNumTouches(); ++i)
  275. {
  276. TouchState* state = input->GetTouch(i);
  277. if (!state->touchedElement_) // Touch on empty space
  278. {
  279. if (state->delta_.x_ ||state->delta_.y_)
  280. {
  281. Camera* camera = cameraNode_->GetComponent<Camera>();
  282. if (!camera)
  283. return;
  284. Graphics* graphics = GetSubsystem<Graphics>();
  285. yaw_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.x_;
  286. pitch_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.y_;
  287. // Construct new orientation for the camera scene node from yaw and pitch; roll is fixed to zero
  288. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  289. }
  290. else
  291. {
  292. // Move the cursor to the touch position
  293. Cursor* cursor = GetSubsystem<UI>()->GetCursor();
  294. if (cursor && cursor->IsVisible())
  295. cursor->SetPosition(state->position_);
  296. }
  297. }
  298. }
  299. }
  300. }
  301. void Sample::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  302. {
  303. // On some platforms like Windows the presence of touch input can only be detected dynamically
  304. InitTouchInput();
  305. UnsubscribeFromEvent("TouchBegin");
  306. }