Castle.java 45 KB

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