DynamicGeometry.cpp 14 KB

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