SpawnTable.java 16 KB

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