Water.cpp 12 KB

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