MultipleViewports.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/Core/CoreEvents.h>
  24. #include <Atomic/Engine/Engine.h>
  25. #include <Atomic/Graphics/Camera.h>
  26. #include <Atomic/Graphics/DebugRenderer.h>
  27. #include <Atomic/Graphics/Graphics.h>
  28. #include <Atomic/Graphics/Light.h>
  29. #include <Atomic/Graphics/Material.h>
  30. #include <Atomic/Graphics/Model.h>
  31. #include <Atomic/Graphics/Octree.h>
  32. #include <Atomic/Graphics/Renderer.h>
  33. #include <Atomic/Graphics/RenderPath.h>
  34. #include <Atomic/Graphics/StaticModel.h>
  35. #include <Atomic/Graphics/Zone.h>
  36. #include <Atomic/Input/Input.h>
  37. #include <Atomic/Resource/ResourceCache.h>
  38. #include <Atomic/Resource/XMLFile.h>
  39. #include <Atomic/Scene/Scene.h>
  40. #include <Atomic/UI/UI.h>
  41. #include "MultipleViewports.h"
  42. #include <Atomic/DebugNew.h>
  43. MultipleViewports::MultipleViewports(Context* context) :
  44. Sample(context),
  45. drawDebug_(false)
  46. {
  47. }
  48. void MultipleViewports::Start()
  49. {
  50. // Execute base class startup
  51. Sample::Start();
  52. // Create the scene content
  53. CreateScene();
  54. // Create the UI content
  55. CreateInstructions();
  56. // Setup the viewports for displaying the scene
  57. SetupViewports();
  58. // Hook up to the frame update and render post-update events
  59. SubscribeToEvents();
  60. // Set the mouse mode to use in the sample
  61. Sample::InitMouseMode(MM_ABSOLUTE);
  62. }
  63. void MultipleViewports::CreateScene()
  64. {
  65. ResourceCache* cache = GetSubsystem<ResourceCache>();
  66. scene_ = new Scene(context_);
  67. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  68. // Also create a DebugRenderer component so that we can draw debug geometry
  69. scene_->CreateComponent<Octree>();
  70. scene_->CreateComponent<DebugRenderer>();
  71. // Create scene node & StaticModel component for showing a static plane
  72. Node* planeNode = scene_->CreateChild("Plane");
  73. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  74. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  75. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  76. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  77. // Create a Zone component for ambient lighting & fog control
  78. Node* zoneNode = scene_->CreateChild("Zone");
  79. Zone* zone = zoneNode->CreateComponent<Zone>();
  80. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  81. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  82. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  83. zone->SetFogStart(100.0f);
  84. zone->SetFogEnd(300.0f);
  85. // Create a directional light to the world. Enable cascaded shadows on it
  86. Node* lightNode = scene_->CreateChild("DirectionalLight");
  87. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  88. Light* light = lightNode->CreateComponent<Light>();
  89. light->SetLightType(LIGHT_DIRECTIONAL);
  90. light->SetCastShadows(true);
  91. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  92. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  93. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  94. // Create some mushrooms
  95. const unsigned NUM_MUSHROOMS = 240;
  96. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  97. {
  98. Node* mushroomNode = scene_->CreateChild("Mushroom");
  99. mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  100. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  101. mushroomNode->SetScale(0.5f + Random(2.0f));
  102. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  103. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  104. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  105. mushroomObject->SetCastShadows(true);
  106. }
  107. // Create randomly sized boxes. If boxes are big enough, make them occluders
  108. const unsigned NUM_BOXES = 20;
  109. for (unsigned i = 0; i < NUM_BOXES; ++i)
  110. {
  111. Node* boxNode = scene_->CreateChild("Box");
  112. float size = 1.0f + Random(10.0f);
  113. boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
  114. boxNode->SetScale(size);
  115. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  116. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  117. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  118. boxObject->SetCastShadows(true);
  119. if (size >= 3.0f)
  120. boxObject->SetOccluder(true);
  121. }
  122. // Create the cameras. Limit far clip distance to match the fog
  123. cameraNode_ = scene_->CreateChild("Camera");
  124. Camera* camera = cameraNode_->CreateComponent<Camera>();
  125. camera->SetFarClip(300.0f);
  126. // Parent the rear camera node to the front camera node and turn it 180 degrees to face backward
  127. // Here, we use the angle-axis constructor for Quaternion instead of the usual Euler angles
  128. rearCameraNode_ = cameraNode_->CreateChild("RearCamera");
  129. rearCameraNode_->Rotate(Quaternion(180.0f, Vector3::UP));
  130. Camera* rearCamera = rearCameraNode_->CreateComponent<Camera>();
  131. rearCamera->SetFarClip(300.0f);
  132. // Because the rear viewport is rather small, disable occlusion culling from it. Use the camera's
  133. // "view override flags" for this. We could also disable eg. shadows or force low material quality
  134. // if we wanted
  135. rearCamera->SetViewOverrideFlags(VO_DISABLE_OCCLUSION);
  136. // Set an initial position for the front camera scene node above the plane
  137. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  138. }
  139. void MultipleViewports::CreateInstructions()
  140. {
  141. SimpleCreateInstructions (
  142. "Use WASD keys and mouse/touch to move\n"
  143. "B to toggle bloom, F to toggle FXAA\n"
  144. "Space to toggle debug geometry\n"
  145. );
  146. }
  147. void MultipleViewports::SetupViewports()
  148. {
  149. Graphics* graphics = GetSubsystem<Graphics>();
  150. Renderer* renderer = GetSubsystem<Renderer>();
  151. renderer->SetNumViewports(2);
  152. // Set up the front camera viewport
  153. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  154. renderer->SetViewport(0, viewport);
  155. // Clone the default render path so that we do not interfere with the other viewport, then add
  156. // bloom and FXAA post process effects to the front viewport. Render path commands can be tagged
  157. // for example with the effect name to allow easy toggling on and off. We start with the effects
  158. // disabled.
  159. ResourceCache* cache = GetSubsystem<ResourceCache>();
  160. SharedPtr<RenderPath> effectRenderPath = viewport->GetRenderPath()->Clone();
  161. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/Bloom.xml"));
  162. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/FXAA2.xml"));
  163. // Make the bloom mixing parameter more pronounced
  164. effectRenderPath->SetShaderParameter("BloomMix", Vector2(0.9f, 0.6f));
  165. effectRenderPath->SetEnabled("Bloom", false);
  166. effectRenderPath->SetEnabled("FXAA2", false);
  167. viewport->SetRenderPath(effectRenderPath);
  168. // Set up the rear camera viewport on top of the front view ("rear view mirror")
  169. // The viewport index must be greater in that case, otherwise the view would be left behind
  170. SharedPtr<Viewport> rearViewport(new Viewport(context_, scene_, rearCameraNode_->GetComponent<Camera>(),
  171. IntRect(graphics->GetWidth() * 2 / 3, 32, graphics->GetWidth() - 32, graphics->GetHeight() / 3)));
  172. renderer->SetViewport(1, rearViewport);
  173. }
  174. void MultipleViewports::SubscribeToEvents()
  175. {
  176. // Subscribe HandleUpdate() method for processing update events
  177. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(MultipleViewports, HandleUpdate));
  178. // Subscribe HandlePostRenderUpdate() method for processing the post-render update event, during which we request
  179. // debug geometry
  180. SubscribeToEvent(E_POSTRENDERUPDATE, ATOMIC_HANDLER(MultipleViewports, HandlePostRenderUpdate));
  181. }
  182. void MultipleViewports::MoveCamera(float timeStep)
  183. {
  184. Input* input = GetSubsystem<Input>();
  185. // Movement speed as world units per second
  186. const float MOVE_SPEED = 20.0f;
  187. // Mouse sensitivity as degrees per pixel
  188. const float MOUSE_SENSITIVITY = 0.1f;
  189. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  190. IntVector2 mouseMove = input->GetMouseMove();
  191. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  192. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  193. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  194. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  195. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  196. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  197. if (input->GetKeyDown(KEY_W))
  198. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  199. if (input->GetKeyDown(KEY_S))
  200. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  201. if (input->GetKeyDown(KEY_A))
  202. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  203. if (input->GetKeyDown(KEY_D))
  204. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  205. // Toggle post processing effects on the front viewport. Note that the rear viewport is unaffected
  206. RenderPath* effectRenderPath = GetSubsystem<Renderer>()->GetViewport(0)->GetRenderPath();
  207. if (input->GetKeyPress(KEY_B))
  208. effectRenderPath->ToggleEnabled("Bloom");
  209. if (input->GetKeyPress(KEY_F))
  210. effectRenderPath->ToggleEnabled("FXAA2");
  211. // Toggle debug geometry with space
  212. if (input->GetKeyPress(KEY_SPACE))
  213. drawDebug_ = !drawDebug_;
  214. }
  215. void MultipleViewports::HandleUpdate(StringHash eventType, VariantMap& eventData)
  216. {
  217. using namespace Update;
  218. // Take the frame time step, which is stored as a float
  219. float timeStep = eventData[P_TIMESTEP].GetFloat();
  220. // Move the camera, scale movement with time step
  221. MoveCamera(timeStep);
  222. }
  223. void MultipleViewports::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  224. {
  225. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  226. // bones. Disable depth test so that we can see the effect of occlusion
  227. if (drawDebug_)
  228. GetSubsystem<Renderer>()->DrawDebugGeometry(false);
  229. }