1 //
2 // Copyright (c) 2008-2017 the Urho3D project.
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21 //
22 
23 #include <Urho3D/Core/CoreEvents.h>
24 #include <Urho3D/Engine/Engine.h>
25 #include <Urho3D/Graphics/AnimatedModel.h>
26 #include <Urho3D/Graphics/AnimationController.h>
27 #include <Urho3D/Graphics/Camera.h>
28 #include <Urho3D/Graphics/DebugRenderer.h>
29 #include <Urho3D/Graphics/Graphics.h>
30 #include <Urho3D/Graphics/Light.h>
31 #include <Urho3D/Graphics/Material.h>
32 #include <Urho3D/Graphics/Octree.h>
33 #include <Urho3D/Graphics/Renderer.h>
34 #include <Urho3D/Graphics/Zone.h>
35 #include <Urho3D/Input/Input.h>
36 #include <Urho3D/Navigation/CrowdAgent.h>
37 #include <Urho3D/Navigation/DynamicNavigationMesh.h>
38 #include <Urho3D/Navigation/Navigable.h>
39 #include <Urho3D/Navigation/NavigationEvents.h>
40 #include <Urho3D/Navigation/Obstacle.h>
41 #include <Urho3D/Navigation/OffMeshConnection.h>
42 #include <Urho3D/Resource/ResourceCache.h>
43 #include <Urho3D/Scene/Scene.h>
44 #include <Urho3D/UI/Font.h>
45 #include <Urho3D/UI/Text.h>
46 #include <Urho3D/UI/UI.h>
47 
48 #include "CrowdNavigation.h"
49 
50 #include <Urho3D/DebugNew.h>
51 
52 static const String INSTRUCTION("instructionText");
53 
URHO3D_DEFINE_APPLICATION_MAIN(CrowdNavigation)54 URHO3D_DEFINE_APPLICATION_MAIN(CrowdNavigation)
55 
56 CrowdNavigation::CrowdNavigation(Context* context) :
57     Sample(context),
58     streamingDistance_(2),
59     drawDebug_(false)
60 {
61 }
62 
Start()63 void CrowdNavigation::Start()
64 {
65     // Execute base class startup
66     Sample::Start();
67 
68     // Create the scene content
69     CreateScene();
70 
71     // Create the UI content
72     CreateUI();
73 
74     // Setup the viewport for displaying the scene
75     SetupViewport();
76 
77     // Hook up to the frame update and render post-update events
78     SubscribeToEvents();
79 
80     // Set the mouse mode to use in the sample
81     Sample::InitMouseMode(MM_ABSOLUTE);
82 }
83 
CreateScene()84 void CrowdNavigation::CreateScene()
85 {
86     ResourceCache* cache = GetSubsystem<ResourceCache>();
87 
88     scene_ = new Scene(context_);
89 
90     // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
91     // Also create a DebugRenderer component so that we can draw debug geometry
92     scene_->CreateComponent<Octree>();
93     scene_->CreateComponent<DebugRenderer>();
94 
95     // Create scene node & StaticModel component for showing a static plane
96     Node* planeNode = scene_->CreateChild("Plane");
97     planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
98     StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
99     planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
100     planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
101 
102     // Create a Zone component for ambient lighting & fog control
103     Node* zoneNode = scene_->CreateChild("Zone");
104     Zone* zone = zoneNode->CreateComponent<Zone>();
105     zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
106     zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
107     zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
108     zone->SetFogStart(100.0f);
109     zone->SetFogEnd(300.0f);
110 
111     // Create a directional light to the world. Enable cascaded shadows on it
112     Node* lightNode = scene_->CreateChild("DirectionalLight");
113     lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
114     Light* light = lightNode->CreateComponent<Light>();
115     light->SetLightType(LIGHT_DIRECTIONAL);
116     light->SetCastShadows(true);
117     light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
118     // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
119     light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
120 
121     // Create randomly sized boxes. If boxes are big enough, make them occluders
122     Node* boxGroup = scene_->CreateChild("Boxes");
123     for (unsigned i = 0; i < 20; ++i)
124     {
125         Node* boxNode = boxGroup->CreateChild("Box");
126         float size = 1.0f + Random(10.0f);
127         boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
128         boxNode->SetScale(size);
129         StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
130         boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
131         boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
132         boxObject->SetCastShadows(true);
133         if (size >= 3.0f)
134             boxObject->SetOccluder(true);
135     }
136 
137     // Create a DynamicNavigationMesh component to the scene root
138     DynamicNavigationMesh* navMesh = scene_->CreateComponent<DynamicNavigationMesh>();
139     // Set small tiles to show navigation mesh streaming
140     navMesh->SetTileSize(32);
141     // Enable drawing debug geometry for obstacles and off-mesh connections
142     navMesh->SetDrawObstacles(true);
143     navMesh->SetDrawOffMeshConnections(true);
144     // Set the agent height large enough to exclude the layers under boxes
145     navMesh->SetAgentHeight(10.0f);
146     // Set nav mesh cell height to minimum (allows agents to be grounded)
147     navMesh->SetCellHeight(0.05f);
148     // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
149     // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
150     scene_->CreateComponent<Navigable>();
151     // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
152     // in the scene and still update the mesh correctly
153     navMesh->SetPadding(Vector3(0.0f, 10.0f, 0.0f));
154     // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
155     // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
156     // it will use renderable geometry instead
157     navMesh->Build();
158 
159     // Create an off-mesh connection to each box to make them climbable (tiny boxes are skipped). A connection is built from 2 nodes.
160     // Note that OffMeshConnections must be added before building the navMesh, but as we are adding Obstacles next, tiles will be automatically rebuilt.
161     // Creating connections post-build here allows us to use FindNearestPoint() to procedurally set accurate positions for the connection
162     CreateBoxOffMeshConnections(navMesh, boxGroup);
163 
164     // Create some mushrooms as obstacles. Note that obstacles are non-walkable areas
165     for (unsigned i = 0; i < 100; ++i)
166         CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
167 
168     // Create a CrowdManager component to the scene root
169     CrowdManager* crowdManager = scene_->CreateComponent<CrowdManager>();
170     CrowdObstacleAvoidanceParams params = crowdManager->GetObstacleAvoidanceParams(0);
171     // Set the params to "High (66)" setting
172     params.velBias = 0.5f;
173     params.adaptiveDivs = 7;
174     params.adaptiveRings = 3;
175     params.adaptiveDepth = 3;
176     crowdManager->SetObstacleAvoidanceParams(0, params);
177 
178     // Create some movable barrels. We create them as crowd agents, as for moving entities it is less expensive and more convenient than using obstacles
179     CreateMovingBarrels(navMesh);
180 
181     // Create Jack node as crowd agent
182     SpawnJack(Vector3(-5.0f, 0.0f, 20.0f), scene_->CreateChild("Jacks"));
183 
184     // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside the scene, because
185     // we want it to be unaffected by scene load / save
186     cameraNode_ = new Node(context_);
187     Camera* camera = cameraNode_->CreateComponent<Camera>();
188     camera->SetFarClip(300.0f);
189 
190     // Set an initial position for the camera scene node above the plane and looking down
191     cameraNode_->SetPosition(Vector3(0.0f, 50.0f, 0.0f));
192     pitch_ = 80.0f;
193     cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
194 }
195 
CreateUI()196 void CrowdNavigation::CreateUI()
197 {
198     ResourceCache* cache = GetSubsystem<ResourceCache>();
199     UI* ui = GetSubsystem<UI>();
200 
201     // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
202     // control the camera, and when visible, it will point the raycast target
203     XMLFile* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
204     SharedPtr<Cursor> cursor(new Cursor(context_));
205     cursor->SetStyleAuto(style);
206     ui->SetCursor(cursor);
207 
208     // Set starting position of the cursor at the rendering window center
209     Graphics* graphics = GetSubsystem<Graphics>();
210     cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
211 
212     // Construct new Text object, set string to display and font to use
213     Text* instructionText = ui->GetRoot()->CreateChild<Text>(INSTRUCTION);
214     instructionText->SetText(
215         "Use WASD keys to move, RMB to rotate view\n"
216         "LMB to set destination, SHIFT+LMB to spawn a Jack\n"
217         "MMB or O key to add obstacles or remove obstacles/agents\n"
218         "F5 to save scene, F7 to load\n"
219         "Tab to toggle navigation mesh streaming\n"
220         "Space to toggle debug geometry\n"
221         "F12 to toggle this instruction text"
222     );
223     instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
224     // The text has multiple rows. Center them in relation to each other
225     instructionText->SetTextAlignment(HA_CENTER);
226 
227     // Position the text relative to the screen center
228     instructionText->SetHorizontalAlignment(HA_CENTER);
229     instructionText->SetVerticalAlignment(VA_CENTER);
230     instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
231 }
232 
SetupViewport()233 void CrowdNavigation::SetupViewport()
234 {
235     Renderer* renderer = GetSubsystem<Renderer>();
236 
237     // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
238     SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
239     renderer->SetViewport(0, viewport);
240 }
241 
SubscribeToEvents()242 void CrowdNavigation::SubscribeToEvents()
243 {
244     // Subscribe HandleUpdate() function for processing update events
245     SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(CrowdNavigation, HandleUpdate));
246 
247     // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request debug geometry
248     SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(CrowdNavigation, HandlePostRenderUpdate));
249 
250     // Subscribe HandleCrowdAgentFailure() function for resolving invalidation issues with agents, during which we
251     // use a larger extents for finding a point on the navmesh to fix the agent's position
252     SubscribeToEvent(E_CROWD_AGENT_FAILURE, URHO3D_HANDLER(CrowdNavigation, HandleCrowdAgentFailure));
253 
254     // Subscribe HandleCrowdAgentReposition() function for controlling the animation
255     SubscribeToEvent(E_CROWD_AGENT_REPOSITION, URHO3D_HANDLER(CrowdNavigation, HandleCrowdAgentReposition));
256 
257     // Subscribe HandleCrowdAgentFormation() function for positioning agent into a formation
258     SubscribeToEvent(E_CROWD_AGENT_FORMATION, URHO3D_HANDLER(CrowdNavigation, HandleCrowdAgentFormation));
259 }
260 
SpawnJack(const Vector3 & pos,Node * jackGroup)261 void CrowdNavigation::SpawnJack(const Vector3& pos, Node* jackGroup)
262 {
263     ResourceCache* cache = GetSubsystem<ResourceCache>();
264     SharedPtr<Node> jackNode(jackGroup->CreateChild("Jack"));
265     jackNode->SetPosition(pos);
266     AnimatedModel* modelObject = jackNode->CreateComponent<AnimatedModel>();
267     modelObject->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
268     modelObject->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
269     modelObject->SetCastShadows(true);
270     jackNode->CreateComponent<AnimationController>();
271 
272     // Create a CrowdAgent component and set its height and realistic max speed/acceleration. Use default radius
273     CrowdAgent* agent = jackNode->CreateComponent<CrowdAgent>();
274     agent->SetHeight(2.0f);
275     agent->SetMaxSpeed(3.0f);
276     agent->SetMaxAccel(5.0f);
277 }
278 
CreateMushroom(const Vector3 & pos)279 void CrowdNavigation::CreateMushroom(const Vector3& pos)
280 {
281     ResourceCache* cache = GetSubsystem<ResourceCache>();
282 
283     Node* mushroomNode = scene_->CreateChild("Mushroom");
284     mushroomNode->SetPosition(pos);
285     mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
286     mushroomNode->SetScale(2.0f + Random(0.5f));
287     StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
288     mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
289     mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
290     mushroomObject->SetCastShadows(true);
291 
292     // Create the navigation Obstacle component and set its height & radius proportional to scale
293     Obstacle* obstacle = mushroomNode->CreateComponent<Obstacle>();
294     obstacle->SetRadius(mushroomNode->GetScale().x_);
295     obstacle->SetHeight(mushroomNode->GetScale().y_);
296 }
297 
CreateBoxOffMeshConnections(DynamicNavigationMesh * navMesh,Node * boxGroup)298 void CrowdNavigation::CreateBoxOffMeshConnections(DynamicNavigationMesh* navMesh, Node* boxGroup)
299 {
300     const Vector<SharedPtr<Node> >& boxes = boxGroup->GetChildren();
301     for (unsigned i=0; i < boxes.Size(); ++i)
302     {
303         Node* box = boxes[i];
304         Vector3 boxPos = box->GetPosition();
305         float boxHalfSize = box->GetScale().x_ / 2;
306 
307         // Create 2 empty nodes for the start & end points of the connection. Note that order matters only when using one-way/unidirectional connection.
308         Node* connectionStart = box->CreateChild("ConnectionStart");
309         connectionStart->SetWorldPosition(navMesh->FindNearestPoint(boxPos + Vector3(boxHalfSize, -boxHalfSize, 0))); // Base of box
310         Node* connectionEnd = connectionStart->CreateChild("ConnectionEnd");
311         connectionEnd->SetWorldPosition(navMesh->FindNearestPoint(boxPos + Vector3(boxHalfSize, boxHalfSize, 0))); // Top of box
312 
313         // Create the OffMeshConnection component to one node and link the other node
314         OffMeshConnection* connection = connectionStart->CreateComponent<OffMeshConnection>();
315         connection->SetEndPoint(connectionEnd);
316     }
317 }
318 
CreateMovingBarrels(DynamicNavigationMesh * navMesh)319 void CrowdNavigation::CreateMovingBarrels(DynamicNavigationMesh* navMesh)
320 {
321     ResourceCache* cache = GetSubsystem<ResourceCache>();
322     Node* barrel = scene_->CreateChild("Barrel");
323     StaticModel* model = barrel->CreateComponent<StaticModel>();
324     model->SetModel(cache->GetResource<Model>("Models/Cylinder.mdl"));
325     Material* material = cache->GetResource<Material>("Materials/StoneTiled.xml");
326     model->SetMaterial(material);
327     material->SetTexture(TU_DIFFUSE, cache->GetResource<Texture2D>("Textures/TerrainDetail2.dds"));
328     model->SetCastShadows(true);
329     for (unsigned i = 0;  i < 20; ++i)
330     {
331         Node* clone = barrel->Clone();
332         float size = 0.5f + Random(1.0f);
333         clone->SetScale(Vector3(size / 1.5f, size * 2.0f, size / 1.5f));
334         clone->SetPosition(navMesh->FindNearestPoint(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f)));
335         CrowdAgent* agent = clone->CreateComponent<CrowdAgent>();
336         agent->SetRadius(clone->GetScale().x_ * 0.5f);
337         agent->SetHeight(size);
338         agent->SetNavigationQuality(NAVIGATIONQUALITY_LOW);
339     }
340     barrel->Remove();
341 }
342 
SetPathPoint(bool spawning)343 void CrowdNavigation::SetPathPoint(bool spawning)
344 {
345     Vector3 hitPos;
346     Drawable* hitDrawable;
347 
348     if (Raycast(250.0f, hitPos, hitDrawable))
349     {
350         DynamicNavigationMesh* navMesh = scene_->GetComponent<DynamicNavigationMesh>();
351         Vector3 pathPos = navMesh->FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
352         Node* jackGroup = scene_->GetChild("Jacks");
353         if (spawning)
354             // Spawn a jack at the target position
355             SpawnJack(pathPos, jackGroup);
356         else
357             // Set crowd agents target position
358             scene_->GetComponent<CrowdManager>()->SetCrowdTarget(pathPos, jackGroup);
359     }
360 }
361 
AddOrRemoveObject()362 void CrowdNavigation::AddOrRemoveObject()
363 {
364     // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
365     Vector3 hitPos;
366     Drawable* hitDrawable;
367 
368     if (Raycast(250.0f, hitPos, hitDrawable))
369     {
370         Node* hitNode = hitDrawable->GetNode();
371 
372         // Note that navmesh rebuild happens when the Obstacle component is removed
373         if (hitNode->GetName() == "Mushroom")
374             hitNode->Remove();
375         else if (hitNode->GetName() == "Jack")
376             hitNode->Remove();
377         else
378             CreateMushroom(hitPos);
379     }
380 }
381 
Raycast(float maxDistance,Vector3 & hitPos,Drawable * & hitDrawable)382 bool CrowdNavigation::Raycast(float maxDistance, Vector3& hitPos, Drawable*& hitDrawable)
383 {
384     hitDrawable = 0;
385 
386     UI* ui = GetSubsystem<UI>();
387     IntVector2 pos = ui->GetCursorPosition();
388     // Check the cursor is visible and there is no UI element in front of the cursor
389     if (!ui->GetCursor()->IsVisible() || ui->GetElementAt(pos, true))
390         return false;
391 
392     Graphics* graphics = GetSubsystem<Graphics>();
393     Camera* camera = cameraNode_->GetComponent<Camera>();
394     Ray cameraRay = camera->GetScreenRay((float)pos.x_ / graphics->GetWidth(), (float)pos.y_ / graphics->GetHeight());
395     // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
396     PODVector<RayQueryResult> results;
397     RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
398     scene_->GetComponent<Octree>()->RaycastSingle(query);
399     if (results.Size())
400     {
401         RayQueryResult& result = results[0];
402         hitPos = result.position_;
403         hitDrawable = result.drawable_;
404         return true;
405     }
406 
407     return false;
408 }
409 
MoveCamera(float timeStep)410 void CrowdNavigation::MoveCamera(float timeStep)
411 {
412     // Right mouse button controls mouse cursor visibility: hide when pressed
413     UI* ui = GetSubsystem<UI>();
414     Input* input = GetSubsystem<Input>();
415     ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
416 
417     // Do not move if the UI has a focused element (the console)
418     if (ui->GetFocusElement())
419         return;
420 
421     // Movement speed as world units per second
422     const float MOVE_SPEED = 20.0f;
423     // Mouse sensitivity as degrees per pixel
424     const float MOUSE_SENSITIVITY = 0.1f;
425 
426     // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
427     // Only move the camera when the cursor is hidden
428     if (!ui->GetCursor()->IsVisible())
429     {
430         IntVector2 mouseMove = input->GetMouseMove();
431         yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
432         pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
433         pitch_ = Clamp(pitch_, -90.0f, 90.0f);
434 
435         // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
436         cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
437     }
438 
439     // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
440     if (input->GetKeyDown(KEY_W))
441         cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
442     if (input->GetKeyDown(KEY_S))
443         cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
444     if (input->GetKeyDown(KEY_A))
445         cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
446     if (input->GetKeyDown(KEY_D))
447         cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
448 
449     // Set destination or spawn a new jack with left mouse button
450     if (input->GetMouseButtonPress(MOUSEB_LEFT))
451         SetPathPoint(input->GetQualifierDown(QUAL_SHIFT));
452     // Add new obstacle or remove existing obstacle/agent with middle mouse button
453     else if (input->GetMouseButtonPress(MOUSEB_MIDDLE) || input->GetKeyPress(KEY_O))
454         AddOrRemoveObject();
455 
456     // Check for loading/saving the scene from/to the file Data/Scenes/CrowdNavigation.xml relative to the executable directory
457     if (input->GetKeyPress(KEY_F5))
458     {
459         File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CrowdNavigation.xml", FILE_WRITE);
460         scene_->SaveXML(saveFile);
461     }
462     else if (input->GetKeyPress(KEY_F7))
463     {
464         File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CrowdNavigation.xml", FILE_READ);
465         scene_->LoadXML(loadFile);
466     }
467 
468     // Toggle debug geometry with space
469     else if (input->GetKeyPress(KEY_SPACE))
470         drawDebug_ = !drawDebug_;
471 
472     // Toggle instruction text with F12
473     else if (input->GetKeyPress(KEY_F12))
474     {
475         UIElement* instruction = ui->GetRoot()->GetChild(INSTRUCTION);
476         instruction->SetVisible(!instruction->IsVisible());
477     }
478 }
479 
ToggleStreaming(bool enabled)480 void CrowdNavigation::ToggleStreaming(bool enabled)
481 {
482     DynamicNavigationMesh* navMesh = scene_->GetComponent<DynamicNavigationMesh>();
483     if (enabled)
484     {
485         int maxTiles = (2 * streamingDistance_ + 1) * (2 * streamingDistance_ + 1);
486         BoundingBox boundingBox = navMesh->GetBoundingBox();
487         SaveNavigationData();
488         navMesh->Allocate(boundingBox, maxTiles);
489     }
490     else
491         navMesh->Build();
492 }
493 
UpdateStreaming()494 void CrowdNavigation::UpdateStreaming()
495 {
496     // Center the navigation mesh at the crowd of jacks
497     Vector3 averageJackPosition;
498     if (Node* jackGroup = scene_->GetChild("Jacks"))
499     {
500         const unsigned numJacks = jackGroup->GetNumChildren();
501         for (unsigned i = 0; i < numJacks; ++i)
502             averageJackPosition += jackGroup->GetChild(i)->GetWorldPosition();
503         averageJackPosition /= (float)numJacks;
504     }
505 
506     // Compute currently loaded area
507     DynamicNavigationMesh* navMesh = scene_->GetComponent<DynamicNavigationMesh>();
508     const IntVector2 jackTile = navMesh->GetTileIndex(averageJackPosition);
509     const IntVector2 numTiles = navMesh->GetNumTiles();
510     const IntVector2 beginTile = VectorMax(IntVector2::ZERO, jackTile - IntVector2::ONE * streamingDistance_);
511     const IntVector2 endTile = VectorMin(jackTile + IntVector2::ONE * streamingDistance_, numTiles - IntVector2::ONE);
512 
513     // Remove tiles
514     for (HashSet<IntVector2>::Iterator i = addedTiles_.Begin(); i != addedTiles_.End();)
515     {
516         const IntVector2 tileIdx = *i;
517         if (beginTile.x_ <= tileIdx.x_ && tileIdx.x_ <= endTile.x_ && beginTile.y_ <= tileIdx.y_ && tileIdx.y_ <= endTile.y_)
518             ++i;
519         else
520         {
521             navMesh->RemoveTile(tileIdx);
522             i = addedTiles_.Erase(i);
523         }
524     }
525 
526     // Add tiles
527     for (int z = beginTile.y_; z <= endTile.y_; ++z)
528         for (int x = beginTile.x_; x <= endTile.x_; ++x)
529         {
530             const IntVector2 tileIdx(x, z);
531             if (!navMesh->HasTile(tileIdx) && tileData_.Contains(tileIdx))
532             {
533                 addedTiles_.Insert(tileIdx);
534                 navMesh->AddTile(tileData_[tileIdx]);
535             }
536         }
537 }
538 
SaveNavigationData()539 void CrowdNavigation::SaveNavigationData()
540 {
541     DynamicNavigationMesh* navMesh = scene_->GetComponent<DynamicNavigationMesh>();
542     tileData_.Clear();
543     addedTiles_.Clear();
544     const IntVector2 numTiles = navMesh->GetNumTiles();
545     for (int z = 0; z < numTiles.y_; ++z)
546         for (int x = 0; x <= numTiles.x_; ++x)
547         {
548             const IntVector2 tileIdx = IntVector2(x, z);
549             tileData_[tileIdx] = navMesh->GetTileData(tileIdx);
550         }
551 }
552 
HandleUpdate(StringHash eventType,VariantMap & eventData)553 void CrowdNavigation::HandleUpdate(StringHash eventType, VariantMap& eventData)
554 {
555     using namespace Update;
556 
557     // Take the frame time step, which is stored as a float
558     float timeStep = eventData[P_TIMESTEP].GetFloat();
559 
560     // Move the camera, scale movement with time step
561     MoveCamera(timeStep);
562 
563     // Update streaming
564     Input* input = GetSubsystem<Input>();
565     if (input->GetKeyPress(KEY_TAB))
566     {
567         useStreaming_ = !useStreaming_;
568         ToggleStreaming(useStreaming_);
569     }
570     if (useStreaming_)
571         UpdateStreaming();
572 
573 }
574 
HandlePostRenderUpdate(StringHash eventType,VariantMap & eventData)575 void CrowdNavigation::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
576 {
577     if (drawDebug_)
578     {
579         // Visualize navigation mesh, obstacles and off-mesh connections
580         scene_->GetComponent<DynamicNavigationMesh>()->DrawDebugGeometry(true);
581         // Visualize agents' path and position to reach
582         scene_->GetComponent<CrowdManager>()->DrawDebugGeometry(true);
583     }
584 }
585 
HandleCrowdAgentFailure(StringHash eventType,VariantMap & eventData)586 void CrowdNavigation::HandleCrowdAgentFailure(StringHash eventType, VariantMap& eventData)
587 {
588     using namespace CrowdAgentFailure;
589 
590     Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
591     CrowdAgentState agentState = (CrowdAgentState)eventData[P_CROWD_AGENT_STATE].GetInt();
592 
593     // If the agent's state is invalid, likely from spawning on the side of a box, find a point in a larger area
594     if (agentState == CA_STATE_INVALID)
595     {
596         // Get a point on the navmesh using more generous extents
597         Vector3 newPos = scene_->GetComponent<DynamicNavigationMesh>()->FindNearestPoint(node->GetPosition(), Vector3(5.0f, 5.0f, 5.0f));
598         // Set the new node position, CrowdAgent component will automatically reset the state of the agent
599         node->SetPosition(newPos);
600     }
601 }
602 
HandleCrowdAgentReposition(StringHash eventType,VariantMap & eventData)603 void CrowdNavigation::HandleCrowdAgentReposition(StringHash eventType, VariantMap& eventData)
604 {
605     static const char* WALKING_ANI = "Models/Jack_Walk.ani";
606 
607     using namespace CrowdAgentReposition;
608 
609     Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
610     CrowdAgent* agent = static_cast<CrowdAgent*>(eventData[P_CROWD_AGENT].GetPtr());
611     Vector3 velocity = eventData[P_VELOCITY].GetVector3();
612     float timeStep = eventData[P_TIMESTEP].GetFloat();
613 
614     // Only Jack agent has animation controller
615     AnimationController* animCtrl = node->GetComponent<AnimationController>();
616     if (animCtrl)
617     {
618         float speed = velocity.Length();
619         if (animCtrl->IsPlaying(WALKING_ANI))
620         {
621             float speedRatio = speed / agent->GetMaxSpeed();
622             // Face the direction of its velocity but moderate the turning speed based on the speed ratio and timeStep
623             node->SetRotation(node->GetRotation().Slerp(Quaternion(Vector3::FORWARD, velocity), 10.0f * timeStep * speedRatio));
624             // Throttle the animation speed based on agent speed ratio (ratio = 1 is full throttle)
625             animCtrl->SetSpeed(WALKING_ANI, speedRatio * 1.5f);
626         }
627         else
628             animCtrl->Play(WALKING_ANI, 0, true, 0.1f);
629 
630         // If speed is too low then stop the animation
631         if (speed < agent->GetRadius())
632             animCtrl->Stop(WALKING_ANI, 0.5f);
633     }
634 }
635 
HandleCrowdAgentFormation(StringHash eventType,VariantMap & eventData)636 void CrowdNavigation::HandleCrowdAgentFormation(StringHash eventType, VariantMap& eventData)
637 {
638     using namespace CrowdAgentFormation;
639 
640     unsigned index = eventData[P_INDEX].GetUInt();
641     unsigned size = eventData[P_SIZE].GetUInt();
642     Vector3 position = eventData[P_POSITION].GetVector3();
643 
644     // The first agent will always move to the exact position, all other agents will select a random point nearby
645     if (index)
646     {
647         CrowdManager* crowdManager = static_cast<CrowdManager*>(GetEventSender());
648         CrowdAgent* agent = static_cast<CrowdAgent*>(eventData[P_CROWD_AGENT].GetPtr());
649         eventData[P_POSITION] = crowdManager->GetRandomPointInCircle(position, agent->GetRadius(), agent->GetQueryFilterType());
650     }
651 }
652