InverseKinematics.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. //
  2. // Copyright (c) 2008-2020 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/Engine/Engine.h>
  24. #include <Urho3D/Graphics/AnimatedModel.h>
  25. #include <Urho3D/Graphics/AnimationController.h>
  26. #include <Urho3D/Graphics/Camera.h>
  27. #include <Urho3D/Graphics/Graphics.h>
  28. #include <Urho3D/Graphics/Material.h>
  29. #include <Urho3D/Graphics/Octree.h>
  30. #include <Urho3D/Graphics/DebugRenderer.h>
  31. #include <Urho3D/Graphics/RibbonTrail.h>
  32. #include <Urho3D/IK/IKEffector.h>
  33. #include <Urho3D/IK/IKSolver.h>
  34. #include <Urho3D/Input/Input.h>
  35. #include <Urho3D/Math/Matrix2.h>
  36. #include <Urho3D/Physics/PhysicsWorld.h>
  37. #include <Urho3D/Physics/CollisionShape.h>
  38. #include <Urho3D/Physics/RigidBody.h>
  39. #include <Urho3D/Resource/ResourceCache.h>
  40. #include <Urho3D/UI/Font.h>
  41. #include <Urho3D/UI/Text.h>
  42. #include <Urho3D/UI/UI.h>
  43. #include <Urho3D/UI/Text3D.h>
  44. #include "InverseKinematics.h"
  45. #include <Urho3D/DebugNew.h>
  46. URHO3D_DEFINE_APPLICATION_MAIN(InverseKinematics)
  47. InverseKinematics::InverseKinematics(Context* context) :
  48. Sample(context)
  49. {
  50. }
  51. void InverseKinematics::Start()
  52. {
  53. // Execute base class startup
  54. Sample::Start();
  55. // Create the scene content
  56. CreateScene();
  57. // Create the UI content
  58. CreateInstructions();
  59. // Setup the viewport for displaying the scene
  60. SetupViewport();
  61. // Hook up to the frame update events
  62. SubscribeToEvents();
  63. // Set the mouse mode to use in the sample
  64. Sample::InitMouseMode(MM_RELATIVE);
  65. GetSubsystem<Input>()->SetMouseVisible(true);
  66. }
  67. void InverseKinematics::CreateScene()
  68. {
  69. auto* cache = GetSubsystem<ResourceCache>();
  70. scene_ = new Scene(context_);
  71. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  72. scene_->CreateComponent<Octree>();
  73. scene_->CreateComponent<DebugRenderer>();
  74. scene_->CreateComponent<PhysicsWorld>();
  75. // Create scene node & StaticModel component for showing a static plane
  76. floorNode_ = scene_->CreateChild("Plane");
  77. floorNode_->SetScale(Vector3(50.0f, 1.0f, 50.0f));
  78. auto* planeObject = floorNode_->CreateComponent<StaticModel>();
  79. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  80. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  81. // Set up collision, we need to raycast to determine foot height
  82. floorNode_->CreateComponent<RigidBody>();
  83. auto* col = floorNode_->CreateComponent<CollisionShape>();
  84. col->SetBox(Vector3(1, 0, 1));
  85. // Create a directional light to the world.
  86. Node* lightNode = scene_->CreateChild("DirectionalLight");
  87. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f)); // The direction vector does not need to be normalized
  88. auto* light = lightNode->CreateComponent<Light>();
  89. light->SetLightType(LIGHT_DIRECTIONAL);
  90. light->SetCastShadows(true);
  91. light->SetShadowBias(BiasParameters(0.00005f, 0.5f));
  92. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  93. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  94. // Load Jack model
  95. jackNode_ = scene_->CreateChild("Jack");
  96. jackNode_->SetRotation(Quaternion(0.0f, 270.0f, 0.0f));
  97. auto* jack = jackNode_->CreateComponent<AnimatedModel>();
  98. jack->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
  99. jack->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
  100. jack->SetCastShadows(true);
  101. // Create animation controller and play walk animation
  102. jackAnimCtrl_ = jackNode_->CreateComponent<AnimationController>();
  103. jackAnimCtrl_->PlayExclusive("Models/Jack_Walk.ani", 0, true, 0.0f);
  104. // We need to attach two inverse kinematic effectors to Jack's feet to
  105. // control the grounding.
  106. leftFoot_ = jackNode_->GetChild("Bip01_L_Foot", true);
  107. rightFoot_ = jackNode_->GetChild("Bip01_R_Foot", true);
  108. leftEffector_ = leftFoot_->CreateComponent<IKEffector>();
  109. rightEffector_ = rightFoot_->CreateComponent<IKEffector>();
  110. // Control 2 segments up to the hips
  111. leftEffector_->SetChainLength(2);
  112. rightEffector_->SetChainLength(2);
  113. // For the effectors to work, an IKSolver needs to be attached to one of
  114. // the parent nodes. Typically, you want to place the solver as close as
  115. // possible to the effectors for optimal performance. Since in this case
  116. // we're solving the legs only, we can place the solver at the spine.
  117. Node* spine = jackNode_->GetChild("Bip01_Spine", true);
  118. solver_ = spine->CreateComponent<IKSolver>();
  119. // Two-bone solver is more efficient and more stable than FABRIK (but only
  120. // works for two bones, obviously).
  121. solver_->SetAlgorithm(IKSolver::TWO_BONE);
  122. // Disable auto-solving, which means we need to call Solve() manually
  123. solver_->SetFeature(IKSolver::AUTO_SOLVE, false);
  124. // Only enable this so the debug draw shows us the pose before solving.
  125. // This should NOT be enabled for any other reason (it does nothing and is
  126. // a waste of performance).
  127. solver_->SetFeature(IKSolver::UPDATE_ORIGINAL_POSE, true);
  128. // Create the camera.
  129. cameraRotateNode_ = scene_->CreateChild("CameraRotate");
  130. cameraNode_ = cameraRotateNode_->CreateChild("Camera");
  131. cameraNode_->CreateComponent<Camera>();
  132. // Set an initial position for the camera scene node above the plane
  133. cameraNode_->SetPosition(Vector3(0, 0, -4));
  134. cameraRotateNode_->SetPosition(Vector3(0, 0.4, 0));
  135. pitch_ = 20;
  136. yaw_ = 50;
  137. }
  138. void InverseKinematics::CreateInstructions()
  139. {
  140. auto* cache = GetSubsystem<ResourceCache>();
  141. auto* ui = GetSubsystem<UI>();
  142. // Construct new Text object, set string to display and font to use
  143. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  144. instructionText->SetText("Left-Click and drag to look around\nRight-Click and drag to change incline\nPress space to reset floor\nPress D to draw debug geometry");
  145. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  146. // Position the text relative to the screen center
  147. instructionText->SetHorizontalAlignment(HA_CENTER);
  148. instructionText->SetVerticalAlignment(VA_CENTER);
  149. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  150. }
  151. void InverseKinematics::SetupViewport()
  152. {
  153. auto* renderer = GetSubsystem<Renderer>();
  154. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
  155. // at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
  156. // use, but now we just use full screen and default render path configured in the engine command line options
  157. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  158. renderer->SetViewport(0, viewport);
  159. }
  160. void InverseKinematics::UpdateCameraAndFloor(float /*timeStep*/)
  161. {
  162. // Do not move if the UI has a focused element (the console)
  163. if (GetSubsystem<UI>()->GetFocusElement())
  164. return;
  165. auto* input = GetSubsystem<Input>();
  166. // Mouse sensitivity as degrees per pixel
  167. const float MOUSE_SENSITIVITY = 0.1f;
  168. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  169. if (input->GetMouseButtonDown(MOUSEB_LEFT))
  170. {
  171. IntVector2 mouseMove = input->GetMouseMove();
  172. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  173. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  174. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  175. }
  176. if (input->GetMouseButtonDown(MOUSEB_RIGHT))
  177. {
  178. IntVector2 mouseMoveInt = input->GetMouseMove();
  179. Vector2 mouseMove = Matrix2(
  180. -Cos(yaw_), Sin(yaw_),
  181. Sin(yaw_), Cos(yaw_)
  182. ) * Vector2(mouseMoveInt.y_, -mouseMoveInt.x_);
  183. floorPitch_ += MOUSE_SENSITIVITY * mouseMove.x_;
  184. floorPitch_ = Clamp(floorPitch_, -90.0f, 90.0f);
  185. floorRoll_ += MOUSE_SENSITIVITY * mouseMove.y_;
  186. }
  187. if (input->GetKeyPress(KEY_SPACE))
  188. {
  189. floorPitch_ = 0;
  190. floorRoll_ = 0;
  191. }
  192. if (input->GetKeyPress(KEY_D))
  193. {
  194. drawDebug_ = !drawDebug_;
  195. }
  196. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  197. cameraRotateNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  198. floorNode_->SetRotation(Quaternion(floorPitch_, 0, floorRoll_));
  199. }
  200. void InverseKinematics::SubscribeToEvents()
  201. {
  202. // Subscribe HandleUpdate() function for processing update events
  203. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(InverseKinematics, HandleUpdate));
  204. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(InverseKinematics, HandlePostRenderUpdate));
  205. SubscribeToEvent(E_SCENEDRAWABLEUPDATEFINISHED, URHO3D_HANDLER(InverseKinematics, HandleSceneDrawableUpdateFinished));
  206. }
  207. void InverseKinematics::HandleUpdate(StringHash /*eventType*/, VariantMap& eventData)
  208. {
  209. using namespace Update;
  210. // Take the frame time step, which is stored as a float
  211. float timeStep = eventData[P_TIMESTEP].GetFloat();
  212. // Move the camera, scale movement with time step
  213. UpdateCameraAndFloor(timeStep);
  214. }
  215. void InverseKinematics::HandlePostRenderUpdate(StringHash /*eventType*/, VariantMap& eventData)
  216. {
  217. if (drawDebug_)
  218. solver_->DrawDebugGeometry(false);
  219. }
  220. void InverseKinematics::HandleSceneDrawableUpdateFinished(StringHash /*eventType*/, VariantMap& eventData)
  221. {
  222. auto* phyWorld = scene_->GetComponent<PhysicsWorld>();
  223. Vector3 leftFootPosition = leftFoot_->GetWorldPosition();
  224. Vector3 rightFootPosition = rightFoot_->GetWorldPosition();
  225. // Cast ray down to get the normal of the underlying surface
  226. PhysicsRaycastResult result;
  227. phyWorld->RaycastSingle(result, Ray(leftFootPosition + Vector3(0, 1, 0), Vector3(0, -1, 0)), 2);
  228. if (result.body_)
  229. {
  230. // Cast again, but this time along the normal. Set the target position
  231. // to the ray intersection
  232. phyWorld->RaycastSingle(result, Ray(leftFootPosition + result.normal_, -result.normal_), 2);
  233. // The foot node has an offset relative to the root node
  234. float footOffset = leftFoot_->GetWorldPosition().y_ - jackNode_->GetWorldPosition().y_;
  235. leftEffector_->SetTargetPosition(result.position_ + result.normal_ * footOffset);
  236. // Rotate foot according to normal
  237. leftFoot_->Rotate(Quaternion(Vector3(0, 1, 0), result.normal_), TS_WORLD);
  238. }
  239. // Same deal with the right foot
  240. phyWorld->RaycastSingle(result, Ray(rightFootPosition + Vector3(0, 1, 0), Vector3(0, -1, 0)), 2);
  241. if (result.body_)
  242. {
  243. phyWorld->RaycastSingle(result, Ray(rightFootPosition + result.normal_, -result.normal_), 2);
  244. float footOffset = rightFoot_->GetWorldPosition().y_ - jackNode_->GetWorldPosition().y_;
  245. rightEffector_->SetTargetPosition(result.position_ + result.normal_ * footOffset);
  246. rightFoot_->Rotate(Quaternion(Vector3(0, 1, 0), result.normal_), TS_WORLD);
  247. }
  248. solver_->Solve();
  249. }