GeoPathFinding.java 14 KB

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