Billboards.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 <Urho3D/Urho3D.h>
  23. #include <Urho3D/Graphics/BillboardSet.h>
  24. #include <Urho3D/Graphics/Camera.h>
  25. #include <Urho3D/Core/CoreEvents.h>
  26. #include <Urho3D/Graphics/DebugRenderer.h>
  27. #include <Urho3D/Engine/Engine.h>
  28. #include <Urho3D/UI/Font.h>
  29. #include <Urho3D/Graphics/Graphics.h>
  30. #include <Urho3D/Input/Input.h>
  31. #include <Urho3D/Graphics/Light.h>
  32. #include <Urho3D/Graphics/Material.h>
  33. #include <Urho3D/Graphics/Model.h>
  34. #include <Urho3D/Graphics/Octree.h>
  35. #include <Urho3D/Graphics/Renderer.h>
  36. #include <Urho3D/Resource/ResourceCache.h>
  37. #include <Urho3D/Scene/Scene.h>
  38. #include <Urho3D/Graphics/StaticModel.h>
  39. #include <Urho3D/UI/Text.h>
  40. #include <Urho3D/UI/UI.h>
  41. #include <Urho3D/Graphics/Zone.h>
  42. #include "Billboards.h"
  43. #include <Urho3D/DebugNew.h>
  44. DEFINE_APPLICATION_MAIN(Billboards)
  45. Billboards::Billboards(Context* context) :
  46. Sample(context),
  47. drawDebug_(false)
  48. {
  49. }
  50. void Billboards::Start()
  51. {
  52. // Execute base class startup
  53. Sample::Start();
  54. // Create the scene content
  55. CreateScene();
  56. // Create the UI content
  57. CreateInstructions();
  58. // Setup the viewport for displaying the scene
  59. SetupViewport();
  60. // Hook up to the frame update and render post-update events
  61. SubscribeToEvents();
  62. }
  63. void Billboards::CreateScene()
  64. {
  65. ResourceCache* cache = GetSubsystem<ResourceCache>();
  66. scene_ = new Scene(context_);
  67. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  68. // Also create a DebugRenderer component so that we can draw debug geometry
  69. scene_->CreateComponent<Octree>();
  70. scene_->CreateComponent<DebugRenderer>();
  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.1f, 0.1f, 0.1f));
  76. zone->SetFogStart(100.0f);
  77. zone->SetFogEnd(300.0f);
  78. // Create a directional light without shadows
  79. Node* lightNode = scene_->CreateChild("DirectionalLight");
  80. lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
  81. Light* light = lightNode->CreateComponent<Light>();
  82. light->SetLightType(LIGHT_DIRECTIONAL);
  83. light->SetColor(Color(0.2f, 0.2f, 0.2f));
  84. light->SetSpecularIntensity(1.0f);
  85. // Create a "floor" consisting of several tiles
  86. for (int y = -5; y <= 5; ++y)
  87. {
  88. for (int x = -5; x <= 5; ++x)
  89. {
  90. Node* floorNode = scene_->CreateChild("FloorTile");
  91. floorNode->SetPosition(Vector3(x * 20.5f, -0.5f, y * 20.5f));
  92. floorNode->SetScale(Vector3(20.0f, 1.0f, 20.f));
  93. StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
  94. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  95. floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  96. }
  97. }
  98. // Create groups of mushrooms, which act as shadow casters
  99. const unsigned NUM_MUSHROOMGROUPS = 25;
  100. const unsigned NUM_MUSHROOMS = 25;
  101. for (unsigned i = 0; i < NUM_MUSHROOMGROUPS; ++i)
  102. {
  103. // First create a scene node for the group. The individual mushrooms nodes will be created as children
  104. Node* groupNode = scene_->CreateChild("MushroomGroup");
  105. groupNode->SetPosition(Vector3(Random(190.0f) - 95.0f, 0.0f, Random(190.0f) - 95.0f));
  106. for (unsigned j = 0; j < NUM_MUSHROOMS; ++j)
  107. {
  108. Node* mushroomNode = groupNode->CreateChild("Mushroom");
  109. mushroomNode->SetPosition(Vector3(Random(25.0f) - 12.5f, 0.0f, Random(25.0f) - 12.5f));
  110. mushroomNode->SetRotation(Quaternion(0.0f, Random() * 360.0f, 0.0f));
  111. mushroomNode->SetScale(1.0f + Random() * 4.0f);
  112. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  113. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  114. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  115. mushroomObject->SetCastShadows(true);
  116. }
  117. }
  118. // Create billboard sets (floating smoke)
  119. const unsigned NUM_BILLBOARDNODES = 25;
  120. const unsigned NUM_BILLBOARDS = 10;
  121. for (unsigned i = 0; i < NUM_BILLBOARDNODES; ++i)
  122. {
  123. Node* smokeNode = scene_->CreateChild("Smoke");
  124. smokeNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(20.0f) + 10.0f, Random(200.0f) - 100.0f));
  125. BillboardSet* billboardObject = smokeNode->CreateComponent<BillboardSet>();
  126. billboardObject->SetNumBillboards(NUM_BILLBOARDS);
  127. billboardObject->SetMaterial(cache->GetResource<Material>("Materials/LitSmoke.xml"));
  128. billboardObject->SetSorted(true);
  129. for (unsigned j = 0; j < NUM_BILLBOARDS; ++j)
  130. {
  131. Billboard* bb = billboardObject->GetBillboard(j);
  132. bb->position_ = Vector3(Random(12.0f) - 6.0f, Random(8.0f) - 4.0f, Random(12.0f) - 6.0f);
  133. bb->size_ = Vector2(Random(2.0f) + 3.0f, Random(2.0f) + 3.0f);
  134. bb->rotation_ = Random() * 360.0f;
  135. bb->enabled_ = true;
  136. }
  137. // After modifying the billboards, they need to be "commited" so that the BillboardSet updates its internals
  138. billboardObject->Commit();
  139. }
  140. // Create shadow casting spotlights
  141. const unsigned NUM_LIGHTS = 9;
  142. for (unsigned i = 0; i < NUM_LIGHTS; ++i)
  143. {
  144. Node* lightNode = scene_->CreateChild("SpotLight");
  145. Light* light = lightNode->CreateComponent<Light>();
  146. float angle = 0.0f;
  147. Vector3 position((i % 3) * 60.0f - 60.0f, 45.0f, (i / 3) * 60.0f - 60.0f);
  148. Color color(((i + 1) & 1) * 0.5f + 0.5f, (((i + 1) >> 1) & 1) * 0.5f + 0.5f, (((i + 1) >> 2) & 1) * 0.5f + 0.5f);
  149. lightNode->SetPosition(position);
  150. lightNode->SetDirection(Vector3(Sin(angle), -1.5f, Cos(angle)));
  151. light->SetLightType(LIGHT_SPOT);
  152. light->SetRange(90.0f);
  153. light->SetRampTexture(cache->GetResource<Texture2D>("Textures/RampExtreme.png"));
  154. light->SetFov(45.0f);
  155. light->SetColor(color);
  156. light->SetSpecularIntensity(1.0f);
  157. light->SetCastShadows(true);
  158. light->SetShadowBias(BiasParameters(0.00002f, 0.0f));
  159. // Configure shadow fading for the lights. When they are far away enough, the lights eventually become unshadowed for
  160. // better GPU performance. Note that we could also set the maximum distance for each object to cast shadows
  161. light->SetShadowFadeDistance(100.0f); // Fade start distance
  162. light->SetShadowDistance(125.0f); // Fade end distance, shadows are disabled
  163. // Set half resolution for the shadow maps for increased performance
  164. light->SetShadowResolution(0.5f);
  165. // The spot lights will not have anything near them, so move the near plane of the shadow camera farther
  166. // for better shadow depth resolution
  167. light->SetShadowNearFarRatio(0.01f);
  168. }
  169. // Create the camera. Limit far clip distance to match the fog
  170. cameraNode_ = scene_->CreateChild("Camera");
  171. Camera* camera = cameraNode_->CreateComponent<Camera>();
  172. camera->SetFarClip(300.0f);
  173. // Set an initial position for the camera scene node above the plane
  174. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  175. }
  176. void Billboards::CreateInstructions()
  177. {
  178. ResourceCache* cache = GetSubsystem<ResourceCache>();
  179. UI* ui = GetSubsystem<UI>();
  180. // Construct new Text object, set string to display and font to use
  181. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  182. instructionText->SetText(
  183. "Use WASD keys and mouse/touch to move\n"
  184. "Space to toggle debug geometry"
  185. );
  186. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  187. // The text has multiple rows. Center them in relation to each other
  188. instructionText->SetTextAlignment(HA_CENTER);
  189. // Position the text relative to the screen center
  190. instructionText->SetHorizontalAlignment(HA_CENTER);
  191. instructionText->SetVerticalAlignment(VA_CENTER);
  192. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  193. }
  194. void Billboards::SetupViewport()
  195. {
  196. Renderer* renderer = GetSubsystem<Renderer>();
  197. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  198. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  199. renderer->SetViewport(0, viewport);
  200. }
  201. void Billboards::SubscribeToEvents()
  202. {
  203. // Subscribe HandleUpdate() function for processing update events
  204. SubscribeToEvent(E_UPDATE, HANDLER(Billboards, HandleUpdate));
  205. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  206. // debug geometry
  207. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(Billboards, HandlePostRenderUpdate));
  208. }
  209. void Billboards::MoveCamera(float timeStep)
  210. {
  211. // Do not move if the UI has a focused element (the console)
  212. if (GetSubsystem<UI>()->GetFocusElement())
  213. return;
  214. Input* input = GetSubsystem<Input>();
  215. // Movement speed as world units per second
  216. const float MOVE_SPEED = 20.0f;
  217. // Mouse sensitivity as degrees per pixel
  218. const float MOUSE_SENSITIVITY = 0.1f;
  219. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  220. IntVector2 mouseMove = input->GetMouseMove();
  221. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  222. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  223. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  224. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  225. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  226. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  227. if (input->GetKeyDown('W'))
  228. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  229. if (input->GetKeyDown('S'))
  230. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  231. if (input->GetKeyDown('A'))
  232. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  233. if (input->GetKeyDown('D'))
  234. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  235. // Toggle debug geometry with space
  236. if (input->GetKeyPress(KEY_SPACE))
  237. drawDebug_ = !drawDebug_;
  238. }
  239. void Billboards::AnimateScene(float timeStep)
  240. {
  241. // Get the light and billboard scene nodes
  242. PODVector<Node*> lightNodes;
  243. PODVector<Node*> billboardNodes;
  244. scene_->GetChildrenWithComponent<Light>(lightNodes);
  245. scene_->GetChildrenWithComponent<BillboardSet>(billboardNodes);
  246. const float LIGHT_ROTATION_SPEED = 20.0f;
  247. const float BILLBOARD_ROTATION_SPEED = 50.0f;
  248. // Rotate the lights around the world Y-axis
  249. for (unsigned i = 0; i < lightNodes.Size(); ++i)
  250. lightNodes[i]->Rotate(Quaternion(0.0f, LIGHT_ROTATION_SPEED * timeStep, 0.0f), TS_WORLD);
  251. // Rotate the individual billboards within the billboard sets, then recommit to make the changes visible
  252. for (unsigned i = 0; i < billboardNodes.Size(); ++i)
  253. {
  254. BillboardSet* billboardObject = billboardNodes[i]->GetComponent<BillboardSet>();
  255. for (unsigned j = 0; j < billboardObject->GetNumBillboards(); ++j)
  256. {
  257. Billboard* bb = billboardObject->GetBillboard(j);
  258. bb->rotation_ += BILLBOARD_ROTATION_SPEED * timeStep;
  259. }
  260. billboardObject->Commit();
  261. }
  262. }
  263. void Billboards::HandleUpdate(StringHash eventType, VariantMap& eventData)
  264. {
  265. using namespace Update;
  266. // Take the frame time step, which is stored as a float
  267. float timeStep = eventData[P_TIMESTEP].GetFloat();
  268. // Move the camera and animate the scene, scale movement with time step
  269. MoveCamera(timeStep);
  270. AnimateScene(timeStep);
  271. }
  272. void Billboards::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  273. {
  274. // If draw debug mode is enabled, draw viewport debug geometry. This time use depth test, as otherwise the result becomes
  275. // hard to interpret due to large object count
  276. if (drawDebug_)
  277. GetSubsystem<Renderer>()->DrawDebugGeometry(true);
  278. }