CharacterDemo.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. #include "AnimatedModel.h"
  2. #include "AnimationController.h"
  3. #include "Camera.h"
  4. #include "Character.h"
  5. #include "CollisionShape.h"
  6. #include "Controls.h"
  7. #include "CoreEvents.h"
  8. #include "Engine.h"
  9. #include "Font.h"
  10. #include "Input.h"
  11. #include "Light.h"
  12. #include "Material.h"
  13. #include "Model.h"
  14. #include "Octree.h"
  15. #include "PhysicsWorld.h"
  16. #include "ProcessUtils.h"
  17. #include "Renderer.h"
  18. #include "RigidBody.h"
  19. #include "ResourceCache.h"
  20. #include "Scene.h"
  21. #include "StaticModel.h"
  22. #include "Text.h"
  23. #include "UI.h"
  24. #include "Zone.h"
  25. #include "CharacterDemo.h"
  26. #include "DebugNew.h"
  27. const float CAMERA_MIN_DIST = 1.0f;
  28. const float CAMERA_MAX_DIST = 5.0f;
  29. DEFINE_APPLICATION_MAIN(CharacterDemo)
  30. CharacterDemo::CharacterDemo(Context* context) :
  31. Sample(context),
  32. firstPerson_(false)
  33. {
  34. // Register factory for the Character component so it can be created via CreateComponent
  35. context_->RegisterFactory<Character>();
  36. }
  37. void CharacterDemo::Start()
  38. {
  39. // Execute base class startup
  40. Sample::Start();
  41. // Create static scene content
  42. CreateScene();
  43. // Create the controllable character
  44. CreateCharacter();
  45. // Create the UI content
  46. CreateInstructions();
  47. // Subscribe to necessary events
  48. SubscribeToEvents();
  49. }
  50. void CharacterDemo::CreateScene()
  51. {
  52. ResourceCache* cache = GetSubsystem<ResourceCache>();
  53. scene_ = new Scene(context_);
  54. // Create scene subsystem components
  55. scene_->CreateComponent<Octree>();
  56. scene_->CreateComponent<PhysicsWorld>();
  57. // Create camera and define viewport. Camera does not necessarily have to belong to the scene
  58. cameraNode_ = new Node(context_);
  59. Camera* camera = cameraNode_->CreateComponent<Camera>();
  60. GetSubsystem<Renderer>()->SetViewport(0, new Viewport(context_, scene_, camera));
  61. // Create static scene content. First create a zone for ambient lighting and fog control
  62. Node* zoneNode = scene_->CreateChild("Zone");
  63. Zone* zone = zoneNode->CreateComponent<Zone>();
  64. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  65. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  66. zone->SetFogStart(100.0f);
  67. zone->SetFogEnd(300.0f);
  68. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  69. // Create a directional light with cascaded shadow mapping
  70. Node* lightNode = scene_->CreateChild("DirectionalLight");
  71. lightNode->SetDirection(Vector3(0.3f, -0.5f, 0.425f));
  72. Light* light = lightNode->CreateComponent<Light>();
  73. light->SetLightType(LIGHT_DIRECTIONAL);
  74. light->SetCastShadows(true);
  75. light->SetShadowBias(BiasParameters(0.0001f, 0.5f));
  76. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  77. light->SetSpecularIntensity(0.5f);
  78. // Create the floor object
  79. Node* floorNode = scene_->CreateChild("Floor");
  80. floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
  81. floorNode->SetScale(Vector3(200.0f, 1.0f, 200.0f));
  82. StaticModel* object = floorNode->CreateComponent<StaticModel>();
  83. object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  84. object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  85. RigidBody* body = floorNode->CreateComponent<RigidBody>();
  86. // Use collision layer bit 2 to mark world scenery. This is what we will raycast against to prevent camera from going
  87. // inside geometry
  88. body->SetCollisionLayer(2);
  89. CollisionShape* shape = floorNode->CreateComponent<CollisionShape>();
  90. shape->SetBox(Vector3::ONE);
  91. // Create mushrooms of varying sizes
  92. const unsigned NUM_MUSHROOMS = 60;
  93. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  94. {
  95. Node* objectNode = scene_->CreateChild("Mushroom");
  96. objectNode->SetPosition(Vector3(Random(180.0f) - 90.0f, 0.0f, Random(180.0f) - 90.0f));
  97. objectNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  98. objectNode->SetScale(2.0f + Random(5.0f));
  99. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  100. object->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  101. object->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  102. object->SetCastShadows(true);
  103. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  104. body->SetCollisionLayer(2);
  105. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  106. shape->SetTriangleMesh(object->GetModel(), 0);
  107. }
  108. // Create movable boxes. Let them fall from the sky at first
  109. const unsigned NUM_SMALL_BOXES = 100;
  110. for (unsigned i = 0; i < NUM_SMALL_BOXES; ++i)
  111. {
  112. float scale = Random(2.0f) + 0.5f;
  113. Node* objectNode = scene_->CreateChild("Box");
  114. objectNode->SetPosition(Vector3(Random(180.0f) - 90.0f, Random(10.0f) + 10.0f, Random(180.0f) - 90.0f));
  115. objectNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
  116. objectNode->SetScale(scale);
  117. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  118. object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  119. object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  120. object->SetCastShadows(true);
  121. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  122. body->SetCollisionLayer(2);
  123. // Bigger boxes will be heavier and harder to move
  124. body->SetMass(scale * 2.0f);
  125. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  126. shape->SetBox(Vector3::ONE);
  127. }
  128. }
  129. void CharacterDemo::CreateCharacter()
  130. {
  131. ResourceCache* cache = GetSubsystem<ResourceCache>();
  132. Node* objectNode = scene_->CreateChild("Jack");
  133. objectNode->SetPosition(Vector3(0.0f, 1.0f, 0.0f));
  134. // Create the rendering component + animation controller
  135. AnimatedModel* object = objectNode->CreateComponent<AnimatedModel>();
  136. object->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
  137. object->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
  138. object->SetCastShadows(true);
  139. objectNode->CreateComponent<AnimationController>();
  140. // Create rigidbody, and set non-zero mass so that the body becomes dynamic
  141. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  142. body->SetCollisionLayer(1);
  143. body->SetMass(1.0f);
  144. // Set zero angular factor so that physics doesn't turn the character on its own.
  145. // Instead we will control the character yaw manually
  146. body->SetAngularFactor(Vector3::ZERO);
  147. // Set the rigidbody to signal collision also when in rest, so that we get ground collisions properly
  148. body->SetCollisionEventMode(COLLISION_ALWAYS);
  149. // Set a capsule shape for collision
  150. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  151. shape->SetCapsule(0.7f, 1.8f, Vector3(0.0f, 0.9f, 0.0f));
  152. // Create the character logic component, which takes care of steering the rigidbody
  153. // Remember it so that we can set the controls. Use a WeakPtr because the scene hierarchy already owns it
  154. // and keeps it alive as long as it's not removed from the hierarchy
  155. character_ = objectNode->CreateComponent<Character>();
  156. }
  157. void CharacterDemo::CreateInstructions()
  158. {
  159. ResourceCache* cache = GetSubsystem<ResourceCache>();
  160. UI* ui = GetSubsystem<UI>();
  161. // Construct new Text object, set string to display and font to use
  162. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  163. instructionText->SetText(
  164. "Use WASD keys and mouse to move\n"
  165. "Space to jump, F to toggle 1st/3rd person"
  166. );
  167. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  168. // The text has multiple rows. Center them in relation to each other
  169. instructionText->SetTextAlignment(HA_CENTER);
  170. // Position the text relative to the screen center
  171. instructionText->SetHorizontalAlignment(HA_CENTER);
  172. instructionText->SetVerticalAlignment(VA_CENTER);
  173. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  174. }
  175. void CharacterDemo::SubscribeToEvents()
  176. {
  177. // Subscribe to Update event for setting the character controls before physics simulation
  178. SubscribeToEvent(E_UPDATE, HANDLER(CharacterDemo, HandleUpdate));
  179. // Subscribe to PostUpdate event for updating the camera position after physics simulation
  180. SubscribeToEvent(E_POSTUPDATE, HANDLER(CharacterDemo, HandlePostUpdate));
  181. }
  182. void CharacterDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  183. {
  184. using namespace Update;
  185. float timeStep = eventData[P_TIMESTEP].GetFloat();
  186. Input* input = GetSubsystem<Input>();
  187. if (character_)
  188. {
  189. UI* ui = GetSubsystem<UI>();
  190. // Get movement controls and assign them to the character logic component. If UI has a focused element, clear controls
  191. if (!ui->GetFocusElement())
  192. {
  193. character_->controls_.Set(CTRL_UP, input->GetKeyDown('W'));
  194. character_->controls_.Set(CTRL_DOWN, input->GetKeyDown('S'));
  195. character_->controls_.Set(CTRL_LEFT, input->GetKeyDown('A'));
  196. character_->controls_.Set(CTRL_RIGHT, input->GetKeyDown('D'));
  197. character_->controls_.Set(CTRL_JUMP, input->GetKeyDown(KEY_SPACE));
  198. // Add character yaw & pitch from the mouse motion
  199. character_->controls_.yaw_ += (float)input->GetMouseMoveX() * YAW_SENSITIVITY;
  200. character_->controls_.pitch_ += (float)input->GetMouseMoveY() * YAW_SENSITIVITY;
  201. // Limit pitch
  202. character_->controls_.pitch_ = Clamp(character_->controls_.pitch_, -80.0f, 80.0f);
  203. // Switch between 1st and 3rd person
  204. if (input->GetKeyPress('F'))
  205. firstPerson_ = !firstPerson_;
  206. }
  207. else
  208. character_->controls_.Set(CTRL_UP | CTRL_DOWN | CTRL_LEFT | CTRL_RIGHT | CTRL_JUMP, false);
  209. // Set rotation already here so that it's updated every rendering frame instead of every physics frame
  210. character_->GetNode()->SetRotation(Quaternion(character_->controls_.yaw_, Vector3::UP));
  211. }
  212. }
  213. void CharacterDemo::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  214. {
  215. if (!character_)
  216. return;
  217. Node* characterNode = character_->GetNode();
  218. // Get camera lookat dir from character yaw + pitch
  219. Quaternion rot = characterNode->GetRotation();
  220. Quaternion dir = rot * Quaternion(character_->controls_.pitch_, Vector3::RIGHT);
  221. if (firstPerson_)
  222. {
  223. // First person camera: position to the head bone + offset slightly forward & up
  224. Node* headNode = characterNode->GetChild("Bip01_Head", true);
  225. if (headNode)
  226. {
  227. cameraNode_->SetPosition(headNode->GetWorldPosition() + rot * Vector3(0.0f, 0.15f, 0.2f));
  228. cameraNode_->SetRotation(dir);
  229. }
  230. }
  231. else
  232. {
  233. // Third person camera: position behind the character
  234. Vector3 aimPoint = characterNode->GetPosition() + rot * Vector3(0.0f, 1.7f, 0.0f);
  235. // Collide camera ray with static physics objects (layer bitmask 2) to ensure we see the character properly
  236. Vector3 rayDir = dir * Vector3::BACK;
  237. float rayDistance = CAMERA_MAX_DIST;
  238. PhysicsRaycastResult result;
  239. scene_->GetComponent<PhysicsWorld>()->RaycastSingle(result, Ray(aimPoint, rayDir), rayDistance, 2);
  240. if (result.body_)
  241. rayDistance = Min(rayDistance, result.distance_);
  242. rayDistance = Clamp(rayDistance, CAMERA_MIN_DIST, CAMERA_MAX_DIST);
  243. cameraNode_->SetPosition(aimPoint + rayDir * rayDistance);
  244. cameraNode_->SetRotation(dir);
  245. }
  246. }