DynamicGeometry.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/Core/CoreEvents.h>
  24. #include <Atomic/Core/Profiler.h>
  25. #include <Atomic/Engine/Engine.h>
  26. #include <Atomic/Graphics/Camera.h>
  27. #include <Atomic/Graphics/Geometry.h>
  28. #include <Atomic/Graphics/Graphics.h>
  29. #include <Atomic/Graphics/IndexBuffer.h>
  30. #include <Atomic/Graphics/Light.h>
  31. #include <Atomic/Graphics/Model.h>
  32. #include <Atomic/Graphics/Octree.h>
  33. #include <Atomic/Graphics/Renderer.h>
  34. #include <Atomic/Graphics/StaticModel.h>
  35. #include <Atomic/Graphics/VertexBuffer.h>
  36. #include <Atomic/Graphics/Zone.h>
  37. #include <Atomic/Input/Input.h>
  38. #include <Atomic/IO/Log.h>
  39. #include <Atomic/Resource/ResourceCache.h>
  40. #include <Atomic/Scene/Scene.h>
  41. #include <Atomic/UI/UI.h>
  42. #include "DynamicGeometry.h"
  43. #include <Atomic/DebugNew.h>
  44. DynamicGeometry::DynamicGeometry(Context* context) :
  45. Sample(context),
  46. animate_(true),
  47. time_(0.0f)
  48. {
  49. }
  50. void DynamicGeometry::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 events
  61. SubscribeToEvents();
  62. // Set the mouse mode to use in the sample
  63. Sample::InitMouseMode(MM_RELATIVE);
  64. }
  65. void DynamicGeometry::CreateScene()
  66. {
  67. ResourceCache* cache = GetSubsystem<ResourceCache>();
  68. scene_ = new Scene(context_);
  69. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  70. // (-1000, -1000, -1000) to (1000, 1000, 1000)
  71. scene_->CreateComponent<Octree>();
  72. // Create a Zone for ambient light & fog control
  73. Node* zoneNode = scene_->CreateChild("Zone");
  74. Zone* zone = zoneNode->CreateComponent<Zone>();
  75. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  76. zone->SetFogColor(Color(0.2f, 0.2f, 0.2f));
  77. zone->SetFogStart(200.0f);
  78. zone->SetFogEnd(300.0f);
  79. // Create a directional light
  80. Node* lightNode = scene_->CreateChild("DirectionalLight");
  81. lightNode->SetDirection(Vector3(-0.6f, -1.0f, -0.8f)); // The direction vector does not need to be normalized
  82. Light* light = lightNode->CreateComponent<Light>();
  83. light->SetLightType(LIGHT_DIRECTIONAL);
  84. light->SetColor(Color(0.4f, 1.0f, 0.4f));
  85. light->SetSpecularIntensity(1.5f);
  86. // Get the original model and its unmodified vertices, which are used as source data for the animation
  87. Model* originalModel = cache->GetResource<Model>("Models/Box.mdl");
  88. if (!originalModel)
  89. {
  90. ATOMIC_LOGERROR("Model not found, cannot initialize example scene");
  91. return;
  92. }
  93. // Get the vertex buffer from the first geometry's first LOD level
  94. VertexBuffer* buffer = originalModel->GetGeometry(0, 0)->GetVertexBuffer(0);
  95. const unsigned char* vertexData = (const unsigned char*)buffer->Lock(0, buffer->GetVertexCount());
  96. if (vertexData)
  97. {
  98. unsigned numVertices = buffer->GetVertexCount();
  99. unsigned vertexSize = buffer->GetVertexSize();
  100. // Copy the original vertex positions
  101. for (unsigned i = 0; i < numVertices; ++i)
  102. {
  103. const Vector3& src = *reinterpret_cast<const Vector3*>(vertexData + i * vertexSize);
  104. originalVertices_.Push(src);
  105. }
  106. buffer->Unlock();
  107. // Detect duplicate vertices to allow seamless animation
  108. vertexDuplicates_.Resize(originalVertices_.Size());
  109. for (unsigned i = 0; i < originalVertices_.Size(); ++i)
  110. {
  111. vertexDuplicates_[i] = i; // Assume not a duplicate
  112. for (unsigned j = 0; j < i; ++j)
  113. {
  114. if (originalVertices_[i].Equals(originalVertices_[j]))
  115. {
  116. vertexDuplicates_[i] = j;
  117. break;
  118. }
  119. }
  120. }
  121. }
  122. else
  123. {
  124. ATOMIC_LOGERROR("Failed to lock the model vertex buffer to get original vertices");
  125. return;
  126. }
  127. // Create StaticModels in the scene. Clone the model for each so that we can modify the vertex data individually
  128. for (int y = -1; y <= 1; ++y)
  129. {
  130. for (int x = -1; x <= 1; ++x)
  131. {
  132. Node* node = scene_->CreateChild("Object");
  133. node->SetPosition(Vector3(x * 2.0f, 0.0f, y * 2.0f));
  134. StaticModel* object = node->CreateComponent<StaticModel>();
  135. SharedPtr<Model> cloneModel = originalModel->Clone();
  136. object->SetModel(cloneModel);
  137. // Store the cloned vertex buffer that we will modify when animating
  138. animatingBuffers_.Push(SharedPtr<VertexBuffer>(cloneModel->GetGeometry(0, 0)->GetVertexBuffer(0)));
  139. }
  140. }
  141. // Finally create one model (pyramid shape) and a StaticModel to display it from scratch
  142. // Note: there are duplicated vertices to enable face normals. We will calculate normals programmatically
  143. {
  144. const unsigned numVertices = 18;
  145. float vertexData[] = {
  146. // Position Normal
  147. 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f,
  148. 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f,
  149. 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
  150. 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f,
  151. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f,
  152. 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f,
  153. 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f,
  154. -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
  155. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f,
  156. 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f,
  157. 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
  158. -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
  159. 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
  160. 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f,
  161. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f,
  162. 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
  163. -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f,
  164. -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f
  165. };
  166. const unsigned short indexData[] = {
  167. 0, 1, 2,
  168. 3, 4, 5,
  169. 6, 7, 8,
  170. 9, 10, 11,
  171. 12, 13, 14,
  172. 15, 16, 17
  173. };
  174. // Calculate face normals now
  175. for (unsigned i = 0; i < numVertices; i += 3)
  176. {
  177. Vector3& v1 = *(reinterpret_cast<Vector3*>(&vertexData[6 * i]));
  178. Vector3& v2 = *(reinterpret_cast<Vector3*>(&vertexData[6 * (i + 1)]));
  179. Vector3& v3 = *(reinterpret_cast<Vector3*>(&vertexData[6 * (i + 2)]));
  180. Vector3& n1 = *(reinterpret_cast<Vector3*>(&vertexData[6 * i + 3]));
  181. Vector3& n2 = *(reinterpret_cast<Vector3*>(&vertexData[6 * (i + 1) + 3]));
  182. Vector3& n3 = *(reinterpret_cast<Vector3*>(&vertexData[6 * (i + 2) + 3]));
  183. Vector3 edge1 = v1 - v2;
  184. Vector3 edge2 = v1 - v3;
  185. n1 = n2 = n3 = edge1.CrossProduct(edge2).Normalized();
  186. }
  187. SharedPtr<Model> fromScratchModel(new Model(context_));
  188. SharedPtr<VertexBuffer> vb(new VertexBuffer(context_));
  189. SharedPtr<IndexBuffer> ib(new IndexBuffer(context_));
  190. SharedPtr<Geometry> geom(new Geometry(context_));
  191. // Shadowed buffer needed for raycasts to work, and so that data can be automatically restored on device loss
  192. vb->SetShadowed(true);
  193. // We could use the "legacy" element bitmask to define elements for more compact code, but let's demonstrate
  194. // defining the vertex elements explicitly to allow any element types and order
  195. PODVector<VertexElement> elements;
  196. elements.Push(VertexElement(TYPE_VECTOR3, SEM_POSITION));
  197. elements.Push(VertexElement(TYPE_VECTOR3, SEM_NORMAL));
  198. vb->SetSize(numVertices, elements);
  199. vb->SetData(vertexData);
  200. ib->SetShadowed(true);
  201. ib->SetSize(numVertices, false);
  202. ib->SetData(indexData);
  203. geom->SetVertexBuffer(0, vb);
  204. geom->SetIndexBuffer(ib);
  205. geom->SetDrawRange(TRIANGLE_LIST, 0, numVertices);
  206. fromScratchModel->SetNumGeometries(1);
  207. fromScratchModel->SetGeometry(0, 0, geom);
  208. fromScratchModel->SetBoundingBox(BoundingBox(Vector3(-0.5f, -0.5f, -0.5f), Vector3(0.5f, 0.5f, 0.5f)));
  209. // Though not necessary to render, the vertex & index buffers must be listed in the model so that it can be saved properly
  210. Vector<SharedPtr<VertexBuffer> > vertexBuffers;
  211. Vector<SharedPtr<IndexBuffer> > indexBuffers;
  212. vertexBuffers.Push(vb);
  213. indexBuffers.Push(ib);
  214. // Morph ranges could also be not defined. Here we simply define a zero range (no morphing) for the vertex buffer
  215. PODVector<unsigned> morphRangeStarts;
  216. PODVector<unsigned> morphRangeCounts;
  217. morphRangeStarts.Push(0);
  218. morphRangeCounts.Push(0);
  219. fromScratchModel->SetVertexBuffers(vertexBuffers, morphRangeStarts, morphRangeCounts);
  220. fromScratchModel->SetIndexBuffers(indexBuffers);
  221. Node* node = scene_->CreateChild("FromScratchObject");
  222. node->SetPosition(Vector3(0.0f, 3.0f, 0.0f));
  223. StaticModel* object = node->CreateComponent<StaticModel>();
  224. object->SetModel(fromScratchModel);
  225. }
  226. // Create the camera
  227. cameraNode_ = new Node(context_);
  228. cameraNode_->SetPosition(Vector3(0.0f, 2.0f, -20.0f));
  229. Camera* camera = cameraNode_->CreateComponent<Camera>();
  230. camera->SetFarClip(300.0f);
  231. }
  232. void DynamicGeometry::CreateInstructions()
  233. {
  234. SimpleCreateInstructions(
  235. "Use WASD keys and mouse/touch to move\n"
  236. "Space to toggle animation"
  237. );
  238. }
  239. void DynamicGeometry::SetupViewport()
  240. {
  241. Renderer* renderer = GetSubsystem<Renderer>();
  242. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  243. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  244. renderer->SetViewport(0, viewport);
  245. }
  246. void DynamicGeometry::SubscribeToEvents()
  247. {
  248. // Subscribe HandleUpdate() function for processing update events
  249. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(DynamicGeometry, HandleUpdate));
  250. }
  251. void DynamicGeometry::MoveCamera(float timeStep)
  252. {
  253. Input* input = GetSubsystem<Input>();
  254. // Movement speed as world units per second
  255. const float MOVE_SPEED = 20.0f;
  256. // Mouse sensitivity as degrees per pixel
  257. const float MOUSE_SENSITIVITY = 0.1f;
  258. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  259. IntVector2 mouseMove = input->GetMouseMove();
  260. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  261. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  262. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  263. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  264. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  265. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  266. if (input->GetKeyDown(KEY_W))
  267. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  268. if (input->GetKeyDown(KEY_S))
  269. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  270. if (input->GetKeyDown(KEY_A))
  271. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  272. if (input->GetKeyDown(KEY_D))
  273. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  274. }
  275. void DynamicGeometry::AnimateObjects(float timeStep)
  276. {
  277. ATOMIC_PROFILE(AnimateObjects);
  278. time_ += timeStep * 100.0f;
  279. // Repeat for each of the cloned vertex buffers
  280. for (unsigned i = 0; i < animatingBuffers_.Size(); ++i)
  281. {
  282. float startPhase = time_ + i * 30.0f;
  283. VertexBuffer* buffer = animatingBuffers_[i];
  284. // Lock the vertex buffer for update and rewrite positions with sine wave modulated ones
  285. // Cannot use discard lock as there is other data (normals, UVs) that we are not overwriting
  286. unsigned char* vertexData = (unsigned char*)buffer->Lock(0, buffer->GetVertexCount());
  287. if (vertexData)
  288. {
  289. unsigned vertexSize = buffer->GetVertexSize();
  290. unsigned numVertices = buffer->GetVertexCount();
  291. for (unsigned j = 0; j < numVertices; ++j)
  292. {
  293. // If there are duplicate vertices, animate them in phase of the original
  294. float phase = startPhase + vertexDuplicates_[j] * 10.0f;
  295. Vector3& src = originalVertices_[j];
  296. Vector3& dest = *reinterpret_cast<Vector3*>(vertexData + j * vertexSize);
  297. dest.x_ = src.x_ * (1.0f + 0.1f * Sin(phase));
  298. dest.y_ = src.y_ * (1.0f + 0.1f * Sin(phase + 60.0f));
  299. dest.z_ = src.z_ * (1.0f + 0.1f * Sin(phase + 120.0f));
  300. }
  301. buffer->Unlock();
  302. }
  303. }
  304. }
  305. void DynamicGeometry::HandleUpdate(StringHash eventType, VariantMap& eventData)
  306. {
  307. using namespace Update;
  308. // Take the frame time step, which is stored as a float
  309. float timeStep = eventData[P_TIMESTEP].GetFloat();
  310. // Toggle animation with space
  311. Input* input = GetSubsystem<Input>();
  312. if (input->GetKeyPress(KEY_SPACE))
  313. animate_ = !animate_;
  314. // Move the camera, scale movement with time step
  315. MoveCamera(timeStep);
  316. // Animate objects' vertex data if enabled
  317. if (animate_)
  318. AnimateObjects(timeStep);
  319. }