SkeletalAnimation.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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/Engine/Engine.h>
  25. #include <Atomic/Graphics/AnimatedModel.h>
  26. #include <Atomic/Graphics/Animation.h>
  27. #include <Atomic/Graphics/AnimationState.h>
  28. #include <Atomic/Graphics/Camera.h>
  29. #include <Atomic/Graphics/DebugRenderer.h>
  30. #include <Atomic/Graphics/Graphics.h>
  31. #include <Atomic/Graphics/Light.h>
  32. #include <Atomic/Graphics/Material.h>
  33. #include <Atomic/Graphics/Octree.h>
  34. #include <Atomic/Graphics/Renderer.h>
  35. #include <Atomic/Graphics/Zone.h>
  36. #include <Atomic/Input/Input.h>
  37. #include <Atomic/Resource/ResourceCache.h>
  38. #include <Atomic/Scene/Scene.h>
  39. #include <Atomic/UI/UI.h>
  40. #include "Mover.h"
  41. #include "SkeletalAnimation.h"
  42. #include <Atomic/DebugNew.h>
  43. SkeletalAnimation::SkeletalAnimation(Context* context) :
  44. Sample(context),
  45. drawDebug_(false)
  46. {
  47. // Register an object factory for our custom Mover component so that we can create them to scene nodes
  48. context->RegisterFactory<Mover>();
  49. }
  50. void SkeletalAnimation::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 and render post-update events
  61. SubscribeToEvents();
  62. // Set the mouse mode to use in the sample
  63. Sample::InitMouseMode(MM_ABSOLUTE);
  64. }
  65. void SkeletalAnimation::CreateScene()
  66. {
  67. ResourceCache* cache = GetSubsystem<ResourceCache>();
  68. scene_ = new Scene(context_);
  69. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  70. // Also create a DebugRenderer component so that we can draw debug geometry
  71. scene_->CreateComponent<Octree>();
  72. scene_->CreateComponent<DebugRenderer>();
  73. // Create scene node & StaticModel component for showing a static plane
  74. Node* planeNode = scene_->CreateChild("Plane");
  75. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  76. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  77. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  78. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  79. // Create a Zone component for ambient lighting & fog control
  80. Node* zoneNode = scene_->CreateChild("Zone");
  81. Zone* zone = zoneNode->CreateComponent<Zone>();
  82. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  83. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  84. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  85. zone->SetFogStart(100.0f);
  86. zone->SetFogEnd(300.0f);
  87. // Create a directional light to the world. Enable cascaded shadows on it
  88. Node* lightNode = scene_->CreateChild("DirectionalLight");
  89. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  90. Light* light = lightNode->CreateComponent<Light>();
  91. light->SetLightType(LIGHT_DIRECTIONAL);
  92. light->SetCastShadows(true);
  93. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  94. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  95. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  96. // Create animated models
  97. const unsigned NUM_MODELS = 100;
  98. const float MODEL_MOVE_SPEED = 2.0f;
  99. const float MODEL_ROTATE_SPEED = 100.0f;
  100. const BoundingBox bounds(Vector3(-47.0f, 0.0f, -47.0f), Vector3(47.0f, 0.0f, 47.0f));
  101. for (unsigned i = 0; i < NUM_MODELS; ++i)
  102. {
  103. Node* modelNode = scene_->CreateChild("Jack");
  104. modelNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  105. modelNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  106. AnimatedModel* modelObject = modelNode->CreateComponent<AnimatedModel>();
  107. modelObject->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
  108. modelObject->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
  109. modelObject->SetCastShadows(true);
  110. // Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
  111. // animation, The alternative would be to use an AnimationController component which updates the animation automatically,
  112. // but we need to update the model's position manually in any case
  113. Animation* walkAnimation = cache->GetResource<Animation>("Models/Jack_Walk.ani");
  114. AnimationState* state = modelObject->AddAnimationState(walkAnimation);
  115. // The state would fail to create (return null) if the animation was not found
  116. if (state)
  117. {
  118. // Enable full blending weight and looping
  119. state->SetWeight(1.0f);
  120. state->SetLooped(true);
  121. state->SetTime(Random(walkAnimation->GetLength()));
  122. }
  123. // Create our custom Mover component that will move & animate the model during each frame's update
  124. Mover* mover = modelNode->CreateComponent<Mover>();
  125. mover->SetParameters(MODEL_MOVE_SPEED, MODEL_ROTATE_SPEED, bounds);
  126. }
  127. // Create the camera. Limit far clip distance to match the fog
  128. cameraNode_ = scene_->CreateChild("Camera");
  129. Camera* camera = cameraNode_->CreateComponent<Camera>();
  130. camera->SetFarClip(300.0f);
  131. // Set an initial position for the camera scene node above the plane
  132. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  133. }
  134. void SkeletalAnimation::CreateInstructions()
  135. {
  136. SimpleCreateInstructions(
  137. "Use WASD keys and mouse/touch to move\n"
  138. "Space to toggle debug geometry"
  139. );
  140. }
  141. void SkeletalAnimation::SetupViewport()
  142. {
  143. Renderer* renderer = GetSubsystem<Renderer>();
  144. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  145. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  146. renderer->SetViewport(0, viewport);
  147. }
  148. void SkeletalAnimation::SubscribeToEvents()
  149. {
  150. // Subscribe HandleUpdate() function for processing update events
  151. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(SkeletalAnimation, HandleUpdate));
  152. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, sent after Renderer subsystem is
  153. // done with defining the draw calls for the viewports (but before actually executing them.) We will request debug geometry
  154. // rendering during that event
  155. SubscribeToEvent(E_POSTRENDERUPDATE, ATOMIC_HANDLER(SkeletalAnimation, HandlePostRenderUpdate));
  156. }
  157. void SkeletalAnimation::MoveCamera(float timeStep)
  158. {
  159. Input* input = GetSubsystem<Input>();
  160. // Movement speed as world units per second
  161. const float MOVE_SPEED = 20.0f;
  162. // Mouse sensitivity as degrees per pixel
  163. const float MOUSE_SENSITIVITY = 0.1f;
  164. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  165. IntVector2 mouseMove = input->GetMouseMove();
  166. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  167. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  168. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  169. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  170. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  171. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  172. if (input->GetKeyDown(KEY_W))
  173. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  174. if (input->GetKeyDown(KEY_S))
  175. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  176. if (input->GetKeyDown(KEY_A))
  177. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  178. if (input->GetKeyDown(KEY_D))
  179. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  180. // Toggle debug geometry with space
  181. if (input->GetKeyPress(KEY_SPACE))
  182. drawDebug_ = !drawDebug_;
  183. }
  184. void SkeletalAnimation::HandleUpdate(StringHash eventType, VariantMap& eventData)
  185. {
  186. using namespace Update;
  187. // Take the frame time step, which is stored as a float
  188. float timeStep = eventData[P_TIMESTEP].GetFloat();
  189. // Move the camera, scale movement with time step
  190. MoveCamera(timeStep);
  191. }
  192. void SkeletalAnimation::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  193. {
  194. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  195. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  196. // bones properly
  197. if (drawDebug_)
  198. GetSubsystem<Renderer>()->DrawDebugGeometry(false);
  199. }