-
Notifications
You must be signed in to change notification settings - Fork 3
/
RN_DetourNavMesh.pas
2312 lines (1966 loc) · 78.6 KB
/
RN_DetourNavMesh.pas
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
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_DetourNavMesh;
interface
uses
Classes, Math, RN_DetourNode, RN_DetourNavMeshHelper, RN_DetourCommon, RN_DetourStatus;
/// The maximum number of vertices per navigation polygon.
/// @ingroup detour
const DT_VERTS_PER_POLYGON = 6;
/// @{
/// @name Tile Serialization Constants
/// These constants are used to detect whether a navigation tile's data
/// and state format is compatible with the current build.
///
/// A magic number used to detect compatibility of navigation tile data.
const DT_NAVMESH_MAGIC = Ord('D') shl 24 or Ord('N') shl 16 or Ord('A') shl 8 or Ord('V');
/// A version number used to detect compatibility of navigation tile data.
const DT_NAVMESH_VERSION = 7;
/// A magic number used to detect the compatibility of navigation tile states.
const DT_NAVMESH_STATE_MAGIC = Ord('D') shl 24 or Ord('N') shl 16 or Ord('M') shl 8 or Ord('S');
/// A version number used to detect compatibility of navigation tile states.
const DT_NAVMESH_STATE_VERSION = 1;
/// @}
/// A flag that indicates that an entity links to an external entity.
/// (E.g. A polygon edge is a portal that links to another polygon.)
const DT_EXT_LINK = $8000;
/// A value that indicates the entity does not link to anything.
const DT_NULL_LINK = $ffffffff;
/// A flag that indicates that an off-mesh connection can be traversed in both directions. (Is bidirectional.)
const DT_OFFMESH_CON_BIDIR = 1;
/// The maximum number of user defined area ids.
/// @ingroup detour
const DT_MAX_AREAS = 64;
/// Tile flags used for various functions and fields.
/// For an example, see dtNavMesh::addTile().
//TdtTileFlags =
/// The navigation mesh owns the tile memory and is responsible for freeing it.
DT_TILE_FREE_DATA = $01;
type
/// Vertex flags returned by dtNavMeshQuery::findStraightPath.
TdtStraightPathFlags =
(
DT_STRAIGHTPATH_START = $01, ///< The vertex is the start position in the path.
DT_STRAIGHTPATH_END = $02, ///< The vertex is the end position in the path.
DT_STRAIGHTPATH_OFFMESH_CONNECTION = $04 ///< The vertex is the start of an off-mesh connection.
);
/// Options for dtNavMeshQuery::findStraightPath.
TdtStraightPathOptions =
(
DT_STRAIGHTPATH_AREA_CROSSINGS = $01, ///< Add a vertex at every polygon edge crossing where area changes.
DT_STRAIGHTPATH_ALL_CROSSINGS = $02 ///< Add a vertex at every polygon edge crossing.
);
/// Options for dtNavMeshQuery::findPath
TdtFindPathOptions =
(
DT_FINDPATH_LOW_QUALITY_FAR = $01, ///< [provisional] trade quality for performance far from the origin. The idea is that by then a new query will be issued
DT_FINDPATH_ANY_ANGLE = $02 ///< use raycasts during pathfind to "shortcut" (raycast still consider costs)
);
/// Options for dtNavMeshQuery::raycast
TdtRaycastOptions =
(
DT_RAYCAST_USE_COSTS = $01 ///< Raycast should calculate movement cost along the ray and fill RaycastHit::cost
);
/// Limit raycasting during any angle pahfinding
/// The limit is given as a multiple of the character radius
const DT_RAY_CAST_LIMIT_PROPORTIONS = 50.0;
/// Flags representing the type of a navigation mesh polygon.
//dtPolyTypes =
/// The polygon is a standard convex polygon that is part of the surface of the mesh.
DT_POLYTYPE_GROUND = 0;
/// The polygon is an off-mesh connection consisting of two vertices.
DT_POLYTYPE_OFFMESH_CONNECTION = 1;
type
/// Defines a polyogn within a dtMeshTile object.
/// @ingroup detour
PPdtPoly = ^PdtPoly;
PdtPoly = ^TdtPoly;
TdtPoly = record
/// Index to first link in linked list. (Or #DT_NULL_LINK if there is no link.)
firstLink: Cardinal;
/// The indices of the polygon's vertices.
/// The actual vertices are located in dtMeshTile::verts.
verts: array [0..DT_VERTS_PER_POLYGON-1] of Word;
/// Packed data representing neighbor polygons references and flags for each edge.
neis: array [0..DT_VERTS_PER_POLYGON-1] of Word;
/// The user defined polygon flags.
flags: Word;
/// The number of vertices in the polygon.
vertCount: Byte;
/// The bit packed area id and polygon type.
/// @note Use the structure's set and get methods to acess this value.
areaAndtype: Byte;
/// Sets the user defined area id. [Limit: < #DT_MAX_AREAS]
procedure setArea(a: Byte);
/// Sets the polygon type. (See: #dtPolyTypes.)
procedure setType(t: Byte);
/// Gets the user defined area id.
function getArea(): Byte;
/// Gets the polygon type. (See: #dtPolyTypes)
function getType(): Byte;
end;
/// Defines the location of detail sub-mesh data within a dtMeshTile.
PdtPolyDetail = ^TdtPolyDetail;
TdtPolyDetail = record
vertBase: Cardinal; ///< The offset of the vertices in the dtMeshTile::detailVerts array.
triBase: Cardinal; ///< The offset of the triangles in the dtMeshTile::detailTris array.
vertCount: Byte; ///< The number of vertices in the sub-mesh.
triCount: Byte; ///< The number of triangles in the sub-mesh.
end;
/// Defines a link between polygons.
/// @note This structure is rarely if ever used by the end user.
/// @see dtMeshTile
PdtLink = ^TdtLink;
TdtLink = record
ref: TdtPolyRef; ///< Neighbour reference. (The neighbor that is linked to.)
next: Cardinal; ///< Index of the next link.
edge: Byte; ///< Index of the polygon edge that owns this link.
side: Byte; ///< If a boundary link, defines on which side the link is.
bmin: Byte; ///< If a boundary link, defines the minimum sub-edge area.
bmax: Byte; ///< If a boundary link, defines the maximum sub-edge area.
end;
/// Bounding volume node.
/// @note This structure is rarely if ever used by the end user.
/// @see dtMeshTile
PdtBVNode = ^TdtBVNode;
TdtBVNode = record
bmin: array [0..2] of Word; ///< Minimum bounds of the node's AABB. [(x, y, z)]
bmax: array [0..2] of Word; ///< Maximum bounds of the node's AABB. [(x, y, z)]
i: Integer; ///< The node's index. (Negative for escape sequence.)
end;
/// Defines an navigation mesh off-mesh connection within a dtMeshTile object.
/// An off-mesh connection is a user defined traversable connection made up to two vertices.
PdtOffMeshConnection = ^TdtOffMeshConnection;
TdtOffMeshConnection = record
/// The endpoints of the connection. [(ax, ay, az, bx, by, bz)]
pos: array [0..5] of Single;
/// The radius of the endpoints. [Limit: >= 0]
rad: Single;
/// The polygon reference of the connection within the tile.
poly: Word;
/// Link flags.
/// @note These are not the connection's user defined flags. Those are assigned via the
/// connection's dtPoly definition. These are link flags used for internal purposes.
flags: Byte;
/// End point side.
side: Byte;
/// The id of the offmesh connection. (User assigned when the navigation mesh is built.)
userId: Cardinal;
end;
/// Provides high level information related to a dtMeshTile object.
/// @ingroup detour
PdtMeshHeader = ^TdtMeshHeader;
TdtMeshHeader = record
magic: Integer; ///< Tile magic number. (Used to identify the data format.)
version: Integer; ///< Tile data format version number.
x: Integer; ///< The x-position of the tile within the dtNavMesh tile grid. (x, y, layer)
y: Integer; ///< The y-position of the tile within the dtNavMesh tile grid. (x, y, layer)
layer: Integer; ///< The layer of the tile within the dtNavMesh tile grid. (x, y, layer)
userId: Cardinal; ///< The user defined id of the tile.
polyCount: Integer; ///< The number of polygons in the tile.
vertCount: Integer; ///< The number of vertices in the tile.
maxLinkCount: Integer; ///< The number of allocated links.
detailMeshCount: Integer; ///< The number of sub-meshes in the detail mesh.
/// The number of unique vertices in the detail mesh. (In addition to the polygon vertices.)
detailVertCount: Integer;
detailTriCount: Integer; ///< The number of triangles in the detail mesh.
bvNodeCount: Integer; ///< The number of bounding volume nodes. (Zero if bounding volumes are disabled.)
offMeshConCount: Integer; ///< The number of off-mesh connections.
offMeshBase: Integer; ///< The index of the first polygon which is an off-mesh connection.
walkableHeight: Single; ///< The height of the agents using the tile.
walkableRadius: Single; ///< The radius of the agents using the tile.
walkableClimb: Single; ///< The maximum climb height of the agents using the tile.
bmin: array [0..2] of Single; ///< The minimum bounds of the tile's AABB. [(x, y, z)]
bmax: array [0..2] of Single; ///< The maximum bounds of the tile's AABB. [(x, y, z)]
/// The bounding volume quantization factor.
bvQuantFactor: Single;
end;
/// Defines a navigation mesh tile.
/// @ingroup detour
PPdtMeshTile = ^PdtMeshTile;
PdtMeshTile = ^TdtMeshTile;
TdtMeshTile = record
salt: Cardinal; ///< Counter describing modifications to the tile.
linksFreeList: Cardinal; ///< Index to the next free link.
header: PdtMeshHeader; ///< The tile header.
polys: PdtPoly; ///< The tile polygons. [Size: dtMeshHeader::polyCount]
verts: PSingle; ///< The tile vertices. [Size: dtMeshHeader::vertCount]
links: PdtLink; ///< The tile links. [Size: dtMeshHeader::maxLinkCount]
detailMeshes: PdtPolyDetail; ///< The tile's detail sub-meshes. [Size: dtMeshHeader::detailMeshCount]
/// The detail mesh's unique vertices. [(x, y, z) * dtMeshHeader::detailVertCount]
detailVerts: PSingle;
/// The detail mesh's triangles. [(vertA, vertB, vertC) * dtMeshHeader::detailTriCount]
detailTris: PByte;
/// The tile bounding volume nodes. [Size: dtMeshHeader::bvNodeCount]
/// (Will be null if bounding volumes are disabled.)
bvTree: PdtBVNode;
offMeshCons: PdtOffMeshConnection; ///< The tile off-mesh connections. [Size: dtMeshHeader::offMeshConCount]
data: PByte; ///< The tile data. (Not directly accessed under normal situations.)
dataSize: Integer; ///< Size of the tile data.
flags: Integer; ///< Tile flags. (See: #dtTileFlags)
next: PdtMeshTile; ///< The next free tile, or the next tile in the spatial grid.
end;
/// Configuration parameters used to define multi-tile navigation meshes.
/// The values are used to allocate space during the initialization of a navigation mesh.
/// @see dtNavMesh::init()
/// @ingroup detour
PdtNavMeshParams = ^TdtNavMeshParams;
TdtNavMeshParams = record
orig: array [0..2] of Single; ///< The world space origin of the navigation mesh's tile space. [(x, y, z)]
tileWidth: Single; ///< The width of each tile. (Along the x-axis.)
tileHeight: Single; ///< The height of each tile. (Along the z-axis.)
maxTiles: Integer; ///< The maximum number of tiles the navigation mesh can contain.
maxPolys: Integer; ///< The maximum number of polygons each tile can contain.
end;
/// A navigation mesh based on tiles of convex polygons.
/// @ingroup detour
TdtNavMesh = class
public
constructor Create();
destructor Destroy; override;
/// @{
/// @name Initialization and Tile Management
/// Initializes the navigation mesh for tiled use.
/// @param[in] params Initialization parameters.
/// @return The status flags for the operation.
function init(params: PdtNavMeshParams): TdtStatus; overload;
/// Initializes the navigation mesh for single tile use.
/// @param[in] data Data of the new tile. (See: #dtCreateNavMeshData)
/// @param[in] dataSize The data size of the new tile.
/// @param[in] flags The tile flags. (See: #dtTileFlags)
/// @return The status flags for the operation.
/// @see dtCreateNavMeshData
function init(data: PByte; dataSize, flags: Integer): TdtStatus; overload;
/// The navigation mesh initialization params.
function getParams(): PdtNavMeshParams;
/// Adds a tile to the navigation mesh.
/// @param[in] data Data for the new tile mesh. (See: #dtCreateNavMeshData)
/// @param[in] dataSize Data size of the new tile mesh.
/// @param[in] flags Tile flags. (See: #dtTileFlags)
/// @param[in] lastRef The desired reference for the tile. (When reloading a tile.) [opt] [Default: 0]
/// @param[out] result The tile reference. (If the tile was succesfully added.) [opt]
/// @return The status flags for the operation.
function addTile(data: PByte; dataSize, flags: Integer; lastRef: TdtTileRef; reslt: PdtTileRef): TdtStatus;
/// Removes the specified tile from the navigation mesh.
/// @param[in] ref The reference of the tile to remove.
/// @param[out] data Data associated with deleted tile.
/// @param[out] dataSize Size of the data associated with deleted tile.
/// @return The status flags for the operation.
function removeTile(ref: TdtTileRef; data: PPointer; dataSize: PInteger): TdtStatus;
/// @}
/// @{
/// @name Query Functions
/// Calculates the tile grid location for the specified world position.
/// @param[in] pos The world position for the query. [(x, y, z)]
/// @param[out] tx The tile's x-location. (x, y)
/// @param[out] ty The tile's y-location. (x, y)
procedure calcTileLoc(pos: PSingle; tx, ty: PInteger);
/// Gets the tile at the specified grid location.
/// @param[in] x The tile's x-location. (x, y, layer)
/// @param[in] y The tile's y-location. (x, y, layer)
/// @param[in] layer The tile's layer. (x, y, layer)
/// @return The tile, or null if the tile does not exist.
function getTileAt(x, y, layer: Integer): PdtMeshTile;
/// Gets all tiles at the specified grid location. (All layers.)
/// @param[in] x The tile's x-location. (x, y)
/// @param[in] y The tile's y-location. (x, y)
/// @param[out] tiles A pointer to an array of tiles that will hold the result.
/// @param[in] maxTiles The maximum tiles the tiles parameter can hold.
/// @return The number of tiles returned in the tiles array.
function getTilesAt(x, y: Integer; tiles: PPdtMeshTile; maxTiles: Integer): Integer;
/// Gets the tile reference for the tile at specified grid location.
/// @param[in] x The tile's x-location. (x, y, layer)
/// @param[in] y The tile's y-location. (x, y, layer)
/// @param[in] layer The tile's layer. (x, y, layer)
/// @return The tile reference of the tile, or 0 if there is none.
function getTileRefAt(x, y, layer: Integer): TdtTileRef;
/// Gets the tile reference for the specified tile.
/// @param[in] tile The tile.
/// @return The tile reference of the tile.
function getTileRef(tile: PdtMeshTile): TdtTileRef;
/// Gets the tile for the specified tile reference.
/// @param[in] ref The tile reference of the tile to retrieve.
/// @return The tile for the specified reference, or null if the
/// reference is invalid.
function getTileByRef(ref: TdtTileRef): PdtMeshTile;
/// The maximum number of tiles supported by the navigation mesh.
/// @return The maximum number of tiles supported by the navigation mesh.
function getMaxTiles(): Integer;
/// Gets the tile at the specified index.
/// @param[in] i The tile index. [Limit: 0 >= index < #getMaxTiles()]
/// @return The tile at the specified index.
function getTile(i: Integer): PdtMeshTile;
/// Gets the tile and polygon for the specified polygon reference.
/// @param[in] ref The reference for the a polygon.
/// @param[out] tile The tile containing the polygon.
/// @param[out] poly The polygon.
/// @return The status flags for the operation.
function getTileAndPolyByRef(ref: TdtPolyRef; tile: PPdtMeshTile; poly: PPdtPoly): TdtStatus;
/// Returns the tile and polygon for the specified polygon reference.
/// @param[in] ref A known valid reference for a polygon.
/// @param[out] tile The tile containing the polygon.
/// @param[out] poly The polygon.
procedure getTileAndPolyByRefUnsafe(ref: TdtPolyRef; tile: PPdtMeshTile; poly: PPdtPoly);
/// Checks the validity of a polygon reference.
/// @param[in] ref The polygon reference to check.
/// @return True if polygon reference is valid for the navigation mesh.
function isValidPolyRef(ref: TdtPolyRef): Boolean;
/// Gets the polygon reference for the tile's base polygon.
/// @param[in] tile The tile.
/// @return The polygon reference for the base polygon in the specified tile.
function getPolyRefBase(tile: PdtMeshTile): TdtPolyRef;
/// Gets the endpoints for an off-mesh connection, ordered by "direction of travel".
/// @param[in] prevRef The reference of the polygon before the connection.
/// @param[in] polyRef The reference of the off-mesh connection polygon.
/// @param[out] startPos The start position of the off-mesh connection. [(x, y, z)]
/// @param[out] endPos The end position of the off-mesh connection. [(x, y, z)]
/// @return The status flags for the operation.
function getOffMeshConnectionPolyEndPoints(prevRef, polyRef: TdtPolyRef; startPos, endPos: PSingle): TdtStatus;
/// Gets the specified off-mesh connection.
/// @param[in] ref The polygon reference of the off-mesh connection.
/// @return The specified off-mesh connection, or null if the polygon reference is not valid.
function getOffMeshConnectionByRef(ref: TdtPolyRef): PdtOffMeshConnection;
/// @}
/// @{
/// @name State Management
/// These functions do not effect #dtTileRef or #dtPolyRef's.
/// Sets the user defined flags for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[in] flags The new flags for the polygon.
/// @return The status flags for the operation.
function setPolyFlags(ref: TdtPolyRef; flags: Word): TdtStatus;
/// Gets the user defined flags for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[out] resultFlags The polygon flags.
/// @return The status flags for the operation.
function getPolyFlags(ref: TdtPolyRef; resultFlags: PWord): TdtStatus;
/// Sets the user defined area for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[in] area The new area id for the polygon. [Limit: < #DT_MAX_AREAS]
/// @return The status flags for the operation.
function setPolyArea(ref: TdtPolyRef; area: Byte): TdtStatus;
/// Gets the user defined area for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[out] resultArea The area id for the polygon.
/// @return The status flags for the operation.
function getPolyArea(ref: TdtPolyRef; resultArea: PByte): TdtStatus;
/// Gets the size of the buffer required by #storeTileState to store the specified tile's state.
/// @param[in] tile The tile.
/// @return The size of the buffer required to store the state.
function getTileStateSize(tile: PdtMeshTile): Integer;
/// Stores the non-structural state of the tile in the specified buffer. (Flags, area ids, etc.)
/// @param[in] tile The tile.
/// @param[out] data The buffer to store the tile's state in.
/// @param[in] maxDataSize The size of the data buffer. [Limit: >= #getTileStateSize]
/// @return The status flags for the operation.
function storeTileState(tile: PdtMeshTile; data: PByte; maxDataSize: Integer): TdtStatus;
/// Restores the state of the tile.
/// @param[in] tile The tile.
/// @param[in] data The new state. (Obtained from #storeTileState.)
/// @param[in] maxDataSize The size of the state within the data buffer.
/// @return The status flags for the operation.
function restoreTileState(tile: PdtMeshTile; data: PByte; maxDataSize: Integer): TdtStatus;
/// @}
/// @{
/// @name Encoding and Decoding
/// These functions are generally meant for internal use only.
/// Derives a standard polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] salt The tile's salt value.
/// @param[in] it The index of the tile.
/// @param[in] ip The index of the polygon within the tile.
function encodePolyId(salt, it, ip: Cardinal): TdtPolyRef;
/// Decodes a standard polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference to decode.
/// @param[out] salt The tile's salt value.
/// @param[out] it The index of the tile.
/// @param[out] ip The index of the polygon within the tile.
/// @see #encodePolyId
procedure decodePolyId(ref: TdtPolyRef; salt, it, ip: PCardinal);
/// Extracts a tile's salt value from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
function decodePolyIdSalt(ref: TdtPolyRef): Cardinal;
/// Extracts the tile's index from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
function decodePolyIdTile(ref: TdtPolyRef): Cardinal;
/// Extracts the polygon's index (within its tile) from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
function decodePolyIdPoly(ref: TdtPolyRef): Cardinal;
/// @end;
procedure SaveToStream(aStream: TMemoryStream);
private
m_params: TdtNavMeshParams; ///< Current initialization params. TODO: do not store this info twice.
m_orig: array [0..2] of Single; ///< Origin of the tile (0,0)
m_tileWidth, m_tileHeight: Single; ///< Dimensions of each tile.
m_maxTiles: Integer; ///< Max number of tiles.
m_tileLutSize: Integer; ///< Tile hash lookup size (must be pot).
m_tileLutMask: Integer; ///< Tile hash lookup mask.
m_posLookup: PPointer; ///< Tile hash lookup.
m_nextFree: PdtMeshTile; ///< Freelist of tiles.
m_tiles: PdtMeshTile; ///< List of tiles.
{$ifndef DT_POLYREF64}
m_saltBits: Cardinal; ///< Number of salt bits in the tile ID.
m_tileBits: Cardinal; ///< Number of tile bits in the tile ID.
m_polyBits: Cardinal; ///< Number of poly bits in the tile ID.
{$endif}
/// Returns pointer to tile in the tile array.
//function getTile(i: Integer): PdtMeshTile;
/// Returns neighbour tile based on side.
//function getTilesAt(x, y: Integer; tiles: Pointer; maxTiles: Integer): Integer;
/// Returns neighbour tile based on side.
function getNeighbourTilesAt(x, y, side: Integer; tiles: PPdtMeshTile; maxTiles: Integer): Integer;
/// Returns all polygons in neighbour tile based on portal defined by the segment.
function findConnectingPolys(va, vb: PSingle;
tile: PdtMeshTile; side: Integer;
con: PdtPolyRef; conarea: PSingle; maxcon: Integer): Integer;
/// Builds internal polygons links for a tile.
procedure connectIntLinks(tile: PdtMeshTile);
/// Builds internal polygons links for a tile.
procedure baseOffMeshLinks(tile: PdtMeshTile);
/// Builds external polygon links for a tile.
procedure connectExtLinks(tile, target: PdtMeshTile; side: Integer);
/// Builds external polygon links for a tile.
procedure connectExtOffMeshLinks(tile, target: PdtMeshTile; side: Integer);
/// Removes external links at specified side.
procedure unconnectExtLinks(tile, target: PdtMeshTile);
// TODO: These methods are duplicates from dtNavMeshQuery, but are needed for off-mesh connection finding.
/// Queries polygons within a tile.
function queryPolygonsInTile(tile: PdtMeshTile; qmin, qmax: PSingle; polys: PdtPolyRef; maxPolys: Integer): Integer;
/// Find nearest polygon within a tile.
function findNearestPolyInTile(tile: PdtMeshTile; center, extents, nearestPt: PSingle): TdtPolyRef;
/// Returns closest point on polygon.
procedure closestPointOnPoly(ref: TdtPolyRef; pos, closest: PSingle; posOverPoly: PBoolean);
end;
/// Allocates a navigation mesh object using the Detour allocator.
/// @return A navigation mesh that is ready for initialization, or null on failure.
/// @ingroup detour
//dtNavMesh* dtAllocNavMesh();
/// Frees the specified navigation mesh object using the Detour allocator.
/// @param[in] navmesh A navigation mesh allocated using #dtAllocNavMesh
/// @ingroup detour
//void dtFreeNavMesh(dtNavMesh* navmesh);
implementation
/// Sets the user defined area id. [Limit: < #DT_MAX_AREAS]
procedure TdtPoly.setArea(a: Byte); begin areaAndtype := (areaAndtype and $c0) or (a and $3f); end;
/// Sets the polygon type. (See: #dtPolyTypes.)
procedure TdtPoly.setType(t: Byte); begin areaAndtype := (areaAndtype and $3f) or (t shl 6); end;
/// Gets the user defined area id.
function TdtPoly.getArea(): Byte; begin Result := areaAndtype and $3f; end;
/// Gets the polygon type. (See: #dtPolyTypes)
function TdtPoly.getType(): Byte; begin Result := areaAndtype shr 6; end;
///////////////////////////////////////////////////////////////////////////
// This section contains detailed documentation for members that don't have
// a source file. It reduces clutter in the main section of the header.
(**
@typedef dtPolyRef
@par
Polygon references are subject to the same invalidate/preserve/restore
rules that apply to #dtTileRef's. If the #dtTileRef for the polygon's
tile changes, the polygon reference becomes invalid.
Changing a polygon's flags, area id, etc. does not impact its polygon
reference.
@typedef dtTileRef
@par
The following changes will invalidate a tile reference:
- The referenced tile has been removed from the navigation mesh.
- The navigation mesh has been initialized using a different set
of #dtNavMeshParams.
A tile reference is preserved/restored if the tile is added to a navigation
mesh initialized with the original #dtNavMeshParams and is added at the
original reference location. (E.g. The lastRef parameter is used with
dtNavMesh::addTile.)
Basically, if the storage structure of a tile changes, its associated
tile reference changes.
@var unsigned short dtPoly::neis[DT_VERTS_PER_POLYGON]
@par
Each entry represents data for the edge starting at the vertex of the same index.
E.g. The entry at index n represents the edge data for vertex[n] to vertex[n+1].
A value of zero indicates the edge has no polygon connection. (It makes up the
border of the navigation mesh.)
The information can be extracted as follows:
@code
neighborRef = neis[n] & 0xff; // Get the neighbor polygon reference.
if (neis[n] & #DT_EX_LINK)
begin
// The edge is an external (portal) edge.
end;
@endcode
@var float dtMeshHeader::bvQuantFactor
@par
This value is used for converting between world and bounding volume coordinates.
For example:
@code
const float cs = 1.0f / tile.header.bvQuantFactor;
const dtBVNode* n = &tile.bvTree[i];
if (n.i >= 0)
begin
// This is a leaf node.
float worldMinX = tile.header.bmin[0] + n.bmin[0]*cs;
float worldMinY = tile.header.bmin[0] + n.bmin[1]*cs;
// Etc...
end;
@endcode
@struct dtMeshTile
@par
Tiles generally only exist within the context of a dtNavMesh object.
Some tile content is optional. For example, a tile may not contain any
off-mesh connections. In this case the associated pointer will be null.
If a detail mesh exists it will share vertices with the base polygon mesh.
Only the vertices unique to the detail mesh will be stored in #detailVerts.
@warning Tiles returned by a dtNavMesh object are not guarenteed to be populated.
For example: The tile at a location might not have been loaded yet, or may have been removed.
In this case, pointers will be null. So if in doubt, check the polygon count in the
tile's header to determine if a tile has polygons defined.
@var float dtOffMeshConnection::pos[6]
@par
For a properly built navigation mesh, vertex A will always be within the bounds of the mesh.
Vertex B is not required to be within the bounds of the mesh.
*)
function overlapSlabs(amin, amax, bmin, bmax: PSingle; px, py: Single): Boolean;
var minx,maxx,ad,ak,bd,bk,aminy,amaxy,bminy,bmaxy,dmin,dmax,thr: Single;
begin
// Check for horizontal overlap.
// The segment is shrunken a little so that slabs which touch
// at end points are not connected.
minx := dtMax(amin[0]+px,bmin[0]+px);
maxx := dtMin(amax[0]-px,bmax[0]-px);
if (minx > maxx) then
Exit(false);
// Check vertical overlap.
ad := (amax[1]-amin[1]) / (amax[0]-amin[0]);
ak := amin[1] - ad*amin[0];
bd := (bmax[1]-bmin[1]) / (bmax[0]-bmin[0]);
bk := bmin[1] - bd*bmin[0];
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) then
Exit(true);
// Check for overlap at endpoints.
thr := Sqr(py*2);
if (dmin*dmin <= thr) or (dmax*dmax <= thr) then
Exit(true);
Result := false;
end;
function getSlabCoord(va: PSingle; side: Integer): Single;
begin
if (side = 0) or (side = 4) then
Exit(va[0])
else if (side = 2) or (side = 6) then
Exit(va[2]);
Result := 0;
end;
procedure calcSlabEndPoints(va, vb, bmin,bmax: PSingle; side: Integer);
begin
if (side = 0) or (side = 4) then
begin
if (va[2] < vb[2]) then
begin
bmin[0] := va[2];
bmin[1] := va[1];
bmax[0] := vb[2];
bmax[1] := vb[1];
end
else
begin
bmin[0] := vb[2];
bmin[1] := vb[1];
bmax[0] := va[2];
bmax[1] := va[1];
end;
end
else if (side = 2) or (side = 6) then
begin
if (va[0] < vb[0]) then
begin
bmin[0] := va[0];
bmin[1] := va[1];
bmax[0] := vb[0];
bmax[1] := vb[1];
end
else
begin
bmin[0] := vb[0];
bmin[1] := vb[1];
bmax[0] := va[0];
bmax[1] := va[1];
end;
end;
end;
function computeTileHash(x, y, mask: Integer): Integer;
const h1: Cardinal = $8da6b343; // Large multiplicative constants;
const h2: Cardinal = $d8163841; // here arbitrarily chosen primes
var n: Int64;
begin
{$Q-}
n := h1 * x + h2 * y;
Result := Integer(n and mask);
{$Q+}
end;
function allocLink(tile: PdtMeshTile): Cardinal;
var link: Cardinal;
begin
if (tile.linksFreeList = DT_NULL_LINK) then
Exit(DT_NULL_LINK);
link := tile.linksFreeList;
tile.linksFreeList := tile.links[link].next;
Result := link;
end;
procedure freeLink(tile: PdtMeshTile; link: Cardinal);
begin
tile.links[link].next := tile.linksFreeList;
tile.linksFreeList := link;
end;
{function dtAllocNavMesh(): PdtNavMesh;
begin
void* mem := dtAlloc(sizeof(dtNavMesh), DT_ALLOC_PERM);
if (!mem) return 0;
return new(mem) dtNavMesh;
end;
/// @par
///
/// This function will only free the memory for tiles with the #DT_TILE_FREE_DATA
/// flag set.
procedure dtFreeNavMesh(dtNavMesh* navmesh);
begin
if (!navmesh) return;
navmesh.~dtNavMesh();
dtFree(navmesh);
end;}
//////////////////////////////////////////////////////////////////////////////////////////
(**
@class dtNavMesh
The navigation mesh consists of one or more tiles defining three primary types of structural data:
A polygon mesh which defines most of the navigation graph. (See rcPolyMesh for its structure.)
A detail mesh used for determining surface height on the polygon mesh. (See rcPolyMeshDetail for its structure.)
Off-mesh connections, which define custom point-to-point edges within the navigation graph.
The general build process is as follows:
-# Create rcPolyMesh and rcPolyMeshDetail data using the Recast build pipeline.
-# Optionally, create off-mesh connection data.
-# Combine the source data into a dtNavMeshCreateParams structure.
-# Create a tile data array using dtCreateNavMeshData().
-# Allocate at dtNavMesh object and initialize it. (For single tile navigation meshes,
the tile data is loaded during this step.)
-# For multi-tile navigation meshes, load the tile data using dtNavMesh::addTile().
Notes:
- This class is usually used in conjunction with the dtNavMeshQuery class for pathfinding.
- Technically, all navigation meshes are tiled. A 'solo' mesh is simply a navigation mesh initialized
to have only a single tile.
- This class does not implement any asynchronous methods. So the ::dtStatus result of all methods will
always contain either a success or failure flag.
@see dtNavMeshQuery, dtCreateNavMeshData, dtNavMeshCreateParams, #dtAllocNavMesh, #dtFreeNavMesh
*)
constructor TdtNavMesh.Create();
begin
FillChar(m_params, sizeof(TdtNavMeshParams), 0);
end;
destructor TdtNavMesh.Destroy;
var i: Integer;
begin
for i := 0 to m_maxTiles - 1 do
begin
if (m_tiles[i].flags and DT_TILE_FREE_DATA) <> 0 then
begin
FreeMem(m_tiles[i].data);
m_tiles[i].data := nil;
m_tiles[i].dataSize := 0;
end;
end;
FreeMem(m_posLookup);
FreeMem(m_tiles);
inherited;
end;
function TdtNavMesh.init(params: PdtNavMeshParams): TdtStatus;
var i: Integer;
begin
Move(params^, m_params, sizeof(TdtNavMeshParams));
dtVcopy(@m_orig[0], @params.orig[0]);
m_tileWidth := params.tileWidth;
m_tileHeight := params.tileHeight;
// Init tiles
m_maxTiles := params.maxTiles;
m_tileLutSize := dtNextPow2(params.maxTiles div 4);
if (m_tileLutSize = 0) then m_tileLutSize := 1;
m_tileLutMask := m_tileLutSize-1;
GetMem(m_tiles, sizeof(TdtMeshTile)*m_maxTiles);
GetMem(m_posLookup, sizeof(PdtMeshTile)*m_tileLutSize);
FillChar(m_tiles[0], sizeof(TdtMeshTile)*m_maxTiles, 0);
FillChar(m_posLookup[0], sizeof(PdtMeshTile)*m_tileLutSize, 0);
m_nextFree := nil;
for i := m_maxTiles-1 downto 0 do
begin
m_tiles[i].salt := 1;
m_tiles[i].next := m_nextFree;
m_nextFree := @m_tiles[i];
end;
// Init ID generator values.
{$ifndef DT_POLYREF64}
m_tileBits := dtIlog2(dtNextPow2(Cardinal(params.maxTiles)));
m_polyBits := dtIlog2(dtNextPow2(Cardinal(params.maxPolys)));
// Only allow 31 salt bits, since the salt mask is calculated using 32bit uint and it will overflow.
m_saltBits := dtMin(Cardinal(31), 32 - m_tileBits - m_polyBits);
if (m_saltBits < 10) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
{$endif}
Result := DT_SUCCESS;
end;
function TdtNavMesh.init(data: PByte; dataSize, flags: Integer): TdtStatus;
var header: PdtMeshHeader; params: TdtNavMeshParams; status: TdtStatus;
begin
// Make sure the data is in right format.
header := PdtMeshHeader(data);
if (header.magic <> DT_NAVMESH_MAGIC) then
Exit(DT_FAILURE or DT_WRONG_MAGIC);
if (header.version <> DT_NAVMESH_VERSION) then
Exit(DT_FAILURE or DT_WRONG_VERSION);
dtVcopy(@params.orig[0], @header.bmin[0]);
params.tileWidth := header.bmax[0] - header.bmin[0];
params.tileHeight := header.bmax[2] - header.bmin[2];
params.maxTiles := 1;
params.maxPolys := header.polyCount;
status := init(@params);
if (dtStatusFailed(status)) then
Exit(status);
Result := addTile(data, dataSize, flags, 0, nil);
end;
/// @par
///
/// @note The parameters are created automatically when the single tile
/// initialization is performed.
function TdtNavMesh.getParams(): PdtNavMeshParams;
begin
Result := @m_params;
end;
//////////////////////////////////////////////////////////////////////////////////////////
function TdtNavMesh.findConnectingPolys(va, vb: PSingle;
tile: PdtMeshTile; side: Integer;
con: PdtPolyRef; conarea: PSingle; maxcon: Integer): Integer;
var amin, amax,bmin,bmax: array [0..2] of Single; apos: Single; m: Word; i,j,n,nv: Integer; base: TdtPolyRef; poly: PdtPoly;
vc,vd: PSingle; bpos: Single;
begin
if (tile = nil) then Exit(0);
calcSlabEndPoints(va, vb, @amin[0], @amax[0], side);
apos := getSlabCoord(va, side);
// Remove links pointing to 'side' and compact the links array.
m := DT_EXT_LINK or Word(side);
n := 0;
base := getPolyRefBase(tile);
for i := 0 to tile.header.polyCount - 1 do
begin
poly := @tile.polys[i];
nv := poly.vertCount;
for j := 0 to nv - 1 do
begin
// Skip edges which do not point to the right side.
if (poly.neis[j] <> m) then continue;
vc := @tile.verts[poly.verts[j]*3];
vd := @tile.verts[poly.verts[(j+1) mod nv]*3];
bpos := getSlabCoord(vc, side);
// Segments are not close enough.
if (Abs(apos-bpos) > 0.01) then
continue;
// Check if the segments touch.
calcSlabEndPoints(vc,vd, @bmin[0],@bmax[0], side);
if (not overlapSlabs(@amin[0],@amax[0], @bmin[0],@bmax[0], 0.01, tile.header.walkableClimb)) then continue;
// Add return value.
if (n < maxcon) then
begin
conarea[n*2+0] := dtMax(amin[0], bmin[0]);
conarea[n*2+1] := dtMin(amax[0], bmax[0]);
con[n] := base or TdtPolyRef(i);
Inc(n);
end;
break;
end;
end;
Result := n;
end;
procedure TdtNavMesh.unconnectExtLinks(tile, target: PdtMeshTile);
var targetNum: Cardinal; i: Integer; poly: PdtPoly; j,pj,nj: Cardinal;
begin