LinePointIterator.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*
  2. * Copyright (C) 2004-2015 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.gameserver.util;
  20. /**
  21. * @author HorridoJoho
  22. */
  23. public final class LinePointIterator
  24. {
  25. // src is moved towards dst in next()
  26. private int _srcX;
  27. private int _srcY;
  28. private final int _dstX;
  29. private final int _dstY;
  30. private final long _dx;
  31. private final long _dy;
  32. private final long _sx;
  33. private final long _sy;
  34. private long _error;
  35. private boolean _first;
  36. public LinePointIterator(int srcX, int srcY, int dstX, int dstY)
  37. {
  38. _srcX = srcX;
  39. _srcY = srcY;
  40. _dstX = dstX;
  41. _dstY = dstY;
  42. _dx = Math.abs((long) dstX - srcX);
  43. _dy = Math.abs((long) dstY - srcY);
  44. _sx = srcX < dstX ? 1 : -1;
  45. _sy = srcY < dstY ? 1 : -1;
  46. if (_dx >= _dy)
  47. {
  48. _error = _dx / 2;
  49. }
  50. else
  51. {
  52. _error = _dy / 2;
  53. }
  54. _first = true;
  55. }
  56. public boolean next()
  57. {
  58. if (_first)
  59. {
  60. _first = false;
  61. return true;
  62. }
  63. else if (_dx >= _dy)
  64. {
  65. if (_srcX != _dstX)
  66. {
  67. _srcX += _sx;
  68. _error += _dy;
  69. if (_error >= _dx)
  70. {
  71. _srcY += _sy;
  72. _error -= _dx;
  73. }
  74. return true;
  75. }
  76. }
  77. else
  78. {
  79. if (_srcY != _dstY)
  80. {
  81. _srcY += _sy;
  82. _error += _dx;
  83. if (_error >= _dy)
  84. {
  85. _srcX += _sx;
  86. _error -= _dy;
  87. }
  88. return true;
  89. }
  90. }
  91. return false;
  92. }
  93. public int x()
  94. {
  95. return _srcX;
  96. }
  97. public int y()
  98. {
  99. return _srcY;
  100. }
  101. }