GeoPathFinding.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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.geonodes;
  16. import java.io.BufferedReader;
  17. import java.io.File;
  18. import java.io.FileReader;
  19. import java.io.LineNumberReader;
  20. import java.io.RandomAccessFile;
  21. import java.nio.ByteBuffer;
  22. import java.nio.IntBuffer;
  23. import java.nio.MappedByteBuffer;
  24. import java.nio.channels.FileChannel;
  25. import java.util.LinkedList;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.StringTokenizer;
  29. import java.util.logging.Logger;
  30. import com.l2jserver.Config;
  31. import com.l2jserver.gameserver.GeoData;
  32. import com.l2jserver.gameserver.model.L2World;
  33. import com.l2jserver.gameserver.model.Location;
  34. import com.l2jserver.gameserver.pathfinding.AbstractNode;
  35. import com.l2jserver.gameserver.pathfinding.AbstractNodeLoc;
  36. import com.l2jserver.gameserver.pathfinding.PathFinding;
  37. import com.l2jserver.gameserver.pathfinding.utils.FastNodeList;
  38. import javolution.util.FastList;
  39. import javolution.util.FastMap;
  40. /**
  41. *
  42. * @author -Nemesiss-
  43. */
  44. public class GeoPathFinding extends PathFinding
  45. {
  46. private static Logger _log = Logger.getLogger(GeoPathFinding.class.getName());
  47. private static Map<Short, ByteBuffer> _pathNodes = new FastMap<Short, ByteBuffer>();
  48. private static Map<Short, IntBuffer> _pathNodesIndex = new FastMap<Short, IntBuffer>();
  49. public static GeoPathFinding getInstance()
  50. {
  51. return SingletonHolder._instance;
  52. }
  53. /**
  54. * @see com.l2jserver.gameserver.pathfinding.PathFinding#PathNodesExist(short)
  55. */
  56. @Override
  57. public boolean pathNodesExist(short regionoffset)
  58. {
  59. return _pathNodesIndex.containsKey(regionoffset);
  60. }
  61. /**
  62. * @see com.l2jserver.gameserver.pathfinding.PathFinding#FindPath(int, int, short, int, int, short)
  63. */
  64. @Override
  65. public List<AbstractNodeLoc> findPath(int x, int y, int z, int tx, int ty, int tz, int instanceId, boolean playable)
  66. {
  67. int gx = (x - L2World.MAP_MIN_X) >> 4;
  68. int gy = (y - L2World.MAP_MIN_Y) >> 4;
  69. short gz = (short) z;
  70. int gtx = (tx - L2World.MAP_MIN_X) >> 4;
  71. int gty = (ty - L2World.MAP_MIN_Y) >> 4;
  72. short gtz = (short) tz;
  73. GeoNode start = readNode(gx, gy, gz);
  74. GeoNode end = readNode(gtx, gty, gtz);
  75. if (start == null || end == null)
  76. return null;
  77. if (Math.abs(start.getLoc().getZ() - z) > 55)
  78. return null; // not correct layer
  79. if (Math.abs(end.getLoc().getZ() - tz) > 55)
  80. return null; // not correct layer
  81. if (start == end)
  82. return null;
  83. // TODO: Find closest path node we CAN access. Now only checks if we can not reach the closest
  84. Location temp = GeoData.getInstance().moveCheck(x, y, z, start.getLoc().getX(), start.getLoc().getY(), start.getLoc().getZ(), instanceId);
  85. if ((temp.getX() != start.getLoc().getX()) || (temp.getY() != start.getLoc().getY()))
  86. return null; // cannot reach closest...
  87. // TODO: Find closest path node around target, now only checks if final location can be reached
  88. temp = GeoData.getInstance().moveCheck(tx, ty, tz, end.getLoc().getX(), end.getLoc().getY(), end.getLoc().getZ(), instanceId);
  89. if ((temp.getX() != end.getLoc().getX()) || (temp.getY() != end.getLoc().getY()))
  90. return null; // cannot reach closest...
  91. //return searchAStar(start, end);
  92. return searchByClosest2(start, end);
  93. }
  94. public List<AbstractNodeLoc> searchByClosest2(GeoNode start, GeoNode end)
  95. {
  96. // Always continues checking from the closest to target non-blocked
  97. // node from to_visit list. There's extra length in path if needed
  98. // to go backwards/sideways but when moving generally forwards, this is extra fast
  99. // and accurate. And can reach insane distances (try it with 800 nodes..).
  100. // Minimum required node count would be around 300-400.
  101. // Generally returns a bit (only a bit) more intelligent looking routes than
  102. // the basic version. Not a true distance image (which would increase CPU
  103. // load) level of intelligence though.
  104. // List of Visited Nodes
  105. FastNodeList visited = new FastNodeList(550);
  106. // List of Nodes to Visit
  107. LinkedList<GeoNode> to_visit = new LinkedList<GeoNode>();
  108. to_visit.add(start);
  109. int targetX = end.getLoc().getNodeX();
  110. int targetY = end.getLoc().getNodeY();
  111. int dx, dy;
  112. boolean added;
  113. int i = 0;
  114. while (i < 550)
  115. {
  116. GeoNode node;
  117. try
  118. {
  119. node = to_visit.removeFirst();
  120. }
  121. catch (Exception e)
  122. {
  123. // No Path found
  124. return null;
  125. }
  126. if (node.equals(end)) //path found!
  127. return constructPath2(node);
  128. else
  129. {
  130. i++;
  131. visited.add(node);
  132. node.attachNeighbors();
  133. GeoNode[] neighbors = node.getNeighbors();
  134. if (neighbors == null)
  135. continue;
  136. for (GeoNode n : neighbors)
  137. {
  138. if (!visited.containsRev(n) && !to_visit.contains(n))
  139. {
  140. added = false;
  141. n.setParent(node);
  142. dx = targetX - n.getLoc().getNodeX();
  143. dy = targetY - n.getLoc().getNodeY();
  144. n.setCost(dx * dx + dy * dy);
  145. for (int index = 0; index < to_visit.size(); index++)
  146. {
  147. // supposed to find it quite early..
  148. if (to_visit.get(index).getCost() > n.getCost())
  149. {
  150. to_visit.add(index, n);
  151. added = true;
  152. break;
  153. }
  154. }
  155. if (!added)
  156. to_visit.addLast(n);
  157. }
  158. }
  159. }
  160. }
  161. //No Path found
  162. return null;
  163. }
  164. public List<AbstractNodeLoc> constructPath2(AbstractNode node)
  165. {
  166. LinkedList<AbstractNodeLoc> path = new LinkedList<AbstractNodeLoc>();
  167. int previousDirectionX = -1000;
  168. int previousDirectionY = -1000;
  169. int directionX;
  170. int directionY;
  171. while (node.getParent() != null)
  172. {
  173. // only add a new route point if moving direction changes
  174. directionX = node.getLoc().getNodeX() - node.getParent().getLoc().getNodeX();
  175. directionY = node.getLoc().getNodeY() - node.getParent().getLoc().getNodeY();
  176. if (directionX != previousDirectionX || directionY != previousDirectionY)
  177. {
  178. previousDirectionX = directionX;
  179. previousDirectionY = directionY;
  180. path.addFirst(node.getLoc());
  181. }
  182. node = node.getParent();
  183. }
  184. return path;
  185. }
  186. public GeoNode[] readNeighbors(GeoNode n, int idx)
  187. {
  188. int node_x = n.getLoc().getNodeX();
  189. int node_y = n.getLoc().getNodeY();
  190. //short node_z = n.getLoc().getZ();
  191. short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
  192. ByteBuffer pn = _pathNodes.get(regoffset);
  193. List<AbstractNode> Neighbors = new FastList<AbstractNode>(8);
  194. GeoNode newNode;
  195. short new_node_x, new_node_y;
  196. //Region for sure will change, we must read from correct file
  197. byte neighbor = pn.get(idx++); //N
  198. if (neighbor > 0)
  199. {
  200. neighbor--;
  201. new_node_x = (short) node_x;
  202. new_node_y = (short) (node_y - 1);
  203. newNode = readNode(new_node_x, new_node_y, neighbor);
  204. if (newNode != null)
  205. Neighbors.add(newNode);
  206. }
  207. neighbor = pn.get(idx++); //NE
  208. if (neighbor > 0)
  209. {
  210. neighbor--;
  211. new_node_x = (short) (node_x + 1);
  212. new_node_y = (short) (node_y - 1);
  213. newNode = readNode(new_node_x, new_node_y, neighbor);
  214. if (newNode != null)
  215. Neighbors.add(newNode);
  216. }
  217. neighbor = pn.get(idx++); //E
  218. if (neighbor > 0)
  219. {
  220. neighbor--;
  221. new_node_x = (short) (node_x + 1);
  222. new_node_y = (short) node_y;
  223. newNode = readNode(new_node_x, new_node_y, neighbor);
  224. if (newNode != null)
  225. Neighbors.add(newNode);
  226. }
  227. neighbor = pn.get(idx++); //SE
  228. if (neighbor > 0)
  229. {
  230. neighbor--;
  231. new_node_x = (short) (node_x + 1);
  232. new_node_y = (short) (node_y + 1);
  233. newNode = readNode(new_node_x, new_node_y, neighbor);
  234. if (newNode != null)
  235. Neighbors.add(newNode);
  236. }
  237. neighbor = pn.get(idx++); //S
  238. if (neighbor > 0)
  239. {
  240. neighbor--;
  241. new_node_x = (short) node_x;
  242. new_node_y = (short) (node_y + 1);
  243. newNode = readNode(new_node_x, new_node_y, neighbor);
  244. if (newNode != null)
  245. Neighbors.add(newNode);
  246. }
  247. neighbor = pn.get(idx++); //SW
  248. if (neighbor > 0)
  249. {
  250. neighbor--;
  251. new_node_x = (short) (node_x - 1);
  252. new_node_y = (short) (node_y + 1);
  253. newNode = readNode(new_node_x, new_node_y, neighbor);
  254. if (newNode != null)
  255. Neighbors.add(newNode);
  256. }
  257. neighbor = pn.get(idx++); //W
  258. if (neighbor > 0)
  259. {
  260. neighbor--;
  261. new_node_x = (short) (node_x - 1);
  262. new_node_y = (short) node_y;
  263. newNode = readNode(new_node_x, new_node_y, neighbor);
  264. if (newNode != null)
  265. Neighbors.add(newNode);
  266. }
  267. neighbor = pn.get(idx++); //NW
  268. if (neighbor > 0)
  269. {
  270. neighbor--;
  271. new_node_x = (short) (node_x - 1);
  272. new_node_y = (short) (node_y - 1);
  273. newNode = readNode(new_node_x, new_node_y, neighbor);
  274. if (newNode != null)
  275. Neighbors.add(newNode);
  276. }
  277. GeoNode[] result = new GeoNode[Neighbors.size()];
  278. return Neighbors.toArray(result);
  279. }
  280. //Private
  281. private GeoNode readNode(short node_x, short node_y, byte layer)
  282. {
  283. short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
  284. if (!this.pathNodesExist(regoffset))
  285. return null;
  286. short nbx = getNodeBlock(node_x);
  287. short nby = getNodeBlock(node_y);
  288. int idx = _pathNodesIndex.get(regoffset).get((nby << 8) + nbx);
  289. ByteBuffer pn = _pathNodes.get(regoffset);
  290. //reading
  291. byte nodes = pn.get(idx);
  292. idx += layer * 10 + 1;//byte + layer*10byte
  293. if (nodes < layer)
  294. {
  295. _log.warning("SmthWrong!");
  296. }
  297. short node_z = pn.getShort(idx);
  298. idx += 2;
  299. return new GeoNode(new GeoNodeLoc(node_x, node_y, node_z), idx);
  300. }
  301. private GeoNode readNode(int gx, int gy, short z)
  302. {
  303. short node_x = getNodePos(gx);
  304. short node_y = getNodePos(gy);
  305. short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
  306. if (!this.pathNodesExist(regoffset))
  307. return null;
  308. short nbx = getNodeBlock(node_x);
  309. short nby = getNodeBlock(node_y);
  310. int idx = _pathNodesIndex.get(regoffset).get((nby << 8) + nbx);
  311. ByteBuffer pn = _pathNodes.get(regoffset);
  312. //reading
  313. byte nodes = pn.get(idx++);
  314. int idx2 = 0; //create index to nearlest node by z
  315. short last_z = Short.MIN_VALUE;
  316. while (nodes > 0)
  317. {
  318. short node_z = pn.getShort(idx);
  319. if (Math.abs(last_z - z) > Math.abs(node_z - z))
  320. {
  321. last_z = node_z;
  322. idx2 = idx + 2;
  323. }
  324. idx += 10; //short + 8 byte
  325. nodes--;
  326. }
  327. return new GeoNode(new GeoNodeLoc(node_x, node_y, last_z), idx2);
  328. }
  329. private GeoPathFinding()
  330. {
  331. LineNumberReader lnr = null;
  332. try
  333. {
  334. _log.info("PathFinding Engine: - Loading Path Nodes...");
  335. File Data = new File("./data/pathnode/pn_index.txt");
  336. if (!Data.exists())
  337. return;
  338. lnr = new LineNumberReader(new BufferedReader(new FileReader(Data)));
  339. }
  340. catch (Exception e)
  341. {
  342. e.printStackTrace();
  343. throw new Error("Failed to Load pn_index File.");
  344. }
  345. String line;
  346. try
  347. {
  348. while ((line = lnr.readLine()) != null)
  349. {
  350. if (line.trim().length() == 0)
  351. continue;
  352. StringTokenizer st = new StringTokenizer(line, "_");
  353. byte rx = Byte.parseByte(st.nextToken());
  354. byte ry = Byte.parseByte(st.nextToken());
  355. LoadPathNodeFile(rx, ry);
  356. }
  357. }
  358. catch (Exception e)
  359. {
  360. e.printStackTrace();
  361. throw new Error("Failed to Read pn_index File.");
  362. }
  363. finally
  364. {
  365. try
  366. {
  367. lnr.close();
  368. }
  369. catch (Exception e)
  370. {
  371. }
  372. }
  373. }
  374. private void LoadPathNodeFile(byte rx, byte ry)
  375. {
  376. if (rx < Config.WORLD_X_MIN || rx > Config.WORLD_X_MAX || ry < Config.WORLD_Y_MIN || ry > Config.WORLD_Y_MAX)
  377. {
  378. _log.warning("Failed to Load PathNode File: invalid region " + rx +","+ ry + "\n");
  379. return;
  380. }
  381. String fname = "./data/pathnode/" + rx + "_" + ry + ".pn";
  382. short regionoffset = getRegionOffset(rx, ry);
  383. _log.info("PathFinding Engine: - Loading: " + fname + " -> region offset: " + regionoffset + "X: " + rx + " Y: " + ry);
  384. File Pn = new File(fname);
  385. int node = 0, size, index = 0;
  386. FileChannel roChannel = null;
  387. try
  388. {
  389. // Create a read-only memory-mapped file
  390. roChannel = new RandomAccessFile(Pn, "r").getChannel();
  391. size = (int) roChannel.size();
  392. MappedByteBuffer nodes;
  393. if (Config.FORCE_GEODATA) //Force O/S to Loads this buffer's content into physical memory.
  394. //it is not guarantee, because the underlying operating system may have paged out some of the buffer's data
  395. nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
  396. else
  397. nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
  398. // Indexing pathnode files, so we will know where each block starts
  399. IntBuffer indexs = IntBuffer.allocate(65536);
  400. while (node < 65536)
  401. {
  402. byte layer = nodes.get(index);
  403. indexs.put(node++, index);
  404. index += layer * 10 + 1;
  405. }
  406. _pathNodesIndex.put(regionoffset, indexs);
  407. _pathNodes.put(regionoffset, nodes);
  408. }
  409. catch (Exception e)
  410. {
  411. e.printStackTrace();
  412. _log.warning("Failed to Load PathNode File: " + fname + "\n");
  413. }
  414. finally
  415. {
  416. try
  417. {
  418. roChannel.close();
  419. }
  420. catch (Exception e)
  421. {
  422. }
  423. }
  424. }
  425. @SuppressWarnings("synthetic-access")
  426. private static class SingletonHolder
  427. {
  428. protected static final GeoPathFinding _instance = new GeoPathFinding();
  429. }
  430. }