WalkingManager.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /*
  2. * Copyright (C) 2004-2013 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.gameserver.instancemanager;
  20. import java.util.ArrayList;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.concurrent.ScheduledFuture;
  25. import org.w3c.dom.NamedNodeMap;
  26. import org.w3c.dom.Node;
  27. import com.l2jserver.gameserver.ThreadPoolManager;
  28. import com.l2jserver.gameserver.ai.CtrlIntention;
  29. import com.l2jserver.gameserver.engines.DocumentParser;
  30. import com.l2jserver.gameserver.model.L2CharPosition;
  31. import com.l2jserver.gameserver.model.L2NpcWalkerNode;
  32. import com.l2jserver.gameserver.model.L2WalkRoute;
  33. import com.l2jserver.gameserver.model.Location;
  34. import com.l2jserver.gameserver.model.actor.L2Npc;
  35. import com.l2jserver.gameserver.model.actor.instance.L2MonsterInstance;
  36. import com.l2jserver.gameserver.model.quest.Quest;
  37. import com.l2jserver.gameserver.network.NpcStringId;
  38. import com.l2jserver.util.Rnd;
  39. /**
  40. * This class manages walking monsters.
  41. * @author GKR
  42. */
  43. public class WalkingManager extends DocumentParser
  44. {
  45. // Repeat style:
  46. // 0 - go back
  47. // 1 - go to first point (circle style)
  48. // 2 - teleport to first point (conveyor style)
  49. // 3 - random walking between points.
  50. private static final byte REPEAT_GO_BACK = 0;
  51. private static final byte REPEAT_GO_FIRST = 1;
  52. private static final byte REPEAT_TELE_FIRST = 2;
  53. private static final byte REPEAT_RANDOM = 3;
  54. protected final Map<Integer, L2WalkRoute> _routes = new HashMap<>(); // all available routes
  55. private final Map<Integer, WalkInfo> _activeRoutes = new HashMap<>(); // each record represents NPC, moving by predefined route from _routes, and moving progress
  56. private final Map<Integer, NpcRoutesHolder> _routesToAttach = new HashMap<>(); // each record represents NPC and all available routes for it
  57. /**
  58. * Holds depending between NPC's spawn point and route
  59. */
  60. private class NpcRoutesHolder
  61. {
  62. private final Map<String, Integer> _correspondences;
  63. public NpcRoutesHolder()
  64. {
  65. _correspondences = new HashMap<>();
  66. }
  67. /**
  68. * Add correspondence between specific route and specific spawn point
  69. * @param routeId id of route
  70. * @param loc Location of spawn point
  71. */
  72. public void addRoute(int routeId, Location loc)
  73. {
  74. _correspondences.put(getUniqueKey(loc), routeId);
  75. }
  76. /**
  77. * @param npc
  78. * @return route id for given NPC.
  79. */
  80. public int getRouteId(L2Npc npc)
  81. {
  82. if (npc.getSpawn() != null)
  83. {
  84. String key = getUniqueKey(npc.getSpawn().getSpawnLocation());
  85. return _correspondences.containsKey(key) ? _correspondences.get(key) : -1;
  86. }
  87. return -1;
  88. }
  89. /**
  90. * @param loc
  91. * @return unique text string for given Location.
  92. */
  93. private String getUniqueKey(Location loc)
  94. {
  95. return (loc.getX() + "-" + loc.getY() + "-" + loc.getZ());
  96. }
  97. }
  98. /**
  99. * Holds info about current walk progress
  100. */
  101. private class WalkInfo
  102. {
  103. protected ScheduledFuture<?> _walkCheckTask;
  104. protected boolean _blocked = false;
  105. protected boolean _suspended = false;
  106. protected boolean _stoppedByAttack = false;
  107. protected int _currentNode = 0;
  108. protected boolean _forward = true; // Determines first --> last or first <-- last direction
  109. private final int _routeId;
  110. protected long _lastActionTime; // Debug field
  111. public WalkInfo(int routeId)
  112. {
  113. _routeId = routeId;
  114. }
  115. /**
  116. * @return id of route of this WalkInfo.
  117. */
  118. protected L2WalkRoute getRoute()
  119. {
  120. return _routes.get(_routeId);
  121. }
  122. /**
  123. * @return current node of this WalkInfo.
  124. */
  125. protected L2NpcWalkerNode getCurrentNode()
  126. {
  127. return getRoute().getNodeList().get(_currentNode);
  128. }
  129. /**
  130. * Calculate next node for this WalkInfo and send debug message from given npc
  131. * @param npc NPC to debug message to be sent from
  132. */
  133. protected void calculateNextNode(L2Npc npc)
  134. {
  135. // Check this first, within the bounds of random moving, we have no conception of "first" or "last" node
  136. if (getRoute().getRepeatType() == REPEAT_RANDOM)
  137. {
  138. int newNode = _currentNode;
  139. while (newNode == _currentNode)
  140. {
  141. newNode = Rnd.get(getRoute().getNodesCount());
  142. }
  143. _currentNode = newNode;
  144. npc.sendDebugMessage("Route id: " + getRoute().getId() + ", next random node is " + _currentNode);
  145. }
  146. else
  147. {
  148. if (_forward)
  149. {
  150. _currentNode++;
  151. }
  152. else
  153. {
  154. _currentNode--;
  155. }
  156. if (_currentNode == getRoute().getNodesCount()) // Last node arrived
  157. {
  158. npc.sendDebugMessage("Route id: " + getRoute().getId() + ", last node arrived");
  159. if (!getRoute().repeatWalk())
  160. {
  161. cancelMoving(npc);
  162. return;
  163. }
  164. switch (getRoute().getRepeatType())
  165. {
  166. case REPEAT_GO_BACK:
  167. _forward = false;
  168. _currentNode -= 2;
  169. break;
  170. case REPEAT_GO_FIRST:
  171. _currentNode = 0;
  172. break;
  173. case REPEAT_TELE_FIRST:
  174. npc.teleToLocation(npc.getSpawn().getLocx(), npc.getSpawn().getLocy(), npc.getSpawn().getLocz());
  175. _currentNode = 0;
  176. break;
  177. }
  178. }
  179. else if (_currentNode == -1) // First node arrived, when direction is first <-- last
  180. {
  181. _currentNode = 1;
  182. _forward = true;
  183. }
  184. }
  185. }
  186. }
  187. protected WalkingManager()
  188. {
  189. load();
  190. }
  191. @Override
  192. public final void load()
  193. {
  194. parseDatapackFile("data/Routes.xml");
  195. _log.info(getClass().getSimpleName() + ": Loaded " + _routes.size() + " walking routes.");
  196. }
  197. @Override
  198. protected void parseDocument()
  199. {
  200. Node n = getCurrentDocument().getFirstChild();
  201. for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
  202. {
  203. if (d.getNodeName().equals("route"))
  204. {
  205. final Integer routeId = parseInteger(d.getAttributes(), "id");
  206. boolean repeat = parseBoolean(d.getAttributes(), "repeat");
  207. String repeatStyle = d.getAttributes().getNamedItem("repeatStyle").getNodeValue();
  208. byte repeatType;
  209. if (repeatStyle.equalsIgnoreCase("back"))
  210. {
  211. repeatType = REPEAT_GO_BACK;
  212. }
  213. else if (repeatStyle.equalsIgnoreCase("cycle"))
  214. {
  215. repeatType = REPEAT_GO_FIRST;
  216. }
  217. else if (repeatStyle.equalsIgnoreCase("conveyor"))
  218. {
  219. repeatType = REPEAT_TELE_FIRST;
  220. }
  221. else if (repeatStyle.equalsIgnoreCase("random"))
  222. {
  223. repeatType = REPEAT_RANDOM;
  224. }
  225. else
  226. {
  227. repeatType = -1;
  228. }
  229. final List<L2NpcWalkerNode> list = new ArrayList<>();
  230. for (Node r = d.getFirstChild(); r != null; r = r.getNextSibling())
  231. {
  232. if (r.getNodeName().equals("point"))
  233. {
  234. NamedNodeMap attrs = r.getAttributes();
  235. int x = parseInt(attrs, "X");
  236. int y = parseInt(attrs, "Y");
  237. int z = parseInt(attrs, "Z");
  238. int delay = parseInt(attrs, "delay");
  239. String chatString = null;
  240. NpcStringId npcString = null;
  241. Node node = attrs.getNamedItem("string");
  242. if (node != null)
  243. {
  244. chatString = node.getNodeValue();
  245. }
  246. else
  247. {
  248. node = attrs.getNamedItem("npcString");
  249. if (node != null)
  250. {
  251. npcString = NpcStringId.getNpcStringId(node.getNodeValue());
  252. if (npcString == null)
  253. {
  254. _log.warning(getClass().getSimpleName() + ": Unknown npcstring '" + node.getNodeValue() + ".");
  255. continue;
  256. }
  257. }
  258. else
  259. {
  260. node = attrs.getNamedItem("npcStringId");
  261. if (node != null)
  262. {
  263. npcString = NpcStringId.getNpcStringId(Integer.parseInt(node.getNodeValue()));
  264. if (npcString == null)
  265. {
  266. _log.warning(getClass().getSimpleName() + ": Unknown npcstring '" + node.getNodeValue() + ".");
  267. continue;
  268. }
  269. }
  270. }
  271. }
  272. list.add(new L2NpcWalkerNode(0, npcString, chatString, x, y, z, delay, parseBoolean(attrs, "run")));
  273. }
  274. else if (r.getNodeName().equals("target"))
  275. {
  276. NamedNodeMap attrs = r.getAttributes();
  277. try
  278. {
  279. int npcId = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
  280. int x = 0, y = 0, z = 0;
  281. x = Integer.parseInt(attrs.getNamedItem("spawnX").getNodeValue());
  282. y = Integer.parseInt(attrs.getNamedItem("spawnY").getNodeValue());
  283. z = Integer.parseInt(attrs.getNamedItem("spawnZ").getNodeValue());
  284. NpcRoutesHolder holder = _routesToAttach.containsKey(npcId) ? _routesToAttach.get(npcId) : new NpcRoutesHolder();
  285. holder.addRoute(routeId, new Location(x, y, z));
  286. _routesToAttach.put(npcId, holder);
  287. }
  288. catch (Exception e)
  289. {
  290. _log.warning("Walking Manager: Error in target definition for route ID: " + routeId);
  291. }
  292. }
  293. }
  294. _routes.put(routeId, new L2WalkRoute(routeId, list, repeat, false, repeatType));
  295. }
  296. }
  297. }
  298. /**
  299. * @param npc NPC to check
  300. * @return {@code true} if given NPC, or its leader is controlled by Walking Manager and moves currently.
  301. */
  302. public boolean isOnWalk(L2Npc npc)
  303. {
  304. L2MonsterInstance monster = null;
  305. if (npc.isMonster())
  306. {
  307. if (((L2MonsterInstance) npc).getLeader() == null)
  308. {
  309. monster = (L2MonsterInstance) npc;
  310. }
  311. else
  312. {
  313. monster = ((L2MonsterInstance) npc).getLeader();
  314. }
  315. }
  316. if (((monster != null) && !isRegistered(monster)) || !isRegistered(npc))
  317. {
  318. return false;
  319. }
  320. WalkInfo walk = monster != null ? _activeRoutes.get(monster.getObjectId()) : _activeRoutes.get(npc.getObjectId());
  321. if (walk._stoppedByAttack || walk._suspended)
  322. {
  323. return false;
  324. }
  325. return true;
  326. }
  327. /**
  328. * @param npc NPC to check
  329. * @return {@code true} if given NPC controlled by Walking Manager.
  330. */
  331. public boolean isRegistered(L2Npc npc)
  332. {
  333. return _activeRoutes.containsKey(npc.getObjectId());
  334. }
  335. /**
  336. * Start to move given NPC by given route
  337. * @param npc NPC to move
  338. * @param routeId id of route to move by
  339. */
  340. public void startMoving(final L2Npc npc, final int routeId)
  341. {
  342. if (_routes.containsKey(routeId) && (npc != null) && !npc.isDead()) // check, if these route and NPC present
  343. {
  344. if (!_activeRoutes.containsKey(npc.getObjectId())) // new walk task
  345. {
  346. // only if not already moved / not engaged in battle... should not happens if called on spawn
  347. if ((npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_ACTIVE) || (npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_IDLE))
  348. {
  349. WalkInfo walk = new WalkInfo(routeId);
  350. if (npc.isDebug())
  351. {
  352. walk._lastActionTime = System.currentTimeMillis();
  353. }
  354. L2NpcWalkerNode node = walk.getCurrentNode();
  355. // adjust next waypoint, if NPC spawns at first waypoint
  356. if ((npc.getX() == node.getMoveX()) && (npc.getY() == node.getMoveY()))
  357. {
  358. walk.calculateNextNode(npc);
  359. node = walk.getCurrentNode();
  360. npc.sendDebugMessage("Route id " + routeId + ", spawn point is same with first waypoint, adjusted to next");
  361. }
  362. if (!npc.isInsideRadius(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 3000, true, false))
  363. {
  364. npc.sendDebugMessage("Route id " + routeId + ", NPC is too far from starting point, walking will no start");
  365. return;
  366. }
  367. npc.sendDebugMessage("Starting to move at route " + routeId);
  368. npc.setIsRunning(node.getRunning());
  369. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new L2CharPosition(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 0));
  370. walk._walkCheckTask = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(new Runnable()
  371. {
  372. @Override
  373. public void run()
  374. {
  375. startMoving(npc, routeId);
  376. }
  377. }, 60000, 60000); // start walk check task, for resuming walk after fight
  378. npc.getKnownList().startTrackingTask();
  379. _activeRoutes.put(npc.getObjectId(), walk); // register route
  380. }
  381. else
  382. {
  383. npc.sendDebugMessage("Trying to start move at route " + routeId + ", but cannot now, scheduled");
  384. ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  385. {
  386. @Override
  387. public void run()
  388. {
  389. startMoving(npc, routeId);
  390. }
  391. }, 60000);
  392. }
  393. }
  394. else
  395. // walk was stopped due to some reason (arrived to node, script action, fight or something else), resume it
  396. {
  397. if ((npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_ACTIVE) || (npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_IDLE))
  398. {
  399. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  400. // Prevent call simultaneously from scheduled task and onArrived() or temporarily stop walking for resuming in future
  401. if (walk._blocked || walk._suspended)
  402. {
  403. npc.sendDebugMessage("Trying continue to move at route " + routeId + ", but cannot now (operation is blocked)");
  404. return;
  405. }
  406. walk._blocked = true;
  407. L2NpcWalkerNode node = walk.getCurrentNode();
  408. npc.sendDebugMessage("Route id: " + routeId + ", continue to node " + walk._currentNode);
  409. npc.setIsRunning(node.getRunning());
  410. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new L2CharPosition(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 0));
  411. walk._blocked = false;
  412. walk._stoppedByAttack = false;
  413. }
  414. else
  415. {
  416. npc.sendDebugMessage("Trying continue to move at route " + routeId + ", but cannot now (wrong AI state)");
  417. }
  418. }
  419. }
  420. }
  421. /**
  422. * Cancel NPC moving permanently
  423. * @param npc NPC to cancel
  424. */
  425. public synchronized void cancelMoving(L2Npc npc)
  426. {
  427. if (_activeRoutes.containsKey(npc.getObjectId()))
  428. {
  429. final WalkInfo walk = _activeRoutes.remove(npc.getObjectId());
  430. walk._walkCheckTask.cancel(true);
  431. npc.getKnownList().stopTrackingTask();
  432. }
  433. }
  434. /**
  435. * Resumes previously stopped moving
  436. * @param npc NPC to resume
  437. */
  438. public void resumeMoving(final L2Npc npc)
  439. {
  440. if (!_activeRoutes.containsKey(npc.getObjectId()))
  441. {
  442. return;
  443. }
  444. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  445. walk._suspended = false;
  446. walk._stoppedByAttack = false;
  447. startMoving(npc, walk.getRoute().getId());
  448. }
  449. /**
  450. * Pause NPC moving until it will be resumed
  451. * @param npc NPC to pause moving
  452. * @param suspend {@code true} if moving was temporarily suspended for some reasons of AI-controlling script
  453. * @param stoppedByAttack {@code true} if moving was suspended because of NPC was attacked or desired to attack
  454. */
  455. public void stopMoving(L2Npc npc, boolean suspend, boolean stoppedByAttack)
  456. {
  457. L2MonsterInstance monster = null;
  458. if (npc.isMonster())
  459. {
  460. if (((L2MonsterInstance) npc).getLeader() == null)
  461. {
  462. monster = (L2MonsterInstance) npc;
  463. }
  464. else
  465. {
  466. monster = ((L2MonsterInstance) npc).getLeader();
  467. }
  468. }
  469. if (((monster != null) && !isRegistered(monster)) || !isRegistered(npc))
  470. {
  471. return;
  472. }
  473. WalkInfo walk = monster != null ? _activeRoutes.get(monster.getObjectId()) : _activeRoutes.get(npc.getObjectId());
  474. walk._suspended = suspend;
  475. walk._stoppedByAttack = stoppedByAttack;
  476. if (monster != null)
  477. {
  478. monster.stopMove(null);
  479. monster.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  480. }
  481. else
  482. {
  483. npc.stopMove(null);
  484. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  485. }
  486. }
  487. /**
  488. * Manage "node arriving"-related tasks: schedule move to next node; send ON_NODE_ARRIVED event to Quest script
  489. * @param npc NPC to manage
  490. */
  491. public void onArrived(final L2Npc npc)
  492. {
  493. if (_activeRoutes.containsKey(npc.getObjectId()))
  494. {
  495. // Notify quest
  496. if (npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_NODE_ARRIVED) != null)
  497. {
  498. for (Quest quest : npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_NODE_ARRIVED))
  499. {
  500. quest.notifyNodeArrived(npc);
  501. }
  502. }
  503. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  504. // Opposite should not happen... but happens sometime
  505. if ((walk._currentNode >= 0) && (walk._currentNode < walk.getRoute().getNodesCount()))
  506. {
  507. L2NpcWalkerNode node = walk.getRoute().getNodeList().get(walk._currentNode);
  508. if (npc.isInsideRadius(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 10, false, false))
  509. {
  510. npc.sendDebugMessage("Route id: " + walk.getRoute().getId() + ", arrived to node " + walk._currentNode);
  511. npc.sendDebugMessage("Done in " + ((System.currentTimeMillis() - walk._lastActionTime) / 1000) + " s.");
  512. walk.calculateNextNode(npc);
  513. int delay = walk.getCurrentNode().getDelay();
  514. walk._blocked = true; // prevents to be ran from walk check task, if there is delay in this node.
  515. if (npc.isDebug())
  516. {
  517. walk._lastActionTime = System.currentTimeMillis();
  518. }
  519. ThreadPoolManager.getInstance().scheduleGeneral(new ArrivedTask(npc, walk), 100 + (delay * 1000L));
  520. }
  521. }
  522. }
  523. }
  524. /**
  525. * Manage "on death"-related tasks: permanently cancel moving of died NPC
  526. * @param npc NPC to manage
  527. */
  528. public void onDeath(L2Npc npc)
  529. {
  530. cancelMoving(npc);
  531. }
  532. /**
  533. * Manage "on spawn"-related tasks: start NPC moving, if there is route attached to its spawn point
  534. * @param npc NPC to manage
  535. */
  536. public void onSpawn(L2Npc npc)
  537. {
  538. if (_routesToAttach.containsKey(npc.getNpcId()))
  539. {
  540. int routeId = _routesToAttach.get(npc.getNpcId()).getRouteId(npc);
  541. if (routeId > 0)
  542. {
  543. startMoving(npc, routeId);
  544. }
  545. }
  546. }
  547. private class ArrivedTask implements Runnable
  548. {
  549. WalkInfo _walk;
  550. L2Npc _npc;
  551. public ArrivedTask(L2Npc npc, WalkInfo walk)
  552. {
  553. _npc = npc;
  554. _walk = walk;
  555. }
  556. @Override
  557. public void run()
  558. {
  559. _walk._blocked = false;
  560. startMoving(_npc, _walk.getRoute().getId());
  561. }
  562. }
  563. public static final WalkingManager getInstance()
  564. {
  565. return SingletonHolder._instance;
  566. }
  567. private static class SingletonHolder
  568. {
  569. protected static final WalkingManager _instance = new WalkingManager();
  570. }
  571. }