Billboards.cpp 13 KB

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