CharacterDemo.cpp 16 KB

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