Sample.inl 13 KB

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