summaryrefslogtreecommitdiffstats
path: root/collision.py
blob: 12d9d8f175dfd8626b0c691960b1b7b4ae09ae97 (plain)
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
from itertools import combinations

from pygame import Vector2


def detectTopCollision(particle, box):
    if particle.top <= box.top:
        return True
    return False


def detectBottomCollision(particle, box):
    if particle.bottom >= box.bottom:
        return True
    return False


def detectLeftCollision(particle, box):
    if particle.left <= box.left:
        return True
    return False


def detectRightCollision(particle, box):
    if particle.right >= box.right:
        return True
    return False


def handleTopCollision(particle, box):
    particle.velocity.y *= -1
    particle.position.y = box.top + particle.radius
    return True


def handleBottomCollision(particle, box):
    particle.velocity.y *= -1
    particle.position.y = box.bottom - particle.radius
    return True


def handleLeftCollision(particle, box):
    particle.velocity.x *= -1
    particle.position.x = box.left + particle.radius
    return True


def handleRightCollision(particle, box):
    particle.velocity.x *= -1
    particle.position.x = box.right - particle.radius
    return True


def handleBoxCollision(particle, box):
    if detectTopCollision(particle, box) or detectBottomCollision(particle, box):
        particle.velocity.y *= -1
        return True
    elif detectLeftCollision(particle, box) or detectRightCollision(particle, box):
        particle.velocity.x *= -1
        return True
    return False


def detectParticleCollision(particle1, particle2):
    if particle1.position.distance_to(particle2.position) <= particle1.radius + particle2.radius and \
            particle1 != particle2:
        return True
    return False


def handleParticleCollision(particle1, particle2):  # https://www.vobarian.com/collisions/2dcollisions2.pdf
    if detectParticleCollision(particle1, particle2):
        n = particle2.position - particle1.position
        un = n / n.magnitude()
        ut = Vector2(-un.y, un.x)

        v1 = particle1.velocity
        v2 = particle2.velocity

        v1n = un.dot(v1)
        v1t = ut.dot(v1)
        v2n = un.dot(v2)
        v2t = ut.dot(v2)

        v1t_prime = v1t
        v2t_prime = v2t

        v1n_prime = (v1n * (particle1.mass - particle2.mass) + 2 * particle2.mass * v2n) / (
                particle1.mass + particle2.mass)
        v2n_prime = (v2n * (particle2.mass - particle1.mass) + 2 * particle1.mass * v1n) / (
                particle1.mass + particle2.mass)

        v1_prime = v1n_prime * un + v1t_prime * ut
        v2_prime = v2n_prime * un + v2t_prime * ut

        particle1.velocity = v1_prime
        particle2.velocity = v2_prime
        return True
    return False


def sweepAndPrune(particle_list):  # broad phase collision detection
    particles = particle_list.copy()

    particles.sort(key=lambda x: x.position.x)
    x_checks = []
    active = [particles[0]]
    for particle in particles:
        if particle == active[0]:
            continue

        start_x = active[-1].position.x - active[-1].radius
        end_x = active[-1].position.x + active[-1].radius
        if (start_x <= particle.position.x - particle.radius <= end_x or
                start_x <= particle.position.x <= end_x or
                start_x <= particle.position.x + particle.radius <= end_x):
            active.append(particle)
        if len(active) > 1:
            x_checks.extend(tuple(combinations(active, 2)))
        active = [particle]

    particles.sort(key=lambda x: x.position.y)
    y_checks = []
    active = [particles[0]]
    for particle in particles:
        if particle == active[0]:
            continue
        start_y = active[-1].position.y - active[-1].radius
        end_y = active[-1].position.y + active[-1].radius
        if (start_y <= particle.position.y - particle.radius <= end_y or
                start_y <= particle.position.y <= end_y or
                start_y <= particle.position.y + particle.radius <= end_y):
            active.append(particle)
        if len(active) > 1:
            y_checks.extend(tuple(combinations(active, 2)))
        active = [particle]

    return remove_duplicates(x_checks, y_checks)


def intersection(arr1, arr2):
    return [value for value in arr1 if value in set(arr2)]


def remove_duplicates(arr1, arr2):
    return list(set(arr1 + arr2))


def spacePartitioning(particle_list, width, height):  # broad phase collision detection

    n = 25

    grid = [[[] for _ in range(n)] for _ in range(n)]

    for particle in particle_list:
        x1 = int(particle.left // (width / n))
        x2 = int(particle.right // (width / n))
        y1 = int(particle.top // (height / n))
        y2 = int(particle.bottom // (height / n))
        if x1 < 0:
            x1 = 0
        if x2 < 0:
            x2 = 0
        if y1 < 0:
            y1 = 0
        if y2 < 0:
            y2 = 0
        if x1 >= n:
            x1 = n - 1
        if x2 >= n:
            x2 = n - 1
        if y1 >= n:
            y1 = n - 1
        if y2 >= n:
            y2 = n - 1

        grid[y1][x1].append(particle)
        grid[y1][x2].append(particle)
        grid[y2][x1].append(particle)
        grid[y2][x2].append(particle)

    checks = []
    for i in range(n):
        for j in range(n):
            checks.extend(tuple(combinations(grid[i][j], 2)))

    return list(set(checks))


def smarterSpacePartitioning(particle_list):  # broad phase collision detection
    particles = particle_list.copy()
    collisions = KDTree(particles)
    # print(collisions.get_collision(), collisions.n1, collisions.n2)
    # quit()
    return list(set(collisions.get_collision()))


def median(arr):
    return arr[len(arr) // 2]


class KDTree:
    default_axis = 0
    max_depth = 2

    def __init__(self, particles, axis=default_axis, depth=0):
        self.depth = depth
        self.particles = particles
        self.axis = axis
        if self.axis == 0:
            particles.sort(key=lambda x: x.position.y)
        else:
            particles.sort(key=lambda x: x.position.x)

        self.median = median(particles)

        self.left, self.right = [], []

        if self.axis == 0:
            for particle in particles:
                if particle.position.x < self.median.position.x:
                    self.left.append(particle)
                else:
                    self.right.append(particle)

                if particle.left < self.median.position.x:
                    self.left.append(particle)
                if particle.right >= self.median.position.x:
                    self.right.append(particle)

        else:
            for particle in particles:
                if particle.position.y < self.median.position.y:
                    self.left.append(particle)
                else:
                    self.right.append(particle)

                if particle.top < self.median.position.y:
                    self.left.append(particle)
                if particle.bottom >= self.median.position.y:
                    self.right.append(particle)

        self.n1, self.n2 = None, None
        self.build()

    def getAxis(self):
        return not self.axis

    def getParticlesLeft(self):
        return self.left

    def getParticlesRight(self):
        return self.right

    def build(self):
        if self.depth == self.max_depth:
            return
        if len(self.particles) > 1:
            self.n1 = KDTree(self.getParticlesLeft(), axis=self.getAxis(), depth=self.depth + 1)
            self.n2 = KDTree(self.getParticlesRight(), axis=self.getAxis(), depth=self.depth + 1)

    def get_collision(self):
        if len(self.particles) == 1:
            return []
        if self.n1 is None or self.n2 is None:
            return []
        return list(combinations(self.particles, 2)) + self.n1.get_collision() + self.n2.get_collision()