15_Navigation.as 15 KB

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