MultiSell.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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.datatables;
  16. import gnu.trove.iterator.TIntObjectIterator;
  17. import gnu.trove.map.hash.TIntObjectHashMap;
  18. import java.io.File;
  19. import java.util.List;
  20. import java.util.logging.Level;
  21. import java.util.logging.Logger;
  22. import javax.xml.parsers.DocumentBuilderFactory;
  23. import javolution.util.FastList;
  24. import org.w3c.dom.DOMException;
  25. import org.w3c.dom.Document;
  26. import org.w3c.dom.Node;
  27. import com.l2jserver.Config;
  28. import com.l2jserver.gameserver.model.actor.L2Npc;
  29. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  30. import com.l2jserver.gameserver.model.multisell.Entry;
  31. import com.l2jserver.gameserver.model.multisell.Ingredient;
  32. import com.l2jserver.gameserver.model.multisell.ListContainer;
  33. import com.l2jserver.gameserver.model.multisell.PreparedListContainer;
  34. import com.l2jserver.gameserver.network.SystemMessageId;
  35. import com.l2jserver.gameserver.network.serverpackets.ExBrExtraUserInfo;
  36. import com.l2jserver.gameserver.network.serverpackets.MultiSellList;
  37. import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
  38. import com.l2jserver.gameserver.network.serverpackets.UserInfo;
  39. import com.l2jserver.util.file.filter.XMLFilter;
  40. public class MultiSell
  41. {
  42. public static final int PAGE_SIZE = 40;
  43. public static final int PC_BANG_POINTS = -100;
  44. public static final int CLAN_REPUTATION = -200;
  45. public static final int FAME = -300;
  46. private static final Logger _log = Logger.getLogger(MultiSell.class.getName());
  47. private final TIntObjectHashMap<ListContainer> _entries;
  48. public static MultiSell getInstance()
  49. {
  50. return SingletonHolder._instance;
  51. }
  52. protected MultiSell()
  53. {
  54. _entries = new TIntObjectHashMap<ListContainer>();
  55. load();
  56. }
  57. public final void reload()
  58. {
  59. _entries.clear();
  60. load();
  61. }
  62. /**
  63. * This will generate the multisell list for the items. There exist various
  64. * parameters in multisells that affect the way they will appear:
  65. * 1) inventory only:
  66. * * if true, only show items of the multisell for which the
  67. * "primary" ingredients are already in the player's inventory. By "primary"
  68. * ingredients we mean weapon and armor.
  69. * * if false, show the entire list.
  70. * 2) maintain enchantment: presumably, only lists with "inventory only" set to true
  71. * should sometimes have this as true. This makes no sense otherwise...
  72. * * If true, then the product will match the enchantment level of the ingredient.
  73. * if the player has multiple items that match the ingredient list but the enchantment
  74. * levels differ, then the entries need to be duplicated to show the products and
  75. * ingredients for each enchantment level.
  76. * For example: If the player has a crystal staff +1 and a crystal staff +3 and goes
  77. * to exchange it at the mammon, the list should have all exchange possibilities for
  78. * the +1 staff, followed by all possibilities for the +3 staff.
  79. * * If false, then any level ingredient will be considered equal and product will always
  80. * be at +0
  81. * 3) apply taxes: Uses the "taxIngredient" entry in order to add a certain amount of adena to the ingredients
  82. * 4) additional product and ingredient multipliers
  83. * @param listId
  84. * @param player
  85. * @param npc
  86. * @param inventoryOnly
  87. * @param productMultiplier
  88. * @param ingredientMultiplier
  89. */
  90. public final void separateAndSend(int listId, L2PcInstance player, L2Npc npc, boolean inventoryOnly, double productMultiplier, double ingredientMultiplier)
  91. {
  92. ListContainer template = _entries.get(listId);
  93. if (template == null)
  94. {
  95. _log.warning("[MultiSell] can't find list id: " + listId + " requested by player: " + player.getName() + ", npcId:" + (npc != null ? npc.getNpcId() : 0));
  96. return;
  97. }
  98. final PreparedListContainer list = new PreparedListContainer(template, inventoryOnly, player, npc);
  99. // Pass through this only when multipliers are different from 1
  100. if (productMultiplier != 1 || ingredientMultiplier != 1)
  101. {
  102. for(Entry entry : list.getEntries())
  103. {
  104. for(Ingredient product : entry.getProducts())
  105. {
  106. //Math.max used here to avoid dropping count to 0
  107. product.setItemCount((long) Math.max(product.getItemCount() * productMultiplier,1));
  108. }
  109. for(Ingredient ingredient : entry.getIngredients())
  110. {
  111. //Math.max used here to avoid dropping count to 0
  112. ingredient.setItemCount((long) Math.max(ingredient.getItemCount() * ingredientMultiplier, 1));
  113. }
  114. }
  115. }
  116. int index = 0;
  117. do
  118. {
  119. // send list at least once even if size = 0
  120. player.sendPacket(new MultiSellList(list, index));
  121. index += PAGE_SIZE;
  122. }
  123. while (index < list.getEntries().size());
  124. player.setMultiSell(list);
  125. }
  126. public final void separateAndSend(int listId, L2PcInstance player, L2Npc npc, boolean inventoryOnly)
  127. {
  128. separateAndSend(listId, player, npc, inventoryOnly, 1, 1);
  129. }
  130. public static final boolean checkSpecialIngredient(int id, long amount, L2PcInstance player)
  131. {
  132. switch (id)
  133. {
  134. case CLAN_REPUTATION:
  135. if (player.getClan() == null)
  136. {
  137. player.sendPacket(SystemMessageId.YOU_ARE_NOT_A_CLAN_MEMBER);
  138. break;
  139. }
  140. if (!player.isClanLeader())
  141. {
  142. player.sendPacket(SystemMessageId.ONLY_THE_CLAN_LEADER_IS_ENABLED);
  143. break;
  144. }
  145. if (player.getClan().getReputationScore() < amount)
  146. {
  147. player.sendPacket(SystemMessageId.THE_CLAN_REPUTATION_SCORE_IS_TOO_LOW);
  148. break;
  149. }
  150. return true;
  151. case FAME:
  152. if (player.getFame() < amount)
  153. {
  154. player.sendPacket(SystemMessageId.NOT_ENOUGH_FAME_POINTS);
  155. break;
  156. }
  157. return true;
  158. }
  159. return false;
  160. }
  161. public static final boolean getSpecialIngredient(int id, long amount, L2PcInstance player)
  162. {
  163. switch (id)
  164. {
  165. case CLAN_REPUTATION:
  166. player.getClan().takeReputationScore((int) amount, true);
  167. SystemMessage smsg = SystemMessage.getSystemMessage(SystemMessageId.S1_DEDUCTED_FROM_CLAN_REP);
  168. smsg.addItemNumber(amount);
  169. player.sendPacket(smsg);
  170. return true;
  171. case FAME:
  172. player.setFame(player.getFame() - (int) amount);
  173. player.sendPacket(new UserInfo(player));
  174. player.sendPacket(new ExBrExtraUserInfo(player));
  175. return true;
  176. }
  177. return false;
  178. }
  179. public static final void addSpecialProduct(int id, long amount, L2PcInstance player)
  180. {
  181. switch (id)
  182. {
  183. case CLAN_REPUTATION:
  184. player.getClan().addReputationScore((int) amount, true);
  185. break;
  186. case FAME:
  187. player.setFame((int) (player.getFame() + amount));
  188. player.sendPacket(new UserInfo(player));
  189. player.sendPacket(new ExBrExtraUserInfo(player));
  190. break;
  191. }
  192. }
  193. private final void load()
  194. {
  195. Document doc = null;
  196. int id = 0;
  197. List<File> files = new FastList<File>();
  198. hashFiles("data/multisell", files);
  199. if (Config.CUSTOM_MULTISELL_LOAD)
  200. hashFiles("data/multisell/custom", files);
  201. for (File f : files)
  202. {
  203. try
  204. {
  205. id = Integer.parseInt(f.getName().replaceAll(".xml", ""));
  206. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  207. factory.setValidating(false);
  208. factory.setIgnoringComments(true);
  209. doc = factory.newDocumentBuilder().parse(f);
  210. }
  211. catch (Exception e)
  212. {
  213. _log.log(Level.SEVERE, "Error loading file " + f, e);
  214. continue;
  215. }
  216. try
  217. {
  218. ListContainer list = parseDocument(doc);
  219. list.setListId(id);
  220. _entries.put(id, list);
  221. }
  222. catch (Exception e)
  223. {
  224. _log.log(Level.SEVERE, "Error in file " + f, e);
  225. }
  226. }
  227. verify();
  228. _log.log(Level.INFO, "MultiSell: Loaded " + _entries.size() + " lists.");
  229. }
  230. private final ListContainer parseDocument(Document doc)
  231. {
  232. int entryId = 1;
  233. Node attribute;
  234. ListContainer list = new ListContainer();
  235. for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling())
  236. {
  237. if ("list".equalsIgnoreCase(n.getNodeName()))
  238. {
  239. attribute = n.getAttributes().getNamedItem("applyTaxes");
  240. if (attribute == null)
  241. list.setApplyTaxes(false);
  242. else
  243. list.setApplyTaxes(Boolean.parseBoolean(attribute.getNodeValue()));
  244. attribute = n.getAttributes().getNamedItem("useRate");
  245. if (attribute != null)
  246. {
  247. try
  248. {
  249. list.setUseRate(Double.valueOf(attribute.getNodeValue()));
  250. if(list.getUseRate() == 0.0)
  251. throw new NumberFormatException("The value cannot be 0"); //threat 0 as invalid value
  252. }
  253. catch (NumberFormatException e)
  254. {
  255. try
  256. {
  257. list.setUseRate(Config.class.getField(attribute.getNodeValue()).getDouble(Config.class));
  258. }
  259. catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | DOMException e1)
  260. {
  261. _log.warning(e.getMessage() + doc.getLocalName());
  262. list.setUseRate(1.0);
  263. }
  264. }
  265. catch (DOMException e)
  266. {
  267. _log.warning(e.getMessage() + doc.getLocalName());
  268. }
  269. }
  270. attribute = n.getAttributes().getNamedItem("maintainEnchantment");
  271. if (attribute == null)
  272. list.setMaintainEnchantment(false);
  273. else
  274. list.setMaintainEnchantment(Boolean.parseBoolean(attribute.getNodeValue()));
  275. for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
  276. {
  277. if ("item".equalsIgnoreCase(d.getNodeName()))
  278. {
  279. Entry e = parseEntry(d, entryId++, list);
  280. list.getEntries().add(e);
  281. }
  282. }
  283. }
  284. else if ("item".equalsIgnoreCase(n.getNodeName()))
  285. {
  286. Entry e = parseEntry(n, entryId++, list);
  287. list.getEntries().add(e);
  288. }
  289. }
  290. return list;
  291. }
  292. private final Entry parseEntry(Node n, int entryId, ListContainer list)
  293. {
  294. Node attribute;
  295. Node first = n.getFirstChild();
  296. final Entry entry = new Entry(entryId);
  297. for (n = first; n != null; n = n.getNextSibling())
  298. {
  299. if ("ingredient".equalsIgnoreCase(n.getNodeName()))
  300. {
  301. int id = Integer.parseInt(n.getAttributes().getNamedItem("id").getNodeValue());
  302. long count = Long.parseLong(n.getAttributes().getNamedItem("count").getNodeValue());
  303. boolean isTaxIngredient, mantainIngredient;
  304. attribute = n.getAttributes().getNamedItem("isTaxIngredient");
  305. if (attribute != null)
  306. isTaxIngredient = Boolean.parseBoolean(attribute.getNodeValue());
  307. else
  308. isTaxIngredient = false;
  309. attribute = n.getAttributes().getNamedItem("maintainIngredient");
  310. if (attribute != null)
  311. mantainIngredient = Boolean.parseBoolean(attribute.getNodeValue());
  312. else
  313. mantainIngredient = false;
  314. entry.addIngredient(new Ingredient(id, count, isTaxIngredient, mantainIngredient));
  315. }
  316. else if ("production".equalsIgnoreCase(n.getNodeName()))
  317. {
  318. int id = Integer.parseInt(n.getAttributes().getNamedItem("id").getNodeValue());
  319. long count = (long) (Long.parseLong(n.getAttributes().getNamedItem("count").getNodeValue()) * list.getUseRate());
  320. entry.addProduct(new Ingredient(id, count, false, false));
  321. }
  322. }
  323. return entry;
  324. }
  325. private final void hashFiles(String dirname, List<File> hash)
  326. {
  327. File dir = new File(Config.DATAPACK_ROOT, dirname);
  328. if (!dir.exists())
  329. {
  330. _log.log(Level.WARNING, "Dir " + dir.getAbsolutePath() + " not exists");
  331. return;
  332. }
  333. File[] files = dir.listFiles(new XMLFilter());
  334. for (File f : files)
  335. hash.add(f);
  336. }
  337. private final void verify()
  338. {
  339. ListContainer list;
  340. final TIntObjectIterator<ListContainer> iter = _entries.iterator();
  341. while (iter.hasNext())
  342. {
  343. iter.advance();
  344. list = iter.value();
  345. for (Entry ent : list.getEntries())
  346. {
  347. for (Ingredient ing : ent.getIngredients())
  348. {
  349. if (!verifyIngredient(ing))
  350. _log.warning("[MultiSell] can't find ingredient with itemId: " + ing.getItemId() + " in list: " + list.getListId());
  351. }
  352. for (Ingredient ing : ent.getProducts())
  353. {
  354. if (!verifyIngredient(ing))
  355. _log.warning("[MultiSell] can't find product with itemId: " + ing.getItemId() + " in list: " + list.getListId());
  356. }
  357. }
  358. }
  359. }
  360. private final boolean verifyIngredient(Ingredient ing)
  361. {
  362. switch (ing.getItemId())
  363. {
  364. case CLAN_REPUTATION:
  365. case FAME:
  366. return true;
  367. default:
  368. if (ing.getTemplate() != null)
  369. return true;
  370. }
  371. return false;
  372. }
  373. private static class SingletonHolder
  374. {
  375. protected static final MultiSell _instance = new MultiSell();
  376. }
  377. }