Fort.java 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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.model.entity;
  20. import java.sql.Connection;
  21. import java.sql.PreparedStatement;
  22. import java.sql.ResultSet;
  23. import java.util.ArrayList;
  24. import java.util.Calendar;
  25. import java.util.HashMap;
  26. import java.util.HashSet;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Set;
  30. import java.util.concurrent.ConcurrentHashMap;
  31. import java.util.concurrent.CopyOnWriteArrayList;
  32. import java.util.concurrent.ScheduledFuture;
  33. import java.util.concurrent.TimeUnit;
  34. import java.util.logging.Level;
  35. import java.util.logging.Logger;
  36. import com.l2jserver.Config;
  37. import com.l2jserver.commons.database.pool.impl.ConnectionFactory;
  38. import com.l2jserver.gameserver.FortUpdater;
  39. import com.l2jserver.gameserver.FortUpdater.UpdaterType;
  40. import com.l2jserver.gameserver.ThreadPoolManager;
  41. import com.l2jserver.gameserver.data.sql.impl.ClanTable;
  42. import com.l2jserver.gameserver.data.xml.impl.DoorData;
  43. import com.l2jserver.gameserver.data.xml.impl.StaticObjectData;
  44. import com.l2jserver.gameserver.datatables.SpawnTable;
  45. import com.l2jserver.gameserver.enums.MountType;
  46. import com.l2jserver.gameserver.instancemanager.CastleManager;
  47. import com.l2jserver.gameserver.instancemanager.FortManager;
  48. import com.l2jserver.gameserver.instancemanager.ZoneManager;
  49. import com.l2jserver.gameserver.model.L2Clan;
  50. import com.l2jserver.gameserver.model.L2Object;
  51. import com.l2jserver.gameserver.model.L2Spawn;
  52. import com.l2jserver.gameserver.model.L2World;
  53. import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
  54. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  55. import com.l2jserver.gameserver.model.actor.instance.L2StaticObjectInstance;
  56. import com.l2jserver.gameserver.model.itemcontainer.Inventory;
  57. import com.l2jserver.gameserver.model.zone.type.L2FortZone;
  58. import com.l2jserver.gameserver.model.zone.type.L2SiegeZone;
  59. import com.l2jserver.gameserver.network.SystemMessageId;
  60. import com.l2jserver.gameserver.network.serverpackets.PlaySound;
  61. import com.l2jserver.gameserver.network.serverpackets.PledgeShowInfoUpdate;
  62. import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
  63. public final class Fort extends AbstractResidence
  64. {
  65. protected static final Logger _log = Logger.getLogger(Fort.class.getName());
  66. private final List<L2DoorInstance> _doors = new ArrayList<>();
  67. private L2StaticObjectInstance _flagPole = null;
  68. private volatile FortSiege _siege = null;
  69. private Calendar _siegeDate;
  70. private Calendar _lastOwnedTime;
  71. private L2SiegeZone _zone;
  72. private L2Clan _fortOwner = null;
  73. private int _fortType = 0;
  74. private int _state = 0;
  75. private int _castleId = 0;
  76. private int _supplyLvL = 0;
  77. private final Map<Integer, FortFunction> _function;
  78. private final ScheduledFuture<?>[] _FortUpdater = new ScheduledFuture<?>[2];
  79. // Spawn Data
  80. private boolean _isSuspiciousMerchantSpawned = false;
  81. private final List<L2Spawn> _siegeNpcs = new CopyOnWriteArrayList<>();
  82. private final List<L2Spawn> _npcCommanders = new CopyOnWriteArrayList<>();
  83. private final List<L2Spawn> _specialEnvoys = new CopyOnWriteArrayList<>();
  84. private final Map<Integer, Integer> _envoyCastles = new HashMap<>(2);
  85. private final Set<Integer> _availableCastles = new HashSet<>(1);
  86. /** Fortress Functions */
  87. public static final int FUNC_TELEPORT = 1;
  88. public static final int FUNC_RESTORE_HP = 2;
  89. public static final int FUNC_RESTORE_MP = 3;
  90. public static final int FUNC_RESTORE_EXP = 4;
  91. public static final int FUNC_SUPPORT = 5;
  92. public class FortFunction
  93. {
  94. private final int _type;
  95. private int _lvl;
  96. protected int _fee;
  97. protected int _tempFee;
  98. private final long _rate;
  99. private long _endDate;
  100. protected boolean _inDebt;
  101. public boolean _cwh;
  102. public FortFunction(int type, int lvl, int lease, int tempLease, long rate, long time, boolean cwh)
  103. {
  104. _type = type;
  105. _lvl = lvl;
  106. _fee = lease;
  107. _tempFee = tempLease;
  108. _rate = rate;
  109. _endDate = time;
  110. initializeTask(cwh);
  111. }
  112. public int getType()
  113. {
  114. return _type;
  115. }
  116. public int getLvl()
  117. {
  118. return _lvl;
  119. }
  120. public int getLease()
  121. {
  122. return _fee;
  123. }
  124. public long getRate()
  125. {
  126. return _rate;
  127. }
  128. public long getEndTime()
  129. {
  130. return _endDate;
  131. }
  132. public void setLvl(int lvl)
  133. {
  134. _lvl = lvl;
  135. }
  136. public void setLease(int lease)
  137. {
  138. _fee = lease;
  139. }
  140. public void setEndTime(long time)
  141. {
  142. _endDate = time;
  143. }
  144. private void initializeTask(boolean cwh)
  145. {
  146. if (getOwnerClan() == null)
  147. {
  148. return;
  149. }
  150. long currentTime = System.currentTimeMillis();
  151. if (_endDate > currentTime)
  152. {
  153. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), _endDate - currentTime);
  154. }
  155. else
  156. {
  157. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), 0);
  158. }
  159. }
  160. private class FunctionTask implements Runnable
  161. {
  162. public FunctionTask(boolean cwh)
  163. {
  164. _cwh = cwh;
  165. }
  166. @Override
  167. public void run()
  168. {
  169. try
  170. {
  171. if (getOwnerClan() == null)
  172. {
  173. return;
  174. }
  175. if ((getOwnerClan().getWarehouse().getAdena() >= _fee) || !_cwh)
  176. {
  177. int fee = _fee;
  178. if (getEndTime() == -1)
  179. {
  180. fee = _tempFee;
  181. }
  182. setEndTime(System.currentTimeMillis() + getRate());
  183. dbSave();
  184. if (_cwh)
  185. {
  186. getOwnerClan().getWarehouse().destroyItemByItemId("CS_function_fee", Inventory.ADENA_ID, fee, null, null);
  187. }
  188. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(true), getRate());
  189. }
  190. else
  191. {
  192. removeFunction(getType());
  193. }
  194. }
  195. catch (Throwable t)
  196. {
  197. }
  198. }
  199. }
  200. public void dbSave()
  201. {
  202. try (Connection con = ConnectionFactory.getInstance().getConnection();
  203. PreparedStatement ps = con.prepareStatement("REPLACE INTO fort_functions (fort_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)"))
  204. {
  205. ps.setInt(1, getResidenceId());
  206. ps.setInt(2, getType());
  207. ps.setInt(3, getLvl());
  208. ps.setInt(4, getLease());
  209. ps.setLong(5, getRate());
  210. ps.setLong(6, getEndTime());
  211. ps.execute();
  212. }
  213. catch (Exception e)
  214. {
  215. _log.log(Level.SEVERE, "Exception: Fort.updateFunctions(int type, int lvl, int lease, long rate, long time, boolean addNew): " + e.getMessage(), e);
  216. }
  217. }
  218. }
  219. public Fort(int fortId)
  220. {
  221. super(fortId);
  222. load();
  223. loadFlagPoles();
  224. _function = new ConcurrentHashMap<>();
  225. if (getOwnerClan() != null)
  226. {
  227. setVisibleFlag(true);
  228. loadFunctions();
  229. }
  230. initResidenceZone();
  231. initNpcs(); // load and spawn npcs (Always spawned)
  232. initSiegeNpcs(); // load suspicious merchants (Despawned 10mins before siege)
  233. // spawnSuspiciousMerchant();// spawn suspicious merchants
  234. initNpcCommanders(); // npc Commanders (not monsters) (Spawned during siege)
  235. spawnNpcCommanders(); // spawn npc Commanders
  236. initSpecialEnvoys(); // envoys from castles (Spawned after fort taken)
  237. if ((getOwnerClan() != null) && (getFortState() == 0))
  238. {
  239. spawnSpecialEnvoys();
  240. }
  241. }
  242. /**
  243. * Return function with id
  244. * @param type
  245. * @return
  246. */
  247. public FortFunction getFunction(int type)
  248. {
  249. return _function.get(type);
  250. }
  251. public void endOfSiege(L2Clan clan)
  252. {
  253. ThreadPoolManager.getInstance().executeAi(new endFortressSiege(this, clan));
  254. }
  255. /**
  256. * Move non clan members off fort area and to nearest town.<BR>
  257. * <BR>
  258. */
  259. public void banishForeigners()
  260. {
  261. getResidenceZone().banishForeigners(getOwnerClan().getId());
  262. }
  263. /**
  264. * @param x
  265. * @param y
  266. * @param z
  267. * @return true if object is inside the zone
  268. */
  269. public boolean checkIfInZone(int x, int y, int z)
  270. {
  271. return getZone().isInsideZone(x, y, z);
  272. }
  273. public L2SiegeZone getZone()
  274. {
  275. if (_zone == null)
  276. {
  277. for (L2SiegeZone zone : ZoneManager.getInstance().getAllZones(L2SiegeZone.class))
  278. {
  279. if (zone.getSiegeObjectId() == getResidenceId())
  280. {
  281. _zone = zone;
  282. break;
  283. }
  284. }
  285. }
  286. return _zone;
  287. }
  288. @Override
  289. public L2FortZone getResidenceZone()
  290. {
  291. return (L2FortZone) super.getResidenceZone();
  292. }
  293. /**
  294. * Get the objects distance to this fort
  295. * @param obj
  296. * @return
  297. */
  298. public double getDistance(L2Object obj)
  299. {
  300. return getZone().getDistanceToZone(obj);
  301. }
  302. public void closeDoor(L2PcInstance activeChar, int doorId)
  303. {
  304. openCloseDoor(activeChar, doorId, false);
  305. }
  306. public void openDoor(L2PcInstance activeChar, int doorId)
  307. {
  308. openCloseDoor(activeChar, doorId, true);
  309. }
  310. public void openCloseDoor(L2PcInstance activeChar, int doorId, boolean open)
  311. {
  312. if (activeChar.getClan() != getOwnerClan())
  313. {
  314. return;
  315. }
  316. L2DoorInstance door = getDoor(doorId);
  317. if (door != null)
  318. {
  319. if (open)
  320. {
  321. door.openMe();
  322. }
  323. else
  324. {
  325. door.closeMe();
  326. }
  327. }
  328. }
  329. // This method is used to begin removing all fort upgrades
  330. public void removeUpgrade()
  331. {
  332. removeDoorUpgrade();
  333. }
  334. /**
  335. * This method will set owner for Fort
  336. * @param clan
  337. * @param updateClansReputation
  338. * @return
  339. */
  340. public boolean setOwner(L2Clan clan, boolean updateClansReputation)
  341. {
  342. if (clan == null)
  343. {
  344. _log.warning(getClass().getSimpleName() + ": Updating Fort owner with null clan!!!");
  345. return false;
  346. }
  347. final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.THE_FORTRESS_BATTLE_OF_S1_HAS_FINISHED);
  348. sm.addCastleId(getResidenceId());
  349. getSiege().announceToPlayer(sm);
  350. final L2Clan oldowner = getOwnerClan();
  351. if ((oldowner != null) && (clan != oldowner))
  352. {
  353. // Remove points from old owner
  354. updateClansReputation(oldowner, true);
  355. try
  356. {
  357. L2PcInstance oldleader = oldowner.getLeader().getPlayerInstance();
  358. if (oldleader != null)
  359. {
  360. if (oldleader.getMountType() == MountType.WYVERN)
  361. {
  362. oldleader.dismount();
  363. }
  364. }
  365. }
  366. catch (Exception e)
  367. {
  368. _log.log(Level.WARNING, "Exception in setOwner: " + e.getMessage(), e);
  369. }
  370. removeOwner(true);
  371. }
  372. setFortState(0, 0); // initialize fort state
  373. // if clan already have castle, don't store him in fortress
  374. if (clan.getCastleId() > 0)
  375. {
  376. getSiege().announceToPlayer(SystemMessage.getSystemMessage(SystemMessageId.NPCS_RECAPTURED_FORTRESS));
  377. return false;
  378. }
  379. // Give points to new owner
  380. if (updateClansReputation)
  381. {
  382. updateClansReputation(clan, false);
  383. }
  384. spawnSpecialEnvoys();
  385. // if clan have already fortress, remove it
  386. if (clan.getFortId() > 0)
  387. {
  388. FortManager.getInstance().getFortByOwner(clan).removeOwner(true);
  389. }
  390. setSupplyLvL(0);
  391. setOwnerClan(clan);
  392. updateOwnerInDB(); // Update in database
  393. saveFortVariables();
  394. if (getSiege().isInProgress())
  395. {
  396. getSiege().endSiege();
  397. }
  398. for (L2PcInstance member : clan.getOnlineMembers(0))
  399. {
  400. giveResidentialSkills(member);
  401. member.sendSkillList();
  402. }
  403. return true;
  404. }
  405. public void removeOwner(boolean updateDB)
  406. {
  407. L2Clan clan = getOwnerClan();
  408. if (clan != null)
  409. {
  410. for (L2PcInstance member : clan.getOnlineMembers(0))
  411. {
  412. removeResidentialSkills(member);
  413. member.sendSkillList();
  414. }
  415. clan.setFortId(0);
  416. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  417. setOwnerClan(null);
  418. setSupplyLvL(0);
  419. saveFortVariables();
  420. removeAllFunctions();
  421. if (updateDB)
  422. {
  423. updateOwnerInDB();
  424. }
  425. }
  426. }
  427. public void raiseSupplyLvL()
  428. {
  429. _supplyLvL++;
  430. if (_supplyLvL > Config.FS_MAX_SUPPLY_LEVEL)
  431. {
  432. _supplyLvL = Config.FS_MAX_SUPPLY_LEVEL;
  433. }
  434. }
  435. public void setSupplyLvL(int val)
  436. {
  437. if (val <= Config.FS_MAX_SUPPLY_LEVEL)
  438. {
  439. _supplyLvL = val;
  440. }
  441. }
  442. public int getSupplyLvL()
  443. {
  444. return _supplyLvL;
  445. }
  446. public void saveFortVariables()
  447. {
  448. try (Connection con = ConnectionFactory.getInstance().getConnection();
  449. PreparedStatement ps = con.prepareStatement("UPDATE fort SET supplyLvL=? WHERE id = ?"))
  450. {
  451. ps.setInt(1, _supplyLvL);
  452. ps.setInt(2, getResidenceId());
  453. ps.execute();
  454. }
  455. catch (Exception e)
  456. {
  457. _log.log(Level.WARNING, "Exception: saveFortVariables(): " + e.getMessage(), e);
  458. }
  459. }
  460. /**
  461. * Show or hide flag inside flag pole.
  462. * @param val
  463. */
  464. public void setVisibleFlag(boolean val)
  465. {
  466. L2StaticObjectInstance flagPole = getFlagPole();
  467. if (flagPole != null)
  468. {
  469. flagPole.setMeshIndex(val ? 1 : 0);
  470. }
  471. }
  472. /**
  473. * Respawn all doors on fort grounds<BR>
  474. * <BR>
  475. */
  476. public void resetDoors()
  477. {
  478. for (L2DoorInstance door : _doors)
  479. {
  480. if (door.getOpen())
  481. {
  482. door.closeMe();
  483. }
  484. if (door.isDead())
  485. {
  486. door.doRevive();
  487. }
  488. if (door.getCurrentHp() < door.getMaxHp())
  489. {
  490. door.setCurrentHp(door.getMaxHp());
  491. }
  492. }
  493. loadDoorUpgrade(); // Check for any upgrade the doors may have
  494. }
  495. // This method upgrade door
  496. public void upgradeDoor(int doorId, int hp, int pDef, int mDef)
  497. {
  498. L2DoorInstance door = getDoor(doorId);
  499. if (door != null)
  500. {
  501. door.setCurrentHp(door.getMaxHp() + hp);
  502. saveDoorUpgrade(doorId, hp, pDef, mDef);
  503. return;
  504. }
  505. }
  506. // This method loads fort
  507. @Override
  508. protected void load()
  509. {
  510. try (Connection con = ConnectionFactory.getInstance().getConnection();
  511. PreparedStatement ps = con.prepareStatement("SELECT * FROM fort WHERE id = ?"))
  512. {
  513. ps.setInt(1, getResidenceId());
  514. int ownerId = 0;
  515. try (ResultSet rs = ps.executeQuery())
  516. {
  517. while (rs.next())
  518. {
  519. setName(rs.getString("name"));
  520. _siegeDate = Calendar.getInstance();
  521. _lastOwnedTime = Calendar.getInstance();
  522. _siegeDate.setTimeInMillis(rs.getLong("siegeDate"));
  523. _lastOwnedTime.setTimeInMillis(rs.getLong("lastOwnedTime"));
  524. ownerId = rs.getInt("owner");
  525. _fortType = rs.getInt("fortType");
  526. _state = rs.getInt("state");
  527. _castleId = rs.getInt("castleId");
  528. _supplyLvL = rs.getInt("supplyLvL");
  529. }
  530. }
  531. if (ownerId > 0)
  532. {
  533. L2Clan clan = ClanTable.getInstance().getClan(ownerId); // Try to find clan instance
  534. clan.setFortId(getResidenceId());
  535. setOwnerClan(clan);
  536. int runCount = getOwnedTime() / (Config.FS_UPDATE_FRQ * 60);
  537. long initial = System.currentTimeMillis() - _lastOwnedTime.getTimeInMillis();
  538. while (initial > (Config.FS_UPDATE_FRQ * 60000L))
  539. {
  540. initial -= (Config.FS_UPDATE_FRQ * 60000L);
  541. }
  542. initial = (Config.FS_UPDATE_FRQ * 60000L) - initial;
  543. if ((Config.FS_MAX_OWN_TIME <= 0) || (getOwnedTime() < (Config.FS_MAX_OWN_TIME * 3600)))
  544. {
  545. _FortUpdater[0] = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FortUpdater(this, clan, runCount, UpdaterType.PERIODIC_UPDATE), initial, Config.FS_UPDATE_FRQ * 60000L); // Schedule owner tasks to start running
  546. if (Config.FS_MAX_OWN_TIME > 0)
  547. {
  548. _FortUpdater[1] = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FortUpdater(this, clan, runCount, UpdaterType.MAX_OWN_TIME), 3600000, 3600000); // Schedule owner tasks to remove owener
  549. }
  550. }
  551. else
  552. {
  553. _FortUpdater[1] = ThreadPoolManager.getInstance().scheduleGeneral(new FortUpdater(this, clan, 0, UpdaterType.MAX_OWN_TIME), 60000); // Schedule owner tasks to remove owner
  554. }
  555. }
  556. else
  557. {
  558. setOwnerClan(null);
  559. }
  560. }
  561. catch (Exception e)
  562. {
  563. _log.log(Level.WARNING, "Exception: loadFortData(): " + e.getMessage(), e);
  564. }
  565. }
  566. /** Load All Functions */
  567. private void loadFunctions()
  568. {
  569. try (Connection con = ConnectionFactory.getInstance().getConnection();
  570. PreparedStatement ps = con.prepareStatement("SELECT * FROM fort_functions WHERE fort_id = ?"))
  571. {
  572. ps.setInt(1, getResidenceId());
  573. try (ResultSet rs = ps.executeQuery())
  574. {
  575. while (rs.next())
  576. {
  577. _function.put(rs.getInt("type"), new FortFunction(rs.getInt("type"), rs.getInt("lvl"), rs.getInt("lease"), 0, rs.getLong("rate"), rs.getLong("endTime"), true));
  578. }
  579. }
  580. }
  581. catch (Exception e)
  582. {
  583. _log.log(Level.SEVERE, "Exception: Fort.loadFunctions(): " + e.getMessage(), e);
  584. }
  585. }
  586. /**
  587. * Remove function In List and in DB
  588. * @param functionType
  589. */
  590. public void removeFunction(int functionType)
  591. {
  592. _function.remove(functionType);
  593. try (Connection con = ConnectionFactory.getInstance().getConnection();
  594. PreparedStatement ps = con.prepareStatement("DELETE FROM fort_functions WHERE fort_id=? AND type=?"))
  595. {
  596. ps.setInt(1, getResidenceId());
  597. ps.setInt(2, functionType);
  598. ps.execute();
  599. }
  600. catch (Exception e)
  601. {
  602. _log.log(Level.SEVERE, "Exception: Fort.removeFunctions(int functionType): " + e.getMessage(), e);
  603. }
  604. }
  605. /**
  606. * Remove all fort functions.
  607. */
  608. private void removeAllFunctions()
  609. {
  610. for (int id : _function.keySet())
  611. {
  612. removeFunction(id);
  613. }
  614. }
  615. public boolean updateFunctions(L2PcInstance player, int type, int lvl, int lease, long rate, boolean addNew)
  616. {
  617. if (player == null)
  618. {
  619. return false;
  620. }
  621. if (lease > 0)
  622. {
  623. if (!player.destroyItemByItemId("Consume", Inventory.ADENA_ID, lease, null, true))
  624. {
  625. return false;
  626. }
  627. }
  628. if (addNew)
  629. {
  630. _function.put(type, new FortFunction(type, lvl, lease, 0, rate, 0, false));
  631. }
  632. else
  633. {
  634. if ((lvl == 0) && (lease == 0))
  635. {
  636. removeFunction(type);
  637. }
  638. else
  639. {
  640. int diffLease = lease - _function.get(type).getLease();
  641. if (diffLease > 0)
  642. {
  643. _function.remove(type);
  644. _function.put(type, new FortFunction(type, lvl, lease, 0, rate, -1, false));
  645. }
  646. else
  647. {
  648. _function.get(type).setLease(lease);
  649. _function.get(type).setLvl(lvl);
  650. _function.get(type).dbSave();
  651. }
  652. }
  653. }
  654. return true;
  655. }
  656. public void activateInstance()
  657. {
  658. loadDoor();
  659. }
  660. // This method loads fort door data from database
  661. private void loadDoor()
  662. {
  663. for (L2DoorInstance door : DoorData.getInstance().getDoors())
  664. {
  665. if ((door.getFort() != null) && (door.getFort().getResidenceId() == getResidenceId()))
  666. {
  667. _doors.add(door);
  668. }
  669. }
  670. }
  671. private void loadFlagPoles()
  672. {
  673. for (L2StaticObjectInstance obj : StaticObjectData.getInstance().getStaticObjects())
  674. {
  675. if ((obj.getType() == 3) && obj.getName().startsWith(getName()))
  676. {
  677. _flagPole = obj;
  678. break;
  679. }
  680. }
  681. if (_flagPole == null)
  682. {
  683. throw new NullPointerException("Can't find flagpole for Fort " + this);
  684. }
  685. }
  686. // This method loads fort door upgrade data from database
  687. private void loadDoorUpgrade()
  688. {
  689. try (Connection con = ConnectionFactory.getInstance().getConnection();
  690. PreparedStatement ps = con.prepareStatement("SELECT * FROM fort_doorupgrade WHERE fortId = ?"))
  691. {
  692. ps.setInt(1, getResidenceId());
  693. try (ResultSet rs = ps.executeQuery())
  694. {
  695. while (rs.next())
  696. {
  697. upgradeDoor(rs.getInt("id"), rs.getInt("hp"), rs.getInt("pDef"), rs.getInt("mDef"));
  698. }
  699. }
  700. }
  701. catch (Exception e)
  702. {
  703. _log.log(Level.WARNING, "Exception: loadFortDoorUpgrade(): " + e.getMessage(), e);
  704. }
  705. }
  706. private void removeDoorUpgrade()
  707. {
  708. try (Connection con = ConnectionFactory.getInstance().getConnection();
  709. PreparedStatement ps = con.prepareStatement("DELETE FROM fort_doorupgrade WHERE fortId = ?"))
  710. {
  711. ps.setInt(1, getResidenceId());
  712. ps.execute();
  713. }
  714. catch (Exception e)
  715. {
  716. _log.log(Level.WARNING, "Exception: removeDoorUpgrade(): " + e.getMessage(), e);
  717. }
  718. }
  719. private void saveDoorUpgrade(int doorId, int hp, int pDef, int mDef)
  720. {
  721. try (Connection con = ConnectionFactory.getInstance().getConnection();
  722. PreparedStatement ps = con.prepareStatement("INSERT INTO fort_doorupgrade (doorId, hp, pDef, mDef) VALUES (?,?,?,?)"))
  723. {
  724. ps.setInt(1, doorId);
  725. ps.setInt(2, hp);
  726. ps.setInt(3, pDef);
  727. ps.setInt(4, mDef);
  728. ps.execute();
  729. }
  730. catch (Exception e)
  731. {
  732. _log.log(Level.WARNING, "Exception: saveDoorUpgrade(int doorId, int hp, int pDef, int mDef): " + e.getMessage(), e);
  733. }
  734. }
  735. private void updateOwnerInDB()
  736. {
  737. L2Clan clan = getOwnerClan();
  738. int clanId = 0;
  739. if (clan != null)
  740. {
  741. clanId = clan.getId();
  742. _lastOwnedTime.setTimeInMillis(System.currentTimeMillis());
  743. }
  744. else
  745. {
  746. _lastOwnedTime.setTimeInMillis(0);
  747. }
  748. try (Connection con = ConnectionFactory.getInstance().getConnection();
  749. PreparedStatement ps = con.prepareStatement("UPDATE fort SET owner=?,lastOwnedTime=?,state=?,castleId=? WHERE id = ?"))
  750. {
  751. ps.setInt(1, clanId);
  752. ps.setLong(2, _lastOwnedTime.getTimeInMillis());
  753. ps.setInt(3, 0);
  754. ps.setInt(4, 0);
  755. ps.setInt(5, getResidenceId());
  756. ps.execute();
  757. // Announce to clan members
  758. if (clan != null)
  759. {
  760. clan.setFortId(getResidenceId()); // Set has fort flag for new owner
  761. SystemMessage sm;
  762. sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CLAN_IS_VICTORIOUS_IN_THE_FORTRESS_BATTLE_OF_S2);
  763. sm.addString(clan.getName());
  764. sm.addCastleId(getResidenceId());
  765. L2World.getInstance().getPlayers().forEach(p -> p.sendPacket(sm));
  766. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  767. clan.broadcastToOnlineMembers(new PlaySound(1, "Siege_Victory", 0, 0, 0, 0, 0));
  768. if (_FortUpdater[0] != null)
  769. {
  770. _FortUpdater[0].cancel(false);
  771. }
  772. if (_FortUpdater[1] != null)
  773. {
  774. _FortUpdater[1].cancel(false);
  775. }
  776. _FortUpdater[0] = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FortUpdater(this, clan, 0, UpdaterType.PERIODIC_UPDATE), Config.FS_UPDATE_FRQ * 60000L, Config.FS_UPDATE_FRQ * 60000L); // Schedule owner tasks to start running
  777. if (Config.FS_MAX_OWN_TIME > 0)
  778. {
  779. _FortUpdater[1] = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FortUpdater(this, clan, 0, UpdaterType.MAX_OWN_TIME), 3600000, 3600000); // Schedule owner tasks to remove owener
  780. }
  781. }
  782. else
  783. {
  784. if (_FortUpdater[0] != null)
  785. {
  786. _FortUpdater[0].cancel(false);
  787. }
  788. _FortUpdater[0] = null;
  789. if (_FortUpdater[1] != null)
  790. {
  791. _FortUpdater[1].cancel(false);
  792. }
  793. _FortUpdater[1] = null;
  794. }
  795. }
  796. catch (Exception e)
  797. {
  798. _log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
  799. }
  800. }
  801. public final L2Clan getOwnerClan()
  802. {
  803. return _fortOwner;
  804. }
  805. public final void setOwnerClan(L2Clan clan)
  806. {
  807. setVisibleFlag(clan != null);
  808. _fortOwner = clan;
  809. }
  810. public final L2DoorInstance getDoor(int doorId)
  811. {
  812. if (doorId <= 0)
  813. {
  814. return null;
  815. }
  816. for (L2DoorInstance door : getDoors())
  817. {
  818. if (door.getId() == doorId)
  819. {
  820. return door;
  821. }
  822. }
  823. return null;
  824. }
  825. public final List<L2DoorInstance> getDoors()
  826. {
  827. return _doors;
  828. }
  829. public final L2StaticObjectInstance getFlagPole()
  830. {
  831. return _flagPole;
  832. }
  833. public final FortSiege getSiege()
  834. {
  835. if (_siege == null)
  836. {
  837. synchronized (this)
  838. {
  839. if (_siege == null)
  840. {
  841. _siege = new FortSiege(this);
  842. }
  843. }
  844. }
  845. return _siege;
  846. }
  847. public final Calendar getSiegeDate()
  848. {
  849. return _siegeDate;
  850. }
  851. public final void setSiegeDate(Calendar siegeDate)
  852. {
  853. _siegeDate = siegeDate;
  854. }
  855. public final int getOwnedTime()
  856. {
  857. if (_lastOwnedTime.getTimeInMillis() == 0)
  858. {
  859. return 0;
  860. }
  861. return (int) ((System.currentTimeMillis() - _lastOwnedTime.getTimeInMillis()) / 1000);
  862. }
  863. public final int getTimeTillRebelArmy()
  864. {
  865. if (_lastOwnedTime.getTimeInMillis() == 0)
  866. {
  867. return 0;
  868. }
  869. return (int) (((_lastOwnedTime.getTimeInMillis() + (Config.FS_MAX_OWN_TIME * 3600000L)) - System.currentTimeMillis()) / 1000L);
  870. }
  871. public final long getTimeTillNextFortUpdate()
  872. {
  873. if (_FortUpdater[0] == null)
  874. {
  875. return 0;
  876. }
  877. return _FortUpdater[0].getDelay(TimeUnit.SECONDS);
  878. }
  879. public void updateClansReputation(L2Clan owner, boolean removePoints)
  880. {
  881. if (owner != null)
  882. {
  883. if (removePoints)
  884. {
  885. owner.takeReputationScore(Config.LOOSE_FORT_POINTS, true);
  886. }
  887. else
  888. {
  889. owner.addReputationScore(Config.TAKE_FORT_POINTS, true);
  890. }
  891. }
  892. }
  893. private static class endFortressSiege implements Runnable
  894. {
  895. private final Fort _f;
  896. private final L2Clan _clan;
  897. public endFortressSiege(Fort f, L2Clan clan)
  898. {
  899. _f = f;
  900. _clan = clan;
  901. }
  902. @Override
  903. public void run()
  904. {
  905. try
  906. {
  907. _f.setOwner(_clan, true);
  908. }
  909. catch (Exception e)
  910. {
  911. _log.log(Level.WARNING, "Exception in endFortressSiege " + e.getMessage(), e);
  912. }
  913. }
  914. }
  915. /**
  916. * @return Returns state of fortress.<BR>
  917. * <BR>
  918. * 0 - not decided yet<BR>
  919. * 1 - independent<BR>
  920. * 2 - contracted with castle<BR>
  921. */
  922. public final int getFortState()
  923. {
  924. return _state;
  925. }
  926. /**
  927. * @param state <ul>
  928. * <li>0 - not decided yet</li>
  929. * <li>1 - independent</li>
  930. * <li>2 - contracted with castle</li>
  931. * </ul>
  932. * @param castleId the Id of the contracted castle (0 if no contract with any castle)
  933. */
  934. public final void setFortState(int state, int castleId)
  935. {
  936. _state = state;
  937. _castleId = castleId;
  938. try (Connection con = ConnectionFactory.getInstance().getConnection();
  939. PreparedStatement ps = con.prepareStatement("UPDATE fort SET state=?,castleId=? WHERE id = ?"))
  940. {
  941. ps.setInt(1, getFortState());
  942. ps.setInt(2, getContractedCastleId());
  943. ps.setInt(3, getResidenceId());
  944. ps.execute();
  945. }
  946. catch (Exception e)
  947. {
  948. _log.log(Level.WARNING, "Exception: setFortState(int state, int castleId): " + e.getMessage(), e);
  949. }
  950. }
  951. /**
  952. * @return the fortress type (0 - small (3 commanders), 1 - big (4 commanders + control room))
  953. */
  954. public final int getFortType()
  955. {
  956. return _fortType;
  957. }
  958. /**
  959. * @param npcId the Id of the ambassador NPC
  960. * @return the Id of the castle this ambassador represents
  961. */
  962. public final int getCastleIdByAmbassador(int npcId)
  963. {
  964. return _envoyCastles.get(npcId);
  965. }
  966. /**
  967. * @param npcId the Id of the ambassador NPC
  968. * @return the castle this ambassador represents
  969. */
  970. public final Castle getCastleByAmbassador(int npcId)
  971. {
  972. return CastleManager.getInstance().getCastleById(getCastleIdByAmbassador(npcId));
  973. }
  974. /**
  975. * @return the Id of the castle contracted with this fortress
  976. */
  977. public final int getContractedCastleId()
  978. {
  979. return _castleId;
  980. }
  981. /**
  982. * @return the castle contracted with this fortress ({@code null} if no contract with any castle)
  983. */
  984. public final Castle getContractedCastle()
  985. {
  986. return CastleManager.getInstance().getCastleById(getContractedCastleId());
  987. }
  988. /**
  989. * Check if this is a border fortress (associated with multiple castles).
  990. * @return {@code true} if this is a border fortress (associated with more than one castle), {@code false} otherwise
  991. */
  992. public final boolean isBorderFortress()
  993. {
  994. return _availableCastles.size() > 1;
  995. }
  996. /**
  997. * @return the amount of barracks in this fortress
  998. */
  999. public final int getFortSize()
  1000. {
  1001. return getFortType() == 0 ? 3 : 5;
  1002. }
  1003. public void spawnSuspiciousMerchant()
  1004. {
  1005. if (_isSuspiciousMerchantSpawned)
  1006. {
  1007. return;
  1008. }
  1009. _isSuspiciousMerchantSpawned = true;
  1010. for (L2Spawn spawnDat : _siegeNpcs)
  1011. {
  1012. spawnDat.doSpawn();
  1013. spawnDat.startRespawn();
  1014. }
  1015. }
  1016. public void despawnSuspiciousMerchant()
  1017. {
  1018. if (!_isSuspiciousMerchantSpawned)
  1019. {
  1020. return;
  1021. }
  1022. _isSuspiciousMerchantSpawned = false;
  1023. for (L2Spawn spawnDat : _siegeNpcs)
  1024. {
  1025. spawnDat.stopRespawn();
  1026. spawnDat.getLastSpawn().deleteMe();
  1027. }
  1028. }
  1029. public void spawnNpcCommanders()
  1030. {
  1031. for (L2Spawn spawnDat : _npcCommanders)
  1032. {
  1033. spawnDat.doSpawn();
  1034. spawnDat.startRespawn();
  1035. }
  1036. }
  1037. public void despawnNpcCommanders()
  1038. {
  1039. for (L2Spawn spawnDat : _npcCommanders)
  1040. {
  1041. spawnDat.stopRespawn();
  1042. spawnDat.getLastSpawn().deleteMe();
  1043. }
  1044. }
  1045. public void spawnSpecialEnvoys()
  1046. {
  1047. for (L2Spawn spawnDat : _specialEnvoys)
  1048. {
  1049. spawnDat.doSpawn();
  1050. spawnDat.startRespawn();
  1051. }
  1052. }
  1053. private void initNpcs()
  1054. {
  1055. try (Connection con = ConnectionFactory.getInstance().getConnection();
  1056. PreparedStatement ps = con.prepareStatement("SELECT * FROM fort_spawnlist WHERE fortId = ? AND spawnType = ?"))
  1057. {
  1058. ps.setInt(1, getResidenceId());
  1059. ps.setInt(2, 0);
  1060. try (ResultSet rs = ps.executeQuery())
  1061. {
  1062. while (rs.next())
  1063. {
  1064. L2Spawn spawnDat = new L2Spawn(rs.getInt("npcId"));
  1065. spawnDat.setAmount(1);
  1066. spawnDat.setX(rs.getInt("x"));
  1067. spawnDat.setY(rs.getInt("y"));
  1068. spawnDat.setZ(rs.getInt("z"));
  1069. spawnDat.setHeading(rs.getInt("heading"));
  1070. spawnDat.setRespawnDelay(60);
  1071. SpawnTable.getInstance().addNewSpawn(spawnDat, false);
  1072. spawnDat.doSpawn();
  1073. spawnDat.startRespawn();
  1074. }
  1075. }
  1076. }
  1077. catch (Exception e)
  1078. {
  1079. _log.log(Level.WARNING, "Fort " + getResidenceId() + " initNpcs: Spawn could not be initialized: " + e.getMessage(), e);
  1080. }
  1081. }
  1082. private void initSiegeNpcs()
  1083. {
  1084. _siegeNpcs.clear();
  1085. try (Connection con = ConnectionFactory.getInstance().getConnection();
  1086. PreparedStatement ps = con.prepareStatement("SELECT id, npcId, x, y, z, heading FROM fort_spawnlist WHERE fortId = ? AND spawnType = ? ORDER BY id"))
  1087. {
  1088. ps.setInt(1, getResidenceId());
  1089. ps.setInt(2, 2);
  1090. try (ResultSet rs = ps.executeQuery())
  1091. {
  1092. while (rs.next())
  1093. {
  1094. final L2Spawn spawnDat = new L2Spawn(rs.getInt("npcId"));
  1095. spawnDat.setAmount(1);
  1096. spawnDat.setX(rs.getInt("x"));
  1097. spawnDat.setY(rs.getInt("y"));
  1098. spawnDat.setZ(rs.getInt("z"));
  1099. spawnDat.setHeading(rs.getInt("heading"));
  1100. spawnDat.setRespawnDelay(60);
  1101. _siegeNpcs.add(spawnDat);
  1102. }
  1103. }
  1104. }
  1105. catch (Exception e)
  1106. {
  1107. _log.log(Level.WARNING, "Fort " + getResidenceId() + " initSiegeNpcs: Spawn could not be initialized: " + e.getMessage(), e);
  1108. }
  1109. }
  1110. private void initNpcCommanders()
  1111. {
  1112. _npcCommanders.clear();
  1113. try (Connection con = ConnectionFactory.getInstance().getConnection();
  1114. PreparedStatement ps = con.prepareStatement("SELECT id, npcId, x, y, z, heading FROM fort_spawnlist WHERE fortId = ? AND spawnType = ? ORDER BY id"))
  1115. {
  1116. ps.setInt(1, getResidenceId());
  1117. ps.setInt(2, 1);
  1118. try (ResultSet rs = ps.executeQuery())
  1119. {
  1120. while (rs.next())
  1121. {
  1122. final L2Spawn spawnDat = new L2Spawn(rs.getInt("npcId"));
  1123. spawnDat.setAmount(1);
  1124. spawnDat.setX(rs.getInt("x"));
  1125. spawnDat.setY(rs.getInt("y"));
  1126. spawnDat.setZ(rs.getInt("z"));
  1127. spawnDat.setHeading(rs.getInt("heading"));
  1128. spawnDat.setRespawnDelay(60);
  1129. _npcCommanders.add(spawnDat);
  1130. }
  1131. }
  1132. }
  1133. catch (Exception e)
  1134. {
  1135. // problem with initializing spawn, go to next one
  1136. _log.log(Level.WARNING, "Fort " + getResidenceId() + " initNpcCommanders: Spawn could not be initialized: " + e.getMessage(), e);
  1137. }
  1138. }
  1139. private void initSpecialEnvoys()
  1140. {
  1141. _specialEnvoys.clear();
  1142. _envoyCastles.clear();
  1143. _availableCastles.clear();
  1144. try (Connection con = ConnectionFactory.getInstance().getConnection();
  1145. PreparedStatement ps = con.prepareStatement("SELECT id, npcId, x, y, z, heading, castleId FROM fort_spawnlist WHERE fortId = ? AND spawnType = ? ORDER BY id"))
  1146. {
  1147. ps.setInt(1, getResidenceId());
  1148. ps.setInt(2, 3);
  1149. try (ResultSet rs = ps.executeQuery())
  1150. {
  1151. while (rs.next())
  1152. {
  1153. final int castleId = rs.getInt("castleId");
  1154. final L2Spawn spawnDat = new L2Spawn(rs.getInt("npcId"));
  1155. spawnDat.setAmount(1);
  1156. spawnDat.setX(rs.getInt("x"));
  1157. spawnDat.setY(rs.getInt("y"));
  1158. spawnDat.setZ(rs.getInt("z"));
  1159. spawnDat.setHeading(rs.getInt("heading"));
  1160. spawnDat.setRespawnDelay(60);
  1161. _specialEnvoys.add(spawnDat);
  1162. _envoyCastles.put(spawnDat.getId(), castleId);
  1163. _availableCastles.add(castleId);
  1164. }
  1165. }
  1166. }
  1167. catch (Exception e)
  1168. {
  1169. // problem with initializing spawn, go to next one
  1170. _log.log(Level.WARNING, "Fort " + getResidenceId() + " initSpecialEnvoys: Spawn could not be initialized: " + e.getMessage(), e);
  1171. }
  1172. }
  1173. @Override
  1174. protected void initResidenceZone()
  1175. {
  1176. for (L2FortZone zone : ZoneManager.getInstance().getAllZones(L2FortZone.class))
  1177. {
  1178. if (zone.getResidenceId() == getResidenceId())
  1179. {
  1180. setResidenceZone(zone);
  1181. break;
  1182. }
  1183. }
  1184. }
  1185. }