Castle.java 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.gameserver.model.entity;
  16. import gnu.trove.map.hash.TIntIntHashMap;
  17. import java.sql.Connection;
  18. import java.sql.PreparedStatement;
  19. import java.sql.ResultSet;
  20. import java.util.ArrayList;
  21. import java.util.Calendar;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. import javolution.util.FastList;
  27. import javolution.util.FastMap;
  28. import com.l2jserver.Config;
  29. import com.l2jserver.L2DatabaseFactory;
  30. import com.l2jserver.gameserver.CastleUpdater;
  31. import com.l2jserver.gameserver.SevenSigns;
  32. import com.l2jserver.gameserver.ThreadPoolManager;
  33. import com.l2jserver.gameserver.datatables.ClanTable;
  34. import com.l2jserver.gameserver.datatables.DoorTable;
  35. import com.l2jserver.gameserver.datatables.SkillTable;
  36. import com.l2jserver.gameserver.datatables.SkillTreesData;
  37. import com.l2jserver.gameserver.instancemanager.CastleManager;
  38. import com.l2jserver.gameserver.instancemanager.CastleManorManager;
  39. import com.l2jserver.gameserver.instancemanager.CastleManorManager.CropProcure;
  40. import com.l2jserver.gameserver.instancemanager.CastleManorManager.SeedProduction;
  41. import com.l2jserver.gameserver.instancemanager.FortManager;
  42. import com.l2jserver.gameserver.instancemanager.TerritoryWarManager;
  43. import com.l2jserver.gameserver.instancemanager.TerritoryWarManager.Territory;
  44. import com.l2jserver.gameserver.instancemanager.ZoneManager;
  45. import com.l2jserver.gameserver.model.L2Clan;
  46. import com.l2jserver.gameserver.model.L2Manor;
  47. import com.l2jserver.gameserver.model.L2Object;
  48. import com.l2jserver.gameserver.model.L2Skill;
  49. import com.l2jserver.gameserver.model.L2SkillLearn;
  50. import com.l2jserver.gameserver.model.actor.instance.L2ArtefactInstance;
  51. import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
  52. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  53. import com.l2jserver.gameserver.model.itemcontainer.PcInventory;
  54. import com.l2jserver.gameserver.model.zone.type.L2CastleZone;
  55. import com.l2jserver.gameserver.model.zone.type.L2ResidenceTeleportZone;
  56. import com.l2jserver.gameserver.model.zone.type.L2SiegeZone;
  57. import com.l2jserver.gameserver.network.serverpackets.PlaySound;
  58. import com.l2jserver.gameserver.network.serverpackets.PledgeShowInfoUpdate;
  59. public class Castle
  60. {
  61. protected static final Logger _log = Logger.getLogger(Castle.class.getName());
  62. // =========================================================
  63. // Data Field
  64. private List<CropProcure> _procure = new ArrayList<CropProcure>();
  65. private List<SeedProduction> _production = new ArrayList<SeedProduction>();
  66. private List<CropProcure> _procureNext = new ArrayList<CropProcure>();
  67. private List<SeedProduction> _productionNext = new ArrayList<SeedProduction>();
  68. private boolean _isNextPeriodApproved = false;
  69. private static final String CASTLE_MANOR_DELETE_PRODUCTION = "DELETE FROM castle_manor_production WHERE castle_id=?;";
  70. private static final String CASTLE_MANOR_DELETE_PRODUCTION_PERIOD = "DELETE FROM castle_manor_production WHERE castle_id=? AND period=?;";
  71. private static final String CASTLE_MANOR_DELETE_PROCURE = "DELETE FROM castle_manor_procure WHERE castle_id=?;";
  72. private static final String CASTLE_MANOR_DELETE_PROCURE_PERIOD = "DELETE FROM castle_manor_procure WHERE castle_id=? AND period=?;";
  73. private static final String CASTLE_UPDATE_CROP = "UPDATE castle_manor_procure SET can_buy=? WHERE crop_id=? AND castle_id=? AND period=?";
  74. private static final String CASTLE_UPDATE_SEED = "UPDATE castle_manor_production SET can_produce=? WHERE seed_id=? AND castle_id=? AND period=?";
  75. // =========================================================
  76. // Data Field
  77. private int _castleId = 0;
  78. private List<L2DoorInstance> _doors = new FastList<L2DoorInstance>();
  79. private List<String> _doorDefault = new FastList<String>();
  80. private String _name = "";
  81. private int _ownerId = 0;
  82. private Siege _siege = null;
  83. private Calendar _siegeDate;
  84. private boolean _isTimeRegistrationOver = true; // true if Castle Lords set the time, or 24h is elapsed after the siege
  85. private Calendar _siegeTimeRegistrationEndDate; // last siege end date + 1 day
  86. private int _taxPercent = 0;
  87. private double _taxRate = 0;
  88. private long _treasury = 0;
  89. private boolean _showNpcCrest = false;
  90. private L2SiegeZone _zone = null;
  91. private L2CastleZone _castleZone = null;
  92. private L2ResidenceTeleportZone _teleZone;
  93. private L2Clan _formerOwner = null;
  94. private List<L2ArtefactInstance> _artefacts = new ArrayList<L2ArtefactInstance>(1);
  95. private TIntIntHashMap _engrave = new TIntIntHashMap(1);
  96. private Map<Integer, CastleFunction> _function;
  97. private FastList<L2Skill> _residentialSkills = new FastList<L2Skill>();
  98. private int _bloodAlliance = 0;
  99. /** Castle Functions */
  100. public static final int FUNC_TELEPORT = 1;
  101. public static final int FUNC_RESTORE_HP = 2;
  102. public static final int FUNC_RESTORE_MP = 3;
  103. public static final int FUNC_RESTORE_EXP = 4;
  104. public static final int FUNC_SUPPORT = 5;
  105. public class CastleFunction
  106. {
  107. private int _type;
  108. private int _lvl;
  109. protected int _fee;
  110. protected int _tempFee;
  111. private long _rate;
  112. private long _endDate;
  113. protected boolean _inDebt;
  114. public boolean _cwh;
  115. public CastleFunction(int type, int lvl, int lease, int tempLease, long rate, long time, boolean cwh)
  116. {
  117. _type = type;
  118. _lvl = lvl;
  119. _fee = lease;
  120. _tempFee = tempLease;
  121. _rate = rate;
  122. _endDate = time;
  123. initializeTask(cwh);
  124. }
  125. public int getType()
  126. {
  127. return _type;
  128. }
  129. public int getLvl()
  130. {
  131. return _lvl;
  132. }
  133. public int getLease()
  134. {
  135. return _fee;
  136. }
  137. public long getRate()
  138. {
  139. return _rate;
  140. }
  141. public long getEndTime()
  142. {
  143. return _endDate;
  144. }
  145. public void setLvl(int lvl)
  146. {
  147. _lvl = lvl;
  148. }
  149. public void setLease(int lease)
  150. {
  151. _fee = lease;
  152. }
  153. public void setEndTime(long time)
  154. {
  155. _endDate = time;
  156. }
  157. private void initializeTask(boolean cwh)
  158. {
  159. if (getOwnerId() <= 0)
  160. return;
  161. long currentTime = System.currentTimeMillis();
  162. if (_endDate > currentTime)
  163. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), _endDate - currentTime);
  164. else
  165. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), 0);
  166. }
  167. private class FunctionTask implements Runnable
  168. {
  169. public FunctionTask(boolean cwh)
  170. {
  171. _cwh = cwh;
  172. }
  173. @Override
  174. public void run()
  175. {
  176. try
  177. {
  178. if (getOwnerId() <= 0)
  179. return;
  180. if (ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().getAdena() >= _fee || !_cwh)
  181. {
  182. int fee = _fee;
  183. if (getEndTime() == -1)
  184. fee = _tempFee;
  185. setEndTime(System.currentTimeMillis() + getRate());
  186. dbSave();
  187. if (_cwh)
  188. {
  189. ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().destroyItemByItemId("CS_function_fee", PcInventory.ADENA_ID, fee, null, null);
  190. if (Config.DEBUG)
  191. _log.warning("deducted " + fee + " adena from " + getName() + " owner's cwh for function id : " + getType());
  192. }
  193. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(true), getRate());
  194. }
  195. else
  196. removeFunction(getType());
  197. }
  198. catch (Exception e)
  199. {
  200. _log.log(Level.SEVERE, "", e);
  201. }
  202. }
  203. }
  204. public void dbSave()
  205. {
  206. Connection con = null;
  207. try
  208. {
  209. PreparedStatement statement;
  210. con = L2DatabaseFactory.getInstance().getConnection();
  211. statement = con.prepareStatement("REPLACE INTO castle_functions (castle_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)");
  212. statement.setInt(1, getCastleId());
  213. statement.setInt(2, getType());
  214. statement.setInt(3, getLvl());
  215. statement.setInt(4, getLease());
  216. statement.setLong(5, getRate());
  217. statement.setLong(6, getEndTime());
  218. statement.execute();
  219. statement.close();
  220. }
  221. catch (Exception e)
  222. {
  223. _log.log(Level.SEVERE, "Exception: Castle.updateFunctions(int type, int lvl, int lease, long rate, long time, boolean addNew): "
  224. + e.getMessage(), e);
  225. }
  226. finally
  227. {
  228. L2DatabaseFactory.close(con);
  229. }
  230. }
  231. }
  232. // =========================================================
  233. // Constructor
  234. public Castle(int castleId)
  235. {
  236. _castleId = castleId;
  237. /*if (_castleId == 7 || castleId == 9) // Goddard and Schuttgart
  238. _nbArtifact = 2;*/
  239. load();
  240. loadDoor();
  241. _function = new FastMap<Integer, CastleFunction>();
  242. final FastList<L2SkillLearn> residentialSkills = SkillTreesData.getInstance().getAvailableResidentialSkills(castleId);
  243. for (L2SkillLearn s : residentialSkills)
  244. {
  245. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  246. if (sk != null)
  247. {
  248. _residentialSkills.add(sk);
  249. }
  250. else
  251. {
  252. _log.warning("Castle Id: " + castleId + " has a null residential skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  253. }
  254. }
  255. if (getOwnerId() != 0)
  256. {
  257. loadFunctions();
  258. }
  259. }
  260. // =========================================================
  261. // Method - Public
  262. /**
  263. * Return function with id
  264. * @param type
  265. * @return
  266. */
  267. public CastleFunction getFunction(int type)
  268. {
  269. if (_function.get(type) != null)
  270. return _function.get(type);
  271. return null;
  272. }
  273. public synchronized void engrave(L2Clan clan, L2Object target)
  274. {
  275. if (!_artefacts.contains(target))
  276. return;
  277. _engrave.put(target.getObjectId(), clan.getClanId());
  278. if (_engrave.size() == _artefacts.size())
  279. {
  280. for (L2ArtefactInstance art : _artefacts)
  281. {
  282. if (_engrave.get(art.getObjectId()) != clan.getClanId())
  283. return;
  284. }
  285. _engrave.clear();
  286. setOwner(clan);
  287. }
  288. }
  289. // This method add to the treasury
  290. /**
  291. * Add amount to castle instance's treasury (warehouse).
  292. * @param amount
  293. */
  294. public void addToTreasury(long amount)
  295. {
  296. // check if owned
  297. if (getOwnerId() <= 0)
  298. {
  299. return;
  300. }
  301. if (_name.equalsIgnoreCase("Schuttgart") || _name.equalsIgnoreCase("Goddard"))
  302. {
  303. Castle rune = CastleManager.getInstance().getCastle("rune");
  304. if (rune != null)
  305. {
  306. long runeTax = (long) (amount * rune.getTaxRate());
  307. if (rune.getOwnerId() > 0)
  308. rune.addToTreasury(runeTax);
  309. amount -= runeTax;
  310. }
  311. }
  312. if (!_name.equalsIgnoreCase("aden") && !_name.equalsIgnoreCase("Rune") && !_name.equalsIgnoreCase("Schuttgart") && !_name.equalsIgnoreCase("Goddard")) // If current castle instance is not Aden, Rune, Goddard or Schuttgart.
  313. {
  314. Castle aden = CastleManager.getInstance().getCastle("aden");
  315. if (aden != null)
  316. {
  317. long adenTax = (long) (amount * aden.getTaxRate()); // Find out what Aden gets from the current castle instance's income
  318. if (aden.getOwnerId() > 0)
  319. aden.addToTreasury(adenTax); // Only bother to really add the tax to the treasury if not npc owned
  320. amount -= adenTax; // Subtract Aden's income from current castle instance's income
  321. }
  322. }
  323. addToTreasuryNoTax(amount);
  324. }
  325. /**
  326. * Add amount to castle instance's treasury (warehouse), no tax paying.
  327. * @param amount
  328. * @return
  329. */
  330. public boolean addToTreasuryNoTax(long amount)
  331. {
  332. if (getOwnerId() <= 0)
  333. return false;
  334. if (amount < 0)
  335. {
  336. amount *= -1;
  337. if (_treasury < amount)
  338. return false;
  339. _treasury -= amount;
  340. }
  341. else
  342. {
  343. if (_treasury + amount > PcInventory.MAX_ADENA) // TODO is this valid after gracia final?
  344. _treasury = PcInventory.MAX_ADENA;
  345. else
  346. _treasury += amount;
  347. }
  348. Connection con = null;
  349. try
  350. {
  351. con = L2DatabaseFactory.getInstance().getConnection();
  352. PreparedStatement statement = con.prepareStatement("UPDATE castle SET treasury = ? WHERE id = ?");
  353. statement.setLong(1, getTreasury());
  354. statement.setInt(2, getCastleId());
  355. statement.execute();
  356. statement.close();
  357. }
  358. catch (Exception e)
  359. {
  360. }
  361. finally
  362. {
  363. L2DatabaseFactory.close(con);
  364. }
  365. return true;
  366. }
  367. /**
  368. * Move non clan members off castle area and to nearest town.<BR><BR>
  369. */
  370. public void banishForeigners()
  371. {
  372. getCastleZone().banishForeigners(getOwnerId());
  373. }
  374. /**
  375. * Return true if object is inside the zone
  376. * @param x
  377. * @param y
  378. * @param z
  379. * @return
  380. */
  381. public boolean checkIfInZone(int x, int y, int z)
  382. {
  383. return getZone().isInsideZone(x, y, z);
  384. }
  385. public L2SiegeZone getZone()
  386. {
  387. if (_zone == null)
  388. {
  389. for (L2SiegeZone zone : ZoneManager.getInstance().getAllZones(L2SiegeZone.class))
  390. {
  391. if (zone.getSiegeObjectId() == getCastleId())
  392. {
  393. _zone = zone;
  394. break;
  395. }
  396. }
  397. }
  398. return _zone;
  399. }
  400. public L2CastleZone getCastleZone()
  401. {
  402. if (_castleZone == null)
  403. {
  404. for (L2CastleZone zone : ZoneManager.getInstance().getAllZones(L2CastleZone.class))
  405. {
  406. if (zone.getCastleId() == getCastleId())
  407. {
  408. _castleZone = zone;
  409. break;
  410. }
  411. }
  412. }
  413. return _castleZone;
  414. }
  415. public L2ResidenceTeleportZone getTeleZone()
  416. {
  417. if (_teleZone == null)
  418. {
  419. for (L2ResidenceTeleportZone zone : ZoneManager.getInstance().getAllZones(L2ResidenceTeleportZone.class))
  420. {
  421. if (zone.getResidenceId() == getCastleId())
  422. {
  423. _teleZone = zone;
  424. break;
  425. }
  426. }
  427. }
  428. return _teleZone;
  429. }
  430. public void oustAllPlayers()
  431. {
  432. getTeleZone().oustAllPlayers();
  433. }
  434. /**
  435. * Get the objects distance to this castle
  436. * @param obj
  437. * @return
  438. */
  439. public double getDistance(L2Object obj)
  440. {
  441. return getZone().getDistanceToZone(obj);
  442. }
  443. public void closeDoor(L2PcInstance activeChar, int doorId)
  444. {
  445. openCloseDoor(activeChar, doorId, false);
  446. }
  447. public void openDoor(L2PcInstance activeChar, int doorId)
  448. {
  449. openCloseDoor(activeChar, doorId, true);
  450. }
  451. public void openCloseDoor(L2PcInstance activeChar, int doorId, boolean open)
  452. {
  453. if (activeChar.getClanId() != getOwnerId())
  454. return;
  455. L2DoorInstance door = getDoor(doorId);
  456. if (door != null)
  457. {
  458. if (open)
  459. door.openMe();
  460. else
  461. door.closeMe();
  462. }
  463. }
  464. // This method is used to begin removing all castle upgrades
  465. public void removeUpgrade()
  466. {
  467. removeDoorUpgrade();
  468. for (Map.Entry<Integer, CastleFunction> fc : _function.entrySet())
  469. removeFunction(fc.getKey());
  470. _function.clear();
  471. }
  472. // This method updates the castle tax rate
  473. public void setOwner(L2Clan clan)
  474. {
  475. // Remove old owner
  476. if (getOwnerId() > 0 && (clan == null || clan.getClanId() != getOwnerId()))
  477. {
  478. L2Clan oldOwner = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
  479. if (oldOwner != null)
  480. {
  481. if (_formerOwner == null)
  482. {
  483. _formerOwner = oldOwner;
  484. if (Config.REMOVE_CASTLE_CIRCLETS)
  485. {
  486. CastleManager.getInstance().removeCirclet(_formerOwner, getCastleId());
  487. }
  488. }
  489. try
  490. {
  491. L2PcInstance oldleader = oldOwner.getLeader().getPlayerInstance();
  492. if (oldleader != null)
  493. {
  494. if (oldleader.getMountType() == 2)
  495. oldleader.dismount();
  496. }
  497. }
  498. catch (Exception e)
  499. {
  500. _log.log(Level.WARNING, "Exception in setOwner: " + e.getMessage(), e);
  501. }
  502. oldOwner.setHasCastle(0); // Unset has castle flag for old owner
  503. for (L2PcInstance member : oldOwner.getOnlineMembers(0))
  504. {
  505. removeResidentialSkills(member);
  506. member.sendSkillList();
  507. }
  508. }
  509. }
  510. updateOwnerInDB(clan); // Update in database
  511. setShowNpcCrest(false);
  512. // if clan have fortress, remove it
  513. if (clan.getHasFort() > 0)
  514. FortManager.getInstance().getFortByOwner(clan).removeOwner(true);
  515. if (getSiege().getIsInProgress()) // If siege in progress
  516. getSiege().midVictory(); // Mid victory phase of siege
  517. TerritoryWarManager.getInstance().getTerritory(_castleId).setOwnerClan(clan);
  518. for (L2PcInstance member : clan.getOnlineMembers(0))
  519. {
  520. giveResidentialSkills(member);
  521. member.sendSkillList();
  522. }
  523. }
  524. public void removeOwner(L2Clan clan)
  525. {
  526. if (clan != null)
  527. {
  528. _formerOwner = clan;
  529. if (Config.REMOVE_CASTLE_CIRCLETS)
  530. {
  531. CastleManager.getInstance().removeCirclet(_formerOwner, getCastleId());
  532. }
  533. for (L2PcInstance member : clan.getOnlineMembers(0))
  534. {
  535. removeResidentialSkills(member);
  536. member.sendSkillList();
  537. }
  538. clan.setHasCastle(0);
  539. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  540. }
  541. updateOwnerInDB(null);
  542. if (getSiege().getIsInProgress())
  543. getSiege().midVictory();
  544. for (Map.Entry<Integer, CastleFunction> fc : _function.entrySet())
  545. removeFunction(fc.getKey());
  546. _function.clear();
  547. }
  548. // This method updates the castle tax rate
  549. public void setTaxPercent(L2PcInstance activeChar, int taxPercent)
  550. {
  551. int maxTax;
  552. switch (SevenSigns.getInstance().getSealOwner(SevenSigns.SEAL_STRIFE))
  553. {
  554. case SevenSigns.CABAL_DAWN:
  555. maxTax = 25;
  556. break;
  557. case SevenSigns.CABAL_DUSK:
  558. maxTax = 5;
  559. break;
  560. default: // no owner
  561. maxTax = 15;
  562. }
  563. if (taxPercent < 0 || taxPercent > maxTax)
  564. {
  565. activeChar.sendMessage("Tax value must be between 0 and " + maxTax + ".");
  566. return;
  567. }
  568. setTaxPercent(taxPercent);
  569. activeChar.sendMessage(getName() + " castle tax changed to " + taxPercent + "%.");
  570. }
  571. public void setTaxPercent(int taxPercent)
  572. {
  573. _taxPercent = taxPercent;
  574. _taxRate = _taxPercent / 100.0;
  575. Connection con = null;
  576. try
  577. {
  578. con = L2DatabaseFactory.getInstance().getConnection();
  579. PreparedStatement statement = con.prepareStatement("Update castle set taxPercent = ? where id = ?");
  580. statement.setInt(1, taxPercent);
  581. statement.setInt(2, getCastleId());
  582. statement.execute();
  583. statement.close();
  584. }
  585. catch (Exception e)
  586. {
  587. }
  588. finally
  589. {
  590. L2DatabaseFactory.close(con);
  591. }
  592. }
  593. /**
  594. * Respawn all doors on castle grounds<BR><BR>
  595. */
  596. public void spawnDoor()
  597. {
  598. spawnDoor(false);
  599. }
  600. /**
  601. * Respawn all doors on castle grounds<BR><BR>
  602. * @param isDoorWeak
  603. */
  604. public void spawnDoor(boolean isDoorWeak)
  605. {
  606. for (int i = 0; i < getDoors().size(); i++)
  607. {
  608. L2DoorInstance door = getDoors().get(i);
  609. if (door.getCurrentHp() <= 0)
  610. {
  611. door.decayMe(); // Kill current if not killed already
  612. door = DoorTable.parseList(_doorDefault.get(i), false);
  613. DoorTable.getInstance().putDoor(door); //Readd the new door to the DoorTable By Erb
  614. if (isDoorWeak)
  615. door.setCurrentHp(door.getMaxHp() / 2);
  616. door.spawnMe(door.getX(), door.getY(), door.getZ());
  617. getDoors().set(i, door);
  618. }
  619. else if (door.getOpen())
  620. door.closeMe();
  621. }
  622. loadDoorUpgrade(); // Check for any upgrade the doors may have
  623. }
  624. // This method upgrade door
  625. public void upgradeDoor(int doorId, int hp, int pDef, int mDef)
  626. {
  627. L2DoorInstance door = getDoor(doorId);
  628. if (door == null)
  629. return;
  630. door.setCurrentHp(door.getMaxHp() + hp);
  631. saveDoorUpgrade(doorId, hp, pDef, mDef);
  632. }
  633. // =========================================================
  634. // Method - Private
  635. // This method loads castle
  636. private void load()
  637. {
  638. Connection con = null;
  639. try
  640. {
  641. PreparedStatement statement;
  642. ResultSet rs;
  643. con = L2DatabaseFactory.getInstance().getConnection();
  644. statement = con.prepareStatement("Select * from castle where id = ?");
  645. statement.setInt(1, getCastleId());
  646. rs = statement.executeQuery();
  647. while (rs.next())
  648. {
  649. _name = rs.getString("name");
  650. //_OwnerId = rs.getInt("ownerId");
  651. _siegeDate = Calendar.getInstance();
  652. _siegeDate.setTimeInMillis(rs.getLong("siegeDate"));
  653. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  654. _siegeTimeRegistrationEndDate.setTimeInMillis(rs.getLong("regTimeEnd"));
  655. _isTimeRegistrationOver = rs.getBoolean("regTimeOver");
  656. _taxPercent = rs.getInt("taxPercent");
  657. _treasury = rs.getLong("treasury");
  658. _showNpcCrest = rs.getBoolean("showNpcCrest");
  659. _bloodAlliance = rs.getInt("bloodAlliance");
  660. }
  661. rs.close();
  662. statement.close();
  663. _taxRate = _taxPercent / 100.0;
  664. statement = con.prepareStatement("Select clan_id from clan_data where hasCastle = ?");
  665. statement.setInt(1, getCastleId());
  666. rs = statement.executeQuery();
  667. while (rs.next())
  668. {
  669. _ownerId = rs.getInt("clan_id");
  670. }
  671. if (getOwnerId() > 0)
  672. {
  673. L2Clan clan = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
  674. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  675. }
  676. rs.close();
  677. statement.close();
  678. }
  679. catch (Exception e)
  680. {
  681. _log.log(Level.WARNING, "Exception: loadCastleData(): " + e.getMessage(), e);
  682. }
  683. finally
  684. {
  685. L2DatabaseFactory.close(con);
  686. }
  687. }
  688. /** Load All Functions */
  689. private void loadFunctions()
  690. {
  691. Connection con = null;
  692. try
  693. {
  694. PreparedStatement statement;
  695. ResultSet rs;
  696. con = L2DatabaseFactory.getInstance().getConnection();
  697. statement = con.prepareStatement("Select * from castle_functions where castle_id = ?");
  698. statement.setInt(1, getCastleId());
  699. rs = statement.executeQuery();
  700. while (rs.next())
  701. {
  702. _function.put(rs.getInt("type"), new CastleFunction(rs.getInt("type"), rs.getInt("lvl"), rs.getInt("lease"), 0, rs.getLong("rate"), rs.getLong("endTime"), true));
  703. }
  704. rs.close();
  705. statement.close();
  706. }
  707. catch (Exception e)
  708. {
  709. _log.log(Level.SEVERE, "Exception: Castle.loadFunctions(): " + e.getMessage(), e);
  710. }
  711. finally
  712. {
  713. L2DatabaseFactory.close(con);
  714. }
  715. }
  716. /**
  717. * Remove function In List and in DB
  718. * @param functionType
  719. */
  720. public void removeFunction(int functionType)
  721. {
  722. _function.remove(functionType);
  723. Connection con = null;
  724. try
  725. {
  726. PreparedStatement statement;
  727. con = L2DatabaseFactory.getInstance().getConnection();
  728. statement = con.prepareStatement("DELETE FROM castle_functions WHERE castle_id=? AND type=?");
  729. statement.setInt(1, getCastleId());
  730. statement.setInt(2, functionType);
  731. statement.execute();
  732. statement.close();
  733. }
  734. catch (Exception e)
  735. {
  736. _log.log(Level.SEVERE, "Exception: Castle.removeFunctions(int functionType): " + e.getMessage(), e);
  737. }
  738. finally
  739. {
  740. L2DatabaseFactory.close(con);
  741. }
  742. }
  743. public boolean updateFunctions(L2PcInstance player, int type, int lvl, int lease, long rate, boolean addNew)
  744. {
  745. if (player == null)
  746. return false;
  747. if (Config.DEBUG)
  748. _log.warning("Called Castle.updateFunctions(int type, int lvl, int lease, long rate, boolean addNew) Owner : " + getOwnerId());
  749. if (lease > 0)
  750. if (!player.destroyItemByItemId("Consume", PcInventory.ADENA_ID, lease, null, true))
  751. return false;
  752. if (addNew)
  753. {
  754. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, 0, false));
  755. }
  756. else
  757. {
  758. if (lvl == 0 && lease == 0)
  759. removeFunction(type);
  760. else
  761. {
  762. int diffLease = lease - _function.get(type).getLease();
  763. if (Config.DEBUG)
  764. _log.warning("Called Castle.updateFunctions diffLease : " + diffLease);
  765. if (diffLease > 0)
  766. {
  767. _function.remove(type);
  768. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, -1, false));
  769. }
  770. else
  771. {
  772. _function.get(type).setLease(lease);
  773. _function.get(type).setLvl(lvl);
  774. _function.get(type).dbSave();
  775. }
  776. }
  777. }
  778. return true;
  779. }
  780. public void activateInstance()
  781. {
  782. for (final L2DoorInstance door : _doors)
  783. {
  784. door.spawnMe(door.getX(), door.getY(), door.getZ());
  785. }
  786. }
  787. // This method loads castle door data from database
  788. private void loadDoor()
  789. {
  790. Connection con = null;
  791. try
  792. {
  793. con = L2DatabaseFactory.getInstance().getConnection();
  794. PreparedStatement statement = con.prepareStatement("Select * from castle_door where castleId = ?");
  795. statement.setInt(1, getCastleId());
  796. ResultSet rs = statement.executeQuery();
  797. while (rs.next())
  798. {
  799. // Create list of the door default for use when respawning dead doors
  800. _doorDefault.add(rs.getString("name") + ";" + rs.getInt("id") + ";" + rs.getInt("x") + ";" + rs.getInt("y") + ";"
  801. + rs.getInt("z") + ";" + rs.getInt("range_xmin") + ";" + rs.getInt("range_ymin") + ";" + rs.getInt("range_zmin")
  802. + ";" + rs.getInt("range_xmax") + ";" + rs.getInt("range_ymax") + ";" + rs.getInt("range_zmax") + ";"
  803. + rs.getInt("hp") + ";" + rs.getInt("pDef") + ";" + rs.getInt("mDef") + ";0");
  804. L2DoorInstance door = DoorTable.parseList(_doorDefault.get(_doorDefault.size() - 1), false);
  805. door.setIsWall(rs.getBoolean("isWall"));
  806. _doors.add(door);
  807. DoorTable.getInstance().putDoor(door);
  808. }
  809. rs.close();
  810. statement.close();
  811. }
  812. catch (Exception e)
  813. {
  814. _log.log(Level.WARNING, "Exception: loadCastleDoor(): " + e.getMessage(),e );
  815. }
  816. finally
  817. {
  818. L2DatabaseFactory.close(con);
  819. }
  820. }
  821. // This method loads castle door upgrade data from database
  822. private void loadDoorUpgrade()
  823. {
  824. Connection con = null;
  825. try
  826. {
  827. con = L2DatabaseFactory.getInstance().getConnection();
  828. PreparedStatement statement = con.prepareStatement("Select * from castle_doorupgrade where doorId in (Select Id from castle_door where castleId = ?)");
  829. statement.setInt(1, getCastleId());
  830. ResultSet rs = statement.executeQuery();
  831. while (rs.next())
  832. {
  833. upgradeDoor(rs.getInt("id"), rs.getInt("hp"), rs.getInt("pDef"), rs.getInt("mDef"));
  834. }
  835. rs.close();
  836. statement.close();
  837. }
  838. catch (Exception e)
  839. {
  840. _log.log(Level.WARNING, "Exception: loadCastleDoorUpgrade(): " + e.getMessage(), e);
  841. }
  842. finally
  843. {
  844. L2DatabaseFactory.close(con);
  845. }
  846. }
  847. private void removeDoorUpgrade()
  848. {
  849. Connection con = null;
  850. try
  851. {
  852. con = L2DatabaseFactory.getInstance().getConnection();
  853. PreparedStatement statement = con.prepareStatement("delete from castle_doorupgrade where doorId in (select id from castle_door where castleId=?)");
  854. statement.setInt(1, getCastleId());
  855. statement.execute();
  856. statement.close();
  857. }
  858. catch (Exception e)
  859. {
  860. _log.log(Level.WARNING, "Exception: removeDoorUpgrade(): " + e.getMessage(), e);
  861. }
  862. finally
  863. {
  864. L2DatabaseFactory.close(con);
  865. }
  866. }
  867. private void saveDoorUpgrade(int doorId, int hp, int pDef, int mDef)
  868. {
  869. Connection con = null;
  870. try
  871. {
  872. con = L2DatabaseFactory.getInstance().getConnection();
  873. PreparedStatement statement = con.prepareStatement("INSERT INTO castle_doorupgrade (doorId, hp, pDef, mDef) values (?,?,?,?)");
  874. statement.setInt(1, doorId);
  875. statement.setInt(2, hp);
  876. statement.setInt(3, pDef);
  877. statement.setInt(4, mDef);
  878. statement.execute();
  879. statement.close();
  880. }
  881. catch (Exception e)
  882. {
  883. _log.log(Level.WARNING, "Exception: saveDoorUpgrade(int doorId, int hp, int pDef, int mDef): " + e.getMessage(), e);
  884. }
  885. finally
  886. {
  887. L2DatabaseFactory.close(con);
  888. }
  889. }
  890. private void updateOwnerInDB(L2Clan clan)
  891. {
  892. if (clan != null)
  893. _ownerId = clan.getClanId(); // Update owner id property
  894. else
  895. {
  896. _ownerId = 0; // Remove owner
  897. resetManor();
  898. }
  899. Connection con = null;
  900. try
  901. {
  902. con = L2DatabaseFactory.getInstance().getConnection();
  903. PreparedStatement statement;
  904. // ============================================================================
  905. // NEED TO REMOVE HAS CASTLE FLAG FROM CLAN_DATA
  906. // SHOULD BE CHECKED FROM CASTLE TABLE
  907. statement = con.prepareStatement("UPDATE clan_data SET hasCastle=0 WHERE hasCastle=?");
  908. statement.setInt(1, getCastleId());
  909. statement.execute();
  910. statement.close();
  911. statement = con.prepareStatement("UPDATE clan_data SET hasCastle=? WHERE clan_id=?");
  912. statement.setInt(1, getCastleId());
  913. statement.setInt(2, getOwnerId());
  914. statement.execute();
  915. statement.close();
  916. // ============================================================================
  917. // Announce to clan memebers
  918. if (clan != null)
  919. {
  920. clan.setHasCastle(getCastleId()); // Set has castle flag for new owner
  921. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  922. clan.broadcastToOnlineMembers(new PlaySound(1, "Siege_Victory", 0, 0, 0, 0, 0));
  923. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  924. }
  925. }
  926. catch (Exception e)
  927. {
  928. _log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
  929. }
  930. finally
  931. {
  932. L2DatabaseFactory.close(con);
  933. }
  934. }
  935. // =========================================================
  936. // Property
  937. public final int getCastleId()
  938. {
  939. return _castleId;
  940. }
  941. public final L2DoorInstance getDoor(int doorId)
  942. {
  943. if (doorId <= 0)
  944. return null;
  945. for (L2DoorInstance door : getDoors())
  946. {
  947. if (door.getDoorId() == doorId)
  948. return door;
  949. }
  950. return null;
  951. }
  952. public final List<L2DoorInstance> getDoors()
  953. {
  954. return _doors;
  955. }
  956. public final String getName()
  957. {
  958. return _name;
  959. }
  960. public final int getOwnerId()
  961. {
  962. return _ownerId;
  963. }
  964. public final Siege getSiege()
  965. {
  966. if (_siege == null)
  967. _siege = new Siege(new Castle[] { this });
  968. return _siege;
  969. }
  970. public final Calendar getSiegeDate()
  971. {
  972. return _siegeDate;
  973. }
  974. public boolean getIsTimeRegistrationOver()
  975. {
  976. return _isTimeRegistrationOver;
  977. }
  978. public void setIsTimeRegistrationOver(boolean val)
  979. {
  980. _isTimeRegistrationOver = val;
  981. }
  982. public Calendar getTimeRegistrationOverDate()
  983. {
  984. if (_siegeTimeRegistrationEndDate == null)
  985. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  986. return _siegeTimeRegistrationEndDate;
  987. }
  988. public final int getTaxPercent()
  989. {
  990. return _taxPercent;
  991. }
  992. public final double getTaxRate()
  993. {
  994. return _taxRate;
  995. }
  996. public final long getTreasury()
  997. {
  998. return _treasury;
  999. }
  1000. public final boolean getShowNpcCrest()
  1001. {
  1002. return _showNpcCrest;
  1003. }
  1004. public final void setShowNpcCrest(boolean showNpcCrest)
  1005. {
  1006. if (_showNpcCrest != showNpcCrest)
  1007. {
  1008. _showNpcCrest = showNpcCrest;
  1009. updateShowNpcCrest();
  1010. }
  1011. }
  1012. public List<SeedProduction> getSeedProduction(int period)
  1013. {
  1014. return (period == CastleManorManager.PERIOD_CURRENT ? _production : _productionNext);
  1015. }
  1016. public List<CropProcure> getCropProcure(int period)
  1017. {
  1018. return (period == CastleManorManager.PERIOD_CURRENT ? _procure : _procureNext);
  1019. }
  1020. public void setSeedProduction(List<SeedProduction> seed, int period)
  1021. {
  1022. if (period == CastleManorManager.PERIOD_CURRENT)
  1023. _production = seed;
  1024. else
  1025. _productionNext = seed;
  1026. }
  1027. public void setCropProcure(List<CropProcure> crop, int period)
  1028. {
  1029. if (period == CastleManorManager.PERIOD_CURRENT)
  1030. _procure = crop;
  1031. else
  1032. _procureNext = crop;
  1033. }
  1034. public SeedProduction getSeed(int seedId, int period)
  1035. {
  1036. for (SeedProduction seed : getSeedProduction(period))
  1037. {
  1038. if (seed.getId() == seedId)
  1039. {
  1040. return seed;
  1041. }
  1042. }
  1043. return null;
  1044. }
  1045. public CropProcure getCrop(int cropId, int period)
  1046. {
  1047. for (CropProcure crop : getCropProcure(period))
  1048. {
  1049. if (crop.getId() == cropId)
  1050. {
  1051. return crop;
  1052. }
  1053. }
  1054. return null;
  1055. }
  1056. public long getManorCost(int period)
  1057. {
  1058. List<CropProcure> procure;
  1059. List<SeedProduction> production;
  1060. if (period == CastleManorManager.PERIOD_CURRENT)
  1061. {
  1062. procure = _procure;
  1063. production = _production;
  1064. }
  1065. else
  1066. {
  1067. procure = _procureNext;
  1068. production = _productionNext;
  1069. }
  1070. long total = 0;
  1071. if (production != null)
  1072. {
  1073. for (SeedProduction seed : production)
  1074. {
  1075. total += L2Manor.getInstance().getSeedBuyPrice(seed.getId()) * seed.getStartProduce();
  1076. }
  1077. }
  1078. if (procure != null)
  1079. {
  1080. for (CropProcure crop : procure)
  1081. {
  1082. total += crop.getPrice() * crop.getStartAmount();
  1083. }
  1084. }
  1085. return total;
  1086. }
  1087. //save manor production data
  1088. public void saveSeedData()
  1089. {
  1090. Connection con = null;
  1091. PreparedStatement statement;
  1092. try
  1093. {
  1094. con = L2DatabaseFactory.getInstance().getConnection();
  1095. statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION);
  1096. statement.setInt(1, getCastleId());
  1097. statement.execute();
  1098. statement.close();
  1099. if (_production != null)
  1100. {
  1101. int count = 0;
  1102. StringBuilder query = new StringBuilder();
  1103. query.append("INSERT INTO castle_manor_production VALUES ");
  1104. String values[] = new String[_production.size()];
  1105. for (SeedProduction s : _production)
  1106. {
  1107. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + ","
  1108. + s.getPrice() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1109. }
  1110. if (values.length > 0)
  1111. {
  1112. query.append(values[0]);
  1113. for (int i = 1; i < values.length; i++)
  1114. {
  1115. query.append(",");
  1116. query.append(values[i]);
  1117. }
  1118. statement = con.prepareStatement(query.toString());
  1119. statement.execute();
  1120. statement.close();
  1121. }
  1122. }
  1123. if (_productionNext != null)
  1124. {
  1125. int count = 0;
  1126. String query = "INSERT INTO castle_manor_production VALUES ";
  1127. String values[] = new String[_productionNext.size()];
  1128. for (SeedProduction s : _productionNext)
  1129. {
  1130. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + ","
  1131. + s.getPrice() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1132. }
  1133. if (values.length > 0)
  1134. {
  1135. query += values[0];
  1136. for (int i = 1; i < values.length; i++)
  1137. {
  1138. query += "," + values[i];
  1139. }
  1140. statement = con.prepareStatement(query);
  1141. statement.execute();
  1142. statement.close();
  1143. }
  1144. }
  1145. }
  1146. catch (Exception e)
  1147. {
  1148. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1149. }
  1150. finally
  1151. {
  1152. L2DatabaseFactory.close(con);
  1153. }
  1154. }
  1155. //save manor production data for specified period
  1156. public void saveSeedData(int period)
  1157. {
  1158. Connection con = null;
  1159. PreparedStatement statement;
  1160. try
  1161. {
  1162. con = L2DatabaseFactory.getInstance().getConnection();
  1163. statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION_PERIOD);
  1164. statement.setInt(1, getCastleId());
  1165. statement.setInt(2, period);
  1166. statement.execute();
  1167. statement.close();
  1168. List<SeedProduction> prod = null;
  1169. prod = getSeedProduction(period);
  1170. if (prod != null)
  1171. {
  1172. int count = 0;
  1173. StringBuilder query = new StringBuilder();
  1174. query.append("INSERT INTO castle_manor_production VALUES ");
  1175. String values[] = new String[prod.size()];
  1176. for (SeedProduction s : prod)
  1177. {
  1178. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + ","
  1179. + s.getPrice() + "," + period + ")";
  1180. }
  1181. if (values.length > 0)
  1182. {
  1183. query.append(values[0]);
  1184. for (int i = 1; i < values.length; i++)
  1185. {
  1186. query.append(",")
  1187. .append(values[i]);
  1188. }
  1189. statement = con.prepareStatement(query.toString());
  1190. statement.execute();
  1191. statement.close();
  1192. }
  1193. }
  1194. }
  1195. catch (Exception e)
  1196. {
  1197. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1198. }
  1199. finally
  1200. {
  1201. L2DatabaseFactory.close(con);
  1202. }
  1203. }
  1204. //save crop procure data
  1205. public void saveCropData()
  1206. {
  1207. Connection con = null;
  1208. PreparedStatement statement;
  1209. try
  1210. {
  1211. con = L2DatabaseFactory.getInstance().getConnection();
  1212. statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE);
  1213. statement.setInt(1, getCastleId());
  1214. statement.execute();
  1215. statement.close();
  1216. if (_procure != null && _procure.size() > 0)
  1217. {
  1218. int count = 0;
  1219. StringBuilder query = new StringBuilder();
  1220. query.append("INSERT INTO castle_manor_procure VALUES ");
  1221. String values[] = new String[_procure.size()];
  1222. for (CropProcure cp : _procure)
  1223. {
  1224. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + ","
  1225. + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1226. }
  1227. if (values.length > 0)
  1228. {
  1229. query.append(values[0]);
  1230. for (int i = 1; i < values.length; i++)
  1231. {
  1232. query.append(",");
  1233. query.append(values[i]);
  1234. }
  1235. statement = con.prepareStatement(query.toString());
  1236. statement.execute();
  1237. statement.close();
  1238. }
  1239. }
  1240. if (_procureNext != null && _procureNext.size() > 0)
  1241. {
  1242. int count = 0;
  1243. String query = "INSERT INTO castle_manor_procure VALUES ";
  1244. String values[] = new String[_procureNext.size()];
  1245. for (CropProcure cp : _procureNext)
  1246. {
  1247. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + ","
  1248. + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1249. }
  1250. if (values.length > 0)
  1251. {
  1252. query += values[0];
  1253. for (int i = 1; i < values.length; i++)
  1254. {
  1255. query += "," + values[i];
  1256. }
  1257. statement = con.prepareStatement(query);
  1258. statement.execute();
  1259. statement.close();
  1260. }
  1261. }
  1262. }
  1263. catch (Exception e)
  1264. {
  1265. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1266. }
  1267. finally
  1268. {
  1269. L2DatabaseFactory.close(con);
  1270. }
  1271. }
  1272. // save crop procure data for specified period
  1273. public void saveCropData(int period)
  1274. {
  1275. Connection con = null;
  1276. PreparedStatement statement;
  1277. try
  1278. {
  1279. con = L2DatabaseFactory.getInstance().getConnection();
  1280. statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE_PERIOD);
  1281. statement.setInt(1, getCastleId());
  1282. statement.setInt(2, period);
  1283. statement.execute();
  1284. statement.close();
  1285. List<CropProcure> proc = null;
  1286. proc = getCropProcure(period);
  1287. if (proc != null && proc.size() > 0)
  1288. {
  1289. int count = 0;
  1290. StringBuilder query = new StringBuilder();
  1291. query.append("INSERT INTO castle_manor_procure VALUES ");
  1292. String values[] = new String[proc.size()];
  1293. for (CropProcure cp : proc)
  1294. {
  1295. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + ","
  1296. + cp.getPrice() + "," + cp.getReward() + "," + period + ")";
  1297. }
  1298. if (values.length > 0)
  1299. {
  1300. query.append(values[0]);
  1301. for (int i = 1; i < values.length; i++)
  1302. {
  1303. query.append(",");
  1304. query.append(values[i]);
  1305. }
  1306. statement = con.prepareStatement(query.toString());
  1307. statement.execute();
  1308. statement.close();
  1309. }
  1310. }
  1311. }
  1312. catch (Exception e)
  1313. {
  1314. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1315. }
  1316. finally
  1317. {
  1318. L2DatabaseFactory.close(con);
  1319. }
  1320. }
  1321. public void updateCrop(int cropId, long amount, int period)
  1322. {
  1323. Connection con = null;
  1324. PreparedStatement statement;
  1325. try
  1326. {
  1327. con = L2DatabaseFactory.getInstance().getConnection();
  1328. statement = con.prepareStatement(CASTLE_UPDATE_CROP);
  1329. statement.setLong(1, amount);
  1330. statement.setInt(2, cropId);
  1331. statement.setInt(3, getCastleId());
  1332. statement.setInt(4, period);
  1333. statement.execute();
  1334. statement.close();
  1335. }
  1336. catch (Exception e)
  1337. {
  1338. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1339. }
  1340. finally
  1341. {
  1342. L2DatabaseFactory.close(con);
  1343. }
  1344. }
  1345. public void updateSeed(int seedId, long amount, int period)
  1346. {
  1347. Connection con = null;
  1348. PreparedStatement statement;
  1349. try
  1350. {
  1351. con = L2DatabaseFactory.getInstance().getConnection();
  1352. statement = con.prepareStatement(CASTLE_UPDATE_SEED);
  1353. statement.setLong(1, amount);
  1354. statement.setInt(2, seedId);
  1355. statement.setInt(3, getCastleId());
  1356. statement.setInt(4, period);
  1357. statement.execute();
  1358. statement.close();
  1359. }
  1360. catch (Exception e)
  1361. {
  1362. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1363. }
  1364. finally
  1365. {
  1366. L2DatabaseFactory.close(con);
  1367. }
  1368. }
  1369. public boolean isNextPeriodApproved()
  1370. {
  1371. return _isNextPeriodApproved;
  1372. }
  1373. public void setNextPeriodApproved(boolean val)
  1374. {
  1375. _isNextPeriodApproved = val;
  1376. }
  1377. public void updateClansReputation()
  1378. {
  1379. if (_formerOwner != null)
  1380. {
  1381. if (_formerOwner != ClanTable.getInstance().getClan(getOwnerId()))
  1382. {
  1383. int maxreward = Math.max(0, _formerOwner.getReputationScore());
  1384. _formerOwner.takeReputationScore(Config.LOOSE_CASTLE_POINTS, true);
  1385. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1386. if (owner != null)
  1387. owner.addReputationScore(Math.min(Config.TAKE_CASTLE_POINTS, maxreward), true);
  1388. }
  1389. else
  1390. _formerOwner.addReputationScore(Config.CASTLE_DEFENDED_POINTS, true);
  1391. }
  1392. else
  1393. {
  1394. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1395. if (owner != null)
  1396. {
  1397. owner.addReputationScore(Config.TAKE_CASTLE_POINTS, true);
  1398. }
  1399. }
  1400. }
  1401. public void updateShowNpcCrest()
  1402. {
  1403. Connection con = null;
  1404. PreparedStatement statement;
  1405. try
  1406. {
  1407. con = L2DatabaseFactory.getInstance().getConnection();
  1408. statement = con.prepareStatement("UPDATE castle SET showNpcCrest = ? WHERE id = ?");
  1409. statement.setString(1, String.valueOf(getShowNpcCrest()));
  1410. statement.setInt(2, getCastleId());
  1411. statement.execute();
  1412. statement.close();
  1413. }
  1414. catch (Exception e)
  1415. {
  1416. _log.info("Error saving showNpcCrest for castle " + getName() + ": " + e.getMessage());
  1417. }
  1418. finally
  1419. {
  1420. L2DatabaseFactory.close(con);
  1421. }
  1422. }
  1423. public FastList<L2Skill> getResidentialSkills()
  1424. {
  1425. return _residentialSkills;
  1426. }
  1427. public void giveResidentialSkills(L2PcInstance player)
  1428. {
  1429. if ((_residentialSkills != null) && !_residentialSkills.isEmpty())
  1430. {
  1431. for (L2Skill sk : _residentialSkills)
  1432. {
  1433. player.addSkill(sk, false);
  1434. }
  1435. }
  1436. Territory territory = TerritoryWarManager.getInstance().getTerritory(getCastleId());
  1437. if (territory != null && territory.getOwnedWardIds().contains(getCastleId() + 80))
  1438. {
  1439. for(int wardId : territory.getOwnedWardIds())
  1440. {
  1441. final FastList<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1442. for (L2SkillLearn s : territorySkills)
  1443. {
  1444. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1445. if (sk != null)
  1446. {
  1447. player.addSkill(sk, false);
  1448. }
  1449. else
  1450. {
  1451. _log.warning("Trying to add a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1452. }
  1453. }
  1454. }
  1455. }
  1456. }
  1457. public void removeResidentialSkills(L2PcInstance player)
  1458. {
  1459. if (_residentialSkills != null && !_residentialSkills.isEmpty())
  1460. {
  1461. for (L2Skill sk : _residentialSkills)
  1462. {
  1463. player.removeSkill(sk, false, true);
  1464. }
  1465. }
  1466. if (TerritoryWarManager.getInstance().getTerritory(getCastleId()) != null)
  1467. {
  1468. for(int wardId : TerritoryWarManager.getInstance().getTerritory(getCastleId()).getOwnedWardIds())
  1469. {
  1470. final FastList<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1471. for (L2SkillLearn s : territorySkills)
  1472. {
  1473. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1474. if (sk != null)
  1475. {
  1476. player.removeSkill(sk, false, true);
  1477. }
  1478. else
  1479. {
  1480. _log.warning("Trying to remove a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1481. }
  1482. }
  1483. }
  1484. }
  1485. }
  1486. /**
  1487. * Register Artefact to castle
  1488. * @param artefact
  1489. */
  1490. public void registerArtefact(L2ArtefactInstance artefact)
  1491. {
  1492. if (Config.DEBUG)
  1493. _log.info("ArtefactId: "+ artefact.getObjectId() + " is registered to "+getName()+" castle.");
  1494. _artefacts.add(artefact);
  1495. }
  1496. public List<L2ArtefactInstance> getArtefacts()
  1497. {
  1498. return _artefacts;
  1499. }
  1500. public void resetManor()
  1501. {
  1502. setCropProcure(new FastList<CropProcure>(), CastleManorManager.PERIOD_CURRENT);
  1503. setCropProcure(new FastList<CropProcure>(), CastleManorManager.PERIOD_NEXT);
  1504. setSeedProduction(new FastList<SeedProduction>(), CastleManorManager.PERIOD_CURRENT);
  1505. setSeedProduction(new FastList<SeedProduction>(), CastleManorManager.PERIOD_NEXT);
  1506. if (Config.ALT_MANOR_SAVE_ALL_ACTIONS)
  1507. {
  1508. saveCropData();
  1509. saveSeedData();
  1510. }
  1511. }
  1512. public int getBloodAlliance()
  1513. {
  1514. return _bloodAlliance;
  1515. }
  1516. public void setBloodAlliance(int count)
  1517. {
  1518. _bloodAlliance = count;
  1519. Connection con = null;
  1520. try
  1521. {
  1522. con = L2DatabaseFactory.getInstance().getConnection();
  1523. PreparedStatement statement = con.prepareStatement("Update castle set bloodAlliance = ? where id = ?");
  1524. statement.setInt(1, _bloodAlliance);
  1525. statement.setInt(2, getCastleId());
  1526. statement.execute();
  1527. statement.close();
  1528. }
  1529. catch (Exception e)
  1530. {
  1531. }
  1532. finally
  1533. {
  1534. L2DatabaseFactory.close(con);
  1535. }
  1536. }
  1537. }