ZoneManager.java 19 KB

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