CellPathFinding.java 11 KB

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