RecipeController.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. /*
  2. * This program is free software; you can redistribute it and/or modify
  3. * it under the terms of the GNU General Public License as published by
  4. * the Free Software Foundation; either version 2, or (at your option)
  5. * any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program; if not, write to the Free Software
  14. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  15. * 02111-1307, USA.
  16. *
  17. * http://www.gnu.org/copyleft/gpl.html
  18. */
  19. package net.sf.l2j.gameserver;
  20. import java.io.File;
  21. import java.io.IOException;
  22. import java.util.Arrays;
  23. import java.util.Collections;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.WeakHashMap;
  27. import java.util.logging.Level;
  28. import java.util.logging.Logger;
  29. import javax.xml.parsers.DocumentBuilderFactory;
  30. import javax.xml.parsers.ParserConfigurationException;
  31. import org.w3c.dom.Document;
  32. import org.w3c.dom.NamedNodeMap;
  33. import org.w3c.dom.Node;
  34. import org.xml.sax.SAXException;
  35. import javolution.util.FastList;
  36. import javolution.util.FastMap;
  37. import net.sf.l2j.Config;
  38. import net.sf.l2j.gameserver.model.Inventory;
  39. import net.sf.l2j.gameserver.model.L2ItemInstance;
  40. import net.sf.l2j.gameserver.model.L2ManufactureItem;
  41. import net.sf.l2j.gameserver.model.L2RecipeInstance;
  42. import net.sf.l2j.gameserver.model.L2RecipeList;
  43. import net.sf.l2j.gameserver.model.L2Skill;
  44. import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
  45. import net.sf.l2j.gameserver.network.SystemMessageId;
  46. import net.sf.l2j.gameserver.serverpackets.ActionFailed;
  47. import net.sf.l2j.gameserver.serverpackets.ItemList;
  48. import net.sf.l2j.gameserver.serverpackets.MagicSkillUse;
  49. import net.sf.l2j.gameserver.serverpackets.RecipeBookItemList;
  50. import net.sf.l2j.gameserver.serverpackets.RecipeItemMakeInfo;
  51. import net.sf.l2j.gameserver.serverpackets.RecipeShopItemInfo;
  52. import net.sf.l2j.gameserver.serverpackets.SetupGauge;
  53. import net.sf.l2j.gameserver.serverpackets.StatusUpdate;
  54. import net.sf.l2j.gameserver.serverpackets.SystemMessage;
  55. import net.sf.l2j.gameserver.skills.Stats;
  56. import net.sf.l2j.gameserver.util.Util;
  57. import net.sf.l2j.util.Rnd;
  58. public class RecipeController
  59. {
  60. protected static final Logger _log = Logger.getLogger(RecipeController.class.getName());
  61. private static RecipeController _instance;
  62. private Map<Integer, L2RecipeList> _lists;
  63. protected static final Map<L2PcInstance, RecipeItemMaker> _activeMakers = Collections.synchronizedMap(new WeakHashMap<L2PcInstance, RecipeItemMaker>());
  64. private static final String RECIPES_FILE = "recipes.xml";
  65. public static RecipeController getInstance()
  66. {
  67. return _instance == null ? _instance = new RecipeController() : _instance;
  68. }
  69. public RecipeController()
  70. {
  71. _lists = new FastMap<Integer, L2RecipeList>();
  72. try
  73. {
  74. this.loadFromXML();
  75. _log.info("RecipeController: Loaded "+_lists.size()+" recipes.");
  76. }
  77. catch (Exception e)
  78. {
  79. _log.log(Level.SEVERE, "Failed loading recipe list", e);
  80. }
  81. }
  82. public int getRecipesCount()
  83. {
  84. return _lists.size();
  85. }
  86. public L2RecipeList getRecipeList(int listId)
  87. {
  88. return _lists.get(listId);
  89. }
  90. public L2RecipeList getRecipeByItemId(int itemId)
  91. {
  92. for (int i = 0; i < _lists.size(); i++)
  93. {
  94. L2RecipeList find = _lists.get(new Integer(i));
  95. if (find.getRecipeId() == itemId)
  96. {
  97. return find;
  98. }
  99. }
  100. return null;
  101. }
  102. public L2RecipeList getRecipeById(int recId)
  103. {
  104. for (int i = 0; i < _lists.size(); i++)
  105. {
  106. L2RecipeList find = _lists.get(new Integer(i));
  107. if (find.getId() == recId)
  108. {
  109. return find;
  110. }
  111. }
  112. return null;
  113. }
  114. public synchronized void requestBookOpen(L2PcInstance player, boolean isDwarvenCraft)
  115. {
  116. RecipeItemMaker maker = null;
  117. if (Config.ALT_GAME_CREATION) maker = _activeMakers.get(player);
  118. if (maker == null)
  119. {
  120. RecipeBookItemList response = new RecipeBookItemList(isDwarvenCraft, player.getMaxMp());
  121. response.addRecipes(isDwarvenCraft ? player.getDwarvenRecipeBook()
  122. : player.getCommonRecipeBook());
  123. player.sendPacket(response);
  124. return;
  125. }
  126. SystemMessage sm = new SystemMessage(SystemMessageId.CANT_ALTER_RECIPEBOOK_WHILE_CRAFTING);
  127. player.sendPacket(sm);
  128. return;
  129. }
  130. public synchronized void requestMakeItemAbort(L2PcInstance player)
  131. {
  132. _activeMakers.remove(player); // TODO: anything else here?
  133. }
  134. public synchronized void requestManufactureItem(L2PcInstance manufacturer, int recipeListId,
  135. L2PcInstance player)
  136. {
  137. L2RecipeList recipeList = getValidRecipeList(player, recipeListId);
  138. if (recipeList == null) return;
  139. List<L2RecipeList> dwarfRecipes = Arrays.asList(manufacturer.getDwarvenRecipeBook());
  140. List<L2RecipeList> commonRecipes = Arrays.asList(manufacturer.getCommonRecipeBook());
  141. if (!dwarfRecipes.contains(recipeList) && !commonRecipes.contains(recipeList))
  142. {
  143. Util.handleIllegalPlayerAction(player,"Warning!! Character "+player.getName()+" of account "+player.getAccountName()+" sent a false recipe id.",Config.DEFAULT_PUNISH);
  144. return;
  145. }
  146. RecipeItemMaker maker;
  147. if (Config.ALT_GAME_CREATION && (maker = _activeMakers.get(manufacturer)) != null) // check if busy
  148. {
  149. player.sendMessage("Manufacturer is busy, please try later.");
  150. return;
  151. }
  152. maker = new RecipeItemMaker(manufacturer, recipeList, player);
  153. if (maker._isValid)
  154. {
  155. if (Config.ALT_GAME_CREATION)
  156. {
  157. _activeMakers.put(manufacturer, maker);
  158. ThreadPoolManager.getInstance().scheduleGeneral(maker, 100);
  159. }
  160. else maker.run();
  161. }
  162. }
  163. public synchronized void requestMakeItem(L2PcInstance player, int recipeListId)
  164. {
  165. if (player.isInDuel())
  166. {
  167. player.sendPacket(new SystemMessage(SystemMessageId.CANT_CRAFT_DURING_COMBAT));
  168. return;
  169. }
  170. L2RecipeList recipeList = getValidRecipeList(player, recipeListId);
  171. if (recipeList == null) return;
  172. List<L2RecipeList> dwarfRecipes = Arrays.asList(player.getDwarvenRecipeBook());
  173. List<L2RecipeList> commonRecipes = Arrays.asList(player.getCommonRecipeBook());
  174. if (!dwarfRecipes.contains(recipeList) && !commonRecipes.contains(recipeList))
  175. {
  176. Util.handleIllegalPlayerAction(player,"Warning!! Character "+player.getName()+" of account "+player.getAccountName()+" sent a false recipe id.",Config.DEFAULT_PUNISH);
  177. return;
  178. }
  179. RecipeItemMaker maker;
  180. // check if already busy (possible in alt mode only)
  181. if (Config.ALT_GAME_CREATION && ((maker = _activeMakers.get(player)) != null))
  182. {
  183. SystemMessage sm = new SystemMessage(SystemMessageId.S1_S2);
  184. sm.addString("You are busy creating ");
  185. sm.addItemName(recipeList.getItemId());
  186. player.sendPacket(sm);
  187. return;
  188. }
  189. maker = new RecipeItemMaker(player, recipeList, player);
  190. if (maker._isValid)
  191. {
  192. if (Config.ALT_GAME_CREATION)
  193. {
  194. _activeMakers.put(player, maker);
  195. ThreadPoolManager.getInstance().scheduleGeneral(maker, 100);
  196. }
  197. else maker.run();
  198. }
  199. }
  200. //TODO XMLize the recipe list
  201. /*private void parseList(String line)
  202. {
  203. try
  204. {
  205. StringTokenizer st = new StringTokenizer(line, ";");
  206. List<L2RecipeInstance> recipePartList = new FastList<L2RecipeInstance>();
  207. //we use common/dwarf for easy reading of the recipes.csv file
  208. String recipeTypeString = st.nextToken();
  209. // now parse the string into a boolean
  210. boolean isDwarvenRecipe;
  211. if (recipeTypeString.equalsIgnoreCase("dwarven")) isDwarvenRecipe = true;
  212. else if (recipeTypeString.equalsIgnoreCase("common")) isDwarvenRecipe = false;
  213. else
  214. { //prints a helpfull message
  215. _log.warning("Error parsing recipes.csv, unknown recipe type " + recipeTypeString);
  216. return;
  217. }
  218. String recipeName = st.nextToken();
  219. int id = Integer.parseInt(st.nextToken());
  220. int recipeId = Integer.parseInt(st.nextToken());
  221. int level = Integer.parseInt(st.nextToken());
  222. //material
  223. StringTokenizer st2 = new StringTokenizer(st.nextToken(), "[],");
  224. while (st2.hasMoreTokens())
  225. {
  226. StringTokenizer st3 = new StringTokenizer(st2.nextToken(), "()");
  227. int rpItemId = Integer.parseInt(st3.nextToken());
  228. int quantity = Integer.parseInt(st3.nextToken());
  229. L2RecipeInstance rp = new L2RecipeInstance(rpItemId, quantity);
  230. recipePartList.add(rp);
  231. }
  232. int itemId = Integer.parseInt(st.nextToken());
  233. int count = Integer.parseInt(st.nextToken());
  234. //npc fee
  235. //String notdoneyet =
  236. st.nextToken();
  237. int mpCost = Integer.parseInt(st.nextToken());
  238. int successRate = Integer.parseInt(st.nextToken());
  239. L2RecipeList recipeList = new L2RecipeList(id, level, recipeId, recipeName, successRate,
  240. mpCost, itemId, count, isDwarvenRecipe);
  241. for (L2RecipeInstance recipePart : recipePartList)
  242. {
  243. recipeList.addRecipe(recipePart);
  244. }
  245. _lists.put(new Integer(_lists.size()), recipeList);
  246. }
  247. catch (Exception e)
  248. {
  249. _log.severe("Exception in RecipeController.parseList() - " + e);
  250. }
  251. }*/
  252. private void loadFromXML() throws SAXException, IOException, ParserConfigurationException
  253. {
  254. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  255. factory.setValidating(false);
  256. factory.setIgnoringComments(true);
  257. File file = new File(Config.DATAPACK_ROOT+"/data/"+RECIPES_FILE);
  258. if (file.exists())
  259. {
  260. Document doc = factory.newDocumentBuilder().parse(file);
  261. List<L2RecipeInstance> recipePartList = new FastList<L2RecipeInstance>();
  262. for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling())
  263. {
  264. if ("list".equalsIgnoreCase(n.getNodeName()))
  265. {
  266. String recipeName;
  267. int id;
  268. for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
  269. {
  270. if ("item".equalsIgnoreCase(d.getNodeName()))
  271. {
  272. recipePartList.clear();
  273. NamedNodeMap attrs = d.getAttributes();
  274. Node att;
  275. att = attrs.getNamedItem("id");
  276. if (att == null)
  277. {
  278. _log.severe("Missing id for recipe item, skipping");
  279. continue;
  280. }
  281. id = Integer.parseInt(att.getNodeValue());
  282. att = attrs.getNamedItem("name");
  283. if (att == null)
  284. {
  285. _log.severe("Missing name for recipe item id: "+id+", skipping");
  286. continue;
  287. }
  288. recipeName = att.getNodeValue();
  289. int recipeId = -1;
  290. int level = -1;
  291. boolean isDwarvenRecipe = true;
  292. int mpCost = -1;
  293. int successRate = -1;
  294. int prodId = -1;
  295. int count = -1;
  296. for (Node c = d.getFirstChild(); c != null; c = c.getNextSibling())
  297. {
  298. if ("recipe".equalsIgnoreCase(c.getNodeName()))
  299. {
  300. NamedNodeMap atts = c.getAttributes();
  301. recipeId = Integer.parseInt(atts.getNamedItem("id").getNodeValue());
  302. level = Integer.parseInt(atts.getNamedItem("level").getNodeValue());
  303. isDwarvenRecipe = atts.getNamedItem("type").getNodeValue().equalsIgnoreCase("dwarven");
  304. }
  305. else if ("mpCost".equalsIgnoreCase(c.getNodeName()))
  306. {
  307. mpCost = Integer.parseInt(c.getTextContent());
  308. }
  309. else if ("successRate".equalsIgnoreCase(c.getNodeName()))
  310. {
  311. successRate = Integer.parseInt(c.getTextContent());
  312. }
  313. else if ("ingredient".equalsIgnoreCase(c.getNodeName()))
  314. {
  315. int ingId = Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue());
  316. int ingCount = Integer.parseInt(c.getAttributes().getNamedItem("count").getNodeValue());
  317. recipePartList.add(new L2RecipeInstance(ingId, ingCount));
  318. }
  319. else if ("production".equalsIgnoreCase(c.getNodeName()))
  320. {
  321. prodId = Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue());
  322. count = Integer.parseInt(c.getAttributes().getNamedItem("count").getNodeValue());
  323. }
  324. }
  325. L2RecipeList recipeList = new L2RecipeList(id, level, recipeId, recipeName, successRate, mpCost, prodId, count, isDwarvenRecipe);
  326. for (L2RecipeInstance recipePart : recipePartList)
  327. {
  328. recipeList.addRecipe(recipePart);
  329. }
  330. _lists.put(_lists.size(), recipeList);
  331. }
  332. }
  333. }
  334. }
  335. }
  336. else
  337. {
  338. _log.severe("Recipes file ("+file.getAbsolutePath()+") doesnt exists.");
  339. }
  340. }
  341. private class RecipeItemMaker implements Runnable
  342. {
  343. protected boolean _isValid;
  344. protected List<TempItem> _items = null;
  345. protected final L2RecipeList _recipeList;
  346. protected final L2PcInstance _player; // "crafter"
  347. protected final L2PcInstance _target; // "customer"
  348. protected final L2Skill _skill;
  349. protected final int _skillId;
  350. protected final int _skillLevel;
  351. protected double _creationPasses;
  352. protected double _manaRequired;
  353. protected int _price;
  354. protected int _totalItems;
  355. protected int _materialsRefPrice;
  356. protected int _delay;
  357. public RecipeItemMaker(L2PcInstance pPlayer, L2RecipeList pRecipeList, L2PcInstance pTarget)
  358. {
  359. _player = pPlayer;
  360. _target = pTarget;
  361. _recipeList = pRecipeList;
  362. _isValid = false;
  363. _skillId = _recipeList.isDwarvenRecipe() ? L2Skill.SKILL_CREATE_DWARVEN
  364. : L2Skill.SKILL_CREATE_COMMON;
  365. _skillLevel = _player.getSkillLevel(_skillId);
  366. _skill = _player.getKnownSkill(_skillId);
  367. _player.isInCraftMode(true);
  368. if (_player.isAlikeDead())
  369. {
  370. _player.sendMessage("Dead people don't craft.");
  371. _player.sendPacket(new ActionFailed());
  372. abort();
  373. return;
  374. }
  375. if (_target.isAlikeDead())
  376. {
  377. _target.sendMessage("Dead customers can't use manufacture.");
  378. _target.sendPacket(new ActionFailed());
  379. abort();
  380. return;
  381. }
  382. if(_target.isProcessingTransaction())
  383. {
  384. _target.sendMessage("You are busy.");
  385. _target.sendPacket(new ActionFailed());
  386. abort();
  387. return;
  388. }
  389. if(_player.isProcessingTransaction())
  390. {
  391. if(_player!=_target)
  392. {
  393. _target.sendMessage("Manufacturer "+_player.getName() + " is busy.");
  394. }
  395. _player.sendPacket(new ActionFailed());
  396. abort();
  397. return;
  398. }
  399. // validate recipe list
  400. if ((_recipeList == null) || (_recipeList.getRecipes().length == 0))
  401. {
  402. _player.sendMessage("No such recipe");
  403. _player.sendPacket(new ActionFailed());
  404. abort();
  405. return;
  406. }
  407. _manaRequired = _recipeList.getMpCost();
  408. // validate skill level
  409. if (_recipeList.getLevel() > _skillLevel)
  410. {
  411. _player.sendMessage("Need skill level " + _recipeList.getLevel());
  412. _player.sendPacket(new ActionFailed());
  413. abort();
  414. return;
  415. }
  416. // check that customer can afford to pay for creation services
  417. if (_player != _target)
  418. {
  419. for (L2ManufactureItem temp : _player.getCreateList().getList())
  420. if (temp.getRecipeId() == _recipeList.getId()) // find recipe for item we want manufactured
  421. {
  422. _price = temp.getCost();
  423. if (_target.getAdena() < _price) // check price
  424. {
  425. _target.sendPacket(new SystemMessage(SystemMessageId.YOU_NOT_ENOUGH_ADENA));
  426. abort();
  427. return;
  428. }
  429. break;
  430. }
  431. }
  432. // make temporary items
  433. if ((_items = listItems(false)) == null)
  434. {
  435. abort();
  436. return;
  437. }
  438. // calculate reference price
  439. for (TempItem i : _items)
  440. {
  441. _materialsRefPrice += i.getReferencePrice() * i.getQuantity();
  442. _totalItems += i.getQuantity();
  443. }
  444. // initial mana check requires MP as written on recipe
  445. if (_player.getCurrentMp() < _manaRequired)
  446. {
  447. _target.sendPacket(new SystemMessage(SystemMessageId.NOT_ENOUGH_MP));
  448. abort();
  449. return;
  450. }
  451. // determine number of creation passes needed
  452. // can "equip" skillLevel items each pass
  453. _creationPasses = (_totalItems / _skillLevel) + ((_totalItems % _skillLevel)!=0 ? 1 : 0);
  454. if (Config.ALT_GAME_CREATION && _creationPasses != 0) // update mana required to "per pass"
  455. _manaRequired /= _creationPasses; // checks to validateMp() will only need portion of mp for one pass
  456. updateMakeInfo(true);
  457. updateCurMp();
  458. updateCurLoad();
  459. _player.isInCraftMode(false);
  460. _isValid = true;
  461. }
  462. public void run()
  463. {
  464. if (!Config.IS_CRAFTING_ENABLED)
  465. {
  466. _target.sendMessage("Item creation is currently disabled.");
  467. abort();
  468. return;
  469. }
  470. if (_player == null || _target == null)
  471. {
  472. _log.warning("player or target == null (disconnected?), aborting"+_target+_player);
  473. abort();
  474. return;
  475. }
  476. if (_player.isOnline()==0 || _target.isOnline()==0)
  477. {
  478. _log.warning("player or target is not online, aborting "+_target+_player);
  479. abort();
  480. return;
  481. }
  482. if (Config.ALT_GAME_CREATION && _activeMakers.get(_player) == null)
  483. {
  484. if (_target!=_player)
  485. {
  486. _target.sendMessage("Manufacture aborted");
  487. _player.sendMessage("Manufacture aborted");
  488. }
  489. else
  490. {
  491. _player.sendMessage("Item creation aborted");
  492. }
  493. abort();
  494. return;
  495. }
  496. if (Config.ALT_GAME_CREATION && !_items.isEmpty())
  497. {
  498. if (!validateMp()) return; // check mana
  499. _player.reduceCurrentMp(_manaRequired); // use some mp
  500. updateCurMp(); // update craft window mp bar
  501. grabSomeItems(); // grab (equip) some more items with a nice msg to player
  502. // if still not empty, schedule another pass
  503. if(!_items.isEmpty())
  504. {
  505. // divided by RATE_CONSUMABLES_COST to remove craft time increase on higher consumables rates
  506. _delay = (int) (Config.ALT_GAME_CREATION_SPEED * _player.getMReuseRate(_skill)
  507. * GameTimeController.TICKS_PER_SECOND / Config.RATE_CONSUMABLE_COST)
  508. * GameTimeController.MILLIS_IN_TICK;
  509. // FIXME: please fix this packet to show crafting animation (somebody)
  510. MagicSkillUse msk = new MagicSkillUse(_player, _skillId, _skillLevel, _delay, 0);
  511. _player.broadcastPacket(msk);
  512. _player.sendPacket(new SetupGauge(0, _delay));
  513. ThreadPoolManager.getInstance().scheduleGeneral(this, 100 + _delay);
  514. }
  515. else
  516. {
  517. // for alt mode, sleep delay msec before finishing
  518. _player.sendPacket(new SetupGauge(0, _delay));
  519. try {
  520. Thread.sleep(_delay);
  521. } catch (InterruptedException e) {
  522. } finally {
  523. finishCrafting();
  524. }
  525. }
  526. } // for old craft mode just finish
  527. else finishCrafting();
  528. }
  529. private void finishCrafting()
  530. {
  531. if(!Config.ALT_GAME_CREATION) _player.reduceCurrentMp(_manaRequired);
  532. // first take adena for manufacture
  533. if ((_target != _player) && _price > 0) // customer must pay for services
  534. {
  535. // attempt to pay for item
  536. L2ItemInstance adenatransfer = _target.transferItem("PayManufacture",
  537. _target.getInventory().getAdenaInstance().getObjectId(),
  538. _price, _player.getInventory(), _player);
  539. if(adenatransfer==null)
  540. {
  541. _target.sendPacket(new SystemMessage(SystemMessageId.YOU_NOT_ENOUGH_ADENA));
  542. abort();
  543. return;
  544. }
  545. }
  546. if ((_items = listItems(true)) == null) // this line actually takes materials from inventory
  547. { // handle possible cheaters here
  548. // (they click craft then try to get rid of items in order to get free craft)
  549. }
  550. else if (Rnd.get(100) < _recipeList.getSuccessRate())
  551. {
  552. rewardPlayer(); // and immediately puts created item in its place
  553. updateMakeInfo(true);
  554. }
  555. else
  556. {
  557. _player.sendMessage("Item(s) failed to create");
  558. if (_target != _player)
  559. _target.sendMessage("Item(s) failed to create");
  560. updateMakeInfo(false);
  561. }
  562. // update load and mana bar of craft window
  563. updateCurMp();
  564. updateCurLoad();
  565. _activeMakers.remove(_player);
  566. _player.isInCraftMode(false);
  567. _target.sendPacket(new ItemList(_target, false));
  568. }
  569. private void updateMakeInfo(boolean success)
  570. {
  571. if (_target == _player) _target.sendPacket(new RecipeItemMakeInfo(_recipeList.getId(), _target,
  572. success));
  573. else _target.sendPacket(new RecipeShopItemInfo(_player.getObjectId(), _recipeList.getId()));
  574. }
  575. private void updateCurLoad()
  576. {
  577. StatusUpdate su = new StatusUpdate(_target.getObjectId());
  578. su.addAttribute(StatusUpdate.CUR_LOAD, _target.getCurrentLoad());
  579. _target.sendPacket(su);
  580. }
  581. private void updateCurMp()
  582. {
  583. StatusUpdate su = new StatusUpdate(_target.getObjectId());
  584. su.addAttribute(StatusUpdate.CUR_MP, (int) _target.getCurrentMp());
  585. _target.sendPacket(su);
  586. }
  587. private void grabSomeItems()
  588. {
  589. int numItems = _skillLevel;
  590. while (numItems > 0 && !_items.isEmpty())
  591. {
  592. TempItem item = _items.get(0);
  593. int count = item.getQuantity();
  594. if (count >= numItems) count = numItems;
  595. item.setQuantity(item.getQuantity() - count);
  596. if (item.getQuantity() <= 0) _items.remove(0);
  597. else _items.set(0, item);
  598. numItems -= count;
  599. if (_target == _player)
  600. {
  601. SystemMessage sm = new SystemMessage(SystemMessageId.S1_S2_EQUIPPED); // you equipped ...
  602. sm.addNumber(count);
  603. sm.addItemName(item.getItemId());
  604. _player.sendPacket(sm);
  605. }
  606. else _target.sendMessage("Manufacturer " + _player.getName() + " used " + count + " "
  607. + item.getItemName());
  608. }
  609. }
  610. private boolean validateMp()
  611. {
  612. if (_player.getCurrentMp() < _manaRequired)
  613. {
  614. // rest (wait for MP)
  615. if (Config.ALT_GAME_CREATION)
  616. {
  617. _player.sendPacket(new SetupGauge(0, _delay));
  618. ThreadPoolManager.getInstance().scheduleGeneral(this, 100 + _delay);
  619. }
  620. else
  621. // no rest - report no mana
  622. {
  623. _target.sendPacket(new SystemMessage(SystemMessageId.NOT_ENOUGH_MP));
  624. abort();
  625. }
  626. return false;
  627. }
  628. return true;
  629. }
  630. private List<TempItem> listItems(boolean remove)
  631. {
  632. L2RecipeInstance[] recipes = _recipeList.getRecipes();
  633. Inventory inv = _target.getInventory();
  634. List<TempItem> materials = new FastList<TempItem>();
  635. for (L2RecipeInstance recipe : recipes)
  636. {
  637. int quantity = _recipeList.isConsumable() ? (int) (recipe.getQuantity() * Config.RATE_CONSUMABLE_COST)
  638. : (int) recipe.getQuantity();
  639. if (quantity > 0)
  640. {
  641. L2ItemInstance item = inv.getItemByItemId(recipe.getItemId());
  642. // check materials
  643. if (item==null || item.getCount() < quantity)
  644. {
  645. _target.sendMessage("You dont have the right elements for making this item"
  646. + ((_recipeList.isConsumable() && Config.RATE_CONSUMABLE_COST != 1) ? ".\nDue to server rates you need "
  647. + Config.RATE_CONSUMABLE_COST
  648. + "x more material than listed in recipe"
  649. : ""));
  650. abort();
  651. return null;
  652. }
  653. // make new temporary object, just for counting puroses
  654. TempItem temp = new TempItem(item, quantity);
  655. materials.add(temp);
  656. }
  657. }
  658. if (remove)
  659. {
  660. for(TempItem tmp : materials)
  661. {
  662. inv.destroyItemByItemId("Manufacture", tmp.getItemId(), tmp.getQuantity(), _target, _player);
  663. }
  664. }
  665. return materials;
  666. }
  667. private void abort()
  668. {
  669. updateMakeInfo(false);
  670. _player.isInCraftMode(false);
  671. _activeMakers.remove(_player);
  672. }
  673. /**
  674. * FIXME: This class should be in some other file, but I don't know where
  675. *
  676. * Class explanation:
  677. * For item counting or checking purposes. When you don't want to modify inventory
  678. * class contains itemId, quantity, ownerId, referencePrice, but not objectId
  679. */
  680. private class TempItem
  681. { // no object id stored, this will be only "list" of items with it's owner
  682. private int _itemId;
  683. private int _quantity;
  684. private int _ownerId;
  685. private int _referencePrice;
  686. private String _itemName;
  687. /**
  688. * @param item
  689. * @param quantity of that item
  690. */
  691. public TempItem(L2ItemInstance item, int quantity)
  692. {
  693. super();
  694. _itemId = item.getItemId();
  695. _quantity = quantity;
  696. _ownerId = item.getOwnerId();
  697. _itemName = item.getItem().getName();
  698. _referencePrice = item.getReferencePrice();
  699. }
  700. /**
  701. * @return Returns the quantity.
  702. */
  703. public int getQuantity()
  704. {
  705. return _quantity;
  706. }
  707. /**
  708. * @param quantity The quantity to set.
  709. */
  710. public void setQuantity(int quantity)
  711. {
  712. _quantity = quantity;
  713. }
  714. public int getReferencePrice()
  715. {
  716. return _referencePrice;
  717. }
  718. /**
  719. * @return Returns the itemId.
  720. */
  721. public int getItemId()
  722. {
  723. return _itemId;
  724. }
  725. /**
  726. * @return Returns the ownerId.
  727. */
  728. public int getOwnerId()
  729. {
  730. return _ownerId;
  731. }
  732. /**
  733. * @return Returns the itemName.
  734. */
  735. public String getItemName()
  736. {
  737. return _itemName;
  738. }
  739. }
  740. private void rewardPlayer()
  741. {
  742. int itemId = _recipeList.getItemId();
  743. int itemCount = _recipeList.getCount();
  744. L2ItemInstance createdItem = _target.getInventory().addItem("Manufacture", itemId, itemCount,
  745. _target, _player);
  746. // inform customer of earned item
  747. SystemMessage sm = null;
  748. if (itemCount > 1)
  749. {
  750. sm = new SystemMessage(SystemMessageId.EARNED_S2_S1_S);
  751. sm.addItemName(itemId);
  752. sm.addNumber(itemCount);
  753. _target.sendPacket(sm);
  754. } else
  755. {
  756. sm = new SystemMessage(SystemMessageId.EARNED_ITEM);
  757. sm.addItemName(itemId);
  758. _target.sendPacket(sm);
  759. }
  760. if (_target != _player)
  761. {
  762. // inform manufacturer of earned profit
  763. sm = new SystemMessage(SystemMessageId.EARNED_ADENA);
  764. sm.addNumber(_price);
  765. _player.sendPacket(sm);
  766. }
  767. if (Config.ALT_GAME_CREATION)
  768. {
  769. int recipeLevel = _recipeList.getLevel();
  770. int exp = createdItem.getReferencePrice() * itemCount;
  771. // one variation
  772. // exp -= materialsRefPrice; // mat. ref. price is not accurate so other method is better
  773. if (exp < 0) exp = 0;
  774. // another variation
  775. exp /= recipeLevel;
  776. for (int i = _skillLevel; i > recipeLevel; i--)
  777. exp /= 4;
  778. int sp = exp / 10;
  779. // Added multiplication of Creation speed with XP/SP gain
  780. // slower crafting -> more XP, faster crafting -> less XP
  781. // you can use ALT_GAME_CREATION_XP_RATE/SP to
  782. // modify XP/SP gained (default = 1)
  783. _player.addExpAndSp((int) _player.calcStat(Stats.EXPSP_RATE, exp * Config.ALT_GAME_CREATION_XP_RATE
  784. * Config.ALT_GAME_CREATION_SPEED, null, null)
  785. ,(int) _player.calcStat(Stats.EXPSP_RATE, sp * Config.ALT_GAME_CREATION_SP_RATE
  786. * Config.ALT_GAME_CREATION_SPEED, null, null));
  787. }
  788. updateMakeInfo(true); // success
  789. }
  790. }
  791. private L2RecipeList getValidRecipeList(L2PcInstance player, int id)
  792. {
  793. L2RecipeList recipeList = getRecipeList(id - 1);
  794. if ((recipeList == null) || (recipeList.getRecipes().length == 0))
  795. {
  796. player.sendMessage("No recipe for: " + id);
  797. player.isInCraftMode(false);
  798. return null;
  799. }
  800. return recipeList;
  801. }
  802. }