WalkingManager.java 16 KB

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