Water.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //
  2. // Copyright (c) 2008-2017 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/Core/CoreEvents.h>
  23. #include <Urho3D/Engine/Engine.h>
  24. #include <Urho3D/Graphics/Camera.h>
  25. #include <Urho3D/Graphics/Graphics.h>
  26. #include <Urho3D/Graphics/Light.h>
  27. #include <Urho3D/Graphics/Material.h>
  28. #include <Urho3D/Graphics/Model.h>
  29. #include <Urho3D/Graphics/Octree.h>
  30. #include <Urho3D/Graphics/Renderer.h>
  31. #include <Urho3D/Graphics/RenderSurface.h>
  32. #include <Urho3D/Graphics/Skybox.h>
  33. #include <Urho3D/Graphics/Terrain.h>
  34. #include <Urho3D/Graphics/Texture2D.h>
  35. #include <Urho3D/Graphics/Zone.h>
  36. #include <Urho3D/Input/Input.h>
  37. #include <Urho3D/IO/File.h>
  38. #include <Urho3D/IO/FileSystem.h>
  39. #include <Urho3D/Resource/ResourceCache.h>
  40. #include <Urho3D/Scene/Scene.h>
  41. #include <Urho3D/UI/Font.h>
  42. #include <Urho3D/UI/Text.h>
  43. #include <Urho3D/UI/UI.h>
  44. #include "Water.h"
  45. #include <Urho3D/DebugNew.h>
  46. URHO3D_DEFINE_APPLICATION_MAIN(Water)
  47. Water::Water(Context* context) :
  48. Sample(context)
  49. {
  50. }
  51. void Water::Start()
  52. {
  53. // Execute base class startup
  54. Sample::Start();
  55. // Create the scene content
  56. CreateScene();
  57. // Create the UI content
  58. CreateInstructions();
  59. // Setup the viewport for displaying the scene
  60. SetupViewport();
  61. // Hook up to the frame update event
  62. SubscribeToEvents();
  63. // Set the mouse mode to use in the sample
  64. Sample::InitMouseMode(MM_RELATIVE);
  65. }
  66. void Water::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. scene_->CreateComponent<Octree>();
  72. // Create a Zone component for ambient lighting & fog control
  73. Node* zoneNode = scene_->CreateChild("Zone");
  74. Zone* zone = zoneNode->CreateComponent<Zone>();
  75. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  76. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  77. zone->SetFogColor(Color(1.0f, 1.0f, 1.0f));
  78. zone->SetFogStart(500.0f);
  79. zone->SetFogEnd(750.0f);
  80. // Create a directional light to the world. Enable cascaded shadows on it
  81. Node* lightNode = scene_->CreateChild("DirectionalLight");
  82. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  83. Light* light = lightNode->CreateComponent<Light>();
  84. light->SetLightType(LIGHT_DIRECTIONAL);
  85. light->SetCastShadows(true);
  86. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  87. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  88. light->SetSpecularIntensity(0.5f);
  89. // Apply slightly overbright lighting to match the skybox
  90. light->SetColor(Color(1.2f, 1.2f, 1.2f));
  91. // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  92. // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  93. // generate the necessary 3D texture coordinates for cube mapping
  94. Node* skyNode = scene_->CreateChild("Sky");
  95. skyNode->SetScale(500.0f); // The scale actually does not matter
  96. Skybox* skybox = skyNode->CreateComponent<Skybox>();
  97. skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  98. skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
  99. // Create heightmap terrain
  100. Node* terrainNode = scene_->CreateChild("Terrain");
  101. terrainNode->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
  102. Terrain* terrain = terrainNode->CreateComponent<Terrain>();
  103. terrain->SetPatchSize(64);
  104. terrain->SetSpacing(Vector3(2.0f, 0.5f, 2.0f)); // Spacing between vertices and vertical resolution of the height map
  105. terrain->SetSmoothing(true);
  106. terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png"));
  107. terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
  108. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  109. // terrain patches and other objects behind it
  110. terrain->SetOccluder(true);
  111. // Create 1000 boxes in the terrain. Always face outward along the terrain normal
  112. unsigned NUM_OBJECTS = 1000;
  113. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  114. {
  115. Node* objectNode = scene_->CreateChild("Box");
  116. Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
  117. position.y_ = terrain->GetHeight(position) + 2.25f;
  118. objectNode->SetPosition(position);
  119. // Create a rotation quaternion from up vector to terrain normal
  120. objectNode->SetRotation(Quaternion(Vector3(0.0f, 1.0f, 0.0f), terrain->GetNormal(position)));
  121. objectNode->SetScale(5.0f);
  122. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  123. object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  124. object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  125. object->SetCastShadows(true);
  126. }
  127. // Create a water plane object that is as large as the terrain
  128. waterNode_ = scene_->CreateChild("Water");
  129. waterNode_->SetScale(Vector3(2048.0f, 1.0f, 2048.0f));
  130. waterNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  131. StaticModel* water = waterNode_->CreateComponent<StaticModel>();
  132. water->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  133. water->SetMaterial(cache->GetResource<Material>("Materials/Water.xml"));
  134. // Set a different viewmask on the water plane to be able to hide it from the reflection camera
  135. water->SetViewMask(0x80000000);
  136. // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
  137. // the scene, because we want it to be unaffected by scene load / save
  138. cameraNode_ = new Node(context_);
  139. Camera* camera = cameraNode_->CreateComponent<Camera>();
  140. camera->SetFarClip(750.0f);
  141. // Set an initial position for the camera scene node above the ground
  142. cameraNode_->SetPosition(Vector3(0.0f, 7.0f, -20.0f));
  143. }
  144. void Water::CreateInstructions()
  145. {
  146. ResourceCache* cache = GetSubsystem<ResourceCache>();
  147. UI* ui = GetSubsystem<UI>();
  148. // Construct new Text object, set string to display and font to use
  149. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  150. instructionText->SetText("Use WASD keys and mouse/touch to move");
  151. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  152. instructionText->SetTextAlignment(HA_CENTER);
  153. // Position the text relative to the screen center
  154. instructionText->SetHorizontalAlignment(HA_CENTER);
  155. instructionText->SetVerticalAlignment(VA_CENTER);
  156. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  157. }
  158. void Water::SetupViewport()
  159. {
  160. Graphics* graphics = GetSubsystem<Graphics>();
  161. Renderer* renderer = GetSubsystem<Renderer>();
  162. ResourceCache* cache = GetSubsystem<ResourceCache>();
  163. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  164. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  165. renderer->SetViewport(0, viewport);
  166. // Create a mathematical plane to represent the water in calculations
  167. waterPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition());
  168. // Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping
  169. waterClipPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition() -
  170. Vector3(0.0f, 0.1f, 0.0f));
  171. // Create camera for water reflection
  172. // It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify
  173. // its position when rendering
  174. reflectionCameraNode_ = cameraNode_->CreateChild();
  175. Camera* reflectionCamera = reflectionCameraNode_->CreateComponent<Camera>();
  176. reflectionCamera->SetFarClip(750.0);
  177. reflectionCamera->SetViewMask(0x7fffffff); // Hide objects with only bit 31 in the viewmask (the water plane)
  178. reflectionCamera->SetAutoAspectRatio(false);
  179. reflectionCamera->SetUseReflection(true);
  180. reflectionCamera->SetReflectionPlane(waterPlane_);
  181. reflectionCamera->SetUseClipping(true); // Enable clipping of geometry behind water plane
  182. reflectionCamera->SetClipPlane(waterClipPlane_);
  183. // The water reflection texture is rectangular. Set reflection camera aspect ratio to match
  184. reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());
  185. // View override flags could be used to optimize reflection rendering. For example disable shadows
  186. //reflectionCamera->SetViewOverrideFlags(VO_DISABLE_SHADOWS);
  187. // Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse
  188. // texture unit of the water material
  189. int texSize = 1024;
  190. SharedPtr<Texture2D> renderTexture(new Texture2D(context_));
  191. renderTexture->SetSize(texSize, texSize, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
  192. renderTexture->SetFilterMode(FILTER_BILINEAR);
  193. RenderSurface* surface = renderTexture->GetRenderSurface();
  194. SharedPtr<Viewport> rttViewport(new Viewport(context_, scene_, reflectionCamera));
  195. surface->SetViewport(0, rttViewport);
  196. Material* waterMat = cache->GetResource<Material>("Materials/Water.xml");
  197. waterMat->SetTexture(TU_DIFFUSE, renderTexture);
  198. }
  199. void Water::SubscribeToEvents()
  200. {
  201. // Subscribe HandleUpdate() function for processing update events
  202. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Water, HandleUpdate));
  203. }
  204. void Water::MoveCamera(float timeStep)
  205. {
  206. // Do not move if the UI has a focused element (the console)
  207. if (GetSubsystem<UI>()->GetFocusElement())
  208. return;
  209. Input* input = GetSubsystem<Input>();
  210. // Movement speed as world units per second
  211. const float MOVE_SPEED = 20.0f;
  212. // Mouse sensitivity as degrees per pixel
  213. const float MOUSE_SENSITIVITY = 0.1f;
  214. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  215. IntVector2 mouseMove = input->GetMouseMove();
  216. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  217. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  218. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  219. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  220. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  221. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  222. if (input->GetKeyDown(KEY_W))
  223. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  224. if (input->GetKeyDown(KEY_S))
  225. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  226. if (input->GetKeyDown(KEY_A))
  227. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  228. if (input->GetKeyDown(KEY_D))
  229. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  230. // In case resolution has changed, adjust the reflection camera aspect ratio
  231. Graphics* graphics = GetSubsystem<Graphics>();
  232. Camera* reflectionCamera = reflectionCameraNode_->GetComponent<Camera>();
  233. reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());
  234. }
  235. void Water::HandleUpdate(StringHash eventType, VariantMap& eventData)
  236. {
  237. using namespace Update;
  238. // Take the frame time step, which is stored as a float
  239. float timeStep = eventData[P_TIMESTEP].GetFloat();
  240. // Move the camera, scale movement with time step
  241. MoveCamera(timeStep);
  242. }