WalkingManager.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 org.w3c.dom.NamedNodeMap;
  25. import org.w3c.dom.Node;
  26. import com.l2jserver.gameserver.ThreadPoolManager;
  27. import com.l2jserver.gameserver.ai.CtrlIntention;
  28. import com.l2jserver.gameserver.engines.DocumentParser;
  29. import com.l2jserver.gameserver.model.L2CharPosition;
  30. import com.l2jserver.gameserver.model.L2NpcWalkerNode;
  31. import com.l2jserver.gameserver.model.L2WalkRoute;
  32. import com.l2jserver.gameserver.model.Location;
  33. import com.l2jserver.gameserver.model.WalkInfo;
  34. import com.l2jserver.gameserver.model.actor.L2Npc;
  35. import com.l2jserver.gameserver.model.actor.instance.L2MonsterInstance;
  36. import com.l2jserver.gameserver.model.actor.tasks.npc.walker.ArrivedTask;
  37. import com.l2jserver.gameserver.model.holders.NpcRoutesHolder;
  38. import com.l2jserver.gameserver.model.quest.Quest;
  39. import com.l2jserver.gameserver.network.NpcStringId;
  40. import com.l2jserver.gameserver.network.clientpackets.Say2;
  41. import com.l2jserver.gameserver.network.serverpackets.NpcSay;
  42. import com.l2jserver.gameserver.util.Broadcast;
  43. /**
  44. * This class manages walking monsters.
  45. * @author GKR
  46. */
  47. public class WalkingManager extends DocumentParser
  48. {
  49. // Repeat style:
  50. // 0 - go back
  51. // 1 - go to first point (circle style)
  52. // 2 - teleport to first point (conveyor style)
  53. // 3 - random walking between points.
  54. public static final byte REPEAT_GO_BACK = 0;
  55. public static final byte REPEAT_GO_FIRST = 1;
  56. public static final byte REPEAT_TELE_FIRST = 2;
  57. public static final byte REPEAT_RANDOM = 3;
  58. private final Map<String, L2WalkRoute> _routes = new HashMap<>(); // all available routes
  59. private final Map<Integer, WalkInfo> _activeRoutes = new HashMap<>(); // each record represents NPC, moving by predefined route from _routes, and moving progress
  60. private final Map<Integer, NpcRoutesHolder> _routesToAttach = new HashMap<>(); // each record represents NPC and all available routes for it
  61. protected WalkingManager()
  62. {
  63. load();
  64. }
  65. @Override
  66. public final void load()
  67. {
  68. parseDatapackFile("data/Routes.xml");
  69. _log.info(getClass().getSimpleName() + ": Loaded " + _routes.size() + " walking routes.");
  70. }
  71. @Override
  72. protected void parseDocument()
  73. {
  74. Node n = getCurrentDocument().getFirstChild();
  75. for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
  76. {
  77. if (d.getNodeName().equals("route"))
  78. {
  79. final String routeName = parseString(d.getAttributes(), "name");
  80. boolean repeat = parseBoolean(d.getAttributes(), "repeat");
  81. String repeatStyle = d.getAttributes().getNamedItem("repeatStyle").getNodeValue();
  82. byte repeatType;
  83. if (repeatStyle.equalsIgnoreCase("back"))
  84. {
  85. repeatType = REPEAT_GO_BACK;
  86. }
  87. else if (repeatStyle.equalsIgnoreCase("cycle"))
  88. {
  89. repeatType = REPEAT_GO_FIRST;
  90. }
  91. else if (repeatStyle.equalsIgnoreCase("conveyor"))
  92. {
  93. repeatType = REPEAT_TELE_FIRST;
  94. }
  95. else if (repeatStyle.equalsIgnoreCase("random"))
  96. {
  97. repeatType = REPEAT_RANDOM;
  98. }
  99. else
  100. {
  101. repeatType = -1;
  102. }
  103. final List<L2NpcWalkerNode> list = new ArrayList<>();
  104. for (Node r = d.getFirstChild(); r != null; r = r.getNextSibling())
  105. {
  106. if (r.getNodeName().equals("point"))
  107. {
  108. NamedNodeMap attrs = r.getAttributes();
  109. int x = parseInt(attrs, "X");
  110. int y = parseInt(attrs, "Y");
  111. int z = parseInt(attrs, "Z");
  112. int delay = parseInt(attrs, "delay");
  113. String chatString = null;
  114. NpcStringId npcString = null;
  115. Node node = attrs.getNamedItem("string");
  116. if (node != null)
  117. {
  118. chatString = node.getNodeValue();
  119. }
  120. else
  121. {
  122. node = attrs.getNamedItem("npcString");
  123. if (node != null)
  124. {
  125. npcString = NpcStringId.getNpcStringId(node.getNodeValue());
  126. if (npcString == null)
  127. {
  128. _log.warning(getClass().getSimpleName() + ": Unknown npcstring '" + node.getNodeValue() + ".");
  129. continue;
  130. }
  131. }
  132. else
  133. {
  134. node = attrs.getNamedItem("npcStringId");
  135. if (node != null)
  136. {
  137. npcString = NpcStringId.getNpcStringId(Integer.parseInt(node.getNodeValue()));
  138. if (npcString == null)
  139. {
  140. _log.warning(getClass().getSimpleName() + ": Unknown npcstring '" + node.getNodeValue() + ".");
  141. continue;
  142. }
  143. }
  144. }
  145. }
  146. list.add(new L2NpcWalkerNode(0, npcString, chatString, x, y, z, delay, parseBoolean(attrs, "run")));
  147. }
  148. else if (r.getNodeName().equals("target"))
  149. {
  150. NamedNodeMap attrs = r.getAttributes();
  151. try
  152. {
  153. int npcId = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
  154. int x = 0, y = 0, z = 0;
  155. x = Integer.parseInt(attrs.getNamedItem("spawnX").getNodeValue());
  156. y = Integer.parseInt(attrs.getNamedItem("spawnY").getNodeValue());
  157. z = Integer.parseInt(attrs.getNamedItem("spawnZ").getNodeValue());
  158. NpcRoutesHolder holder = _routesToAttach.containsKey(npcId) ? _routesToAttach.get(npcId) : new NpcRoutesHolder();
  159. holder.addRoute(routeName, new Location(x, y, z));
  160. _routesToAttach.put(npcId, holder);
  161. }
  162. catch (Exception e)
  163. {
  164. _log.warning("Walking Manager: Error in target definition for route : " + routeName);
  165. }
  166. }
  167. }
  168. _routes.put(routeName, new L2WalkRoute(routeName, list, repeat, false, repeatType));
  169. }
  170. }
  171. }
  172. /**
  173. * @param npc NPC to check
  174. * @return {@code true} if given NPC, or its leader is controlled by Walking Manager and moves currently.
  175. */
  176. public boolean isOnWalk(L2Npc npc)
  177. {
  178. L2MonsterInstance monster = null;
  179. if (npc.isMonster())
  180. {
  181. if (((L2MonsterInstance) npc).getLeader() == null)
  182. {
  183. monster = (L2MonsterInstance) npc;
  184. }
  185. else
  186. {
  187. monster = ((L2MonsterInstance) npc).getLeader();
  188. }
  189. }
  190. if (((monster != null) && !isRegistered(monster)) || !isRegistered(npc))
  191. {
  192. return false;
  193. }
  194. WalkInfo walk = monster != null ? _activeRoutes.get(monster.getObjectId()) : _activeRoutes.get(npc.getObjectId());
  195. if (walk.isStoppedByAttack() || walk.isSuspended())
  196. {
  197. return false;
  198. }
  199. return true;
  200. }
  201. public L2WalkRoute getRoute(String route)
  202. {
  203. return _routes.get(route);
  204. }
  205. /**
  206. * @param npc NPC to check
  207. * @return {@code true} if given NPC controlled by Walking Manager.
  208. */
  209. public boolean isRegistered(L2Npc npc)
  210. {
  211. return _activeRoutes.containsKey(npc.getObjectId());
  212. }
  213. /**
  214. * @param npc
  215. * @return name of route
  216. */
  217. public String getRouteName(L2Npc npc)
  218. {
  219. return _activeRoutes.containsKey(npc.getObjectId()) ? _activeRoutes.get(npc.getObjectId()).getRoute().getName() : "";
  220. }
  221. /**
  222. * Start to move given NPC by given route
  223. * @param npc NPC to move
  224. * @param routeName name of route to move by
  225. */
  226. public void startMoving(final L2Npc npc, final String routeName)
  227. {
  228. if (_routes.containsKey(routeName) && (npc != null) && !npc.isDead()) // check, if these route and NPC present
  229. {
  230. if (!_activeRoutes.containsKey(npc.getObjectId())) // new walk task
  231. {
  232. // only if not already moved / not engaged in battle... should not happens if called on spawn
  233. if ((npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_ACTIVE) || (npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_IDLE))
  234. {
  235. WalkInfo walk = new WalkInfo(routeName);
  236. if (npc.isDebug())
  237. {
  238. walk.setLastAction(System.currentTimeMillis());
  239. }
  240. L2NpcWalkerNode node = walk.getCurrentNode();
  241. // adjust next waypoint, if NPC spawns at first waypoint
  242. if ((npc.getX() == node.getMoveX()) && (npc.getY() == node.getMoveY()))
  243. {
  244. walk.calculateNextNode(npc);
  245. node = walk.getCurrentNode();
  246. npc.sendDebugMessage("Route " + routeName + ", spawn point is same with first waypoint, adjusted to next");
  247. }
  248. if (!npc.isInsideRadius(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 3000, true, false))
  249. {
  250. npc.sendDebugMessage("Route " + routeName + ", NPC is too far from starting point, walking will no start");
  251. return;
  252. }
  253. npc.sendDebugMessage("Starting to move at route " + routeName);
  254. npc.setIsRunning(node.getRunning());
  255. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new L2CharPosition(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 0));
  256. walk.setWalkCheckTask(ThreadPoolManager.getInstance().scheduleAiAtFixedRate(new Runnable()
  257. {
  258. @Override
  259. public void run()
  260. {
  261. startMoving(npc, routeName);
  262. }
  263. }, 60000, 60000)); // start walk check task, for resuming walk after fight
  264. npc.getKnownList().startTrackingTask();
  265. _activeRoutes.put(npc.getObjectId(), walk); // register route
  266. }
  267. else
  268. {
  269. npc.sendDebugMessage("Trying to start move at route " + routeName + ", but cannot now, scheduled");
  270. ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  271. {
  272. @Override
  273. public void run()
  274. {
  275. startMoving(npc, routeName);
  276. }
  277. }, 60000);
  278. }
  279. }
  280. else
  281. // walk was stopped due to some reason (arrived to node, script action, fight or something else), resume it
  282. {
  283. if (_activeRoutes.containsKey(npc.getObjectId()) && ((npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_ACTIVE) || (npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_IDLE)))
  284. {
  285. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  286. if (walk == null)
  287. {
  288. return;
  289. }
  290. // Prevent call simultaneously from scheduled task and onArrived() or temporarily stop walking for resuming in future
  291. if (walk.isBlocked() || walk.isSuspended())
  292. {
  293. npc.sendDebugMessage("Trying continue to move at route " + routeName + ", but cannot now (operation is blocked)");
  294. return;
  295. }
  296. walk.setBlocked(true);
  297. L2NpcWalkerNode node = walk.getCurrentNode();
  298. npc.sendDebugMessage("Route id: " + routeName + ", continue to node " + walk.getCurrentNodeId());
  299. npc.setIsRunning(node.getRunning());
  300. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new L2CharPosition(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 0));
  301. walk.setBlocked(false);
  302. walk.setStoppedByAttack(false);
  303. }
  304. else
  305. {
  306. npc.sendDebugMessage("Trying continue to move at route " + routeName + ", but cannot now (wrong AI state)");
  307. }
  308. }
  309. }
  310. }
  311. /**
  312. * Cancel NPC moving permanently
  313. * @param npc NPC to cancel
  314. */
  315. public synchronized void cancelMoving(L2Npc npc)
  316. {
  317. if (_activeRoutes.containsKey(npc.getObjectId()))
  318. {
  319. final WalkInfo walk = _activeRoutes.remove(npc.getObjectId());
  320. walk.getWalkCheckTask().cancel(true);
  321. npc.getKnownList().stopTrackingTask();
  322. }
  323. }
  324. /**
  325. * Resumes previously stopped moving
  326. * @param npc NPC to resume
  327. */
  328. public void resumeMoving(final L2Npc npc)
  329. {
  330. if (!_activeRoutes.containsKey(npc.getObjectId()))
  331. {
  332. return;
  333. }
  334. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  335. walk.setSuspended(false);
  336. walk.setStoppedByAttack(false);
  337. startMoving(npc, walk.getRoute().getName());
  338. }
  339. /**
  340. * Pause NPC moving until it will be resumed
  341. * @param npc NPC to pause moving
  342. * @param suspend {@code true} if moving was temporarily suspended for some reasons of AI-controlling script
  343. * @param stoppedByAttack {@code true} if moving was suspended because of NPC was attacked or desired to attack
  344. */
  345. public void stopMoving(L2Npc npc, boolean suspend, boolean stoppedByAttack)
  346. {
  347. L2MonsterInstance monster = null;
  348. if (npc.isMonster())
  349. {
  350. if (((L2MonsterInstance) npc).getLeader() == null)
  351. {
  352. monster = (L2MonsterInstance) npc;
  353. }
  354. else
  355. {
  356. monster = ((L2MonsterInstance) npc).getLeader();
  357. }
  358. }
  359. if (((monster != null) && !isRegistered(monster)) || !isRegistered(npc))
  360. {
  361. return;
  362. }
  363. WalkInfo walk = monster != null ? _activeRoutes.get(monster.getObjectId()) : _activeRoutes.get(npc.getObjectId());
  364. walk.setSuspended(suspend);
  365. walk.setStoppedByAttack(stoppedByAttack);
  366. if (monster != null)
  367. {
  368. monster.stopMove(null);
  369. monster.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  370. }
  371. else
  372. {
  373. npc.stopMove(null);
  374. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  375. }
  376. }
  377. /**
  378. * Manage "node arriving"-related tasks: schedule move to next node; send ON_NODE_ARRIVED event to Quest script
  379. * @param npc NPC to manage
  380. */
  381. public void onArrived(final L2Npc npc)
  382. {
  383. if (_activeRoutes.containsKey(npc.getObjectId()))
  384. {
  385. // Notify quest
  386. if (npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_NODE_ARRIVED) != null)
  387. {
  388. for (Quest quest : npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_NODE_ARRIVED))
  389. {
  390. quest.notifyNodeArrived(npc);
  391. }
  392. }
  393. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  394. // Opposite should not happen... but happens sometime
  395. if ((walk.getCurrentNodeId() >= 0) && (walk.getCurrentNodeId() < walk.getRoute().getNodesCount()))
  396. {
  397. L2NpcWalkerNode node = walk.getRoute().getNodeList().get(walk.getCurrentNodeId());
  398. if (npc.isInsideRadius(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 10, false, false))
  399. {
  400. npc.sendDebugMessage("Route: " + walk.getRoute().getName() + ", arrived to node " + walk.getCurrentNodeId());
  401. npc.sendDebugMessage("Done in " + ((System.currentTimeMillis() - walk.getLastAction()) / 1000) + " s.");
  402. walk.calculateNextNode(npc);
  403. int delay = node.getDelay();
  404. walk.setBlocked(true); // prevents to be ran from walk check task, if there is delay in this node.
  405. if (node.getNpcString() != null)
  406. {
  407. Broadcast.toKnownPlayers(npc, new NpcSay(npc, Say2.NPC_ALL, node.getNpcString()));
  408. }
  409. else
  410. {
  411. final String text = node.getChatText();
  412. if ((text != null) && !text.isEmpty())
  413. {
  414. Broadcast.toKnownPlayers(npc, new NpcSay(npc, Say2.NPC_ALL, text));
  415. }
  416. }
  417. if (npc.isDebug())
  418. {
  419. walk.setLastAction(System.currentTimeMillis());
  420. }
  421. ThreadPoolManager.getInstance().scheduleGeneral(new ArrivedTask(npc, walk), 100 + (delay * 1000L));
  422. }
  423. }
  424. }
  425. }
  426. /**
  427. * Manage "on death"-related tasks: permanently cancel moving of died NPC
  428. * @param npc NPC to manage
  429. */
  430. public void onDeath(L2Npc npc)
  431. {
  432. cancelMoving(npc);
  433. }
  434. /**
  435. * Manage "on spawn"-related tasks: start NPC moving, if there is route attached to its spawn point
  436. * @param npc NPC to manage
  437. */
  438. public void onSpawn(L2Npc npc)
  439. {
  440. if (_routesToAttach.containsKey(npc.getNpcId()))
  441. {
  442. final String routeName = _routesToAttach.get(npc.getNpcId()).getRouteName(npc);
  443. if (!routeName.isEmpty())
  444. {
  445. startMoving(npc, routeName);
  446. }
  447. }
  448. }
  449. public static final WalkingManager getInstance()
  450. {
  451. return SingletonHolder._instance;
  452. }
  453. private static class SingletonHolder
  454. {
  455. protected static final WalkingManager _instance = new WalkingManager();
  456. }
  457. }