Advertisement
Guest User

DynamicGeometry.cpp

a guest
Mar 8th, 2015
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 14.68 KB | None | 0 0
  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.  
  23. #include <Urho3D/Urho3D.h>
  24.  
  25. #include <Urho3D/Graphics/Camera.h>
  26. #include <Urho3D/Core/CoreEvents.h>
  27. #include <Urho3D/Engine/Engine.h>
  28. #include <Urho3D/UI/Font.h>
  29. #include <Urho3D/Graphics/Geometry.h>
  30. #include <Urho3D/Graphics/Graphics.h>
  31. #include <Urho3D/Graphics/IndexBuffer.h>
  32. #include <Urho3D/Input/Input.h>
  33. #include <Urho3D/Graphics/Light.h>
  34. #include <Urho3D/IO/Log.h>
  35. #include <Urho3D/Graphics/Model.h>
  36. #include <Urho3D/Graphics/Octree.h>
  37. #include <Urho3D/Core/Profiler.h>
  38. #include <Urho3D/Graphics/Renderer.h>
  39. #include <Urho3D/Resource/ResourceCache.h>
  40. #include <Urho3D/Scene/Scene.h>
  41. #include <Urho3D/Graphics/StaticModel.h>
  42. #include <Urho3D/UI/Text.h>
  43. #include <Urho3D/Graphics/VertexBuffer.h>
  44. #include <Urho3D/UI/UI.h>
  45. #include <Urho3D/Graphics/Zone.h>
  46.  
  47. #include "DynamicGeometry.h"
  48.  
  49. #include <Urho3D/DebugNew.h>
  50.  
  51. DEFINE_APPLICATION_MAIN(DynamicGeometry)
  52.  
  53. DynamicGeometry::DynamicGeometry(Context* context) :
  54.     Sample(context),
  55.     animate_(true),
  56.     time_(0.0f)
  57. {
  58. }
  59.  
  60. void DynamicGeometry::Start()
  61. {
  62.     // Execute base class startup
  63.     Sample::Start();
  64.  
  65.     // Create the scene content
  66.     CreateScene();
  67.  
  68.     // Create the UI content
  69.     CreateInstructions();
  70.  
  71.     // Setup the viewport for displaying the scene
  72.     SetupViewport();
  73.  
  74.     // Hook up to the frame update events
  75.     SubscribeToEvents();
  76. }
  77.  
  78. void DynamicGeometry::CreateScene()
  79. {
  80.     ResourceCache* cache = GetSubsystem<ResourceCache>();
  81.  
  82.     scene_ = new Scene(context_);
  83.  
  84.     // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  85.     // (-1000, -1000, -1000) to (1000, 1000, 1000)
  86.     scene_->CreateComponent<Octree>();
  87.  
  88.     // Create a Zone for ambient light & fog control
  89.     Node* zoneNode = scene_->CreateChild("Zone");
  90.     Zone* zone = zoneNode->CreateComponent<Zone>();
  91.     zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  92.     zone->SetFogColor(Color(0.2f, 0.2f, 0.2f));
  93.     zone->SetFogStart(200.0f);
  94.     zone->SetFogEnd(300.0f);
  95.  
  96.     // Create a directional light
  97.     Node* lightNode = scene_->CreateChild("DirectionalLight");
  98.     lightNode->SetDirection(Vector3(-0.6f, -1.0f, -0.8f)); // The direction vector does not need to be normalized
  99.     Light* light = lightNode->CreateComponent<Light>();
  100.     light->SetLightType(LIGHT_DIRECTIONAL);
  101.     light->SetColor(Color(0.4f, 1.0f, 0.4f));
  102.     light->SetSpecularIntensity(1.5f);
  103.  
  104.     // Get the original model and its unmodified vertices, which are used as source data for the animation
  105.     Model* originalModel = cache->GetResource<Model>("Models/Box.mdl");
  106.     if (!originalModel)
  107.     {
  108.         LOGERROR("Model not found, cannot initialize example scene");
  109.         return;
  110.     }
  111.     // Get the vertex buffer from the first geometry's first LOD level
  112.     VertexBuffer* buffer = originalModel->GetGeometry(0, 0)->GetVertexBuffer(0);
  113.     const unsigned char* vertexData = (const unsigned char*)buffer->Lock(0, buffer->GetVertexCount());
  114.     if (vertexData)
  115.     {
  116.         unsigned numVertices = buffer->GetVertexCount();
  117.         unsigned vertexSize = buffer->GetVertexSize();
  118.         // Copy the original vertex positions
  119.         for (unsigned i = 0; i < numVertices; ++i)
  120.         {
  121.             const Vector3& src = *reinterpret_cast<const Vector3*>(vertexData + i * vertexSize);
  122.             originalVertices_.Push(src);
  123.         }
  124.         buffer->Unlock();
  125.  
  126.         // Detect duplicate vertices to allow seamless animation
  127.         vertexDuplicates_.Resize(originalVertices_.Size());
  128.         for (unsigned i = 0; i < originalVertices_.Size(); ++i)
  129.         {
  130.             vertexDuplicates_[i] = i; // Assume not a duplicate
  131.             for (unsigned j = 0; j < i; ++j)
  132.             {
  133.                 if (originalVertices_[i].Equals(originalVertices_[j]))
  134.                 {
  135.                     vertexDuplicates_[i] = j;
  136.                     break;
  137.                 }
  138.             }
  139.         }
  140.     }
  141.     else
  142.     {
  143.         LOGERROR("Failed to lock the model vertex buffer to get original vertices");
  144.         return;
  145.     }
  146.  
  147.     // Create StaticModels in the scene. Clone the model for each so that we can modify the vertex data individually
  148.     for (int y = -1; y <= 1; ++y)
  149.     {
  150.         for (int x = -1; x <= 1; ++x)
  151.         {
  152.             Node* node = scene_->CreateChild("Object");
  153.             node->SetPosition(Vector3(x * 2.0f, 0.0f, y * 2.0f));
  154.             StaticModel* object = node->CreateComponent<StaticModel>();
  155.             SharedPtr<Model> cloneModel = originalModel->Clone();
  156.             object->SetModel(cloneModel);
  157.             // Store the cloned vertex buffer that we will modify when animating
  158.             animatingBuffers_.Push(SharedPtr<VertexBuffer>(cloneModel->GetGeometry(0, 0)->GetVertexBuffer(0)));
  159.         }
  160.     }
  161.  
  162.     // Finally create one model (pyramid shape) and a StaticModel to display it from scratch
  163.     // Note: there are duplicated vertices to enable face normals. We will calculate normals programmatically
  164.     {
  165.         const unsigned numVertices = 18;
  166.  
  167.         float vertexData[] = {
  168.             // Position
  169.             0.0f, 0.5f, 0.0f,
  170.             0.5f, -0.5f, 0.5f,
  171.             0.5f, -0.5f, -0.5f,
  172.  
  173.             0.0f, 0.5f, 0.0f,
  174.             -0.5f, -0.5f, 0.5f,
  175.             0.5f, -0.5f, 0.5f,
  176.  
  177.             0.0f, 0.5f, 0.0f,
  178.             -0.5f, -0.5f, -0.5f,
  179.             -0.5f, -0.5f, 0.5f,
  180.  
  181.             0.0f, 0.5f, 0.0f,
  182.             0.5f, -0.5f, -0.5f,
  183.             -0.5f, -0.5f, -0.5f,
  184.  
  185.             0.5f, -0.5f, -0.5f,
  186.             0.5f, -0.5f, 0.5f,
  187.             -0.5f, -0.5f, 0.5f,
  188.  
  189.             0.5f, -0.5f, -0.5f,
  190.             -0.5f, -0.5f, 0.5f,
  191.             -0.5f, -0.5f, -0.5f,
  192.         };
  193.  
  194.         float normalData[] = {
  195.             // Normal
  196.              0.0f, 0.0f, 0.0f,
  197.              0.0f, 0.0f, 0.0f,
  198.              0.0f, 0.0f, 0.0f,
  199.  
  200.              0.0f, 0.0f, 0.0f,
  201.              0.0f, 0.0f, 0.0f,
  202.              0.0f, 0.0f, 0.0f,
  203.  
  204.              0.0f, 0.0f, 0.0f,
  205.              0.0f, 0.0f, 0.0f,
  206.              0.0f, 0.0f, 0.0f,
  207.  
  208.              0.0f, 0.0f, 0.0f,
  209.              0.0f, 0.0f, 0.0f,
  210.              0.0f, 0.0f, 0.0f,
  211.  
  212.              0.0f, 0.0f, 0.0f,
  213.              0.0f, 0.0f, 0.0f,
  214.              0.0f, 0.0f, 0.0f,
  215.  
  216.              0.0f, 0.0f, 0.0f,
  217.              0.0f, 0.0f, 0.0f,
  218.              0.0f, 0.0f, 0.0f
  219.         };
  220.  
  221.         const unsigned short indexData[] = {
  222.             0, 1, 2,
  223.             3, 4, 5,
  224.             6, 7, 8,
  225.             9, 10, 11,
  226.             12, 13, 14,
  227.             15, 16, 17
  228.         };
  229.  
  230.         // Calculate face normals now
  231.         for (unsigned i = 0; i < numVertices; i += 3)
  232.         {
  233.             Vector3& v1 = *(reinterpret_cast<Vector3*>(&vertexData[3 * i]));
  234.             Vector3& v2 = *(reinterpret_cast<Vector3*>(&vertexData[3 * (i + 1)]));
  235.             Vector3& v3 = *(reinterpret_cast<Vector3*>(&vertexData[3 * (i + 2)]));
  236.             Vector3& n1 = *(reinterpret_cast<Vector3*>(&normalData[3 * i]));
  237.             Vector3& n2 = *(reinterpret_cast<Vector3*>(&normalData[3 * (i + 1)]));
  238.             Vector3& n3 = *(reinterpret_cast<Vector3*>(&normalData[3 * (i + 2)]));
  239.  
  240.             Vector3 edge1 = v1 - v2;
  241.             Vector3 edge2 = v1 - v3;
  242.             n1 = n2 = n3 = edge1.CrossProduct(edge2).Normalized();
  243.         }
  244.  
  245.         SharedPtr<Model> fromScratchModel(new Model(context_));
  246.         SharedPtr<VertexBuffer> vb(new VertexBuffer(context_));
  247.         SharedPtr<VertexBuffer> nb(new VertexBuffer(context_));
  248.         SharedPtr<IndexBuffer> ib(new IndexBuffer(context_));
  249.         SharedPtr<Geometry> geom(new Geometry(context_));
  250.  
  251.         // Shadowed buffer needed for raycasts to work, and so that data can be automatically restored on device loss
  252.         vb->SetShadowed(true);
  253.         vb->SetSize(numVertices, MASK_POSITION);
  254.         vb->SetData(vertexData);
  255.  
  256.         nb->SetShadowed(true);
  257.         nb->SetSize(numVertices, MASK_NORMAL);
  258.         nb->SetData(normalData);
  259.  
  260.         ib->SetShadowed(true);
  261.         ib->SetSize(numVertices, false);
  262.         ib->SetData(indexData);
  263.  
  264.         geom->SetVertexBuffer(0, vb);
  265.         geom->SetVertexBuffer(1, nb);
  266.         geom->SetIndexBuffer(ib);
  267.         geom->SetDrawRange(TRIANGLE_LIST, 0, numVertices);
  268.  
  269.         fromScratchModel->SetNumGeometries(1);
  270.         fromScratchModel->SetGeometry(0, 0, geom);
  271.         fromScratchModel->SetBoundingBox(BoundingBox(Vector3(-0.5f, -0.5f, -0.5f), Vector3(0.5f, 0.5f, 0.5f)));
  272.  
  273.         Node* node = scene_->CreateChild("FromScratchObject");
  274.         node->SetPosition(Vector3(0.0f, 3.0f, 0.0f));
  275.         StaticModel* object = node->CreateComponent<StaticModel>();
  276.         object->SetModel(fromScratchModel);
  277.     }
  278.  
  279.     // Create the camera
  280.     cameraNode_ = new Node(context_);
  281.     cameraNode_->SetPosition(Vector3(0.0f, 2.0f, -20.0f));
  282.     Camera* camera = cameraNode_->CreateComponent<Camera>();
  283.     camera->SetFarClip(300.0f);
  284. }
  285.  
  286. void DynamicGeometry::CreateInstructions()
  287. {
  288.     ResourceCache* cache = GetSubsystem<ResourceCache>();
  289.     UI* ui = GetSubsystem<UI>();
  290.  
  291.     // Construct new Text object, set string to display and font to use
  292.     Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  293.     instructionText->SetText(
  294.         "Use WASD keys and mouse/touch to move\n"
  295.         "Space to toggle animation"
  296.     );
  297.     instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  298.     // The text has multiple rows. Center them in relation to each other
  299.     instructionText->SetTextAlignment(HA_CENTER);
  300.  
  301.     // Position the text relative to the screen center
  302.     instructionText->SetHorizontalAlignment(HA_CENTER);
  303.     instructionText->SetVerticalAlignment(VA_CENTER);
  304.     instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  305. }
  306.  
  307. void DynamicGeometry::SetupViewport()
  308. {
  309.     Renderer* renderer = GetSubsystem<Renderer>();
  310.  
  311.     // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  312.     SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  313.     renderer->SetViewport(0, viewport);
  314. }
  315.  
  316. void DynamicGeometry::SubscribeToEvents()
  317. {
  318.     // Subscribe HandleUpdate() function for processing update events
  319.     SubscribeToEvent(E_UPDATE, HANDLER(DynamicGeometry, HandleUpdate));
  320. }
  321.  
  322. void DynamicGeometry::MoveCamera(float timeStep)
  323. {
  324.     // Do not move if the UI has a focused element (the console)
  325.     if (GetSubsystem<UI>()->GetFocusElement())
  326.         return;
  327.  
  328.     Input* input = GetSubsystem<Input>();
  329.  
  330.     // Movement speed as world units per second
  331.     const float MOVE_SPEED = 20.0f;
  332.     // Mouse sensitivity as degrees per pixel
  333.     const float MOUSE_SENSITIVITY = 0.1f;
  334.  
  335.     // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  336.     IntVector2 mouseMove = input->GetMouseMove();
  337.     yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  338.     pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  339.     pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  340.  
  341.     // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  342.     cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  343.  
  344.     // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  345.     if (input->GetKeyDown('W'))
  346.         cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  347.     if (input->GetKeyDown('S'))
  348.         cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  349.     if (input->GetKeyDown('A'))
  350.         cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  351.     if (input->GetKeyDown('D'))
  352.         cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  353. }
  354.  
  355. void DynamicGeometry::AnimateObjects(float timeStep)
  356. {
  357.     PROFILE(AnimateObjects);
  358.  
  359.     time_ += timeStep * 100.0f;
  360.  
  361.     // Repeat for each of the cloned vertex buffers
  362.     for (unsigned i = 0; i < animatingBuffers_.Size(); ++i)
  363.     {
  364.         float startPhase = time_ + i * 30.0f;
  365.         VertexBuffer* buffer = animatingBuffers_[i];
  366.  
  367.         // Lock the vertex buffer for update and rewrite positions with sine wave modulated ones
  368.         // Cannot use discard lock as there is other data (normals, UVs) that we are not overwriting
  369.         unsigned char* vertexData = (unsigned char*)buffer->Lock(0, buffer->GetVertexCount());
  370.         if (vertexData)
  371.         {
  372.             unsigned vertexSize = buffer->GetVertexSize();
  373.             unsigned numVertices = buffer->GetVertexCount();
  374.             for (unsigned j = 0; j < numVertices; ++j)
  375.             {
  376.                 // If there are duplicate vertices, animate them in phase of the original
  377.                 float phase = startPhase + vertexDuplicates_[j] * 10.0f;
  378.                 Vector3& src = originalVertices_[j];
  379.                 Vector3& dest = *reinterpret_cast<Vector3*>(vertexData + j * vertexSize);
  380.                 dest.x_ = src.x_ * (1.0f + 0.1f * Sin(phase));
  381.                 dest.y_ = src.y_ * (1.0f + 0.1f * Sin(phase + 60.0f));
  382.                 dest.z_ = src.z_ * (1.0f + 0.1f * Sin(phase + 120.0f));
  383.             }
  384.  
  385.             buffer->Unlock();
  386.         }
  387.     }
  388. }
  389.  
  390. void DynamicGeometry::HandleUpdate(StringHash eventType, VariantMap& eventData)
  391. {
  392.     using namespace Update;
  393.  
  394.     // Take the frame time step, which is stored as a float
  395.     float timeStep = eventData[P_TIMESTEP].GetFloat();
  396.  
  397.     // Toggle animation with space
  398.     Input* input = GetSubsystem<Input>();
  399.     if (input->GetKeyPress(KEY_SPACE))
  400.         animate_ = !animate_;
  401.  
  402.     // Move the camera, scale movement with time step
  403.     MoveCamera(timeStep);
  404.  
  405.     // Animate objects' vertex data if enabled
  406.     if (animate_)
  407.         AnimateObjects(timeStep);
  408. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement