Decals.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 "DecalSet.h"
  27. #include "Engine.h"
  28. #include "Font.h"
  29. #include "Graphics.h"
  30. #include "Input.h"
  31. #include "Light.h"
  32. #include "Material.h"
  33. #include "Model.h"
  34. #include "Octree.h"
  35. #include "Renderer.h"
  36. #include "ResourceCache.h"
  37. #include "StaticModel.h"
  38. #include "Text.h"
  39. #include "UI.h"
  40. #include "XMLFile.h"
  41. #include "Zone.h"
  42. #include "Decals.h"
  43. #include "DebugNew.h"
  44. // Expands to this example's entry-point
  45. DEFINE_APPLICATION_MAIN(Decals)
  46. Decals::Decals(Context* context) :
  47. Sample(context),
  48. yaw_(0.0f),
  49. pitch_(0.0f),
  50. drawDebug_(false)
  51. {
  52. }
  53. void Decals::Start()
  54. {
  55. // Execute base class startup
  56. Sample::Start();
  57. // Create the scene content
  58. CreateScene();
  59. // Create the UI content
  60. CreateUI();
  61. // Setup the viewport for displaying the scene
  62. SetupViewport();
  63. // Hook up to the frame update and render post-update events
  64. SubscribeToEvents();
  65. }
  66. void Decals::CreateScene()
  67. {
  68. ResourceCache* cache = GetSubsystem<ResourceCache>();
  69. scene_ = new Scene(context_);
  70. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  71. // (-1000, -1000, -1000) to (1000, 1000, 1000). Also create a DebugRenderer component so that we can draw
  72. // debug geometry
  73. scene_->CreateComponent<Octree>();
  74. scene_->CreateComponent<DebugRenderer>();
  75. // Create scene node & StaticModel component for showing a static plane
  76. Node* planeNode = scene_->CreateChild("Plane");
  77. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  78. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  79. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  80. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  81. // Create a Zone component for ambient lighting & fog color control
  82. Node* zoneNode = scene_->CreateChild("Zone");
  83. Zone* zone = zoneNode->CreateComponent<Zone>();
  84. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  85. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  86. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  87. zone->SetFogStart(100.0f);
  88. zone->SetFogEnd(300.0f);
  89. // Create a directional light to the world. Enable cascaded shadows on it
  90. Node* lightNode = scene_->CreateChild("Directional light");
  91. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  92. Light* light = lightNode->CreateComponent<Light>();
  93. light->SetLightType(LIGHT_DIRECTIONAL);
  94. light->SetCastShadows(true);
  95. light->SetShadowBias(BiasParameters(0.0001f, 0.5f));
  96. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  97. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  98. // Create some mushrooms
  99. const unsigned NUM_MUSHROOMS = 240;
  100. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  101. {
  102. Node* mushroomNode = scene_->CreateChild("Mushroom");
  103. mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  104. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  105. mushroomNode->SetScale(0.5f + Random(2.0f));
  106. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  107. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  108. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  109. mushroomObject->SetCastShadows(true);
  110. }
  111. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  112. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  113. const unsigned NUM_BOXES = 20;
  114. for (unsigned i = 0; i < NUM_BOXES; ++i)
  115. {
  116. Node* boxNode = scene_->CreateChild("Box");
  117. float size = 1.0f + Random(10.0f);
  118. boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
  119. boxNode->SetScale(size);
  120. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  121. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  122. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  123. boxObject->SetCastShadows(true);
  124. if (size >= 5.0f)
  125. boxObject->SetOccluder(true);
  126. }
  127. // Create the camera. Limit far clip distance to match the fog
  128. cameraNode_ = scene_->CreateChild("Camera");
  129. Camera* camera = cameraNode_->CreateComponent<Camera>();
  130. camera->SetFarClip(300.0f);
  131. // Set an initial position for the camera scene node above the plane
  132. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  133. }
  134. void Decals::CreateUI()
  135. {
  136. ResourceCache* cache = GetSubsystem<ResourceCache>();
  137. UI* ui = GetSubsystem<UI>();
  138. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  139. // control the camera, and when visible, it will point the raycast target
  140. XMLFile* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  141. SharedPtr<Cursor> cursor(new Cursor(context_));
  142. cursor->SetStyleAuto(style);
  143. ui->SetCursor(cursor);
  144. // Set starting position of the cursor at the rendering window center
  145. Graphics* graphics = GetSubsystem<Graphics>();
  146. cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
  147. // Construct new Text object, set string to display and font to use
  148. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  149. instructionText->SetText(
  150. "Use WASD keys to move\n"
  151. "LMB = paint decal, RMB = rotate view\n"
  152. "Space to toggle debug geometry\n"
  153. "7 to toggle occlusion culling"
  154. );
  155. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  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 Decals::SetupViewport()
  162. {
  163. Renderer* renderer = GetSubsystem<Renderer>();
  164. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  165. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  166. renderer->SetViewport(0, viewport);
  167. }
  168. void Decals::MoveCamera(float timeStep)
  169. {
  170. // Right mouse button controls mouse cursor visibility: hide when pressed
  171. UI* ui = GetSubsystem<UI>();
  172. Input* input = GetSubsystem<Input>();
  173. ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
  174. // Do not move if the UI has a focused element (the console)
  175. if (ui->GetFocusElement())
  176. return;
  177. // Movement speed as world units per second
  178. const float MOVE_SPEED = 20.0f;
  179. // Mouse sensitivity as degrees per pixel
  180. const float MOUSE_SENSITIVITY = 0.1f;
  181. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  182. // Only move the camera when the cursor is hidden
  183. if (!ui->GetCursor()->IsVisible())
  184. {
  185. IntVector2 mouseMove = input->GetMouseMove();
  186. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  187. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  188. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  189. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  190. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  191. }
  192. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  193. if (input->GetKeyDown('W'))
  194. cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);
  195. if (input->GetKeyDown('S'))
  196. cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);
  197. if (input->GetKeyDown('A'))
  198. cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);
  199. if (input->GetKeyDown('D'))
  200. cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);
  201. // Toggle debug geometry with space
  202. if (input->GetKeyPress(KEY_SPACE))
  203. drawDebug_ = !drawDebug_;
  204. // Paint decal with the left mousebutton; cursor must be visible
  205. if (ui->GetCursor()->IsVisible() && input->GetMouseButtonPress(MOUSEB_LEFT))
  206. PaintDecal();
  207. }
  208. void Decals::PaintDecal()
  209. {
  210. UI* ui = GetSubsystem<UI>();
  211. Graphics* graphics = GetSubsystem<Graphics>();
  212. IntVector2 pos = ui->GetCursorPosition();
  213. // Make sure no UI element in front of the cursor
  214. if (ui->GetElementAt(pos, true))
  215. return;
  216. Camera* camera = cameraNode_->GetComponent<Camera>();
  217. Ray cameraRay = camera->GetScreenRay((float)pos.x_ / graphics->GetWidth(), (float)pos.y_ / graphics->GetHeight());
  218. // Raycast up to 250 world units distance, pick only geometry objects, not eg. zones or lights, only get the first
  219. // (closest) hit
  220. PODVector<RayQueryResult> results;
  221. RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, 250.0f, DRAWABLE_GEOMETRY);
  222. scene_->GetComponent<Octree>()->RaycastSingle(query);
  223. if (results.Size())
  224. {
  225. RayQueryResult& result = results[0];
  226. // Calculate hit position in world space
  227. Vector3 rayHitPos = cameraRay.origin_ + cameraRay.direction_ * result.distance_;
  228. // Check if target scene node already has a DecalSet component. If not, create now
  229. Node* targetNode = result.drawable_->GetNode();
  230. DecalSet* decal = targetNode->GetComponent<DecalSet>();
  231. if (!decal)
  232. {
  233. ResourceCache* cache = GetSubsystem<ResourceCache>();
  234. decal = targetNode->CreateComponent<DecalSet>();
  235. decal->SetMaterial(cache->GetResource<Material>("Materials/UrhoDecal.xml"));
  236. }
  237. // Add a square decal to the decal set using the geometry of the drawable that was hit, orient it to face the camera,
  238. // 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
  239. // plane) over a large area using just one DecalSet component, the decals will all be culled as one unit. If that is
  240. // undesirable, it may be necessary to create more than one DecalSet based on the distance
  241. decal->AddDecal(result.drawable_, rayHitPos, cameraNode_->GetWorldRotation(), 0.5f, 1.0f, 1.0f, Vector2::ZERO,
  242. Vector2::ONE);
  243. }
  244. }
  245. void Decals::SubscribeToEvents()
  246. {
  247. // Subscribes HandleUpdate() method for processing update events
  248. SubscribeToEvent(E_UPDATE, HANDLER(Decals, HandleUpdate));
  249. // Subscribes HandlePostRenderUpdate() method for processing the post-render update event, sent after Renderer subsystem is
  250. // done with defining the draw calls for the viewports (but before actually executing them)
  251. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(Decals, HandlePostRenderUpdate));
  252. }
  253. void Decals::HandleUpdate(StringHash eventType, VariantMap& eventData)
  254. {
  255. // Event parameters are always defined inside a namespace corresponding to the event's name
  256. using namespace Update;
  257. // Take the frame time step, which is stored as a float
  258. float timeStep = eventData[P_TIMESTEP].GetFloat();
  259. // Move the camera, scale movement with time step
  260. MoveCamera(timeStep);
  261. }
  262. void Decals::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  263. {
  264. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  265. // bones. Disable depth test so that we can see the effect of occlusion
  266. if (drawDebug_)
  267. GetSubsystem<Renderer>()->DrawDebugGeometry(false);
  268. }