CharacterDemo.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/Core/CoreEvents.h>
  24. #include <Atomic/Core/ProcessUtils.h>
  25. #include <Atomic/Engine/Engine.h>
  26. #include <Atomic/Graphics/AnimatedModel.h>
  27. #include <Atomic/Graphics/AnimationController.h>
  28. #include <Atomic/Graphics/Camera.h>
  29. #include <Atomic/Graphics/Light.h>
  30. #include <Atomic/Graphics/Material.h>
  31. #include <Atomic/Graphics/Octree.h>
  32. #include <Atomic/Graphics/Renderer.h>
  33. #include <Atomic/Graphics/Zone.h>
  34. #include <Atomic/Input/Controls.h>
  35. #include <Atomic/Input/Input.h>
  36. #include <Atomic/IO/FileSystem.h>
  37. #include <Atomic/Physics/CollisionShape.h>
  38. #include <Atomic/Physics/PhysicsWorld.h>
  39. #include <Atomic/Physics/RigidBody.h>
  40. #include <Atomic/Resource/ResourceCache.h>
  41. #include <Atomic/Scene/SceneEvents.h>
  42. #include <Atomic/Scene/Scene.h>
  43. #include "Character.h"
  44. #include "CharacterDemo.h"
  45. #include "Touch.h"
  46. #include <Atomic/DebugNew.h>
  47. CharacterDemo::CharacterDemo(Context* context) :
  48. Sample(context),
  49. firstPerson_(false)
  50. {
  51. // Register factory and attributes for the Character component so it can be created via CreateComponent, and loaded / saved
  52. Character::RegisterObject(context);
  53. }
  54. CharacterDemo::~CharacterDemo()
  55. {
  56. }
  57. void CharacterDemo::Start()
  58. {
  59. // Execute base class startup
  60. Sample::Start();
  61. if (touchEnabled_)
  62. touch_ = new Touch(context_, TOUCH_SENSITIVITY);
  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. // Set the mouse mode to use in the sample
  72. Sample::InitMouseMode(MM_RELATIVE);
  73. }
  74. void CharacterDemo::CreateScene()
  75. {
  76. ResourceCache* cache = GetSubsystem<ResourceCache>();
  77. scene_ = new Scene(context_);
  78. // Create scene subsystem components
  79. scene_->CreateComponent<Octree>();
  80. scene_->CreateComponent<PhysicsWorld>();
  81. // Create camera and define viewport. We will be doing load / save, so it's convenient to create the camera outside the scene,
  82. // so that it won't be destroyed and recreated, and we don't have to redefine the viewport on load
  83. cameraNode_ = new Node(context_);
  84. Camera* camera = cameraNode_->CreateComponent<Camera>();
  85. camera->SetFarClip(300.0f);
  86. GetSubsystem<Renderer>()->SetViewport(0, new Viewport(context_, scene_, camera));
  87. // Create static scene content. First create a zone for ambient lighting and fog control
  88. Node* zoneNode = scene_->CreateChild("Zone");
  89. Zone* zone = zoneNode->CreateComponent<Zone>();
  90. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  91. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  92. zone->SetFogStart(100.0f);
  93. zone->SetFogEnd(300.0f);
  94. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  95. // Create a directional light with cascaded shadow mapping
  96. Node* lightNode = scene_->CreateChild("DirectionalLight");
  97. lightNode->SetDirection(Vector3(0.3f, -0.5f, 0.425f));
  98. Light* light = lightNode->CreateComponent<Light>();
  99. light->SetLightType(LIGHT_DIRECTIONAL);
  100. light->SetCastShadows(true);
  101. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  102. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  103. light->SetSpecularIntensity(0.5f);
  104. // Create the floor object
  105. Node* floorNode = scene_->CreateChild("Floor");
  106. floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
  107. floorNode->SetScale(Vector3(200.0f, 1.0f, 200.0f));
  108. StaticModel* object = floorNode->CreateComponent<StaticModel>();
  109. object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  110. object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  111. RigidBody* body = floorNode->CreateComponent<RigidBody>();
  112. // Use collision layer bit 2 to mark world scenery. This is what we will raycast against to prevent camera from going
  113. // inside geometry
  114. body->SetCollisionLayer(2);
  115. CollisionShape* shape = floorNode->CreateComponent<CollisionShape>();
  116. shape->SetBox(Vector3::ONE);
  117. // Create mushrooms of varying sizes
  118. const unsigned NUM_MUSHROOMS = 60;
  119. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  120. {
  121. Node* objectNode = scene_->CreateChild("Mushroom");
  122. objectNode->SetPosition(Vector3(Random(180.0f) - 90.0f, 0.0f, Random(180.0f) - 90.0f));
  123. objectNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  124. objectNode->SetScale(2.0f + Random(5.0f));
  125. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  126. object->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  127. object->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  128. object->SetCastShadows(true);
  129. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  130. body->SetCollisionLayer(2);
  131. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  132. shape->SetTriangleMesh(object->GetModel(), 0);
  133. }
  134. // Create movable boxes. Let them fall from the sky at first
  135. const unsigned NUM_BOXES = 100;
  136. for (unsigned i = 0; i < NUM_BOXES; ++i)
  137. {
  138. float scale = Random(2.0f) + 0.5f;
  139. Node* objectNode = scene_->CreateChild("Box");
  140. objectNode->SetPosition(Vector3(Random(180.0f) - 90.0f, Random(10.0f) + 10.0f, Random(180.0f) - 90.0f));
  141. objectNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
  142. objectNode->SetScale(scale);
  143. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  144. object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  145. object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  146. object->SetCastShadows(true);
  147. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  148. body->SetCollisionLayer(2);
  149. // Bigger boxes will be heavier and harder to move
  150. body->SetMass(scale * 2.0f);
  151. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  152. shape->SetBox(Vector3::ONE);
  153. }
  154. }
  155. void CharacterDemo::CreateCharacter()
  156. {
  157. ResourceCache* cache = GetSubsystem<ResourceCache>();
  158. Node* objectNode = scene_->CreateChild("Jack");
  159. objectNode->SetPosition(Vector3(0.0f, 1.0f, 0.0f));
  160. // spin node
  161. Node* adjustNode = objectNode->CreateChild("AdjNode");
  162. adjustNode->SetRotation( Quaternion(180, Vector3(0,1,0) ) );
  163. // Create the rendering component + animation controller
  164. AnimatedModel* object = adjustNode->CreateComponent<AnimatedModel>();
  165. object->SetModel(cache->GetResource<Model>("Models/Mutant/Mutant.mdl"));
  166. object->SetMaterial(cache->GetResource<Material>("Models/Mutant/Materials/mutant_M.xml"));
  167. object->SetCastShadows(true);
  168. adjustNode->CreateComponent<AnimationController>();
  169. // Set the head bone for manual control
  170. object->GetSkeleton().GetBone("Mutant:Head")->animated_ = false;
  171. // Create rigidbody, and set non-zero mass so that the body becomes dynamic
  172. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  173. body->SetCollisionLayer(1);
  174. body->SetMass(1.0f);
  175. // Set zero angular factor so that physics doesn't turn the character on its own.
  176. // Instead we will control the character yaw manually
  177. body->SetAngularFactor(Vector3::ZERO);
  178. // Set the rigidbody to signal collision also when in rest, so that we get ground collisions properly
  179. body->SetCollisionEventMode(COLLISION_ALWAYS);
  180. // Set a capsule shape for collision
  181. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  182. shape->SetCapsule(0.7f, 1.8f, Vector3(0.0f, 0.9f, 0.0f));
  183. // Create the character logic component, which takes care of steering the rigidbody
  184. // Remember it so that we can set the controls. Use a WeakPtr because the scene hierarchy already owns it
  185. // and keeps it alive as long as it's not removed from the hierarchy
  186. character_ = objectNode->CreateComponent<Character>();
  187. }
  188. void CharacterDemo::CreateInstructions()
  189. {
  190. SimpleCreateInstructions( "Use WASD keys and mouse/touch to move\n"
  191. "Space to jump, F to toggle 1st/3rd person\n"
  192. "F5 to save scene, F7 to load" );
  193. }
  194. void CharacterDemo::SubscribeToEvents()
  195. {
  196. // Subscribe to Update event for setting the character controls before physics simulation
  197. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(CharacterDemo, HandleUpdate));
  198. // Subscribe to PostUpdate event for updating the camera position after physics simulation
  199. SubscribeToEvent(E_POSTUPDATE, ATOMIC_HANDLER(CharacterDemo, HandlePostUpdate));
  200. // Unsubscribe the SceneUpdate event from base class as the camera node is being controlled in HandlePostUpdate() in this sample
  201. UnsubscribeFromEvent(E_SCENEUPDATE);
  202. }
  203. void CharacterDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  204. {
  205. using namespace Update;
  206. Input* input = GetSubsystem<Input>();
  207. if (character_)
  208. {
  209. // Clear previous controls
  210. character_->controls_.Set(CTRL_FORWARD | CTRL_BACK | CTRL_LEFT | CTRL_RIGHT | CTRL_JUMP, false);
  211. // Update controls using touch utility class
  212. if (touch_)
  213. touch_->UpdateTouches(character_->controls_);
  214. if (!touch_ || !touch_->useGyroscope_)
  215. {
  216. character_->controls_.Set(CTRL_FORWARD, input->GetKeyDown(KEY_W));
  217. character_->controls_.Set(CTRL_BACK, input->GetKeyDown(KEY_S));
  218. character_->controls_.Set(CTRL_LEFT, input->GetKeyDown(KEY_A));
  219. character_->controls_.Set(CTRL_RIGHT, input->GetKeyDown(KEY_D));
  220. }
  221. character_->controls_.Set(CTRL_JUMP, input->GetKeyDown(KEY_SPACE));
  222. // Add character yaw & pitch from the mouse motion or touch input
  223. if (touchEnabled_)
  224. {
  225. for (unsigned i = 0; i < input->GetNumTouches(); ++i)
  226. {
  227. /*
  228. TouchState* state = input->GetTouch(i);
  229. if (!state->touchedElement_) // Touch on empty space
  230. {
  231. Camera* camera = cameraNode_->GetComponent<Camera>();
  232. if (!camera)
  233. return;
  234. Graphics* graphics = GetSubsystem<Graphics>();
  235. character_->controls_.yaw_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.x_;
  236. character_->controls_.pitch_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.y_;
  237. }
  238. */
  239. }
  240. }
  241. else
  242. {
  243. character_->controls_.yaw_ += (float)input->GetMouseMoveX() * YAW_SENSITIVITY;
  244. character_->controls_.pitch_ += (float)input->GetMouseMoveY() * YAW_SENSITIVITY;
  245. }
  246. // Limit pitch
  247. character_->controls_.pitch_ = Clamp(character_->controls_.pitch_, -80.0f, 80.0f);
  248. // Set rotation already here so that it's updated every rendering frame instead of every physics frame
  249. character_->GetNode()->SetRotation(Quaternion(character_->controls_.yaw_, Vector3::UP));
  250. // Switch between 1st and 3rd person
  251. if (input->GetKeyPress(KEY_F))
  252. firstPerson_ = !firstPerson_;
  253. // Turn on/off gyroscope on mobile platform
  254. if (touch_ && input->GetKeyPress(KEY_G))
  255. touch_->useGyroscope_ = !touch_->useGyroscope_;
  256. // Check for loading / saving the scene
  257. if (input->GetKeyPress(KEY_F5))
  258. {
  259. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CharacterDemo.xml", FILE_WRITE);
  260. scene_->SaveXML(saveFile);
  261. }
  262. if (input->GetKeyPress(KEY_F7))
  263. {
  264. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CharacterDemo.xml", FILE_READ);
  265. scene_->LoadXML(loadFile);
  266. // After loading we have to reacquire the weak pointer to the Character component, as it has been recreated
  267. // Simply find the character's scene node by name as there's only one of them
  268. Node* characterNode = scene_->GetChild("Jack", true);
  269. if (characterNode)
  270. character_ = characterNode->GetComponent<Character>();
  271. }
  272. }
  273. }
  274. void CharacterDemo::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  275. {
  276. if (!character_)
  277. return;
  278. Node* characterNode = character_->GetNode();
  279. // Get camera lookat dir from character yaw + pitch
  280. Quaternion rot = characterNode->GetRotation();
  281. Quaternion dir = rot * Quaternion(character_->controls_.pitch_, Vector3::RIGHT);
  282. // Turn head to camera pitch, but limit to avoid unnatural animation
  283. Node* headNode = characterNode->GetChild("Mutant:Head", true);
  284. float limitPitch = Clamp(character_->controls_.pitch_, -45.0f, 45.0f);
  285. Quaternion headDir = rot * Quaternion(limitPitch, Vector3(1.0f, 0.0f, 0.0f));
  286. // This could be expanded to look at an arbitrary target, now just look at a point in front
  287. Vector3 headWorldTarget = headNode->GetWorldPosition() + headDir * Vector3(0.0f, 0.0f, -1.0f);
  288. headNode->LookAt(headWorldTarget, Vector3(0.0f, 1.0f, 0.0f));
  289. if (firstPerson_)
  290. {
  291. cameraNode_->SetPosition(headNode->GetWorldPosition() + rot * Vector3(0.0f, 0.15f, 0.2f));
  292. cameraNode_->SetRotation(dir);
  293. }
  294. else
  295. {
  296. // Third person camera: position behind the character
  297. Vector3 aimPoint = characterNode->GetPosition() + rot * Vector3(0.0f, 1.7f, 0.0f);
  298. // Collide camera ray with static physics objects (layer bitmask 2) to ensure we see the character properly
  299. Vector3 rayDir = dir * Vector3::BACK;
  300. float rayDistance = touch_ ? touch_->cameraDistance_ : CAMERA_INITIAL_DIST;
  301. PhysicsRaycastResult result;
  302. scene_->GetComponent<PhysicsWorld>()->RaycastSingle(result, Ray(aimPoint, rayDir), rayDistance, 2);
  303. if (result.body_)
  304. rayDistance = Min(rayDistance, result.distance_);
  305. rayDistance = Clamp(rayDistance, CAMERA_MIN_DIST, CAMERA_MAX_DIST);
  306. cameraNode_->SetPosition(aimPoint + rayDir * rayDistance);
  307. cameraNode_->SetRotation(dir);
  308. }
  309. }