DynamicGeometry.cpp 15 KB

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