39_CrowdNavigation.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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.Linq;
  25. using AtomicEngine;
  26. namespace FeatureExamples
  27. {
  28. public class CrowdNavigationSample : Sample
  29. {
  30. Scene scene;
  31. bool drawDebug;
  32. CrowdManager crowdManager;
  33. public CrowdNavigationSample() : base() { }
  34. public override void Start()
  35. {
  36. base.Start();
  37. CreateScene();
  38. CreateUI();
  39. SetupViewport();
  40. SubscribeToEvents();
  41. }
  42. void CreateUI()
  43. {
  44. var cache = GetSubsystem<ResourceCache>();
  45. SimpleCreateInstructions(
  46. "Use WASD keys to move, RMB to rotate view\n" +
  47. "LMB to set destination, SHIFT+LMB to spawn a Jack\n" +
  48. "CTRL+LMB to teleport main agent\n" +
  49. "MMB to add obstacles or remove obstacles/agents\n" +
  50. "F5 to save scene, F7 to load\n" +
  51. "Space to toggle debug geometry");
  52. }
  53. protected override void Update(float timeStep)
  54. {
  55. MoveCamera(timeStep);
  56. base.Update(timeStep);
  57. }
  58. void SubscribeToEvents()
  59. {
  60. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  61. {
  62. if (drawDebug)
  63. {
  64. // Visualize navigation mesh, obstacles and off-mesh connections
  65. scene.GetComponent<DynamicNavigationMesh>().DrawDebugGeometry(true);
  66. // Visualize agents' path and position to reach
  67. crowdManager.DrawDebugGeometry(true);
  68. }
  69. });
  70. SubscribeToEvent<CrowdAgentFailureEvent>(e =>
  71. {
  72. Node node = e.Node;
  73. CrowdAgentState agentState = (CrowdAgentState) e.CrowdAgentState;
  74. // If the agent's state is invalid, likely from spawning on the side of a box, find a point in a larger area
  75. if (agentState == CrowdAgentState.CA_STATE_INVALID)
  76. {
  77. // Get a point on the navmesh using more generous extents
  78. Vector3 newPos = scene.GetComponent<DynamicNavigationMesh>().FindNearestPoint(node.Position, new Vector3(5.0f, 5.0f, 5.0f));
  79. // Set the new node position, CrowdAgent component will automatically reset the state of the agent
  80. node.Position = newPos;
  81. }
  82. });
  83. SubscribeToEvent<CrowdAgentRepositionEvent>(e =>
  84. {
  85. string WALKING_ANI = "Models/Jack_Walk.ani";
  86. Node node = e.Node;
  87. Vector3 velocity = e.Velocity;
  88. // Only Jack agent has animation controller
  89. AnimationController animCtrl = node.GetComponent<AnimationController>();
  90. if (animCtrl != null)
  91. {
  92. float speed = velocity.Length;
  93. if (animCtrl.IsPlaying(WALKING_ANI))
  94. {
  95. float speedRatio = speed / e.CrowdAgent.MaxSpeed;
  96. // Face the direction of its velocity but moderate the turning speed based on the speed ratio as we do not have timeStep here
  97. node.Rotation = Quaternion.Slerp(node.Rotation, Quaternion.FromRotationTo(Vector3.UnitZ, velocity), 10f * e.TimeStep * speedRatio);
  98. // Throttle the animation speed based on agent speed ratio (ratio = 1 is full throttle)
  99. animCtrl.SetSpeed(WALKING_ANI, speedRatio);
  100. }
  101. else
  102. animCtrl.Play(WALKING_ANI, 0, true, 0.1f);
  103. // If speed is too low then stopping the animation
  104. if (speed < e.CrowdAgent.Radius)
  105. animCtrl.Stop(WALKING_ANI, 0.8f);
  106. }
  107. });
  108. }
  109. void MoveCamera(float timeStep)
  110. {
  111. // Right mouse button controls mouse cursor visibility: hide when pressed
  112. Input input = GetSubsystem<Input>();
  113. var rightMouseDown = input.GetMouseButtonDown(Constants.MOUSEB_RIGHT);
  114. // Movement speed as world units per second
  115. const float moveSpeed = 20.0f;
  116. // Mouse sensitivity as degrees per pixel
  117. const float mouseSensitivity = 0.1f;
  118. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  119. // Only move the camera when the cursor is hidden
  120. if (rightMouseDown)
  121. {
  122. IntVector2 mouseMove = input.MouseMove;
  123. Yaw += mouseSensitivity * mouseMove.X;
  124. Pitch += mouseSensitivity * mouseMove.Y;
  125. Pitch = MathHelper.Clamp(Pitch, -90.0f, 90.0f);
  126. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  127. CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0.0f);
  128. }
  129. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  130. if (input.GetKeyDown(Constants.KEY_W)) CameraNode.Translate(Vector3.UnitZ * moveSpeed * timeStep);
  131. if (input.GetKeyDown(Constants.KEY_S)) CameraNode.Translate(-Vector3.UnitZ * moveSpeed * timeStep);
  132. if (input.GetKeyDown(Constants.KEY_A)) CameraNode.Translate(-Vector3.UnitX * moveSpeed * timeStep);
  133. if (input.GetKeyDown(Constants.KEY_D)) CameraNode.Translate(Vector3.UnitX * moveSpeed * timeStep);
  134. const int qualShift = 1;
  135. // Set destination or spawn a new jack with left mouse button
  136. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  137. SetPathPoint(input.GetQualifierDown(qualShift));
  138. // Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  139. if (input.GetMouseButtonPress(Constants.MOUSEB_MIDDLE))
  140. AddOrRemoveObject();
  141. /*
  142. // Check for loading/saving the scene. Save the scene to the file Data/Scenes/CrowdNavigation.xml relative to the executable
  143. // directory
  144. if (input.GetKeyPress(Key.F5))
  145. scene.SaveXml(FileSystem.ProgramDir + "Data/Scenes/CrowdNavigation.xml");
  146. if (input.GetKeyPress(Key.F7))
  147. scene.LoadXml(FileSystem.ProgramDir + "Data/Scenes/CrowdNavigation.xml");
  148. */
  149. // Toggle debug geometry with space
  150. if (input.GetKeyPress(Constants.KEY_SPACE))
  151. drawDebug = !drawDebug;
  152. }
  153. bool Raycast(float maxDistance, out Vector3 hitPos, out Drawable hitDrawable)
  154. {
  155. var input = GetSubsystem<Input>();
  156. hitDrawable = null;
  157. hitPos = new Vector3();
  158. var graphics = GetSubsystem<Graphics>();
  159. Camera camera = CameraNode.GetComponent<Camera>();
  160. IntVector2 pos = input.MousePosition;
  161. Ray cameraRay = camera.GetScreenRay((float)pos.X / graphics.Width, (float)pos.Y / graphics.Height);
  162. RayOctreeQuery query = new RayOctreeQuery(cameraRay, RayQueryLevel.RAY_TRIANGLE, maxDistance, Constants.DRAWABLE_GEOMETRY);
  163. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  164. scene.GetComponent<Octree>().RaycastSingle(query);
  165. if (query.Results.Count > 0)
  166. {
  167. var first = query.Results.First();
  168. hitPos = first.Position;
  169. hitDrawable = first.Drawable;
  170. return true;
  171. }
  172. return false;
  173. }
  174. void SetPathPoint(bool spawning)
  175. {
  176. Vector3 hitPos;
  177. Drawable hitDrawable;
  178. if (Raycast(250.0f, out hitPos, out hitDrawable))
  179. {
  180. DynamicNavigationMesh navMesh = scene.GetComponent<DynamicNavigationMesh>();
  181. Vector3 pathPos = navMesh.FindNearestPoint(hitPos, new Vector3(1.0f, 1.0f, 1.0f));
  182. Node jackGroup = scene.GetChild("Jacks", false);
  183. if (spawning)
  184. // Spawn a jack at the target position
  185. SpawnJack(pathPos, jackGroup);
  186. else
  187. // Set crowd agents target position
  188. scene.GetComponent<CrowdManager>().SetCrowdTarget(pathPos, jackGroup);
  189. }
  190. }
  191. void AddOrRemoveObject()
  192. {
  193. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  194. Vector3 hitPos;
  195. Drawable hitDrawable;
  196. if (Raycast(250.0f, out hitPos, out hitDrawable))
  197. {
  198. Node hitNode = hitDrawable.Node;
  199. // Note that navmesh rebuild happens when the Obstacle component is removed
  200. if (hitNode.Name == "Mushroom")
  201. hitNode.Remove();
  202. else if (hitNode.Name == "Jack")
  203. hitNode.Remove();
  204. else
  205. CreateMushroom(hitPos);
  206. }
  207. }
  208. void SetupViewport()
  209. {
  210. var renderer = GetSubsystem<Renderer>();
  211. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  212. }
  213. void CreateScene()
  214. {
  215. var cache = GetSubsystem<ResourceCache>();
  216. scene = new Scene();
  217. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  218. // Also create a DebugRenderer component so that we can draw debug geometry
  219. scene.CreateComponent<Octree>();
  220. scene.CreateComponent<DebugRenderer>();
  221. // Create scene node & StaticModel component for showing a static plane
  222. Node planeNode = scene.CreateChild("Plane");
  223. planeNode.Scale = new Vector3(100.0f, 1.0f, 100.0f);
  224. StaticModel planeObject = planeNode.CreateComponent<StaticModel>();
  225. planeObject.Model = (cache.Get<Model>("Models/Plane.mdl"));
  226. planeObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  227. // Create a Zone component for ambient lighting & fog control
  228. Node zoneNode = scene.CreateChild("Zone");
  229. Zone zone = zoneNode.CreateComponent<Zone>();
  230. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  231. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  232. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  233. zone.FogStart = 100.0f;
  234. zone.FogEnd = 300.0f;
  235. // Create a directional light to the world. Enable cascaded shadows on it
  236. Node lightNode = scene.CreateChild("DirectionalLight");
  237. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  238. Light light = lightNode.CreateComponent<Light>();
  239. light.LightType = LightType.LIGHT_DIRECTIONAL;
  240. light.CastShadows = true;
  241. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  242. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  243. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  244. // Create randomly sized boxes. If boxes are big enough, make them occluders
  245. const uint numBoxes = 20;
  246. Node boxGroup = scene.CreateChild("Boxes");
  247. for (uint i = 0; i < numBoxes; ++i)
  248. {
  249. Node boxNode = boxGroup.CreateChild("Box");
  250. float size = 1.0f + NextRandom(10.0f);
  251. boxNode.Position = (new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f));
  252. boxNode.SetScale(size);
  253. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  254. boxObject.Model = (cache.Get<Model>("Models/Box.mdl"));
  255. boxObject.SetMaterial(cache.Get<Material>("Materials/Stone.xml"));
  256. boxObject.CastShadows = true;
  257. if (size >= 3.0f)
  258. boxObject.Occluder = true;
  259. }
  260. // Create a DynamicNavigationMesh component to the scene root
  261. DynamicNavigationMesh navMesh = scene.CreateComponent<DynamicNavigationMesh>();
  262. // Set the agent height large enough to exclude the layers under boxes
  263. navMesh.AgentHeight = 10.0f;
  264. navMesh.CellHeight = 0.05f;
  265. navMesh.DrawObstacles = true;
  266. navMesh.DrawOffMeshConnections = true;
  267. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  268. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  269. scene.CreateComponent<Navigable>();
  270. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  271. // in the scene and still update the mesh correctly
  272. navMesh.Padding = new Vector3(0.0f, 10.0f, 0.0f);
  273. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  274. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  275. // it will use renderable geometry instead
  276. navMesh.Build();
  277. // Create an off-mesh connection to each box to make them climbable (tiny boxes are skipped). A connection is built from 2 nodes.
  278. // Note that OffMeshConnections must be added before building the navMesh, but as we are adding Obstacles next, tiles will be automatically rebuilt.
  279. // Creating connections post-build here allows us to use FindNearestPoint() to procedurally set accurate positions for the connection
  280. CreateBoxOffMeshConnections(navMesh, boxGroup);
  281. // Create some mushrooms
  282. const uint numMushrooms = 100;
  283. for (uint i = 0; i < numMushrooms; ++i)
  284. CreateMushroom(new Vector3(NextRandom(90.0f) - 45.0f, 0.0f, NextRandom(90.0f) - 45.0f));
  285. // Create a CrowdManager component to the scene root
  286. crowdManager = scene.CreateComponent<CrowdManager>();
  287. var parameters = crowdManager.GetObstacleAvoidanceParams(0);
  288. // Set the params to "High (66)" setting
  289. parameters.VelBias = 0.5f;
  290. parameters.AdaptiveDivs = 7;
  291. parameters.AdaptiveRings = 3;
  292. parameters.AdaptiveDepth = 3;
  293. crowdManager.SetObstacleAvoidanceParams(0, parameters);
  294. // Create some movable barrels. We create them as crowd agents, as for moving entities it is less expensive and more convenient than using obstacles
  295. CreateMovingBarrels(navMesh);
  296. // Create Jack node that will follow the path
  297. SpawnJack(new Vector3(-5.0f, 0.0f, 20.0f), scene.CreateChild("Jacks"));
  298. // Create the camera. Limit far clip distance to match the fog
  299. CameraNode = new Node();
  300. Camera camera = CameraNode.CreateComponent<Camera>();
  301. camera.FarClip = 300.0f;
  302. // Set an initial position for the camera scene node above the plane
  303. CameraNode.Position = new Vector3(0.0f, 50.0f, 0.0f);
  304. Pitch = 80.0f;
  305. CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0.0f);
  306. }
  307. void SpawnJack(Vector3 pos, Node jackGroup)
  308. {
  309. var cache = GetSubsystem<ResourceCache>();
  310. Node jackNode = jackGroup.CreateChild("Jack");
  311. jackNode.Position = pos;
  312. AnimatedModel modelObject = jackNode.CreateComponent<AnimatedModel>();
  313. modelObject.Model = (cache.Get<Model>("Models/Jack.mdl"));
  314. modelObject.SetMaterial(cache.Get<Material>("Materials/Jack.xml"));
  315. modelObject.CastShadows = true;
  316. jackNode.CreateComponent<AnimationController>();
  317. // Create the CrowdAgent
  318. var agent = jackNode.CreateComponent<CrowdAgent>();
  319. agent.Height = 2.0f;
  320. agent.MaxSpeed = 3.0f;
  321. agent.MaxAccel = 3.0f;
  322. }
  323. void CreateMushroom(Vector3 pos)
  324. {
  325. var cache = GetSubsystem<ResourceCache>();
  326. Node mushroomNode = scene.CreateChild("Mushroom");
  327. mushroomNode.Position = (pos);
  328. mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
  329. mushroomNode.SetScale(2.0f + NextRandom(0.5f));
  330. StaticModel mushroomObject = mushroomNode.CreateComponent<StaticModel>();
  331. mushroomObject.Model = (cache.Get<Model>("Models/Mushroom.mdl"));
  332. mushroomObject.SetMaterial(cache.Get<Material>("Materials/Mushroom.xml"));
  333. mushroomObject.CastShadows = true;
  334. // Create the navigation obstacle
  335. Obstacle obstacle = mushroomNode.CreateComponent<Obstacle>();
  336. obstacle.Radius = mushroomNode.Scale.X;
  337. obstacle.Height = mushroomNode.Scale.Y;
  338. }
  339. void CreateBoxOffMeshConnections(DynamicNavigationMesh navMesh, Node boxGroup)
  340. {
  341. foreach (var box in boxGroup.GetChildren())
  342. {
  343. var boxPos = box.Position;
  344. float boxHalfSize = box.Scale.X / 2;
  345. var connectionStart = box.CreateChild("ConnectionStart");
  346. connectionStart.SetWorldPosition(navMesh.FindNearestPoint(boxPos + new Vector3(boxHalfSize, -boxHalfSize, 0), Vector3.One));
  347. var connectionEnd = box.CreateChild("ConnectionEnd");
  348. connectionEnd.SetWorldPosition(navMesh.FindNearestPoint(boxPos + new Vector3(boxHalfSize, boxHalfSize, 0), Vector3.One));
  349. OffMeshConnection connection = connectionStart.CreateComponent<OffMeshConnection>();
  350. connection.EndPoint = connectionEnd;
  351. }
  352. }
  353. void CreateMovingBarrels(DynamicNavigationMesh navMesh)
  354. {
  355. var cache = GetSubsystem<ResourceCache>();
  356. Node barrel = scene.CreateChild("Barrel");
  357. StaticModel model = barrel.CreateComponent<StaticModel>();
  358. model.Model = cache.Get<Model>("Models/Cylinder.mdl");
  359. Material material = cache.Get<Material>("Materials/StoneTiled.xml");
  360. model.SetMaterial(material);
  361. material.SetTexture(TextureUnit.TU_DIFFUSE, cache.Get<Texture2D>("Textures/TerrainDetail2.dds"));
  362. model.CastShadows = true;
  363. for (int i = 0; i < 20; ++i)
  364. {
  365. Node clone = barrel.Clone(CreateMode.REPLICATED);
  366. float size = 0.5f + NextRandom(1.0f);
  367. clone.Scale = new Vector3(size / 1.5f, size * 2.0f, size / 1.5f);
  368. clone.Position = navMesh.FindNearestPoint(new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f), Vector3.One);
  369. CrowdAgent agent = clone.CreateComponent<CrowdAgent>();
  370. agent.Radius = clone.Scale.X * 0.5f;
  371. agent.Height = size;
  372. agent.NavigationQuality = NavigationQuality.NAVIGATIONQUALITY_LOW;
  373. }
  374. barrel.Remove();
  375. }
  376. }
  377. }