CellPathFinding.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.gameserver.pathfinding.cellnodes;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. import java.util.ListIterator;
  19. import java.util.logging.Level;
  20. import java.util.logging.Logger;
  21. import javolution.util.FastList;
  22. import com.l2jserver.Config;
  23. import com.l2jserver.gameserver.GeoData;
  24. import com.l2jserver.gameserver.idfactory.IdFactory;
  25. import com.l2jserver.gameserver.model.L2ItemInstance;
  26. import com.l2jserver.gameserver.model.L2World;
  27. import com.l2jserver.gameserver.pathfinding.AbstractNode;
  28. import com.l2jserver.gameserver.pathfinding.AbstractNodeLoc;
  29. import com.l2jserver.gameserver.pathfinding.PathFinding;
  30. import com.l2jserver.util.StringUtil;
  31. /**
  32. *
  33. * @author Sami, DS
  34. * Credits to Diamond
  35. */
  36. public class CellPathFinding extends PathFinding
  37. {
  38. private static final Logger _log = Logger.getLogger(CellPathFinding.class.getName());
  39. private BufferInfo[] _allBuffers;
  40. private int _findSuccess = 0;
  41. private int _findFails = 0;
  42. private int _postFilterUses = 0;
  43. private int _postFilterPlayableUses = 0;
  44. private int _postFilterPasses = 0;
  45. private long _postFilterElapsed = 0;
  46. private FastList<L2ItemInstance> _debugItems = null;
  47. public static CellPathFinding getInstance()
  48. {
  49. return SingletonHolder._instance;
  50. }
  51. private CellPathFinding()
  52. {
  53. try
  54. {
  55. String[] array = Config.PATHFIND_BUFFERS.split(";");
  56. _allBuffers = new BufferInfo[array.length];
  57. String buf;
  58. String[] args;
  59. for (int i = 0; i < array.length; i++)
  60. {
  61. buf = array[i];
  62. args = buf.split("x");
  63. if (args.length != 2)
  64. throw new Exception("Invalid buffer definition: " + buf);
  65. _allBuffers[i] = new BufferInfo(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
  66. }
  67. }
  68. catch (Exception e)
  69. {
  70. _log.log(Level.WARNING, "CellPathFinding: Problem during buffer init: " + e.getMessage(), e);
  71. throw new Error("CellPathFinding: load aborted");
  72. }
  73. }
  74. /**
  75. * @see com.l2jserver.gameserver.pathfinding.PathFinding#PathNodesExist(short)
  76. */
  77. @Override
  78. public boolean pathNodesExist(short regionoffset)
  79. {
  80. return false;
  81. }
  82. /**
  83. * @see com.l2jserver.gameserver.pathfinding.PathFinding#FindPath(int, int, short, int, int, short)
  84. */
  85. @Override
  86. public List<AbstractNodeLoc> findPath(int x, int y, int z, int tx, int ty, int tz, int instanceId, boolean playable)
  87. {
  88. int gx = (x - L2World.MAP_MIN_X) >> 4;
  89. int gy = (y - L2World.MAP_MIN_Y) >> 4;
  90. if (!GeoData.getInstance().hasGeo(x, y))
  91. return null;
  92. short gz = GeoData.getInstance().getHeight(x, y, z);
  93. int gtx = (tx - L2World.MAP_MIN_X) >> 4;
  94. int gty = (ty - L2World.MAP_MIN_Y) >> 4;
  95. if (!GeoData.getInstance().hasGeo(tx, ty))
  96. return null;
  97. short gtz = GeoData.getInstance().getHeight(tx, ty, tz);
  98. CellNodeBuffer buffer = alloc(64 + 2*Math.max(Math.abs(gx - gtx), Math.abs(gy - gty)), playable);
  99. if (buffer == null)
  100. return null;
  101. boolean debug = playable && Config.DEBUG_PATH;
  102. if (debug)
  103. {
  104. if (_debugItems == null)
  105. _debugItems = new FastList<L2ItemInstance>();
  106. else
  107. {
  108. for (L2ItemInstance item : _debugItems)
  109. {
  110. if (item == null)
  111. continue;
  112. item.decayMe();
  113. }
  114. _debugItems.clear();
  115. }
  116. }
  117. FastList<AbstractNodeLoc> path = null;
  118. try
  119. {
  120. CellNode result = buffer.findPath(gx, gy, gz, gtx, gty, gtz);
  121. if (debug)
  122. {
  123. for (CellNode n : buffer.debugPath())
  124. {
  125. if (n.getCost() < 0) // calculated path
  126. dropDebugItem(1831, (int)(-n.getCost() * 10), n.getLoc());
  127. else // known nodes
  128. dropDebugItem(57, (int)(n.getCost() * 10), n.getLoc());
  129. }
  130. }
  131. if (result == null)
  132. {
  133. _findFails++;
  134. return null;
  135. }
  136. path = constructPath(result);
  137. }
  138. catch (Exception e)
  139. {
  140. e.printStackTrace();
  141. return null;
  142. }
  143. finally
  144. {
  145. buffer.free();
  146. }
  147. if (path.size() < 3 || Config.MAX_POSTFILTER_PASSES <= 0)
  148. {
  149. _findSuccess++;
  150. return path;
  151. }
  152. long timeStamp = System.currentTimeMillis();
  153. _postFilterUses++;
  154. if (playable)
  155. _postFilterPlayableUses++;
  156. int currentX, currentY, currentZ;
  157. ListIterator<AbstractNodeLoc> middlePoint, endPoint;
  158. AbstractNodeLoc locMiddle, locEnd;
  159. boolean remove;
  160. int pass = 0;
  161. do
  162. {
  163. pass++;
  164. _postFilterPasses++;
  165. remove = false;
  166. middlePoint = path.listIterator();
  167. endPoint = path.listIterator(1);
  168. locEnd = null;
  169. currentX = x;
  170. currentY = y;
  171. currentZ = z;
  172. while (endPoint.hasNext())
  173. {
  174. locEnd = endPoint.next();
  175. locMiddle = middlePoint.next();
  176. if (GeoData.getInstance().canMoveFromToTarget(currentX, currentY, currentZ, locEnd.getX(), locEnd.getY(), locEnd.getZ(), instanceId))
  177. {
  178. middlePoint.remove();
  179. remove = true;
  180. if (debug)
  181. dropDebugItem(735,1,locMiddle);
  182. }
  183. else
  184. {
  185. currentX = locMiddle.getX();
  186. currentY = locMiddle.getY();
  187. currentZ = locMiddle.getZ();
  188. }
  189. }
  190. }
  191. // only one postfilter pass for AI
  192. while (playable && remove && path.size() > 2 && pass < Config.MAX_POSTFILTER_PASSES);
  193. if (debug)
  194. {
  195. middlePoint = path.listIterator();
  196. while (middlePoint.hasNext())
  197. {
  198. locMiddle = middlePoint.next();
  199. dropDebugItem(65, 1, locMiddle);
  200. }
  201. }
  202. _findSuccess++;
  203. _postFilterElapsed += System.currentTimeMillis() - timeStamp;
  204. return path;
  205. }
  206. private FastList<AbstractNodeLoc> constructPath(AbstractNode node)
  207. {
  208. FastList<AbstractNodeLoc> path = new FastList<AbstractNodeLoc>();
  209. int previousDirectionX = Integer.MIN_VALUE;
  210. int previousDirectionY = Integer.MIN_VALUE;
  211. int directionX, directionY;
  212. while (node.getParent() != null)
  213. {
  214. if (!Config.ADVANCED_DIAGONAL_STRATEGY && node.getParent().getParent() != null)
  215. {
  216. int tmpX = node.getLoc().getNodeX() - node.getParent().getParent().getLoc().getNodeX();
  217. int tmpY = node.getLoc().getNodeY() - node.getParent().getParent().getLoc().getNodeY();
  218. if (Math.abs(tmpX) == Math.abs(tmpY))
  219. {
  220. directionX = tmpX;
  221. directionY = tmpY;
  222. }
  223. else
  224. {
  225. directionX = node.getLoc().getNodeX() - node.getParent().getLoc().getNodeX();
  226. directionY = node.getLoc().getNodeY() - node.getParent().getLoc().getNodeY();
  227. }
  228. }
  229. else
  230. {
  231. directionX = node.getLoc().getNodeX() - node.getParent().getLoc().getNodeX();
  232. directionY = node.getLoc().getNodeY() - node.getParent().getLoc().getNodeY();
  233. }
  234. // only add a new route point if moving direction changes
  235. if (directionX != previousDirectionX || directionY != previousDirectionY)
  236. {
  237. previousDirectionX = directionX;
  238. previousDirectionY = directionY;
  239. path.addFirst(node.getLoc());
  240. node.setLoc(null);
  241. }
  242. node = node.getParent();
  243. }
  244. return path;
  245. }
  246. private final CellNodeBuffer alloc(int size, boolean playable)
  247. {
  248. CellNodeBuffer current = null;
  249. for (BufferInfo i : _allBuffers)
  250. {
  251. if (i.mapSize >= size)
  252. {
  253. for (CellNodeBuffer buf : i.bufs)
  254. {
  255. if (buf.lock())
  256. {
  257. i.uses++;
  258. if (playable)
  259. i.playableUses++;
  260. i.elapsed += buf.getElapsedTime();
  261. current = buf;
  262. break;
  263. }
  264. }
  265. if (current != null)
  266. break;
  267. // not found, allocate temporary buffer
  268. current = new CellNodeBuffer(i.mapSize);
  269. current.lock();
  270. if (i.bufs.size() < i.count)
  271. {
  272. i.bufs.add(current);
  273. i.uses++;
  274. if (playable)
  275. i.playableUses++;
  276. break;
  277. }
  278. else
  279. {
  280. i.overflows++;
  281. if (playable)
  282. i.playableOverflows++;
  283. //System.err.println("Overflow, size requested: " + size + " playable:"+playable);
  284. }
  285. }
  286. }
  287. return current;
  288. }
  289. private final void dropDebugItem(int itemId, int num, AbstractNodeLoc loc)
  290. {
  291. final L2ItemInstance item = new L2ItemInstance(IdFactory.getInstance().getNextId(), itemId);
  292. item.setCount(num);
  293. item.spawnMe(loc.getX(), loc.getY(), loc.getZ());
  294. _debugItems.add(item);
  295. }
  296. private static final class BufferInfo
  297. {
  298. final int mapSize;
  299. final int count;
  300. ArrayList<CellNodeBuffer> bufs;
  301. int uses = 0;
  302. int playableUses = 0;
  303. int overflows = 0;
  304. int playableOverflows = 0;
  305. long elapsed = 0;
  306. public BufferInfo(int size, int cnt)
  307. {
  308. mapSize = size;
  309. count = cnt;
  310. bufs = new ArrayList<CellNodeBuffer>(count);
  311. }
  312. @Override
  313. public String toString()
  314. {
  315. final StringBuilder stat = new StringBuilder(100);
  316. StringUtil.append(stat,
  317. String.valueOf(mapSize), "x", String.valueOf(mapSize),
  318. " num:", String.valueOf(bufs.size()), "/" ,String.valueOf(count),
  319. " uses:", String.valueOf(uses), "/", String.valueOf(playableUses));
  320. if (uses > 0)
  321. StringUtil.append(stat, " total/avg(ms):",
  322. String.valueOf(elapsed), "/", String.format("%1.2f", (double)elapsed/uses));
  323. StringUtil.append(stat, " ovf:", String.valueOf(overflows), "/",
  324. String.valueOf(playableOverflows));
  325. return stat.toString();
  326. }
  327. }
  328. @Override
  329. public String[] getStat()
  330. {
  331. final String[] result = new String[_allBuffers.length + 1];
  332. for (int i = 0; i < _allBuffers.length; i++)
  333. result[i] = _allBuffers[i].toString();
  334. final StringBuilder stat = new StringBuilder(100);
  335. StringUtil.append(stat,
  336. "LOS postfilter uses:", String.valueOf(_postFilterUses),
  337. "/", String.valueOf(_postFilterPlayableUses));
  338. if (_postFilterUses > 0)
  339. StringUtil.append(stat, " total/avg(ms):",
  340. String.valueOf(_postFilterElapsed), "/",
  341. String.format("%1.2f", (double)_postFilterElapsed/_postFilterUses),
  342. " passes total/avg:", String.valueOf(_postFilterPasses), "/",
  343. String.format("%1.1f", (double)_postFilterPasses/_postFilterUses),"\r\n");
  344. StringUtil.append(stat, "Pathfind success/fail:", String.valueOf(_findSuccess),
  345. "/", String.valueOf(_findFails));
  346. result[result.length - 1] = stat.toString();
  347. return result;
  348. }
  349. @SuppressWarnings("synthetic-access")
  350. private static class SingletonHolder
  351. {
  352. protected static final CellPathFinding _instance = new CellPathFinding();
  353. }
  354. }