15_Navigation.lua 19 KB

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