ZoneManager.java 20 KB

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