15_Navigation.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. // Copyright (c) 2015 Xamarin Inc
  4. // Copyright (c) 2016 THUNDERBEAST GAMES LLC
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. using System.Collections.Generic;
  25. using System.Linq;
  26. using AtomicEngine;
  27. namespace FeatureExamples
  28. {
  29. public class NavigationSample : Sample
  30. {
  31. float yaw;
  32. float pitch;
  33. bool drawDebug;
  34. Node jackNode;
  35. Vector3 endPos;
  36. List<Vector3> currentPath = new List<Vector3>();
  37. public NavigationSample() : base() { }
  38. public override void Start()
  39. {
  40. base.Start();
  41. CreateScene();
  42. CreateUI();
  43. SetupViewport();
  44. SubscribeToEvents();
  45. }
  46. void SubscribeToEvents()
  47. {
  48. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  49. {
  50. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  51. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  52. // bones properly
  53. if (drawDebug)
  54. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  55. if (currentPath.Count > 0)
  56. {
  57. // Visualize the current calculated path
  58. DebugRenderer debug = scene.GetComponent<DebugRenderer>();
  59. debug.AddBoundingBox(new BoundingBox(endPos - new Vector3(0.1f, 0.1f, 0.1f), endPos + new Vector3(0.1f, 0.1f, 0.1f)),
  60. new Color(1.0f, 1.0f, 1.0f), true);
  61. // Draw the path with a small upward bias so that it does not clip into the surfaces
  62. Vector3 bias = new Vector3(0.0f, 0.05f, 0.0f);
  63. debug.AddLine(jackNode.Position + bias, currentPath[0] + bias, new Color(1.0f, 1.0f, 1.0f), true);
  64. if (currentPath.Count > 1)
  65. {
  66. for (int i = 0; i < currentPath.Count - 1; ++i)
  67. debug.AddLine(currentPath[i] + bias, currentPath[i + 1] + bias, new Color(1.0f, 1.0f, 1.0f), true);
  68. }
  69. }
  70. });
  71. }
  72. protected override void Update(float timeStep)
  73. {
  74. base.Update(timeStep);
  75. MoveCamera(timeStep);
  76. FollowPath(timeStep);
  77. }
  78. void MoveCamera(float timeStep)
  79. {
  80. var input = GetSubsystem<Input>();
  81. // Right mouse button controls mouse cursor visibility: hide when pressed
  82. bool rightMouseDown = input.GetMouseButtonDown(Constants.MOUSEB_RIGHT);
  83. // Movement speed as world units per second
  84. const float moveSpeed = 20.0f;
  85. // Mouse sensitivity as degrees per pixel
  86. const float mouseSensitivity = 0.1f;
  87. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  88. // Only move the camera when the cursor is hidden
  89. if (rightMouseDown)
  90. {
  91. IntVector2 mouseMove = input.MouseMove;
  92. yaw += mouseSensitivity * mouseMove.X;
  93. pitch += mouseSensitivity * mouseMove.Y;
  94. pitch = MathHelper.Clamp(pitch, -90.0f, 90.0f);
  95. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  96. CameraNode.Rotation = new Quaternion(pitch, yaw, 0.0f);
  97. }
  98. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  99. if (input.GetKeyDown(Constants.KEY_W))
  100. CameraNode.Translate(Vector3.UnitZ * moveSpeed * timeStep);
  101. if (input.GetKeyDown(Constants.KEY_S))
  102. CameraNode.Translate(-Vector3.UnitZ * moveSpeed * timeStep);
  103. if (input.GetKeyDown(Constants.KEY_A))
  104. CameraNode.Translate(-Vector3.UnitX * moveSpeed * timeStep);
  105. if (input.GetKeyDown(Constants.KEY_D))
  106. CameraNode.Translate(Vector3.UnitX * moveSpeed * timeStep);
  107. // Set destination or teleport with left mouse button
  108. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  109. SetPathPoint();
  110. // Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  111. if (input.GetMouseButtonPress(Constants.MOUSEB_MIDDLE))
  112. AddOrRemoveObject();
  113. // Toggle debug geometry with space
  114. if (input.GetKeyPress(Constants.KEY_SPACE))
  115. drawDebug = !drawDebug;
  116. }
  117. void SetupViewport()
  118. {
  119. var renderer = GetSubsystem<Renderer>();
  120. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  121. }
  122. void CreateUI()
  123. {
  124. SimpleCreateInstructions(
  125. "Use WASD keys to move, RMB to rotate view\n" +
  126. "LMB to set destination, SHIFT+LMB to teleport\n" +
  127. "MMB to add or remove obstacles\n" +
  128. "Space to toggle debug geometry");
  129. }
  130. void CreateScene()
  131. {
  132. var cache = GetSubsystem<ResourceCache>();
  133. scene = new Scene();
  134. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  135. // Also create a DebugRenderer component so that we can draw debug geometry
  136. scene.CreateComponent<Octree>();
  137. scene.CreateComponent<DebugRenderer>();
  138. // Create scene node & StaticModel component for showing a static plane
  139. Node planeNode = scene.CreateChild("Plane");
  140. planeNode.Scale = new Vector3(100.0f, 1.0f, 100.0f);
  141. StaticModel planeObject = planeNode.CreateComponent<StaticModel>();
  142. planeObject.Model = cache.Get<Model>("Models/Plane.mdl");
  143. planeObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  144. // Create a Zone component for ambient lighting & fog control
  145. Node zoneNode = scene.CreateChild("Zone");
  146. Zone zone = zoneNode.CreateComponent<Zone>();
  147. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  148. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  149. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  150. zone.FogStart = 100.0f;
  151. zone.FogEnd = 300.0f;
  152. // Create a directional light to the world. Enable cascaded shadows on it
  153. Node lightNode = scene.CreateChild("DirectionalLight");
  154. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  155. Light light = lightNode.CreateComponent<Light>();
  156. light.LightType = LightType.LIGHT_DIRECTIONAL;
  157. light.CastShadows = true;
  158. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  159. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  160. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  161. // Create some mushrooms
  162. const uint numMushrooms = 100;
  163. for (uint i = 0; i < numMushrooms; ++i)
  164. CreateMushroom(new Vector3(NextRandom(90.0f) - 45.0f, 0.0f, NextRandom(90.0f) - 45.0f));
  165. // Create randomly sized boxes. If boxes are big enough, make them occluders
  166. const uint numBoxes = 20;
  167. for (uint i = 0; i < numBoxes; ++i)
  168. {
  169. Node boxNode = scene.CreateChild("Box");
  170. float size = 1.0f + NextRandom(10.0f);
  171. boxNode.Position = new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f);
  172. boxNode.SetScale(size);
  173. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  174. boxObject.Model = cache.Get<Model>("Models/Box.mdl");
  175. boxObject.SetMaterial(cache.Get<Material>("Materials/Stone.xml"));
  176. boxObject.CastShadows = true;
  177. if (size >= 3.0f)
  178. boxObject.Occluder = true;
  179. }
  180. // Create Jack node that will follow the path
  181. jackNode = scene.CreateChild("Jack");
  182. jackNode.Position = new Vector3(-5.0f, 0.0f, 20.0f);
  183. AnimatedModel modelObject = jackNode.CreateComponent<AnimatedModel>();
  184. modelObject.Model = cache.Get<Model>("Models/Jack.mdl");
  185. modelObject.SetMaterial(cache.Get<Material>("Materials/Jack.xml"));
  186. modelObject.CastShadows = true;
  187. // Create a NavigationMesh component to the scene root
  188. NavigationMesh navMesh = scene.CreateComponent<NavigationMesh>();
  189. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  190. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  191. scene.CreateComponent<Navigable>();
  192. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  193. // in the scene and still update the mesh correctly
  194. navMesh.Padding = new Vector3(0.0f, 10.0f, 0.0f);
  195. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  196. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  197. // it will use renderable geometry instead
  198. navMesh.Build();
  199. // Create the camera. Limit far clip distance to match the fog
  200. CameraNode = scene.CreateChild("Camera");
  201. Camera camera = CameraNode.CreateComponent<Camera>();
  202. camera.FarClip = 300.0f;
  203. // Set an initial position for the camera scene node above the plane
  204. CameraNode.Position = new Vector3(0.0f, 5.0f, 0.0f);
  205. }
  206. void SetPathPoint()
  207. {
  208. var input = GetSubsystem<Input>();
  209. Vector3 hitPos;
  210. Drawable hitDrawable;
  211. NavigationMesh navMesh = scene.GetComponent<NavigationMesh>();
  212. if (Raycast(250.0f, out hitPos, out hitDrawable))
  213. {
  214. Vector3 pathPos = navMesh.FindNearestPoint(hitPos, new Vector3(1.0f, 1.0f, 1.0f));
  215. if (input.GetQualifierDown(Constants.QUAL_SHIFT))
  216. {
  217. // Teleport
  218. currentPath.Clear();
  219. jackNode.LookAt(new Vector3(pathPos.X, jackNode.Position.Y, pathPos.Z), Vector3.UnitY, TransformSpace.TS_WORLD);
  220. jackNode.Position = (pathPos);
  221. }
  222. else
  223. {
  224. // Calculate path from Jack's current position to the end point
  225. endPos = pathPos;
  226. var result = navMesh.FindPath(currentPath, jackNode.Position, endPos);
  227. }
  228. }
  229. }
  230. void AddOrRemoveObject()
  231. {
  232. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  233. Vector3 hitPos;
  234. Drawable hitDrawable;
  235. if (Raycast(250.0f, out hitPos, out hitDrawable))
  236. {
  237. // The part of the navigation mesh we must update, which is the world bounding box of the associated
  238. // drawable component
  239. BoundingBox updateBox;
  240. Node hitNode = hitDrawable.Node;
  241. if (hitNode.Name == "Mushroom")
  242. {
  243. updateBox = hitDrawable.WorldBoundingBox;
  244. hitNode.Remove();
  245. }
  246. else
  247. {
  248. Node newNode = CreateMushroom(hitPos);
  249. updateBox = newNode.GetComponent<StaticModel>().WorldBoundingBox;
  250. }
  251. // Rebuild part of the navigation mesh, then recalculate path if applicable
  252. NavigationMesh navMesh = scene.GetComponent<NavigationMesh>();
  253. navMesh.Build(updateBox);
  254. if (currentPath.Count > 0)
  255. navMesh.FindPath(currentPath, jackNode.Position, endPos);
  256. }
  257. }
  258. Node CreateMushroom(Vector3 pos)
  259. {
  260. var cache = GetSubsystem<ResourceCache>();
  261. Node mushroomNode = scene.CreateChild("Mushroom");
  262. mushroomNode.Position = pos;
  263. mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
  264. mushroomNode.SetScale(2.0f + NextRandom(0.5f));
  265. StaticModel mushroomObject = mushroomNode.CreateComponent<StaticModel>();
  266. mushroomObject.Model = (cache.Get<Model>("Models/Mushroom.mdl"));
  267. mushroomObject.SetMaterial(cache.Get<Material>("Materials/Mushroom.xml"));
  268. mushroomObject.CastShadows = true;
  269. return mushroomNode;
  270. }
  271. bool Raycast(float maxDistance, out Vector3 hitPos, out Drawable hitDrawable)
  272. {
  273. var input = GetSubsystem<Input>();
  274. hitDrawable = null;
  275. hitPos = new Vector3();
  276. var graphics = GetSubsystem<Graphics>();
  277. Camera camera = CameraNode.GetComponent<Camera>();
  278. IntVector2 pos = input.MousePosition;
  279. Ray cameraRay = camera.GetScreenRay((float)pos.X / graphics.Width, (float)pos.Y / graphics.Height);
  280. RayOctreeQuery query = new RayOctreeQuery(cameraRay, RayQueryLevel.RAY_TRIANGLE, maxDistance, Constants.DRAWABLE_GEOMETRY);
  281. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  282. scene.GetComponent<Octree>().RaycastSingle(query);
  283. if (query.Results.Count > 0)
  284. {
  285. var first = query.Results.First();
  286. hitPos = first.Position;
  287. hitDrawable = first.Drawable;
  288. return true;
  289. }
  290. return false;
  291. }
  292. void FollowPath(float timeStep)
  293. {
  294. if (currentPath.Count > 0)
  295. {
  296. Vector3 nextWaypoint = currentPath[0]; // NB: currentPath[0] is the next waypoint in order
  297. // Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target
  298. float move = 5.0f * timeStep;
  299. float distance = (jackNode.Position - nextWaypoint).Length;
  300. if (move > distance)
  301. move = distance;
  302. jackNode.LookAt(nextWaypoint, Vector3.UnitY, TransformSpace.TS_WORLD);
  303. jackNode.Translate(Vector3.UnitZ * move, TransformSpace.TS_LOCAL);
  304. // Remove waypoint if reached it
  305. if (distance < 0.1f)
  306. currentPath.RemoveAt(0);
  307. }
  308. }
  309. }
  310. }