SpawnTable.java 16 KB

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