-
Notifications
You must be signed in to change notification settings - Fork 17
/
nav_mesh.cpp.go
2051 lines (1843 loc) · 58.1 KB
/
nav_mesh.cpp.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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package unityai
import (
"math"
"reflect"
"sort"
"unsafe"
)
type PortalArea struct {
min, max float32
}
func GetWorldTileBounds(tile NavMeshTile) MinMaxAABB {
Assert(tile.header != nil)
tileBounds := NewMinMaxAABB(tile.header.bmin, tile.header.bmax)
if tile.transformed != 0 {
var mat Matrix4x4f
mat.SetTR(tile.position, tile.rotation)
TransformAABBSlow(tileBounds, mat, &tileBounds)
}
return tileBounds
}
func OverlapSlabs(amin Vector2f, amax Vector2f, bmin Vector2f, bmax Vector2f, px float32, py float32) bool {
// Check for horizontal overlap.
// The segment is shrunken a little so that slabs which touch
// at end points are not connected.
minx := FloatMax(amin.x+px, bmin.x+px)
maxx := FloatMin(amax.x-px, bmax.x-px)
if minx > maxx {
return false
}
// Check vertical overlap.
ad := (amax.y - amin.y) / (amax.x - amin.x)
ak := amin.y - ad*amin.x
bd := (bmax.y - bmin.y) / (bmax.x - bmin.x)
bk := bmin.y - bd*bmin.x
aminy := ad*minx + ak
amaxy := ad*maxx + ak
bminy := bd*minx + bk
bmaxy := bd*maxx + bk
dmin := bminy - aminy
dmax := bmaxy - amaxy
// Crossing segments always overlap.
if dmin*dmax < 0 {
return true
}
// Check for overlap at endpoints.
thr := Sqr(py * 2)
if dmin*dmin <= thr || dmax*dmax <= thr {
return true
}
return false
}
func OverlapDetailSlabs(aslabs []Vector2f, acount int32, bslabs []Vector2f, bcount int32, px float32, py float32) bool {
for i := int32(0); i < acount-1; i++ {
amin := aslabs[i]
amax := aslabs[i+1]
for j := int32(0); j < bcount-1; j++ {
bmin := bslabs[j]
bmax := bslabs[j+1]
if OverlapSlabs(amin, amax, bmin, bmax, px, py) {
return true
}
}
}
return false
}
func GetSlabCoord(va Vector3f, side int32) float32 {
if side == 0 || side == 4 {
return va.x
} else if side == 2 || side == 6 {
return va.z
}
return 0
}
func MakeDetailEdgeSlabs(slabs []Vector2f, pts []Vector3f, npts int32, side int32) {
va := pts[0]
vb := pts[npts-1]
if side == 0 || side == 4 {
if va.z < vb.z {
for i := int32(0); i < npts; i++ {
slabs[i].x = pts[i].z
slabs[i].y = pts[i].y
}
} else {
for i := int32(0); i < npts; i++ {
slabs[i].x = pts[npts-1-i].z
slabs[i].y = pts[npts-1-i].y
}
}
} else if side == 2 || side == 6 {
if va.x < vb.x {
for i := int32(0); i < npts; i++ {
slabs[i].x = pts[i].x
slabs[i].y = pts[i].y
}
} else {
for i := int32(0); i < npts; i++ {
slabs[i].x = pts[npts-1-i].x
slabs[i].y = pts[npts-1-i].y
}
}
} else {
// fix warning of uninitialized bmin, bmax
Assert(false)
for i := int32(0); i < npts; i++ {
slabs[i].x = 0
slabs[i].y = 0
}
}
}
func OppositeTile(side int32) int32 {
return (side + 4) & 0x7
}
func NeighbourLocation(x *int32, y *int32, side int32) {
nx := *x
ny := *y
switch side {
case 0:
nx++
case 1:
nx++
ny++
case 2:
ny++
case 3:
nx--
ny++
case 4:
nx--
case 5:
nx--
ny--
case 6:
ny--
case 7:
nx++
ny--
}
*x = nx
*y = ny
}
// It's assumed the triangle (a,b,c) is not degenerate - otherwise division by zero might occur
func ClosestPtPointTriangle(p Vector3f, a Vector3f, b Vector3f, c Vector3f) Vector3f {
// Check if P in vertex region outside A
ab := b.Sub(a)
ac := c.Sub(a)
ap := p.Sub(a)
d1 := DotVector3f(ab, ap)
d2 := DotVector3f(ac, ap)
if d1 <= 0.0 && d2 <= 0.0 {
// barycentric coordinates (1,0,0)
return a
}
// Check if P in vertex region outside B
bp := p.Sub(b)
d3 := DotVector3f(ab, bp)
d4 := DotVector3f(ac, bp)
if d3 >= 0.0 && d4 <= d3 {
// barycentric coordinates (0,1,0)
return b
}
// Check if P in edge region of AB, if so return projection of P onto AB
vc := d1*d4 - d3*d2
if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
// barycentric coordinates (1-v,v,0)
v := d1 / (d1 - d3)
return a.Add(ab.Mulf(v))
}
// Check if P in vertex region outside C
cp := p.Sub(c)
d5 := DotVector3f(ab, cp)
d6 := DotVector3f(ac, cp)
if d6 >= 0.0 && d5 <= d6 {
// barycentric coordinates (0,0,1)
return c
}
// Check if P in edge region of AC, if so return projection of P onto AC
vb := d5*d2 - d1*d6
if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
// barycentric coordinates (1-w,0,w)
w := d2 / (d2 - d6)
return a.Add(ac.Mulf(w))
}
// Check if P in edge region of BC, if so return projection of P onto BC
va := d3*d6 - d5*d4
if va <= 0.0 && (d4-d3) >= 0.0 && (d5-d6) >= 0.0 {
// barycentric coordinates (0,1-w,w)
w := (d4 - d3) / ((d4 - d3) + (d5 - d6))
return LerpVector3f(b, c, w)
}
// P inside face region. Compute Q through its barycentric coordinates (u,v,w)
denom := 1.0 / (va + vb + vc)
v := vb * denom
w := vc * denom
return a.Add(ab.Mulf(v)).Add(ac.Mulf(w))
}
func OverlapQuantBounds(amin []uint16, amax []uint16, bmin []uint16, bmax []uint16) bool {
overlap := true
if amin[0] > bmax[0] || amax[0] < bmin[0] {
overlap = false
}
if amin[1] > bmax[1] || amax[1] < bmin[1] {
overlap = false
}
if amin[2] > bmax[2] || amax[2] < bmin[2] {
overlap = false
}
return overlap
}
//////////////////////////////////////////////////////////////////////////////////////////
func NewNavMesh() *NavMesh {
mesh := &NavMesh{
m_firstOffMeshConnection: kNavMeshNullLink,
m_timeStamp: 1,
m_SurfaceIDToData: make(map[int32]*SurfaceData),
}
mesh.m_tiles.Init()
mesh.m_links.Init()
mesh.m_offMeshConnections.Init()
return mesh
}
// Creates a surface - set of tiles sharing some data
// Reserves room for tiles belonging for a given surface.
// Params:
// tileCount - (in) number of tiles to reserve memory for.
// settings - (in) settings for tiles belonging to this surface.
//
func (this *NavMesh) CreateSurface(reserveTileCount int, settings NavMeshBuildSettings, pos Vector3f, rot Quaternionf) int32 {
// Find an unused and non-zero id
var id int32
for {
id = NexSurfaceId()
if _, ok := this.m_SurfaceIDToData[id]; ok {
continue
} else {
break
}
}
data := NewSurfaceData()
data.m_Settings = settings
data.m_Position = pos
data.m_Rotation = rot
data.m_TileLUT = make(map[TileLoc]uint32, reserveTileCount)
this.m_SurfaceIDToData[id] = data
return id
}
// Removes a surface
// Params:
// surfaceID - (in) id of surface to remove.
func (this *NavMesh) RemoveSurface(surfaceID int32) {
delete(this.m_SurfaceIDToData, surfaceID)
}
func (this *NavMesh) GetSurfaceSettings(surfaceID int32) *NavMeshBuildSettings {
data, ok := this.m_SurfaceIDToData[surfaceID]
if ok {
return &data.m_Settings
} else {
return nil
}
}
func (this *NavMesh) SetSurfaceSettings(surfaceID int32, settings NavMeshBuildSettings) {
data := this.m_SurfaceIDToData[surfaceID]
data.m_Settings = settings
this.m_SurfaceIDToData[surfaceID] = data
}
func (this *NavMesh) GetSurfaceTransform(surfaceID int32, pos *Vector3f, rot *Quaternionf) NavMeshStatus {
data, ok := this.m_SurfaceIDToData[surfaceID]
if !ok {
return kNavMeshFailure
}
*pos = data.m_Position
*rot = data.m_Rotation
return kNavMeshSuccess
}
const kMaxPoints = 16
// Returns all polygons in neighbour tile based on portal defined by the segment.
func (this *NavMesh) FindConnectingPolys(fromPoints []Vector3f, fromPointCount int32,
tile *NavMeshTile, side int32, con []NavMeshPolyRef, conarea []PortalArea,
maxcon int32, portalHeight float32) int32 {
if tile == nil {
return 0
}
if fromPointCount < 2 {
return 0
}
portalHalfHeight := 0.5 * portalHeight // Slab check is symmetrical (kinda like radius).
var fromSlabs [kMaxPoints]Vector2f
MakeDetailEdgeSlabs(fromSlabs[:], fromPoints, fromPointCount, side)
fromMin := fromSlabs[0]
fromMax := fromSlabs[fromPointCount-1]
fromCoord := GetSlabCoord(fromPoints[0], side)
var toPoints [kMaxPoints]Vector3f
var toSlabs [kMaxPoints]Vector2f
var toPointCount int32 = 0
// Remove links pointing to 'side' and compact the links array.
m := kNavMeshExtLink | uint16(side)
n := int32(0)
base := this.GetPolyRefBase(tile)
for i := int32(0); i < tile.header.polyCount; i++ {
poly := &tile.polys[i]
nv := poly.vertCount
for j := uint8(0); j < nv; j++ {
// Skip edges which do not point to the right side.
if poly.neis[j] != m {
continue
}
// Segments are not close enough along the border.
toCoord := GetSlabCoord(tile.verts[poly.verts[j]], side)
if FloatAbs(fromCoord-toCoord) > 0.01 {
continue
}
this.GetPolyEdgeDetailPoints(tile, i, int32(j), toPoints[:], &toPointCount, kMaxPoints)
if toPointCount == 0 {
continue
}
MakeDetailEdgeSlabs(toSlabs[:], toPoints[:], toPointCount, side)
toMin := toSlabs[0]
toMax := toSlabs[toPointCount-1]
// Check if the segments touch.
if !OverlapDetailSlabs(fromSlabs[:], fromPointCount, toSlabs[:], toPointCount, 0.01, portalHalfHeight) {
continue
}
// Add return value.
if n < maxcon {
conarea[n].min = FloatMax(fromMin.x, toMin.x)
conarea[n].max = FloatMin(fromMax.x, toMax.x)
con[n] = base | EncodeBasePolyId(kPolyTypeGround, uint32(i))
n++
}
break
}
}
return n
}
func (this *NavMesh) RemoveLinkBetween(from NavMeshPolyRef, to NavMeshPolyRef) {
if DecodePolyIdType(from) == kPolyTypeOffMeshConnection {
con := this.GetOffMeshConnectionUnsafe(from)
if con != nil {
// Remove link from connect polygon.
k := con.firstLink
pk := kNavMeshNullLink
for k != kNavMeshNullLink {
if this.m_links.Get(k).ref == to {
nk := this.m_links.Get(k).next
if pk == kNavMeshNullLink {
con.firstLink = nk
} else {
Assert(pk != nk)
this.m_links.Get(pk).next = nk
}
con.endPoints[this.m_links.Get(k).edge].tileRef = 0
this.m_links.Release(k)
break
}
pk = k
k = this.m_links.Get(k).next
}
}
} else {
var neiTile *NavMeshTile
var neiPoly *NavMeshPoly
if NavMeshStatusSucceed(this.GetTileAndPolyByRef(from, &neiTile, &neiPoly)) {
// Remove link from connect polygon.
ip := GetPolyIndex(neiTile, neiPoly)
k := uint32(neiTile.polyLinks[ip])
pk := kNavMeshNullLink
for k != kNavMeshNullLink {
if this.m_links.Get(k).ref == to {
nk := this.m_links.Get(k).next
if pk == kNavMeshNullLink {
neiTile.polyLinks[ip] = nk
} else {
Assert(pk != nk)
this.m_links.Get(pk).next = nk
}
this.m_links.Release(k)
break
}
pk = k
k = this.m_links.Get(k).next
}
}
}
}
// Removes all internal and external links from a tile.
func (this *NavMesh) UnconnectLinks(tile *NavMeshTile) {
Assert(tile != nil)
Assert(tile.header != nil)
Assert(tile.polyLinks != nil)
base := this.GetPolyRefBase(tile)
for i := int32(0); i < tile.header.polyCount; i++ {
polyRef := base | EncodeBasePolyId(kPolyTypeGround, uint32(i))
j := tile.polyLinks[i]
for j != kNavMeshNullLink {
next := this.m_links.Get(j).next
// Remove link to this polygon
this.RemoveLinkBetween(this.m_links.Get(j).ref, polyRef)
this.m_links.Release(j)
j = next
}
tile.polyLinks[i] = kNavMeshNullLink
}
}
type EdgePointSample struct {
t float32
pt Vector3f
}
type EdgePointSamples []EdgePointSample
var _ sort.Interface = EdgePointSamples{}
func (this EdgePointSamples) Len() int {
return len(this)
}
func (this EdgePointSamples) Less(i, j int) bool {
return this[i].t < this[j].t
}
func (this EdgePointSamples) Swap(i, j int) {
this[i], this[j] = this[j], this[i]
}
const kMaxSamples = 64
// Returns polygon edge points based on detail mesh.
// If 'maxPoints' is less than the number of points on the edge, the edge is simplified.
// Params:
// tile - (in) pointer to tile where the polygon lies.
// poly - (in) polygon index
// edge - (in) edge index
// points - (out) array to store the edge points (maxPoints*3).
// pointCount - (out) number of points stored.
// maxPoints - (in) max number of points that can fit into points, must be >= 2.
func (this *NavMesh) GetPolyEdgeDetailPoints(tile *NavMeshTile, p int32, edge int32,
points []Vector3f, pointCount *int32, maxPoints int32) NavMeshStatus {
Assert(maxPoints > 2)
poly := &tile.polys[p]
pd := &tile.detailMeshes[p]
ndv := pd.vertCount
vertCount := poly.vertCount
v0 := tile.verts[poly.verts[edge]]
v1 := tile.verts[poly.verts[NextIndex(edge, int32(vertCount))]]
var samples [kMaxSamples]EdgePointSample
// Add first edge vertex
samples[0].t = 0.0
samples[0].pt = v0
sampleCount := int32(1)
// Collect detail vertices close to the edge.
// adds up to kMaxSamples-2 detail vertices.
if ndv != 0 {
EPS := float32(0.0001)
dvx := v1.x - v0.x
dvz := v1.z - v0.z
lenSq := dvx*dvx + dvz*dvz
if lenSq < EPS {
*pointCount = 0
return kNavMeshFailure
}
distanceThr := Sqr(0.01)
nrm := 1.0 / lenSq
dverts := tile.detailVerts[pd.vertBase:]
for i := 0; i < int(ndv); i++ {
dv := dverts[i]
dpx := dv.x - v0.x
dpz := dv.z - v0.z
t := FloatClamp((dvx*dpx+dvz*dpz)*nrm, 0.0, 1.0)
// Skip points projected to end points of edge
if t < EPS || t > (1.0-EPS) {
continue
}
// Skip points not close to edge
x := t*dvx - dpx
z := t*dvz - dpz
distSqr := x*x + z*z
if distSqr > distanceThr {
continue
}
// Accept and add point.
samples[sampleCount].t = t
samples[sampleCount].pt = dv
sampleCount++
// Leave room for last vertex
if sampleCount == kMaxSamples-1 {
break
}
}
// Order the collected detail vertices
sort.Sort(EdgePointSamples(samples[1:sampleCount]))
}
// Add last edge vertex
samples[sampleCount].t = 1.0
samples[sampleCount].pt = v1
sampleCount++
// Simplify if needed.
for sampleCount > maxPoints {
// Find
removeIdx := int32(-1)
minDist := float32(math.MaxFloat32)
for i := int32(1); i < sampleCount-1; i++ {
var t float32
d := SqrDistancePointSegment(&t, samples[i].pt, samples[i-1].pt, samples[i+1].pt)
if d < minDist {
minDist = d
removeIdx = i
}
}
// Remove removeIdx
for i := removeIdx; i < sampleCount-1; i++ {
samples[i] = samples[i+1]
}
sampleCount--
}
for i := int32(0); i < sampleCount; i++ {
points[i] = samples[i].pt
}
*pointCount = sampleCount
return kNavMeshSuccess
}
// Builds external polygon links for a tile.
func (this *NavMesh) ConnectExtLinks(tile *NavMeshTile, target *NavMeshTile, side int32, portalHeight float32) {
if tile == nil {
return
}
// Unity specific: Do not connect tiles from different surfaces.
// We expect each navmesh surface to be separate and connected to each other only via off-mesh connections.
if tile.surfaceID != target.surfaceID {
return
}
// Connect border links.
for i := int32(0); i < tile.header.polyCount; i++ {
poly := &tile.polys[i]
nv := poly.vertCount
for j := uint8(0); j < nv; j++ {
// Skip non-portal edges.
if (poly.neis[j] & kNavMeshExtLink) == 0 {
continue
}
dir := poly.neis[j] & 0xff
if side != -1 && dir != uint16(side) {
continue
}
// Create new links
va := tile.verts[poly.verts[j]]
vb := tile.verts[poly.verts[NextIndex(int32(j), int32(nv))]]
var points [kMaxPoints]Vector3f
var pointCount = int32(0)
this.GetPolyEdgeDetailPoints(tile, i, int32(j), points[:], &pointCount, kMaxPoints)
var nei [4]NavMeshPolyRef
var neia [4]PortalArea
nnei := this.FindConnectingPolys(points[:], pointCount, target, OppositeTile(int32(dir)), nei[:], neia[:], 4, portalHeight)
for k := int32(0); k < nnei; k++ {
idx := this.m_links.Alloc()
if idx != kNavMeshNullLink {
link := this.m_links.Get(idx)
link.ref = nei[k]
link.edge = j
link.side = uint8(dir)
Assert(idx != tile.polyLinks[i])
link.next = tile.polyLinks[i]
tile.polyLinks[i] = idx
// Compress portal limits to a byte value.
if dir == 0 || dir == 4 {
tmin := (neia[k].min - va.z) / (vb.z - va.z)
tmax := (neia[k].max - va.z) / (vb.z - va.z)
if tmin > tmax {
tmin, tmax = tmax, tmin
}
link.bmin = uint8(FloatClamp(tmin, 0.0, 1.0) * 255.0)
link.bmax = uint8(FloatClamp(tmax, 0.0, 1.0) * 255.0)
} else if dir == 2 || dir == 6 {
tmin := (neia[k].min - va.x) / (vb.x - va.x)
tmax := (neia[k].max - va.x) / (vb.x - va.x)
if tmin > tmax {
tmin, tmax = tmax, tmin
}
link.bmin = uint8(FloatClamp(tmin, 0.0, 1.0) * 255.0)
link.bmax = uint8(FloatClamp(tmax, 0.0, 1.0) * 255.0)
}
}
}
}
}
}
// Builds internal polygons links for a tile.
func (this *NavMesh) ConnectIntLinks(tile *NavMeshTile) {
Assert(tile != nil)
Assert(tile.header != nil)
polyCount := tile.header.polyCount
// Allocate and nullify per poly links
Assert(tile.polyLinks == nil)
tile.polyLinks = make([]uint32, polyCount)
for i := int32(0); i < polyCount; i++ {
tile.polyLinks[i] = kNavMeshNullLink
}
base := this.GetPolyRefBase(tile)
for i := int32(0); i < polyCount; i++ {
poly := &tile.polys[i]
// Build edge links backwards so that the links will be
// in the linked list from lowest index to highest.
for j := int32(poly.vertCount) - 1; j >= 0; j-- {
// Skip hard and non-internal edges.
if poly.neis[j] == 0 || (poly.neis[j]&kNavMeshExtLink) != 0 {
continue
}
idx := this.m_links.Alloc()
if idx != kNavMeshNullLink {
link := this.m_links.Get(idx)
link.ref = base | EncodeBasePolyId(kPolyTypeGround, uint32(poly.neis[j]-1))
link.edge = uint8(j)
link.side = 0xff
link.bmin = 0
link.bmax = 0
// Add to linked list.
Assert(idx != tile.polyLinks[i])
link.next = tile.polyLinks[i]
tile.polyLinks[i] = idx
}
}
}
}
// Returns closest point on polygon.
func (this *NavMesh) ClosestPointOnPolyInTileLocal(tile *NavMeshTile, poly *NavMeshPoly, pos Vector3f, closest *Vector3f) {
ip := GetPolyIndex(tile, poly)
pd := &tile.detailMeshes[ip]
closestDistSqr := float32(math.MaxFloat32)
for j := 0; j < int(pd.triCount); j++ {
t := tile.detailTris[(int(pd.triBase)+j)*4:]
var v [3]Vector3f
for k := 0; k < 3; k++ {
if uint8(t[k]) < poly.vertCount {
v[k] = tile.verts[poly.verts[t[k]]]
} else {
v[k] = tile.detailVerts[uint8(pd.vertBase)+(uint8(t[k])-poly.vertCount)]
}
}
pt := ClosestPtPointTriangle(pos, v[0], v[1], v[2])
d := SqrDistance(pos, pt)
if d < closestDistSqr {
*closest = pt
closestDistSqr = d
}
}
}
type NearestQuery struct {
m_NavMesh *NavMesh
m_PolyRef NavMeshPolyRef
m_DistanceSqr float32
m_Center Vector3f
m_Point Vector3f
}
func NewNearestQuery(navmesh *NavMesh, center Vector3f) NearestQuery {
return NearestQuery{
navmesh, 0, math.MaxFloat32, center, Vector3f{0, 0, 0},
}
}
func (this *NearestQuery) ProcessPolygons(tile *NavMeshTile, polyRefs []NavMeshPolyRef, polys []*NavMeshPoly, itemCount int) {
localPosition := WorldToTile(tile, this.m_Center)
// Find nearest polygon amongst the nearby polygons.
for i := 0; i < itemCount; i++ {
ref := polyRefs[i]
poly := polys[i]
var closestPtPoly Vector3f
this.m_NavMesh.ClosestPointOnPolyInTileLocal(tile, poly, localPosition, &closestPtPoly)
d := SqrDistance(localPosition, closestPtPoly)
if d < this.m_DistanceSqr {
this.m_Point = closestPtPoly
this.m_DistanceSqr = d
this.m_PolyRef = ref
}
}
}
// Find nearest polygon within a tile.
func (this *NavMesh) FindNearestPoly(typeID int32, center Vector3f, extents Vector3f, nearestPt *Vector3f) NavMeshPolyRef {
// Get nearby polygons from proximity grid.
nearest := NewNearestQuery(this, center)
this.QueryPolygons(typeID, center, extents, &nearest)
if nearest.m_PolyRef == 0 {
return 0
}
if nearestPt != nil {
tile := this.GetTileByRef(NavMeshTileRef(nearest.m_PolyRef))
if tile != nil {
*nearestPt = TileToWorld(tile, nearest.m_Point)
}
}
return nearest.m_PolyRef
}
// Returns polygons which overlap the query box.
// Params:
// typeID - (in) query surfaces with this id. -1 means query all surfaces.
// center[3] - (in) the center of the search box.
// extents[3] - (in) the extents of the search box.
// callback - (in/out) pointer to callback interface to batch-process the results, see NavMeshProcessCallback.
func (this *NavMesh) QueryPolygons(typeID int32, cen Vector3f, ext Vector3f, callback NavMeshProcessCallback) {
bounds := NewMinMaxAABB(cen.Sub(ext), cen.Add(ext))
for _, surf := range this.m_SurfaceIDToData {
if typeID != -1 && typeID != surf.m_Settings.agentTypeID {
continue
}
var overlap MinMaxAABB
if !IntersectionAABBAABB(bounds, surf.m_WorldBounds, &overlap) {
continue
}
var localBounds AABB
InverseTransformAABB(NewAABBFromMinMax(overlap), surf.m_Position, surf.m_Rotation, &localBounds)
invTileSize := 1.0 / (float32(surf.m_Settings.tileSize) * surf.m_Settings.cellSize)
iminx := FloorfToInt((localBounds.m_Center.x - localBounds.m_Extent.x) * invTileSize)
imaxx := FloorfToInt((localBounds.m_Center.x + localBounds.m_Extent.x) * invTileSize)
jminz := FloorfToInt((localBounds.m_Center.z - localBounds.m_Extent.z) * invTileSize)
jmaxz := FloorfToInt((localBounds.m_Center.z + localBounds.m_Extent.z) * invTileSize)
for i := iminx; i <= imaxx; i++ {
for j := jminz; j <= jmaxz; j++ {
key := TileLoc{i, j}
tileIndex, ok := surf.m_TileLUT[key]
if !ok {
continue
}
this.QueryPolygonsInTile(this.m_tiles.Get(tileIndex), localBounds.m_Center, localBounds.m_Extent, callback)
}
}
}
}
const kBufferSize = 32
// Queries polygons within a tile.
func (this *NavMesh) QueryPolygonsInTile(tile *NavMeshTile, center Vector3f, extents Vector3f, callback NavMeshProcessCallback) {
var polyRefs [kBufferSize]NavMeshPolyRef
var polys [kBufferSize]*NavMeshPoly
qmin := center.Sub(extents)
qmax := center.Add(extents)
if tile.bvTree != nil {
offset := int32(0)
node := &tile.bvTree[offset]
// The final node is garbage as we allocate 2*polyCount but need one less for the tree.
// Here we make sure the end node is not reached by subtracting 1
end := &tile.bvTree[tile.header.bvNodeCount-1]
tbmin := tile.header.bmin
tbmax := tile.header.bmax
qfac := tile.header.bvQuantFactor
// Calculate quantized box
var bmin, bmax [3]uint16
// FloatClamp query box to world box.
minx := FloatClamp(qmin.x, tbmin.x, tbmax.x) - tbmin.x
miny := FloatClamp(qmin.y, tbmin.y, tbmax.y) - tbmin.y
minz := FloatClamp(qmin.z, tbmin.z, tbmax.z) - tbmin.z
maxx := FloatClamp(qmax.x, tbmin.x, tbmax.x) - tbmin.x
maxy := FloatClamp(qmax.y, tbmin.y, tbmax.y) - tbmin.y
maxz := FloatClamp(qmax.z, tbmin.z, tbmax.z) - tbmin.z
// Quantize
bmin[0] = uint16(qfac*minx) & 0xfffe
bmin[1] = uint16(qfac*miny) & 0xfffe
bmin[2] = uint16(qfac*minz) & 0xfffe
bmax[0] = uint16(qfac*maxx+1) | 1
bmax[1] = uint16(qfac*maxy+1) | 1
bmax[2] = uint16(qfac*maxz+1) | 1
// Traverse tree
base := this.GetPolyRefBase(tile)
n := 0
for uintptr(unsafe.Pointer(node)) < uintptr(unsafe.Pointer(end)) {
overlap := OverlapQuantBounds(bmin[:], bmax[:], node.bmin[:], node.bmax[:])
isLeafNode := node.i >= 0
if isLeafNode && overlap {
if n >= kBufferSize {
callback.ProcessPolygons(tile, polyRefs[:], polys[:], n)
n = 0
}
polyRefs[n] = base | EncodeBasePolyId(kPolyTypeGround, uint32(node.i))
polys[n] = &tile.polys[node.i]
n++
}
if overlap || isLeafNode {
offset++
node = &tile.bvTree[offset]
} else {
escapeIndex := -node.i
offset += escapeIndex
node = &tile.bvTree[offset]
}
}
if n > 0 {
callback.ProcessPolygons(tile, polyRefs[:], polys[:], n)
}
} else {
var bmin, bmax Vector3f
n := 0
base := this.GetPolyRefBase(tile)
for i := int32(0); i < tile.header.polyCount; i++ {
// Calc polygon bounds.
p := &tile.polys[i]
bmax = tile.verts[p.verts[0]]
bmin = bmax
for j := uint8(1); j < p.vertCount; j++ {
v := tile.verts[p.verts[j]]
bmin = MinVector3f(bmin, v)
bmax = MaxVector3f(bmax, v)
}
if OverlapBounds(qmin, qmax, bmin, bmax) {
if n >= kBufferSize {
callback.ProcessPolygons(tile, polyRefs[:], polys[:], n)
n = 0
}
polyRefs[n] = base | EncodeBasePolyId(kPolyTypeGround, uint32(i))
polys[n] = p
n++
}
}
if n > 0 {
callback.ProcessPolygons(tile, polyRefs[:], polys[:], n)
}
}
}
// Adds new tile into the navmesh.
// The add will fail if the data is in wrong format,
// there is not enough tiles left, or if there is a tile already at the location.
// Params:
// data - (in) Data of the new tile mesh.
// dataSize - (in) Data size of the new tile mesh.
// flags - (in) Tile flags, see NavMeshTileFlags.
// surfaceID - (in) surface identifier for the tile.
// result - (out,optional) tile ref if the tile was successfully added.
func (this *NavMesh) AddTile(data []byte, dataSize int32, flags NavMeshTileFlags, surfaceID int32, result *NavMeshTileRef) NavMeshStatus {
// Make sure the data is in right format.
header := (*NavMeshDataHeader)(unsafe.Pointer(&(data[0])))
if header.magic != kNavMeshMagic {
return kNavMeshFailure | kNavMeshWrongMagic
}
if header.version != kNavMeshVersion {
return kNavMeshFailure | kNavMeshWrongVersion
}
// Patch header pointers.
headerSize := Align4(unsafe.Sizeof(NavMeshDataHeader{}))
vertsSize := Align4(unsafe.Sizeof(Vector3f{}) * uintptr(header.vertCount))
polysSize := Align4(unsafe.Sizeof(NavMeshPoly{}) * uintptr(header.polyCount))
detailMeshesSize := Align4(unsafe.Sizeof(NavMeshPolyDetail{}) * uintptr(header.detailMeshCount))
detailVertsSize := Align4(unsafe.Sizeof(Vector3f{}) * uintptr(header.detailVertCount))
detailTrisSize := Align4(unsafe.Sizeof(NavMeshPolyDetailIndex(0)) * 4 * uintptr(header.detailTriCount))
bvtreeSize := Align4(unsafe.Sizeof(NavMeshBVNode{}) * uintptr(header.bvNodeCount))
d := headerSize
var verts []Vector3f
sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&(verts)))
sliceHeader.Cap = int(header.vertCount)
sliceHeader.Len = int(header.vertCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += vertsSize
var polys []NavMeshPoly
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(polys)))
sliceHeader.Cap = int(header.polyCount)
sliceHeader.Len = int(header.polyCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += polysSize
var detailMeshes []NavMeshPolyDetail
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(detailMeshes)))
sliceHeader.Cap = int(header.detailMeshCount)
sliceHeader.Len = int(header.detailMeshCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += detailMeshesSize
var detailVerts []Vector3f
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(detailVerts)))
sliceHeader.Cap = int(header.detailVertCount)
sliceHeader.Len = int(header.detailVertCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += detailVertsSize
var detailTris []NavMeshPolyDetailIndex
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(detailTris)))
sliceHeader.Cap = int(header.detailTriCount * 4)
sliceHeader.Len = int(header.detailTriCount * 4)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += detailTrisSize
var bvTree []NavMeshBVNode
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(bvTree)))
sliceHeader.Cap = int(header.bvNodeCount)
sliceHeader.Len = int(header.bvNodeCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += bvtreeSize
if d != uint32(dataSize) {
println(d, dataSize)
return kNavMeshFailure
}
// Allocate a tile.
newTileIndex := this.m_tiles.Alloc()
// Make sure we could allocate a tile.
if newTileIndex == kNavMeshNullLink {
return kNavMeshFailure | kNavMeshOutOfMemory
}
_, ok := this.m_SurfaceIDToData[surfaceID]
Assert(ok)
tile := this.m_tiles.Get(newTileIndex)
// Insert tile into the position lut.
surfaceData := this.m_SurfaceIDToData[surfaceID]
lut := surfaceData.m_TileLUT
lut[TileLoc{header.x, header.y}] = newTileIndex
position := surfaceData.m_Position
rotation := surfaceData.m_Rotation
// Consider: Post process all these
var tileWorldBounds AABB
tilebounds := NewMinMaxAABB(header.bmin, header.bmax)
TransformAABB(NewAABBFromMinMax(tilebounds), position, rotation, &tileWorldBounds)
surfaceData.m_WorldBounds.Encapsulate(NewMinMaxAABBFromAABB(tileWorldBounds))
// Patch header pointers.
tile.verts = verts
tile.polys = polys
tile.detailMeshes = detailMeshes
tile.detailVerts = detailVerts
tile.detailTris = detailTris
tile.bvTree = bvTree
// If there are no items in the bvtree, reset the tree pointer.
if bvtreeSize == 0 {