CharacterDemo.cpp 14 KB

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