ZoneManager.java 19 KB

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