SpawnTable.java 16 KB

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