CastleManorManager.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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.instancemanager;
  16. import java.sql.Connection;
  17. import java.sql.PreparedStatement;
  18. import java.sql.ResultSet;
  19. import java.util.ArrayList;
  20. import java.util.Calendar;
  21. import java.util.List;
  22. import java.util.concurrent.ScheduledFuture;
  23. import java.util.logging.Level;
  24. import java.util.logging.Logger;
  25. import javolution.util.FastList;
  26. import com.l2jserver.Config;
  27. import com.l2jserver.L2DatabaseFactory;
  28. import com.l2jserver.gameserver.ThreadPoolManager;
  29. import com.l2jserver.gameserver.datatables.ClanTable;
  30. import com.l2jserver.gameserver.datatables.ManorData;
  31. import com.l2jserver.gameserver.model.L2Clan;
  32. import com.l2jserver.gameserver.model.L2World;
  33. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  34. import com.l2jserver.gameserver.model.entity.Castle;
  35. import com.l2jserver.gameserver.model.itemcontainer.ClanWarehouse;
  36. import com.l2jserver.gameserver.model.itemcontainer.ItemContainer;
  37. import com.l2jserver.gameserver.network.SystemMessageId;
  38. import com.l2jserver.util.Rnd;
  39. /**
  40. * Class for Castle Manor Manager load manor data from DB update/reload/delete, handles all schedule for manor.
  41. * @author l3x
  42. */
  43. public class CastleManorManager
  44. {
  45. protected static final Logger _log = Logger.getLogger(CastleManorManager.class.getName());
  46. public static final int PERIOD_CURRENT = 0;
  47. public static final int PERIOD_NEXT = 1;
  48. private static final String CASTLE_MANOR_LOAD_PROCURE = "SELECT * FROM castle_manor_procure WHERE castle_id=?";
  49. private static final String CASTLE_MANOR_LOAD_PRODUCTION = "SELECT * FROM castle_manor_production WHERE castle_id=?";
  50. private static final int NEXT_PERIOD_APPROVE = Config.ALT_MANOR_APPROVE_TIME; // 6:00
  51. private static final int NEXT_PERIOD_APPROVE_MIN = Config.ALT_MANOR_APPROVE_MIN; //
  52. private static final int MANOR_REFRESH = Config.ALT_MANOR_REFRESH_TIME; // 20:00
  53. private static final int MANOR_REFRESH_MIN = Config.ALT_MANOR_REFRESH_MIN; //
  54. protected static final long MAINTENANCE_PERIOD = Config.ALT_MANOR_MAINTENANCE_PERIOD; // 6 mins
  55. private Calendar _manorRefresh;
  56. private Calendar _periodApprove;
  57. private boolean _underMaintenance;
  58. private boolean _disabled;
  59. protected ScheduledFuture<?> _scheduledManorRefresh;
  60. protected ScheduledFuture<?> _scheduledMaintenanceEnd;
  61. protected ScheduledFuture<?> _scheduledNextPeriodapprove;
  62. public static class CropProcure
  63. {
  64. final int _cropId;
  65. long _buyResidual;
  66. final int _rewardType;
  67. final long _buy;
  68. final long _price;
  69. public CropProcure(int id)
  70. {
  71. _cropId = id;
  72. _buyResidual = 0;
  73. _rewardType = 0;
  74. _buy = 0;
  75. _price = 0;
  76. }
  77. public CropProcure(int id, long amount, int type, long buy, long price)
  78. {
  79. _cropId = id;
  80. _buyResidual = amount;
  81. _rewardType = type;
  82. _buy = buy;
  83. _price = price;
  84. }
  85. public int getReward()
  86. {
  87. return _rewardType;
  88. }
  89. public int getId()
  90. {
  91. return _cropId;
  92. }
  93. public long getAmount()
  94. {
  95. return _buyResidual;
  96. }
  97. public long getStartAmount()
  98. {
  99. return _buy;
  100. }
  101. public long getPrice()
  102. {
  103. return _price;
  104. }
  105. public void setAmount(long amount)
  106. {
  107. _buyResidual = amount;
  108. }
  109. }
  110. public static class SeedProduction
  111. {
  112. final int _seedId;
  113. long _residual;
  114. final long _price;
  115. final long _sales;
  116. public SeedProduction(int id)
  117. {
  118. _seedId = id;
  119. _residual = 0;
  120. _price = 0;
  121. _sales = 0;
  122. }
  123. public SeedProduction(int id, long amount, long price, long sales)
  124. {
  125. _seedId = id;
  126. _residual = amount;
  127. _price = price;
  128. _sales = sales;
  129. }
  130. public int getId()
  131. {
  132. return _seedId;
  133. }
  134. public long getCanProduce()
  135. {
  136. return _residual;
  137. }
  138. public long getPrice()
  139. {
  140. return _price;
  141. }
  142. public long getStartProduce()
  143. {
  144. return _sales;
  145. }
  146. public void setCanProduce(long amount)
  147. {
  148. _residual = amount;
  149. }
  150. }
  151. protected CastleManorManager()
  152. {
  153. load(); // load data from database
  154. init(); // schedule all manor related events
  155. _underMaintenance = false;
  156. _disabled = !Config.ALLOW_MANOR;
  157. boolean isApproved;
  158. if (_periodApprove.getTimeInMillis() > _manorRefresh.getTimeInMillis())
  159. {
  160. // Next approve period already scheduled
  161. isApproved = (_manorRefresh.getTimeInMillis() > Calendar.getInstance().getTimeInMillis());
  162. }
  163. else
  164. {
  165. isApproved = ((_periodApprove.getTimeInMillis() < Calendar.getInstance().getTimeInMillis()) && (_manorRefresh.getTimeInMillis() > Calendar.getInstance().getTimeInMillis()));
  166. }
  167. for (Castle c : CastleManager.getInstance().getCastles())
  168. {
  169. c.setNextPeriodApproved(isApproved);
  170. }
  171. }
  172. private void load()
  173. {
  174. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  175. PreparedStatement statementProduction = con.prepareStatement(CASTLE_MANOR_LOAD_PRODUCTION);
  176. PreparedStatement statementProcure = con.prepareStatement(CASTLE_MANOR_LOAD_PROCURE))
  177. {
  178. for (Castle castle : CastleManager.getInstance().getCastles())
  179. {
  180. FastList<SeedProduction> production = new FastList<>();
  181. FastList<SeedProduction> productionNext = new FastList<>();
  182. FastList<CropProcure> procure = new FastList<>();
  183. FastList<CropProcure> procureNext = new FastList<>();
  184. // restore seed production info
  185. statementProduction.setInt(1, castle.getCastleId());
  186. try (ResultSet rs = statementProduction.executeQuery())
  187. {
  188. statementProduction.clearParameters();
  189. while (rs.next())
  190. {
  191. int seedId = rs.getInt("seed_id");
  192. int canProduce = rs.getInt("can_produce");
  193. int startProduce = rs.getInt("start_produce");
  194. int price = rs.getInt("seed_price");
  195. int period = rs.getInt("period");
  196. if (period == PERIOD_CURRENT)
  197. {
  198. production.add(new SeedProduction(seedId, canProduce, price, startProduce));
  199. }
  200. else
  201. {
  202. productionNext.add(new SeedProduction(seedId, canProduce, price, startProduce));
  203. }
  204. }
  205. }
  206. castle.setSeedProduction(production, PERIOD_CURRENT);
  207. castle.setSeedProduction(productionNext, PERIOD_NEXT);
  208. // restore procure info
  209. statementProcure.setInt(1, castle.getCastleId());
  210. try (ResultSet rs = statementProcure.executeQuery())
  211. {
  212. statementProcure.clearParameters();
  213. while (rs.next())
  214. {
  215. int cropId = rs.getInt("crop_id");
  216. int canBuy = rs.getInt("can_buy");
  217. int startBuy = rs.getInt("start_buy");
  218. int rewardType = rs.getInt("reward_type");
  219. int price = rs.getInt("price");
  220. int period = rs.getInt("period");
  221. if (period == PERIOD_CURRENT)
  222. {
  223. procure.add(new CropProcure(cropId, canBuy, rewardType, startBuy, price));
  224. }
  225. else
  226. {
  227. procureNext.add(new CropProcure(cropId, canBuy, rewardType, startBuy, price));
  228. }
  229. }
  230. }
  231. castle.setCropProcure(procure, PERIOD_CURRENT);
  232. castle.setCropProcure(procureNext, PERIOD_NEXT);
  233. if (!procure.isEmpty() || !procureNext.isEmpty() || !production.isEmpty() || !productionNext.isEmpty())
  234. {
  235. _log.info(getClass().getSimpleName() + ": " + castle.getName() + ": Data loaded");
  236. }
  237. }
  238. }
  239. catch (Exception e)
  240. {
  241. _log.info("Error restoring manor data: " + e.getMessage());
  242. }
  243. }
  244. private void init()
  245. {
  246. _manorRefresh = Calendar.getInstance();
  247. _manorRefresh.set(Calendar.HOUR_OF_DAY, MANOR_REFRESH);
  248. _manorRefresh.set(Calendar.MINUTE, MANOR_REFRESH_MIN);
  249. _periodApprove = Calendar.getInstance();
  250. _periodApprove.set(Calendar.HOUR_OF_DAY, NEXT_PERIOD_APPROVE);
  251. _periodApprove.set(Calendar.MINUTE, NEXT_PERIOD_APPROVE_MIN);
  252. updateManorRefresh();
  253. updatePeriodApprove();
  254. }
  255. public void updateManorRefresh()
  256. {
  257. _log.info("Manor System: Manor refresh updated");
  258. _scheduledManorRefresh = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  259. {
  260. @Override
  261. public void run()
  262. {
  263. if (!isDisabled())
  264. {
  265. setUnderMaintenance(true);
  266. _log.info("Manor System: Under maintenance mode started");
  267. _scheduledMaintenanceEnd = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  268. {
  269. @Override
  270. public void run()
  271. {
  272. _log.info("Manor System: Next period started");
  273. setNextPeriod();
  274. try
  275. {
  276. save();
  277. }
  278. catch (Exception e)
  279. {
  280. _log.log(Level.WARNING, "Manor System: Failed to save manor data: " + e.getMessage(), e);
  281. }
  282. setUnderMaintenance(false);
  283. }
  284. }, MAINTENANCE_PERIOD);
  285. }
  286. updateManorRefresh();
  287. }
  288. }, getMillisToManorRefresh());
  289. }
  290. public void updatePeriodApprove()
  291. {
  292. _log.info("Manor System: Manor period approve updated");
  293. _scheduledNextPeriodapprove = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  294. {
  295. @Override
  296. public void run()
  297. {
  298. if (!isDisabled())
  299. {
  300. approveNextPeriod();
  301. _log.info("Manor System: Next period approved");
  302. }
  303. updatePeriodApprove();
  304. }
  305. }, getMillisToNextPeriodApprove());
  306. }
  307. public long getMillisToManorRefresh()
  308. {
  309. // use safe interval 120s to prevent double run
  310. if ((_manorRefresh.getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) < 120000)
  311. {
  312. setNewManorRefresh();
  313. }
  314. _log.info("Manor System: New Schedule for manor refresh @ " + _manorRefresh.getTime());
  315. return (_manorRefresh.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  316. }
  317. public void setNewManorRefresh()
  318. {
  319. _manorRefresh = Calendar.getInstance();
  320. _manorRefresh.set(Calendar.HOUR_OF_DAY, MANOR_REFRESH);
  321. _manorRefresh.set(Calendar.MINUTE, MANOR_REFRESH_MIN);
  322. _manorRefresh.set(Calendar.SECOND, 0);
  323. _manorRefresh.add(Calendar.HOUR_OF_DAY, 24);
  324. }
  325. public long getMillisToNextPeriodApprove()
  326. {
  327. // use safe interval 120s to prevent double run
  328. if ((_periodApprove.getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) < 120000)
  329. {
  330. setNewPeriodApprove();
  331. }
  332. _log.info("Manor System: New Schedule for period approve @ " + _periodApprove.getTime());
  333. return (_periodApprove.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  334. }
  335. public void setNewPeriodApprove()
  336. {
  337. _periodApprove = Calendar.getInstance();
  338. _periodApprove.set(Calendar.HOUR_OF_DAY, NEXT_PERIOD_APPROVE);
  339. _periodApprove.set(Calendar.MINUTE, NEXT_PERIOD_APPROVE_MIN);
  340. _periodApprove.set(Calendar.SECOND, 0);
  341. _periodApprove.add(Calendar.HOUR_OF_DAY, 24);
  342. }
  343. public void setNextPeriod()
  344. {
  345. for (Castle c : CastleManager.getInstance().getCastles())
  346. {
  347. if (c.getOwnerId() <= 0)
  348. {
  349. continue;
  350. }
  351. L2Clan clan = ClanTable.getInstance().getClan(c.getOwnerId());
  352. if (clan == null)
  353. {
  354. continue;
  355. }
  356. ItemContainer cwh = clan.getWarehouse();
  357. if (!(cwh instanceof ClanWarehouse))
  358. {
  359. _log.info("Can't get clan warehouse for clan " + ClanTable.getInstance().getClan(c.getOwnerId()));
  360. continue;
  361. }
  362. for (CropProcure crop : c.getCropProcure(PERIOD_CURRENT))
  363. {
  364. if (crop.getStartAmount() == 0)
  365. {
  366. continue;
  367. }
  368. // adding bought crops to clan warehouse
  369. if ((crop.getStartAmount() - crop.getAmount()) > 0)
  370. {
  371. long count = crop.getStartAmount() - crop.getAmount();
  372. count = (count * 90) / 100;
  373. if (count < 1)
  374. {
  375. if (Rnd.nextInt(99) < 90)
  376. {
  377. count = 1;
  378. }
  379. }
  380. if (count > 0)
  381. {
  382. cwh.addItem("Manor", ManorData.getInstance().getMatureCrop(crop.getId()), count, null, null);
  383. }
  384. }
  385. // reserved and not used money giving back to treasury
  386. if (crop.getAmount() > 0)
  387. {
  388. c.addToTreasuryNoTax(crop.getAmount() * crop.getPrice());
  389. }
  390. }
  391. c.setSeedProduction(c.getSeedProduction(PERIOD_NEXT), PERIOD_CURRENT);
  392. c.setCropProcure(c.getCropProcure(PERIOD_NEXT), PERIOD_CURRENT);
  393. if (c.getTreasury() < c.getManorCost(PERIOD_CURRENT))
  394. {
  395. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  396. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  397. }
  398. else
  399. {
  400. FastList<SeedProduction> production = new FastList<>();
  401. for (SeedProduction s : c.getSeedProduction(PERIOD_CURRENT))
  402. {
  403. s.setCanProduce(s.getStartProduce());
  404. production.add(s);
  405. }
  406. c.setSeedProduction(production, PERIOD_NEXT);
  407. FastList<CropProcure> procure = new FastList<>();
  408. for (CropProcure cr : c.getCropProcure(PERIOD_CURRENT))
  409. {
  410. cr.setAmount(cr.getStartAmount());
  411. procure.add(cr);
  412. }
  413. c.setCropProcure(procure, PERIOD_NEXT);
  414. }
  415. if (Config.ALT_MANOR_SAVE_ALL_ACTIONS)
  416. {
  417. c.saveCropData();
  418. c.saveSeedData();
  419. }
  420. // Sending notification to a clan leader
  421. L2PcInstance clanLeader = null;
  422. clanLeader = L2World.getInstance().getPlayer(clan.getLeader().getName());
  423. if (clanLeader != null)
  424. {
  425. clanLeader.sendPacket(SystemMessageId.THE_MANOR_INFORMATION_HAS_BEEN_UPDATED);
  426. }
  427. c.setNextPeriodApproved(false);
  428. }
  429. }
  430. public void approveNextPeriod()
  431. {
  432. for (Castle c : CastleManager.getInstance().getCastles())
  433. {
  434. boolean notFunc = false;
  435. if (c.getOwnerId() <= 0)
  436. { // Castle has no owner
  437. c.setCropProcure(new FastList<CropProcure>(), PERIOD_NEXT);
  438. c.setSeedProduction(new FastList<SeedProduction>(), PERIOD_NEXT);
  439. }
  440. else if (c.getTreasury() < c.getManorCost(PERIOD_NEXT))
  441. {
  442. notFunc = true;
  443. _log.info("Manor for castle " + c.getName() + " disabled, not enough adena in treasury: " + c.getTreasury() + ", " + c.getManorCost(PERIOD_NEXT) + " required.");
  444. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  445. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  446. }
  447. else
  448. {
  449. ItemContainer cwh = ClanTable.getInstance().getClan(c.getOwnerId()).getWarehouse();
  450. if (!(cwh instanceof ClanWarehouse))
  451. {
  452. _log.info("Can't get clan warehouse for clan " + ClanTable.getInstance().getClan(c.getOwnerId()));
  453. continue;
  454. }
  455. int slots = 0;
  456. for (CropProcure crop : c.getCropProcure(PERIOD_NEXT))
  457. {
  458. if (crop.getStartAmount() > 0)
  459. {
  460. if (cwh.getItemByItemId(ManorData.getInstance().getMatureCrop(crop.getId())) == null)
  461. {
  462. slots++;
  463. }
  464. }
  465. }
  466. if (!cwh.validateCapacity(slots))
  467. {
  468. notFunc = true;
  469. _log.info("Manor for castle " + c.getName() + " disabled, not enough free slots in clan warehouse: " + (Config.WAREHOUSE_SLOTS_CLAN - cwh.getSize()) + ", but " + slots + " required.");
  470. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  471. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  472. }
  473. }
  474. c.setNextPeriodApproved(true);
  475. c.addToTreasuryNoTax((-1) * c.getManorCost(PERIOD_NEXT));
  476. if (notFunc)
  477. {
  478. L2Clan clan = ClanTable.getInstance().getClan(c.getOwnerId());
  479. L2PcInstance clanLeader = null;
  480. if (clan != null)
  481. {
  482. clanLeader = L2World.getInstance().getPlayer(clan.getLeaderId());
  483. }
  484. if (clanLeader != null)
  485. {
  486. clanLeader.sendPacket(SystemMessageId.THE_AMOUNT_IS_NOT_SUFFICIENT_AND_SO_THE_MANOR_IS_NOT_IN_OPERATION);
  487. }
  488. }
  489. }
  490. }
  491. private List<SeedProduction> getNewSeedsList(int castleId)
  492. {
  493. List<SeedProduction> seeds = new ArrayList<>();
  494. List<Integer> seedsIds = ManorData.getInstance().getSeedsForCastle(castleId);
  495. for (int sd : seedsIds)
  496. {
  497. seeds.add(new SeedProduction(sd));
  498. }
  499. return seeds;
  500. }
  501. private List<CropProcure> getNewCropsList(int castleId)
  502. {
  503. List<CropProcure> crops = new ArrayList<>();
  504. List<Integer> cropsIds = ManorData.getInstance().getCropsForCastle(castleId);
  505. for (int cr : cropsIds)
  506. {
  507. crops.add(new CropProcure(cr));
  508. }
  509. return crops;
  510. }
  511. public boolean isUnderMaintenance()
  512. {
  513. return _underMaintenance;
  514. }
  515. public void setUnderMaintenance(boolean mode)
  516. {
  517. _underMaintenance = mode;
  518. }
  519. public boolean isDisabled()
  520. {
  521. return _disabled;
  522. }
  523. public void setDisabled(boolean mode)
  524. {
  525. _disabled = mode;
  526. }
  527. public SeedProduction getNewSeedProduction(int id, long amount, long price, long sales)
  528. {
  529. return new SeedProduction(id, amount, price, sales);
  530. }
  531. public CropProcure getNewCropProcure(int id, long amount, int type, long price, long buy)
  532. {
  533. return new CropProcure(id, amount, type, buy, price);
  534. }
  535. public void save()
  536. {
  537. for (Castle c : CastleManager.getInstance().getCastles())
  538. {
  539. c.saveSeedData();
  540. c.saveCropData();
  541. }
  542. }
  543. public static final CastleManorManager getInstance()
  544. {
  545. return SingletonHolder._instance;
  546. }
  547. private static class SingletonHolder
  548. {
  549. protected static final CastleManorManager _instance = new CastleManorManager();
  550. }
  551. }