Decals.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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/DecalSet.h>
  28. #include <Atomic/Graphics/Graphics.h>
  29. #include <Atomic/Graphics/Light.h>
  30. #include <Atomic/Graphics/Material.h>
  31. #include <Atomic/Graphics/Model.h>
  32. #include <Atomic/Graphics/Octree.h>
  33. #include <Atomic/Graphics/Renderer.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/Scene/Scene.h>
  39. #include <Atomic/UI/UI.h>
  40. #include "Decals.h"
  41. #include <Atomic/DebugNew.h>
  42. Decals::Decals(Context* context) :
  43. Sample(context),
  44. drawDebug_(false)
  45. {
  46. }
  47. void Decals::Start()
  48. {
  49. // Execute base class startup
  50. Sample::Start();
  51. // Create the scene content
  52. CreateScene();
  53. // Create the UI content
  54. CreateUI();
  55. // Setup the viewport for displaying the scene
  56. SetupViewport();
  57. // Hook up to the frame update and render post-update events
  58. SubscribeToEvents();
  59. }
  60. void Decals::CreateScene()
  61. {
  62. ResourceCache* cache = GetSubsystem<ResourceCache>();
  63. scene_ = new Scene(context_);
  64. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  65. // Also create a DebugRenderer component so that we can draw debug geometry
  66. scene_->CreateComponent<Octree>();
  67. scene_->CreateComponent<DebugRenderer>();
  68. // Create scene node & StaticModel component for showing a static plane
  69. Node* planeNode = scene_->CreateChild("Plane");
  70. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  71. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  72. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  73. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  74. // Create a Zone component for ambient lighting & fog control
  75. Node* zoneNode = scene_->CreateChild("Zone");
  76. Zone* zone = zoneNode->CreateComponent<Zone>();
  77. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  78. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  79. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  80. zone->SetFogStart(100.0f);
  81. zone->SetFogEnd(300.0f);
  82. // Create a directional light to the world. Enable cascaded shadows on it
  83. Node* lightNode = scene_->CreateChild("DirectionalLight");
  84. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  85. Light* light = lightNode->CreateComponent<Light>();
  86. light->SetLightType(LIGHT_DIRECTIONAL);
  87. light->SetCastShadows(true);
  88. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  89. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  90. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  91. // Create some mushrooms
  92. const unsigned NUM_MUSHROOMS = 240;
  93. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  94. {
  95. Node* mushroomNode = scene_->CreateChild("Mushroom");
  96. mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  97. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  98. mushroomNode->SetScale(0.5f + Random(2.0f));
  99. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  100. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  101. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  102. mushroomObject->SetCastShadows(true);
  103. }
  104. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  105. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  106. const unsigned NUM_BOXES = 20;
  107. for (unsigned i = 0; i < NUM_BOXES; ++i)
  108. {
  109. Node* boxNode = scene_->CreateChild("Box");
  110. float size = 1.0f + Random(10.0f);
  111. boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
  112. boxNode->SetScale(size);
  113. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  114. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  115. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  116. boxObject->SetCastShadows(true);
  117. if (size >= 3.0f)
  118. boxObject->SetOccluder(true);
  119. }
  120. // Create the camera. Limit far clip distance to match the fog
  121. cameraNode_ = scene_->CreateChild("Camera");
  122. Camera* camera = cameraNode_->CreateComponent<Camera>();
  123. camera->SetFarClip(300.0f);
  124. // Set an initial position for the camera scene node above the plane
  125. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  126. }
  127. void Decals::CreateUI()
  128. {
  129. SimpleCreateInstructions (
  130. "Use WASD keys to move\n"
  131. "LMB to paint decals, RMB to rotate view\n"
  132. "Space to toggle debug geometry\n"
  133. "7 to toggle occlusion culling"
  134. );
  135. }
  136. void Decals::SetupViewport()
  137. {
  138. Renderer* renderer = GetSubsystem<Renderer>();
  139. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  140. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  141. renderer->SetViewport(0, viewport);
  142. }
  143. void Decals::SubscribeToEvents()
  144. {
  145. // Subscribe HandleUpdate() function for processing update events
  146. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(Decals, HandleUpdate));
  147. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  148. // debug geometry
  149. SubscribeToEvent(E_POSTRENDERUPDATE, ATOMIC_HANDLER(Decals, HandlePostRenderUpdate));
  150. }
  151. void Decals::MoveCamera(float timeStep)
  152. {
  153. // Right mouse button controls mouse cursor visibility: hide when pressed
  154. UI* ui = GetSubsystem<UI>();
  155. Input* input = GetSubsystem<Input>();
  156. // Movement speed as world units per second
  157. const float MOVE_SPEED = 20.0f;
  158. // Mouse sensitivity as degrees per pixel
  159. const float MOUSE_SENSITIVITY = 0.1f;
  160. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  161. // Only move the camera when the cursor is hidden
  162. if (input->GetMouseButtonDown(MOUSEB_RIGHT))
  163. {
  164. IntVector2 mouseMove = input->GetMouseMove();
  165. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  166. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  167. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  168. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  169. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  170. }
  171. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  172. if (input->GetKeyDown(KEY_W))
  173. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  174. if (input->GetKeyDown(KEY_S))
  175. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  176. if (input->GetKeyDown(KEY_A))
  177. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  178. if (input->GetKeyDown(KEY_D))
  179. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  180. // Toggle debug geometry with space
  181. if (input->GetKeyPress(KEY_SPACE))
  182. drawDebug_ = !drawDebug_;
  183. // Paint decal with the left mousebutton; cursor must be visible
  184. if (input->IsMouseVisible() && input->GetMouseButtonPress(MOUSEB_LEFT))
  185. PaintDecal();
  186. }
  187. void Decals::PaintDecal()
  188. {
  189. Vector3 hitPos;
  190. Drawable* hitDrawable;
  191. if (Raycast(250.0f, hitPos, hitDrawable))
  192. {
  193. // Check if target scene node already has a DecalSet component. If not, create now
  194. Node* targetNode = hitDrawable->GetNode();
  195. DecalSet* decal = targetNode->GetComponent<DecalSet>();
  196. if (!decal)
  197. {
  198. ResourceCache* cache = GetSubsystem<ResourceCache>();
  199. decal = targetNode->CreateComponent<DecalSet>();
  200. decal->SetMaterial(cache->GetResource<Material>("Materials/UrhoDecal.xml"));
  201. }
  202. // Add a square decal to the decal set using the geometry of the drawable that was hit, orient it to face the camera,
  203. // use full texture UV's (0,0) to (1,1). Note that if we create several decals to a large object (such as the ground
  204. // plane) over a large area using just one DecalSet component, the decals will all be culled as one unit. If that is
  205. // undesirable, it may be necessary to create more than one DecalSet based on the distance
  206. decal->AddDecal(hitDrawable, hitPos, cameraNode_->GetRotation(), 0.5f, 1.0f, 1.0f, Vector2::ZERO,
  207. Vector2::ONE);
  208. }
  209. }
  210. bool Decals::Raycast(float maxDistance, Vector3& hitPos, Drawable*& hitDrawable)
  211. {
  212. hitDrawable = 0;
  213. Input* input = GetSubsystem<Input>();
  214. IntVector2 pos = input->GetMousePosition();
  215. // Check the cursor is visible and there is no UI element in front of the cursor
  216. if (!input->IsMouseVisible())
  217. return false;
  218. Graphics* graphics = GetSubsystem<Graphics>();
  219. Camera* camera = cameraNode_->GetComponent<Camera>();
  220. Ray cameraRay = camera->GetScreenRay((float)pos.x_ / graphics->GetWidth(), (float)pos.y_ / graphics->GetHeight());
  221. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  222. PODVector<RayQueryResult> results;
  223. RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  224. scene_->GetComponent<Octree>()->RaycastSingle(query);
  225. if (results.Size())
  226. {
  227. RayQueryResult& result = results[0];
  228. hitPos = result.position_;
  229. hitDrawable = result.drawable_;
  230. return true;
  231. }
  232. return false;
  233. }
  234. void Decals::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. }
  242. void Decals::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  243. {
  244. // If draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion
  245. if (drawDebug_)
  246. GetSubsystem<Renderer>()->DrawDebugGeometry(false);
  247. }