Decals.cpp 13 KB

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