15_Navigation.as 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. // Navigation example.
  2. // This sample demonstrates:
  3. // - Generating a navigation mesh into the scene
  4. // - Performing path queries to the navigation mesh
  5. // - Rebuilding the navigation mesh partially when adding or removing objects
  6. // - Visualizing custom debug geometry
  7. // - Raycasting drawable components
  8. // - Making a node follow the Detour path
  9. #include "Scripts/Utilities/Sample.as"
  10. Vector3 endPos;
  11. Array<Vector3> currentPath;
  12. Node@ jackNode;
  13. void Start()
  14. {
  15. // Execute the common startup for samples
  16. SampleStart();
  17. // Create the scene content
  18. CreateScene();
  19. // Create the UI content
  20. CreateUI();
  21. // Setup the viewport for displaying the scene
  22. SetupViewport();
  23. // Set the mouse mode to use in the sample
  24. SampleInitMouseMode(MM_RELATIVE);
  25. // Hook up to the frame update and render post-update events
  26. SubscribeToEvents();
  27. }
  28. void CreateScene()
  29. {
  30. scene_ = Scene();
  31. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  32. // Also create a DebugRenderer component so that we can draw debug geometry
  33. scene_.CreateComponent("Octree");
  34. scene_.CreateComponent("DebugRenderer");
  35. // Create scene node & StaticModel component for showing a static plane
  36. Node@ planeNode = scene_.CreateChild("Plane");
  37. planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
  38. StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
  39. planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  40. planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  41. // Create a Zone component for ambient lighting & fog control
  42. Node@ zoneNode = scene_.CreateChild("Zone");
  43. Zone@ zone = zoneNode.CreateComponent("Zone");
  44. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  45. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  46. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  47. zone.fogStart = 100.0f;
  48. zone.fogEnd = 300.0f;
  49. // Create a directional light to the world. Enable cascaded shadows on it
  50. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  51. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  52. Light@ light = lightNode.CreateComponent("Light");
  53. light.lightType = LIGHT_DIRECTIONAL;
  54. light.castShadows = true;
  55. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  56. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  57. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  58. // Create some mushrooms
  59. const uint NUM_MUSHROOMS = 100;
  60. for (uint i = 0; i < NUM_MUSHROOMS; ++i)
  61. CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  62. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  63. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  64. const uint NUM_BOXES = 20;
  65. for (uint i = 0; i < NUM_BOXES; ++i)
  66. {
  67. Node@ boxNode = scene_.CreateChild("Box");
  68. float size = 1.0f + Random(10.0f);
  69. boxNode.position = Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f);
  70. boxNode.SetScale(size);
  71. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  72. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  73. boxObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  74. boxObject.castShadows = true;
  75. if (size >= 3.0f)
  76. boxObject.occluder = true;
  77. }
  78. // Create Jack node that will follow the path
  79. jackNode = scene_.CreateChild("Jack");
  80. jackNode.position = Vector3(-5.0f, 0.0f, 20.0f);
  81. AnimatedModel@ modelObject = jackNode.CreateComponent("AnimatedModel");
  82. modelObject.model = cache.GetResource("Model", "Models/Jack.mdl");
  83. modelObject.material = cache.GetResource("Material", "Materials/Jack.xml");
  84. modelObject.castShadows = true;
  85. // Create a NavigationMesh component to the scene root
  86. NavigationMesh@ navMesh = scene_.CreateComponent("NavigationMesh");
  87. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  88. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  89. scene_.CreateComponent("Navigable");
  90. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  91. // in the scene and still update the mesh correctly
  92. navMesh.padding = Vector3(0.0f, 10.0f, 0.0f);
  93. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  94. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  95. // it will use renderable geometry instead
  96. navMesh.Build();
  97. // Create the camera. Limit far clip distance to match the fog
  98. cameraNode = scene_.CreateChild("Camera");
  99. Camera@ camera = cameraNode.CreateComponent("Camera");
  100. camera.farClip = 300.0f;
  101. // Set an initial position for the camera scene node above the plane and looking down
  102. cameraNode.position = Vector3(0.0f, 50.0f, 0.0f);
  103. pitch = 80.0f;
  104. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  105. }
  106. void CreateUI()
  107. {
  108. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  109. // control the camera, and when visible, it will point the raycast target
  110. XMLFile@ style = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
  111. Cursor@ cursor = Cursor();
  112. cursor.SetStyleAuto(style);
  113. ui.cursor = cursor;
  114. // Set starting position of the cursor at the rendering window center
  115. cursor.SetPosition(graphics.width / 2, graphics.height / 2);
  116. // Construct new Text object, set string to display and font to use
  117. Text@ instructionText = ui.root.CreateChild("Text");
  118. instructionText.text =
  119. "Use WASD keys to move, RMB to rotate view\n"
  120. "LMB to set destination, SHIFT+LMB to teleport\n"
  121. "MMB or O key to add or remove obstacles\n"
  122. "Space to toggle debug geometry";
  123. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  124. // The text has multiple rows. Center them in relation to each other
  125. instructionText.textAlignment = HA_CENTER;
  126. // Position the text relative to the screen center
  127. instructionText.horizontalAlignment = HA_CENTER;
  128. instructionText.verticalAlignment = VA_CENTER;
  129. instructionText.SetPosition(0, ui.root.height / 4);
  130. }
  131. void SetupViewport()
  132. {
  133. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  134. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  135. renderer.viewports[0] = viewport;
  136. }
  137. void SubscribeToEvents()
  138. {
  139. // Subscribe HandleUpdate() function for processing update events
  140. SubscribeToEvent("Update", "HandleUpdate");
  141. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  142. // debug geometry
  143. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  144. }
  145. void MoveCamera(float timeStep)
  146. {
  147. input.mouseVisible = input.mouseMode != MM_RELATIVE;
  148. bool mouseDown = input.mouseButtonDown[MOUSEB_RIGHT];
  149. // Override the MM_RELATIVE mouse grabbed settings, to allow interaction with UI
  150. input.mouseGrabbed = mouseDown;
  151. // Right mouse button controls mouse cursor visibility: hide when pressed
  152. ui.cursor.visible = !mouseDown;
  153. // Do not move if the UI has a focused element (the console)
  154. if (ui.focusElement !is null)
  155. return;
  156. // Movement speed as world units per second
  157. const float MOVE_SPEED = 20.0f;
  158. // Mouse sensitivity as degrees per pixel
  159. const float MOUSE_SENSITIVITY = 0.1f;
  160. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  161. // Only move the camera when the cursor is hidden
  162. if (!ui.cursor.visible)
  163. {
  164. IntVector2 mouseMove = input.mouseMove;
  165. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  166. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  167. pitch = Clamp(pitch, -90.0f, 90.0f);
  168. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  169. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  170. }
  171. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  172. if (input.keyDown[KEY_W])
  173. cameraNode.Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  174. if (input.keyDown[KEY_S])
  175. cameraNode.Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  176. if (input.keyDown[KEY_A])
  177. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  178. if (input.keyDown[KEY_D])
  179. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  180. // Set destination or teleport with left mouse button
  181. if (input.mouseButtonPress[MOUSEB_LEFT])
  182. SetPathPoint();
  183. // Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  184. if (input.mouseButtonPress[MOUSEB_MIDDLE] || input.keyPress[KEY_O])
  185. AddOrRemoveObject();
  186. // Toggle debug geometry with space
  187. if (input.keyPress[KEY_SPACE])
  188. drawDebug = !drawDebug;
  189. }
  190. void SetPathPoint()
  191. {
  192. Vector3 hitPos;
  193. Drawable@ hitDrawable;
  194. NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
  195. if (Raycast(250.0f, hitPos, hitDrawable))
  196. {
  197. Vector3 pathPos = navMesh.FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
  198. if (input.qualifierDown[QUAL_SHIFT])
  199. {
  200. // Teleport
  201. currentPath.Clear();
  202. jackNode.LookAt(Vector3(pathPos.x, jackNode.position.y, pathPos.z), Vector3::UP);
  203. jackNode.position = pathPos;
  204. }
  205. else
  206. {
  207. // Calculate path from Jack's current position to the end point
  208. endPos = pathPos;
  209. currentPath = navMesh.FindPath(jackNode.position, endPos);
  210. }
  211. }
  212. }
  213. void AddOrRemoveObject()
  214. {
  215. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  216. Vector3 hitPos;
  217. Drawable@ hitDrawable;
  218. if (Raycast(250.0f, hitPos, hitDrawable))
  219. {
  220. // The part of the navigation mesh we must update, which is the world bounding box of the associated
  221. // drawable component
  222. BoundingBox updateBox;
  223. Node@ hitNode = hitDrawable.node;
  224. if (hitNode.name == "Mushroom")
  225. {
  226. updateBox = hitDrawable.worldBoundingBox;
  227. hitNode.Remove();
  228. }
  229. else
  230. {
  231. Node@ newNode = CreateMushroom(hitPos);
  232. StaticModel@ newObject = newNode.GetComponent("StaticModel");
  233. updateBox = newObject.worldBoundingBox;
  234. }
  235. // Rebuild part of the navigation mesh, then rebuild the path if applicable
  236. NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
  237. navMesh.Build(updateBox);
  238. if (currentPath.length > 0)
  239. currentPath = navMesh.FindPath(jackNode.position, endPos);
  240. }
  241. }
  242. Node@ CreateMushroom(const Vector3& pos)
  243. {
  244. Node@ mushroomNode = scene_.CreateChild("Mushroom");
  245. mushroomNode.position = pos;
  246. mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  247. mushroomNode.SetScale(2.0f + Random(0.5f));
  248. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  249. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  250. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  251. mushroomObject.castShadows = true;
  252. return mushroomNode;
  253. }
  254. bool Raycast(float maxDistance, Vector3& hitPos, Drawable@& hitDrawable)
  255. {
  256. hitDrawable = null;
  257. IntVector2 pos = ui.cursorPosition;
  258. // Check the cursor is visible and there is no UI element in front of the cursor
  259. if (!ui.cursor.visible || ui.GetElementAt(pos, true) !is null)
  260. return false;
  261. Camera@ camera = cameraNode.GetComponent("Camera");
  262. Ray cameraRay = camera.GetScreenRay(float(pos.x) / graphics.width, float(pos.y) / graphics.height);
  263. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  264. // Note the convenience accessor to scene's Octree component
  265. RayQueryResult result = scene_.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  266. if (result.drawable !is null)
  267. {
  268. hitPos = result.position;
  269. hitDrawable = result.drawable;
  270. return true;
  271. }
  272. return false;
  273. }
  274. void FollowPath(float timeStep)
  275. {
  276. if (currentPath.length > 0)
  277. {
  278. Vector3 nextWaypoint = currentPath[0]; // NB: currentPath[0] is the next waypoint in order
  279. // Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target
  280. float move = 5.0f * timeStep;
  281. float distance = (jackNode.position - nextWaypoint).length;
  282. if (move > distance)
  283. move = distance;
  284. jackNode.LookAt(nextWaypoint, Vector3::UP);
  285. jackNode.Translate(Vector3::FORWARD * move);
  286. // Remove waypoint if reached it
  287. if (distance < 0.1)
  288. currentPath.Erase(0);
  289. }
  290. }
  291. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  292. {
  293. // Take the frame time step, which is stored as a float
  294. float timeStep = eventData["TimeStep"].GetFloat();
  295. // Move the camera, scale movement with time step
  296. MoveCamera(timeStep);
  297. // Make Jack follow the Detour path
  298. FollowPath(timeStep);
  299. }
  300. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  301. {
  302. // If draw debug mode is enabled, draw navigation mesh debug geometry
  303. if (drawDebug)
  304. {
  305. NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
  306. navMesh.DrawDebugGeometry(true);
  307. }
  308. if (currentPath.length > 0)
  309. {
  310. // Visualize the current calculated path
  311. // Note the convenience accessor to the DebugRenderer component
  312. DebugRenderer@ debug = scene_.debugRenderer;
  313. debug.AddBoundingBox(BoundingBox(endPos - Vector3(0.1f, 0.1f, 0.1f), endPos + Vector3(0.1f, 0.1f, 0.1f)),
  314. Color(1.0f, 1.0f, 1.0f));
  315. // Draw the path with a small upward bias so that it does not clip into the surfaces
  316. Vector3 bias(0.0f, 0.05f, 0.0f);
  317. debug.AddLine(jackNode.position + bias, currentPath[0] + bias, Color(1.0f, 1.0f, 1.0f));
  318. if (currentPath.length > 1)
  319. {
  320. for (uint i = 0; i < currentPath.length - 1; ++i)
  321. debug.AddLine(currentPath[i] + bias, currentPath[i + 1] + bias, Color(1.0f, 1.0f, 1.0f));
  322. }
  323. }
  324. }
  325. // Create XML patch instructions for screen joystick layout specific to this sample app
  326. String patchInstructions =
  327. "<patch>" +
  328. " <add sel=\"/element\">" +
  329. " <element type=\"Button\">" +
  330. " <attribute name=\"Name\" value=\"Button3\" />" +
  331. " <attribute name=\"Position\" value=\"-120 -120\" />" +
  332. " <attribute name=\"Size\" value=\"96 96\" />" +
  333. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
  334. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
  335. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
  336. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
  337. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
  338. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
  339. " <element type=\"Text\">" +
  340. " <attribute name=\"Name\" value=\"Label\" />" +
  341. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
  342. " <attribute name=\"Vert Alignment\" value=\"Center\" />" +
  343. " <attribute name=\"Color\" value=\"0 0 0 1\" />" +
  344. " <attribute name=\"Text\" value=\"Teleport\" />" +
  345. " </element>" +
  346. " <element type=\"Text\">" +
  347. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  348. " <attribute name=\"Text\" value=\"LSHIFT\" />" +
  349. " </element>" +
  350. " <element type=\"Text\">" +
  351. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  352. " <attribute name=\"Text\" value=\"LEFT\" />" +
  353. " </element>" +
  354. " </element>" +
  355. " <element type=\"Button\">" +
  356. " <attribute name=\"Name\" value=\"Button4\" />" +
  357. " <attribute name=\"Position\" value=\"-120 -12\" />" +
  358. " <attribute name=\"Size\" value=\"96 96\" />" +
  359. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
  360. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
  361. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
  362. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
  363. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
  364. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
  365. " <element type=\"Text\">" +
  366. " <attribute name=\"Name\" value=\"Label\" />" +
  367. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
  368. " <attribute name=\"Vert Alignment\" value=\"Center\" />" +
  369. " <attribute name=\"Color\" value=\"0 0 0 1\" />" +
  370. " <attribute name=\"Text\" value=\"Obstacles\" />" +
  371. " </element>" +
  372. " <element type=\"Text\">" +
  373. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  374. " <attribute name=\"Text\" value=\"MIDDLE\" />" +
  375. " </element>" +
  376. " </element>" +
  377. " </add>" +
  378. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  379. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" +
  380. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  381. " <element type=\"Text\">" +
  382. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  383. " <attribute name=\"Text\" value=\"LEFT\" />" +
  384. " </element>" +
  385. " </add>" +
  386. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  387. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
  388. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  389. " <element type=\"Text\">" +
  390. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  391. " <attribute name=\"Text\" value=\"SPACE\" />" +
  392. " </element>" +
  393. " </add>" +
  394. "</patch>";