SpawnTable.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*
  2. * Copyright (C) 2004-2013 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.datatables;
  20. import java.sql.Connection;
  21. import java.sql.PreparedStatement;
  22. import java.sql.ResultSet;
  23. import java.sql.Statement;
  24. import java.util.Collections;
  25. import java.util.Map;
  26. import java.util.Set;
  27. import java.util.logging.Level;
  28. import java.util.logging.Logger;
  29. import javolution.util.FastMap;
  30. import javolution.util.FastSet;
  31. import com.l2jserver.Config;
  32. import com.l2jserver.L2DatabaseFactory;
  33. import com.l2jserver.gameserver.engines.DocumentParser;
  34. import com.l2jserver.gameserver.instancemanager.DayNightSpawnManager;
  35. import com.l2jserver.gameserver.instancemanager.ZoneManager;
  36. import com.l2jserver.gameserver.model.L2Spawn;
  37. import com.l2jserver.gameserver.model.StatsSet;
  38. import com.l2jserver.gameserver.model.actor.templates.L2NpcTemplate;
  39. import com.l2jserver.gameserver.model.interfaces.IL2Procedure;
  40. import org.w3c.dom.NamedNodeMap;
  41. import org.w3c.dom.Node;
  42. /**
  43. * Spawn data retriever.
  44. * @author Zoey76
  45. */
  46. public final class SpawnTable extends DocumentParser
  47. {
  48. private static final Logger _log = Logger.getLogger(SpawnTable.class.getName());
  49. // SQL
  50. private static final String SELECT_SPAWNS = "SELECT count, npc_templateid, locx, locy, locz, heading, respawn_delay, respawn_random, loc_id, periodOfDay FROM spawnlist";
  51. private static final String SELECT_CUSTOM_SPAWNS = "SELECT count, npc_templateid, locx, locy, locz, heading, respawn_delay, respawn_random, loc_id, periodOfDay FROM custom_spawnlist";
  52. private static final Map<Integer, Set<L2Spawn>> _spawnTable = new FastMap<Integer, Set<L2Spawn>>().shared();
  53. private int _xmlSpawnCount = 0;
  54. protected SpawnTable()
  55. {
  56. load();
  57. }
  58. /**
  59. * Wrapper to load all spawns.
  60. */
  61. @Override
  62. public void load()
  63. {
  64. if (!Config.ALT_DEV_NO_SPAWNS)
  65. {
  66. fillSpawnTable(false);
  67. final int spawnCount = _spawnTable.size();
  68. _log.info(getClass().getSimpleName() + ": Loaded " + spawnCount + " npc spawns.");
  69. if (Config.CUSTOM_SPAWNLIST_TABLE)
  70. {
  71. fillSpawnTable(true);
  72. _log.info(getClass().getSimpleName() + ": Loaded " + (_spawnTable.size() - spawnCount) + " custom npc spawns.");
  73. }
  74. // Load XML list
  75. parseDirectory("data/spawnlist");
  76. _log.info(getClass().getSimpleName() + ": Loaded " + _xmlSpawnCount + " npc spawns from XML.");
  77. }
  78. }
  79. private boolean checkTemplate(int npcId)
  80. {
  81. L2NpcTemplate npcTemplate = NpcTable.getInstance().getTemplate(npcId);
  82. if (npcTemplate == null)
  83. {
  84. _log.warning(getClass().getSimpleName() + ": Data missing in NPC table for ID: " + npcId + ".");
  85. return false;
  86. }
  87. if (npcTemplate.isType("L2SiegeGuard") || npcTemplate.isType("L2RaidBoss") || (!Config.ALLOW_CLASS_MASTERS && npcTemplate.isType("L2ClassMaster")))
  88. {
  89. // Don't spawn
  90. return false;
  91. }
  92. return true;
  93. }
  94. @Override
  95. protected void parseDocument()
  96. {
  97. NamedNodeMap attrs;
  98. for (Node list = getCurrentDocument().getFirstChild(); list != null; list = list.getNextSibling())
  99. {
  100. if (list.getNodeName().equalsIgnoreCase("list"))
  101. {
  102. for (Node param = list.getFirstChild(); param != null; param = param.getNextSibling())
  103. {
  104. attrs = param.getAttributes();
  105. if (param.getNodeName().equalsIgnoreCase("spawn"))
  106. {
  107. String territoryName = null;
  108. // Check, if spawn territory specified and exists
  109. if (attrs.getNamedItem("zone") != null && ZoneManager.getInstance().getSpawnTerritory(attrs.getNamedItem("zone").getNodeValue()) != null)
  110. {
  111. territoryName = parseString(attrs, "zone");
  112. }
  113. for (Node npctag = param.getFirstChild(); npctag != null; npctag = npctag.getNextSibling())
  114. {
  115. attrs = npctag.getAttributes();
  116. if (npctag.getNodeName().equalsIgnoreCase("npc"))
  117. {
  118. // mandatory
  119. final int templateId = parseInt(attrs, "id");
  120. // coordinates are optional, if territory is specified; mandatory otherwise
  121. int x = 0;
  122. int y = 0;
  123. int z = 0;
  124. try
  125. {
  126. x = parseInt(attrs, "x");
  127. y = parseInt(attrs, "y");
  128. z = parseInt(attrs, "z");
  129. }
  130. catch (NullPointerException npe)
  131. {
  132. // x, y, z can be unspecified, if this spawn is territory based, do nothing
  133. }
  134. if ((x == 0) && (y == 0) && (territoryName == null)) // Both coordinates and zone are unspecified
  135. {
  136. _log.warning("XML Spawnlist: Spawn could not be initialized, both coordinates and zone are unspecified for ID " + templateId);
  137. continue;
  138. }
  139. StatsSet spawnInfo = new StatsSet();
  140. spawnInfo.set("npcTemplateid", templateId);
  141. spawnInfo.set("x", x);
  142. spawnInfo.set("y", y);
  143. spawnInfo.set("z", z);
  144. spawnInfo.set("territoryName", territoryName);
  145. // trying to read optional parameters
  146. if (attrs.getNamedItem("heading") != null)
  147. {
  148. spawnInfo.set("heading", parseInt(attrs, "heading"));
  149. }
  150. if (attrs.getNamedItem("count") != null)
  151. {
  152. spawnInfo.set("count", parseInt(attrs, "count"));
  153. }
  154. if (attrs.getNamedItem("respawnDelay") != null)
  155. {
  156. spawnInfo.set("respawnDelay", parseInt(attrs, "respawnDelay"));
  157. }
  158. if (attrs.getNamedItem("respawnRandom") != null)
  159. {
  160. spawnInfo.set("respawnRandom", parseInt(attrs, "respawnRandom"));
  161. }
  162. if (attrs.getNamedItem("periodOfDay") != null)
  163. {
  164. String period = attrs.getNamedItem("periodOfDay").getNodeValue();
  165. if (period.equalsIgnoreCase("day") || period.equalsIgnoreCase("night"))
  166. {
  167. spawnInfo.set("periodOfDay", period.equalsIgnoreCase("day") ? 1 : 2);
  168. }
  169. }
  170. _xmlSpawnCount += addSpawn(spawnInfo);
  171. }
  172. }
  173. }
  174. }
  175. }
  176. }
  177. }
  178. /**
  179. * Retrieves spawn data from database.
  180. * @param isCustom if {@code true} the spawns are loaded as custom from custom spawn table
  181. * @return the spawn count
  182. */
  183. private int fillSpawnTable(boolean isCustom)
  184. {
  185. int npcSpawnCount = 0;
  186. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  187. Statement s = con.createStatement();
  188. ResultSet rs = s.executeQuery(isCustom ? SELECT_CUSTOM_SPAWNS : SELECT_SPAWNS))
  189. {
  190. while (rs.next())
  191. {
  192. StatsSet spawnInfo = new StatsSet();
  193. int npcId = rs.getInt("npc_templateid");
  194. // Check basic requirements first
  195. if (!checkTemplate(npcId))
  196. {
  197. // Don't spawn
  198. continue;
  199. }
  200. spawnInfo.set("npcTemplateid", npcId);
  201. spawnInfo.set("count", rs.getInt("count"));
  202. spawnInfo.set("x", rs.getInt("locx"));
  203. spawnInfo.set("y", rs.getInt("locy"));
  204. spawnInfo.set("z", rs.getInt("locz"));
  205. spawnInfo.set("heading", rs.getInt("heading"));
  206. spawnInfo.set("respawnDelay", rs.getInt("respawn_delay"));
  207. spawnInfo.set("respawnRandom", rs.getInt("respawn_random"));
  208. spawnInfo.set("locId", rs.getInt("loc_id"));
  209. spawnInfo.set("periodOfDay", rs.getInt("periodOfDay"));
  210. spawnInfo.set("isCustomSpawn", isCustom);
  211. npcSpawnCount += addSpawn(spawnInfo);
  212. }
  213. }
  214. catch (Exception e)
  215. {
  216. _log.log(Level.WARNING, getClass().getSimpleName() + ": Spawn could not be initialized: " + e.getMessage(), e);
  217. }
  218. return npcSpawnCount;
  219. }
  220. private int addSpawn(StatsSet spawnInfo)
  221. {
  222. L2Spawn spawnDat;
  223. int ret = 0;
  224. try
  225. {
  226. spawnDat = new L2Spawn(NpcTable.getInstance().getTemplate(spawnInfo.getInt("npcTemplateid")));
  227. spawnDat.setAmount(spawnInfo.getInt("count", 1));
  228. spawnDat.setX(spawnInfo.getInt("x", 0));
  229. spawnDat.setY(spawnInfo.getInt("y", 0));
  230. spawnDat.setZ(spawnInfo.getInt("z", 0));
  231. spawnDat.setHeading(spawnInfo.getInt("heading", -1));
  232. spawnDat.setRespawnDelay(spawnInfo.getInt("respawnDelay", 0), spawnInfo.getInt("respawnRandom", 0));
  233. spawnDat.setLocationId(spawnInfo.getInt("locId", 0));
  234. String territoryName = spawnInfo.getString("territoryName", "");
  235. spawnDat.setCustom(spawnInfo.getBoolean("isCustomSpawn", false));
  236. if (!territoryName.isEmpty())
  237. {
  238. spawnDat.setSpawnTerritory(ZoneManager.getInstance().getSpawnTerritory(territoryName));
  239. }
  240. switch (spawnInfo.getInt("periodOfDay", 0))
  241. {
  242. case 0: // default
  243. ret += spawnDat.init();
  244. break;
  245. case 1: // Day
  246. DayNightSpawnManager.getInstance().addDayCreature(spawnDat);
  247. ret = 1;
  248. break;
  249. case 2: // Night
  250. DayNightSpawnManager.getInstance().addNightCreature(spawnDat);
  251. ret = 1;
  252. break;
  253. }
  254. addSpawn(spawnDat);
  255. }
  256. catch (Exception e)
  257. {
  258. // problem with initializing spawn, go to next one
  259. _log.log(Level.WARNING, "Spawn could not be initialized: " + e.getMessage(), e);
  260. }
  261. return ret;
  262. }
  263. public Map<Integer, Set<L2Spawn>> getSpawnTable()
  264. {
  265. return _spawnTable;
  266. }
  267. /**
  268. * Get the spawns for the NPC Id.
  269. * @param npcId the NPC Id
  270. * @return the spawn set for the given npcId
  271. */
  272. public Set<L2Spawn> getSpawns(int npcId)
  273. {
  274. return _spawnTable.containsKey(npcId) ? _spawnTable.get(npcId) : Collections.<L2Spawn> emptySet();
  275. }
  276. /**
  277. * Get the first NPC spawn.
  278. * @param npcId the NPC Id to search
  279. * @return the first not null spawn, if any
  280. */
  281. public L2Spawn getFirstSpawn(int npcId)
  282. {
  283. if (_spawnTable.containsKey(npcId))
  284. {
  285. for (L2Spawn spawn : _spawnTable.get(npcId))
  286. {
  287. if (spawn != null)
  288. {
  289. return spawn;
  290. }
  291. }
  292. }
  293. return null;
  294. }
  295. /**
  296. * Add a new spawn to the spawn table.
  297. * @param spawn the spawn to add
  298. * @param storeInDb if {@code true} it'll be saved in the database
  299. */
  300. public void addNewSpawn(L2Spawn spawn, boolean storeInDb)
  301. {
  302. addSpawn(spawn);
  303. if (storeInDb)
  304. {
  305. final String spawnTable = spawn.isCustom() && Config.CUSTOM_SPAWNLIST_TABLE ? "custom_spawnlist" : "spawnlist";
  306. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  307. PreparedStatement insert = con.prepareStatement("INSERT INTO " + spawnTable + "(count,npc_templateid,locx,locy,locz,heading,respawn_delay,respawn_random,loc_id) values(?,?,?,?,?,?,?,?,?)"))
  308. {
  309. insert.setInt(1, spawn.getAmount());
  310. insert.setInt(2, spawn.getId());
  311. insert.setInt(3, spawn.getX());
  312. insert.setInt(4, spawn.getY());
  313. insert.setInt(5, spawn.getZ());
  314. insert.setInt(6, spawn.getHeading());
  315. insert.setInt(7, spawn.getRespawnDelay() / 1000);
  316. insert.setInt(8, spawn.getRespawnMaxDelay() - spawn.getRespawnMinDelay());
  317. insert.setInt(9, spawn.getLocationId());
  318. insert.execute();
  319. }
  320. catch (Exception e)
  321. {
  322. _log.log(Level.WARNING, getClass().getSimpleName() + ": Could not store spawn in the DB:" + e.getMessage(), e);
  323. }
  324. }
  325. }
  326. /**
  327. * Delete an spawn from the spawn table.
  328. * @param spawn the spawn to delete
  329. * @param updateDb if {@code true} database will be updated
  330. */
  331. public void deleteSpawn(L2Spawn spawn, boolean updateDb)
  332. {
  333. if (!removeSpawn(spawn))
  334. {
  335. return;
  336. }
  337. if (updateDb)
  338. {
  339. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  340. PreparedStatement delete = con.prepareStatement("DELETE FROM " + (spawn.isCustom() ? "custom_spawnlist" : "spawnlist") + " WHERE locx=? AND locy=? AND locz=? AND npc_templateid=? AND heading=?"))
  341. {
  342. delete.setInt(1, spawn.getX());
  343. delete.setInt(2, spawn.getY());
  344. delete.setInt(3, spawn.getZ());
  345. delete.setInt(4, spawn.getId());
  346. delete.setInt(5, spawn.getHeading());
  347. delete.execute();
  348. }
  349. catch (Exception e)
  350. {
  351. _log.log(Level.WARNING, getClass().getSimpleName() + ": Spawn " + spawn + " could not be removed from DB: " + e.getMessage(), e);
  352. }
  353. }
  354. }
  355. /**
  356. * Add a spawn to the spawn set if present, otherwise add a spawn set and add the spawn to the newly created spawn set.
  357. * @param spawn the NPC spawn to add
  358. */
  359. private void addSpawn(L2Spawn spawn)
  360. {
  361. if (!_spawnTable.containsKey(spawn.getId()))
  362. {
  363. _spawnTable.put(spawn.getId(), new FastSet<L2Spawn>().shared());
  364. }
  365. _spawnTable.get(spawn.getId()).add(spawn);
  366. }
  367. /**
  368. * Remove a spawn from the spawn set, if the spawn set is empty, remove it as well.
  369. * @param spawn the NPC spawn to remove
  370. * @return {@code true} if the spawn was successfully removed, {@code false} otherwise
  371. */
  372. private boolean removeSpawn(L2Spawn spawn)
  373. {
  374. if (_spawnTable.containsKey(spawn.getId()))
  375. {
  376. final Set<L2Spawn> set = _spawnTable.get(spawn.getId());
  377. boolean removed = set.remove(spawn);
  378. if (set.isEmpty())
  379. {
  380. _spawnTable.remove(spawn.getId());
  381. }
  382. return removed;
  383. }
  384. return false;
  385. }
  386. /**
  387. * Execute a procedure over all spawns.<br>
  388. * <font size="4" color="red">Do not use it!</font>
  389. * @param procedure the procedure to execute
  390. * @return {@code true} if all procedures were executed, {@code false} otherwise
  391. */
  392. public boolean forEachSpawn(IL2Procedure<L2Spawn> procedure)
  393. {
  394. for (Set<L2Spawn> set : _spawnTable.values())
  395. {
  396. for (L2Spawn spawn : set)
  397. {
  398. if (!procedure.execute(spawn))
  399. {
  400. return false;
  401. }
  402. }
  403. }
  404. return true;
  405. }
  406. public static SpawnTable getInstance()
  407. {
  408. return SingletonHolder._instance;
  409. }
  410. private static class SingletonHolder
  411. {
  412. protected static final SpawnTable _instance = new SpawnTable();
  413. }
  414. }