39_CrowdNavigation.as 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. // CrowdNavigation example.
  2. // This sample demonstrates:
  3. // - Generating a dynamic navigation mesh into the scene
  4. // - Performing path queries to the navigation mesh
  5. // - Adding and removing obstacles/agents at runtime
  6. // - Raycasting drawable components
  7. // - Crowd movement management
  8. // - Accessing crowd agents with the crowd manager
  9. // - Using off-mesh connections to make boxes climbable
  10. // - Using agents to simulate moving obstacles
  11. #include "Scripts/Utilities/Sample.as"
  12. const String INSTRUCTION("instructionText");
  13. bool useStreaming = false;
  14. // Used for streaming only
  15. const int STREAMING_DISTANCE = 2;
  16. Array<VectorBuffer> navigationTilesData;
  17. Array<IntVector2> navigationTilesIdx;
  18. Array<IntVector2> addedTiles;
  19. void Start()
  20. {
  21. // Execute the common startup for samples
  22. SampleStart();
  23. // Create the scene content
  24. CreateScene();
  25. // Create the UI content
  26. CreateUI();
  27. // Setup the viewport for displaying the scene
  28. SetupViewport();
  29. // Set the mouse mode to use in the sample
  30. SampleInitMouseMode(MM_RELATIVE);
  31. // Hook up to the frame update and render post-update events
  32. SubscribeToEvents();
  33. }
  34. void CreateScene()
  35. {
  36. scene_ = Scene();
  37. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  38. // Also create a DebugRenderer component so that we can draw debug geometry
  39. scene_.CreateComponent("Octree");
  40. scene_.CreateComponent("DebugRenderer");
  41. // Create scene node & StaticModel component for showing a static plane
  42. Node@ planeNode = scene_.CreateChild("Plane");
  43. planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
  44. StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
  45. planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  46. planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  47. // Create a Zone component for ambient lighting & fog control
  48. Node@ zoneNode = scene_.CreateChild("Zone");
  49. Zone@ zone = zoneNode.CreateComponent("Zone");
  50. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  51. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  52. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  53. zone.fogStart = 100.0f;
  54. zone.fogEnd = 300.0f;
  55. // Create a directional light to the world. Enable cascaded shadows on it
  56. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  57. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  58. Light@ light = lightNode.CreateComponent("Light");
  59. light.lightType = LIGHT_DIRECTIONAL;
  60. light.castShadows = true;
  61. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  62. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  63. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  64. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  65. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  66. Node@ boxGroup = scene_.CreateChild("Boxes");
  67. for (uint i = 0; i < 20; ++i)
  68. {
  69. Node@ boxNode = boxGroup.CreateChild("Box");
  70. float size = 1.0f + Random(10.0f);
  71. boxNode.position = Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f);
  72. boxNode.SetScale(size);
  73. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  74. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  75. boxObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  76. boxObject.castShadows = true;
  77. if (size >= 3.0f)
  78. boxObject.occluder = true;
  79. }
  80. // Create a DynamicNavigationMesh component to the scene root
  81. DynamicNavigationMesh@ navMesh = scene_.CreateComponent("DynamicNavigationMesh");
  82. // Set small tiles to show navigation mesh streaming
  83. navMesh.tileSize = 32;
  84. // Enable drawing debug geometry for obstacles and off-mesh connections
  85. navMesh.drawObstacles = true;
  86. navMesh.drawOffMeshConnections = true;
  87. // Set the agent height large enough to exclude the layers under boxes
  88. navMesh.agentHeight = 10;
  89. // Set nav mesh cell height to minimum (allows agents to be grounded)
  90. navMesh.cellHeight = 0.05f;
  91. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  92. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  93. scene_.CreateComponent("Navigable");
  94. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  95. // in the scene and still update the mesh correctly
  96. navMesh.padding = Vector3(0.0f, 10.0f, 0.0f);
  97. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  98. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  99. // it will use renderable geometry instead
  100. navMesh.Build();
  101. // Create an off-mesh connection to each box to make it climbable (tiny boxes are skipped). A connection is built from 2 nodes.
  102. // Note that OffMeshConnections must be added before building the navMesh, but as we are adding Obstacles next, tiles will be automatically rebuilt.
  103. // Creating connections post-build here allows us to use FindNearestPoint() to procedurally set accurate positions for the connection
  104. CreateBoxOffMeshConnections(navMesh, boxGroup);
  105. // Create some mushrooms as obstacles. Note that obstacles are non-walkable areas
  106. for (uint i = 0; i < 100; ++i)
  107. CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  108. // Create a CrowdManager component to the scene root (mandatory for crowd agents)
  109. CrowdManager@ crowdManager = scene_.CreateComponent("CrowdManager");
  110. CrowdObstacleAvoidanceParams params = crowdManager.GetObstacleAvoidanceParams(0);
  111. // Set the params to "High (66)" setting
  112. params.velBias = 0.5f;
  113. params.adaptiveDivs = 7;
  114. params.adaptiveRings = 3;
  115. params.adaptiveDepth = 3;
  116. crowdManager.SetObstacleAvoidanceParams(0, params);
  117. // Create some movable barrels. We create them as crowd agents, as for moving entities it is less expensive and more convenient than using obstacles
  118. CreateMovingBarrels(navMesh);
  119. // Create Jack node as crowd agent
  120. SpawnJack(Vector3(-5.0f, 0, 20.0f), scene_.CreateChild("Jacks"));
  121. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  122. // the scene, because we want it to be unaffected by scene load / save
  123. cameraNode = Node();
  124. Camera@ camera = cameraNode.CreateComponent("Camera");
  125. camera.farClip = 300.0f;
  126. // Set an initial position for the camera scene node above the plane and looking down
  127. cameraNode.position = Vector3(0.0f, 50.0f, 0.0f);
  128. pitch = 80.0f;
  129. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  130. }
  131. void CreateUI()
  132. {
  133. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  134. // control the camera, and when visible, it will point the raycast target
  135. XMLFile@ style = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
  136. Cursor@ cursor = Cursor();
  137. cursor.SetStyleAuto(style);
  138. ui.cursor = cursor;
  139. // Set starting position of the cursor at the rendering window center
  140. cursor.SetPosition(graphics.width / 2, graphics.height / 2);
  141. // Construct new Text object, set string to display and font to use
  142. Text@ instructionText = ui.root.CreateChild("Text", INSTRUCTION);
  143. instructionText.text =
  144. "Use WASD keys to move, RMB to rotate view\n"
  145. "LMB to set destination, SHIFT+LMB to spawn a Jack\n"
  146. "MMB or O key to add obstacles or remove obstacles/agents\n"
  147. "F5 to save scene, F7 to load\n"
  148. "Tab to toggle navigation mesh streaming\n"
  149. "Space to toggle debug geometry\n"
  150. "F12 to toggle this instruction text";
  151. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  152. // The text has multiple rows. Center them in relation to each other
  153. instructionText.textAlignment = HA_CENTER;
  154. // Position the text relative to the screen center
  155. instructionText.horizontalAlignment = HA_CENTER;
  156. instructionText.verticalAlignment = VA_CENTER;
  157. instructionText.SetPosition(0, ui.root.height / 4);
  158. }
  159. void SetupViewport()
  160. {
  161. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  162. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  163. renderer.viewports[0] = viewport;
  164. }
  165. void SubscribeToEvents()
  166. {
  167. // Subscribe HandleUpdate() function for processing update events
  168. SubscribeToEvent("Update", "HandleUpdate");
  169. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request debug geometry
  170. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  171. // Subscribe HandleCrowdAgentFailure() function for resolving invalidation issues with agents, during which we
  172. // use a larger extents for finding a point on the navmesh to fix the agent's position
  173. SubscribeToEvent("CrowdAgentFailure", "HandleCrowdAgentFailure");
  174. // Subscribe HandleCrowdAgentReposition() function for controlling the animation
  175. SubscribeToEvent("CrowdAgentReposition", "HandleCrowdAgentReposition");
  176. // Subscribe HandleCrowdAgentFormation() function for positioning agent into a formation
  177. SubscribeToEvent("CrowdAgentFormation", "HandleCrowdAgentFormation");
  178. }
  179. void CreateMushroom(const Vector3& pos)
  180. {
  181. Node@ mushroomNode = scene_.CreateChild("Mushroom");
  182. mushroomNode.position = pos;
  183. mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  184. mushroomNode.SetScale(2.0f + Random(0.5f));
  185. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  186. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  187. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  188. mushroomObject.castShadows = true;
  189. // Create the navigation Obstacle component and set its height & radius proportional to scale
  190. Obstacle@ obstacle = mushroomNode.CreateComponent("Obstacle");
  191. obstacle.radius = mushroomNode.scale.x;
  192. obstacle.height = mushroomNode.scale.y;
  193. }
  194. void SpawnJack(const Vector3& pos, Node@ jackGroup)
  195. {
  196. Node@ jackNode = jackGroup.CreateChild("Jack");
  197. jackNode.position = pos;
  198. AnimatedModel@ modelObject = jackNode.CreateComponent("AnimatedModel");
  199. modelObject.model = cache.GetResource("Model", "Models/Jack.mdl");
  200. modelObject.material = cache.GetResource("Material", "Materials/Jack.xml");
  201. modelObject.castShadows = true;
  202. jackNode.CreateComponent("AnimationController");
  203. // Create a CrowdAgent component and set its height and realistic max speed/acceleration. Use default radius
  204. CrowdAgent@ agent = jackNode.CreateComponent("CrowdAgent");
  205. agent.height = 2.0f;
  206. agent.maxSpeed = 3.0f;
  207. agent.maxAccel = 5.0f;
  208. }
  209. void CreateBoxOffMeshConnections(DynamicNavigationMesh@ navMesh, Node@ boxGroup)
  210. {
  211. Array<Node@>@ boxes = boxGroup.GetChildren();
  212. for (uint i=0; i < boxes.length; ++i)
  213. {
  214. Node@ box = boxes[i];
  215. Vector3 boxPos = box.position;
  216. float boxHalfSize = box.scale.x / 2;
  217. // Create 2 empty nodes for the start & end points of the connection. Note that order matters only when using one-way/unidirectional connection.
  218. Node@ connectionStart = box.CreateChild("ConnectionStart");
  219. connectionStart.worldPosition = navMesh.FindNearestPoint(boxPos + Vector3(boxHalfSize, -boxHalfSize, 0)); // Base of box
  220. Node@ connectionEnd = connectionStart.CreateChild("ConnectionEnd");
  221. connectionEnd.worldPosition = navMesh.FindNearestPoint(boxPos + Vector3(boxHalfSize, boxHalfSize, 0)); // Top of box
  222. // Create the OffMeshConnection component to one node and link the other node
  223. OffMeshConnection@ connection = connectionStart.CreateComponent("OffMeshConnection");
  224. connection.endPoint = connectionEnd;
  225. }
  226. }
  227. void CreateMovingBarrels(DynamicNavigationMesh@ navMesh)
  228. {
  229. Node@ barrel = scene_.CreateChild("Barrel");
  230. StaticModel@ model = barrel.CreateComponent("StaticModel");
  231. model.model = cache.GetResource("Model", "Models/Cylinder.mdl");
  232. Material@ material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  233. model.material = material;
  234. material.textures[TU_DIFFUSE] = cache.GetResource("Texture2D", "Textures/TerrainDetail2.dds");
  235. model.castShadows = true;
  236. for (uint i = 0; i < 20; ++i)
  237. {
  238. Node@ clone = barrel.Clone();
  239. float size = 0.5 + Random(1);
  240. clone.scale = Vector3(size / 1.5, size * 2.0, size / 1.5);
  241. clone.position = navMesh.FindNearestPoint(Vector3(Random(80.0) - 40.0, size * 0.5 , Random(80.0) - 40.0));
  242. CrowdAgent@ agent = clone.CreateComponent("CrowdAgent");
  243. agent.radius = clone.scale.x * 0.5f;
  244. agent.height = size;
  245. agent.navigationQuality = NAVIGATIONQUALITY_LOW;
  246. }
  247. barrel.Remove();
  248. }
  249. void SetPathPoint(bool spawning)
  250. {
  251. Vector3 hitPos;
  252. Drawable@ hitDrawable;
  253. if (Raycast(250.0f, hitPos, hitDrawable))
  254. {
  255. DynamicNavigationMesh@ navMesh = scene_.GetComponent("DynamicNavigationMesh");
  256. Vector3 pathPos = navMesh.FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
  257. Node@ jackGroup = scene_.GetChild("Jacks");
  258. if (spawning)
  259. // Spawn a jack at the target position
  260. SpawnJack(pathPos, jackGroup);
  261. else
  262. // Set crowd agents target position
  263. cast<CrowdManager>(scene_.GetComponent("CrowdManager")).SetCrowdTarget(pathPos, jackGroup);
  264. }
  265. }
  266. void AddOrRemoveObject()
  267. {
  268. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  269. Vector3 hitPos;
  270. Drawable@ hitDrawable;
  271. if (Raycast(250.0f, hitPos, hitDrawable))
  272. {
  273. Node@ hitNode = hitDrawable.node;
  274. // Note that navmesh rebuild happens when the Obstacle component is removed
  275. if (hitNode.name == "Mushroom")
  276. hitNode.Remove();
  277. else if (hitNode.name == "Jack")
  278. hitNode.Remove();
  279. else
  280. CreateMushroom(hitPos);
  281. }
  282. }
  283. bool Raycast(float maxDistance, Vector3& hitPos, Drawable@& hitDrawable)
  284. {
  285. hitDrawable = null;
  286. IntVector2 pos = ui.cursorPosition;
  287. // Check the cursor is visible and there is no UI element in front of the cursor
  288. if (!ui.cursor.visible || ui.GetElementAt(pos, true) !is null)
  289. return false;
  290. Camera@ camera = cameraNode.GetComponent("Camera");
  291. Ray cameraRay = camera.GetScreenRay(float(pos.x) / graphics.width, float(pos.y) / graphics.height);
  292. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  293. // Note the convenience accessor to scene's Octree component
  294. RayQueryResult result = scene_.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  295. if (result.drawable !is null)
  296. {
  297. hitPos = result.position;
  298. hitDrawable = result.drawable;
  299. return true;
  300. }
  301. return false;
  302. }
  303. void MoveCamera(float timeStep)
  304. {
  305. input.mouseVisible = input.mouseMode != MM_RELATIVE;
  306. bool mouseDown = input.mouseButtonDown[MOUSEB_RIGHT];
  307. // Override the MM_RELATIVE mouse grabbed settings, to allow interaction with UI
  308. input.mouseGrabbed = mouseDown;
  309. // Right mouse button controls mouse cursor visibility: hide when pressed
  310. ui.cursor.visible = !mouseDown;
  311. // Do not move if the UI has a focused element (the console)
  312. if (ui.focusElement !is null)
  313. return;
  314. // Movement speed as world units per second
  315. const float MOVE_SPEED = 20.0f;
  316. // Mouse sensitivity as degrees per pixel
  317. const float MOUSE_SENSITIVITY = 0.1f;
  318. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  319. // Only move the camera when the cursor is hidden
  320. if (!ui.cursor.visible)
  321. {
  322. IntVector2 mouseMove = input.mouseMove;
  323. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  324. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  325. pitch = Clamp(pitch, -90.0f, 90.0f);
  326. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  327. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  328. }
  329. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  330. if (input.keyDown[KEY_W])
  331. cameraNode.Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  332. if (input.keyDown[KEY_S])
  333. cameraNode.Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  334. if (input.keyDown[KEY_A])
  335. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  336. if (input.keyDown[KEY_D])
  337. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  338. // Set destination or spawn a jack with left mouse button
  339. if (input.mouseButtonPress[MOUSEB_LEFT])
  340. SetPathPoint(input.qualifierDown[QUAL_SHIFT]);
  341. // Add new obstacle or remove existing obstacle/agent with middle mouse button
  342. else if (input.mouseButtonPress[MOUSEB_MIDDLE] || input.keyPress[KEY_O])
  343. AddOrRemoveObject();
  344. // Check for loading/saving the scene from/to the file Data/Scenes/CrowdNavigation.xml relative to the executable directory
  345. if (input.keyPress[KEY_F5])
  346. {
  347. File saveFile(fileSystem.programDir + "Data/Scenes/CrowdNavigation.xml", FILE_WRITE);
  348. scene_.SaveXML(saveFile);
  349. }
  350. else if (input.keyPress[KEY_F7])
  351. {
  352. File loadFile(fileSystem.programDir + "Data/Scenes/CrowdNavigation.xml", FILE_READ);
  353. scene_.LoadXML(loadFile);
  354. }
  355. // Toggle debug geometry with space
  356. else if (input.keyPress[KEY_SPACE])
  357. drawDebug = !drawDebug;
  358. // Toggle instruction text with F12
  359. else if (input.keyPress[KEY_F12])
  360. {
  361. UIElement@ instruction = ui.root.GetChild(INSTRUCTION);
  362. instruction.visible = !instruction.visible;
  363. }
  364. }
  365. void ToggleStreaming(bool enabled)
  366. {
  367. DynamicNavigationMesh@ navMesh = scene_.GetComponent("DynamicNavigationMesh");
  368. if (enabled)
  369. {
  370. int maxTiles = (2 * STREAMING_DISTANCE + 1) * (2 * STREAMING_DISTANCE + 1);
  371. BoundingBox boundingBox = navMesh.boundingBox;
  372. SaveNavigationData();
  373. navMesh.Allocate(boundingBox, maxTiles);
  374. }
  375. else
  376. navMesh.Build();
  377. }
  378. void UpdateStreaming()
  379. {
  380. DynamicNavigationMesh@ navMesh = scene_.GetComponent("DynamicNavigationMesh");
  381. // Center the navigation mesh at the crowd of jacks
  382. Vector3 averageJackPosition;
  383. Node@ jackGroup = scene_.GetChild("Jacks");
  384. if (jackGroup !is null)
  385. {
  386. for (uint i = 0; i < jackGroup.numChildren; ++i)
  387. averageJackPosition += jackGroup.children[i].worldPosition;
  388. averageJackPosition /= jackGroup.numChildren;
  389. }
  390. // Compute currently loaded area
  391. IntVector2 jackTile = navMesh.GetTileIndex(averageJackPosition);
  392. IntVector2 beginTile = VectorMax(IntVector2(0, 0), jackTile - IntVector2(1, 1) * STREAMING_DISTANCE);
  393. IntVector2 endTile = VectorMin(jackTile + IntVector2(1, 1) * STREAMING_DISTANCE, navMesh.numTiles - IntVector2(1, 1));
  394. // Remove tiles
  395. for (uint i = 0; i < addedTiles.length;)
  396. {
  397. IntVector2 tileIdx = addedTiles[i];
  398. if (beginTile.x <= tileIdx.x && tileIdx.x <= endTile.x && beginTile.y <= tileIdx.y && tileIdx.y <= endTile.y)
  399. ++i;
  400. else
  401. {
  402. addedTiles.Erase(i);
  403. navMesh.RemoveTile(tileIdx);
  404. }
  405. }
  406. // Add tiles
  407. for (int z = beginTile.y; z <= endTile.y; ++z)
  408. for (int x = beginTile.x; x <= endTile.x; ++x)
  409. {
  410. const IntVector2 tileIdx(x, z);
  411. int tileDataIdx = navigationTilesIdx.Find(tileIdx);
  412. if (!navMesh.HasTile(tileIdx) && tileDataIdx != -1)
  413. {
  414. addedTiles.Push(tileIdx);
  415. navMesh.AddTile(navigationTilesData[tileDataIdx]);
  416. }
  417. }
  418. }
  419. void SaveNavigationData()
  420. {
  421. DynamicNavigationMesh@ navMesh = scene_.GetComponent("DynamicNavigationMesh");
  422. navigationTilesData.Clear();
  423. navigationTilesIdx.Clear();
  424. addedTiles.Clear();
  425. IntVector2 numTiles = navMesh.numTiles;
  426. for (int z = 0; z < numTiles.y; ++z)
  427. for (int x = 0; x < numTiles.x; ++x)
  428. {
  429. IntVector2 idx(x, z);
  430. navigationTilesData.Push(navMesh.GetTileData(idx));
  431. navigationTilesIdx.Push(idx);
  432. }
  433. }
  434. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  435. {
  436. // Take the frame time step, which is stored as a float
  437. float timeStep = eventData["TimeStep"].GetFloat();
  438. // Move the camera, scale movement with time step
  439. MoveCamera(timeStep);
  440. // Update streaming
  441. if (input.keyPress[KEY_TAB])
  442. {
  443. useStreaming = !useStreaming;
  444. ToggleStreaming(useStreaming);
  445. }
  446. if (useStreaming)
  447. UpdateStreaming();
  448. }
  449. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  450. {
  451. if (drawDebug)
  452. {
  453. // Visualize navigation mesh, obstacles and off-mesh connections
  454. cast<DynamicNavigationMesh>(scene_.GetComponent("DynamicNavigationMesh")).DrawDebugGeometry(true);
  455. // Visualize agents' path and position to reach
  456. cast<CrowdManager>(scene_.GetComponent("CrowdManager")).DrawDebugGeometry(true);
  457. }
  458. }
  459. void HandleCrowdAgentFailure(StringHash eventType, VariantMap& eventData)
  460. {
  461. Node@ node = eventData["Node"].GetPtr();
  462. int state = eventData["CrowdAgentState"].GetInt();
  463. // If the agent's state is invalid, likely from spawning on the side of a box, find a point in a larger area
  464. if (state == CA_STATE_INVALID)
  465. {
  466. // Get a point on the navmesh using more generous extents
  467. Vector3 newPos = cast<DynamicNavigationMesh>(scene_.GetComponent("DynamicNavigationMesh")).FindNearestPoint(node.position, Vector3(5.0f,5.0f,5.0f));
  468. // Set the new node position, CrowdAgent component will automatically reset the state of the agent
  469. node.position = newPos;
  470. }
  471. }
  472. void HandleCrowdAgentFormation(StringHash eventType, VariantMap& eventData)
  473. {
  474. uint index = eventData["Index"].GetUInt();
  475. uint size = eventData["Size"].GetUInt();
  476. Vector3 position = eventData["Position"].GetVector3();
  477. // The first agent will always move to the exact position, all other agents will select a random point nearby
  478. if (index > 0)
  479. {
  480. CrowdManager@ crowdManager =GetEventSender();
  481. CrowdAgent@ agent = eventData["CrowdAgent"].GetPtr();
  482. eventData["Position"] = crowdManager.GetRandomPointInCircle(position, agent.radius, agent.queryFilterType);
  483. }
  484. }
  485. void HandleCrowdAgentReposition(StringHash eventType, VariantMap& eventData)
  486. {
  487. const String WALKING_ANI = "Models/Jack_Walk.ani";
  488. Node@ node = eventData["Node"].GetPtr();
  489. CrowdAgent@ agent = eventData["CrowdAgent"].GetPtr();
  490. Vector3 velocity = eventData["Velocity"].GetVector3();
  491. float timeStep = eventData["TimeStep"].GetFloat();
  492. // Only Jack agent has animation controller
  493. AnimationController@ animCtrl = node.GetComponent("AnimationController");
  494. if (animCtrl !is null)
  495. {
  496. float speed = velocity.length;
  497. if (animCtrl.IsPlaying(WALKING_ANI))
  498. {
  499. float speedRatio = speed / agent.maxSpeed;
  500. // Face the direction of its velocity but moderate the turning speed based on the speed ratio and timeStep
  501. node.rotation = node.rotation.Slerp(Quaternion(Vector3::FORWARD, velocity), 10.f * timeStep * speedRatio);
  502. // Throttle the animation speed based on agent speed ratio (ratio = 1 is full throttle)
  503. animCtrl.SetSpeed(WALKING_ANI, speedRatio * 1.5f);
  504. }
  505. else
  506. animCtrl.Play(WALKING_ANI, 0, true, 0.1f);
  507. // If speed is too low then stop the animation
  508. if (speed < agent.radius)
  509. animCtrl.Stop(WALKING_ANI, 0.5f);
  510. }
  511. }
  512. // Create XML patch instructions for screen joystick layout specific to this sample app
  513. String patchInstructions =
  514. "<patch>" +
  515. " <add sel=\"/element\">" +
  516. " <element type=\"Button\">" +
  517. " <attribute name=\"Name\" value=\"Button3\" />" +
  518. " <attribute name=\"Position\" value=\"-120 -120\" />" +
  519. " <attribute name=\"Size\" value=\"96 96\" />" +
  520. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
  521. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
  522. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
  523. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
  524. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
  525. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
  526. " <element type=\"Text\">" +
  527. " <attribute name=\"Name\" value=\"Label\" />" +
  528. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
  529. " <attribute name=\"Vert Alignment\" value=\"Center\" />" +
  530. " <attribute name=\"Color\" value=\"0 0 0 1\" />" +
  531. " <attribute name=\"Text\" value=\"Spawn\" />" +
  532. " </element>" +
  533. " <element type=\"Text\">" +
  534. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  535. " <attribute name=\"Text\" value=\"LSHIFT\" />" +
  536. " </element>" +
  537. " <element type=\"Text\">" +
  538. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  539. " <attribute name=\"Text\" value=\"LEFT\" />" +
  540. " </element>" +
  541. " </element>" +
  542. " <element type=\"Button\">" +
  543. " <attribute name=\"Name\" value=\"Button4\" />" +
  544. " <attribute name=\"Position\" value=\"-120 -12\" />" +
  545. " <attribute name=\"Size\" value=\"96 96\" />" +
  546. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
  547. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
  548. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
  549. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
  550. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
  551. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
  552. " <element type=\"Text\">" +
  553. " <attribute name=\"Name\" value=\"Label\" />" +
  554. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
  555. " <attribute name=\"Vert Alignment\" value=\"Center\" />" +
  556. " <attribute name=\"Color\" value=\"0 0 0 1\" />" +
  557. " <attribute name=\"Text\" value=\"Obstacles\" />" +
  558. " </element>" +
  559. " <element type=\"Text\">" +
  560. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  561. " <attribute name=\"Text\" value=\"MIDDLE\" />" +
  562. " </element>" +
  563. " </element>" +
  564. " </add>" +
  565. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  566. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" +
  567. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  568. " <element type=\"Text\">" +
  569. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  570. " <attribute name=\"Text\" value=\"LEFT\" />" +
  571. " </element>" +
  572. " </add>" +
  573. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  574. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
  575. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  576. " <element type=\"Text\">" +
  577. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  578. " <attribute name=\"Text\" value=\"SPACE\" />" +
  579. " </element>" +
  580. " </add>" +
  581. "</patch>";