SkeletalAnimation.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Core/CoreEvents.h>
  4. #include <Urho3D/Engine/Engine.h>
  5. #include <Urho3D/Graphics/AnimatedModel.h>
  6. #include <Urho3D/Graphics/Animation.h>
  7. #include <Urho3D/Graphics/AnimationState.h>
  8. #include <Urho3D/Graphics/Camera.h>
  9. #include <Urho3D/Graphics/DebugRenderer.h>
  10. #include <Urho3D/Graphics/Graphics.h>
  11. #include <Urho3D/Graphics/Light.h>
  12. #include <Urho3D/Graphics/Material.h>
  13. #include <Urho3D/Graphics/Octree.h>
  14. #include <Urho3D/Graphics/Renderer.h>
  15. #include <Urho3D/Graphics/Zone.h>
  16. #include <Urho3D/Graphics/RenderPath.h>
  17. #include <Urho3D/Input/Input.h>
  18. #include <Urho3D/Resource/ResourceCache.h>
  19. #include <Urho3D/Scene/Scene.h>
  20. #include <Urho3D/UI/Font.h>
  21. #include <Urho3D/UI/Text.h>
  22. #include <Urho3D/UI/UI.h>
  23. #include "Mover.h"
  24. #include "SkeletalAnimation.h"
  25. #include <Urho3D/DebugNew.h>
  26. URHO3D_DEFINE_APPLICATION_MAIN(SkeletalAnimation)
  27. SkeletalAnimation::SkeletalAnimation(Context* context) :
  28. Sample(context),
  29. drawDebug_(false)
  30. {
  31. // Register an object factory for our custom Mover component so that we can create them to scene nodes
  32. context->RegisterFactory<Mover>();
  33. }
  34. void SkeletalAnimation::Start()
  35. {
  36. // Execute base class startup
  37. Sample::Start();
  38. // Create the scene content
  39. CreateScene();
  40. // Create the UI content
  41. CreateInstructions();
  42. // Setup the viewport for displaying the scene
  43. SetupViewport();
  44. // Hook up to the frame update and render post-update events
  45. SubscribeToEvents();
  46. // Set the mouse mode to use in the sample
  47. Sample::InitMouseMode(MM_ABSOLUTE);
  48. }
  49. void SkeletalAnimation::CreateScene()
  50. {
  51. auto* cache = GetSubsystem<ResourceCache>();
  52. scene_ = new Scene(context_);
  53. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  54. // Also create a DebugRenderer component so that we can draw debug geometry
  55. scene_->CreateComponent<Octree>();
  56. scene_->CreateComponent<DebugRenderer>();
  57. // Create scene node & StaticModel component for showing a static plane
  58. Node* planeNode = scene_->CreateChild("Plane");
  59. planeNode->SetScale(Vector3(50.0f, 1.0f, 50.0f));
  60. auto* planeObject = planeNode->CreateComponent<StaticModel>();
  61. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  62. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  63. // Create a Zone component for ambient lighting & fog control
  64. Node* zoneNode = scene_->CreateChild("Zone");
  65. auto* zone = zoneNode->CreateComponent<Zone>();
  66. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  67. zone->SetAmbientColor(Color(0.5f, 0.5f, 0.5f));
  68. zone->SetFogColor(Color(0.4f, 0.5f, 0.8f));
  69. zone->SetFogStart(100.0f);
  70. zone->SetFogEnd(300.0f);
  71. // Create a directional light to the world. Enable cascaded shadows on it
  72. Node* lightNode = scene_->CreateChild("DirectionalLight");
  73. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  74. auto* light = lightNode->CreateComponent<Light>();
  75. light->SetLightType(LIGHT_DIRECTIONAL);
  76. light->SetCastShadows(true);
  77. light->SetColor(Color(0.5f, 0.5f, 0.5f));
  78. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  79. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  80. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  81. // Create animated models
  82. const unsigned NUM_MODELS = 30;
  83. const float MODEL_MOVE_SPEED = 2.0f;
  84. const float MODEL_ROTATE_SPEED = 100.0f;
  85. const BoundingBox bounds(Vector3(-20.0f, 0.0f, -20.0f), Vector3(20.0f, 0.0f, 20.0f));
  86. for (unsigned i = 0; i < NUM_MODELS; ++i)
  87. {
  88. Node* modelNode = scene_->CreateChild("Jill");
  89. modelNode->SetPosition(Vector3(Random(40.0f) - 20.0f, 0.0f, Random(40.0f) - 20.0f));
  90. modelNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  91. auto* modelObject = modelNode->CreateComponent<AnimatedModel>();
  92. modelObject->SetModel(cache->GetResource<Model>("Models/Kachujin/Kachujin.mdl"));
  93. modelObject->SetMaterial(cache->GetResource<Material>("Models/Kachujin/Materials/Kachujin.xml"));
  94. modelObject->SetCastShadows(true);
  95. // Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
  96. // animation, The alternative would be to use an AnimationController component which updates the animation automatically,
  97. // but we need to update the model's position manually in any case
  98. auto* walkAnimation = cache->GetResource<Animation>("Models/Kachujin/Kachujin_Walk.ani");
  99. AnimationState* state = modelObject->AddAnimationState(walkAnimation);
  100. // The state would fail to create (return null) if the animation was not found
  101. if (state)
  102. {
  103. // Enable full blending weight and looping
  104. state->SetWeight(1.0f);
  105. state->SetLooped(true);
  106. state->SetTime(Random(walkAnimation->GetLength()));
  107. }
  108. // Create our custom Mover component that will move & animate the model during each frame's update
  109. auto* mover = modelNode->CreateComponent<Mover>();
  110. mover->SetParameters(MODEL_MOVE_SPEED, MODEL_ROTATE_SPEED, bounds);
  111. #ifdef URHO3D_GLES3
  112. Node* nLight = modelNode->CreateChild("Light", LOCAL);
  113. nLight->SetPosition(Vector3(1.0f, 2.0f, 1.0f));
  114. nLight->LookAt(Vector3::ZERO, Vector3::UP, TransformSpace::Parent);
  115. Light* light = nLight->CreateComponent<Light>();
  116. light->SetLightType(LIGHT_SPOT);
  117. light->SetColor(Color(0.5f + Random(0.5f), 0.5f + Random(0.5f), 0.5f + Random(0.5f)));
  118. #endif
  119. }
  120. // Create the camera. Limit far clip distance to match the fog
  121. cameraNode_ = scene_->CreateChild("Camera");
  122. auto* camera = cameraNode_->CreateComponent<Camera>();
  123. camera->SetFarClip(300.0f);
  124. // Set an initial position for the camera scene node above the plane
  125. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  126. #ifdef URHO3D_GLES3
  127. CreateLights();
  128. #endif
  129. }
  130. #ifdef URHO3D_GLES3
  131. void SkeletalAnimation::CreateLights() {
  132. for (unsigned i = 0; i < 40; i++) {
  133. Node* nLight = scene_->CreateChild("Light", LOCAL);
  134. Vector3 pos(Random(40.0f) - 20.0f, 1.0f + Random(1.0f), Random(40.0f) - 20.0f);
  135. nLight->SetPosition(pos);
  136. pos.y_ = 0;
  137. pos.x_ += Random(2.0f) - 1.0f;
  138. pos.z_ += Random(2.0f) - 1.0f;
  139. nLight->LookAt(pos);
  140. Light* light = nLight->CreateComponent<Light>();
  141. light->SetLightType(LIGHT_SPOT);
  142. light->SetColor(Color(0.5f + Random(0.5f), 0.5f + Random(0.5f), 0.5f + Random(0.5f)));
  143. }
  144. }
  145. #endif
  146. void SkeletalAnimation::CreateInstructions()
  147. {
  148. auto* cache = GetSubsystem<ResourceCache>();
  149. auto* ui = GetSubsystem<UI>();
  150. // Construct new Text object, set string to display and font to use
  151. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  152. instructionText->SetText(
  153. "Use WASD keys and mouse/touch to move\n"
  154. "Space to toggle debug geometry"
  155. );
  156. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  157. // The text has multiple rows. Center them in relation to each other
  158. instructionText->SetTextAlignment(HA_CENTER);
  159. // Position the text relative to the screen center
  160. instructionText->SetHorizontalAlignment(HA_CENTER);
  161. instructionText->SetVerticalAlignment(VA_CENTER);
  162. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  163. }
  164. void SkeletalAnimation::SetupViewport()
  165. {
  166. auto* renderer = GetSubsystem<Renderer>();
  167. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  168. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  169. #ifdef URHO3D_GLES3
  170. SharedPtr<RenderPath> rp(new RenderPath);
  171. auto* cache = GetSubsystem<ResourceCache>();
  172. rp->Load(cache->GetResource<XMLFile>("RenderPaths/Deferred.xml"));
  173. viewport->SetRenderPath(rp);
  174. #endif
  175. renderer->SetViewport(0, viewport);
  176. }
  177. void SkeletalAnimation::SubscribeToEvents()
  178. {
  179. // Subscribe HandleUpdate() function for processing update events
  180. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(SkeletalAnimation, HandleUpdate));
  181. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, sent after Renderer subsystem is
  182. // done with defining the draw calls for the viewports (but before actually executing them.) We will request debug geometry
  183. // rendering during that event
  184. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(SkeletalAnimation, HandlePostRenderUpdate));
  185. }
  186. void SkeletalAnimation::MoveCamera(float timeStep)
  187. {
  188. // Do not move if the UI has a focused element (the console)
  189. if (GetSubsystem<UI>()->GetFocusElement())
  190. return;
  191. auto* input = GetSubsystem<Input>();
  192. // Movement speed as world units per second
  193. const float MOVE_SPEED = 20.0f;
  194. // Mouse sensitivity as degrees per pixel
  195. const float MOUSE_SENSITIVITY = 0.1f;
  196. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  197. IntVector2 mouseMove = input->GetMouseMove();
  198. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  199. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  200. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  201. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  202. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  203. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  204. if (input->GetKeyDown(KEY_W))
  205. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  206. if (input->GetKeyDown(KEY_S))
  207. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  208. if (input->GetKeyDown(KEY_A))
  209. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  210. if (input->GetKeyDown(KEY_D))
  211. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  212. // Toggle debug geometry with space
  213. if (input->GetKeyPress(KEY_SPACE))
  214. drawDebug_ = !drawDebug_;
  215. }
  216. void SkeletalAnimation::HandleUpdate(StringHash eventType, VariantMap& eventData)
  217. {
  218. using namespace Update;
  219. // Take the frame time step, which is stored as a float
  220. float timeStep = eventData[P_TIMESTEP].GetFloat();
  221. // Move the camera, scale movement with time step
  222. MoveCamera(timeStep);
  223. }
  224. void SkeletalAnimation::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  225. {
  226. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  227. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  228. // bones properly
  229. if (drawDebug_)
  230. GetSubsystem<Renderer>()->DrawDebugGeometry(false);
  231. }