DEADSOFTWARE

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