-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathspace.go
616 lines (481 loc) · 12.6 KB
/
space.go
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package cirno
import (
"fmt"
"reflect"
"github.com/golang-collections/collections/queue"
)
// Space represents a geometric space
// with shapes within it.
type Space struct {
min Vector
max Vector
shapes Shapes
tree *quadTree
useTags bool
}
// Cells returns all the cells the space is subdivided to.
func (space *Space) Cells() map[*Rectangle]Shapes {
cells := map[*Rectangle]Shapes{}
for leaf := range space.tree.leaves {
cell := leaf.boundary.toRectangle()
cells[cell] = leaf.shapes.Copy()
}
return cells
}
// Max returns the max point of the space.
func (space *Space) Max() Vector {
return space.max
}
// Min returns the min point of the space.
func (space *Space) Min() Vector {
return space.min
}
// UseTags indicates whether the space relies on
// tags for collision detection.
func (space *Space) UseTags() bool {
return space.useTags
}
// InBounds detects if the center the given shape
// is within the space bounds.
func (space *Space) InBounds(shape Shape) (bool, error) {
if shape == nil {
return false, fmt.Errorf("the shape is nil")
}
pos := shape.Center()
return pos.X >= space.min.X ||
pos.Y >= space.min.Y || pos.X <= space.max.X ||
pos.Y <= space.max.Y, nil
}
// AdjustShapePosition changes the position of the shape
// if it's out of bounds.
func (space *Space) AdjustShapePosition(shape Shape) error {
if shape == nil {
return fmt.Errorf("the shape is nil")
}
pos := shape.Center()
if pos.X < space.min.X {
pos = shape.SetPosition(NewVector(space.min.X, pos.Y))
}
if pos.Y < space.min.Y {
pos = shape.SetPosition(NewVector(pos.X, space.min.Y))
}
if pos.X > space.max.X {
pos = shape.SetPosition(NewVector(space.max.X, pos.Y))
}
if pos.Y > space.max.Y {
pos = shape.SetPosition(NewVector(pos.X, space.max.Y))
}
return nil
}
// Add adds a new shape in the space.
func (space *Space) Add(shapes ...Shape) error {
for _, shape := range shapes {
if shape == nil {
return fmt.Errorf("the shape is nil")
}
inBounds, err := space.InBounds(shape)
if err != nil {
return err
}
if !inBounds {
return fmt.Errorf("the shape is out of bounds")
}
space.shapes.Insert(shape)
_, err = space.tree.insert(shape)
if err != nil {
return err
}
}
return nil
}
// Remove removes the shape from the space.
func (space *Space) Remove(shapes ...Shape) error {
for _, shape := range shapes {
if shape == nil {
return fmt.Errorf("the shape is nil")
}
space.shapes.Remove(shape)
err := space.tree.remove(shape)
if err != nil {
return err
}
}
return nil
}
// Contains returns true if the shape is within the space,
// and false otherwise.
func (space *Space) Contains(shape Shape) (bool, error) {
if shape == nil {
return false, fmt.Errorf("the shape is nil")
}
return space.shapes.Contains(shape)
}
// Clear removes all shapes from
// the space.
func (space *Space) Clear() error {
space.shapes = make(Shapes, 0)
return space.tree.clear()
}
// Shapes returns the list of all shapes
// within the space.
func (space *Space) Shapes() Shapes {
return space.shapes.Copy()
}
// Update should be called on the shape
// whenever it's moved within the space.
func (space *Space) Update(shape Shape) (map[Vector]Shapes, error) {
if shape == nil {
return nil, fmt.Errorf("the shape is nil")
}
contains, err := space.Contains(shape)
if err != nil {
return nil, err
}
if !contains {
return nil, fmt.Errorf("the space doesn't contain the given shape")
}
// Remove the shape from all the nodes that don't contain it
// anymore and remove all these nodes from the shape's domain.
nodesToRemove := []*quadTreeNode{}
for _, node := range shape.nodes() {
overlapped, err := node.boundary.collidesShape(shape)
if err != nil {
return nil, err
}
if !overlapped {
nodesToRemove = append(nodesToRemove, node)
}
}
for _, node := range nodesToRemove {
node.shapes.Remove(shape)
shape.removeNodes(node)
}
// Add the shape in all the nodes
// that must be in its domain.
nodeQueue := queue.New()
nodeQueue.Enqueue(space.tree.root)
for nodeQueue.Len() > 0 {
node := nodeQueue.Dequeue().(*quadTreeNode)
// If the node is already
// in the domain, skip it.
if shape.containsNode(node) {
continue
}
// If the shape is not covered by the node area,
// skip it to the next node.
overlapped, err := node.boundary.collidesShape(shape)
if err != nil {
return nil, err
}
if !overlapped {
continue
}
// If the node is not a leaf,
// skip it.
if node.northWest != nil {
nodeQueue.Enqueue(node.northEast)
nodeQueue.Enqueue(node.northWest)
nodeQueue.Enqueue(node.southEast)
nodeQueue.Enqueue(node.southWest)
continue
}
// If the node limit is not exceeded,
// add the shape in the list of shapes
// covered by the node area.
if len(node.shapes) < node.tree.nodeCapacity ||
node.level >= node.tree.maxLevel {
node.shapes.Insert(shape)
shape.addNodes(node)
} else {
// Split the node into four subareas
// and add the subnodes in the queue.
err := node.split()
if err != nil {
return nil, err
}
nodeQueue.Enqueue(node.northEast)
nodeQueue.Enqueue(node.northWest)
nodeQueue.Enqueue(node.southEast)
nodeQueue.Enqueue(node.southWest)
}
}
// Return all the nodes where
// the shape is now located in.
cells := map[Vector]Shapes{}
for _, node := range shape.nodes() {
cells[node.boundary.center()] = node.shapes.Copy()
}
return cells, nil
}
// Rebuild rebuilds the space's index
// of fhapes in purpose to optimize it.
func (space *Space) Rebuild() error {
return space.tree.redistribute()
}
// CollidingShapes returns the dictionary where key
// is a shape and value is the set of shapes
// colliding with the key shape.
func (space *Space) CollidingShapes() (map[Shape]Shapes, error) {
collidingShapes := make(map[Shape]Shapes)
shapeGroups := space.tree.shapeGroups()
for _, area := range shapeGroups {
shapes := area.Items()
for i, shape := range shapes {
if _, ok := collidingShapes[shape]; !ok {
collidingShapes[shape] = make(Shapes, 0)
}
for _, otherShape := range shapes[i+1:] {
overlapped, err := ResolveCollision(shape, otherShape, space.useTags)
if err != nil {
return nil, err
}
if overlapped {
collidingShapes[shape].Insert(otherShape)
if _, ok := collidingShapes[otherShape]; !ok {
collidingShapes[otherShape] = make(Shapes, 0)
}
collidingShapes[otherShape].Insert(shape)
}
}
if len(collidingShapes[shape]) == 0 {
delete(collidingShapes, shape)
}
}
}
return collidingShapes, nil
}
// CollidingWith returns the set of shapes colliding with the given shape.
func (space *Space) CollidingWith(shape Shape) (Shapes, error) {
if shape == nil {
return nil, fmt.Errorf("the shape is nil")
}
shapes := make(Shapes, 0)
nodes := shape.nodes()
for _, area := range nodes {
for item := range area.shapes {
overlapped, err := ResolveCollision(item, shape, space.useTags)
if err != nil {
return nil, err
}
if item != shape && overlapped {
shapes.Insert(item)
}
}
}
return shapes, nil
}
// CollidedBy returns the set of shapes collided by the given shape.
func (space *Space) CollidedBy(shape Shape) (Shapes, error) {
if shape == nil {
return nil, fmt.Errorf("the shape is nil")
}
shapes := make(Shapes, 0)
nodes := shape.nodes()
for _, area := range nodes {
for item := range area.shapes {
overlapped, err := ResolveCollision(shape, item, space.useTags)
if err != nil {
return nil, err
}
if item != shape && overlapped {
shapes.Insert(item)
}
}
}
return shapes, nil
}
// WouldBeCollidedBy returns all the shapes that would be collided by
// the given shape if it moved in the specified direction.
func (space *Space) WouldBeCollidedBy(shape Shape, moveDiff Vector, turnDiff float64) (Shapes, error) {
if shape == nil {
return nil, fmt.Errorf("the shape is nil")
}
shapes := make(Shapes, 0)
originalPos := shape.Center()
originalAngle := shape.Angle()
shapeType := reflect.TypeOf(shape).Elem()
// Get all the nodes where the shape is located
// before movement.
areas := shape.nodes()
shape.Move(moveDiff)
shape.Rotate(turnDiff)
// Make sure the shape is in bounds.
space.AdjustShapePosition(shape)
// Update the shape's position in the quad tree.
nodes, err := space.Update(shape)
if err != nil {
return nil, err
}
// Add shapes from the previous nodes.
for _, area := range areas {
nodes[area.boundary.center()] = area.shapes.Copy()
}
// Search for collisions in the nodes
// the shape belongs to.
for _, area := range nodes {
for item := range area {
if item == shape {
continue
}
itemType := reflect.TypeOf(item).Elem()
id := shapeType.Name() + "_" + itemType.Name()
// Make sure lines will collide.
if id == "Line_Line" {
lineShape := shape.(*Line)
lineItem := item.(*Line)
shouldCollide, err := lineShape.ShouldCollide(lineItem)
if err != nil {
return nil, err
}
if space.useTags && !shouldCollide {
continue
}
linesWouldIntersect, err := linesWouldCollide(originalPos,
originalAngle, moveDiff, turnDiff, lineShape, lineItem)
if err != nil {
return nil, err
}
if linesWouldIntersect {
shapes.Insert(lineItem)
continue
}
}
overlapped, err := ResolveCollision(shape,
item, space.useTags)
if err != nil {
return nil, err
}
if overlapped {
shapes.Insert(item)
}
}
}
// Move the shape back.
shape.SetPosition(originalPos)
shape.SetAngle(originalAngle)
_, err = space.Update(shape)
if err != nil {
return nil, err
}
return shapes, nil
}
// WouldBeCollidingWith returns all the shapes that would be colliding the given one
// if it moved in the specified direction.
func (space *Space) WouldBeCollidingWith(shape Shape, moveDiff Vector, turnDiff float64) (Shapes, error) {
if shape == nil {
return nil, fmt.Errorf("the shape is nil")
}
shapes := make(Shapes, 0)
originalPos := shape.Center()
originalAngle := shape.Angle()
shapeType := reflect.TypeOf(shape).Elem()
// Get all the nodes where the shape is located
// before movement.
areas := shape.nodes()
shape.Move(moveDiff)
shape.Rotate(turnDiff)
// Make sure the shape is in bounds.
space.AdjustShapePosition(shape)
// Update the shape's position in the quad tree.
nodes, err := space.Update(shape)
if err != nil {
return nil, err
}
// Add shapes from the previous nodes.
for _, area := range areas {
nodes[area.boundary.center()] = area.shapes.Copy()
}
// Search for collisions in the nodes
// the shape belongs to.
for _, area := range nodes {
for item := range area {
if item == shape {
continue
}
itemType := reflect.TypeOf(item).Elem()
id := shapeType.Name() + "_" + itemType.Name()
// Make sure lines will collide.
if id == "Line_Line" {
lineShape := shape.(*Line)
lineItem := item.(*Line)
linesCollinear, err := lineShape.CollinearTo(lineItem)
if err != nil {
return nil, err
}
if linesCollinear {
// Check line tags.
shouldCollide, err := lineItem.ShouldCollide(lineShape)
if err != nil {
return nil, err
}
if space.useTags && !shouldCollide {
continue
}
linesWouldIntersect, err := linesWouldCollide(originalPos,
originalAngle, moveDiff, turnDiff, lineShape, lineItem)
if err != nil {
return nil, err
}
if linesWouldIntersect {
shapes.Insert(lineItem)
continue
}
}
}
overlapped, err := ResolveCollision(item,
shape, space.useTags)
if err != nil {
return nil, err
}
if overlapped {
shapes.Insert(item)
}
}
}
// Move the shape back.
shape.SetPosition(originalPos)
shape.SetAngle(originalAngle)
_, err = space.Update(shape)
if err != nil {
return nil, err
}
return shapes, nil
}
// NewSpace creates a new empty space with the given parameters.
func NewSpace(
subdivisionFactor, shapesInArea int, width,
height float64, min, max Vector, useTags bool,
) (
*Space, error,
) {
if width <= 0 || height <= 0 {
return nil, fmt.Errorf(
"Space must have positive values for width and height")
}
if min.X >= max.X {
return nil, fmt.Errorf(
"The value of min X is incorrect")
}
if min.Y >= max.Y {
return nil, fmt.Errorf(
"The value of min Y is incorrect")
}
space := new(Space)
space.min = min
space.max = max
space.useTags = useTags
space.shapes = make(Shapes, 0)
boundary, err := newAABB(NewVector(
-width/2.0, -height/2.0),
NewVector(width/2.0, height/2.0))
if err != nil {
return nil, err
}
tree, err := newQuadTree(boundary,
subdivisionFactor, shapesInArea)
if err != nil {
return nil, err
}
space.tree = tree
return space, nil
}