HugeObjectCount.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. //
  2. // Copyright (c) 2008-2015 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/Camera.h>
  24. #include <Urho3D/Core/CoreEvents.h>
  25. #include <Urho3D/Engine/Engine.h>
  26. #include <Urho3D/UI/Font.h>
  27. #include <Urho3D/Graphics/Graphics.h>
  28. #include <Urho3D/Input/Input.h>
  29. #include <Urho3D/Graphics/Material.h>
  30. #include <Urho3D/Graphics/Model.h>
  31. #include <Urho3D/Graphics/Octree.h>
  32. #include <Urho3D/Core/Profiler.h>
  33. #include <Urho3D/Graphics/Renderer.h>
  34. #include <Urho3D/Resource/ResourceCache.h>
  35. #include <Urho3D/Scene/Scene.h>
  36. #include <Urho3D/Graphics/StaticModelGroup.h>
  37. #include <Urho3D/UI/Text.h>
  38. #include <Urho3D/UI/UI.h>
  39. #include <Urho3D/Graphics/Zone.h>
  40. #include "HugeObjectCount.h"
  41. #include <Urho3D/DebugNew.h>
  42. DEFINE_APPLICATION_MAIN(HugeObjectCount)
  43. HugeObjectCount::HugeObjectCount(Context* context) :
  44. Sample(context),
  45. animate_(false),
  46. useGroups_(false)
  47. {
  48. }
  49. void HugeObjectCount::Start()
  50. {
  51. // Execute base class startup
  52. Sample::Start();
  53. // Create the scene content
  54. CreateScene();
  55. // Create the UI content
  56. CreateInstructions();
  57. // Setup the viewport for displaying the scene
  58. SetupViewport();
  59. // Hook up to the frame update events
  60. SubscribeToEvents();
  61. }
  62. void HugeObjectCount::CreateScene()
  63. {
  64. ResourceCache* cache = GetSubsystem<ResourceCache>();
  65. if (!scene_)
  66. scene_ = new Scene(context_);
  67. else
  68. {
  69. scene_->Clear();
  70. boxNodes_.Clear();
  71. }
  72. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  73. // (-1000, -1000, -1000) to (1000, 1000, 1000)
  74. scene_->CreateComponent<Octree>();
  75. // Create a Zone for ambient light & fog control
  76. Node* zoneNode = scene_->CreateChild("Zone");
  77. Zone* zone = zoneNode->CreateComponent<Zone>();
  78. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  79. zone->SetFogColor(Color(0.2f, 0.2f, 0.2f));
  80. zone->SetFogStart(200.0f);
  81. zone->SetFogEnd(300.0f);
  82. // Create a directional light
  83. Node* lightNode = scene_->CreateChild("DirectionalLight");
  84. lightNode->SetDirection(Vector3(-0.6f, -1.0f, -0.8f)); // The direction vector does not need to be normalized
  85. Light* light = lightNode->CreateComponent<Light>();
  86. light->SetLightType(LIGHT_DIRECTIONAL);
  87. if (!useGroups_)
  88. {
  89. light->SetColor(Color(0.7f, 0.35f, 0.0f));
  90. // Create individual box StaticModels in the scene
  91. for (int y = -125; y < 125; ++y)
  92. {
  93. for (int x = -125; x < 125; ++x)
  94. {
  95. Node* boxNode = scene_->CreateChild("Box");
  96. boxNode->SetPosition(Vector3(x * 0.3f, 0.0f, y * 0.3f));
  97. boxNode->SetScale(0.25f);
  98. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  99. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  100. boxNodes_.Push(SharedPtr<Node>(boxNode));
  101. }
  102. }
  103. }
  104. else
  105. {
  106. light->SetColor(Color(0.6f, 0.6f, 0.6f));
  107. light->SetSpecularIntensity(1.5f);
  108. // Create StaticModelGroups in the scene
  109. StaticModelGroup* lastGroup = 0;
  110. for (int y = -125; y < 125; ++y)
  111. {
  112. for (int x = -125; x < 125; ++x)
  113. {
  114. // Create new group if no group yet, or the group has already "enough" objects. The tradeoff is between culling
  115. // accuracy and the amount of CPU processing needed for all the objects. Note that the group's own transform
  116. // does not matter, and it does not render anything if instance nodes are not added to it
  117. if (!lastGroup || lastGroup->GetNumInstanceNodes() >= 25 * 25)
  118. {
  119. Node* boxGroupNode = scene_->CreateChild("BoxGroup");
  120. lastGroup = boxGroupNode->CreateComponent<StaticModelGroup>();
  121. lastGroup->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  122. }
  123. Node* boxNode = scene_->CreateChild("Box");
  124. boxNode->SetPosition(Vector3(x * 0.3f, 0.0f, y * 0.3f));
  125. boxNode->SetScale(0.25f);
  126. boxNodes_.Push(SharedPtr<Node>(boxNode));
  127. lastGroup->AddInstanceNode(boxNode);
  128. }
  129. }
  130. }
  131. // Create the camera. Create it outside the scene so that we can clear the whole scene without affecting it
  132. if (!cameraNode_)
  133. {
  134. cameraNode_ = new Node(context_);
  135. cameraNode_->SetPosition(Vector3(0.0f, 10.0f, -100.0f));
  136. Camera* camera = cameraNode_->CreateComponent<Camera>();
  137. camera->SetFarClip(300.0f);
  138. }
  139. }
  140. void HugeObjectCount::CreateInstructions()
  141. {
  142. ResourceCache* cache = GetSubsystem<ResourceCache>();
  143. UI* ui = GetSubsystem<UI>();
  144. // Construct new Text object, set string to display and font to use
  145. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  146. instructionText->SetText(
  147. "Use WASD keys and mouse/touch to move\n"
  148. "Space to toggle animation\n"
  149. "G to toggle object group optimization"
  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 HugeObjectCount::SetupViewport()
  160. {
  161. Renderer* 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 HugeObjectCount::SubscribeToEvents()
  167. {
  168. // Subscribe HandleUpdate() function for processing update events
  169. SubscribeToEvent(E_UPDATE, HANDLER(HugeObjectCount, HandleUpdate));
  170. }
  171. void HugeObjectCount::MoveCamera(float timeStep)
  172. {
  173. // Do not move if the UI has a focused element (the console)
  174. if (GetSubsystem<UI>()->GetFocusElement())
  175. return;
  176. Input* input = GetSubsystem<Input>();
  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. IntVector2 mouseMove = input->GetMouseMove();
  183. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  184. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  185. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  186. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  187. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  188. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  189. if (input->GetKeyDown('W'))
  190. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  191. if (input->GetKeyDown('S'))
  192. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  193. if (input->GetKeyDown('A'))
  194. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  195. if (input->GetKeyDown('D'))
  196. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  197. }
  198. void HugeObjectCount::AnimateObjects(float timeStep)
  199. {
  200. PROFILE(AnimateObjects);
  201. const float ROTATE_SPEED = 15.0f;
  202. // Rotate about the Z axis (roll)
  203. Quaternion rotateQuat(ROTATE_SPEED * timeStep, Vector3::FORWARD);
  204. for (unsigned i = 0; i < boxNodes_.Size(); ++i)
  205. boxNodes_[i]->Rotate(rotateQuat);
  206. }
  207. void HugeObjectCount::HandleUpdate(StringHash eventType, VariantMap& eventData)
  208. {
  209. using namespace Update;
  210. // Take the frame time step, which is stored as a float
  211. float timeStep = eventData[P_TIMESTEP].GetFloat();
  212. // Toggle animation with space
  213. Input* input = GetSubsystem<Input>();
  214. if (input->GetKeyPress(KEY_SPACE))
  215. animate_ = !animate_;
  216. // Toggle grouped / ungrouped mode
  217. if (input->GetKeyPress('G'))
  218. {
  219. useGroups_ = !useGroups_;
  220. CreateScene();
  221. }
  222. // Move the camera, scale movement with time step
  223. MoveCamera(timeStep);
  224. // Animate scene if enabled
  225. if (animate_)
  226. AnimateObjects(timeStep);
  227. }