CharacterDemo.cpp 13 KB

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