forked from SolarLune/tetra3d
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bounds.go
795 lines (583 loc) · 22.2 KB
/
bounds.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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
package tetra3d
import (
"math"
"sort"
"github.com/kvartborg/vector"
)
type Intersection struct {
// The contact point between the two intersecting objects. Note that this may be the average
// between the two overlapping shapes, rather than the point of contact specifically.
StartingPoint vector.Vector // The starting point for the intersection; either the center of the object for sphere / aabb, the center of the closest point for capsules, or the triangle position for triangless.
ContactPoint vector.Vector // The contact point for the intersection.
MTV vector.Vector // MTV represents the minimum translation vector to remove the calling object from the intersecting object.
Triangle *Triangle // Triangle represents the triangle that was intersected in intersection tests that involve triangle meshes; if no triangle mesh was tested against, then this will be nil.
Normal vector.Vector
}
// Slope returns the slope of the intersection's normal, in radians. This ranges from 0 (straight up) to pi (straight down).
func (intersection *Intersection) Slope() float64 {
return vector.Y.Angle(intersection.Normal)
}
// Collision represents the result of a collision test. A Collision test may result in multiple intersections, and
// so an Collision holds each of these individual intersections in its Intersections slice.
// The intersections are sorted in order of distance from the starting point of the intersection (the center of the
// colliding sphere / aabb, the closest point in the capsule, the center of the closest triangle, etc) to the
// contact point.
type Collision struct {
CollidedObject BoundingObject // The BoundingObject collided with
Intersections []*Intersection // The slice of Intersections, one for each object or triangle intersected with, arranged in order of distance (far to close).
}
func newCollision(collidedObject BoundingObject) *Collision {
return &Collision{
CollidedObject: collidedObject,
Intersections: []*Intersection{},
}
}
func (col *Collision) add(intersection *Intersection) *Collision {
col.Intersections = append(col.Intersections, intersection)
return col
}
// sort the intersections by distance from starting point (which should be the same for all collisions except for triangle-triangle) to contact point.
func (col *Collision) sortResults() {
sort.Slice(col.Intersections, func(i, j int) bool {
return fastVectorDistanceSquared(col.Intersections[i].StartingPoint, col.Intersections[i].ContactPoint) >
fastVectorDistanceSquared(col.Intersections[j].StartingPoint, col.Intersections[j].ContactPoint)
})
}
// AverageMTV returns the average MTV (minimum translation vector) from all Intersections contained within the Collision.
// To be specific, this isn't actually the pure average, but rather is the result of adding together all MTVs from Intersections
// in the Collision for the direction, and using the greatest MTV's magnitude for the distance of the returned vector. In other
// words, AverageMTV returns the MTV to move in that should resolve all intersections from the Collision.
func (col *Collision) AverageMTV() vector.Vector {
greatestDist := 0.0
mtv := vector.Vector{0, 0, 0}
for _, inter := range col.Intersections {
mag := inter.MTV.Magnitude()
if mag > greatestDist {
greatestDist = mag
}
vector.In(mtv).Add(inter.MTV)
}
vector.In(mtv).Unit().Scale(greatestDist)
return mtv
}
// AverageSlope returns the average slope of the Collision (ranging from 0, pointing straight up, to pi pointing straight down).
// This average is spread across all intersections contained within the Collision.
func (result *Collision) AverageSlope() float64 {
slope := result.Intersections[0].Slope()
slopeCount := 1.0
for i := 1; i < len(result.Intersections); i++ {
inter := result.Intersections[i]
if inter.MTV.Magnitude() > 0 {
slope += inter.Slope()
slopeCount++
}
}
return slope / slopeCount
}
// AverageContactPoint returns the average contact point out of the contact points of all Intersections
// contained within the Collision.
func (result *Collision) AverageContactPoint() vector.Vector {
contactPoint := vector.Vector{0, 0, 0}
for _, inter := range result.Intersections {
vector.In(contactPoint).Add(inter.ContactPoint)
}
contactPoint[0] /= float64(len(result.Intersections))
contactPoint[1] /= float64(len(result.Intersections))
contactPoint[2] /= float64(len(result.Intersections))
return contactPoint
}
// BoundingObject represents a Node type that can be tested for collision. The exposed functions are essentially just
// concerning whether an object that implements BoundingObject is colliding with another BoundingObject, and
// if so, by how much.
type BoundingObject interface {
// Colliding returns true if the BoundingObject is intersecting the other BoundingObject.
Colliding(other BoundingObject) bool
// Collision returns a Collision if the BoundingObject is intersecting another BoundingObject. If
// no intersection is reported, Collision returns nil.
Collision(other BoundingObject) *Collision
// CollisionTest performs an collision test if the bounding object were to move in the given direction in world space.
// It returns all valid Collisions across all BoundingObjects passed in as others. Collisions will be sorted in order of
// distance. If no Collisions occurred, it will return an empty slice.
CollisionTest(dx, dy, dz float64, others ...BoundingObject) []*Collision
// CollisionTestVec performs an collision test if the bounding object were to move in the given direction in world space
// using a vector. It returns all valid Collisions across all BoundingObjects passed in as others. Collisions will be sorted in order of
// distance. If no Collisions occurred, it will return an empty slice.
CollisionTestVec(moveVec vector.Vector, others ...BoundingObject) []*Collision
}
// The below set of bt functions are used to test for intersection between BoundingObject pairs.
// I forget now, but I guess when I wrote this, bt* stood for Bounding Test, haha.
func btSphereSphere(sphereA, sphereB *BoundingSphere) *Collision {
spherePos := sphereA.WorldPosition()
bPos := sphereB.WorldPosition()
sphereRadius := sphereA.WorldRadius()
bRadius := sphereB.WorldRadius()
delta := fastVectorSub(bPos, spherePos)
dist := delta.Magnitude()
delta = delta.Unit().Invert()
s2 := sphereRadius + bRadius
if dist > s2 {
return nil
}
result := newCollision(sphereB)
result.add(
&Intersection{
StartingPoint: spherePos,
ContactPoint: bPos.Add(delta.Scale(bRadius)),
MTV: delta.Scale(s2 - dist),
Normal: delta,
},
)
return result
}
func btSphereAABB(sphere *BoundingSphere, aabb *BoundingAABB) *Collision {
spherePos := sphere.WorldPosition()
sphereRadius := sphere.WorldRadius()
intersection := aabb.ClosestPoint(spherePos)
distance := fastVectorSub(spherePos, intersection).Magnitude()
if distance > sphereRadius {
return nil
}
delta := fastVectorSub(spherePos, intersection).Unit().Scale(sphereRadius - distance)
return newCollision(aabb).add(
&Intersection{
StartingPoint: spherePos,
ContactPoint: intersection,
MTV: delta,
Normal: aabbNormalGuess(delta),
},
)
}
func btSphereTriangles(sphere *BoundingSphere, triangles *BoundingTriangles) *Collision {
// If we're not intersecting the triangle's bounding AABB, we couldn't possibly be colliding with any of the triangles, so we're good
if !sphere.Colliding(triangles.BoundingAABB) {
return nil
}
triTrans := triangles.Transform()
invertedTransform := triTrans.Inverted()
transformNoLoc := triTrans.SetRow(3, vector.Vector{0, 0, 0, 1})
spherePos := invertedTransform.MultVec(sphere.WorldPosition())
sphereRadius := sphere.WorldRadius() * math.Abs(math.Max(invertedTransform[0][0], math.Max(invertedTransform[1][1], invertedTransform[2][2])))
result := newCollision(triangles)
for _, meshPart := range triangles.Mesh.MeshParts {
mesh := meshPart.Mesh
for i := meshPart.TriangleStart; i < meshPart.TriangleEnd; i++ {
tri := mesh.Triangles[i]
v0 := mesh.VertexPositions[tri.ID*3]
v1 := mesh.VertexPositions[tri.ID*3+1]
v2 := mesh.VertexPositions[tri.ID*3+2]
// TODO: Replace this with an actual octree or something; the triangles should be spatially segmented into areas where a colliding object
// only has to check triangles in the nearby cells.
if fastVectorSub(spherePos, tri.Center).Magnitude() > tri.MaxSpan+sphereRadius {
continue
}
closest := closestPointOnTri(spherePos, v0, v1, v2)
delta := fastVectorSub(spherePos, closest)
if mag := delta.Magnitude(); mag <= sphereRadius {
result.add(
&Intersection{
StartingPoint: spherePos,
ContactPoint: triangles.Transform().MultVec(closest),
MTV: transformNoLoc.MultVec(delta.Unit().Scale(sphereRadius - mag)),
Triangle: tri,
Normal: transformNoLoc.MultVec(tri.Normal).Unit(),
},
)
}
}
}
if len(result.Intersections) == 0 {
return nil
}
result.sortResults()
return result
}
func btAABBAABB(aabbA, aabbB *BoundingAABB) *Collision {
aPos := aabbA.WorldPosition()
bPos := aabbB.WorldPosition()
aSize := aabbA.Size.Scale(0.5)
bSize := aabbB.Size.Scale(0.5)
dx := bPos[0] - aPos[0]
px := (bSize[0] + aSize[0]) - math.Abs(dx)
if px <= 0 {
return nil
}
dy := bPos[1] - aPos[1]
py := (bSize[1] + aSize[1]) - math.Abs(dy)
if py <= 0 {
return nil
}
dz := bPos[2] - aPos[2]
pz := (bSize[2] + aSize[2]) - math.Abs(dz)
if pz <= 0 {
return nil
}
result := newCollision(aabbB)
if px < py && px < pz {
sx := -1.0
if math.Signbit(dx) {
sx = 1
}
result.add(&Intersection{
StartingPoint: aPos,
ContactPoint: vector.Vector{aPos[0] + (aSize[0] * sx), bPos[1], bPos[2]},
MTV: vector.Vector{px * sx, 0, 0},
Normal: vector.Vector{sx, 0, 0},
})
} else if py < pz && py < px {
sy := -1.0
if math.Signbit(dy) {
sy = 1
}
result.add(&Intersection{
StartingPoint: aPos,
ContactPoint: vector.Vector{bPos[0], aPos[1] + (aSize[1] * sy), bPos[2]},
MTV: vector.Vector{0, py * sy, 0},
Normal: vector.Vector{0, sy, 0},
})
} else {
sz := -1.0
if math.Signbit(dz) {
sz = 1
}
result.add(&Intersection{
StartingPoint: aPos,
ContactPoint: vector.Vector{bPos[0], bPos[1], aPos[2] + (aSize[2] * sz)},
MTV: vector.Vector{0, 0, pz * sz},
Normal: vector.Vector{0, 0, sz},
})
}
return result
}
func btAABBTriangles(box *BoundingAABB, triangles *BoundingTriangles) *Collision {
// See https://gdbooks.gitbooks.io/3dcollisions/content/Chapter4/aabb-triangle.html
// If we're not intersecting the triangle's bounding AABB, we couldn't possibly be colliding with any of the triangles, so we're good
if !box.Colliding(triangles.BoundingAABB) {
return nil
}
boxPos := box.WorldPosition()
boxSize := box.Size.Scale(0.5)
transform := triangles.Transform()
transformNoLoc := transform.SetRow(3, vector.Vector{0, 0, 0, 1})
result := newCollision(triangles)
for _, meshPart := range triangles.Mesh.MeshParts {
mesh := meshPart.Mesh
for i := meshPart.TriangleStart; i < meshPart.TriangleEnd; i++ {
tri := mesh.Triangles[i]
v0 := transform.MultVec(mesh.VertexPositions[tri.ID*3]).Sub(boxPos)
v1 := transform.MultVec(mesh.VertexPositions[tri.ID*3+1]).Sub(boxPos)
v2 := transform.MultVec(mesh.VertexPositions[tri.ID*3+2]).Sub(boxPos)
// tc := v0.Add(v1).Add(v2).Scale(1.0 / 3.0)
ab := v1.Sub(v0).Unit()
bc := v2.Sub(v1).Unit()
ca := v0.Sub(v2).Unit()
axes := []vector.Vector{
vector.X,
vector.Y,
vector.Z,
vectorCross(vector.X, ab, bc),
vectorCross(vector.X, bc, ca),
vectorCross(vector.X, ca, ab),
vectorCross(vector.Y, ab, bc),
vectorCross(vector.Y, bc, ca),
vectorCross(vector.Y, ca, ab),
vectorCross(vector.Z, ab, bc),
vectorCross(vector.Z, bc, ca),
vectorCross(vector.Z, ca, ab),
transformNoLoc.MultVec(tri.Normal),
}
var overlapAxis vector.Vector
smallestOverlap := math.MaxFloat64
for _, axis := range axes {
if axis == nil {
return nil
}
axis = axis.Unit()
p1 := project(axis, v0, v1, v2)
r := boxSize[0]*math.Abs(dot(vector.X, axis)) +
boxSize[1]*math.Abs(dot(vector.Y, axis)) +
boxSize[2]*math.Abs(dot(vector.Z, axis))
p2 := projection{
Max: r,
Min: -r,
}
overlap := p1.Overlap(p2)
if !p1.IsOverlapping(p2) {
overlapAxis = nil
break
}
if overlap < smallestOverlap {
smallestOverlap = overlap
overlapAxis = axis
}
}
if overlapAxis != nil {
mtv := overlapAxis.Scale(smallestOverlap)
result.add(&Intersection{
StartingPoint: boxPos,
ContactPoint: closestPointOnTri(vector.Vector{0, 0, 0}, v0, v1, v2).Add(boxPos),
MTV: mtv,
Triangle: tri,
Normal: axes[12],
})
}
}
}
if len(result.Intersections) == 0 {
return nil
}
result.sortResults()
return result
}
func btTrianglesTriangles(trianglesA, trianglesB *BoundingTriangles) *Collision {
// See https://gdbooks.gitbooks.io/3dcollisions/content/Chapter4/aabb-triangle.html
// If we're not intersecting the triangle's bounding AABB, we couldn't possibly be colliding with any of the triangles, so we're good
if !trianglesA.BoundingAABB.Colliding(trianglesB.BoundingAABB) {
return nil
}
transformA := trianglesA.Transform()
transformB := trianglesB.Transform()
transformedA := [][]vector.Vector{}
transformedB := [][]vector.Vector{}
result := newCollision(trianglesB)
for _, meshPart := range trianglesA.Mesh.MeshParts {
mesh := meshPart.Mesh
for i := meshPart.TriangleStart; i < meshPart.TriangleEnd; i++ {
tri := mesh.Triangles[i]
v0 := transformA.MultVec(mesh.VertexPositions[tri.ID*3])
v1 := transformA.MultVec(mesh.VertexPositions[tri.ID*3+1])
v2 := transformA.MultVec(mesh.VertexPositions[tri.ID*3+2])
transformedA = append(transformedA,
[]vector.Vector{
v0, v1, v2,
v1.Sub(v0).Unit(),
v2.Sub(v1).Unit(),
v0.Sub(v2).Unit(),
transformA.MultVec(tri.Normal),
},
)
}
}
bTris := []*Triangle{}
for _, meshPart := range trianglesB.Mesh.MeshParts {
mesh := meshPart.Mesh
for i := meshPart.TriangleStart; i < meshPart.TriangleEnd; i++ {
tri := mesh.Triangles[i]
v0 := transformB.MultVec(mesh.VertexPositions[tri.ID*3])
v1 := transformB.MultVec(mesh.VertexPositions[tri.ID*3+1])
v2 := transformB.MultVec(mesh.VertexPositions[tri.ID*3+2])
bTris = append(bTris, tri)
transformedB = append(transformedB,
[]vector.Vector{
v0, v1, v2,
v1.Sub(v0).Unit(),
v2.Sub(v1).Unit(),
v0.Sub(v2).Unit(),
transformB.MultVec(tri.Normal),
},
)
}
}
for _, a := range transformedA {
for bTriIndex, b := range transformedB {
axes := []vector.Vector{
vectorCross(a[3], b[3], b[4]),
vectorCross(a[3], b[4], b[5]),
vectorCross(a[3], b[5], b[6]),
vectorCross(a[4], b[3], b[4]),
vectorCross(a[4], b[4], b[5]),
vectorCross(a[4], b[5], b[6]),
vectorCross(a[5], b[3], b[4]),
vectorCross(a[5], b[4], b[5]),
vectorCross(a[5], b[5], b[6]),
transformA.MultVec(a[6]),
transformB.MultVec(b[6]),
}
var overlapAxis vector.Vector
smallestOverlap := math.MaxFloat64
for _, axis := range axes {
if axis == nil {
return nil
}
axis = axis.Unit()
p1 := project(axis, a[0], a[1], a[2])
p2 := project(axis, b[0], b[1], b[2])
overlap := p1.Overlap(p2)
if !p1.IsOverlapping(p2) {
overlapAxis = nil
break
}
if overlap < smallestOverlap {
smallestOverlap = overlap
overlapAxis = axis
}
}
if overlapAxis != nil {
mtv := overlapAxis.Scale(smallestOverlap)
result.add(
&Intersection{
StartingPoint: transformA.MultVec(bTris[bTriIndex].Center),
// ContactPoint: b[0].Add(b[1]).Add(b[2]).Scale(1.0 / 3.0),
ContactPoint: trianglesB.WorldPosition().Add(mtv),
MTV: mtv,
Triangle: bTris[bTriIndex],
Normal: b[6],
},
)
}
}
}
if len(result.Intersections) == 0 {
return nil
}
result.sortResults()
return result
}
func btCapsuleCapsule(capsuleA, capsuleB *BoundingCapsule) *Collision {
capsuleA.internalSphere.SetLocalScale(capsuleA.LocalScale())
// By getting the closest point to the world position (center), and then getting it again, we get closer to the
// true closest point for both capsules, which is good enough for now lol
caClosest := capsuleA.ClosestPoint(capsuleB.WorldPosition())
cbClosest := capsuleB.ClosestPoint(capsuleA.WorldPosition())
capsuleA.internalSphere.SetLocalPosition(capsuleA.ClosestPoint(cbClosest))
capsuleA.internalSphere.Radius = capsuleA.Radius
capsuleB.internalSphere.SetLocalScale(capsuleB.LocalScale())
capsuleB.internalSphere.SetLocalPosition(capsuleB.ClosestPoint(caClosest))
capsuleB.internalSphere.Radius = capsuleB.Radius
return btSphereSphere(capsuleA.internalSphere, capsuleB.internalSphere)
}
func btSphereCapsule(sphere *BoundingSphere, capsule *BoundingCapsule) *Collision {
capsule.internalSphere.SetLocalScale(capsule.LocalScale())
capsule.internalSphere.SetLocalPosition(capsule.ClosestPoint(sphere.WorldPosition()))
capsule.internalSphere.Radius = capsule.Radius
return btSphereSphere(sphere, capsule.internalSphere)
}
func btCapsuleAABB(capsule *BoundingCapsule, aabb *BoundingAABB) *Collision {
capsule.internalSphere.SetLocalScale(capsule.LocalScale())
capsule.internalSphere.SetLocalPosition(capsule.ClosestPoint(aabb.WorldPosition()))
capsule.internalSphere.Radius = capsule.Radius
return btSphereAABB(capsule.internalSphere, aabb)
}
func btCapsuleTriangles(capsule *BoundingCapsule, triangles *BoundingTriangles) *Collision {
capsule.internalSphere.SetLocalScale(capsule.LocalScale())
capsule.internalSphere.SetLocalPosition(capsule.ClosestPoint(triangles.BoundingAABB.WorldPosition()))
capsule.internalSphere.Radius = capsule.Radius
// If we're not intersecting the triangle's bounding AABB, we couldn't possibly be colliding with any of the triangles, so we're good
if !capsule.internalSphere.Colliding(triangles.BoundingAABB) {
return nil
}
triTrans := triangles.Transform()
invertedTransform := triTrans.Inverted()
transformNoLoc := triTrans.SetRow(3, vector.Vector{0, 0, 0, 1})
capsuleRadius := capsule.WorldRadius() * math.Abs(math.Max(invertedTransform[0][0], math.Max(invertedTransform[1][1], invertedTransform[2][2])))
capsuleTop := invertedTransform.MultVec(capsule.lineTop())
capsuleBottom := invertedTransform.MultVec(capsule.lineBottom())
capsulePosition := invertedTransform.MultVec(capsule.WorldPosition())
capsuleLine := capsuleTop.Sub(capsuleBottom)
capSpread := capsuleLine.Magnitude() + capsuleRadius
capDot := dot(capsuleLine, capsuleLine)
var closestCapsulePoint vector.Vector
result := newCollision(triangles)
for _, meshPart := range triangles.Mesh.MeshParts {
mesh := meshPart.Mesh
for i := meshPart.TriangleStart; i < meshPart.TriangleEnd; i++ {
tri := mesh.Triangles[i]
// TODO: Replace this with an actual octree or something; the triangles should be spatially segmented into areas where a colliding object
// only has to check triangles in the nearby cells.
if fastVectorSub(capsulePosition, tri.Center).Magnitude() > tri.MaxSpan+capSpread {
continue
}
if fastVectorDistanceSquared(tri.Center, capsuleTop) < fastVectorDistanceSquared(tri.Center, capsuleBottom) {
closestCapsulePoint = capsuleTop
} else {
closestCapsulePoint = capsuleBottom
}
v0 := mesh.VertexPositions[tri.ID*3]
v1 := mesh.VertexPositions[tri.ID*3+1]
v2 := mesh.VertexPositions[tri.ID*3+2]
closest := closestPointOnTri(closestCapsulePoint, v0, v1, v2)
// Doing this manually to avoid doing as much as possible~
t := dot(closest.Sub(capsuleBottom), capsuleLine) / capDot
t = math.Max(math.Min(t, 1), 0)
spherePos := capsuleBottom.Add(capsuleLine.Scale(t))
delta := fastVectorSub(spherePos, closest)
if mag := delta.Magnitude(); mag <= capsuleRadius {
result.add(
&Intersection{
StartingPoint: closest,
ContactPoint: triangles.Transform().MultVec(closest),
MTV: transformNoLoc.MultVec(delta.Unit().Scale(capsuleRadius - mag)),
Triangle: tri,
Normal: transformNoLoc.MultVec(tri.Normal).Unit(),
},
)
}
}
}
if len(result.Intersections) == 0 {
return nil
}
result.sortResults()
return result
}
func commonCollisionTest(node INode, dx, dy, dz float64, others ...BoundingObject) []*Collision {
var ogPos vector.Vector
// If dx, dy, and dz are 0, we don't need to reposition the node for the collision test.
if dx != 0 && dy != 0 && dz != 0 {
ogPos = node.WorldPosition()
node.Move(dx, dy, dz)
}
intersections := []*Collision{}
for _, o := range others {
if result := node.(BoundingObject).Collision(o); result != nil {
intersections = append(intersections, result)
}
}
// Sort the IntersectionResults by distance (closer intersections come up "sooner").
sort.Slice(intersections, func(i, j int) bool {
return fastVectorDistanceSquared(intersections[i].AverageContactPoint(), intersections[i].Intersections[0].StartingPoint) >
fastVectorDistanceSquared(intersections[j].AverageContactPoint(), intersections[j].Intersections[0].StartingPoint)
})
if dx != 0 && dy != 0 && dz != 0 {
for _, result := range intersections {
for _, hit := range result.Intersections {
hit.MTV[0] -= dx
hit.MTV[1] -= dy
hit.MTV[2] -= dz
}
}
node.SetWorldPosition(ogPos)
}
return intersections
}
type projection struct {
Min, Max float64
}
func project(axis vector.Vector, points ...vector.Vector) projection {
projection := projection{}
projection.Min = dot(axis, points[0])
projection.Max = projection.Min
for _, point := range points[1:] {
p := dot(axis, point)
if p < projection.Min {
projection.Min = p
} else if p > projection.Max {
projection.Max = p
}
}
// margin := 0.01
// projection.Min -= margin
// projection.Max += margin
return projection
}
func (projection projection) Overlap(other projection) float64 {
if !projection.IsOverlapping(other) {
return 0
}
if projection.Max > other.Min {
return projection.Max - other.Min
}
return projection.Min - other.Max
}
func (projection projection) IsOverlapping(other projection) bool {
return !(projection.Min > other.Max || other.Min > projection.Max)
}