DEADSOFTWARE

`Grid.forEachInAABB()`: no more callbacks
[d2df-sdl.git] / src / game / g_grid.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
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.
7 *
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.
12 *
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/>.
15 *)
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}
22 {$ENDIF}
23 {.$DEFINE GRID_USE_ORTHO_ACCEL}
24 {$DEFINE LINEAABB2}
25 unit g_grid;
27 interface
29 uses
30 mempool;
32 (*
33 * In order to make this usable for kind-of-recursive calls,
34 * we'll use "frame memory pool" to return results. That is,
35 * we will allocate a memory pool that will be cleared on
36 * frame start, and then used as a simple "no-free" allocator.
37 * Grid will put results into this pool, and will never bother
38 * to free it. Caller should call "release" on result, and
39 * the pool will throw away everything.
40 * No more callbacks, of course.
41 *)
43 const
44 GridTileSize = 32; // must be power of two!
46 type
47 TBodyProxyId = Integer;
49 generic TBodyGridBase<ITP> = class{$IFDEF USE_MEMPOOL}(TPoolObject){$ENDIF}
50 public
51 type PITP = ^ITP;
53 type TGridQueryCB = function (obj: ITP; tag: Integer): Boolean is nested; // return `true` to stop
54 type TGridRayQueryCB = function (obj: ITP; tag: Integer; x, y, prevx, prevy: Integer): Boolean is nested; // return `true` to stop
55 type TCellQueryCB = procedure (x, y: Integer) is nested; // top-left cell corner coords
57 const TagDisabled = $40000000;
58 const TagFullMask = $3fffffff;
60 private
61 const
62 GridCellBucketSize = 8; // WARNING! can't be less than 2!
64 public
65 type
66 PBodyProxyRec = ^TBodyProxyRec;
67 TBodyProxyRec = record
68 private
69 mX, mY, mWidth, mHeight: Integer; // aabb
70 mQueryMark: LongWord; // was this object visited at this query?
71 mObj: ITP;
72 mTag: Integer; // `TagDisabled` set: disabled ;-)
73 nextLink: TBodyProxyId; // next free or nothing
75 private
76 procedure setup (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer);
78 function getTag (): Integer; inline;
79 procedure setTag (v: Integer); inline;
81 function getEnabled (): Boolean; inline;
82 procedure setEnabled (v: Boolean); inline;
84 function getX1 (): Integer; inline;
85 function getY1 (): Integer; inline;
87 public
88 property x: Integer read mX;
89 property y: Integer read mY;
90 property width: Integer read mWidth;
91 property height: Integer read mHeight;
92 property tag: Integer read getTag write setTag;
93 property enabled: Boolean read getEnabled write setEnabled;
94 property obj: ITP read mObj;
96 property x0: Integer read mX;
97 property y0: Integer read mY;
98 property x1: Integer read getX1;
99 property y1: Integer read getY1;
100 end;
102 private
103 type
104 PGridCell = ^TGridCell;
105 TGridCell = record
106 bodies: array [0..GridCellBucketSize-1] of Integer; // -1: end of list
107 next: Integer; // in this cell; index in mCells
108 end;
110 TCellArray = array of TGridCell;
112 TGridInternalCB = function (grida: Integer; bodyId: TBodyProxyId): Boolean of object; // return `true` to stop
114 private
115 //mTileSize: Integer;
116 const mTileSize = GridTileSize;
117 type TGetProxyFn = function (pxidx: Integer): PBodyProxyRec of object;
119 public
120 const tileSize = mTileSize;
122 type
123 TAtPointEnumerator = record
124 private
125 mCells: TCellArray;
126 curidx, curbki: Integer;
127 getpx: TGetProxyFn;
128 public
129 constructor Create (acells: TCellArray; aidx: Integer; agetpx: TGetProxyFn);
130 function MoveNext (): Boolean; inline;
131 function getCurrent (): PBodyProxyRec; inline;
132 property Current: PBodyProxyRec read getCurrent;
133 end;
135 private
136 mMinX, mMinY: Integer; // so grids can start at any origin
137 mWidth, mHeight: Integer; // in tiles
138 mGrid: array of Integer; // mWidth*mHeight, index in mCells
139 mCells: TCellArray; // cell pool
140 mFreeCell: Integer; // first free cell index or -1
141 mLastQuery: LongWord;
142 mUsedCells: Integer;
143 mProxies: array of TBodyProxyRec;
144 mProxyFree: TBodyProxyId; // free
145 mProxyCount: Integer; // currently used
146 mProxyMaxCount: Integer;
147 mInQuery: Boolean;
149 public
150 dbgShowTraceLog: Boolean;
151 {$IF DEFINED(D2F_DEBUG)}
152 dbgRayTraceTileHitCB: TCellQueryCB;
153 {$ENDIF}
155 private
156 function allocCell (): Integer;
157 procedure freeCell (idx: Integer); // `next` is simply overwritten
159 function allocProxy (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer): TBodyProxyId;
160 procedure freeProxy (body: TBodyProxyId);
162 function forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
164 function inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
165 function remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
167 function getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
168 procedure setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
170 function getGridWidthPx (): Integer; inline;
171 function getGridHeightPx (): Integer; inline;
173 function getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
175 public
176 constructor Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
177 destructor Destroy (); override;
179 function insertBody (aObj: ITP; ax, ay, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
180 procedure removeBody (body: TBodyProxyId); // WARNING! this WILL destroy proxy!
182 procedure moveBody (body: TBodyProxyId; nx, ny: Integer);
183 procedure resizeBody (body: TBodyProxyId; nw, nh: Integer);
184 procedure moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
186 function insideGrid (x, y: Integer): Boolean; inline;
188 // `false` if `body` is surely invalid
189 function getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
190 function getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
191 function getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
193 //WARNING: don't modify grid while any query is in progress (no checks are made!)
194 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
195 // no callback: return `true` on the first hit
196 //function forEachInAABB (x, y, w, h: Integer; cb: TGridQueryCB; tagmask: Integer=-1; allowDisabled: Boolean=false): ITP;
197 // return number of ITP thingys put into frame pool
198 function forEachInAABB (x, y, w, h: Integer; tagmask: Integer=-1; allowDisabled: Boolean=false; firstHit: Boolean=false): Integer;
200 //WARNING: don't modify grid while any query is in progress (no checks are made!)
201 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
202 // no callback: return object on the first hit or nil
203 function forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
205 function atCellInPoint (x, y: Integer): TAtPointEnumerator;
207 //WARNING: don't modify grid while any query is in progress (no checks are made!)
208 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
209 // cb with `(nil)` will be called before processing new tile
210 // no callback: return object of the nearest hit or nil
211 // if `inverted` is true, trace will register bodies *exluding* tagmask
212 //WARNING: don't change tags in callbacks here!
214 function traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP; overload;
215 function traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
218 //WARNING: don't modify grid while any query is in progress (no checks are made!)
219 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
220 // cb with `(nil)` will be called before processing new tile
221 // no callback: return object of the nearest hit or nil
222 // if `inverted` is true, trace will register bodies *exluding* tagmask
223 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
224 //WARNING: don't change tags in callbacks here!
225 function traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP; overload;
226 function traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
228 // return `false` if we're still inside at the end
229 // line should be either strict horizontal, or strict vertical, otherwise an exception will be thrown
230 // `true`: endpoint will point at the last "inside" pixel
231 // `false`: endpoint will be (ax1, ay1)
232 //WARNING: don't change tags in callbacks here!
233 function traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
235 //WARNING: don't modify grid while any query is in progress (no checks are made!)
236 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
237 // trace line along the grid, calling `cb` for all objects in passed cells, in no particular order
238 //WARNING: don't change tags in callbacks here!
239 function forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
241 // trace box with the given velocity; return object hit (if any)
242 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
243 //WARNING: don't change tags in callbacks here!
244 function traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
246 // debug
247 procedure forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
248 function forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
249 procedure dumpStats ();
251 public
252 //WARNING! no sanity checks!
253 property proxyEnabled[pid: TBodyProxyId]: Boolean read getProxyEnabled write setProxyEnabled;
255 property gridX0: Integer read mMinX;
256 property gridY0: Integer read mMinY;
257 property gridWidth: Integer read getGridWidthPx; // in pixels
258 property gridHeight: Integer read getGridHeightPx; // in pixels
260 property proxy[idx: TBodyProxyId]: PBodyProxyRec read getProxyById;
261 end;
264 type
265 // common structure for all line tracers
266 TLineWalker = record
267 public
268 const TileSize = GridTileSize;
270 private
271 wx0, wy0, wx1, wy1: Integer; // window coordinates
272 stx, sty: Integer; // "steps" for x and y axes
273 stleft: Integer; // "steps left"
274 err, errinc, errmax: Integer;
275 xd, yd: Integer; // current coord
276 horiz: Boolean;
278 public
279 // call `setyp` after this
280 constructor Create (minx, miny, maxx, maxy: Integer);
282 procedure setClip (minx, miny, maxx, maxy: Integer); inline;
284 // this will use `w[xy][01]` to clip coords
285 // return `false` if the whole line was clipped away
286 // on `true`, you should process first point, and go on
287 function setup (x0, y0, x1, y1: Integer): Boolean;
289 // call this *after* doing a step
290 // WARNING! if you will do a step when this returns `true`, you will fall into limbo
291 function done (): Boolean; inline;
293 // as you will prolly call `done()` after doing a step anyway, this will do it for you
294 // move to next point, return `true` when the line is complete (i.e. you should stop)
295 function step (): Boolean; inline;
297 // move to next tile; return `true` if the line is complete (and walker state is undefined then)
298 function stepToNextTile (): Boolean; inline;
300 procedure getXY (out ox, oy: Integer); inline;
302 public
303 // current coords
304 property x: Integer read xd;
305 property y: Integer read yd;
306 end;
309 procedure swapInt (var a: Integer; var b: Integer); inline;
310 //function minInt (a, b: Integer): Integer; inline;
311 //function maxInt (a, b: Integer): Integer; inline;
314 implementation
316 uses
317 SysUtils, e_log, g_console, geom, utils;
320 // ////////////////////////////////////////////////////////////////////////// //
321 procedure swapInt (var a: Integer; var b: Integer); inline; var t: Integer; begin t := a; a := b; b := t; end;
322 //procedure swapInt (var a: Integer; var b: Integer); inline; begin a := a xor b; b := b xor a; a := a xor b; end;
323 //function minInt (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
324 //function maxInt (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
327 // ////////////////////////////////////////////////////////////////////////// //
328 constructor TLineWalker.Create (minx, miny, maxx, maxy: Integer);
329 begin
330 setClip(minx, miny, maxx, maxy);
331 end;
333 procedure TLineWalker.setClip (minx, miny, maxx, maxy: Integer); inline;
334 begin
335 // clip rectange
336 wx0 := minx;
337 wy0 := miny;
338 wx1 := maxx;
339 wy1 := maxy;
340 end;
342 function TLineWalker.setup (x0, y0, x1, y1: Integer): Boolean;
343 var
344 sx0, sy0, sx1, sy1: Single;
345 begin
346 if (wx1 < wx0) or (wy1 < wy0) then begin stleft := 0; xd := x0; yd := y0; result := false; exit; end;
348 if (x0 >= wx0) and (y0 >= wy0) and (x0 <= wx1) and (y0 <= wy1) and
349 (x1 >= wx0) and (y1 >= wy0) and (x1 <= wx1) and (y1 <= wy1) then
350 begin
351 result := true;
352 end
353 else
354 begin
355 sx0 := x0; sy0 := y0;
356 sx1 := x1; sy1 := y1;
357 result := clipLine(sx0, sy0, sx1, sy1, wx0, wy0, wx1, wy1);
358 if not result then begin stleft := 0; xd := x0; yd := y0; exit; end;
359 x0 := trunc(sx0); y0 := trunc(sy0);
360 x1 := trunc(sx1); y1 := trunc(sy1);
361 end;
363 // check for ortho lines
364 if (y0 = y1) then
365 begin
366 // horizontal
367 horiz := true;
368 stleft := abs(x1-x0)+1;
369 if (x0 < x1) then stx := 1 else stx := -1;
370 sty := 0;
371 errinc := 0;
372 errmax := 10; // anything that is greater than zero
373 end
374 else if (x0 = x1) then
375 begin
376 // vertical
377 horiz := false;
378 stleft := abs(y1-y0)+1;
379 stx := 0;
380 if (y0 < y1) then sty := 1 else sty := -1;
381 errinc := 0;
382 errmax := 10; // anything that is greater than zero
383 end
384 else
385 begin
386 // diagonal
387 if (abs(x1-x0) >= abs(y1-y0)) then
388 begin
389 // horizontal
390 horiz := true;
391 stleft := abs(x1-x0)+1;
392 errinc := abs(y1-y0)+1;
393 end
394 else
395 begin
396 // vertical
397 horiz := false;
398 stleft := abs(y1-y0)+1;
399 errinc := abs(x1-x0)+1;
400 end;
401 if (x0 < x1) then stx := 1 else stx := -1;
402 if (y0 < y1) then sty := 1 else sty := -1;
403 errmax := stleft;
404 end;
405 xd := x0;
406 yd := y0;
407 err := -errmax;
408 end;
410 function TLineWalker.done (): Boolean; inline; begin result := (stleft <= 0); end;
412 // true: done
413 function TLineWalker.step (): Boolean; inline;
414 begin
415 if horiz then
416 begin
417 xd += stx;
418 err += errinc;
419 if (err >= 0) then begin err -= errmax; yd += sty; end;
420 end
421 else
422 begin
423 yd += sty;
424 err += errinc;
425 if (err >= 0) then begin err -= errmax; xd += stx; end;
426 end;
427 Dec(stleft);
428 result := (stleft <= 0);
429 end;
431 // true: done
432 function TLineWalker.stepToNextTile (): Boolean; inline;
433 var
434 ex, ey: Integer;
435 xwalk, ywalk, wklen: Integer; // to the respective edges
436 f: Integer;
437 begin
438 result := false;
440 if (stleft < 2) then begin result := true; exit; end; // max one pixel left, nothing to do
442 // strictly horizontal?
443 if (sty = 0) then
444 begin
445 // only xd
446 if (stx < 0) then
447 begin
448 // xd: to left edge
449 ex := (xd and (not (TileSize-1)))-1;
450 stleft -= xd-ex;
451 end
452 else
453 begin
454 // xd: to right edge
455 ex := (xd or (TileSize-1))+1;
456 stleft -= ex-xd;
457 end;
458 result := (stleft <= 0);
459 xd := ex;
460 exit;
461 end;
463 // strictly vertical?
464 if (stx = 0) then
465 begin
466 // only xd
467 if (sty < 0) then
468 begin
469 // yd: to top edge
470 ey := (yd and (not (TileSize-1)))-1;
471 stleft -= yd-ey;
472 end
473 else
474 begin
475 // yd: to bottom edge
476 ey := (yd or (TileSize-1))+1;
477 stleft -= ey-yd;
478 end;
479 result := (stleft <= 0);
480 yd := ey;
481 exit;
482 end;
484 // diagonal
486 // calculate xwalk
487 if (stx < 0) then
488 begin
489 ex := (xd and (not (TileSize-1)))-1;
490 xwalk := xd-ex;
491 end
492 else
493 begin
494 ex := (xd or (TileSize-1))+1;
495 xwalk := ex-xd;
496 end;
498 // calculate ywalk
499 if (sty < 0) then
500 begin
501 ey := (yd and (not (TileSize-1)))-1;
502 ywalk := yd-ey;
503 end
504 else
505 begin
506 ey := (yd or (TileSize-1))+1;
507 ywalk := ey-yd;
508 end;
511 while (xd <> ex) and (yd <> ey) do
512 begin
513 if horiz then
514 begin
515 xd += stx;
516 err += errinc;
517 if (err >= 0) then begin err -= errmax; yd += sty; end;
518 end
519 else
520 begin
521 yd += sty;
522 err += errinc;
523 if (err >= 0) then begin err -= errmax; xd += stx; end;
524 end;
525 Dec(stleft);
526 if (stleft < 1) then begin result := true; exit; end;
527 end;
530 if (xwalk <= ywalk) then wklen := xwalk else wklen := ywalk;
531 while true do
532 begin
533 // in which dir we want to walk?
534 stleft -= wklen;
535 if (stleft <= 0) then begin result := true; exit; end;
536 if horiz then
537 begin
538 xd += wklen*stx;
539 for f := 1 to wklen do
540 begin
541 err += errinc;
542 if (err >= 0) then begin err -= errmax; yd += sty; end;
543 end;
544 end
545 else
546 begin
547 yd += wklen*sty;
548 for f := 1 to wklen do
549 begin
550 err += errinc;
551 if (err >= 0) then begin err -= errmax; xd += stx; end;
552 end;
553 end;
554 // check for walk completion
555 if (xd = ex) or (yd = ey) then exit;
556 wklen := 1;
557 end;
558 end;
560 procedure TLineWalker.getXY (out ox, oy: Integer); inline; begin ox := xd; oy := yd; end;
563 // ////////////////////////////////////////////////////////////////////////// //
564 procedure TBodyGridBase.TBodyProxyRec.setup (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer);
565 begin
566 mX := aX;
567 mY := aY;
568 mWidth := aWidth;
569 mHeight := aHeight;
570 mQueryMark := 0;
571 mObj := aObj;
572 mTag := aTag;
573 nextLink := -1;
574 end;
577 function TBodyGridBase.TBodyProxyRec.getTag (): Integer; inline;
578 begin
579 result := mTag and TagFullMask;
580 end;
582 procedure TBodyGridBase.TBodyProxyRec.setTag (v: Integer); inline;
583 begin
584 mTag := (mTag and TagDisabled) or (v and TagFullMask);
585 end;
587 function TBodyGridBase.TBodyProxyRec.getEnabled (): Boolean; inline;
588 begin
589 result := ((mTag and TagDisabled) = 0);
590 end;
592 procedure TBodyGridBase.TBodyProxyRec.setEnabled (v: Boolean); inline;
593 begin
594 if v then mTag := mTag and (not TagDisabled) else mTag := mTag or TagDisabled;
595 end;
597 function TBodyGridBase.TBodyProxyRec.getX1 (): Integer; inline;
598 begin
599 result := mX+mWidth-1;
600 end;
602 function TBodyGridBase.TBodyProxyRec.getY1 (): Integer; inline;
603 begin
604 result := mY+mHeight-1;
605 end;
608 // ////////////////////////////////////////////////////////////////////////// //
609 constructor TBodyGridBase.TAtPointEnumerator.Create (acells: TCellArray; aidx: Integer; agetpx: TGetProxyFn);
610 begin
611 mCells := acells;
612 curidx := aidx;
613 curbki := -1;
614 getpx := agetpx;
615 end;
618 function TBodyGridBase.TAtPointEnumerator.MoveNext (): Boolean; inline;
619 begin
620 while (curidx <> -1) do
621 begin
622 while (curbki < GridCellBucketSize) do
623 begin
624 Inc(curbki);
625 if (mCells[curidx].bodies[curbki] = -1) then break;
626 result := true;
627 exit;
628 end;
629 curidx := mCells[curidx].next;
630 curbki := -1;
631 end;
632 result := false;
633 end;
636 function TBodyGridBase.TAtPointEnumerator.getCurrent (): PBodyProxyRec; inline;
637 begin
638 result := getpx(mCells[curidx].bodies[curbki]);
639 end;
642 // ////////////////////////////////////////////////////////////////////////// //
643 constructor TBodyGridBase.Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
644 var
645 idx: Integer;
646 begin
647 dbgShowTraceLog := false;
648 {$IF DEFINED(D2F_DEBUG)}
649 dbgRayTraceTileHitCB := nil;
650 {$ENDIF}
652 if aTileSize < 1 then aTileSize := 1;
653 if aTileSize > 8192 then aTileSize := 8192; // arbitrary limit
654 mTileSize := aTileSize;
656 if (aPixWidth < mTileSize) then aPixWidth := mTileSize;
657 if (aPixHeight < mTileSize) then aPixHeight := mTileSize;
658 mMinX := aMinPixX;
659 mMinY := aMinPixY;
660 mWidth := (aPixWidth+mTileSize-1) div mTileSize;
661 mHeight := (aPixHeight+mTileSize-1) div mTileSize;
662 SetLength(mGrid, mWidth*mHeight);
663 SetLength(mCells, mWidth*mHeight);
664 SetLength(mProxies, 8192);
665 mFreeCell := 0;
666 // init free list
667 for idx := 0 to High(mCells) do
668 begin
669 mCells[idx].bodies[0] := -1;
670 mCells[idx].bodies[GridCellBucketSize-1] := -1; // "has free room" flag
671 mCells[idx].next := idx+1;
672 end;
673 mCells[High(mCells)].next := -1; // last cell
674 // init grid
675 for idx := 0 to High(mGrid) do mGrid[idx] := -1;
676 // init proxies
677 for idx := 0 to High(mProxies) do mProxies[idx].nextLink := idx+1;
678 mProxies[High(mProxies)].nextLink := -1;
679 mLastQuery := 0;
680 mUsedCells := 0;
681 mProxyFree := 0;
682 mProxyCount := 0;
683 mProxyMaxCount := 0;
684 e_WriteLog(Format('created grid with size: %dx%d (tile size: %d); pix: %dx%d', [mWidth, mHeight, mTileSize, mWidth*mTileSize, mHeight*mTileSize]), TMsgType.Notify);
685 end;
688 destructor TBodyGridBase.Destroy ();
689 begin
690 mCells := nil;
691 mGrid := nil;
692 mProxies := nil;
693 inherited;
694 end;
697 // ////////////////////////////////////////////////////////////////////////// //
698 procedure TBodyGridBase.dumpStats ();
699 var
700 idx, mcb, ccidx, cnt: Integer;
701 begin
702 mcb := 0;
703 for idx := 0 to High(mGrid) do
704 begin
705 ccidx := mGrid[idx];
706 cnt := 0;
707 while ccidx >= 0 do
708 begin
709 Inc(cnt);
710 ccidx := mCells[ccidx].next;
711 end;
712 if (mcb < cnt) then mcb := cnt;
713 end;
714 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]), TMsgType.Notify);
715 end;
718 procedure TBodyGridBase.forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
719 var
720 g, f, ccidx: Integer;
721 cc: PGridCell;
722 begin
723 if (body < 0) or (body > High(mProxies)) or not assigned(cb) then exit;
724 for g := 0 to High(mGrid) do
725 begin
726 ccidx := mGrid[g];
727 while (ccidx <> -1) do
728 begin
729 cc := @mCells[ccidx];
730 for f := 0 to GridCellBucketSize-1 do
731 begin
732 if (cc.bodies[f] = -1) then break;
733 if (cc.bodies[f] = body) then cb((g mod mWidth)*mTileSize+mMinX, (g div mWidth)*mTileSize+mMinY);
734 end;
735 // next cell
736 ccidx := cc.next;
737 end;
738 end;
739 end;
742 function TBodyGridBase.forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
743 var
744 f, ccidx: Integer;
745 cc: PGridCell;
746 begin
747 result := Default(ITP);
748 if not assigned(cb) then exit;
749 Dec(x, mMinX);
750 Dec(y, mMinY);
751 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y > mHeight*mTileSize) then exit;
752 ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
753 while (ccidx <> -1) do
754 begin
755 cc := @mCells[ccidx];
756 for f := 0 to GridCellBucketSize-1 do
757 begin
758 if (cc.bodies[f] = -1) then break;
759 if cb(mProxies[cc.bodies[f]].mObj, mProxies[cc.bodies[f]].mTag) then begin result := mProxies[cc.bodies[f]].mObj; exit; end;
760 end;
761 // next cell
762 ccidx := cc.next;
763 end;
764 end;
767 // ////////////////////////////////////////////////////////////////////////// //
768 function TBodyGridBase.getGridWidthPx (): Integer; inline; begin result := mWidth*mTileSize; end;
769 function TBodyGridBase.getGridHeightPx (): Integer; inline; begin result := mHeight*mTileSize; end;
772 function TBodyGridBase.insideGrid (x, y: Integer): Boolean; inline;
773 begin
774 // fix coords
775 Dec(x, mMinX);
776 Dec(y, mMinY);
777 result := (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize);
778 end;
781 function TBodyGridBase.getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
782 begin
783 if (body >= 0) and (body < Length(mProxies)) then
784 begin
785 with mProxies[body] do begin rx := mX; ry := mY; end;
786 result := true;
787 end
788 else
789 begin
790 rx := 0;
791 ry := 0;
792 result := false;
793 end;
794 end;
797 function TBodyGridBase.getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
798 begin
799 if (body >= 0) and (body < Length(mProxies)) then
800 begin
801 with mProxies[body] do begin rw := mWidth; rh := mHeight; end;
802 result := true;
803 end
804 else
805 begin
806 rw := 0;
807 rh := 0;
808 result := false;
809 end;
810 end;
813 function TBodyGridBase.getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
814 begin
815 if (body >= 0) and (body < Length(mProxies)) then
816 begin
817 with mProxies[body] do begin rx := mX; ry := mY; rw := mWidth; rh := mHeight; end;
818 result := true;
819 end
820 else
821 begin
822 rx := 0;
823 ry := 0;
824 rw := 0;
825 rh := 0;
826 result := false;
827 end;
828 end;
832 // ////////////////////////////////////////////////////////////////////////// //
833 function TBodyGridBase.getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
834 begin
835 if (pid >= 0) and (pid < Length(mProxies)) then result := ((mProxies[pid].mTag and TagDisabled) = 0) else result := false;
836 end;
839 procedure TBodyGridBase.setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
840 begin
841 if (pid >= 0) and (pid < Length(mProxies)) then
842 begin
843 if val then
844 begin
845 mProxies[pid].mTag := mProxies[pid].mTag and not TagDisabled;
846 end
847 else
848 begin
849 mProxies[pid].mTag := mProxies[pid].mTag or TagDisabled;
850 end;
851 end;
852 end;
855 function TBodyGridBase.getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
856 begin
857 if (idx >= 0) and (idx < Length(mProxies)) then result := @mProxies[idx] else result := nil;
858 end;
861 // ////////////////////////////////////////////////////////////////////////// //
862 function TBodyGridBase.allocCell (): Integer;
863 var
864 idx: Integer;
865 pc: PGridCell;
866 begin
867 if (mFreeCell < 0) then
868 begin
869 // no free cells, want more
870 mFreeCell := Length(mCells);
871 SetLength(mCells, mFreeCell+32768); // arbitrary number
872 for idx := mFreeCell to High(mCells) do
873 begin
874 mCells[idx].bodies[0] := -1;
875 mCells[idx].bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
876 mCells[idx].next := idx+1;
877 end;
878 mCells[High(mCells)].next := -1; // last cell
879 end;
880 result := mFreeCell;
881 pc := @mCells[result];
882 mFreeCell := pc.next;
883 pc.next := -1;
884 Inc(mUsedCells);
885 //e_WriteLog(Format('grid: allocated new cell #%d (total: %d)', [result, mUsedCells]), MSG_NOTIFY);
886 end;
889 procedure TBodyGridBase.freeCell (idx: Integer);
890 begin
891 if (idx >= 0) and (idx < Length(mCells)) then
892 begin
893 with mCells[idx] do
894 begin
895 bodies[0] := -1;
896 bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
897 next := mFreeCell;
898 end;
899 mFreeCell := idx;
900 Dec(mUsedCells);
901 end;
902 end;
905 // ////////////////////////////////////////////////////////////////////////// //
906 function TBodyGridBase.allocProxy (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer): TBodyProxyId;
907 var
908 olen, idx: Integer;
909 px: PBodyProxyRec;
910 begin
911 if (mProxyFree = -1) then
912 begin
913 // no free proxies, resize list
914 olen := Length(mProxies);
915 SetLength(mProxies, olen+8192); // arbitrary number
916 for idx := olen to High(mProxies) do mProxies[idx].nextLink := idx+1;
917 mProxies[High(mProxies)].nextLink := -1;
918 mProxyFree := olen;
919 end;
920 // get one from list
921 result := mProxyFree;
922 px := @mProxies[result];
923 mProxyFree := px.nextLink;
924 px.setup(aX, aY, aWidth, aHeight, aObj, aTag);
925 // add to used list
926 px.nextLink := -1;
927 // statistics
928 Inc(mProxyCount);
929 if (mProxyMaxCount < mProxyCount) then mProxyMaxCount := mProxyCount;
930 end;
932 procedure TBodyGridBase.freeProxy (body: TBodyProxyId);
933 begin
934 if (body < 0) or (body > High(mProxies)) then exit; // just in case
935 if (mProxyCount = 0) then raise Exception.Create('wutafuuuuu in grid (no allocated proxies, what i should free now?)');
936 // add to free list
937 mProxies[body].mObj := nil;
938 mProxies[body].nextLink := mProxyFree;
939 mProxyFree := body;
940 Dec(mProxyCount);
941 end;
944 // ////////////////////////////////////////////////////////////////////////// //
945 function TBodyGridBase.forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
946 var
947 gw, gh: Integer;
948 ex, ey: Integer;
949 gx, gy: Integer;
950 begin
951 result := false;
952 if (w < 1) or (h < 1) or not assigned(cb) then exit;
953 // fix coords
954 Dec(x, mMinX);
955 Dec(y, mMinY);
956 // go on
957 if (x+w <= 0) or (y+h <= 0) then exit;
958 gw := mWidth;
959 gh := mHeight;
960 if (x >= gw*mTileSize) or (y >= gh*mTileSize) then exit;
961 ex := (x+w-1) div mTileSize;
962 ey := (y+h-1) div mTileSize;
963 x := x div mTileSize;
964 y := y div mTileSize;
965 // clip rect
966 if (x < 0) then x := 0 else if (x >= gw) then x := gw-1;
967 if (y < 0) then y := 0 else if (y >= gh) then y := gh-1;
968 if (ex < 0) then ex := 0 else if (ex >= gw) then ex := gw-1;
969 if (ey < 0) then ey := 0 else if (ey >= gh) then ey := gh-1;
970 if (x > ex) or (y > ey) then exit; // just in case
971 // do the work
972 for gy := y to ey do
973 begin
974 for gx := x to ex do
975 begin
976 result := cb(gy*gw+gx, bodyId);
977 if result then exit;
978 end;
979 end;
980 end;
983 // ////////////////////////////////////////////////////////////////////////// //
984 function TBodyGridBase.inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
985 var
986 ccidx: Integer;
987 pc: Integer;
988 pi: PGridCell;
989 f: Integer;
990 begin
991 result := false; // never stop
992 // add body to the given grid cell
993 pc := mGrid[grida];
994 if (pc <> -1) then
995 begin
996 {$IF DEFINED(D2F_DEBUG)}
997 ccidx := pc;
998 while (ccidx <> -1) do
999 begin
1000 pi := @mCells[ccidx];
1001 for f := 0 to GridCellBucketSize-1 do
1002 begin
1003 if (pi.bodies[f] = -1) then break;
1004 if (pi.bodies[f] = bodyId) then raise Exception.Create('trying to insert already inserted proxy');
1005 end;
1006 ccidx := pi.next;
1007 end;
1008 {$ENDIF}
1009 ccidx := pc;
1010 while (ccidx <> -1) do
1011 begin
1012 pi := @mCells[ccidx];
1013 // check "has room" flag
1014 if (pi.bodies[GridCellBucketSize-1] = -1) then
1015 begin
1016 // can add here
1017 for f := 0 to GridCellBucketSize-1 do
1018 begin
1019 if (pi.bodies[f] = -1) then
1020 begin
1021 pi.bodies[f] := bodyId;
1022 if (f+1 < GridCellBucketSize) then pi.bodies[f+1] := -1;
1023 exit;
1024 end;
1025 end;
1026 raise Exception.Create('internal error in grid inserter');
1027 end;
1028 // no room, go to next cell in list (if there is any)
1029 ccidx := pi.next;
1030 end;
1031 // no room in cells, add new cell to list
1032 end;
1033 // either no room, or no cell at all
1034 ccidx := allocCell();
1035 pi := @mCells[ccidx];
1036 pi.bodies[0] := bodyId;
1037 pi.bodies[1] := -1;
1038 pi.next := pc;
1039 mGrid[grida] := ccidx;
1040 end;
1043 // assume that we cannot have one object added to bucket twice
1044 function TBodyGridBase.remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
1045 var
1046 f, c: Integer;
1047 pidx, ccidx: Integer;
1048 pc: PGridCell;
1049 begin
1050 result := false; // never stop
1051 // find and remove cell
1052 pidx := -1; // previous cell index
1053 ccidx := mGrid[grida]; // current cell index
1054 while (ccidx <> -1) do
1055 begin
1056 pc := @mCells[ccidx];
1057 for f := 0 to GridCellBucketSize-1 do
1058 begin
1059 if (pc.bodies[f] = bodyId) then
1060 begin
1061 // i found her!
1062 if (f = 0) and (pc.bodies[1] = -1) then
1063 begin
1064 // this cell contains no elements, remove it
1065 if (pidx = -1) then mGrid[grida] := pc.next else mCells[pidx].next := pc.next;
1066 freeCell(ccidx);
1067 exit;
1068 end;
1069 // remove element from bucket
1070 for c := f to GridCellBucketSize-2 do
1071 begin
1072 pc.bodies[c] := pc.bodies[c+1];
1073 if (pc.bodies[c] = -1) then break;
1074 end;
1075 pc.bodies[GridCellBucketSize-1] := -1; // "has free room" flag
1076 exit;
1077 end;
1078 end;
1079 pidx := ccidx;
1080 ccidx := pc.next;
1081 end;
1082 end;
1085 // ////////////////////////////////////////////////////////////////////////// //
1086 function TBodyGridBase.insertBody (aObj: ITP; aX, aY, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
1087 begin
1088 aTag := aTag and TagFullMask;
1089 result := allocProxy(aX, aY, aWidth, aHeight, aObj, aTag);
1090 //insertInternal(result);
1091 forGridRect(aX, aY, aWidth, aHeight, inserter, result);
1092 end;
1095 procedure TBodyGridBase.removeBody (body: TBodyProxyId);
1096 var
1097 px: PBodyProxyRec;
1098 begin
1099 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1100 px := @mProxies[body];
1101 //removeInternal(body);
1102 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1103 freeProxy(body);
1104 end;
1107 // ////////////////////////////////////////////////////////////////////////// //
1108 procedure TBodyGridBase.moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
1109 var
1110 px: PBodyProxyRec;
1111 x0, y0, w, h: Integer;
1112 begin
1113 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1114 px := @mProxies[body];
1115 x0 := px.mX;
1116 y0 := px.mY;
1117 w := px.mWidth;
1118 h := px.mHeight;
1119 {$IF DEFINED(D2F_DEBUG_MOVER)}
1120 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);
1121 {$ENDIF}
1122 if (nx = x0) and (ny = y0) and (nw = w) and (nh = h) then exit;
1123 // map -> grid
1124 Dec(x0, mMinX);
1125 Dec(y0, mMinY);
1126 Dec(nx, mMinX);
1127 Dec(ny, mMinY);
1128 // did any corner crossed tile boundary?
1129 if (x0 div mTileSize <> nx div mTileSize) or
1130 (y0 div mTileSize <> ny div mTileSize) or
1131 ((x0+w-1) div mTileSize <> (nx+nw-1) div mTileSize) or
1132 ((y0+h-1) div mTileSize <> (ny+nh-1) div mTileSize) then
1133 begin
1134 //writeln('moveResizeBody: cell occupation changed! old=(', x0, ',', y0, ')-(', x0+w-1, ',', y0+h-1, '); new=(', nx, ',', ny, ')-(', nx+nw-1, ',', ny+nh-1, ')');
1135 //removeInternal(body);
1136 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1137 px.mX := nx+mMinX;
1138 px.mY := ny+mMinY;
1139 px.mWidth := nw;
1140 px.mHeight := nh;
1141 //insertInternal(body);
1142 forGridRect(px.mX, px.mY, nw, nh, inserter, body);
1143 end
1144 else
1145 begin
1146 px.mX := nx+mMinX;
1147 px.mY := ny+mMinY;
1148 px.mWidth := nw;
1149 px.mHeight := nh;
1150 end;
1151 end;
1154 //TODO: optimize for horizontal/vertical moves
1155 procedure TBodyGridBase.moveBody (body: TBodyProxyId; nx, ny: Integer);
1156 var
1157 px: PBodyProxyRec;
1158 x0, y0: Integer;
1159 ogx0, ogx1, ogy0, ogy1: Integer; // old grid rect
1160 ngx0, ngx1, ngy0, ngy1: Integer; // new grid rect
1161 gx, gy: Integer;
1162 gw, gh: Integer;
1163 pw, ph: Integer;
1164 begin
1165 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1166 // check if tile coords was changed
1167 px := @mProxies[body];
1168 x0 := px.mX;
1169 y0 := px.mY;
1170 if (nx = x0) and (ny = y0) then exit;
1171 // map -> grid
1172 Dec(x0, mMinX);
1173 Dec(y0, mMinY);
1174 Dec(nx, mMinX);
1175 Dec(ny, mMinY);
1176 // check for heavy work
1177 pw := px.mWidth;
1178 ph := px.mHeight;
1179 ogx0 := x0 div mTileSize;
1180 ogy0 := y0 div mTileSize;
1181 ngx0 := nx div mTileSize;
1182 ngy0 := ny div mTileSize;
1183 ogx1 := (x0+pw-1) div mTileSize;
1184 ogy1 := (y0+ph-1) div mTileSize;
1185 ngx1 := (nx+pw-1) div mTileSize;
1186 ngy1 := (ny+ph-1) div mTileSize;
1187 {$IF DEFINED(D2F_DEBUG_MOVER)}
1188 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);
1189 {$ENDIF}
1190 if (ogx0 <> ngx0) or (ogy0 <> ngy0) or (ogx1 <> ngx1) or (ogy1 <> ngy1) then
1191 begin
1192 // crossed tile boundary, do heavy work
1193 gw := mWidth;
1194 gh := mHeight;
1195 // cycle with old rect, remove body where it is necessary
1196 // optimized for horizontal moves
1197 {$IF DEFINED(D2F_DEBUG_MOVER)}
1198 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);
1199 {$ENDIF}
1200 // remove stale marks
1201 if not ((ogy0 >= gh) or (ogy1 < 0)) and
1202 not ((ogx0 >= gw) or (ogx1 < 0)) then
1203 begin
1204 if (ogx0 < 0) then ogx0 := 0;
1205 if (ogy0 < 0) then ogy0 := 0;
1206 if (ogx1 > gw-1) then ogx1 := gw-1;
1207 if (ogy1 > gh-1) then ogy1 := gh-1;
1208 {$IF DEFINED(D2F_DEBUG_MOVER)}
1209 e_WriteLog(Format(' norm og:(%d,%d)-(%d,%d)', [ogx0, ogy0, ogx1, ogy1]), MSG_NOTIFY);
1210 {$ENDIF}
1211 for gx := ogx0 to ogx1 do
1212 begin
1213 if (gx < ngx0) or (gx > ngx1) then
1214 begin
1215 // this column is completely outside of new rect
1216 for gy := ogy0 to ogy1 do
1217 begin
1218 {$IF DEFINED(D2F_DEBUG_MOVER)}
1219 e_WriteLog(Format(' remove0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1220 {$ENDIF}
1221 remover(gy*gw+gx, body);
1222 end;
1223 end
1224 else
1225 begin
1226 // heavy checks
1227 for gy := ogy0 to ogy1 do
1228 begin
1229 if (gy < ngy0) or (gy > ngy1) then
1230 begin
1231 {$IF DEFINED(D2F_DEBUG_MOVER)}
1232 e_WriteLog(Format(' remove1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1233 {$ENDIF}
1234 remover(gy*gw+gx, body);
1235 end;
1236 end;
1237 end;
1238 end;
1239 end;
1240 // cycle with new rect, add body where it is necessary
1241 if not ((ngy0 >= gh) or (ngy1 < 0)) and
1242 not ((ngx0 >= gw) or (ngx1 < 0)) then
1243 begin
1244 if (ngx0 < 0) then ngx0 := 0;
1245 if (ngy0 < 0) then ngy0 := 0;
1246 if (ngx1 > gw-1) then ngx1 := gw-1;
1247 if (ngy1 > gh-1) then ngy1 := gh-1;
1248 {$IF DEFINED(D2F_DEBUG_MOVER)}
1249 e_WriteLog(Format(' norm ng:(%d,%d)-(%d,%d)', [ngx0, ngy0, ngx1, ngy1]), MSG_NOTIFY);
1250 {$ENDIF}
1251 for gx := ngx0 to ngx1 do
1252 begin
1253 if (gx < ogx0) or (gx > ogx1) then
1254 begin
1255 // this column is completely outside of old rect
1256 for gy := ngy0 to ngy1 do
1257 begin
1258 {$IF DEFINED(D2F_DEBUG_MOVER)}
1259 e_WriteLog(Format(' insert0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1260 {$ENDIF}
1261 inserter(gy*gw+gx, body);
1262 end;
1263 end
1264 else
1265 begin
1266 // heavy checks
1267 for gy := ngy0 to ngy1 do
1268 begin
1269 if (gy < ogy0) or (gy > ogy1) then
1270 begin
1271 {$IF DEFINED(D2F_DEBUG_MOVER)}
1272 e_WriteLog(Format(' insert1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1273 {$ENDIF}
1274 inserter(gy*gw+gx, body);
1275 end;
1276 end;
1277 end;
1278 end;
1279 end;
1280 // done
1281 end
1282 else
1283 begin
1284 {$IF DEFINED(D2F_DEBUG_MOVER)}
1285 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);
1286 {$ENDIF}
1287 end;
1288 // update coordinates
1289 px.mX := nx+mMinX;
1290 px.mY := ny+mMinY;
1291 end;
1294 procedure TBodyGridBase.resizeBody (body: TBodyProxyId; nw, nh: Integer);
1295 var
1296 px: PBodyProxyRec;
1297 x0, y0, w, h: Integer;
1298 begin
1299 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1300 // check if tile coords was changed
1301 px := @mProxies[body];
1302 x0 := px.mX-mMinX;
1303 y0 := px.mY-mMinY;
1304 w := px.mWidth;
1305 h := px.mHeight;
1306 {$IF DEFINED(D2F_DEBUG_MOVER)}
1307 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);
1308 {$ENDIF}
1309 if ((x0+w-1) div mTileSize <> (x0+nw-1) div mTileSize) or
1310 ((y0+h-1) div mTileSize <> (y0+nh-1) div mTileSize) then
1311 begin
1312 // crossed tile boundary, do heavy work
1313 //removeInternal(body);
1314 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1315 px.mWidth := nw;
1316 px.mHeight := nh;
1317 //insertInternal(body);
1318 forGridRect(px.mX, px.mY, nw, nh, inserter, body);
1319 end
1320 else
1321 begin
1322 // nothing to do with the grid, just fix size
1323 px.mWidth := nw;
1324 px.mHeight := nh;
1325 end;
1326 end;
1329 // ////////////////////////////////////////////////////////////////////////// //
1330 function TBodyGridBase.atCellInPoint (x, y: Integer): TAtPointEnumerator;
1331 var
1332 ccidx: Integer = -1;
1333 begin
1334 Dec(x, mMinX);
1335 Dec(y, mMinY);
1336 if (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize) then ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1337 result := TAtPointEnumerator.Create(mCells, ccidx, getProxyById);
1338 end;
1341 // ////////////////////////////////////////////////////////////////////////// //
1342 // no callback: return `true` on the first hit
1343 function TBodyGridBase.forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
1344 var
1345 f: Integer;
1346 idx, curci: Integer;
1347 cc: PGridCell = nil;
1348 px: PBodyProxyRec;
1349 lq: LongWord;
1350 ptag: Integer;
1351 begin
1352 result := Default(ITP);
1353 if (exittag <> nil) then exittag^ := 0;
1354 tagmask := tagmask and TagFullMask;
1355 if (tagmask = 0) then exit;
1357 {$IF DEFINED(D2F_DEBUG_XXQ)}
1358 if (assigned(cb)) then e_WriteLog(Format('0: grid pointquery: (%d,%d)', [x, y]), MSG_NOTIFY);
1359 {$ENDIF}
1361 // make coords (0,0)-based
1362 Dec(x, mMinX);
1363 Dec(y, mMinY);
1364 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y >= mHeight*mTileSize) then exit;
1366 curci := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1368 {$IF DEFINED(D2F_DEBUG_XXQ)}
1369 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);
1370 {$ENDIF}
1372 // restore coords
1373 Inc(x, mMinX);
1374 Inc(y, mMinY);
1376 // increase query counter
1377 Inc(mLastQuery);
1378 if (mLastQuery = 0) then
1379 begin
1380 // just in case of overflow
1381 mLastQuery := 1;
1382 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1383 end;
1384 lq := mLastQuery;
1386 {$IF DEFINED(D2F_DEBUG_XXQ)}
1387 if (assigned(cb)) then e_WriteLog(Format('2: grid pointquery: (%d,%d); lq=%u', [x, y, lq]), MSG_NOTIFY);
1388 {$ENDIF}
1390 while (curci <> -1) do
1391 begin
1392 {$IF DEFINED(D2F_DEBUG_XXQ)}
1393 if (assigned(cb)) then e_WriteLog(Format(' cell #%d', [curci]), MSG_NOTIFY);
1394 {$ENDIF}
1395 cc := @mCells[curci];
1396 for f := 0 to GridCellBucketSize-1 do
1397 begin
1398 if (cc.bodies[f] = -1) then break;
1399 px := @mProxies[cc.bodies[f]];
1400 {$IF DEFINED(D2F_DEBUG_XXQ)}
1401 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);
1402 {$ENDIF}
1403 // shit. has to do it this way, so i can change tag in callback
1404 if (px.mQueryMark <> lq) then
1405 begin
1406 px.mQueryMark := lq;
1407 ptag := px.mTag;
1408 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
1409 (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
1410 begin
1411 if assigned(cb) then
1412 begin
1413 if cb(px.mObj, ptag) then
1414 begin
1415 result := px.mObj;
1416 if (exittag <> nil) then exittag^ := ptag;
1417 exit;
1418 end;
1419 end
1420 else
1421 begin
1422 result := px.mObj;
1423 if (exittag <> nil) then exittag^ := ptag;
1424 exit;
1425 end;
1426 end;
1427 end;
1428 end;
1429 curci := cc.next;
1430 end;
1431 end;
1434 // ////////////////////////////////////////////////////////////////////////// //
1435 // no callback: return `true` on the first hit
1436 // return number of ITP thingys put into frame pool
1437 function TBodyGridBase.forEachInAABB (x, y, w, h: Integer; tagmask: Integer=-1; allowDisabled: Boolean=false; firstHit: Boolean=false): Integer;
1438 var
1439 idx: Integer;
1440 gx, gy: Integer;
1441 sx, sy, ex, ey: Integer;
1442 curci: Integer;
1443 f: Integer;
1444 cc: PGridCell = nil;
1445 px: PBodyProxyRec;
1446 lq: LongWord;
1447 gw, gh: Integer;
1448 x0, y0: Integer;
1449 ptag: Integer;
1450 presobj: PITP;
1451 begin
1452 result := 0;
1453 if (w < 1) or (h < 1) then exit;
1454 tagmask := tagmask and TagFullMask;
1455 if (tagmask = 0) then exit;
1457 x0 := x;
1458 y0 := y;
1460 // fix coords
1461 Dec(x, mMinX);
1462 Dec(y, mMinY);
1464 gw := mWidth;
1465 gh := mHeight;
1467 if (x+w <= 0) or (y+h <= 0) then exit;
1468 if (x >= gw*mTileSize) or (y >= gh*mTileSize) then exit;
1470 sx := x div mTileSize;
1471 sy := y div mTileSize;
1472 ex := (x+w-1) div mTileSize;
1473 ey := (y+h-1) div mTileSize;
1475 // clip rect
1476 if (sx < 0) then sx := 0 else if (sx >= gw) then sx := gw-1;
1477 if (sy < 0) then sy := 0 else if (sy >= gh) then sy := gh-1;
1478 if (ex < 0) then ex := 0 else if (ex >= gw) then ex := gw-1;
1479 if (ey < 0) then ey := 0 else if (ey >= gh) then ey := gh-1;
1480 if (sx > ex) or (sy > ey) then exit; // just in case
1482 // has something to do
1483 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1484 mInQuery := true;
1486 // increase query counter
1487 Inc(mLastQuery);
1488 if (mLastQuery = 0) then
1489 begin
1490 // just in case of overflow
1491 mLastQuery := 1;
1492 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1493 end;
1494 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
1495 lq := mLastQuery;
1497 // go on
1498 for gy := sy to ey do
1499 begin
1500 for gx := sx to ex do
1501 begin
1502 // process cells
1503 curci := mGrid[gy*gw+gx];
1504 while (curci <> -1) do
1505 begin
1506 cc := @mCells[curci];
1507 for f := 0 to GridCellBucketSize-1 do
1508 begin
1509 if (cc.bodies[f] = -1) then break;
1510 px := @mProxies[cc.bodies[f]];
1511 // shit! has to do it this way, so i can change tag in callback
1512 if (px.mQueryMark = lq) then continue;
1513 px.mQueryMark := lq;
1514 ptag := px.mTag;
1515 if (not allowDisabled) and ((ptag and TagDisabled) <> 0) then continue;
1516 if ((ptag and tagmask) = 0) then continue;
1517 if (x0 >= px.mX+px.mWidth) or (y0 >= px.mY+px.mHeight) then continue;
1518 if (x0+w <= px.mX) or (y0+h <= px.mY) then continue;
1519 presobj := PITP(framePool.alloc(sizeof(ITP)));
1520 Move(px.mObj, presobj^, sizeof(ITP));
1521 Inc(result);
1522 if (firstHit) then begin mInQuery := false; exit; end;
1523 (*
1524 if assigned(cb) then
1525 begin
1526 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
1527 end
1528 else
1529 begin
1530 result := px.mObj;
1531 mInQuery := false;
1532 exit;
1533 end;
1534 *)
1535 end;
1536 curci := cc.next;
1537 end;
1538 end;
1539 end;
1541 mInQuery := false;
1542 end;
1545 // ////////////////////////////////////////////////////////////////////////// //
1546 function TBodyGridBase.forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
1547 var
1548 lw: TLineWalker;
1549 ccidx: Integer;
1550 cc: PGridCell;
1551 px: PBodyProxyRec;
1552 lq: LongWord;
1553 f, ptag: Integer;
1554 gw, gh, minx, miny: Integer;
1555 x0, y0: Integer;
1556 x1, y1: Integer;
1557 cx, cy: Integer;
1558 //px0, py0, px1, py1: Integer;
1559 begin
1560 log := false;
1561 result := Default(ITP);
1562 tagmask := tagmask and TagFullMask;
1563 if (tagmask = 0) or not assigned(cb) then exit;
1565 gw := mWidth;
1566 gh := mHeight;
1567 minx := mMinX;
1568 miny := mMinY;
1570 // make query coords (0,0)-based
1571 x0 := ax0-minx;
1572 y0 := ay0-miny;
1573 x1 := ax1-minx;
1574 y1 := ay1-miny;
1576 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
1577 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
1579 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1580 mInQuery := true;
1582 // increase query counter
1583 Inc(mLastQuery);
1584 if (mLastQuery = 0) then
1585 begin
1586 // just in case of overflow
1587 mLastQuery := 1;
1588 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1589 end;
1590 lq := mLastQuery;
1592 repeat
1593 lw.getXY(cx, cy);
1594 // check tile
1595 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
1596 // process cells
1597 while (ccidx <> -1) do
1598 begin
1599 cc := @mCells[ccidx];
1600 for f := 0 to GridCellBucketSize-1 do
1601 begin
1602 if (cc.bodies[f] = -1) then break;
1603 px := @mProxies[cc.bodies[f]];
1604 ptag := px.mTag;
1605 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1606 begin
1607 px.mQueryMark := lq; // mark as processed
1608 if cb(px.mObj, ptag) then
1609 begin
1610 result := px.mObj;
1611 mInQuery := false;
1612 exit;
1613 end;
1614 end;
1615 end;
1616 // next cell
1617 ccidx := cc.next;
1618 end;
1619 // done processing cells, move to next tile
1620 until lw.stepToNextTile();
1622 mInQuery := false;
1623 end;
1626 // ////////////////////////////////////////////////////////////////////////// //
1627 // trace box with the given velocity; return object hit (if any)
1628 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
1629 function TBodyGridBase.traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
1630 var
1631 gx, gy: Integer;
1632 ccidx: Integer;
1633 cc: PGridCell;
1634 px: PBodyProxyRec;
1635 lq: LongWord;
1636 f, ptag: Integer;
1637 minu0: Single = 100000.0;
1638 u0: Single;
1639 cx0, cy0, cx1, cy1: Integer;
1640 hitpx: PBodyProxyRec = nil;
1641 begin
1642 result := Default(ITP);
1643 ex := ax0+dx;
1644 ey := ay0+dy;
1645 if (aw < 1) or (ah < 1) then exit;
1647 cx0 := nmin(ax0, ax0+dx);
1648 cy0 := nmin(ay0, ay0+dy);
1649 cx1 := nmax(ax0+aw-1, ax0+aw-1+dx);
1650 cy1 := nmax(ay0+ah-1, ay0+ah-1+dy);
1652 cx0 -= mMinX; cy0 -= mMinY;
1653 cx1 -= mMinX; cy1 -= mMinY;
1655 if (cx1 < 0) or (cy1 < 0) or (cx0 >= mWidth*mTileSize) or (cy0 >= mHeight*mTileSize) then exit;
1657 if (cx0 < 0) then cx0 := 0;
1658 if (cy0 < 0) then cy0 := 0;
1659 if (cx1 >= mWidth*mTileSize) then cx1 := mWidth*mTileSize-1;
1660 if (cy1 >= mHeight*mTileSize) then cy1 := mHeight*mTileSize-1;
1661 // just in case
1662 if (cx0 > cx1) or (cy0 > cy1) then exit;
1664 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1665 mInQuery := true;
1667 // increase query counter
1668 Inc(mLastQuery);
1669 if (mLastQuery = 0) then
1670 begin
1671 // just in case of overflow
1672 mLastQuery := 1;
1673 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1674 end;
1675 lq := mLastQuery;
1677 for gy := cy0 div mTileSize to cy1 div mTileSize do
1678 begin
1679 for gx := cx0 div mTileSize to cx1 div mTileSize do
1680 begin
1681 ccidx := mGrid[gy*mWidth+gx];
1682 while (ccidx <> -1) do
1683 begin
1684 cc := @mCells[ccidx];
1685 for f := 0 to GridCellBucketSize-1 do
1686 begin
1687 if (cc.bodies[f] = -1) then break;
1688 px := @mProxies[cc.bodies[f]];
1689 ptag := px.mTag;
1690 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1691 begin
1692 px.mQueryMark := lq; // mark as processed
1693 if assigned(cb) then
1694 begin
1695 if not cb(px.mObj, ptag) then continue;
1696 end;
1697 if not sweepAABB(ax0, ay0, aw, ah, dx, dy, px.mX, px.mY, px.mWidth, px.mHeight, @u0) then continue;
1698 if (minu0 > u0) then
1699 begin
1700 hitpx := px;
1701 result := px.mObj;
1702 minu0 := u0;
1703 if (u0 = 0.0) then
1704 begin
1705 ex := ax0;
1706 ey := ay0;
1707 mInQuery := false;
1708 exit;
1709 end;
1710 end;
1711 end;
1712 end;
1713 // next cell
1714 ccidx := cc.next;
1715 end;
1716 end;
1717 end;
1719 if (minu0 <= 1.0) then
1720 begin
1721 ex := ax0+round(dx*minu0);
1722 ey := ay0+round(dy*minu0);
1723 // just in case, compensate for floating point inexactness
1724 if (ex >= hitpx.mX) and (ey >= hitpx.mY) and (ex < hitpx.mX+hitpx.mWidth) and (ey < hitpx.mY+hitpx.mHeight) then
1725 begin
1726 ex := ax0+trunc(dx*minu0);
1727 ey := ay0+trunc(dy*minu0);
1728 end;
1729 end;
1731 mInQuery := false;
1732 end;
1735 // ////////////////////////////////////////////////////////////////////////// //
1736 {.$DEFINE D2F_DEBUG_OTR}
1737 function TBodyGridBase.traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
1738 var
1739 ccidx: Integer;
1740 cc: PGridCell;
1741 px: PBodyProxyRec;
1742 ptag: Integer;
1743 minx, miny: Integer;
1744 f, c0, c1: Integer;
1745 x0, y0, x1, y1: Integer;
1746 celly0, celly1: Integer;
1747 dy: Integer;
1748 filled: array[0..mTileSize-1] of Byte;
1749 {$IF DEFINED(D2F_DEBUG_OTR)}
1750 s: AnsiString = '';
1751 {$ENDIF}
1752 begin
1753 result := false;
1754 ex := ax1;
1755 ey := ay1;
1756 if not ((ax0 = ax1) or (ay0 = ay1)) then raise Exception.Create('orthoray is not orthogonal');
1758 tagmask := tagmask and TagFullMask;
1759 if (tagmask = 0) then exit;
1761 if (forEachAtPoint(ax0, ay0, nil, tagmask) = nil) then exit;
1763 minx := mMinX;
1764 miny := mMinY;
1766 // offset query coords to (0,0)-based
1767 x0 := ax0-minx;
1768 y0 := ay0-miny;
1769 x1 := ax1-minx;
1770 y1 := ay1-miny;
1772 if (x0 = x1) then
1773 begin
1774 if (x0 < 0) or (x0 >= mWidth*mTileSize) then exit; // oops
1775 // vertical
1776 if (y0 < y1) then
1777 begin
1778 // down
1779 if (y1 < 0) or (y0 >= mHeight*mTileSize) then exit;
1780 //if (ay0 < 0) then ay0 := 0;
1781 if (y0 < 0) then exit;
1782 if (y1 >= mHeight*mTileSize) then y1 := mHeight*mTileSize-1;
1783 dy := 1;
1784 end
1785 else
1786 begin
1787 // up
1788 if (y0 < 0) or (y1 >= mHeight*mTileSize) then exit;
1789 //if (ay1 < 0) then ay1 := 0;
1790 if (y1 < 0) then exit;
1791 if (y0 >= mHeight*mTileSize) then y0 := mHeight*mTileSize-1;
1792 dy := -1;
1793 end;
1794 // check tile
1795 while true do
1796 begin
1797 ccidx := mGrid[(y0 div mTileSize)*mWidth+(x0 div mTileSize)];
1798 FillChar(filled, sizeof(filled), 0);
1799 celly0 := y0 and (not (mTileSize-1));
1800 celly1 := celly0+mTileSize-1;
1801 while (ccidx <> -1) do
1802 begin
1803 cc := @mCells[ccidx];
1804 for f := 0 to GridCellBucketSize-1 do
1805 begin
1806 if (cc.bodies[f] = -1) then break;
1807 px := @mProxies[cc.bodies[f]];
1808 ptag := px.mTag;
1809 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
1810 (ax0 >= px.x0) and (ax0 <= px.x1) then
1811 begin
1812 // bound c0 and c1 to cell
1813 c0 := nclamp(px.y0-miny, celly0, celly1);
1814 c1 := nclamp(px.y1-miny, celly0, celly1);
1815 // fill the thing
1816 {$IF DEFINED(D2F_DEBUG_OTR)}
1817 e_LogWritefln('**px.y0=%s; px.y1=%s; c0=%s; c1=%s; celly0=%s; celly1=%s; [%s..%s]', [px.y0-miny, px.y1-miny, c0, c1, celly0, celly1, c0-celly0, (c0-celly0)+(c1-c0)]);
1818 {$ENDIF}
1819 //assert(c0 <= c1);
1820 FillChar(filled[c0-celly0], c1-c0+1, 1);
1821 end;
1822 end;
1823 // next cell
1824 ccidx := cc.next;
1825 end;
1826 {$IF DEFINED(D2F_DEBUG_OTR)}
1827 s := formatstrf(' x=%s; ay0=%s; ay1=%s; y0=%s; celly0=%s; celly1=%s; dy=%s; [', [ax0, ay0, ay1, y0, celly0, celly1, dy]);
1828 for f := 0 to High(filled) do if (filled[f] <> 0) then s += '1' else s += '0';
1829 s += ']';
1830 e_LogWriteln(s);
1831 {$ENDIF}
1832 // now go till we hit cell boundary or empty space
1833 if (dy < 0) then
1834 begin
1835 // up
1836 while (y0 >= celly0) and (filled[y0-celly0] <> 0) do
1837 begin
1838 {$IF DEFINED(D2F_DEBUG_OTR)}
1839 e_LogWritefln(' filled: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
1840 {$ENDIF}
1841 Dec(y0);
1842 Dec(ay0);
1843 end;
1844 {$IF DEFINED(D2F_DEBUG_OTR)}
1845 e_LogWritefln(' span done: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
1846 {$ENDIF}
1847 if (ay0 <= ay1) then begin ey := ay1; result := false; exit; end;
1848 if (y0 >= celly0) then begin ey := ay0+1; {assert(forEachAtPoint(ex, ey, nil, tagmask) <> nil);} result := true; exit; end;
1849 end
1850 else
1851 begin
1852 // down
1853 while (y0 <= celly1) and (filled[y0-celly0] <> 0) do begin Inc(y0); Inc(ay0); end;
1854 if (ay0 >= ay1) then begin ey := ay1; result := false; exit; end;
1855 if (y0 <= celly1) then begin ey := ay0-1; result := true; exit; end;
1856 end;
1857 end;
1858 end
1859 else
1860 begin
1861 // horizontal
1862 assert(false);
1863 end;
1864 end;
1867 // ////////////////////////////////////////////////////////////////////////// //
1868 function TBodyGridBase.traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
1869 var
1870 ex, ey: Integer;
1871 begin
1872 result := traceRay(ex, ey, x0, y0, x1, y1, cb, tagmask);
1873 end;
1876 // no callback: return `true` on the nearest hit
1877 // you are not supposed to understand this
1878 function TBodyGridBase.traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
1879 var
1880 lw: TLineWalker;
1881 ccidx: Integer;
1882 cc: PGridCell;
1883 px: PBodyProxyRec;
1884 lq: LongWord;
1885 f, ptag: Integer;
1886 gw, gh, minx, miny: Integer;
1887 x0, y0: Integer;
1888 x1, y1: Integer;
1889 cx, cy: Integer;
1890 px0, py0, px1, py1: Integer;
1891 lastDistSq, distSq, hx, hy: Integer;
1892 firstCell: Boolean = true;
1893 wasHit: Boolean;
1894 begin
1895 result := Default(ITP);
1896 tagmask := tagmask and TagFullMask;
1897 if (tagmask = 0) then exit;
1899 gw := mWidth;
1900 gh := mHeight;
1901 minx := mMinX;
1902 miny := mMinY;
1904 // make query coords (0,0)-based
1905 x0 := ax0-minx;
1906 y0 := ay0-miny;
1907 x1 := ax1-minx;
1908 y1 := ay1-miny;
1910 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
1911 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
1913 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
1915 {$IF DEFINED(D2F_DEBUG)}
1916 //if assigned(dbgRayTraceTileHitCB) then e_LogWritefln('*** traceRay: (%s,%s)-(%s,%s)', [x0, y0, x1, y1]);
1917 {$ENDIF}
1919 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1920 mInQuery := true;
1922 // increase query counter
1923 Inc(mLastQuery);
1924 if (mLastQuery = 0) then
1925 begin
1926 // just in case of overflow
1927 mLastQuery := 1;
1928 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1929 end;
1930 lq := mLastQuery;
1932 repeat
1933 lw.getXY(cx, cy);
1934 {$IF DEFINED(D2F_DEBUG)}
1935 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB(cx+mMinX, cy+mMinY);
1936 {$ENDIF}
1937 // check tile
1938 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
1939 // process cells
1940 wasHit := false;
1941 while (ccidx <> -1) do
1942 begin
1943 cc := @mCells[ccidx];
1944 for f := 0 to GridCellBucketSize-1 do
1945 begin
1946 if (cc.bodies[f] = -1) then break;
1947 px := @mProxies[cc.bodies[f]];
1948 ptag := px.mTag;
1949 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1950 begin
1951 px.mQueryMark := lq; // mark as processed
1952 if assigned(cb) then
1953 begin
1954 if not cb(px.mObj, ptag) then continue;
1955 end;
1956 // get adjusted proxy coords
1957 px0 := px.mX-minx;
1958 py0 := px.mY-miny;
1959 px1 := px0+px.mWidth-1;
1960 py1 := py0+px.mHeight-1;
1961 {$IF DEFINED(D2F_DEBUG)}
1962 //if assigned(dbgRayTraceTileHitCB) then e_LogWritefln(' cxy=(%s,%s); pan=(%s,%s)-(%s,%s)', [cx, cy, px0, py0, px1, py1]);
1963 {$ENDIF}
1964 // inside?
1965 if firstCell and (x0 >= px0) and (y0 >= py0) and (x0 <= px1) and (y0 <= py1) then
1966 begin
1967 // oops
1968 ex := ax0;
1969 ey := ay0;
1970 result := px.mObj;
1971 mInQuery := false;
1972 {$IF DEFINED(D2F_DEBUG)}
1973 if assigned(dbgRayTraceTileHitCB) then e_LogWriteln(' INSIDE!');
1974 {$ENDIF}
1975 exit;
1976 end;
1977 // do line-vs-aabb test
1978 if lineAABBIntersects(x0, y0, x1, y1, px0, py0, px1-px0+1, py1-py0+1, hx, hy) then
1979 begin
1980 // hit detected
1981 distSq := distanceSq(x0, y0, hx, hy);
1982 {$IF DEFINED(D2F_DEBUG)}
1983 //if assigned(dbgRayTraceTileHitCB) then e_LogWritefln(' hit=(%s,%s); distSq=%s; lastDistSq=%s', [hx, hy, distSq, lastDistSq]);
1984 {$ENDIF}
1985 if (distSq < lastDistSq) then
1986 begin
1987 lastDistSq := distSq;
1988 ex := hx+minx;
1989 ey := hy+miny;
1990 result := px.mObj;
1991 wasHit := true;
1992 end;
1993 end;
1994 end;
1995 end;
1996 // next cell
1997 ccidx := cc.next;
1998 end;
1999 // done processing cells; exit if we registered a hit
2000 // next cells can't have better candidates, obviously
2001 if wasHit then begin mInQuery := false; exit; end;
2002 firstCell := false;
2003 // move to next tile
2004 until lw.stepToNextTile();
2006 mInQuery := false;
2007 end;
2010 // ////////////////////////////////////////////////////////////////////////// //
2011 // no callback: return `true` on the nearest hit
2012 (*
2013 function TBodyGridBase.traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2014 var
2015 ex, ey: Integer;
2016 begin
2017 result := traceRayOld(ex, ey, x0, y0, x1, y1, cb, tagmask);
2018 end;
2021 // no callback: return `true` on the nearest hit
2022 // you are not supposed to understand this
2023 function TBodyGridBase.traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2024 var
2025 wx0, wy0, wx1, wy1: Integer; // window coordinates
2026 stx, sty: Integer; // "steps" for x and y axes
2027 dsx, dsy: Integer; // "lengthes" for x and y axes
2028 dx2, dy2: Integer; // "double lengthes" for x and y axes
2029 xd, yd: Integer; // current coord
2030 e: Integer; // "error" (as in bresenham algo)
2031 rem: Integer;
2032 term: Integer;
2033 xptr, yptr: PInteger;
2034 xfixed: Boolean;
2035 temp: Integer;
2036 prevx, prevy: Integer;
2037 lastDistSq: Integer;
2038 ccidx, curci: Integer;
2039 hasUntried: Boolean;
2040 lastGA: Integer = -1;
2041 ga, x, y: Integer;
2042 lastObj: ITP;
2043 wasHit: Boolean = false;
2044 gw, gh, minx, miny, maxx, maxy: Integer;
2045 cc: PGridCell;
2046 px: PBodyProxyRec;
2047 lq: LongWord;
2048 f, ptag, distSq: Integer;
2049 x0, y0, x1, y1: Integer;
2050 //swapped: Boolean = false; // true: xd is yd, and vice versa
2051 // horizontal walker
2052 {$IFDEF GRID_USE_ORTHO_ACCEL}
2053 wklen, wkstep: Integer;
2054 //wksign: Integer;
2055 hopt: Boolean;
2056 {$ENDIF}
2057 // skipper
2058 xdist, ydist: Integer;
2059 begin
2060 result := Default(ITP);
2061 lastObj := Default(ITP);
2062 tagmask := tagmask and TagFullMask;
2063 ex := ax1; // why not?
2064 ey := ay1; // why not?
2065 if (tagmask = 0) then exit;
2067 if (ax0 = ax1) and (ay0 = ay1) then
2068 begin
2069 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2070 if (result <> nil) then
2071 begin
2072 if assigned(cb) and not cb(result, ptag, ax0, ay0, ax0, ay0) then result := Default(ITP);
2073 end;
2074 exit;
2075 end;
2077 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
2079 gw := mWidth;
2080 gh := mHeight;
2081 minx := mMinX;
2082 miny := mMinY;
2083 maxx := gw*mTileSize-1;
2084 maxy := gh*mTileSize-1;
2086 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2087 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);
2088 {$ENDIF}
2090 x0 := ax0;
2091 y0 := ay0;
2092 x1 := ax1;
2093 y1 := ay1;
2095 // offset query coords to (0,0)-based
2096 Dec(x0, minx);
2097 Dec(y0, miny);
2098 Dec(x1, minx);
2099 Dec(y1, miny);
2101 // clip rectange
2102 wx0 := 0;
2103 wy0 := 0;
2104 wx1 := maxx;
2105 wy1 := maxy;
2107 // horizontal setup
2108 if (x0 < x1) then
2109 begin
2110 // from left to right
2111 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
2112 stx := 1; // going right
2113 end
2114 else
2115 begin
2116 // from right to left
2117 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
2118 stx := -1; // going left
2119 x0 := -x0;
2120 x1 := -x1;
2121 wx0 := -wx0;
2122 wx1 := -wx1;
2123 swapInt(wx0, wx1);
2124 end;
2126 // vertical setup
2127 if (y0 < y1) then
2128 begin
2129 // from top to bottom
2130 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
2131 sty := 1; // going down
2132 end
2133 else
2134 begin
2135 // from bottom to top
2136 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
2137 sty := -1; // going up
2138 y0 := -y0;
2139 y1 := -y1;
2140 wy0 := -wy0;
2141 wy1 := -wy1;
2142 swapInt(wy0, wy1);
2143 end;
2145 dsx := x1-x0;
2146 dsy := y1-y0;
2148 if (dsx < dsy) then
2149 begin
2150 //swapped := true;
2151 xptr := @yd;
2152 yptr := @xd;
2153 swapInt(x0, y0);
2154 swapInt(x1, y1);
2155 swapInt(dsx, dsy);
2156 swapInt(wx0, wy0);
2157 swapInt(wx1, wy1);
2158 swapInt(stx, sty);
2159 end
2160 else
2161 begin
2162 xptr := @xd;
2163 yptr := @yd;
2164 end;
2166 dx2 := 2*dsx;
2167 dy2 := 2*dsy;
2168 xd := x0;
2169 yd := y0;
2170 e := 2*dsy-dsx;
2171 term := x1;
2173 xfixed := false;
2174 if (y0 < wy0) then
2175 begin
2176 // clip at top
2177 temp := dx2*(wy0-y0)-dsx;
2178 xd += temp div dy2;
2179 rem := temp mod dy2;
2180 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
2181 if (xd+1 >= wx0) then
2182 begin
2183 yd := wy0;
2184 e -= rem+dsx;
2185 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
2186 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
2187 xfixed := true;
2188 end;
2189 end;
2191 if (not xfixed) and (x0 < wx0) then
2192 begin
2193 // clip at left
2194 temp := dy2*(wx0-x0);
2195 yd += temp div dx2;
2196 rem := temp mod dx2;
2197 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
2198 xd := wx0;
2199 e += rem;
2200 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
2201 end;
2203 if (y1 > wy1) then
2204 begin
2205 // clip at bottom
2206 temp := dx2*(wy1-y0)+dsx;
2207 term := x0+temp div dy2;
2208 rem := temp mod dy2;
2209 if (rem = 0) then Dec(term);
2210 end;
2212 if (term > wx1) then term := wx1; // clip at right
2214 Inc(term); // draw last point
2215 //if (term = xd) then exit; // this is the only point, get out of here
2217 if (sty = -1) then yd := -yd;
2218 if (stx = -1) then begin xd := -xd; term := -term; end;
2219 dx2 -= dy2;
2221 // first move, to skip starting point
2222 // DON'T DO THIS! loop will take care of that
2223 if (xd = term) then
2224 begin
2225 //FIXME!
2226 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2227 if (result <> nil) then
2228 begin
2229 if assigned(cb) then
2230 begin
2231 if cb(result, ptag, ax0, ay0, ax0, ay0) then
2232 begin
2233 ex := ax0;
2234 ey := ay0;
2235 end
2236 else
2237 begin
2238 result := nil;
2239 end;
2240 end
2241 else
2242 begin
2243 ex := ax0;
2244 ey := ay0;
2245 end;
2246 end;
2247 exit;
2248 end;
2250 prevx := xptr^+minx;
2251 prevy := yptr^+miny;
2252 ( *
2253 // move coords
2254 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2255 xd += stx;
2256 // done?
2257 if (xd = term) then exit;
2258 * )
2260 {$IF DEFINED(D2F_DEBUG)}
2261 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2262 {$ENDIF}
2263 // DON'T DO THIS! loop will take care of that
2264 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
2265 //ccidx := mGrid[lastGA];
2267 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2268 //if assigned(dbgRayTraceTileHitCB) then e_WriteLog('1:TRACING!', MSG_NOTIFY);
2269 {$ENDIF}
2271 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
2273 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2274 mInQuery := true;
2276 // increase query counter
2277 Inc(mLastQuery);
2278 if (mLastQuery = 0) then
2279 begin
2280 // just in case of overflow
2281 mLastQuery := 1;
2282 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2283 end;
2284 lq := mLastQuery;
2286 {$IFDEF GRID_USE_ORTHO_ACCEL}
2287 // if this is strict horizontal/vertical trace, use optimized codepath
2288 if (ax0 = ax1) or (ay0 = ay1) then
2289 begin
2290 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
2291 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
2292 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
2293 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
2294 hopt := (ay0 = ay1); // horizontal?
2295 if (stx < 0) then begin {wksign := -1;} wklen := -(term-xd); end else begin {wksign := 1;} wklen := term-xd; end;
2296 {$IF DEFINED(D2F_DEBUG)}
2297 if dbgShowTraceLog then e_LogWritefln('optimized htrace; wklen=%d', [wklen]);
2298 {$ENDIF}
2299 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2300 // one of those will never change
2301 x := xptr^+minx;
2302 y := yptr^+miny;
2303 while (wklen > 0) do
2304 begin
2305 {$IF DEFINED(D2F_DEBUG)}
2306 if dbgShowTraceLog then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; y=%d; y=%d', [ga, xptr^+minx, yptr^+miny, y, ay0]);
2307 {$ENDIF}
2308 // new tile?
2309 if (ga <> lastGA) then
2310 begin
2311 lastGA := ga;
2312 ccidx := mGrid[lastGA];
2313 // convert coords to map (to avoid ajdusting coords inside the loop)
2314 if hopt then x := xptr^+minx else y := yptr^+miny;
2315 while (ccidx <> -1) do
2316 begin
2317 cc := @mCells[ccidx];
2318 for f := 0 to GridCellBucketSize-1 do
2319 begin
2320 if (cc.bodies[f] = -1) then break;
2321 px := @mProxies[cc.bodies[f]];
2322 ptag := px.mTag;
2323 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) and
2324 // constant coord should be inside
2325 ((hopt and (y >= px.y0) and (y <= px.y1)) or
2326 ((not hopt) and (x >= px.x0) and (x <= px.x1))) then
2327 begin
2328 px.mQueryMark := lq; // mark as processed
2329 // inside the proxy?
2330 if (hopt and (x > px.x0) and (x < px.x1)) or
2331 ((not hopt) and (y > px.y0) and (y < px.y1)) then
2332 begin
2333 // setup prev[xy]
2334 if assigned(cb) then
2335 begin
2336 if cb(px.mObj, ptag, x, y, x, y) then
2337 begin
2338 result := px.mObj;
2339 ex := x;
2340 ey := y;
2341 mInQuery := false;
2342 exit;
2343 end;
2344 end
2345 else
2346 begin
2347 distSq := distanceSq(ax0, ay0, x, y);
2348 {$IF DEFINED(D2F_DEBUG)}
2349 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]);
2350 {$ENDIF}
2351 if (distSq < lastDistSq) then
2352 begin
2353 ex := x;
2354 ey := y;
2355 result := px.mObj;
2356 mInQuery := false;
2357 exit;
2358 end;
2359 end;
2360 continue;
2361 end;
2362 // remember this hitpoint if it is nearer than an old one
2363 // setup prev[xy]
2364 if hopt then
2365 begin
2366 // horizontal trace
2367 prevy := y;
2368 y := yptr^+miny;
2369 if (stx < 0) then
2370 begin
2371 // going left
2372 if (x < px.x1) then continue; // not on the right edge
2373 x := px.x1;
2374 prevx := x+1;
2375 end
2376 else
2377 begin
2378 // going right
2379 if (x > px.x0) then continue; // not on the left edge
2380 x := px.x0;
2381 prevx := x-1;
2382 end;
2383 end
2384 else
2385 begin
2386 // vertical trace
2387 prevx := x;
2388 x := xptr^+minx;
2389 if (stx < 0) then
2390 begin
2391 // going up
2392 if (y < px.y1) then continue; // not on the bottom edge
2393 y := px.y1;
2394 prevy := x+1;
2395 end
2396 else
2397 begin
2398 // going down
2399 if (y > px.y0) then continue; // not on the top edge
2400 y := px.y0;
2401 prevy := y-1;
2402 end;
2403 end;
2404 if assigned(cb) then
2405 begin
2406 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2407 begin
2408 result := px.mObj;
2409 ex := prevx;
2410 ey := prevy;
2411 mInQuery := false;
2412 exit;
2413 end;
2414 end
2415 else
2416 begin
2417 distSq := distanceSq(ax0, ay0, prevx, prevy);
2418 {$IF DEFINED(D2F_DEBUG)}
2419 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]);
2420 {$ENDIF}
2421 if (distSq < lastDistSq) then
2422 begin
2423 wasHit := true;
2424 lastDistSq := distSq;
2425 ex := prevx;
2426 ey := prevy;
2427 lastObj := px.mObj;
2428 end;
2429 end;
2430 end;
2431 end;
2432 // next cell
2433 ccidx := cc.next;
2434 end;
2435 if wasHit and not assigned(cb) then begin result := lastObj; mInQuery := false; exit; end;
2436 if assigned(cb) and cb(nil, 0, x, y, x, y) then begin result := lastObj; mInQuery := false; exit; end;
2437 end;
2438 // skip to next tile
2439 if hopt then
2440 begin
2441 if (stx > 0) then
2442 begin
2443 // to the right
2444 wkstep := ((xptr^ or (mTileSize-1))+1)-xptr^;
2445 {$IF DEFINED(D2F_DEBUG)}
2446 if dbgShowTraceLog then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2447 {$ENDIF}
2448 if (wkstep >= wklen) then break;
2449 Inc(xptr^, wkstep);
2450 Inc(ga);
2451 end
2452 else
2453 begin
2454 // to the left
2455 wkstep := xptr^-((xptr^ and (not (mTileSize-1)))-1);
2456 {$IF DEFINED(D2F_DEBUG)}
2457 if dbgShowTraceLog then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2458 {$ENDIF}
2459 if (wkstep >= wklen) then break;
2460 Dec(xptr^, wkstep);
2461 Dec(ga);
2462 end;
2463 end
2464 else
2465 begin
2466 if (stx > 0) then
2467 begin
2468 // to the down
2469 wkstep := ((yptr^ or (mTileSize-1))+1)-yptr^;
2470 {$IF DEFINED(D2F_DEBUG)}
2471 if dbgShowTraceLog then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2472 {$ENDIF}
2473 if (wkstep >= wklen) then break;
2474 Inc(yptr^, wkstep);
2475 Inc(ga, mWidth);
2476 end
2477 else
2478 begin
2479 // to the up
2480 wkstep := yptr^-((yptr^ and (not (mTileSize-1)))-1);
2481 {$IF DEFINED(D2F_DEBUG)}
2482 if dbgShowTraceLog then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2483 {$ENDIF}
2484 if (wkstep >= wklen) then break;
2485 Dec(yptr^, wkstep);
2486 Dec(ga, mWidth);
2487 end;
2488 end;
2489 Dec(wklen, wkstep);
2490 end;
2491 // we can travel less than one cell
2492 if wasHit and not assigned(cb) then result := lastObj else begin ex := ax1; ey := ay1; end;
2493 mInQuery := false;
2494 exit;
2495 end;
2496 {$ENDIF}
2498 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2499 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2500 {$ENDIF}
2502 //e_LogWritefln('*********************', []);
2503 ccidx := -1;
2504 // can omit checks
2505 while (xd <> term) do
2506 begin
2507 // check cell(s)
2508 {$IF DEFINED(D2F_DEBUG)}
2509 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2510 {$ENDIF}
2511 // new tile?
2512 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2513 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2514 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);
2515 {$ENDIF}
2516 if (ga <> lastGA) then
2517 begin
2518 // yes
2519 {$IF DEFINED(D2F_DEBUG)}
2520 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2521 {$ENDIF}
2522 if (ccidx <> -1) then
2523 begin
2524 // signal cell completion
2525 if assigned(cb) then
2526 begin
2527 if cb(nil, 0, xptr^+minx, yptr^+miny, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2528 end
2529 else if wasHit then
2530 begin
2531 result := lastObj;
2532 mInQuery := false;
2533 exit;
2534 end;
2535 end;
2536 lastGA := ga;
2537 ccidx := mGrid[lastGA];
2538 end;
2539 // has something to process in this tile?
2540 if (ccidx <> -1) then
2541 begin
2542 // process cell
2543 curci := ccidx;
2544 hasUntried := false; // this will be set to `true` if we have some proxies we still want to process at the next step
2545 // convert coords to map (to avoid ajdusting coords inside the loop)
2546 x := xptr^+minx;
2547 y := yptr^+miny;
2548 // process cell list
2549 while (curci <> -1) do
2550 begin
2551 cc := @mCells[curci];
2552 for f := 0 to GridCellBucketSize-1 do
2553 begin
2554 if (cc.bodies[f] = -1) then break;
2555 px := @mProxies[cc.bodies[f]];
2556 ptag := px.mTag;
2557 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2558 begin
2559 // can we process this proxy?
2560 if (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
2561 begin
2562 px.mQueryMark := lq; // mark as processed
2563 if assigned(cb) then
2564 begin
2565 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2566 begin
2567 result := px.mObj;
2568 ex := prevx;
2569 ey := prevy;
2570 mInQuery := false;
2571 exit;
2572 end;
2573 end
2574 else
2575 begin
2576 // remember this hitpoint if it is nearer than an old one
2577 distSq := distanceSq(ax0, ay0, prevx, prevy);
2578 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2579 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);
2580 {$ENDIF}
2581 if (distSq < lastDistSq) then
2582 begin
2583 wasHit := true;
2584 lastDistSq := distSq;
2585 ex := prevx;
2586 ey := prevy;
2587 lastObj := px.mObj;
2588 end;
2589 end;
2590 end
2591 else
2592 begin
2593 // this is possibly interesting proxy, set "has more to check" flag
2594 hasUntried := true;
2595 end;
2596 end;
2597 end;
2598 // next cell
2599 curci := cc.next;
2600 end;
2601 // still has something interesting in this cell?
2602 if not hasUntried then
2603 begin
2604 // nope, don't process this cell anymore; signal cell completion
2605 ccidx := -1;
2606 if assigned(cb) then
2607 begin
2608 if cb(nil, 0, x, y, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2609 end
2610 else if wasHit then
2611 begin
2612 result := lastObj;
2613 mInQuery := false;
2614 exit;
2615 end;
2616 end;
2617 end;
2618 if (ccidx = -1) then
2619 begin
2620 // move to cell edge, as we have nothing to trace here anymore
2621 if (stx < 0) then xdist := xd and (not (mTileSize-1)) else xdist := xd or (mTileSize-1);
2622 if (sty < 0) then ydist := yd and (not (mTileSize-1)) else ydist := yd or (mTileSize-1);
2623 //e_LogWritefln('0: swapped=%d; xd=%d; yd=%d; stx=%d; sty=%d; e=%d; dx2=%d; dy2=%d; term=%d; xdist=%d; ydist=%d', [swapped, xd, yd, stx, sty, e, dx2, dy2, term, xdist, ydist]);
2624 while (xd <> xdist) and (yd <> ydist) do
2625 begin
2626 // step
2627 xd += stx;
2628 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2629 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
2630 if (xd = term) then break;
2631 end;
2632 //e_LogWritefln('1: swapped=%d; xd=%d; yd=%d; stx=%d; sty=%d; e=%d; dx2=%d; dy2=%d; term=%d; xdist=%d; ydist=%d', [swapped, xd, yd, stx, sty, e, dx2, dy2, term, xdist, ydist]);
2633 if (xd = term) then break;
2634 end;
2635 //putPixel(xptr^, yptr^);
2636 // move coords
2637 prevx := xptr^+minx;
2638 prevy := yptr^+miny;
2639 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2640 xd += stx;
2641 end;
2642 // we can travel less than one cell
2643 if wasHit and not assigned(cb) then
2644 begin
2645 result := lastObj;
2646 end
2647 else
2648 begin
2649 ex := ax1; // why not?
2650 ey := ay1; // why not?
2651 end;
2653 mInQuery := false;
2654 end;
2655 *)
2658 end.