Util.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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.util;
  16. import java.io.File;
  17. import java.text.DateFormat;
  18. import java.text.SimpleDateFormat;
  19. import java.util.Collection;
  20. import java.util.Date;
  21. import java.util.List;
  22. import javolution.text.TextBuilder;
  23. import javolution.util.FastList;
  24. import com.l2jserver.Config;
  25. import com.l2jserver.gameserver.GeoData;
  26. import com.l2jserver.gameserver.ThreadPoolManager;
  27. import com.l2jserver.gameserver.model.L2Object;
  28. import com.l2jserver.gameserver.model.actor.L2Character;
  29. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  30. import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
  31. import com.l2jserver.gameserver.network.serverpackets.ShowBoard;
  32. import com.l2jserver.util.file.filter.ExtFilter;
  33. /**
  34. * General Utility functions related to game server.
  35. */
  36. public final class Util
  37. {
  38. public static void handleIllegalPlayerAction(L2PcInstance actor, String message, int punishment)
  39. {
  40. ThreadPoolManager.getInstance().scheduleGeneral(new IllegalPlayerAction(actor, message, punishment), 5000);
  41. }
  42. public static String getRelativePath(File base, File file)
  43. {
  44. return file.toURI().getPath().substring(base.toURI().getPath().length());
  45. }
  46. /**
  47. * @param obj1
  48. * @param obj2
  49. * @return degree value of object 2 to the horizontal line with object 1 being the origin.
  50. */
  51. public static double calculateAngleFrom(L2Object obj1, L2Object obj2)
  52. {
  53. return calculateAngleFrom(obj1.getX(), obj1.getY(), obj2.getX(), obj2.getY());
  54. }
  55. /**
  56. * @param obj1X
  57. * @param obj1Y
  58. * @param obj2X
  59. * @param obj2Y
  60. * @return degree value of object 2 to the horizontal line with object 1 being the origin
  61. */
  62. public static final double calculateAngleFrom(int obj1X, int obj1Y, int obj2X, int obj2Y)
  63. {
  64. double angleTarget = Math.toDegrees(Math.atan2(obj2Y - obj1Y, obj2X - obj1X));
  65. if (angleTarget < 0)
  66. {
  67. angleTarget = 360 + angleTarget;
  68. }
  69. return angleTarget;
  70. }
  71. public static final double convertHeadingToDegree(int clientHeading)
  72. {
  73. double degree = clientHeading / 182.044444444;
  74. return degree;
  75. }
  76. public static final int convertDegreeToClientHeading(double degree)
  77. {
  78. if (degree < 0)
  79. {
  80. degree = 360 + degree;
  81. }
  82. return (int) (degree * 182.044444444);
  83. }
  84. public static final int calculateHeadingFrom(L2Object obj1, L2Object obj2)
  85. {
  86. return calculateHeadingFrom(obj1.getX(), obj1.getY(), obj2.getX(), obj2.getY());
  87. }
  88. public static final int calculateHeadingFrom(int obj1X, int obj1Y, int obj2X, int obj2Y)
  89. {
  90. double angleTarget = Math.toDegrees(Math.atan2(obj2Y - obj1Y, obj2X - obj1X));
  91. if (angleTarget < 0)
  92. {
  93. angleTarget = 360 + angleTarget;
  94. }
  95. return (int) (angleTarget * 182.044444444);
  96. }
  97. public static final int calculateHeadingFrom(double dx, double dy)
  98. {
  99. double angleTarget = Math.toDegrees(Math.atan2(dy, dx));
  100. if (angleTarget < 0)
  101. {
  102. angleTarget = 360 + angleTarget;
  103. }
  104. return (int) (angleTarget * 182.044444444);
  105. }
  106. /**
  107. * @param x1
  108. * @param y1
  109. * @param x2
  110. * @param y2
  111. * @return the distance between the two coordinates in 2D plane
  112. */
  113. public static double calculateDistance(int x1, int y1, int x2, int y2)
  114. {
  115. return calculateDistance(x1, y1, 0, x2, y2, 0, false);
  116. }
  117. /**
  118. * @param x1
  119. * @param y1
  120. * @param z1
  121. * @param x2
  122. * @param y2
  123. * @param z2
  124. * @param includeZAxis - if true, includes also the Z axis in the calculation
  125. * @return the distance between the two coordinates
  126. */
  127. public static double calculateDistance(int x1, int y1, int z1, int x2, int y2, int z2, boolean includeZAxis)
  128. {
  129. double dx = (double) x1 - x2;
  130. double dy = (double) y1 - y2;
  131. if (includeZAxis)
  132. {
  133. double dz = z1 - z2;
  134. return Math.sqrt((dx * dx) + (dy * dy) + (dz * dz));
  135. }
  136. return Math.sqrt((dx * dx) + (dy * dy));
  137. }
  138. /**
  139. * @param obj1
  140. * @param obj2
  141. * @param includeZAxis - if true, includes also the Z axis in the calculation
  142. * @return the distance between the two objects
  143. */
  144. public static double calculateDistance(L2Object obj1, L2Object obj2, boolean includeZAxis)
  145. {
  146. if ((obj1 == null) || (obj2 == null))
  147. {
  148. return 1000000;
  149. }
  150. return calculateDistance(obj1.getPosition().getX(), obj1.getPosition().getY(), obj1.getPosition().getZ(), obj2.getPosition().getX(), obj2.getPosition().getY(), obj2.getPosition().getZ(), includeZAxis);
  151. }
  152. /**
  153. * @param str - the string whose first letter to capitalize
  154. * @return a string with the first letter of the {@code str} capitalized
  155. */
  156. public static String capitalizeFirst(String str)
  157. {
  158. if ((str == null) || str.isEmpty())
  159. {
  160. return str;
  161. }
  162. final char[] arr = str.toCharArray();
  163. final char c = arr[0];
  164. if (Character.isLetter(c))
  165. {
  166. arr[0] = Character.toUpperCase(c);
  167. }
  168. return new String(arr);
  169. }
  170. /**
  171. * (Based on ucwords() function of PHP)<br>
  172. * DrHouse: still functional but must be rewritten to avoid += to concat strings
  173. * @param str - the string to capitalize
  174. * @return a string with the first letter of every word in {@code str} capitalized
  175. */
  176. @Deprecated
  177. public static String capitalizeWords(String str)
  178. {
  179. if ((str == null) || str.isEmpty())
  180. {
  181. return str;
  182. }
  183. char[] charArray = str.toCharArray();
  184. StringBuilder result = new StringBuilder();
  185. // Capitalize the first letter in the given string!
  186. charArray[0] = Character.toUpperCase(charArray[0]);
  187. for (int i = 0; i < charArray.length; i++)
  188. {
  189. if (Character.isWhitespace(charArray[i]))
  190. {
  191. charArray[i + 1] = Character.toUpperCase(charArray[i + 1]);
  192. }
  193. result.append(charArray[i]);
  194. }
  195. return result.toString();
  196. }
  197. /**
  198. * @param range
  199. * @param obj1
  200. * @param obj2
  201. * @param includeZAxis
  202. * @return {@code true} if the two objects are within specified range between each other, {@code false} otherwise
  203. */
  204. public static boolean checkIfInRange(int range, L2Object obj1, L2Object obj2, boolean includeZAxis)
  205. {
  206. if ((obj1 == null) || (obj2 == null))
  207. {
  208. return false;
  209. }
  210. if (obj1.getInstanceId() != obj2.getInstanceId())
  211. {
  212. return false;
  213. }
  214. if (range == -1)
  215. {
  216. return true; // not limited
  217. }
  218. int rad = 0;
  219. if (obj1 instanceof L2Character)
  220. {
  221. rad += ((L2Character) obj1).getTemplate().getCollisionRadius();
  222. }
  223. if (obj2 instanceof L2Character)
  224. {
  225. rad += ((L2Character) obj2).getTemplate().getCollisionRadius();
  226. }
  227. double dx = obj1.getX() - obj2.getX();
  228. double dy = obj1.getY() - obj2.getY();
  229. if (includeZAxis)
  230. {
  231. double dz = obj1.getZ() - obj2.getZ();
  232. double d = (dx * dx) + (dy * dy) + (dz * dz);
  233. return d <= ((range * range) + (2 * range * rad) + (rad * rad));
  234. }
  235. double d = (dx * dx) + (dy * dy);
  236. return d <= ((range * range) + (2 * range * rad) + (rad * rad));
  237. }
  238. /**
  239. * Checks if object is within short (sqrt(int.max_value)) radius, not using collisionRadius. Faster calculation than checkIfInRange if distance is short and collisionRadius isn't needed. Not for long distance checks (potential teleports, far away castles etc).
  240. * @param radius
  241. * @param obj1
  242. * @param obj2
  243. * @param includeZAxis if true, check also Z axis (3-dimensional check), otherwise only 2D
  244. * @return {@code true} if objects are within specified range between each other, {@code false} otherwise
  245. */
  246. public static boolean checkIfInShortRadius(int radius, L2Object obj1, L2Object obj2, boolean includeZAxis)
  247. {
  248. if ((obj1 == null) || (obj2 == null))
  249. {
  250. return false;
  251. }
  252. if (radius == -1)
  253. {
  254. return true; // not limited
  255. }
  256. int dx = obj1.getX() - obj2.getX();
  257. int dy = obj1.getY() - obj2.getY();
  258. if (includeZAxis)
  259. {
  260. int dz = obj1.getZ() - obj2.getZ();
  261. return ((dx * dx) + (dy * dy) + (dz * dz)) <= (radius * radius);
  262. }
  263. return ((dx * dx) + (dy * dy)) <= (radius * radius);
  264. }
  265. /**
  266. * @param str - the String to count
  267. * @return the number of "words" in a given string.
  268. */
  269. public static int countWords(String str)
  270. {
  271. return str.trim().split("\\s+").length;
  272. }
  273. /**
  274. * (Based on implode() in PHP)
  275. * @param strArray - an array of strings to concatenate
  276. * @param strDelim - the delimiter to put between the strings
  277. * @return a delimited string for a given array of string elements.
  278. */
  279. public static String implodeString(Iterable<String> strArray, String strDelim)
  280. {
  281. final TextBuilder sbString = TextBuilder.newInstance();
  282. for (String strValue : strArray)
  283. {
  284. sbString.append(strValue);
  285. sbString.append(strDelim);
  286. }
  287. String result = sbString.toString();
  288. TextBuilder.recycle(sbString);
  289. return result;
  290. }
  291. /**
  292. * (Based on round() in PHP)
  293. * @param number - the number to round
  294. * @param numPlaces - how many digits after decimal point to leave intact
  295. * @return the value of {@code number} rounded to specified number of digits after the decimal point.
  296. */
  297. public static float roundTo(float number, int numPlaces)
  298. {
  299. if (numPlaces <= 1)
  300. {
  301. return Math.round(number);
  302. }
  303. float exponent = (float) Math.pow(10, numPlaces);
  304. return Math.round(number * exponent) / exponent;
  305. }
  306. /**
  307. * @param text - the text to check
  308. * @return {@code true} if {@code text} contains only numbers, {@code false} otherwise
  309. */
  310. public static boolean isDigit(String text)
  311. {
  312. if ((text == null) || text.isEmpty())
  313. {
  314. return false;
  315. }
  316. for (char c : text.toCharArray())
  317. {
  318. if (!Character.isDigit(c))
  319. {
  320. return false;
  321. }
  322. }
  323. return true;
  324. }
  325. /**
  326. * @param text - the text to check
  327. * @return {@code true} if {@code text} contains only letters and/or numbers, {@code false} otherwise
  328. */
  329. public static boolean isAlphaNumeric(String text)
  330. {
  331. if ((text == null) || text.isEmpty())
  332. {
  333. return false;
  334. }
  335. for (char c : text.toCharArray())
  336. {
  337. if (!Character.isLetterOrDigit(c))
  338. {
  339. return false;
  340. }
  341. }
  342. return true;
  343. }
  344. /**
  345. * Format the specified digit using the digit grouping symbol "," (comma).<br>
  346. * For example, 123456789 becomes 123,456,789.
  347. * @param amount - the amount of adena
  348. * @return the formatted adena amount
  349. */
  350. public static String formatAdena(long amount)
  351. {
  352. String s = "";
  353. long rem = amount % 1000;
  354. s = Long.toString(rem);
  355. amount = (amount - rem) / 1000;
  356. while (amount > 0)
  357. {
  358. if (rem < 99)
  359. {
  360. s = '0' + s;
  361. }
  362. if (rem < 9)
  363. {
  364. s = '0' + s;
  365. }
  366. rem = amount % 1000;
  367. s = Long.toString(rem) + "," + s;
  368. amount = (amount - rem) / 1000;
  369. }
  370. return s;
  371. }
  372. /**
  373. * Format the given date on the given format
  374. * @param date : the date to format.
  375. * @param format : the format to correct by.
  376. * @return a string representation of the formatted date.
  377. */
  378. public static String formatDate(Date date, String format)
  379. {
  380. if (date == null)
  381. {
  382. return null;
  383. }
  384. final DateFormat dateFormat = new SimpleDateFormat(format);
  385. return dateFormat.format(date);
  386. }
  387. /**
  388. * @param <T>
  389. * @param array - the array to look into
  390. * @param obj - the object to search for
  391. * @return {@code true} if the {@code array} contains the {@code obj}, {@code false} otherwise.
  392. */
  393. public static <T> boolean contains(T[] array, T obj)
  394. {
  395. for (T element : array)
  396. {
  397. if (element == obj)
  398. {
  399. return true;
  400. }
  401. }
  402. return false;
  403. }
  404. /**
  405. * @param array - the array to look into
  406. * @param obj - the integer to search for
  407. * @return {@code true} if the {@code array} contains the {@code obj}, {@code false} otherwise
  408. */
  409. public static boolean contains(int[] array, int obj)
  410. {
  411. for (int element : array)
  412. {
  413. if (element == obj)
  414. {
  415. return true;
  416. }
  417. }
  418. return false;
  419. }
  420. public static File[] getDatapackFiles(String dirname, String extention)
  421. {
  422. File dir = new File(Config.DATAPACK_ROOT, "data/" + dirname);
  423. if (!dir.exists())
  424. {
  425. return null;
  426. }
  427. return dir.listFiles(new ExtFilter(extention));
  428. }
  429. public static String getDateString(Date date)
  430. {
  431. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  432. return dateFormat.format(date.getTime());
  433. }
  434. /**
  435. * Sends the given html to the player.
  436. * @param activeChar
  437. * @param html
  438. */
  439. public static void sendHtml(L2PcInstance activeChar, String html)
  440. {
  441. NpcHtmlMessage npcHtml = new NpcHtmlMessage(0);
  442. npcHtml.setHtml(html);
  443. activeChar.sendPacket(npcHtml);
  444. }
  445. /**
  446. * Sends the html using the community board window.
  447. * @param activeChar
  448. * @param html
  449. */
  450. public static void sendCBHtml(L2PcInstance activeChar, String html)
  451. {
  452. sendCBHtml(activeChar, html, "");
  453. }
  454. /**
  455. * Sends the html using the community board window.
  456. * @param activeChar
  457. * @param html
  458. * @param fillMultiEdit fills the multiedit window (if any) inside the community board.
  459. */
  460. public static void sendCBHtml(L2PcInstance activeChar, String html, String fillMultiEdit)
  461. {
  462. if (activeChar == null)
  463. return;
  464. if (html != null)
  465. {
  466. activeChar.clearBypass();
  467. int len = html.length();
  468. for (int i = 0; i < len; i++)
  469. {
  470. int start = html.indexOf("\"bypass ", i);
  471. int finish = html.indexOf("\"", start + 1);
  472. if (start < 0 || finish < 0)
  473. break;
  474. if (html.substring(start + 8, start + 10).equals("-h"))
  475. start += 11;
  476. else
  477. start += 8;
  478. i = finish;
  479. int finish2 = html.indexOf("$", start);
  480. if (finish2 < finish && finish2 > 0)
  481. activeChar.addBypass2(html.substring(start, finish2).trim());
  482. else
  483. activeChar.addBypass(html.substring(start, finish).trim());
  484. }
  485. }
  486. if (fillMultiEdit != null)
  487. {
  488. activeChar.sendPacket(new ShowBoard(html, "1001"));
  489. fillMultiEditContent(activeChar, fillMultiEdit);
  490. }
  491. else
  492. {
  493. activeChar.sendPacket(new ShowBoard(null, "101"));
  494. activeChar.sendPacket(new ShowBoard(html, "101"));
  495. activeChar.sendPacket(new ShowBoard(null, "102"));
  496. activeChar.sendPacket(new ShowBoard(null, "103"));
  497. }
  498. }
  499. /**
  500. *
  501. * Fills the community board's multiedit window with text. Must send after sendCBHtml
  502. * @param activeChar
  503. * @param text
  504. */
  505. public static void fillMultiEditContent(L2PcInstance activeChar, String text)
  506. {
  507. text = text.replaceAll("<br>", "\n");
  508. List<String> arg = new FastList<>();
  509. arg.add("0");
  510. arg.add("0");
  511. arg.add("0");
  512. arg.add("0");
  513. arg.add("0");
  514. arg.add("0");
  515. arg.add(activeChar.getName());
  516. arg.add(Integer.toString(activeChar.getObjectId()));
  517. arg.add(activeChar.getAccountName());
  518. arg.add("9");
  519. arg.add(" ");
  520. arg.add(" ");
  521. arg.add(text);
  522. arg.add("0");
  523. arg.add("0");
  524. arg.add("0");
  525. arg.add("0");
  526. activeChar.sendPacket(new ShowBoard(arg));
  527. }
  528. /**
  529. * Return the number of players in a defined radius.<br>
  530. * @param range : the radius.
  531. * @param npc : the object to make the test on.
  532. * @param playable : true counts summons and pets.
  533. * @param invisible : true counts invisible characters.
  534. * @return the number of targets found.
  535. */
  536. public static int getPlayersCountInRadius(int range, L2Object npc, boolean playable, boolean invisible)
  537. {
  538. int count = 0;
  539. final Collection<L2Object> objs = npc.getKnownList().getKnownObjects().values();
  540. for (L2Object obj : objs)
  541. {
  542. if (obj != null && ((obj.isPlayable() && playable) || obj.isPet()))
  543. {
  544. if (obj.isPlayer() && !invisible)
  545. {
  546. if (obj.getActingPlayer().getAppearance().getInvisible())
  547. continue;
  548. }
  549. final L2Character cha = (L2Character) obj;
  550. if (cha.getZ() < (npc.getZ() - 100) && cha.getZ() > (npc.getZ() + 100) || !(GeoData.getInstance().canSeeTarget(cha.getX(), cha.getY(), cha.getZ(), npc.getX(), npc.getY(), npc.getZ())))
  551. continue;
  552. if (Util.checkIfInRange(range, npc, obj, true) && !cha.isDead())
  553. count++;
  554. }
  555. }
  556. return count;
  557. }
  558. }