-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathposition.py
411 lines (320 loc) · 12.9 KB
/
position.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# pyre-ignore-all-errors[6, 14, 15, 58]
from __future__ import annotations
import itertools
import math
import random
from collections.abc import Iterable
from typing import TYPE_CHECKING, SupportsFloat, SupportsIndex
# pyre-fixme[21]
from s2clientprotocol import common_pb2 as common_pb
if TYPE_CHECKING:
from sc2.unit import Unit
from sc2.units import Units
EPSILON: float = 10**-8
def _sign(num: SupportsFloat | SupportsIndex) -> float:
return math.copysign(1, num)
class Pointlike(tuple):
@property
def position(self) -> Pointlike:
return self
def distance_to(self, target: Unit | Point2) -> float:
"""Calculate a single distance from a point or unit to another point or unit
:param target:"""
p = target.position
return math.hypot(self[0] - p[0], self[1] - p[1])
def distance_to_point2(self, p: Point2 | tuple[float, float]) -> float:
"""Same as the function above, but should be a bit faster because of the dropped asserts
and conversion.
:param p:"""
return math.hypot(self[0] - p[0], self[1] - p[1])
def _distance_squared(self, p2: Point2) -> float:
"""Function used to not take the square root as the distances will stay proportionally the same.
This is to speed up the sorting process.
:param p2:"""
return (self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2
def sort_by_distance(self, ps: Units | Iterable[Point2]) -> list[Point2]:
"""This returns the target points sorted as list.
You should not pass a set or dict since those are not sortable.
If you want to sort your units towards a point, use 'units.sorted_by_distance_to(point)' instead.
:param ps:"""
return sorted(ps, key=lambda p: self.distance_to_point2(p.position))
def closest(self, ps: Units | Iterable[Point2]) -> Unit | Point2:
"""This function assumes the 2d distance is meant
:param ps:"""
assert ps, "ps is empty"
return min(ps, key=lambda p: self.distance_to(p))
def distance_to_closest(self, ps: Units | Iterable[Point2]) -> float:
"""This function assumes the 2d distance is meant
:param ps:"""
assert ps, "ps is empty"
closest_distance = math.inf
for p2 in ps:
p2 = p2.position
distance = self.distance_to(p2)
if distance <= closest_distance:
closest_distance = distance
return closest_distance
def furthest(self, ps: Units | Iterable[Point2]) -> Unit | Pointlike:
"""This function assumes the 2d distance is meant
:param ps: Units object, or iterable of Unit or Point2"""
assert ps, "ps is empty"
return max(ps, key=lambda p: self.distance_to(p))
def distance_to_furthest(self, ps: Units | Iterable[Point2]) -> float:
"""This function assumes the 2d distance is meant
:param ps:"""
assert ps, "ps is empty"
furthest_distance = -math.inf
for p2 in ps:
p2 = p2.position
distance = self.distance_to(p2)
if distance >= furthest_distance:
furthest_distance = distance
return furthest_distance
def offset(self, p) -> Pointlike:
"""
:param p:
"""
return self.__class__(a + b for a, b in itertools.zip_longest(self, p[: len(self)], fillvalue=0))
def unit_axes_towards(self, p) -> Pointlike:
"""
:param p:
"""
return self.__class__(_sign(b - a) for a, b in itertools.zip_longest(self, p[: len(self)], fillvalue=0))
def towards(self, p: Unit | Pointlike, distance: int | float = 1, limit: bool = False) -> Pointlike:
"""
:param p:
:param distance:
:param limit:
"""
p = p.position
# assert self != p, f"self is {self}, p is {p}"
# TODO test and fix this if statement
if self == p:
return self
# end of test
d = self.distance_to(p)
if limit:
distance = min(d, distance)
return self.__class__(
a + (b - a) / d * distance for a, b in itertools.zip_longest(self, p[: len(self)], fillvalue=0)
)
def __eq__(self, other: object) -> bool:
try:
return all(abs(a - b) <= EPSILON for a, b in itertools.zip_longest(self, other, fillvalue=0))
except TypeError:
return False
def __hash__(self) -> int:
return hash(tuple(self))
class Point2(Pointlike):
@classmethod
def from_proto(cls, data) -> Point2:
"""
:param data:
"""
return cls((data.x, data.y))
@property
# pyre-fixme[11]
def as_Point2D(self) -> common_pb.Point2D:
return common_pb.Point2D(x=self.x, y=self.y)
@property
# pyre-fixme[11]
def as_PointI(self) -> common_pb.PointI:
"""Represents points on the minimap. Values must be between 0 and 64."""
return common_pb.PointI(x=self.x, y=self.y)
@property
def rounded(self) -> Point2:
return Point2((math.floor(self[0]), math.floor(self[1])))
@property
def length(self) -> float:
"""This property exists in case Point2 is used as a vector."""
return math.hypot(self[0], self[1])
@property
def normalized(self) -> Point2:
"""This property exists in case Point2 is used as a vector."""
length = self.length
# Cannot normalize if length is zero
assert length
return self.__class__((self[0] / length, self[1] / length))
@property
def x(self) -> float:
return self[0]
@property
def y(self) -> float:
return self[1]
@property
def to2(self) -> Point2:
return Point2(self[:2])
@property
def to3(self) -> Point3:
return Point3((*self, 0))
def round(self, decimals: int) -> Point2:
"""Rounds each number in the tuple to the amount of given decimals."""
return Point2((round(self[0], decimals), round(self[1], decimals)))
def offset(self, p: Point2) -> Point2:
return Point2((self[0] + p[0], self[1] + p[1]))
def random_on_distance(self, distance) -> Point2:
if isinstance(distance, (tuple, list)): # interval
distance = distance[0] + random.random() * (distance[1] - distance[0])
assert distance > 0, "Distance is not greater than 0"
angle = random.random() * 2 * math.pi
dx, dy = math.cos(angle), math.sin(angle)
return Point2((self.x + dx * distance, self.y + dy * distance))
def towards_with_random_angle(
self,
p: Point2 | Point3,
distance: int | float = 1,
max_difference: int | float = (math.pi / 4),
) -> Point2:
tx, ty = self.to2.towards(p.to2, 1)
angle = math.atan2(ty - self.y, tx - self.x)
angle = (angle - max_difference) + max_difference * 2 * random.random()
return Point2((self.x + math.cos(angle) * distance, self.y + math.sin(angle) * distance))
def circle_intersection(self, p: Point2, r: int | float) -> set[Point2]:
"""self is point1, p is point2, r is the radius for circles originating in both points
Used in ramp finding
:param p:
:param r:"""
assert self != p, "self is equal to p"
distance_between_points = self.distance_to(p)
assert r >= distance_between_points / 2
# remaining distance from center towards the intersection, using pythagoras
remaining_distance_from_center = (r**2 - (distance_between_points / 2) ** 2) ** 0.5
# center of both points
offset_to_center = Point2(((p.x - self.x) / 2, (p.y - self.y) / 2))
center = self.offset(offset_to_center)
# stretch offset vector in the ratio of remaining distance from center to intersection
vector_stretch_factor = remaining_distance_from_center / (distance_between_points / 2)
v = offset_to_center
offset_to_center_stretched = Point2((v.x * vector_stretch_factor, v.y * vector_stretch_factor))
# rotate vector by 90° and -90°
vector_rotated_1 = Point2((offset_to_center_stretched.y, -offset_to_center_stretched.x))
vector_rotated_2 = Point2((-offset_to_center_stretched.y, offset_to_center_stretched.x))
intersect1 = center.offset(vector_rotated_1)
intersect2 = center.offset(vector_rotated_2)
return {intersect1, intersect2}
@property
def neighbors4(self) -> set:
return {
Point2((self.x - 1, self.y)),
Point2((self.x + 1, self.y)),
Point2((self.x, self.y - 1)),
Point2((self.x, self.y + 1)),
}
@property
def neighbors8(self) -> set:
return self.neighbors4 | {
Point2((self.x - 1, self.y - 1)),
Point2((self.x - 1, self.y + 1)),
Point2((self.x + 1, self.y - 1)),
Point2((self.x + 1, self.y + 1)),
}
def negative_offset(self, other: Point2) -> Point2:
return self.__class__((self[0] - other[0], self[1] - other[1]))
def __add__(self, other: Point2) -> Point2:
return self.offset(other)
def __sub__(self, other: Point2) -> Point2:
return self.negative_offset(other)
def __neg__(self) -> Point2:
return self.__class__(-a for a in self)
def __abs__(self) -> float:
return math.hypot(self.x, self.y)
def __bool__(self) -> bool:
return self.x != 0 or self.y != 0
def __mul__(self, other: int | float | Point2) -> Point2:
try:
# pyre-ignore[16]
return self.__class__((self.x * other.x, self.y * other.y))
except AttributeError:
return self.__class__((self.x * other, self.y * other))
def __rmul__(self, other: int | float | Point2) -> Point2:
return self.__mul__(other)
def __truediv__(self, other: int | float | Point2) -> Point2:
if isinstance(other, self.__class__):
return self.__class__((self.x / other.x, self.y / other.y))
return self.__class__((self.x / other, self.y / other))
def is_same_as(self, other: Point2, dist: float = 0.001) -> bool:
return self.distance_to_point2(other) <= dist
def direction_vector(self, other: Point2) -> Point2:
"""Converts a vector to a direction that can face vertically, horizontally or diagonal or be zero, e.g. (0, 0), (1, -1), (1, 0)"""
return self.__class__((_sign(other.x - self.x), _sign(other.y - self.y)))
def manhattan_distance(self, other: Point2) -> float:
"""
:param other:
"""
return abs(other.x - self.x) + abs(other.y - self.y)
@staticmethod
def center(points: list[Point2]) -> Point2:
"""Returns the central point for points in list
:param points:"""
s = Point2((0, 0))
for p in points:
s += p
return s / len(points)
class Point3(Point2):
@classmethod
def from_proto(cls, data) -> Point3:
"""
:param data:
"""
return cls((data.x, data.y, data.z))
@property
# pyre-fixme[11]
def as_Point(self) -> common_pb.Point:
return common_pb.Point(x=self.x, y=self.y, z=self.z)
@property
def rounded(self) -> Point3:
return Point3((math.floor(self[0]), math.floor(self[1]), math.floor(self[2])))
@property
def z(self) -> float:
return self[2]
@property
def to3(self) -> Point3:
return Point3(self)
def __add__(self, other: Point2 | Point3) -> Point3:
if not isinstance(other, Point3) and isinstance(other, Point2):
return Point3((self.x + other.x, self.y + other.y, self.z))
# pyre-ignore[16]
return Point3((self.x + other.x, self.y + other.y, self.z + other.z))
class Size(Point2):
@property
def width(self) -> float:
return self[0]
@property
def height(self) -> float:
return self[1]
class Rect(tuple):
@classmethod
def from_proto(cls, data) -> Rect:
"""
:param data:
"""
assert data.p0.x < data.p1.x and data.p0.y < data.p1.y
return cls((data.p0.x, data.p0.y, data.p1.x - data.p0.x, data.p1.y - data.p0.y))
@property
def x(self) -> float:
return self[0]
@property
def y(self) -> float:
return self[1]
@property
def width(self) -> float:
return self[2]
@property
def height(self) -> float:
return self[3]
@property
def right(self) -> float:
"""Returns the x-coordinate of the rectangle of its right side."""
return self.x + self.width
@property
def top(self) -> float:
"""Returns the y-coordinate of the rectangle of its top side."""
return self.y + self.height
@property
def size(self) -> Size:
return Size((self[2], self[3]))
@property
def center(self) -> Point2:
return Point2((self.x + self.width / 2, self.y + self.height / 2))
def offset(self, p) -> Rect:
return self.__class__((self[0] + p[0], self[1] + p[1], self[2], self[3]))