ZoneManager.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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.instancemanager;
  16. import gnu.trove.procedure.TObjectProcedure;
  17. import java.lang.reflect.Constructor;
  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. import org.w3c.dom.NamedNodeMap;
  27. import org.w3c.dom.Node;
  28. import com.l2jserver.Config;
  29. import com.l2jserver.gameserver.engines.DocumentParser;
  30. import com.l2jserver.gameserver.model.L2Object;
  31. import com.l2jserver.gameserver.model.L2World;
  32. import com.l2jserver.gameserver.model.L2WorldRegion;
  33. import com.l2jserver.gameserver.model.actor.L2Character;
  34. import com.l2jserver.gameserver.model.items.instance.L2ItemInstance;
  35. import com.l2jserver.gameserver.model.zone.L2ZoneRespawn;
  36. import com.l2jserver.gameserver.model.zone.L2ZoneType;
  37. import com.l2jserver.gameserver.model.zone.form.ZoneCuboid;
  38. import com.l2jserver.gameserver.model.zone.form.ZoneCylinder;
  39. import com.l2jserver.gameserver.model.zone.form.ZoneNPoly;
  40. import com.l2jserver.gameserver.model.zone.type.L2ArenaZone;
  41. import com.l2jserver.gameserver.model.zone.type.L2OlympiadStadiumZone;
  42. import com.l2jserver.gameserver.model.zone.type.L2RespawnZone;
  43. /**
  44. * This class manages the zones
  45. * @author durgus
  46. */
  47. public class ZoneManager extends DocumentParser
  48. {
  49. private static final Logger _log = Logger.getLogger(ZoneManager.class.getName());
  50. private final Map<Class<? extends L2ZoneType>, Map<Integer, ? extends L2ZoneType>> _classZones = new HashMap<>();
  51. private int _lastDynamicId = 300000;
  52. private List<L2ItemInstance> _debugItems;
  53. /**
  54. * @return
  55. */
  56. public static final ZoneManager getInstance()
  57. {
  58. return SingletonHolder._instance;
  59. }
  60. protected ZoneManager()
  61. {
  62. load();
  63. }
  64. public void reload()
  65. {
  66. // Get the world regions
  67. int count = 0;
  68. L2WorldRegion[][] worldRegions = L2World.getInstance().getAllWorldRegions();
  69. for (int x = 0; x < worldRegions.length; x++)
  70. {
  71. for (int y = 0; y < worldRegions[x].length; y++)
  72. {
  73. worldRegions[x][y].getZones().clear();
  74. count++;
  75. }
  76. }
  77. GrandBossManager.getInstance().getZones().clear();
  78. _log.info("Removed zones in " + count + " regions.");
  79. // Load the zones
  80. load();
  81. L2World.getInstance().forEachObject(new ForEachCharacterRevalidateZone());
  82. }
  83. protected final class ForEachCharacterRevalidateZone implements TObjectProcedure<L2Object>
  84. {
  85. @Override
  86. public final boolean execute(final L2Object o)
  87. {
  88. if (o instanceof L2Character)
  89. ((L2Character) o).revalidateZone(true);
  90. return true;
  91. }
  92. }
  93. @Override
  94. protected void parseDocument()
  95. {
  96. // Get the world regions
  97. L2WorldRegion[][] worldRegions = L2World.getInstance().getAllWorldRegions();
  98. NamedNodeMap attrs;
  99. Node attribute;
  100. String zoneName;
  101. int[][] coords;
  102. int zoneId, minZ, maxZ;
  103. String zoneType, zoneShape;
  104. List<int[]> rs = new ArrayList<>();
  105. for (Node n = getCurrentDocument().getFirstChild(); n != null; n = n.getNextSibling())
  106. {
  107. if ("list".equalsIgnoreCase(n.getNodeName()))
  108. {
  109. attrs = n.getAttributes();
  110. attribute = attrs.getNamedItem("enabled");
  111. if (attribute != null && !Boolean.parseBoolean(attribute.getNodeValue()))
  112. continue;
  113. for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
  114. {
  115. if ("zone".equalsIgnoreCase(d.getNodeName()))
  116. {
  117. attrs = d.getAttributes();
  118. attribute = attrs.getNamedItem("id");
  119. if (attribute != null)
  120. zoneId = Integer.parseInt(attribute.getNodeValue());
  121. else
  122. zoneId = _lastDynamicId++;
  123. attribute = attrs.getNamedItem("name");
  124. if (attribute != null)
  125. zoneName = attribute.getNodeValue();
  126. else
  127. zoneName = null;
  128. minZ = parseInt(attrs, "minZ");
  129. maxZ = parseInt(attrs, "maxZ");
  130. zoneType = attrs.getNamedItem("type").getNodeValue();
  131. zoneShape = attrs.getNamedItem("shape").getNodeValue();
  132. // Create the zone
  133. Class<?> newZone = null;
  134. Constructor<?> zoneConstructor = null;
  135. L2ZoneType temp = null;
  136. try
  137. {
  138. newZone = Class.forName("com.l2jserver.gameserver.model.zone.type.L2" + zoneType);
  139. zoneConstructor = newZone.getConstructor(int.class);
  140. temp = (L2ZoneType) zoneConstructor.newInstance(zoneId);
  141. }
  142. catch (Exception e)
  143. {
  144. _log.warning("ZoneData: No such zone type: " + zoneType + " in file: " + getCurrentFile().getName());
  145. continue;
  146. }
  147. // Get the zone shape from xml
  148. try
  149. {
  150. coords = null;
  151. int[] point;
  152. rs.clear();
  153. for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling())
  154. {
  155. if ("node".equalsIgnoreCase(cd.getNodeName()))
  156. {
  157. attrs = cd.getAttributes();
  158. point = new int[2];
  159. point[0] = parseInt(attrs, "X");
  160. point[1] = parseInt(attrs, "Y");
  161. rs.add(point);
  162. }
  163. }
  164. coords = rs.toArray(new int[rs.size()][2]);
  165. if (coords == null || coords.length == 0)
  166. {
  167. _log.warning("ZoneData: missing data for zone: " + zoneId + " XML file: " + getCurrentFile().getName());
  168. continue;
  169. }
  170. // Create this zone. Parsing for cuboids is a
  171. // bit different than for other polygons
  172. // cuboids need exactly 2 points to be defined.
  173. // Other polygons need at least 3 (one per
  174. // vertex)
  175. if (zoneShape.equalsIgnoreCase("Cuboid"))
  176. {
  177. if (coords.length == 2)
  178. temp.setZone(new ZoneCuboid(coords[0][0], coords[1][0], coords[0][1], coords[1][1], minZ, maxZ));
  179. else
  180. {
  181. _log.warning("ZoneData: Missing cuboid vertex in sql data for zone: " + zoneId + " in file: " + getCurrentFile().getName());
  182. continue;
  183. }
  184. }
  185. else if (zoneShape.equalsIgnoreCase("NPoly"))
  186. {
  187. // nPoly needs to have at least 3 vertices
  188. if (coords.length > 2)
  189. {
  190. final int[] aX = new int[coords.length];
  191. final int[] aY = new int[coords.length];
  192. for (int i = 0; i < coords.length; i++)
  193. {
  194. aX[i] = coords[i][0];
  195. aY[i] = coords[i][1];
  196. }
  197. temp.setZone(new ZoneNPoly(aX, aY, minZ, maxZ));
  198. }
  199. else
  200. {
  201. _log.warning("ZoneData: Bad data for zone: " + zoneId + " in file: " + getCurrentFile().getName());
  202. continue;
  203. }
  204. }
  205. else if (zoneShape.equalsIgnoreCase("Cylinder"))
  206. {
  207. // A Cylinder zone requires a center point
  208. // at x,y and a radius
  209. attrs = d.getAttributes();
  210. final int zoneRad = Integer.parseInt(attrs.getNamedItem("rad").getNodeValue());
  211. if (coords.length == 1 && zoneRad > 0)
  212. temp.setZone(new ZoneCylinder(coords[0][0], coords[0][1], minZ, maxZ, zoneRad));
  213. else
  214. {
  215. _log.warning("ZoneData: Bad data for zone: " + zoneId + " in file: " + getCurrentFile().getName());
  216. continue;
  217. }
  218. }
  219. }
  220. catch (Exception e)
  221. {
  222. _log.log(Level.WARNING, "ZoneData: Failed to load zone " + zoneId + " coordinates: " + e.getMessage(), e);
  223. }
  224. // Check for additional parameters
  225. for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling())
  226. {
  227. if ("stat".equalsIgnoreCase(cd.getNodeName()))
  228. {
  229. attrs = cd.getAttributes();
  230. String name = attrs.getNamedItem("name").getNodeValue();
  231. String val = attrs.getNamedItem("val").getNodeValue();
  232. temp.setParameter(name, val);
  233. }
  234. else if ("spawn".equalsIgnoreCase(cd.getNodeName()) && temp instanceof L2ZoneRespawn)
  235. {
  236. attrs = cd.getAttributes();
  237. int spawnX = Integer.parseInt(attrs.getNamedItem("X").getNodeValue());
  238. int spawnY = Integer.parseInt(attrs.getNamedItem("Y").getNodeValue());
  239. int spawnZ = Integer.parseInt(attrs.getNamedItem("Z").getNodeValue());
  240. Node val = attrs.getNamedItem("type");
  241. ((L2ZoneRespawn) temp).parseLoc(spawnX, spawnY, spawnZ, val == null ? null : val.getNodeValue());
  242. }
  243. else if ("race".equalsIgnoreCase(cd.getNodeName()) && temp instanceof L2RespawnZone)
  244. {
  245. attrs = cd.getAttributes();
  246. String race = attrs.getNamedItem("name").getNodeValue();
  247. String point = attrs.getNamedItem("point").getNodeValue();
  248. ((L2RespawnZone) temp).addRaceRespawnPoint(race, point);
  249. }
  250. }
  251. if (checkId(zoneId))
  252. _log.config("Caution: Zone (" + zoneId + ") from file: " + getCurrentFile().getName() + " overrides previos definition.");
  253. if (zoneName != null && !zoneName.isEmpty())
  254. temp.setName(zoneName);
  255. addZone(zoneId, temp);
  256. // Register the zone into any world region it
  257. // intersects with...
  258. // currently 11136 test for each zone :>
  259. int ax, ay, bx, by;
  260. for (int x = 0; x < worldRegions.length; x++)
  261. {
  262. for (int y = 0; y < worldRegions[x].length; y++)
  263. {
  264. ax = (x - L2World.OFFSET_X) << L2World.SHIFT_BY;
  265. bx = ((x + 1) - L2World.OFFSET_X) << L2World.SHIFT_BY;
  266. ay = (y - L2World.OFFSET_Y) << L2World.SHIFT_BY;
  267. by = ((y + 1) - L2World.OFFSET_Y) << L2World.SHIFT_BY;
  268. if (temp.getZone().intersectsRectangle(ax, bx, ay, by))
  269. {
  270. if (Config.DEBUG)
  271. {
  272. _log.info("Zone (" + zoneId + ") added to: " + x + " " + y);
  273. }
  274. worldRegions[x][y].addZone(temp);
  275. }
  276. }
  277. }
  278. }
  279. }
  280. }
  281. }
  282. }
  283. @Override
  284. public final void load()
  285. {
  286. _log.info("Loading zones...");
  287. _classZones.clear();
  288. long started = System.currentTimeMillis();
  289. parseDirectory("data/zones");
  290. started = System.currentTimeMillis() - started;
  291. _log.info("Done: loaded " + _classZones.size() + " zone classes and " + getSize() + " zones in " + (started / 1000) + " seconds.");
  292. }
  293. public int getSize()
  294. {
  295. int i = 0;
  296. for (Map<Integer, ? extends L2ZoneType> map : _classZones.values())
  297. {
  298. i += map.size();
  299. }
  300. return i;
  301. }
  302. public boolean checkId(int id)
  303. {
  304. for (Map<Integer, ? extends L2ZoneType> map : _classZones.values())
  305. {
  306. if (map.containsKey(id))
  307. return true;
  308. }
  309. return false;
  310. }
  311. /**
  312. * Add new zone
  313. * @param <T>
  314. * @param id
  315. * @param zone
  316. */
  317. @SuppressWarnings("unchecked")
  318. public <T extends L2ZoneType> void addZone(Integer id, T zone)
  319. {
  320. Map<Integer, T> map = (Map<Integer, T>) _classZones.get(zone.getClass());
  321. if (map == null)
  322. {
  323. map = new HashMap<>();
  324. map.put(id, zone);
  325. _classZones.put(zone.getClass(), map);
  326. }
  327. else
  328. map.put(id, zone);
  329. }
  330. /**
  331. * Returns all zones registered with the ZoneManager. To minimize iteration processing retrieve zones from L2WorldRegion for a specific location instead.
  332. * @return zones
  333. * @see #getAllZones(Class)
  334. */
  335. @Deprecated
  336. public Collection<L2ZoneType> getAllZones()
  337. {
  338. List<L2ZoneType> zones = new ArrayList<>();
  339. for (Map<Integer, ? extends L2ZoneType> map : _classZones.values())
  340. {
  341. zones.addAll(map.values());
  342. }
  343. return zones;
  344. }
  345. /**
  346. * Return all zones by class type
  347. * @param <T>
  348. * @param zoneType Zone class
  349. * @return Collection of zones
  350. */
  351. @SuppressWarnings("unchecked")
  352. public <T extends L2ZoneType> Collection<T> getAllZones(Class<T> zoneType)
  353. {
  354. return (Collection<T>) _classZones.get(zoneType).values();
  355. }
  356. /**
  357. * Get zone by ID
  358. * @param id
  359. * @return
  360. * @see #getZoneById(int, Class)
  361. */
  362. public L2ZoneType getZoneById(int id)
  363. {
  364. for (Map<Integer, ? extends L2ZoneType> map : _classZones.values())
  365. {
  366. if (map.containsKey(id))
  367. return map.get(id);
  368. }
  369. return null;
  370. }
  371. /**
  372. * Get zone by ID and zone class
  373. * @param <T>
  374. * @param id
  375. * @param zoneType
  376. * @return zone
  377. */
  378. @SuppressWarnings("unchecked")
  379. public <T extends L2ZoneType> T getZoneById(int id, Class<T> zoneType)
  380. {
  381. return (T) _classZones.get(zoneType).get(id);
  382. }
  383. /**
  384. * Returns all zones from where the object is located
  385. * @param object
  386. * @return zones
  387. */
  388. public List<L2ZoneType> getZones(L2Object object)
  389. {
  390. return getZones(object.getX(), object.getY(), object.getZ());
  391. }
  392. /**
  393. * @param <T>
  394. * @param object
  395. * @param type
  396. * @return zone from where the object is located by type
  397. */
  398. public <T extends L2ZoneType> T getZone(L2Object object, Class<T> type)
  399. {
  400. if (object == null)
  401. return null;
  402. return getZone(object.getX(), object.getY(), object.getZ(), type);
  403. }
  404. /**
  405. * Returns all zones from given coordinates (plane)
  406. * @param x
  407. * @param y
  408. * @return zones
  409. */
  410. public List<L2ZoneType> getZones(int x, int y)
  411. {
  412. L2WorldRegion region = L2World.getInstance().getRegion(x, y);
  413. List<L2ZoneType> temp = new ArrayList<>();
  414. for (L2ZoneType zone : region.getZones())
  415. {
  416. if (zone.isInsideZone(x, y))
  417. temp.add(zone);
  418. }
  419. return temp;
  420. }
  421. /**
  422. * Returns all zones from given coordinates
  423. * @param x
  424. * @param y
  425. * @param z
  426. * @return zones
  427. */
  428. public List<L2ZoneType> getZones(int x, int y, int z)
  429. {
  430. L2WorldRegion region = L2World.getInstance().getRegion(x, y);
  431. List<L2ZoneType> temp = new ArrayList<>();
  432. for (L2ZoneType zone : region.getZones())
  433. {
  434. if (zone.isInsideZone(x, y, z))
  435. temp.add(zone);
  436. }
  437. return temp;
  438. }
  439. /**
  440. * @param <T>
  441. * @param x
  442. * @param y
  443. * @param z
  444. * @param type
  445. * @return zone from given coordinates
  446. */
  447. @SuppressWarnings("unchecked")
  448. public <T extends L2ZoneType> T getZone(int x, int y, int z, Class<T> type)
  449. {
  450. L2WorldRegion region = L2World.getInstance().getRegion(x, y);
  451. for (L2ZoneType zone : region.getZones())
  452. {
  453. if (zone.isInsideZone(x, y, z) && type.isInstance(zone))
  454. return (T) zone;
  455. }
  456. return null;
  457. }
  458. public final L2ArenaZone getArena(L2Character character)
  459. {
  460. if (character == null)
  461. return null;
  462. for (L2ZoneType temp : ZoneManager.getInstance().getZones(character.getX(), character.getY(), character.getZ()))
  463. {
  464. if (temp instanceof L2ArenaZone && temp.isCharacterInZone(character))
  465. return ((L2ArenaZone) temp);
  466. }
  467. return null;
  468. }
  469. public final L2OlympiadStadiumZone getOlympiadStadium(L2Character character)
  470. {
  471. if (character == null)
  472. return null;
  473. for (L2ZoneType temp : ZoneManager.getInstance().getZones(character.getX(), character.getY(), character.getZ()))
  474. {
  475. if (temp instanceof L2OlympiadStadiumZone && temp.isCharacterInZone(character))
  476. return ((L2OlympiadStadiumZone) temp);
  477. }
  478. return null;
  479. }
  480. /**
  481. * For testing purposes only
  482. * @param <T>
  483. * @param obj
  484. * @param type
  485. * @return
  486. */
  487. @SuppressWarnings("unchecked")
  488. public <T extends L2ZoneType> T getClosestZone(L2Object obj, Class<T> type)
  489. {
  490. T zone = getZone(obj, type);
  491. if (zone == null)
  492. {
  493. double closestdis = Double.MAX_VALUE;
  494. for (T temp : (Collection<T>) _classZones.get(type).values())
  495. {
  496. double distance = temp.getDistanceToZone(obj);
  497. if (distance < closestdis)
  498. {
  499. closestdis = distance;
  500. zone = temp;
  501. }
  502. }
  503. }
  504. return zone;
  505. }
  506. /**
  507. * General storage for debug items used for visualizing zones.
  508. * @return list of items
  509. */
  510. public List<L2ItemInstance> getDebugItems()
  511. {
  512. if (_debugItems == null)
  513. _debugItems = new ArrayList<>();
  514. return _debugItems;
  515. }
  516. /**
  517. * Remove all debug items from l2world
  518. */
  519. public void clearDebugItems()
  520. {
  521. if (_debugItems != null)
  522. {
  523. Iterator<L2ItemInstance> it = _debugItems.iterator();
  524. while (it.hasNext())
  525. {
  526. L2ItemInstance item = it.next();
  527. if (item != null)
  528. item.decayMe();
  529. it.remove();
  530. }
  531. }
  532. }
  533. private static class SingletonHolder
  534. {
  535. protected static final ZoneManager _instance = new ZoneManager();
  536. }
  537. }