MultipleViewports.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. //
  2. // Copyright (c) 2008-2013 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 "Camera.h"
  23. #include "CoreEvents.h"
  24. #include "Cursor.h"
  25. #include "DebugRenderer.h"
  26. #include "Engine.h"
  27. #include "Font.h"
  28. #include "Graphics.h"
  29. #include "Input.h"
  30. #include "Light.h"
  31. #include "Material.h"
  32. #include "Model.h"
  33. #include "Octree.h"
  34. #include "Renderer.h"
  35. #include "RenderPath.h"
  36. #include "ResourceCache.h"
  37. #include "Scene.h"
  38. #include "StaticModel.h"
  39. #include "Text.h"
  40. #include "UI.h"
  41. #include "XMLFile.h"
  42. #include "Zone.h"
  43. #include "MultipleViewports.h"
  44. #include "DebugNew.h"
  45. DEFINE_APPLICATION_MAIN(MultipleViewports)
  46. MultipleViewports::MultipleViewports(Context* context) :
  47. Sample(context),
  48. yaw_(0.0f),
  49. pitch_(0.0f),
  50. drawDebug_(false)
  51. {
  52. }
  53. void MultipleViewports::Start()
  54. {
  55. // Execute base class startup
  56. Sample::Start();
  57. // Create the scene content
  58. CreateScene();
  59. // Create the UI content
  60. CreateInstructions();
  61. // Setup the viewports for displaying the scene
  62. SetupViewports();
  63. // Hook up to the frame update and render post-update events
  64. SubscribeToEvents();
  65. }
  66. void MultipleViewports::CreateScene()
  67. {
  68. ResourceCache* cache = GetSubsystem<ResourceCache>();
  69. scene_ = new Scene(context_);
  70. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  71. // Also create a DebugRenderer component so that we can draw debug geometry
  72. scene_->CreateComponent<Octree>();
  73. scene_->CreateComponent<DebugRenderer>();
  74. // Create scene node & StaticModel component for showing a static plane
  75. Node* planeNode = scene_->CreateChild("Plane");
  76. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  77. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  78. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  79. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  80. // Create a Zone component for ambient lighting & fog control
  81. Node* zoneNode = scene_->CreateChild("Zone");
  82. Zone* zone = zoneNode->CreateComponent<Zone>();
  83. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  84. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  85. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  86. zone->SetFogStart(100.0f);
  87. zone->SetFogEnd(300.0f);
  88. // Create a directional light to the world. Enable cascaded shadows on it
  89. Node* lightNode = scene_->CreateChild("DirectionalLight");
  90. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  91. Light* light = lightNode->CreateComponent<Light>();
  92. light->SetLightType(LIGHT_DIRECTIONAL);
  93. light->SetCastShadows(true);
  94. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  95. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  96. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  97. // Create some mushrooms
  98. const unsigned NUM_MUSHROOMS = 240;
  99. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  100. {
  101. Node* mushroomNode = scene_->CreateChild("Mushroom");
  102. mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  103. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  104. mushroomNode->SetScale(0.5f + Random(2.0f));
  105. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  106. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  107. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  108. mushroomObject->SetCastShadows(true);
  109. }
  110. // Create randomly sized boxes. If boxes are big enough, make them occluders
  111. const unsigned NUM_BOXES = 20;
  112. for (unsigned i = 0; i < NUM_BOXES; ++i)
  113. {
  114. Node* boxNode = scene_->CreateChild("Box");
  115. float size = 1.0f + Random(10.0f);
  116. boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
  117. boxNode->SetScale(size);
  118. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  119. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  120. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  121. boxObject->SetCastShadows(true);
  122. if (size >= 3.0f)
  123. boxObject->SetOccluder(true);
  124. }
  125. // Create the cameras. Limit far clip distance to match the fog
  126. cameraNode_ = scene_->CreateChild("Camera");
  127. Camera* camera = cameraNode_->CreateComponent<Camera>();
  128. camera->SetFarClip(300.0f);
  129. // Parent the rear camera node to the front camera node and turn it 180 degrees to face backward
  130. // Here, we use the angle-axis constructor for Quaternion instead of the usual Euler angles
  131. rearCameraNode_ = cameraNode_->CreateChild("RearCamera");
  132. rearCameraNode_->Rotate(Quaternion(180.0f, Vector3::UP));
  133. Camera* rearCamera = rearCameraNode_->CreateComponent<Camera>();
  134. rearCamera->SetFarClip(300.0f);
  135. // Because the rear viewport is rather small, disable occlusion culling from it. Use the camera's
  136. // "view override flags" for this. We could also disable eg. shadows or force low material quality
  137. // if we wanted
  138. rearCamera->SetViewOverrideFlags(VO_DISABLE_OCCLUSION);
  139. // Set an initial position for the front camera scene node above the plane
  140. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  141. }
  142. void MultipleViewports::CreateInstructions()
  143. {
  144. ResourceCache* cache = GetSubsystem<ResourceCache>();
  145. UI* ui = GetSubsystem<UI>();
  146. // Construct new Text object, set string to display and font to use
  147. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  148. instructionText->SetText(
  149. "Use WASD keys and mouse to move\n"
  150. "B to toggle bloom, F to toggle FXAA\n"
  151. "Space to toggle debug geometry\n"
  152. );
  153. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  154. // The text has multiple rows. Center them in relation to each other
  155. instructionText->SetTextAlignment(HA_CENTER);
  156. // Position the text relative to the screen center
  157. instructionText->SetHorizontalAlignment(HA_CENTER);
  158. instructionText->SetVerticalAlignment(VA_CENTER);
  159. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  160. }
  161. void MultipleViewports::SetupViewports()
  162. {
  163. Graphics* graphics = GetSubsystem<Graphics>();
  164. Renderer* renderer = GetSubsystem<Renderer>();
  165. renderer->SetNumViewports(2);
  166. // Set up the front camera viewport
  167. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  168. renderer->SetViewport(0, viewport);
  169. // Clone the default render path so that we do not interfere with the other viewport, then add
  170. // bloom and FXAA post process effects to the front viewport. Render path commands can be tagged
  171. // for example with the effect name to allow easy toggling on and off. We start with the effects
  172. // disabled.
  173. ResourceCache* cache = GetSubsystem<ResourceCache>();
  174. SharedPtr<RenderPath> effectRenderPath = viewport->GetRenderPath()->Clone();
  175. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/Bloom.xml"));
  176. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/EdgeFilter.xml"));
  177. // Make the bloom mixing parameter more pronounced
  178. effectRenderPath->SetShaderParameter("BloomMix", Vector2(0.9f, 0.6f));
  179. effectRenderPath->SetEnabled("Bloom", false);
  180. effectRenderPath->SetEnabled("EdgeFilter", false);
  181. viewport->SetRenderPath(effectRenderPath);
  182. // Set up the rear camera viewport on top of the front view ("rear view mirror")
  183. // The viewport index must be greater in that case, otherwise the view would be left behind
  184. SharedPtr<Viewport> rearViewport(new Viewport(context_, scene_, rearCameraNode_->GetComponent<Camera>(),
  185. IntRect(graphics->GetWidth() * 2 / 3, 32, graphics->GetWidth() - 32, graphics->GetHeight() / 3)));
  186. renderer->SetViewport(1, rearViewport);
  187. }
  188. void MultipleViewports::SubscribeToEvents()
  189. {
  190. // Subscribe HandleUpdate() method for processing update events
  191. SubscribeToEvent(E_UPDATE, HANDLER(MultipleViewports, HandleUpdate));
  192. // Subscribe HandlePostRenderUpdate() method for processing the post-render update event, during which we request
  193. // debug geometry
  194. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(MultipleViewports, HandlePostRenderUpdate));
  195. }
  196. void MultipleViewports::MoveCamera(float timeStep)
  197. {
  198. // Do not move if the UI has a focused element (the console)
  199. if (GetSubsystem<UI>()->GetFocusElement())
  200. return;
  201. Input* input = GetSubsystem<Input>();
  202. // Movement speed as world units per second
  203. const float MOVE_SPEED = 20.0f;
  204. // Mouse sensitivity as degrees per pixel
  205. const float MOUSE_SENSITIVITY = 0.1f;
  206. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  207. IntVector2 mouseMove = input->GetMouseMove();
  208. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  209. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  210. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  211. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  212. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  213. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  214. if (input->GetKeyDown('W'))
  215. cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);
  216. if (input->GetKeyDown('S'))
  217. cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);
  218. if (input->GetKeyDown('A'))
  219. cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);
  220. if (input->GetKeyDown('D'))
  221. cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);
  222. // Toggle post processing effects on the front viewport. Note that the rear viewport is unaffected
  223. RenderPath* effectRenderPath = GetSubsystem<Renderer>()->GetViewport(0)->GetRenderPath();
  224. if (input->GetKeyPress('B'))
  225. effectRenderPath->ToggleEnabled("Bloom");
  226. if (input->GetKeyPress('F'))
  227. effectRenderPath->ToggleEnabled("EdgeFilter");
  228. // Toggle debug geometry with space
  229. if (input->GetKeyPress(KEY_SPACE))
  230. drawDebug_ = !drawDebug_;
  231. }
  232. void MultipleViewports::HandleUpdate(StringHash eventType, VariantMap& eventData)
  233. {
  234. using namespace Update;
  235. // Take the frame time step, which is stored as a float
  236. float timeStep = eventData[P_TIMESTEP].GetFloat();
  237. // Move the camera, scale movement with time step
  238. MoveCamera(timeStep);
  239. }
  240. void MultipleViewports::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  241. {
  242. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  243. // bones. Disable depth test so that we can see the effect of occlusion
  244. if (drawDebug_)
  245. GetSubsystem<Renderer>()->DrawDebugGeometry(true);
  246. }