GeoPathFinding.java 13 KB

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