HugeObjectCount.cpp 9.6 KB

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