39_CrowdNavigation.lua 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. -- CrowdNavigation example.
  2. -- This sample demonstrates:
  3. -- - Generating a cached navigation mesh into the scene
  4. -- - Performing path queries to the navigation mesh
  5. -- - Adding and removing obstacles at runtime from the dynamic mesh
  6. -- - Visualizing custom debug geometry
  7. -- - Raycasting drawable components
  8. -- - Making a node follow the Detour path
  9. -- - Crowd movement management
  10. require "LuaScripts/Utilities/Sample"
  11. local endPos = nil
  12. local currentPath = {}
  13. local jackNodes = {}
  14. local crowdManager = nil
  15. local mushrooms = {}
  16. function Start()
  17. -- Execute the common startup for samples
  18. SampleStart()
  19. -- Create the scene content
  20. CreateScene()
  21. -- Create the UI content
  22. CreateUI()
  23. -- Setup the viewport for displaying the scene
  24. SetupViewport()
  25. -- Hook up to the frame update and render post-update events
  26. SubscribeToEvents()
  27. end
  28. function CreateScene()
  29. scene_ = Scene()
  30. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  31. -- Also create a DebugRenderer component so that we can draw debug geometry
  32. scene_:CreateComponent("Octree")
  33. scene_:CreateComponent("DebugRenderer")
  34. -- Create scene node & StaticModel component for showing a static plane
  35. local planeNode = scene_:CreateChild("Plane")
  36. planeNode.scale = Vector3(100.0, 1.0, 100.0)
  37. local planeObject = planeNode:CreateComponent("StaticModel")
  38. planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
  39. planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  40. -- Create a Zone component for ambient lighting & fog control
  41. local zoneNode = scene_:CreateChild("Zone")
  42. local zone = zoneNode:CreateComponent("Zone")
  43. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  44. zone.ambientColor = Color(0.15, 0.15, 0.15)
  45. zone.fogColor = Color(0.5, 0.5, 0.7)
  46. zone.fogStart = 100.0
  47. zone.fogEnd = 300.0
  48. -- Create a directional light to the world. Enable cascaded shadows on it
  49. local lightNode = scene_:CreateChild("DirectionalLight")
  50. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  51. local light = lightNode:CreateComponent("Light")
  52. light.lightType = LIGHT_DIRECTIONAL
  53. light.castShadows = true
  54. light.shadowBias = BiasParameters(0.00025, 0.5)
  55. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  56. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  57. -- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  58. -- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  59. local NUM_BOXES = 20
  60. for i = 1, NUM_BOXES do
  61. local boxNode = scene_:CreateChild("Box")
  62. local size = 1.0 + Random(10.0)
  63. boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0)
  64. boxNode:SetScale(size)
  65. local boxObject = boxNode:CreateComponent("StaticModel")
  66. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  67. boxObject.material = cache:GetResource("Material", "Materials/Stone.xml")
  68. boxObject.castShadows = true
  69. if size >= 3.0 then
  70. boxObject.occluder = true
  71. end
  72. end
  73. -- Create a DynamicNavigationMesh component to the scene root
  74. local navMesh = scene_:CreateComponent("DynamicNavigationMesh")
  75. -- Set the agent height large enough to exclude the layers under boxes
  76. navMesh.agentHeight = 10
  77. -- Set nav mesh tilesize to something reasonable
  78. navMesh.tileSize = 64
  79. -- Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  80. -- navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  81. scene_:CreateComponent("Navigable")
  82. -- Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  83. -- in the scene and still update the mesh correctly
  84. navMesh.padding = Vector3(0.0, 10.0, 0.0)
  85. -- Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  86. -- physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  87. -- it will use renderable geometry instead
  88. navMesh:Build()
  89. crowdManager = scene_:CreateComponent("DetourCrowdManager")
  90. -- Create Jack node that will follow the path
  91. SpawnJack(Vector3(-5, 0, 20))
  92. -- Create some mushrooms
  93. local NUM_MUSHROOMS = 100
  94. for i = 1, NUM_MUSHROOMS do
  95. CreateMushroom(Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0))
  96. end
  97. -- Create the camera. Limit far clip distance to match the fog
  98. cameraNode = scene_:CreateChild("Camera")
  99. local camera = cameraNode:CreateComponent("Camera")
  100. camera.farClip = 300.0
  101. -- Set an initial position for the camera scene node above the plane
  102. cameraNode.position = Vector3(0.0, 5.0, 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 spawn a Jack\n"..
  117. "MMB 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. -- Subscribe HandleCrowdAgentFailure() function for resolving invalidation issues with agents, during which we
  139. -- use a larger extents for finding a point on the navmesh to fix the agent's position
  140. SubscribeToEvent("CrowdAgentFailure", "HandleCrowdAgentFailure")
  141. end
  142. function MoveCamera(timeStep)
  143. -- Right mouse button controls mouse cursor visibility: hide when pressed
  144. ui.cursor.visible = not input:GetMouseButtonDown(MOUSEB_RIGHT)
  145. -- Do not move if the UI has a focused element (the console)
  146. if ui.focusElement ~= nil then
  147. return
  148. end
  149. -- Movement speed as world units per second
  150. local MOVE_SPEED = 20.0
  151. -- Mouse sensitivity as degrees per pixel
  152. local MOUSE_SENSITIVITY = 0.1
  153. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  154. -- Only move the camera when the cursor is hidden
  155. if not ui.cursor.visible then
  156. local mouseMove = input.mouseMove
  157. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  158. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  159. pitch = Clamp(pitch, -90.0, 90.0)
  160. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  161. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  162. end
  163. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  164. if input:GetKeyDown(KEY_W) then
  165. cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  166. end
  167. if input:GetKeyDown(KEY_S) then
  168. cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  169. end
  170. if input:GetKeyDown(KEY_A) then
  171. cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  172. end
  173. if input:GetKeyDown(KEY_D) then
  174. cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  175. end
  176. -- Set destination or spawn a jack with left mouse button
  177. if input:GetMouseButtonPress(MOUSEB_LEFT) then
  178. SetPathPoint()
  179. end
  180. -- Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  181. if input:GetMouseButtonPress(MOUSEB_MIDDLE) then
  182. AddOrRemoveObject()
  183. end
  184. -- Toggle debug geometry with space
  185. if input:GetKeyPress(KEY_SPACE) then
  186. drawDebug = not drawDebug
  187. end
  188. end
  189. function SetPathPoint()
  190. local result, hitPos, hitDrawable = Raycast(250.0)
  191. local navMesh = scene_:GetComponent("DynamicNavigationMesh")
  192. if result then
  193. local pathPos = navMesh:FindNearestPoint(hitPos, Vector3.ONE)
  194. if input:GetQualifierDown(QUAL_SHIFT) then
  195. -- spawn a jack
  196. SpawnJack(pathPos)
  197. else
  198. -- Calculate path from Jack's current position to the end point
  199. local ct = table.maxn(jackNodes)
  200. if ct > 0 then
  201. for i = 1, ct do
  202. local agt = jackNodes[i]:GetComponent("CrowdAgent")
  203. agt.enabled = true
  204. if i == 1 then
  205. -- The first agent will always move to the exact target
  206. agt:SetMoveTarget(pathPos)
  207. else
  208. -- Keep the random point on the navigation mesh
  209. local targetPos = navMesh:FindNearestPoint(pathPos + Vector3(Random(-4.5, 4.5), 0, Random(-4.5, 4.5)), Vector3.ONE)
  210. agt:SetMoveTarget(targetPos)
  211. end
  212. end
  213. end
  214. end
  215. end
  216. end
  217. function GetIndexOf(tableTarget, objectTarget)
  218. for k,v in pairs(tableTarget) do
  219. if objectTarget == v then
  220. return k
  221. end
  222. end
  223. return -1
  224. end
  225. function AddOrRemoveObject()
  226. -- Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  227. local result, hitPos, hitDrawable = Raycast(250.0)
  228. if result then
  229. local hitNode = hitDrawable:GetNode()
  230. if hitNode.name == "Mushroom" then
  231. local idx = GetIndexOf(mushrooms, hitNode)
  232. if idx >= 0 then
  233. table.remove(mushrooms, idx)
  234. end
  235. hitNode:Remove()
  236. else
  237. local newNode = CreateMushroom(hitPos)
  238. local newObject = newNode:GetComponent("StaticModel")
  239. end
  240. end
  241. end
  242. function SpawnJack(pos)
  243. local jackNode = scene_:CreateChild("Jack")
  244. jackNode.position = pos
  245. local modelObject = jackNode:CreateComponent("AnimatedModel")
  246. modelObject.model = cache:GetResource("Model", "Models/Jack.mdl")
  247. modelObject.material = cache:GetResource("Material", "Materials/Jack.xml")
  248. modelObject.castShadows = true
  249. local agent = jackNode:CreateComponent("CrowdAgent")
  250. agent.height = 2.0
  251. agent.enabled = false
  252. table.insert(jackNodes, jackNode)
  253. end
  254. function CreateMushroom(pos)
  255. local mushroomNode = scene_:CreateChild("Mushroom")
  256. mushroomNode.position = pos
  257. mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
  258. mushroomNode:SetScale(2.0 + Random(0.5))
  259. local mushroomObject = mushroomNode:CreateComponent("StaticModel")
  260. mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
  261. mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
  262. mushroomObject.castShadows = true
  263. local obstacleObject = mushroomNode:CreateComponent("Obstacle")
  264. obstacleObject.radius = mushroomNode.scale.x
  265. table.insert(mushrooms, mushroomNode)
  266. return mushroomNode
  267. end
  268. function Raycast(maxDistance)
  269. local hitPos = nil
  270. local hitDrawable = nil
  271. local pos = ui.cursorPosition
  272. -- Check the cursor is visible and there is no UI element in front of the cursor
  273. if (not ui.cursor.visible) or (ui:GetElementAt(pos, true) ~= nil) then
  274. return false, nil, nil
  275. end
  276. local camera = cameraNode:GetComponent("Camera")
  277. local cameraRay = camera:GetScreenRay(pos.x / graphics.width, pos.y / graphics.height)
  278. -- Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  279. local octree = scene_:GetComponent("Octree")
  280. local result = octree:RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY)
  281. if result.drawable ~= nil then
  282. -- Calculate hit position in world space
  283. hitPos = cameraRay.origin + cameraRay.direction * result.distance
  284. hitDrawable = result.drawable
  285. return true, hitPos, hitDrawable
  286. end
  287. return false, nil, nil
  288. end
  289. function HandleUpdate(eventType, eventData)
  290. -- Take the frame time step, which is stored as a float
  291. local timeStep = eventData:GetFloat("TimeStep")
  292. -- Move the camera, scale movement with time step
  293. MoveCamera(timeStep)
  294. -- Make the CrowdAgents face the direction of their velocity
  295. local ct = table.maxn(jackNodes)
  296. if ct > 0 then
  297. for i = 1, ct do
  298. local agent = jackNodes[i]:GetComponent("CrowdAgent")
  299. jackNodes[i].worldDirection = agent:GetActualVelocity()
  300. end
  301. end
  302. end
  303. function HandlePostRenderUpdate(eventType, eventData)
  304. -- If draw debug mode is enabled, draw navigation mesh debug geometry
  305. if drawDebug then
  306. local navMesh = scene_:GetComponent("DynamicNavigationMesh")
  307. navMesh:DrawDebugGeometry(true)
  308. -- Visualize the start and end points and the last calculated path
  309. local size = table.maxn(jackNodes)
  310. if size > 0 then
  311. for i = 1, size do
  312. local agent = jackNodes[i]:GetComponent("CrowdAgent")
  313. agent:DrawDebugGeometry(true)
  314. end
  315. end
  316. size = table.maxn(mushrooms)
  317. if size > 0 then
  318. for i = 1, size do
  319. local obstacle = mushrooms[i]:GetComponent("Obstacle")
  320. obstacle:DrawDebugGeometry(true)
  321. end
  322. end
  323. end
  324. end
  325. function HandleCrowdAgentFailure(eventType, eventData)
  326. local node = eventData:GetPtr("Node", "Node")
  327. local agent = eventData:GetPtr("CrowdAgent", "CrowdAgent")
  328. local agentState = eventData:GetInt("CrowdAgentState")
  329. -- If the agent's state is invalid, likely from spawning on the side of a box, find a point in a larger area
  330. if agentState == CROWD_AGENT_INVALID then
  331. local navMesh = scene_:GetComponent("DynamicNavigationMesh")
  332. -- Get a point on the navmesh using more generous extents
  333. local newPos = navMesh:FindNearestPoint(node:GetWorldPosition(), Vector3(5, 5, 5))
  334. -- Set the new node position, CrowdAgent component will automatically reset the state of the agent
  335. node:SetWorldPosition(newPos)
  336. end
  337. end
  338. -- Create XML patch instructions for screen joystick layout specific to this sample app
  339. function GetScreenJoystickPatchString()
  340. return
  341. "<patch>" ..
  342. " <add sel=\"/element\">" ..
  343. " <element type=\"Button\">" ..
  344. " <attribute name=\"Name\" value=\"Button3\" />" ..
  345. " <attribute name=\"Position\" value=\"-120 -120\" />" ..
  346. " <attribute name=\"Size\" value=\"96 96\" />" ..
  347. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" ..
  348. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" ..
  349. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" ..
  350. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" ..
  351. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" ..
  352. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" ..
  353. " <element type=\"Text\">" ..
  354. " <attribute name=\"Name\" value=\"Label\" />" ..
  355. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" ..
  356. " <attribute name=\"Vert Alignment\" value=\"Center\" />" ..
  357. " <attribute name=\"Color\" value=\"0 0 0 1\" />" ..
  358. " <attribute name=\"Text\" value=\"Spawn Jack\" />" ..
  359. " </element>" ..
  360. " <element type=\"Text\">" ..
  361. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  362. " <attribute name=\"Text\" value=\"LSHIFT\" />" ..
  363. " </element>" ..
  364. " <element type=\"Text\">" ..
  365. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
  366. " <attribute name=\"Text\" value=\"LEFT\" />" ..
  367. " </element>" ..
  368. " </element>" ..
  369. " <element type=\"Button\">" ..
  370. " <attribute name=\"Name\" value=\"Button4\" />" ..
  371. " <attribute name=\"Position\" value=\"-120 -12\" />" ..
  372. " <attribute name=\"Size\" value=\"96 96\" />" ..
  373. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" ..
  374. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" ..
  375. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" ..
  376. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" ..
  377. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" ..
  378. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" ..
  379. " <element type=\"Text\">" ..
  380. " <attribute name=\"Name\" value=\"Label\" />" ..
  381. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" ..
  382. " <attribute name=\"Vert Alignment\" value=\"Center\" />" ..
  383. " <attribute name=\"Color\" value=\"0 0 0 1\" />" ..
  384. " <attribute name=\"Text\" value=\"Obstacles\" />" ..
  385. " </element>" ..
  386. " <element type=\"Text\">" ..
  387. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
  388. " <attribute name=\"Text\" value=\"MIDDLE\" />" ..
  389. " </element>" ..
  390. " </element>" ..
  391. " </add>" ..
  392. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
  393. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" ..
  394. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
  395. " <element type=\"Text\">" ..
  396. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
  397. " <attribute name=\"Text\" value=\"LEFT\" />" ..
  398. " </element>" ..
  399. " </add>" ..
  400. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  401. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
  402. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  403. " <element type=\"Text\">" ..
  404. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  405. " <attribute name=\"Text\" value=\"SPACE\" />" ..
  406. " </element>" ..
  407. " </add>" ..
  408. "</patch>"
  409. end