1 (* Copyright (C) DooM 2D:Forever Developers
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 // universal spatial grid
17 {$INCLUDE ../shared/a_modes.inc}
18 {$IF DEFINED(D2F_DEBUG)}
19 {.$DEFINE D2F_DEBUG_RAYTRACE}
20 {.$DEFINE D2F_DEBUG_XXQ}
21 {.$DEFINE D2F_DEBUG_MOVER}
29 TBodyProxyId
= Integer;
31 generic TBodyGridBase
<ITP
> = class(TObject
)
33 type TGridQueryCB
= function (obj
: ITP
; tag
: Integer): Boolean is nested
; // return `true` to stop
34 type TGridRayQueryCB
= function (obj
: ITP
; tag
: Integer; x
, y
, prevx
, prevy
: Integer): Boolean is nested
; // return `true` to stop
35 type TGridAlongQueryCB
= function (obj
: ITP
; tag
: Integer): Boolean is nested
; // return `true` to stop
37 type TCellQueryCB
= procedure (x
, y
: Integer) is nested
; // top-left cell corner coords
39 const TagDisabled
= $40000000;
40 const TagFullMask
= $3fffffff;
44 GridDefaultTileSize
= 32; // must be power of two!
45 GridCellBucketSize
= 8; // WARNING! can't be less than 2!
49 PBodyProxyRec
= ^TBodyProxyRec
;
50 TBodyProxyRec
= record
52 mX
, mY
, mWidth
, mHeight
: Integer; // aabb
53 mQueryMark
: LongWord; // was this object visited at this query?
55 mTag
: Integer; // `TagDisabled` set: disabled ;-)
56 nextLink
: TBodyProxyId
; // next free or nothing
59 procedure setup (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer);
62 PGridCell
= ^TGridCell
;
64 bodies
: array [0..GridCellBucketSize
-1] of Integer; // -1: end of list
65 next
: Integer; // in this cell; index in mCells
68 TGridInternalCB
= function (grida
: Integer; bodyId
: TBodyProxyId
): Boolean of object; // return `true` to stop
72 const mTileSize
= GridDefaultTileSize
;
75 const tileSize
= mTileSize
;
78 mMinX
, mMinY
: Integer; // so grids can start at any origin
79 mWidth
, mHeight
: Integer; // in tiles
80 mGrid
: array of Integer; // mWidth*mHeight, index in mCells
81 mCells
: array of TGridCell
; // cell pool
82 mFreeCell
: Integer; // first free cell index or -1
85 mProxies
: array of TBodyProxyRec
;
86 mProxyFree
: TBodyProxyId
; // free
87 mProxyCount
: Integer; // currently used
88 mProxyMaxCount
: Integer;
91 dbgShowTraceLog
: Boolean;
92 {$IF DEFINED(D2F_DEBUG)}
93 dbgRayTraceTileHitCB
: TCellQueryCB
;
97 function allocCell (): Integer;
98 procedure freeCell (idx
: Integer); // `next` is simply overwritten
100 function allocProxy (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer): TBodyProxyId
;
101 procedure freeProxy (body
: TBodyProxyId
);
103 procedure insertInternal (body
: TBodyProxyId
);
104 procedure removeInternal (body
: TBodyProxyId
);
106 function forGridRect (x
, y
, w
, h
: Integer; cb
: TGridInternalCB
; bodyId
: TBodyProxyId
): Boolean;
108 function inserter (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
109 function remover (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
111 function getProxyEnabled (pid
: TBodyProxyId
): Boolean; inline;
112 procedure setProxyEnabled (pid
: TBodyProxyId
; val
: Boolean); inline;
114 function getGridWidthPx (): Integer; inline;
115 function getGridHeightPx (): Integer; inline;
118 constructor Create (aMinPixX
, aMinPixY
, aPixWidth
, aPixHeight
: Integer{; aTileSize: Integer=GridDefaultTileSize});
119 destructor Destroy (); override;
121 function insertBody (aObj
: ITP
; ax
, ay
, aWidth
, aHeight
: Integer; aTag
: Integer=-1): TBodyProxyId
;
122 procedure removeBody (body
: TBodyProxyId
); // WARNING! this WILL destroy proxy!
124 procedure moveBody (body
: TBodyProxyId
; nx
, ny
: Integer);
125 procedure resizeBody (body
: TBodyProxyId
; nw
, nh
: Integer);
126 procedure moveResizeBody (body
: TBodyProxyId
; nx
, ny
, nw
, nh
: Integer);
128 function insideGrid (x
, y
: Integer): Boolean; inline;
130 // `false` if `body` is surely invalid
131 function getBodyXY (body
: TBodyProxyId
; out rx
, ry
: Integer): Boolean; inline;
132 function getBodyWH (body
: TBodyProxyId
; out rw
, rh
: Integer): Boolean; inline;
133 function getBodyDims (body
: TBodyProxyId
; out rx
, ry
, rw
, rh
: Integer): Boolean; inline;
135 //WARNING: don't modify grid while any query is in progress (no checks are made!)
136 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
137 // no callback: return `true` on the first hit
138 function forEachInAABB (x
, y
, w
, h
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; allowDisabled
: Boolean=false): ITP
;
140 //WARNING: don't modify grid while any query is in progress (no checks are made!)
141 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
142 // no callback: return object on the first hit or nil
143 function forEachAtPoint (x
, y
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; exittag
: PInteger=nil): ITP
;
145 //WARNING: don't modify grid while any query is in progress (no checks are made!)
146 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
147 // cb with `(nil)` will be called before processing new tile
148 // no callback: return object of the nearest hit or nil
149 // if `inverted` is true, trace will register bodies *exluding* tagmask
150 //WARNING: don't change tags in callbacks here!
151 function traceRay (const x0
, y0
, x1
, y1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
; overload
;
152 function traceRay (out ex
, ey
: Integer; const ax0
, ay0
, ax1
, ay1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
;
154 //function traceOrthoRayWhileIn (const x0, y0, x1, y1: Integer; tagmask: Integer=-1): ITP; overload;
155 //function traceOrthoRayWhileIn (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): ITP;
157 //WARNING: don't modify grid while any query is in progress (no checks are made!)
158 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
159 // trace line along the grid, calling `cb` for all objects in passed cells, in no particular order
160 //WARNING: don't change tags in callbacks here!
161 function forEachAlongLine (const x0
, y0
, x1
, y1
: Integer; cb
: TGridAlongQueryCB
; tagmask
: Integer=-1; log
: Boolean=false): ITP
;
164 procedure forEachBodyCell (body
: TBodyProxyId
; cb
: TCellQueryCB
);
165 function forEachInCell (x
, y
: Integer; cb
: TGridQueryCB
): ITP
;
166 procedure dumpStats ();
168 //WARNING! no sanity checks!
169 property proxyEnabled
[pid
: TBodyProxyId
]: Boolean read getProxyEnabled write setProxyEnabled
;
171 property gridX0
: Integer read mMinX
;
172 property gridY0
: Integer read mMinY
;
173 property gridWidth
: Integer read getGridWidthPx
; // in pixels
174 property gridHeight
: Integer read getGridHeightPx
; // in pixels
178 // you are not supposed to understand this
179 // returns `true` if there is an intersection, and enter coords
180 // enter coords will be equal to (x0, y0) if starting point is inside the box
181 // if result is `false`, `inx` and `iny` are undefined
182 function lineAABBIntersects (x0
, y0
, x1
, y1
: Integer; bx
, by
, bw
, bh
: Integer; out inx
, iny
: Integer): Boolean;
184 function distanceSq (x0
, y0
, x1
, y1
: Integer): Integer; inline;
186 procedure swapInt (var a
: Integer; var b
: Integer); inline;
187 function minInt (a
, b
: Integer): Integer; inline;
188 function maxInt (a
, b
: Integer): Integer; inline;
197 // ////////////////////////////////////////////////////////////////////////// //
198 procedure swapInt (var a
: Integer; var b
: Integer); inline; var t
: Integer; begin t
:= a
; a
:= b
; b
:= t
; end;
199 function minInt (a
, b
: Integer): Integer; inline; begin if (a
< b
) then result
:= a
else result
:= b
; end;
200 function maxInt (a
, b
: Integer): Integer; inline; begin if (a
> b
) then result
:= a
else result
:= b
; end;
202 function distanceSq (x0
, y0
, x1
, y1
: Integer): Integer; inline; begin result
:= (x1
-x0
)*(x1
-x0
)+(y1
-y0
)*(y1
-y0
); end;
205 // ////////////////////////////////////////////////////////////////////////// //
206 // you are not supposed to understand this
207 // returns `true` if there is an intersection, and enter coords
208 // enter coords will be equal to (x0, y0) if starting point is inside the box
209 // if result is `false`, `inx` and `iny` are undefined
210 function lineAABBIntersects (x0
, y0
, x1
, y1
: Integer; bx
, by
, bw
, bh
: Integer; out inx
, iny
: Integer): Boolean;
212 wx0
, wy0
, wx1
, wy1
: Integer; // window coordinates
213 stx
, sty
: Integer; // "steps" for x and y axes
214 dsx
, dsy
: Integer; // "lengthes" for x and y axes
215 dx2
, dy2
: Integer; // "double lengthes" for x and y axes
216 xd
, yd
: Integer; // current coord
217 e
: Integer; // "error" (as in bresenham algo)
228 if (bw
< 1) or (bh
< 1) then exit
; // impossible box
230 if (x0
= x1
) and (y0
= y1
) then
233 result
:= (x0
>= bx
) and (y0
>= by
) and (x0
< bx
+bw
) and (y0
< by
+bh
);
237 // check if staring point is inside the box
238 if (x0
>= bx
) and (y0
>= by
) and (x0
< bx
+bw
) and (y0
< by
+bh
) then begin result
:= true; exit
; end;
249 // from left to right
250 if (x0
> wx1
) or (x1
< wx0
) then exit
; // out of screen
251 stx
:= 1; // going right
255 // from right to left
256 if (x1
> wx1
) or (x0
< wx0
) then exit
; // out of screen
257 stx
:= -1; // going left
268 // from top to bottom
269 if (y0
> wy1
) or (y1
< wy0
) then exit
; // out of screen
270 sty
:= 1; // going down
274 // from bottom to top
275 if (y1
> wy1
) or (y0
< wy0
) then exit
; // out of screen
276 sty
:= -1; // going up
315 temp
:= dx2
*(wy0
-y0
)-dsx
;
318 if (xd
> wx1
) then exit
; // x is moved out of clipping rect, nothing to do
319 if (xd
+1 >= wx0
) then
323 if (rem
> 0) then begin Inc(xd
); e
+= dy2
; end;
328 if (not xfixed
) and (x0
< wx0
) then
331 temp
:= dy2
*(wx0
-x0
);
334 if (yd
> wy1
) or (yd
= wy1
) and (rem
>= dsx
) then exit
;
337 if (rem
>= dsx
) then begin Inc(yd
); e
-= dx2
; end;
344 temp := dx2*(wy1-y0)+dsx;
345 term := x0+temp div dy2;
347 if (rem = 0) then Dec(term);
350 if (term > wx1) then term := wx1; // clip at right
352 Inc(term); // draw last point
353 //if (term = xd) then exit; // this is the only point, get out of here
356 if (sty
= -1) then yd
:= -yd
;
357 if (stx
= -1) then begin xd
:= -xd
; {!term := -term;} end;
366 // ////////////////////////////////////////////////////////////////////////// //
367 procedure TBodyGridBase
.TBodyProxyRec
.setup (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer);
380 // ////////////////////////////////////////////////////////////////////////// //
381 constructor TBodyGridBase
.Create (aMinPixX
, aMinPixY
, aPixWidth
, aPixHeight
: Integer{; aTileSize: Integer=GridDefaultTileSize});
385 dbgShowTraceLog
:= false;
386 {$IF DEFINED(D2F_DEBUG)}
387 dbgRayTraceTileHitCB
:= nil;
390 if aTileSize < 1 then aTileSize := 1;
391 if aTileSize > 8192 then aTileSize := 8192; // arbitrary limit
392 mTileSize := aTileSize;
394 if (aPixWidth
< mTileSize
) then aPixWidth
:= mTileSize
;
395 if (aPixHeight
< mTileSize
) then aPixHeight
:= mTileSize
;
398 mWidth
:= (aPixWidth
+mTileSize
-1) div mTileSize
;
399 mHeight
:= (aPixHeight
+mTileSize
-1) div mTileSize
;
400 SetLength(mGrid
, mWidth
*mHeight
);
401 SetLength(mCells
, mWidth
*mHeight
);
402 SetLength(mProxies
, 8192);
405 for idx
:= 0 to High(mCells
) do
407 mCells
[idx
].bodies
[0] := -1;
408 mCells
[idx
].bodies
[GridCellBucketSize
-1] := -1; // "has free room" flag
409 mCells
[idx
].next
:= idx
+1;
411 mCells
[High(mCells
)].next
:= -1; // last cell
413 for idx
:= 0 to High(mGrid
) do mGrid
[idx
] := -1;
415 for idx
:= 0 to High(mProxies
) do mProxies
[idx
].nextLink
:= idx
+1;
416 mProxies
[High(mProxies
)].nextLink
:= -1;
422 e_WriteLog(Format('created grid with size: %dx%d (tile size: %d); pix: %dx%d', [mWidth
, mHeight
, mTileSize
, mWidth
*mTileSize
, mHeight
*mTileSize
]), MSG_NOTIFY
);
426 destructor TBodyGridBase
.Destroy ();
435 // ////////////////////////////////////////////////////////////////////////// //
436 procedure TBodyGridBase
.dumpStats ();
438 idx
, mcb
, cidx
, cnt
: Integer;
441 for idx
:= 0 to High(mGrid
) do
448 cidx
:= mCells
[cidx
].next
;
450 if (mcb
< cnt
) then mcb
:= cnt
;
452 e_WriteLog(Format('grid size: %dx%d (tile size: %d); pix: %dx%d; used cells: %d; max bodies in cell: %d; max proxies allocated: %d; proxies used: %d', [mWidth
, mHeight
, mTileSize
, mWidth
*mTileSize
, mHeight
*mTileSize
, mUsedCells
, mcb
, mProxyMaxCount
, mProxyCount
]), MSG_NOTIFY
);
456 procedure TBodyGridBase
.forEachBodyCell (body
: TBodyProxyId
; cb
: TCellQueryCB
);
461 if (body
< 0) or (body
> High(mProxies
)) or not assigned(cb
) then exit
;
462 for g
:= 0 to High(mGrid
) do
465 while (cidx
<> -1) do
468 for f
:= 0 to GridCellBucketSize
-1 do
470 if (cc
.bodies
[f
] = -1) then break
;
471 if (cc
.bodies
[f
] = body
) then cb((g
mod mWidth
)*mTileSize
+mMinX
, (g
div mWidth
)*mTileSize
+mMinY
);
480 function TBodyGridBase
.forEachInCell (x
, y
: Integer; cb
: TGridQueryCB
): ITP
;
485 result
:= Default(ITP
);
486 if not assigned(cb
) then exit
;
489 if (x
< 0) or (y
< 0) or (x
>= mWidth
*mTileSize
) or (y
> mHeight
*mTileSize
) then exit
;
490 cidx
:= mGrid
[(y
div mTileSize
)*mWidth
+(x
div mTileSize
)];
491 while (cidx
<> -1) do
494 for f
:= 0 to GridCellBucketSize
-1 do
496 if (cc
.bodies
[f
] = -1) then break
;
497 if cb(mProxies
[cc
.bodies
[f
]].mObj
, mProxies
[cc
.bodies
[f
]].mTag
) then begin result
:= mProxies
[cc
.bodies
[f
]].mObj
; exit
; end;
505 // ////////////////////////////////////////////////////////////////////////// //
506 function TBodyGridBase
.getGridWidthPx (): Integer; inline; begin result
:= mWidth
*mTileSize
; end;
507 function TBodyGridBase
.getGridHeightPx (): Integer; inline; begin result
:= mHeight
*mTileSize
; end;
510 function TBodyGridBase
.insideGrid (x
, y
: Integer): Boolean; inline;
515 result
:= (x
>= 0) and (y
>= 0) and (x
< mWidth
*mTileSize
) and (y
< mHeight
*mTileSize
);
519 function TBodyGridBase
.getBodyXY (body
: TBodyProxyId
; out rx
, ry
: Integer): Boolean; inline;
521 if (body
>= 0) and (body
< Length(mProxies
)) then
523 with mProxies
[body
] do begin rx
:= mX
; ry
:= mY
; end;
535 function TBodyGridBase
.getBodyWH (body
: TBodyProxyId
; out rw
, rh
: Integer): Boolean; inline;
537 if (body
>= 0) and (body
< Length(mProxies
)) then
539 with mProxies
[body
] do begin rw
:= mWidth
; rh
:= mHeight
; end;
551 function TBodyGridBase
.getBodyDims (body
: TBodyProxyId
; out rx
, ry
, rw
, rh
: Integer): Boolean; inline;
553 if (body
>= 0) and (body
< Length(mProxies
)) then
555 with mProxies
[body
] do begin rx
:= mX
; ry
:= mY
; rw
:= mWidth
; rh
:= mHeight
; end;
570 // ////////////////////////////////////////////////////////////////////////// //
571 function TBodyGridBase
.getProxyEnabled (pid
: TBodyProxyId
): Boolean; inline;
573 if (pid
>= 0) then result
:= ((mProxies
[pid
].mTag
and TagDisabled
) = 0) else result
:= false;
577 procedure TBodyGridBase
.setProxyEnabled (pid
: TBodyProxyId
; val
: Boolean); inline;
583 mProxies
[pid
].mTag
:= mProxies
[pid
].mTag
and not TagDisabled
;
587 mProxies
[pid
].mTag
:= mProxies
[pid
].mTag
or TagDisabled
;
593 // ////////////////////////////////////////////////////////////////////////// //
594 function TBodyGridBase
.allocCell (): Integer;
599 if (mFreeCell
< 0) then
601 // no free cells, want more
602 mFreeCell
:= Length(mCells
);
603 SetLength(mCells
, mFreeCell
+32768); // arbitrary number
604 for idx
:= mFreeCell
to High(mCells
) do
606 mCells
[idx
].bodies
[0] := -1;
607 mCells
[idx
].bodies
[GridCellBucketSize
-1] := -1; // 'has free room' flag
608 mCells
[idx
].next
:= idx
+1;
610 mCells
[High(mCells
)].next
:= -1; // last cell
613 pc
:= @mCells
[result
];
614 mFreeCell
:= pc
.next
;
617 //e_WriteLog(Format('grid: allocated new cell #%d (total: %d)', [result, mUsedCells]), MSG_NOTIFY);
621 procedure TBodyGridBase
.freeCell (idx
: Integer);
623 if (idx
>= 0) and (idx
< Length(mCells
)) then
628 bodies
[GridCellBucketSize
-1] := -1; // 'has free room' flag
637 // ////////////////////////////////////////////////////////////////////////// //
638 function TBodyGridBase
.allocProxy (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer): TBodyProxyId
;
643 if (mProxyFree
= -1) then
645 // no free proxies, resize list
646 olen
:= Length(mProxies
);
647 SetLength(mProxies
, olen
+8192); // arbitrary number
648 for idx
:= olen
to High(mProxies
) do mProxies
[idx
].nextLink
:= idx
+1;
649 mProxies
[High(mProxies
)].nextLink
:= -1;
653 result
:= mProxyFree
;
654 px
:= @mProxies
[result
];
655 mProxyFree
:= px
.nextLink
;
656 px
.setup(aX
, aY
, aWidth
, aHeight
, aObj
, aTag
);
661 if (mProxyMaxCount
< mProxyCount
) then mProxyMaxCount
:= mProxyCount
;
664 procedure TBodyGridBase
.freeProxy (body
: TBodyProxyId
);
666 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
667 if (mProxyCount
= 0) then raise Exception
.Create('wutafuuuuu in grid (no allocated proxies, what i should free now?)');
669 mProxies
[body
].mObj
:= nil;
670 mProxies
[body
].nextLink
:= mProxyFree
;
676 // ////////////////////////////////////////////////////////////////////////// //
677 function TBodyGridBase
.forGridRect (x
, y
, w
, h
: Integer; cb
: TGridInternalCB
; bodyId
: TBodyProxyId
): Boolean;
685 if (w
< 1) or (h
< 1) or not assigned(cb
) then exit
;
690 if (x
+w
<= 0) or (y
+h
<= 0) then exit
;
693 //tsize := mTileSize;
694 if (x
>= gw
*tsize
) or (y
>= gh
*tsize
) then exit
;
695 for gy
:= y
div tsize
to (y
+h
-1) div tsize
do
697 if (gy
< 0) then continue
;
698 if (gy
>= gh
) then break
;
699 for gx
:= x
div tsize
to (x
+w
-1) div tsize
do
701 if (gx
< 0) then continue
;
702 if (gx
>= gw
) then break
;
703 result
:= cb(gy
*gw
+gx
, bodyId
);
710 // ////////////////////////////////////////////////////////////////////////// //
711 function TBodyGridBase
.inserter (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
718 result
:= false; // never stop
719 // add body to the given grid cell
723 {$IF DEFINED(D2F_DEBUG)}
725 while (cidx
<> -1) do
728 for f
:= 0 to GridCellBucketSize
-1 do
730 if (pi
.bodies
[f
] = -1) then break
;
731 if (pi
.bodies
[f
] = bodyId
) then raise Exception
.Create('trying to insert already inserted proxy');
737 while (cidx
<> -1) do
740 // check "has room" flag
741 if (pi
.bodies
[GridCellBucketSize
-1] = -1) then
744 for f
:= 0 to GridCellBucketSize
-1 do
746 if (pi
.bodies
[f
] = -1) then
748 pi
.bodies
[f
] := bodyId
;
749 if (f
+1 < GridCellBucketSize
) then pi
.bodies
[f
+1] := -1;
753 raise Exception
.Create('internal error in grid inserter');
755 // no room, go to next cell in list (if there is any)
758 // no room in cells, add new cell to list
760 // either no room, or no cell at all
763 pi
.bodies
[0] := bodyId
;
766 mGrid
[grida
] := cidx
;
769 procedure TBodyGridBase
.insertInternal (body
: TBodyProxyId
);
773 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
774 px
:= @mProxies
[body
];
775 forGridRect(px
.mX
, px
.mY
, px
.mWidth
, px
.mHeight
, inserter
, body
);
779 // assume that we cannot have one object added to bucket twice
780 function TBodyGridBase
.remover (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
786 result
:= false; // never stop
787 // find and remove cell
788 pidx
:= -1; // previous cell index
789 cidx
:= mGrid
[grida
]; // current cell index
790 while (cidx
<> -1) do
793 for f
:= 0 to GridCellBucketSize
-1 do
795 if (pc
.bodies
[f
] = bodyId
) then
798 if (f
= 0) and (pc
.bodies
[1] = -1) then
800 // this cell contains no elements, remove it
801 if (pidx
= -1) then mGrid
[grida
] := pc
.next
else mCells
[pidx
].next
:= pc
.next
;
805 // remove element from bucket
806 for c
:= f
to GridCellBucketSize
-2 do
808 pc
.bodies
[c
] := pc
.bodies
[c
+1];
809 if (pc
.bodies
[c
] = -1) then break
;
811 pc
.bodies
[GridCellBucketSize
-1] := -1; // "has free room" flag
820 procedure TBodyGridBase
.removeInternal (body
: TBodyProxyId
);
824 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
825 px
:= @mProxies
[body
];
826 forGridRect(px
.mX
, px
.mY
, px
.mWidth
, px
.mHeight
, remover
, body
);
830 // ////////////////////////////////////////////////////////////////////////// //
831 function TBodyGridBase
.insertBody (aObj
: ITP
; aX
, aY
, aWidth
, aHeight
: Integer; aTag
: Integer=-1): TBodyProxyId
;
833 aTag
:= aTag
and TagFullMask
;
834 result
:= allocProxy(aX
, aY
, aWidth
, aHeight
, aObj
, aTag
);
835 insertInternal(result
);
839 procedure TBodyGridBase
.removeBody (body
: TBodyProxyId
);
841 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
842 removeInternal(body
);
847 // ////////////////////////////////////////////////////////////////////////// //
848 procedure TBodyGridBase
.moveResizeBody (body
: TBodyProxyId
; nx
, ny
, nw
, nh
: Integer);
851 x0
, y0
, w
, h
: Integer;
853 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
854 px
:= @mProxies
[body
];
859 {$IF DEFINED(D2F_DEBUG_MOVER)}
860 e_WriteLog(Format('proxy #%d: MOVERESIZE: xg=%d;yg=%d;w=%d;h=%d;nx=%d;ny=%d;nw=%d;nh=%d', [body
, x0
-mMinX
, y0
-mMinY
, w
, h
, nx
-mMinX
, ny
-mMinY
, nw
, nh
]), MSG_NOTIFY
);
862 if (nx
= x0
) and (ny
= y0
) and (nw
= w
) and (nh
= h
) then exit
;
868 // did any corner crossed tile boundary?
869 if (x0
div mTileSize
<> nx
div mTileSize
) or
870 (y0
div mTileSize
<> ny
div mTileSize
) or
871 ((x0
+w
) div mTileSize
<> (nx
+nw
) div mTileSize
) or
872 ((y0
+h
) div mTileSize
<> (ny
+nh
) div mTileSize
) then
874 removeInternal(body
);
879 insertInternal(body
);
890 //TODO: optimize for horizontal/vertical moves
891 procedure TBodyGridBase
.moveBody (body
: TBodyProxyId
; nx
, ny
: Integer);
895 ogx0
, ogx1
, ogy0
, ogy1
: Integer; // old grid rect
896 ngx0
, ngx1
, ngy0
, ngy1
: Integer; // new grid rect
901 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
902 // check if tile coords was changed
903 px
:= @mProxies
[body
];
906 if (nx
= x0
) and (ny
= y0
) then exit
;
912 // check for heavy work
915 ogx0
:= x0
div mTileSize
;
916 ogy0
:= y0
div mTileSize
;
917 ngx0
:= nx
div mTileSize
;
918 ngy0
:= ny
div mTileSize
;
919 ogx1
:= (x0
+pw
-1) div mTileSize
;
920 ogy1
:= (y0
+ph
-1) div mTileSize
;
921 ngx1
:= (nx
+pw
-1) div mTileSize
;
922 ngy1
:= (ny
+ph
-1) div mTileSize
;
923 {$IF DEFINED(D2F_DEBUG_MOVER)}
924 e_WriteLog(Format('proxy #%d: checkmove: xg=%d;yg=%d;w=%d;h=%d;nx=%d;ny=%d og:(%d,%d)-(%d,%d); ng:(%d,%d)-(%d,%d)', [body
, x0
, y0
, pw
, ph
, nx
, ny
, ogx0
, ogy0
, ogx1
, ogy1
, ngx0
, ngy0
, ngx1
, ngy1
]), MSG_NOTIFY
);
926 if (ogx0
<> ngx0
) or (ogy0
<> ngy0
) or (ogx1
<> ngx1
) or (ogy1
<> ngy1
) then
928 // crossed tile boundary, do heavy work
931 // cycle with old rect, remove body where it is necessary
932 // optimized for horizontal moves
933 {$IF DEFINED(D2F_DEBUG_MOVER)}
934 e_WriteLog(Format('proxy #%d: xg=%d;yg=%d;w=%d;h=%d;nx=%d;ny=%d og:(%d,%d)-(%d,%d); ng:(%d,%d)-(%d,%d)', [body
, x0
, y0
, pw
, ph
, nx
, ny
, ogx0
, ogy0
, ogx1
, ogy1
, ngx0
, ngy0
, ngx1
, ngy1
]), MSG_NOTIFY
);
936 // remove stale marks
937 if not ((ogy0
>= gh
) or (ogy1
< 0)) and
938 not ((ogx0
>= gw
) or (ogx1
< 0)) then
940 if (ogx0
< 0) then ogx0
:= 0;
941 if (ogy0
< 0) then ogy0
:= 0;
942 if (ogx1
> gw
-1) then ogx1
:= gw
-1;
943 if (ogy1
> gh
-1) then ogy1
:= gh
-1;
944 {$IF DEFINED(D2F_DEBUG_MOVER)}
945 e_WriteLog(Format(' norm og:(%d,%d)-(%d,%d)', [ogx0
, ogy0
, ogx1
, ogy1
]), MSG_NOTIFY
);
947 for gx
:= ogx0
to ogx1
do
949 if (gx
< ngx0
) or (gx
> ngx1
) then
951 // this column is completely outside of new rect
952 for gy
:= ogy0
to ogy1
do
954 {$IF DEFINED(D2F_DEBUG_MOVER)}
955 e_WriteLog(Format(' remove0:(%d,%d)', [gx
, gy
]), MSG_NOTIFY
);
957 remover(gy
*gw
+gx
, body
);
963 for gy
:= ogy0
to ogy1
do
965 if (gy
< ngy0
) or (gy
> ngy1
) then
967 {$IF DEFINED(D2F_DEBUG_MOVER)}
968 e_WriteLog(Format(' remove1:(%d,%d)', [gx
, gy
]), MSG_NOTIFY
);
970 remover(gy
*gw
+gx
, body
);
976 // cycle with new rect, add body where it is necessary
977 if not ((ngy0
>= gh
) or (ngy1
< 0)) and
978 not ((ngx0
>= gw
) or (ngx1
< 0)) then
980 if (ngx0
< 0) then ngx0
:= 0;
981 if (ngy0
< 0) then ngy0
:= 0;
982 if (ngx1
> gw
-1) then ngx1
:= gw
-1;
983 if (ngy1
> gh
-1) then ngy1
:= gh
-1;
984 {$IF DEFINED(D2F_DEBUG_MOVER)}
985 e_WriteLog(Format(' norm ng:(%d,%d)-(%d,%d)', [ngx0
, ngy0
, ngx1
, ngy1
]), MSG_NOTIFY
);
987 for gx
:= ngx0
to ngx1
do
989 if (gx
< ogx0
) or (gx
> ogx1
) then
991 // this column is completely outside of old rect
992 for gy
:= ngy0
to ngy1
do
994 {$IF DEFINED(D2F_DEBUG_MOVER)}
995 e_WriteLog(Format(' insert0:(%d,%d)', [gx
, gy
]), MSG_NOTIFY
);
997 inserter(gy
*gw
+gx
, body
);
1003 for gy
:= ngy0
to ngy1
do
1005 if (gy
< ogy0
) or (gy
> ogy1
) then
1007 {$IF DEFINED(D2F_DEBUG_MOVER)}
1008 e_WriteLog(Format(' insert1:(%d,%d)', [gx
, gy
]), MSG_NOTIFY
);
1010 inserter(gy
*gw
+gx
, body
);
1020 {$IF DEFINED(D2F_DEBUG_MOVER)}
1021 e_WriteLog(Format('proxy #%d: GRID OK: xg=%d;yg=%d;w=%d;h=%d;nx=%d;ny=%d og:(%d,%d)-(%d,%d); ng:(%d,%d)-(%d,%d)', [body
, x0
, y0
, pw
, ph
, nx
, ny
, ogx0
, ogy0
, ogx1
, ogy1
, ngx0
, ngy0
, ngx1
, ngy1
]), MSG_NOTIFY
);
1024 // update coordinates
1029 procedure TBodyGridBase
.resizeBody (body
: TBodyProxyId
; nw
, nh
: Integer);
1032 x0
, y0
, w
, h
: Integer;
1034 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
1035 // check if tile coords was changed
1036 px
:= @mProxies
[body
];
1041 {$IF DEFINED(D2F_DEBUG_MOVER)}
1042 e_WriteLog(Format('proxy #%d: RESIZE: xg=%d;yg=%d;w=%d;h=%d;nw=%d;nh=%d', [body
, x0
, y0
, w
, h
, nw
, nh
]), MSG_NOTIFY
);
1044 if ((x0
+w
) div mTileSize
<> (x0
+nw
) div mTileSize
) or
1045 ((y0
+h
) div mTileSize
<> (y0
+nh
) div mTileSize
) then
1047 // crossed tile boundary, do heavy work
1048 removeInternal(body
);
1051 insertInternal(body
);
1055 // nothing to do with the grid, just fix size
1062 // ////////////////////////////////////////////////////////////////////////// //
1063 // no callback: return `true` on the first hit
1064 function TBodyGridBase
.forEachAtPoint (x
, y
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; exittag
: PInteger=nil): ITP
;
1067 idx
, curci
: Integer;
1068 cc
: PGridCell
= nil;
1073 result
:= Default(ITP
);
1074 if (exittag
<> nil) then exittag
^ := 0;
1075 tagmask
:= tagmask
and TagFullMask
;
1076 if (tagmask
= 0) then exit
;
1078 {$IF DEFINED(D2F_DEBUG_XXQ)}
1079 if (assigned(cb
)) then e_WriteLog(Format('0: grid pointquery: (%d,%d)', [x
, y
]), MSG_NOTIFY
);
1082 // make coords (0,0)-based
1085 if (x
< 0) or (y
< 0) or (x
>= mWidth
*mTileSize
) or (y
>= mHeight
*mTileSize
) then exit
;
1087 curci
:= mGrid
[(y
div mTileSize
)*mWidth
+(x
div mTileSize
)];
1089 {$IF DEFINED(D2F_DEBUG_XXQ)}
1090 if (assigned(cb
)) then e_WriteLog(Format('1: grid pointquery: (%d,%d) (%d,%d) %d', [x
, y
, (x
div mTileSize
), (y
div mTileSize
), curci
]), MSG_NOTIFY
);
1097 // increase query counter
1099 if (mLastQuery
= 0) then
1101 // just in case of overflow
1103 for idx
:= 0 to High(mProxies
) do mProxies
[idx
].mQueryMark
:= 0;
1107 {$IF DEFINED(D2F_DEBUG_XXQ)}
1108 if (assigned(cb
)) then e_WriteLog(Format('2: grid pointquery: (%d,%d); lq=%u', [x
, y
, lq
]), MSG_NOTIFY
);
1111 while (curci
<> -1) do
1113 {$IF DEFINED(D2F_DEBUG_XXQ)}
1114 if (assigned(cb
)) then e_WriteLog(Format(' cell #%d', [curci
]), MSG_NOTIFY
);
1116 cc
:= @mCells
[curci
];
1117 for f
:= 0 to GridCellBucketSize
-1 do
1119 if (cc
.bodies
[f
] = -1) then break
;
1120 px
:= @mProxies
[cc
.bodies
[f
]];
1121 {$IF DEFINED(D2F_DEBUG_XXQ)}
1122 if (assigned(cb
)) then e_WriteLog(Format(' proxy #%d; qm:%u; tag:%08x; tagflag:%d %u', [cc
.bodies
[f
], px
.mQueryMark
, px
.mTag
, (px
.mTag
and tagmask
), LongWord(px
.mObj
)]), MSG_NOTIFY
);
1124 // shit. has to do it this way, so i can change tag in callback
1125 if (px
.mQueryMark
<> lq
) then
1127 px
.mQueryMark
:= lq
;
1129 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and
1130 (x
>= px
.mX
) and (y
>= px
.mY
) and (x
< px
.mX
+px
.mWidth
) and (y
< px
.mY
+px
.mHeight
) then
1132 if assigned(cb
) then
1134 if cb(px
.mObj
, ptag
) then
1137 if (exittag
<> nil) then exittag
^ := ptag
;
1144 if (exittag
<> nil) then exittag
^ := ptag
;
1155 // ////////////////////////////////////////////////////////////////////////// //
1156 // no callback: return `true` on the first hit
1157 function TBodyGridBase
.forEachInAABB (x
, y
, w
, h
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; allowDisabled
: Boolean=false): ITP
;
1165 cc
: PGridCell
= nil;
1172 result
:= Default(ITP
);
1173 if (w
< 1) or (h
< 1) then exit
;
1174 tagmask
:= tagmask
and TagFullMask
;
1175 if (tagmask
= 0) then exit
;
1185 //tsize := mTileSize;
1187 if (x
+w
<= 0) or (y
+h
<= 0) then exit
;
1188 if (x
>= gw
*tsize
) or (y
>= mHeight
*tsize
) then exit
;
1190 // increase query counter
1192 if (mLastQuery
= 0) then
1194 // just in case of overflow
1196 for idx
:= 0 to High(mProxies
) do mProxies
[idx
].mQueryMark
:= 0;
1198 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
1202 for gy
:= y
div tsize
to (y
+h
-1) div tsize
do
1204 if (gy
< 0) then continue
;
1205 if (gy
>= mHeight
) then break
;
1206 for gx
:= x
div tsize
to (x
+w
-1) div tsize
do
1208 if (gx
< 0) then continue
;
1209 if (gx
>= gw
) then break
;
1211 curci
:= mGrid
[gy
*gw
+gx
];
1212 while (curci
<> -1) do
1214 cc
:= @mCells
[curci
];
1215 for f
:= 0 to GridCellBucketSize
-1 do
1217 if (cc
.bodies
[f
] = -1) then break
;
1218 px
:= @mProxies
[cc
.bodies
[f
]];
1219 // shit. has to do it this way, so i can change tag in callback
1220 if (px
.mQueryMark
= lq
) then continue
;
1221 px
.mQueryMark
:= lq
;
1223 if (not allowDisabled
) and ((ptag
and TagDisabled
) <> 0) then continue
;
1224 if ((ptag
and tagmask
) = 0) then continue
;
1225 if (x0
>= px
.mX
+px
.mWidth
) or (y0
>= px
.mY
+px
.mHeight
) then continue
;
1226 if (x0
+w
<= px
.mX
) or (y0
+h
<= px
.mY
) then continue
;
1227 if assigned(cb
) then
1229 if cb(px
.mObj
, ptag
) then begin result
:= px
.mObj
; exit
; end;
1244 // ////////////////////////////////////////////////////////////////////////// //
1245 // no callback: return `true` on the nearest hit
1246 function TBodyGridBase
.traceRay (const x0
, y0
, x1
, y1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
;
1250 result
:= traceRay(ex
, ey
, x0
, y0
, x1
, y1
, cb
, tagmask
);
1254 // no callback: return `true` on the nearest hit
1255 // you are not supposed to understand this
1256 function TBodyGridBase
.traceRay (out ex
, ey
: Integer; const ax0
, ay0
, ax1
, ay1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
;
1260 wx0
, wy0
, wx1
, wy1
: Integer; // window coordinates
1261 stx
, sty
: Integer; // "steps" for x and y axes
1262 dsx
, dsy
: Integer; // "lengthes" for x and y axes
1263 dx2
, dy2
: Integer; // "double lengthes" for x and y axes
1264 xd
, yd
: Integer; // current coord
1265 e
: Integer; // "error" (as in bresenham algo)
1268 xptr
, yptr
: PInteger;
1271 prevx
, prevy
: Integer;
1272 lastDistSq
: Integer;
1273 ccidx
, curci
: Integer;
1274 hasUntried
: Boolean;
1275 lastGA
: Integer = -1;
1278 wasHit
: Boolean = false;
1279 gw
, gh
, minx
, miny
, maxx
, maxy
: Integer;
1283 f
, ptag
, distSq
: Integer;
1284 x0
, y0
, x1
, y1
: Integer;
1285 // horizontal walker
1286 wklen
, wkstep
: Integer;
1289 result
:= Default(ITP
);
1290 lastObj
:= Default(ITP
);
1291 tagmask
:= tagmask
and TagFullMask
;
1292 ex
:= ax1
; // why not?
1293 ey
:= ay1
; // why not?
1294 if (tagmask
= 0) then exit
;
1296 if (ax0
= ax1
) and (ay0
= ay1
) then
1298 result
:= forEachAtPoint(ax0
, ay0
, nil, tagmask
, @ptag
);
1299 if (result
<> nil) then
1301 if assigned(cb
) and not cb(result
, ptag
, ax0
, ay0
, ax0
, ay0
) then result
:= Default(ITP
);
1306 lastDistSq
:= distanceSq(ax0
, ay0
, ax1
, ay1
)+1;
1315 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1316 if assigned(dbgRayTraceTileHitCB
) then e_WriteLog(Format('TRACING: (%d,%d)-(%d,%d) [(%d,%d)-(%d,%d)]; maxdistsq=%d', [ax0
, ay0
, ax1
, ay1
, minx
, miny
, maxx
, maxy
, lastDistSq
]), MSG_NOTIFY
);
1324 // offset query coords to (0,0)-based
1339 // from left to right
1340 if (x0
> wx1
) or (x1
< wx0
) then exit
; // out of screen
1341 stx
:= 1; // going right
1345 // from right to left
1346 if (x1
> wx1
) or (x0
< wx0
) then exit
; // out of screen
1347 stx
:= -1; // going left
1358 // from top to bottom
1359 if (y0
> wy1
) or (y1
< wy0
) then exit
; // out of screen
1360 sty
:= 1; // going down
1364 // from bottom to top
1365 if (y1
> wy1
) or (y0
< wy0
) then exit
; // out of screen
1366 sty
:= -1; // going up
1405 temp
:= dx2
*(wy0
-y0
)-dsx
;
1407 rem
:= temp
mod dy2
;
1408 if (xd
> wx1
) then exit
; // x is moved out of clipping rect, nothing to do
1409 if (xd
+1 >= wx0
) then
1413 if (rem
> 0) then begin Inc(xd
); e
+= dy2
; end;
1418 if (not xfixed
) and (x0
< wx0
) then
1421 temp
:= dy2
*(wx0
-x0
);
1423 rem
:= temp
mod dx2
;
1424 if (yd
> wy1
) or (yd
= wy1
) and (rem
>= dsx
) then exit
;
1427 if (rem
>= dsx
) then begin Inc(yd
); e
-= dx2
; end;
1433 temp
:= dx2
*(wy1
-y0
)+dsx
;
1434 term
:= x0
+temp
div dy2
;
1435 rem
:= temp
mod dy2
;
1436 if (rem
= 0) then Dec(term
);
1439 if (term
> wx1
) then term
:= wx1
; // clip at right
1441 Inc(term
); // draw last point
1442 //if (term = xd) then exit; // this is the only point, get out of here
1444 if (sty
= -1) then yd
:= -yd
;
1445 if (stx
= -1) then begin xd
:= -xd
; term
:= -term
; end;
1448 // first move, to skip starting point
1449 // DON'T DO THIS! loop will take care of that
1452 result
:= forEachAtPoint(ax0
, ay0
, nil, tagmask
, @ptag
);
1453 if (result
<> nil) then
1455 if assigned(cb
) then
1457 if cb(result
, ptag
, ax0
, ay0
, ax0
, ay0
) then
1476 prevx
:= xptr
^+minx
;
1477 prevy
:= yptr
^+miny
;
1480 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
1483 if (xd = term) then exit;
1486 {$IF DEFINED(D2F_DEBUG)}
1487 if (xptr
^ < 0) or (yptr
^ < 0) or (xptr
^ >= gw
*tsize
) and (yptr
^ >= gh
*tsize
) then raise Exception
.Create('raycaster internal error (0)');
1489 // DON'T DO THIS! loop will take care of that
1490 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
1491 //ccidx := mGrid[lastGA];
1493 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1494 //if assigned(dbgRayTraceTileHitCB) then e_WriteLog('1:TRACING!', MSG_NOTIFY);
1497 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
1499 // increase query counter
1501 if (mLastQuery
= 0) then
1503 // just in case of overflow
1505 for f
:= 0 to High(mProxies
) do mProxies
[f
].mQueryMark
:= 0;
1509 // if this is strict horizontal trace, use optimized codepath
1510 if (ax0
= ax1
) or (ay0
= ay1
) then
1512 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
1513 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
1514 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
1515 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
1516 hopt
:= (ay0
= ay1
); // horizontal?
1517 if (stx
< 0) then wklen
:= -(term
-xd
) else wklen
:= term
-xd
;
1518 {$IF DEFINED(D2F_DEBUG)}
1519 if dbgShowTraceLog
then e_LogWritefln('optimized htrace; wklen=%d', [wklen
]);
1521 ga
:= (yptr
^ div tsize
)*gw
+(xptr
^ div tsize
);
1522 // one of those will never change
1525 {$IF DEFINED(D2F_DEBUG)}
1528 if (y
<> ay0
) then raise Exception
.Create('htrace fatal internal error');
1532 if (x
<> ax0
) then raise Exception
.Create('vtrace fatal internal error');
1535 while (wklen
> 0) do
1537 {$IF DEFINED(D2F_DEBUG)}
1538 if dbgShowTraceLog
then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; y=%d; y=%d', [ga
, xptr
^+minx
, yptr
^+miny
, y
, ay0
]);
1541 if (ga
<> lastGA
) then
1544 ccidx
:= mGrid
[lastGA
];
1545 // convert coords to map (to avoid ajdusting coords inside the loop)
1546 if hopt
then x
:= xptr
^+minx
else y
:= yptr
^+miny
;
1547 while (ccidx
<> -1) do
1549 cc
:= @mCells
[ccidx
];
1550 for f
:= 0 to GridCellBucketSize
-1 do
1552 if (cc
.bodies
[f
] = -1) then break
;
1553 px
:= @mProxies
[cc
.bodies
[f
]];
1555 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) and
1556 // constant coord should be inside
1557 ((hopt
and (y
>= px
.mY
) and (y
< px
.mY
+px
.mHeight
)) or
1558 ((not hopt
) and (x
>= px
.mX
) and (x
< px
.mX
+px
.mWidth
))) then
1560 px
.mQueryMark
:= lq
; // mark as processed
1561 // inside the proxy?
1562 if (hopt
and (x
> px
.mX
) and (x
< px
.mX
+px
.mWidth
-1)) or
1563 ((not hopt
) and (y
> px
.mY
) and (y
< px
.mY
+px
.mHeight
-1)) then
1565 if assigned(cb
) then
1567 if cb(px
.mObj
, ptag
, x
, y
, x
, y
) then
1578 distSq
:= distanceSq(ax0
, ay0
, x
, y
);
1579 {$IF DEFINED(D2F_DEBUG)}
1580 if dbgShowTraceLog
then e_LogWritefln(' EMBEDDED hhit(%d): a=(%d,%d), h=(%d,%d), distsq=%d; lastsq=%d', [cc
.bodies
[f
], ax0
, ay0
, x
, y
, distSq
, lastDistSq
]);
1582 if (distSq
< lastDistSq
) then
1592 // remember this hitpoint if it is nearer than an old one
1599 if (x
< px
.mX
) then continue
;
1600 prevx
:= px
.mX
+px
.mWidth
;
1605 if (x
> px
.mX
{+px.mWidth}) then continue
;
1615 if (y
< px
.mY
) then continue
;
1616 prevy
:= px
.mY
+px
.mHeight
;
1621 if (y
> px
.mY
{+px.mHeight}) then continue
;
1625 if assigned(cb
) then
1629 if hopt
then x
:= prevx
-1 else y
:= prevy
-1;
1633 if hopt
then x
:= prevx
+1 else y
:= prevy
+1;
1635 if cb(px
.mObj
, ptag
, x
, y
, prevx
, prevy
) then
1647 distSq
:= distanceSq(ax0
, ay0
, prevx
, prevy
);
1648 {$IF DEFINED(D2F_DEBUG)}
1649 if dbgShowTraceLog
then e_LogWritefln(' hhit(%d): a=(%d,%d), h=(%d,%d), p=(%d,%d), distsq=%d; lastsq=%d', [cc
.bodies
[f
], ax0
, ay0
, x
, y
, prevx
, prevy
, distSq
, lastDistSq
]);
1651 if (distSq
< lastDistSq
) then
1654 lastDistSq
:= distSq
;
1665 if wasHit
and not assigned(cb
) then begin result
:= lastObj
; exit
; end;
1667 // skip to next tile
1673 wkstep
:= ((xptr
^ or (mTileSize
-1))+1)-xptr
^;
1674 {$IF DEFINED(D2F_DEBUG)}
1675 if dbgShowTraceLog
then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen
, wkstep
]);
1677 if (wkstep
>= wklen
) then break
;
1684 wkstep
:= xptr
^-((xptr
^ and (not (mTileSize
-1)))-1);
1685 {$IF DEFINED(D2F_DEBUG)}
1686 if dbgShowTraceLog
then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen
, wkstep
]);
1688 if (wkstep
>= wklen
) then break
;
1698 wkstep
:= ((yptr
^ or (mTileSize
-1))+1)-yptr
^;
1699 {$IF DEFINED(D2F_DEBUG)}
1700 if dbgShowTraceLog
then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen
, wkstep
]);
1702 if (wkstep
>= wklen
) then break
;
1709 wkstep
:= yptr
^-((yptr
^ and (not (mTileSize
-1)))-1);
1710 {$IF DEFINED(D2F_DEBUG)}
1711 if dbgShowTraceLog
then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen
, wkstep
]);
1713 if (wkstep
>= wklen
) then break
;
1720 // we can travel less than one cell
1721 if wasHit
and not assigned(cb
) then result
:= lastObj
else begin ex
:= ax1
; ey
:= ay1
; end;
1725 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1726 if assigned(dbgRayTraceTileHitCB
) then dbgRayTraceTileHitCB((xptr
^ div tsize
*tsize
)+minx
, (yptr
^ div tsize
*tsize
)+miny
);
1731 while (xd
<> term
) do
1734 {$IF DEFINED(D2F_DEBUG)}
1735 if (xptr
^ < 0) or (yptr
^ < 0) or (xptr
^ >= gw
*tsize
) and (yptr
^ >= gh
*tsize
) then raise Exception
.Create('raycaster internal error (0)');
1738 ga
:= (yptr
^ div tsize
)*gw
+(xptr
^ div tsize
);
1739 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1740 if assigned(dbgRayTraceTileHitCB
) then e_WriteLog(Format(' xd=%d; term=%d; gx=%d; gy=%d; ga=%d; lastga=%d', [xd
, term
, xptr
^, yptr
^, ga
, lastGA
]), MSG_NOTIFY
);
1742 if (ga
<> lastGA
) then
1745 {$IF DEFINED(D2F_DEBUG)}
1746 if assigned(dbgRayTraceTileHitCB
) then dbgRayTraceTileHitCB((xptr
^ div tsize
*tsize
)+minx
, (yptr
^ div tsize
*tsize
)+miny
);
1748 if (ccidx
<> -1) then
1750 // signal cell completion
1751 if assigned(cb
) then
1753 if cb(nil, 0, xptr
^+minx
, yptr
^+miny
, prevx
, prevy
) then begin result
:= lastObj
; exit
; end;
1762 ccidx
:= mGrid
[lastGA
];
1764 // has something to process in this tile?
1765 if (ccidx
<> -1) then
1769 hasUntried
:= false; // this will be set to `true` if we have some proxies we still want to process at the next step
1770 // convert coords to map (to avoid ajdusting coords inside the loop)
1773 // process cell list
1774 while (curci
<> -1) do
1776 cc
:= @mCells
[curci
];
1777 for f
:= 0 to GridCellBucketSize
-1 do
1779 if (cc
.bodies
[f
] = -1) then break
;
1780 px
:= @mProxies
[cc
.bodies
[f
]];
1782 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) then
1784 // can we process this proxy?
1785 if (x
>= px
.mX
) and (y
>= px
.mY
) and (x
< px
.mX
+px
.mWidth
) and (y
< px
.mY
+px
.mHeight
) then
1787 px
.mQueryMark
:= lq
; // mark as processed
1788 if assigned(cb
) then
1790 if cb(px
.mObj
, ptag
, x
, y
, prevx
, prevy
) then
1798 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1799 distSq := distanceSq(ax0, ay0, prevx, prevy);
1800 if assigned(dbgRayTraceTileHitCB) then e_WriteLog(Format(' hit(%d): a=(%d,%d), h=(%d,%d), p=(%d,%d); distsq=%d; lastsq=%d', [cc.bodies[f], ax0, ay0, x, y, prevx, prevy, distSq, lastDistSq]), MSG_NOTIFY);
1801 if (distSq < lastDistSq) then
1804 lastDistSq := distSq;
1814 // remember this hitpoint if it is nearer than an old one
1815 distSq
:= distanceSq(ax0
, ay0
, prevx
, prevy
);
1816 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1817 if assigned(dbgRayTraceTileHitCB
) then e_WriteLog(Format(' hit(%d): a=(%d,%d), h=(%d,%d), p=(%d,%d); distsq=%d; lastsq=%d', [cc
.bodies
[f
], ax0
, ay0
, x
, y
, prevx
, prevy
, distSq
, lastDistSq
]), MSG_NOTIFY
);
1819 if (distSq
< lastDistSq
) then
1822 lastDistSq
:= distSq
;
1831 // this is possibly interesting proxy, set "has more to check" flag
1839 // still has something interesting in this cell?
1840 if not hasUntried
then
1842 // nope, don't process this cell anymore; signal cell completion
1844 if assigned(cb
) then
1846 if cb(nil, 0, x
, y
, prevx
, prevy
) then begin result
:= lastObj
; exit
; end;
1855 //putPixel(xptr^, yptr^);
1857 prevx
:= xptr
^+minx
;
1858 prevy
:= yptr
^+miny
;
1859 if (e
>= 0) then begin yd
+= sty
; e
-= dx2
; end else e
+= dy2
;
1862 // we can travel less than one cell
1863 if wasHit
and not assigned(cb
) then
1869 ex
:= ax1
; // why not?
1870 ey
:= ay1
; // why not?
1875 // ////////////////////////////////////////////////////////////////////////// //
1876 //FIXME! optimize this with real tile walking
1877 function TBodyGridBase
.forEachAlongLine (const x0
, y0
, x1
, y1
: Integer; cb
: TGridAlongQueryCB
; tagmask
: Integer=-1; log
: Boolean=false): ITP
;
1883 xerr
, yerr
: Integer;
1884 incx
, incy
: Integer;
1885 stepx
, stepy
: Integer;
1887 maxx
, maxy
: Integer;
1894 minx
, miny
: Integer;
1896 lastWasInGrid
: Boolean;
1902 result
:= Default(ITP
);
1903 tagmask
:= tagmask
and TagFullMask
;
1904 if (tagmask
= 0) or not assigned(cb
) then exit
;
1912 if (dx
> 0) then incx
:= 1 else if (dx
< 0) then incx
:= -1 else incx
:= 0;
1913 if (dy
> 0) then incy
:= 1 else if (dy
< 0) then incy
:= -1 else incy
:= 0;
1915 if (incx
= 0) and (incy
= 0) then exit
; // just incase
1920 if (dx
> dy
) then d
:= dx
else d
:= dy
;
1922 // `x` and `y` will be in grid coords
1926 // increase query counter
1928 if (mLastQuery
= 0) then
1930 // just in case of overflow
1932 for i
:= 0 to High(mProxies
) do mProxies
[i
].mQueryMark
:= 0;
1936 // cache various things
1937 //tsize := mTileSize;
1943 // setup distance and flags
1944 lastWasInGrid
:= (x
>= 0) and (y
>= 0) and (x
<= maxx
) and (y
<= maxy
);
1946 // setup starting tile ('cause we'll adjust tile vars only on tile edge crossing)
1947 if lastWasInGrid
then ccidx
:= mGrid
[(y
div tsize
)*gw
+(x
div tsize
)] else ccidx
:= -1;
1949 // it is slightly faster this way
1953 if (log
) then e_WriteLog(Format('tracing: (%d,%d)-(%d,%d)', [x
, y
, x1
-minx
, y1
-miny
]), MSG_NOTIFY
);
1963 // invariant: one of those always changed
1964 {$IF DEFINED(D2F_DEBUG)}
1965 if (xerr
< 0) and (yerr
< 0) then raise Exception
.Create('internal bug in grid raycaster (0)');
1967 if (xerr
>= 0) then begin xerr
-= d
; x
+= incx
; stepx
:= incx
; end else stepx
:= 0;
1968 if (yerr
>= 0) then begin yerr
-= d
; y
+= incy
; stepy
:= incy
; end else stepy
:= 0;
1969 // invariant: we always doing a step
1970 {$IF DEFINED(D2F_DEBUG)}
1971 if ((stepx
or stepy
) = 0) then raise Exception
.Create('internal bug in grid raycaster (1)');
1974 // check for crossing tile/grid boundary
1975 if (x
>= 0) and (y
>= 0) and (x
<= maxx
) and (y
<= maxy
) then
1977 // we're still in grid
1978 lastWasInGrid
:= true;
1979 // check for tile edge crossing
1980 if (stepx
< 0) and ((x
mod tsize
) = tsize
-1) then tbcross
:= true
1981 else if (stepx
> 0) and ((x
mod tsize
) = 0) then tbcross
:= true
1982 else if (stepy
< 0) and ((y
mod tsize
) = tsize
-1) then tbcross
:= true
1983 else if (stepy
> 0) and ((y
mod tsize
) = 0) then tbcross
:= true
1984 else tbcross
:= false;
1985 // crossed tile edge?
1988 // setup new cell index
1989 ccidx
:= mGrid
[(y
div tsize
)*gw
+(x
div tsize
)];
1990 if (log
) then e_WriteLog(Format(' stepped to new tile (%d,%d) -- (%d,%d)', [(x
div tsize
), (y
div tsize
), x
, y
]), MSG_NOTIFY
);
1993 if (ccidx
= -1) then
1995 // we have nothing interesting here anymore, jump directly to tile edge
2000 if (incy < 0) then tedist := y-(y and (not tsize)) else tedist := (y or (tsize-1))-y;
2001 if (tedist > 1) then
2003 if (log) then e_WriteLog(Format(' doing vertical jump from tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2006 if (log) then e_WriteLog(Format(' jumped to tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2009 else if (incy = 0) then
2012 if (incx < 0) then tedist := x-(x and (not tsize)) else tedist := (x or (tsize-1))-x;
2013 if (tedist > 1) then
2015 if (log) then e_WriteLog(Format(' doing horizontal jump from tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2018 if (log) then e_WriteLog(Format(' jumped to tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2024 // get minimal distance to tile edges
2025 if (incx < 0) then tedist := x-(x and (not tsize)) else if (incx > 0) then tedist := (x or (tsize+1))-x else tedist := 0;
2026 {$IF DEFINED(D2F_DEBUG)}
2027 if (tedist < 0) then raise Exception.Create('internal bug in grid raycaster (2.x)');
2029 if (incy < 0) then f := y-(y and (not tsize)) else if (incy > 0) then f := (y or (tsize+1))-y else f := 0;
2030 {$IF DEFINED(D2F_DEBUG)}
2031 if (f < 0) then raise Exception.Create('internal bug in grid raycaster (2.y)');
2033 if (tedist = 0) then tedist := f else if (f <> 0) then tedist := minInt(tedist, f);
2035 if (tedist > 1) then
2037 if (log) then e_WriteLog(Format(' doing jump from tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2040 if (xerr >= 0) then begin x += incx*((xerr div d)+1); xerr := (xerr mod d)-d; end;
2041 if (yerr >= 0) then begin y += incy*((yerr div d)+1); yerr := (yerr mod d)-d; end;
2043 if (log) then e_WriteLog(Format(' jumped to tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2051 if lastWasInGrid
then exit
; // oops, stepped out of the grid -- there is no way to return
2055 // has something to process in the current cell?
2056 if (ccidx
<> -1) then
2060 // convert coords to map (to avoid ajdusting coords inside the loop)
2063 // process cell list
2064 while (curci
<> -1) do
2066 cc
:= @mCells
[curci
];
2067 for f
:= 0 to GridCellBucketSize
-1 do
2069 if (cc
.bodies
[f
] = -1) then break
;
2070 px
:= @mProxies
[cc
.bodies
[f
]];
2072 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) then
2074 px
.mQueryMark
:= lq
; // mark as processed
2075 if cb(px
.mObj
, ptag
) then begin result
:= px
.mObj
; exit
; end;
2081 ccidx
:= -1; // don't process this anymore
2082 // convert coords to grid