DEADSOFTWARE

grid: fixed update bug with resized bodies ('cmon, missing '-1' is *so* well-known...
[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 unit g_grid;
26 interface
28 const
29 GridTileSize = 32; // must be power of two!
31 type
32 TBodyProxyId = Integer;
34 generic TBodyGridBase<ITP> = class(TObject)
35 public
36 type TGridQueryCB = function (obj: ITP; tag: Integer): Boolean is nested; // return `true` to stop
37 type TGridRayQueryCB = function (obj: ITP; tag: Integer; x, y, prevx, prevy: Integer): Boolean is nested; // return `true` to stop
38 type TCellQueryCB = procedure (x, y: Integer) is nested; // top-left cell corner coords
40 const TagDisabled = $40000000;
41 const TagFullMask = $3fffffff;
43 private
44 const
45 GridCellBucketSize = 8; // WARNING! can't be less than 2!
47 public
48 type
49 PBodyProxyRec = ^TBodyProxyRec;
50 TBodyProxyRec = record
51 private
52 mX, mY, mWidth, mHeight: Integer; // aabb
53 mQueryMark: LongWord; // was this object visited at this query?
54 mObj: ITP;
55 mTag: Integer; // `TagDisabled` set: disabled ;-)
56 nextLink: TBodyProxyId; // next free or nothing
58 private
59 procedure setup (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer);
61 function getTag (): Integer; inline;
62 procedure setTag (v: Integer); inline;
64 function getEnabled (): Boolean; inline;
65 procedure setEnabled (v: Boolean); inline;
67 function getX1 (): Integer; inline;
68 function getY1 (): Integer; inline;
70 public
71 property x: Integer read mX;
72 property y: Integer read mY;
73 property width: Integer read mWidth;
74 property height: Integer read mHeight;
75 property tag: Integer read getTag write setTag;
76 property enabled: Boolean read getEnabled write setEnabled;
77 property obj: ITP read mObj;
79 property x0: Integer read mX;
80 property y0: Integer read mY;
81 property x1: Integer read getX1;
82 property y1: Integer read getY1;
83 end;
85 private
86 type
87 PGridCell = ^TGridCell;
88 TGridCell = record
89 bodies: array [0..GridCellBucketSize-1] of Integer; // -1: end of list
90 next: Integer; // in this cell; index in mCells
91 end;
93 TCellArray = array of TGridCell;
95 TGridInternalCB = function (grida: Integer; bodyId: TBodyProxyId): Boolean of object; // return `true` to stop
97 private
98 //mTileSize: Integer;
99 const mTileSize = GridTileSize;
100 type TGetProxyFn = function (pxidx: Integer): PBodyProxyRec of object;
102 public
103 const tileSize = mTileSize;
105 type
106 TAtPointEnumerator = record
107 private
108 mCells: TCellArray;
109 curidx, curbki: Integer;
110 getpx: TGetProxyFn;
111 public
112 constructor Create (acells: TCellArray; aidx: Integer; agetpx: TGetProxyFn);
113 function MoveNext (): Boolean; inline;
114 function getCurrent (): PBodyProxyRec; inline;
115 property Current: PBodyProxyRec read getCurrent;
116 end;
118 private
119 mMinX, mMinY: Integer; // so grids can start at any origin
120 mWidth, mHeight: Integer; // in tiles
121 mGrid: array of Integer; // mWidth*mHeight, index in mCells
122 mCells: TCellArray; // cell pool
123 mFreeCell: Integer; // first free cell index or -1
124 mLastQuery: LongWord;
125 mUsedCells: Integer;
126 mProxies: array of TBodyProxyRec;
127 mProxyFree: TBodyProxyId; // free
128 mProxyCount: Integer; // currently used
129 mProxyMaxCount: Integer;
130 mInQuery: Boolean;
132 public
133 dbgShowTraceLog: Boolean;
134 {$IF DEFINED(D2F_DEBUG)}
135 dbgRayTraceTileHitCB: TCellQueryCB;
136 {$ENDIF}
138 private
139 function allocCell (): Integer;
140 procedure freeCell (idx: Integer); // `next` is simply overwritten
142 function allocProxy (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer): TBodyProxyId;
143 procedure freeProxy (body: TBodyProxyId);
145 function forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
147 function inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
148 function remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
150 function getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
151 procedure setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
153 function getGridWidthPx (): Integer; inline;
154 function getGridHeightPx (): Integer; inline;
156 function getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
158 public
159 constructor Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
160 destructor Destroy (); override;
162 function insertBody (aObj: ITP; ax, ay, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
163 procedure removeBody (body: TBodyProxyId); // WARNING! this WILL destroy proxy!
165 procedure moveBody (body: TBodyProxyId; nx, ny: Integer);
166 procedure resizeBody (body: TBodyProxyId; nw, nh: Integer);
167 procedure moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
169 function insideGrid (x, y: Integer): Boolean; inline;
171 // `false` if `body` is surely invalid
172 function getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
173 function getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
174 function getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
176 //WARNING: don't modify grid while any query is in progress (no checks are made!)
177 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
178 // no callback: return `true` on the first hit
179 function forEachInAABB (x, y, w, h: Integer; cb: TGridQueryCB; tagmask: Integer=-1; allowDisabled: Boolean=false): ITP;
181 //WARNING: don't modify grid while any query is in progress (no checks are made!)
182 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
183 // no callback: return object on the first hit or nil
184 function forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
186 function atCellInPoint (x, y: Integer): TAtPointEnumerator;
188 //WARNING: don't modify grid while any query is in progress (no checks are made!)
189 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
190 // cb with `(nil)` will be called before processing new tile
191 // no callback: return object of the nearest hit or nil
192 // if `inverted` is true, trace will register bodies *exluding* tagmask
193 //WARNING: don't change tags in callbacks here!
194 function traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP; overload;
195 function traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
197 //WARNING: don't modify grid while any query is in progress (no checks are made!)
198 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
199 // cb with `(nil)` will be called before processing new tile
200 // no callback: return object of the nearest hit or nil
201 // if `inverted` is true, trace will register bodies *exluding* tagmask
202 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
203 //WARNING: don't change tags in callbacks here!
204 function traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP; overload;
205 function traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
207 // return `false` if we're still inside at the end
208 // line should be either strict horizontal, or strict vertical, otherwise an exception will be thrown
209 // `true`: endpoint will point at the last "inside" pixel
210 // `false`: endpoint will be (ax1, ay1)
211 //WARNING: don't change tags in callbacks here!
212 function traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
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 // trace line along the grid, calling `cb` for all objects in passed cells, in no particular order
217 //WARNING: don't change tags in callbacks here!
218 function forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
220 // trace box with the given velocity; return object hit (if any)
221 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
222 //WARNING: don't change tags in callbacks here!
223 function traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
225 // debug
226 procedure forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
227 function forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
228 procedure dumpStats ();
230 public
231 //WARNING! no sanity checks!
232 property proxyEnabled[pid: TBodyProxyId]: Boolean read getProxyEnabled write setProxyEnabled;
234 property gridX0: Integer read mMinX;
235 property gridY0: Integer read mMinY;
236 property gridWidth: Integer read getGridWidthPx; // in pixels
237 property gridHeight: Integer read getGridHeightPx; // in pixels
239 property proxy[idx: TBodyProxyId]: PBodyProxyRec read getProxyById;
240 end;
243 type
244 // common structure for all line tracers
245 TLineWalker = record
246 public
247 const TileSize = GridTileSize;
249 private
250 wx0, wy0, wx1, wy1: Integer; // window coordinates
251 stx, sty: Integer; // "steps" for x and y axes
252 dx2, dy2: Integer; // "double lengthes" for x and y axes
253 xd, yd: Integer; // current coord
254 e: Integer; // "error" (as in bresenham algo)
255 term: Integer; // end for xd (xd = term: done)
256 //xptr, yptr: PInteger;
257 xyswapped: Boolean; // true: xd is y
259 public
260 // call `setyp` after this
261 constructor Create (minx, miny, maxx, maxy: Integer);
263 procedure setClip (minx, miny, maxx, maxy: Integer); inline;
265 // this will use `w[xy][01]` to clip coords
266 // return `false` if the whole line was clipped away
267 // on `true`, you should process first point, and go on
268 function setup (x0, y0, x1, y1: Integer): Boolean;
270 // call this *after* doing a step
271 // WARNING! if you will do a step when this returns `true`, you will fall into limbo
272 function done (): Boolean; inline;
274 // as you will prolly call `done()` after doing a step anyway, this will do it for you
275 // move to next point, return `true` when the line is complete (i.e. you should stop)
276 function step (): Boolean; inline;
278 // move to next tile; return `true` if the line is complete (and walker state is undefined then)
279 function stepToNextTile (): Boolean; inline;
281 // hack for line-vs-aabb; NOT PROPERLY TESTED!
282 procedure getPrevXY (out ox, oy: Integer); inline;
284 // current coords
285 function x (): Integer; inline;
286 function y (): Integer; inline;
288 procedure getXY (out ox, oy: Integer); inline;
290 // move directions; always [-1..1] (can be zero!)
291 function dx (): Integer; inline;
292 function dy (): Integer; inline;
293 end;
296 // you are not supposed to understand this
297 // returns `true` if there is an intersection, and enter coords
298 // enter coords will be equal to (x0, y0) if starting point is inside the box
299 // if result is `false`, `inx` and `iny` are undefined
300 function lineAABBIntersects (x0, y0, x1, y1: Integer; bx, by, bw, bh: Integer; out inx, iny: Integer): Boolean;
302 // sweep two AABB's to see if and when they are overlapping
303 // returns `true` if collision was detected (but boxes doesn't overlap)
304 // u1 and u1 has no sense if no collision was detected
305 // u0 = normalized time of first collision (i.e. collision starts at myMove*u0)
306 // u1 = normalized time of second collision (i.e. collision stops after myMove*u1)
307 // hitedge for `it`: 0: top; 1: right; 2: bottom; 3: left
308 // enter/exit coords will form non-intersecting configuration (i.e. will be before/after the actual collision)
309 function sweepAABB (mex0, mey0, mew, meh: Integer; medx, medy: Integer; itx0, ity0, itw, ith: Integer;
310 u0: PSingle=nil; hitedge: PInteger=nil; u1: PSingle=nil): Boolean;
312 function distanceSq (x0, y0, x1, y1: Integer): Integer; inline;
314 procedure swapInt (var a: Integer; var b: Integer); inline;
315 //function minInt (a, b: Integer): Integer; inline;
316 //function maxInt (a, b: Integer): Integer; inline;
319 implementation
321 uses
322 SysUtils, e_log, g_console, utils;
325 // ////////////////////////////////////////////////////////////////////////// //
326 //procedure swapInt (var a: Integer; var b: Integer); inline; var t: Integer; begin t := a; a := b; b := t; end;
327 procedure swapInt (var a: Integer; var b: Integer); inline; begin a := a xor b; b := b xor a; a := a xor b; end;
328 //function minInt (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
329 //function maxInt (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
331 function distanceSq (x0, y0, x1, y1: Integer): Integer; inline; begin result := (x1-x0)*(x1-x0)+(y1-y0)*(y1-y0); end;
334 // ////////////////////////////////////////////////////////////////////////// //
335 constructor TLineWalker.Create (minx, miny, maxx, maxy: Integer);
336 begin
337 setClip(minx, miny, maxx, maxy);
338 end;
340 procedure TLineWalker.setClip (minx, miny, maxx, maxy: Integer); inline;
341 begin
342 // clip rectange
343 wx0 := minx;
344 wy0 := miny;
345 wx1 := maxx;
346 wy1 := maxy;
347 end;
349 function TLineWalker.done (): Boolean; inline; begin result := (xd = term); end;
351 function TLineWalker.step (): Boolean; inline;
352 begin
353 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
354 xd += stx;
355 result := (xd = term);
356 end;
358 function TLineWalker.stepToNextTile (): Boolean; inline;
359 var
360 ex, ey: Integer;
361 xwalk, ywalk, wklen: Integer; // to the respective edges
362 lstx, lsty, lterm: Integer;
363 le, ldx2, ldy2: Integer;
364 lxd, lyd: Integer;
365 f: Integer;
366 begin
367 result := false;
369 lstx := stx;
370 lsty := sty;
371 lterm := term;
372 lxd := xd;
374 // ortho?
375 if (lsty = 0) then
376 begin
377 // only xd
378 //assert(lsty <> 0);
379 if (lstx < 0) then
380 begin
381 // xd: to left edge
382 xd := (lxd and (not (TileSize-1)))-1;
383 result := (lxd <= lterm);
384 exit;
385 end
386 else
387 begin
388 // xd: to right edge
389 xd := (lxd or (TileSize-1))+1;
390 result := (lxd >= lterm);
391 exit;
392 end;
393 end;
395 // not ortho
396 //assert(lstx <> 0); // invariant
398 lyd := yd;
399 le := e;
400 ldx2 := dx2;
401 ldy2 := dy2;
403 // calculate xwalk
404 if (lstx < 0) then
405 begin
406 ex := (lxd and (not (TileSize-1)))-1;
407 xwalk := lxd-ex;
408 end
409 else
410 begin
411 ex := (lxd or (TileSize-1))+1;
412 xwalk := ex-lxd;
413 end;
415 // calculate ywalk
416 if (lsty < 0) then
417 begin
418 ey := (lyd and (not (TileSize-1)))-1;
419 ywalk := lyd-ey;
420 end
421 else
422 begin
423 ey := (lyd or (TileSize-1))+1;
424 ywalk := ey-lyd;
425 end;
427 while true do
428 begin
429 // in which dir we want to walk?
430 if (xwalk <= ywalk) then wklen := xwalk else wklen := ywalk;
431 // walk x
432 if (lstx < 0) then
433 begin
434 lxd -= wklen;
435 if (lxd <= lterm) then begin xd := lxd; result := true; exit; end;
436 end
437 else
438 begin
439 lxd += wklen;
440 if (lxd >= lterm) then begin xd := lxd; result := true; exit; end;
441 end;
442 // walk y
443 for f := 1 to wklen do if (le >= 0) then begin lyd += lsty; le -= ldx2; end else le += ldy2;
444 if (lxd = ex) or (lyd = ey) then break;
445 xwalk -= wklen; if (xwalk = 0) then xwalk := TileSize;
446 ywalk -= wklen; if (ywalk = 0) then ywalk := TileSize;
447 end;
448 //assert((xd div TileSize <> lxd div TileSize) or (yd div TileSize <> lyd div TileSize));
449 xd := lxd;
450 yd := lyd;
451 e := le;
452 end;
454 // NOT TESTED!
455 procedure TLineWalker.getPrevXY (out ox, oy: Integer); inline;
456 begin
457 //writeln('e=', e, '; dx2=', dx2, '; dy2=', dy2);
458 if xyswapped then
459 begin
460 if (e >= 0) then ox := yd-sty else ox := yd;
461 oy := xd-stx;
462 end
463 else
464 begin
465 if (e >= 0) then oy := yd-sty else oy := yd;
466 ox := xd-stx;
467 end;
468 end;
470 function TLineWalker.x (): Integer; inline; begin if xyswapped then result := yd else result := xd; end;
471 function TLineWalker.y (): Integer; inline; begin if xyswapped then result := xd else result := yd; end;
472 procedure TLineWalker.getXY (out ox, oy: Integer); inline; begin if xyswapped then begin ox := yd; oy := xd; end else begin ox := xd; oy := yd; end; end;
474 function TLineWalker.dx (): Integer; inline; begin if xyswapped then result := stx else result := sty; end;
475 function TLineWalker.dy (): Integer; inline; begin if xyswapped then result := sty else result := stx; end;
477 function TLineWalker.setup (x0, y0, x1, y1: Integer): Boolean;
478 procedure swapInt (var a: Integer; var b: Integer); inline; begin a := a xor b; b := b xor a; a := a xor b; end;
479 var
480 dsx, dsy: Integer; // "lengthes" for x and y axes
481 rem: Integer;
482 xfixed: Boolean;
483 temp: Integer;
484 begin
485 result := false;
486 xyswapped := false;
488 // horizontal setup
489 if (x0 < x1) then
490 begin
491 // from left to right
492 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
493 stx := 1; // going right
494 end
495 else
496 begin
497 // from right to left
498 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
499 stx := -1; // going left
500 x0 := -x0;
501 x1 := -x1;
502 wx0 := -wx0;
503 wx1 := -wx1;
504 swapInt(wx0, wx1);
505 end;
507 // vertical setup
508 if (y0 < y1) then
509 begin
510 // from top to bottom
511 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
512 sty := 1; // going down
513 end
514 else
515 begin
516 // from bottom to top
517 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
518 sty := -1; // going up
519 y0 := -y0;
520 y1 := -y1;
521 wy0 := -wy0;
522 wy1 := -wy1;
523 swapInt(wy0, wy1);
524 end;
526 dsx := x1-x0;
527 dsy := y1-y0;
529 if (dsx < dsy) then
530 begin
531 xyswapped := true;
532 //xptr := @yd;
533 //yptr := @xd;
534 swapInt(x0, y0);
535 swapInt(x1, y1);
536 swapInt(dsx, dsy);
537 swapInt(wx0, wy0);
538 swapInt(wx1, wy1);
539 swapInt(stx, sty);
540 end
541 else
542 begin
543 //xptr := @xd;
544 //yptr := @yd;
545 end;
547 dx2 := 2*dsx;
548 dy2 := 2*dsy;
549 xd := x0;
550 yd := y0;
551 e := 2*dsy-dsx;
552 term := x1;
554 xfixed := false;
555 if (y0 < wy0) then
556 begin
557 // clip at top
558 temp := dx2*(wy0-y0)-dsx;
559 xd += temp div dy2;
560 rem := temp mod dy2;
561 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
562 if (xd+1 >= wx0) then
563 begin
564 yd := wy0;
565 e -= rem+dsx;
566 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
567 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
568 xfixed := true;
569 end;
570 end;
572 if (not xfixed) and (x0 < wx0) then
573 begin
574 // clip at left
575 temp := dy2*(wx0-x0);
576 yd += temp div dx2;
577 rem := temp mod dx2;
578 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
579 xd := wx0;
580 e += rem;
581 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
582 end;
584 if (y1 > wy1) then
585 begin
586 // clip at bottom
587 temp := dx2*(wy1-y0)+dsx;
588 term := x0+temp div dy2;
589 rem := temp mod dy2;
590 if (rem = 0) then Dec(term);
591 end;
593 if (term > wx1) then term := wx1; // clip at right
595 Inc(term); // draw last point (it is ok to inc here, as `term` sign will be changed later
596 //if (term = xd) then exit; // this is the only point, get out of here
598 if (sty = -1) then yd := -yd;
599 if (stx = -1) then begin xd := -xd; term := -term; end;
600 dx2 -= dy2;
602 result := true;
603 end;
606 // ////////////////////////////////////////////////////////////////////////// //
607 // you are not supposed to understand this
608 // returns `true` if there is an intersection, and enter coords
609 // enter coords will be equal to (x0, y0) if starting point is inside the box
610 // if result is `false`, `inx` and `iny` are undefined
611 function lineAABBIntersects (x0, y0, x1, y1: Integer; bx, by, bw, bh: Integer; out inx, iny: Integer): Boolean;
612 var
613 wx0, wy0, wx1, wy1: Integer; // window coordinates
614 stx, sty: Integer; // "steps" for x and y axes
615 dsx, dsy: Integer; // "lengthes" for x and y axes
616 dx2, dy2: Integer; // "double lengthes" for x and y axes
617 xd, yd: Integer; // current coord
618 e: Integer; // "error" (as in bresenham algo)
619 rem: Integer;
620 //!term: Integer;
621 d0, d1: PInteger;
622 xfixed: Boolean;
623 temp: Integer;
624 begin
625 result := false;
626 // why not
627 inx := x0;
628 iny := y0;
629 if (bw < 1) or (bh < 1) then exit; // impossible box
631 if (x0 = x1) and (y0 = y1) then
632 begin
633 // check this point
634 result := (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh);
635 exit;
636 end;
638 // check if staring point is inside the box
639 if (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh) then begin result := true; exit; end;
641 // clip rectange
642 wx0 := bx;
643 wy0 := by;
644 wx1 := bx+bw-1;
645 wy1 := by+bh-1;
647 // horizontal setup
648 if (x0 < x1) then
649 begin
650 // from left to right
651 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
652 stx := 1; // going right
653 end
654 else
655 begin
656 // from right to left
657 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
658 stx := -1; // going left
659 x0 := -x0;
660 x1 := -x1;
661 wx0 := -wx0;
662 wx1 := -wx1;
663 swapInt(wx0, wx1);
664 end;
666 // vertical setup
667 if (y0 < y1) then
668 begin
669 // from top to bottom
670 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
671 sty := 1; // going down
672 end
673 else
674 begin
675 // from bottom to top
676 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
677 sty := -1; // going up
678 y0 := -y0;
679 y1 := -y1;
680 wy0 := -wy0;
681 wy1 := -wy1;
682 swapInt(wy0, wy1);
683 end;
685 dsx := x1-x0;
686 dsy := y1-y0;
688 if (dsx < dsy) then
689 begin
690 d0 := @yd;
691 d1 := @xd;
692 swapInt(x0, y0);
693 swapInt(x1, y1);
694 swapInt(dsx, dsy);
695 swapInt(wx0, wy0);
696 swapInt(wx1, wy1);
697 swapInt(stx, sty);
698 end
699 else
700 begin
701 d0 := @xd;
702 d1 := @yd;
703 end;
705 dx2 := 2*dsx;
706 dy2 := 2*dsy;
707 xd := x0;
708 yd := y0;
709 e := 2*dsy-dsx;
710 //!term := x1;
712 xfixed := false;
713 if (y0 < wy0) then
714 begin
715 // clip at top
716 temp := dx2*(wy0-y0)-dsx;
717 xd += temp div dy2;
718 rem := temp mod dy2;
719 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
720 if (xd+1 >= wx0) then
721 begin
722 yd := wy0;
723 e -= rem+dsx;
724 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
725 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
726 xfixed := true;
727 end;
728 end;
730 if (not xfixed) and (x0 < wx0) then
731 begin
732 // clip at left
733 temp := dy2*(wx0-x0);
734 yd += temp div dx2;
735 rem := temp mod dx2;
736 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
737 xd := wx0;
738 e += rem;
739 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
740 end;
742 (*
743 if (y1 > wy1) then
744 begin
745 // clip at bottom
746 temp := dx2*(wy1-y0)+dsx;
747 term := x0+temp div dy2;
748 rem := temp mod dy2;
749 if (rem = 0) then Dec(term);
750 end;
752 if (term > wx1) then term := wx1; // clip at right
754 Inc(term); // draw last point
755 //if (term = xd) then exit; // this is the only point, get out of here
756 *)
758 if (sty = -1) then yd := -yd;
759 if (stx = -1) then begin xd := -xd; {!term := -term;} end;
760 //!dx2 -= dy2;
762 inx := d0^;
763 iny := d1^;
764 result := true;
765 end;
768 // ////////////////////////////////////////////////////////////////////////// //
769 function sweepAABB (mex0, mey0, mew, meh: Integer; medx, medy: Integer; itx0, ity0, itw, ith: Integer;
770 u0: PSingle=nil; hitedge: PInteger=nil; u1: PSingle=nil): Boolean;
771 var
772 tin, tout: Single;
774 function axisOverlap (me0, me1, it0, it1, d, he0, he1: Integer): Boolean; inline;
775 var
776 t: Single;
777 begin
778 result := false;
780 if (me1 < it0) then
781 begin
782 if (d >= 0) then exit; // oops, no hit
783 t := (me1-it0+1)/d;
784 if (t > tin) then begin tin := t; hitedge^ := he1; end;
785 end
786 else if (it1 < me0) then
787 begin
788 if (d <= 0) then exit; // oops, no hit
789 t := (me0-it1-1)/d;
790 if (t > tin) then begin tin := t; hitedge^ := he0; end;
791 end;
793 if (d < 0) and (it1 > me0) then
794 begin
795 t := (me0-it1-1)/d;
796 if (t < tout) then tout := t;
797 end
798 else if (d > 0) and (me1 > it0) then
799 begin
800 t := (me1-it0+1)/d;
801 if (t < tout) then tout := t;
802 end;
804 result := true;
805 end;
807 var
808 mex1, mey1, itx1, ity1, vx, vy: Integer;
809 htt: Integer = -1;
810 begin
811 result := false;
812 if (u0 <> nil) then u0^ := -1.0;
813 if (u1 <> nil) then u1^ := -1.0;
814 if (hitedge = nil) then hitedge := @htt else hitedge^ := -1;
816 if (mew < 1) or (meh < 1) or (itw < 1) or (ith < 1) then exit;
818 mex1 := mex0+mew-1;
819 mey1 := mey0+meh-1;
820 itx1 := itx0+itw-1;
821 ity1 := ity0+ith-1;
823 // check if they are overlapping right now (SAT)
824 //if (mex1 >= itx0) and (mex0 <= itx1) and (mey1 >= ity0) and (mey0 <= ity1) then begin result := true; exit; end;
826 if (medx = 0) and (medy = 0) then exit; // both boxes are sationary
828 // treat b as stationary, so invert v to get relative velocity
829 vx := -medx;
830 vy := -medy;
832 tin := -100000000.0;
833 tout := 100000000.0;
835 if not axisOverlap(mex0, mex1, itx0, itx1, vx, 1, 3) then exit;
836 if not axisOverlap(mey0, mey1, ity0, ity1, vy, 2, 0) then exit;
838 if (u0 <> nil) then u0^ := tin;
839 if (u1 <> nil) then u1^ := tout;
841 if (tin <= tout) and (tin >= 0.0) and (tin <= 1.0) then
842 begin
843 result := true;
844 end;
845 end;
848 // ////////////////////////////////////////////////////////////////////////// //
849 procedure TBodyGridBase.TBodyProxyRec.setup (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer);
850 begin
851 mX := aX;
852 mY := aY;
853 mWidth := aWidth;
854 mHeight := aHeight;
855 mQueryMark := 0;
856 mObj := aObj;
857 mTag := aTag;
858 nextLink := -1;
859 end;
862 function TBodyGridBase.TBodyProxyRec.getTag (): Integer; inline;
863 begin
864 result := mTag and TagFullMask;
865 end;
867 procedure TBodyGridBase.TBodyProxyRec.setTag (v: Integer); inline;
868 begin
869 mTag := (mTag and TagDisabled) or (v and TagFullMask);
870 end;
872 function TBodyGridBase.TBodyProxyRec.getEnabled (): Boolean; inline;
873 begin
874 result := ((mTag and TagDisabled) = 0);
875 end;
877 procedure TBodyGridBase.TBodyProxyRec.setEnabled (v: Boolean); inline;
878 begin
879 if v then mTag := mTag and (not TagDisabled) else mTag := mTag or TagDisabled;
880 end;
882 function TBodyGridBase.TBodyProxyRec.getX1 (): Integer; inline;
883 begin
884 result := mX+mWidth-1;
885 end;
887 function TBodyGridBase.TBodyProxyRec.getY1 (): Integer; inline;
888 begin
889 result := mY+mHeight-1;
890 end;
893 // ////////////////////////////////////////////////////////////////////////// //
894 constructor TBodyGridBase.TAtPointEnumerator.Create (acells: TCellArray; aidx: Integer; agetpx: TGetProxyFn);
895 begin
896 mCells := acells;
897 curidx := aidx;
898 curbki := -1;
899 getpx := agetpx;
900 end;
903 function TBodyGridBase.TAtPointEnumerator.MoveNext (): Boolean; inline;
904 begin
905 while (curidx <> -1) do
906 begin
907 while (curbki < GridCellBucketSize) do
908 begin
909 Inc(curbki);
910 if (mCells[curidx].bodies[curbki] = -1) then break;
911 result := true;
912 exit;
913 end;
914 curidx := mCells[curidx].next;
915 curbki := -1;
916 end;
917 result := false;
918 end;
921 function TBodyGridBase.TAtPointEnumerator.getCurrent (): PBodyProxyRec; inline;
922 begin
923 result := getpx(mCells[curidx].bodies[curbki]);
924 end;
927 // ////////////////////////////////////////////////////////////////////////// //
928 constructor TBodyGridBase.Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
929 var
930 idx: Integer;
931 begin
932 dbgShowTraceLog := false;
933 {$IF DEFINED(D2F_DEBUG)}
934 dbgRayTraceTileHitCB := nil;
935 {$ENDIF}
937 if aTileSize < 1 then aTileSize := 1;
938 if aTileSize > 8192 then aTileSize := 8192; // arbitrary limit
939 mTileSize := aTileSize;
941 if (aPixWidth < mTileSize) then aPixWidth := mTileSize;
942 if (aPixHeight < mTileSize) then aPixHeight := mTileSize;
943 mMinX := aMinPixX;
944 mMinY := aMinPixY;
945 mWidth := (aPixWidth+mTileSize-1) div mTileSize;
946 mHeight := (aPixHeight+mTileSize-1) div mTileSize;
947 SetLength(mGrid, mWidth*mHeight);
948 SetLength(mCells, mWidth*mHeight);
949 SetLength(mProxies, 8192);
950 mFreeCell := 0;
951 // init free list
952 for idx := 0 to High(mCells) do
953 begin
954 mCells[idx].bodies[0] := -1;
955 mCells[idx].bodies[GridCellBucketSize-1] := -1; // "has free room" flag
956 mCells[idx].next := idx+1;
957 end;
958 mCells[High(mCells)].next := -1; // last cell
959 // init grid
960 for idx := 0 to High(mGrid) do mGrid[idx] := -1;
961 // init proxies
962 for idx := 0 to High(mProxies) do mProxies[idx].nextLink := idx+1;
963 mProxies[High(mProxies)].nextLink := -1;
964 mLastQuery := 0;
965 mUsedCells := 0;
966 mProxyFree := 0;
967 mProxyCount := 0;
968 mProxyMaxCount := 0;
969 e_WriteLog(Format('created grid with size: %dx%d (tile size: %d); pix: %dx%d', [mWidth, mHeight, mTileSize, mWidth*mTileSize, mHeight*mTileSize]), MSG_NOTIFY);
970 end;
973 destructor TBodyGridBase.Destroy ();
974 begin
975 mCells := nil;
976 mGrid := nil;
977 mProxies := nil;
978 inherited;
979 end;
982 // ////////////////////////////////////////////////////////////////////////// //
983 procedure TBodyGridBase.dumpStats ();
984 var
985 idx, mcb, ccidx, cnt: Integer;
986 begin
987 mcb := 0;
988 for idx := 0 to High(mGrid) do
989 begin
990 ccidx := mGrid[idx];
991 cnt := 0;
992 while ccidx >= 0 do
993 begin
994 Inc(cnt);
995 ccidx := mCells[ccidx].next;
996 end;
997 if (mcb < cnt) then mcb := cnt;
998 end;
999 e_WriteLog(Format('grid size: %dx%d (tile size: %d); pix: %dx%d; used cells: %d; max bodies in cell: %d; max proxies allocated: %d; proxies used: %d', [mWidth, mHeight, mTileSize, mWidth*mTileSize, mHeight*mTileSize, mUsedCells, mcb, mProxyMaxCount, mProxyCount]), MSG_NOTIFY);
1000 end;
1003 procedure TBodyGridBase.forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
1004 var
1005 g, f, ccidx: Integer;
1006 cc: PGridCell;
1007 begin
1008 if (body < 0) or (body > High(mProxies)) or not assigned(cb) then exit;
1009 for g := 0 to High(mGrid) do
1010 begin
1011 ccidx := mGrid[g];
1012 while (ccidx <> -1) do
1013 begin
1014 cc := @mCells[ccidx];
1015 for f := 0 to GridCellBucketSize-1 do
1016 begin
1017 if (cc.bodies[f] = -1) then break;
1018 if (cc.bodies[f] = body) then cb((g mod mWidth)*mTileSize+mMinX, (g div mWidth)*mTileSize+mMinY);
1019 end;
1020 // next cell
1021 ccidx := cc.next;
1022 end;
1023 end;
1024 end;
1027 function TBodyGridBase.forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
1028 var
1029 f, ccidx: Integer;
1030 cc: PGridCell;
1031 begin
1032 result := Default(ITP);
1033 if not assigned(cb) then exit;
1034 Dec(x, mMinX);
1035 Dec(y, mMinY);
1036 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y > mHeight*mTileSize) then exit;
1037 ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1038 while (ccidx <> -1) do
1039 begin
1040 cc := @mCells[ccidx];
1041 for f := 0 to GridCellBucketSize-1 do
1042 begin
1043 if (cc.bodies[f] = -1) then break;
1044 if cb(mProxies[cc.bodies[f]].mObj, mProxies[cc.bodies[f]].mTag) then begin result := mProxies[cc.bodies[f]].mObj; exit; end;
1045 end;
1046 // next cell
1047 ccidx := cc.next;
1048 end;
1049 end;
1052 // ////////////////////////////////////////////////////////////////////////// //
1053 function TBodyGridBase.getGridWidthPx (): Integer; inline; begin result := mWidth*mTileSize; end;
1054 function TBodyGridBase.getGridHeightPx (): Integer; inline; begin result := mHeight*mTileSize; end;
1057 function TBodyGridBase.insideGrid (x, y: Integer): Boolean; inline;
1058 begin
1059 // fix coords
1060 Dec(x, mMinX);
1061 Dec(y, mMinY);
1062 result := (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize);
1063 end;
1066 function TBodyGridBase.getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
1067 begin
1068 if (body >= 0) and (body < Length(mProxies)) then
1069 begin
1070 with mProxies[body] do begin rx := mX; ry := mY; end;
1071 result := true;
1072 end
1073 else
1074 begin
1075 rx := 0;
1076 ry := 0;
1077 result := false;
1078 end;
1079 end;
1082 function TBodyGridBase.getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
1083 begin
1084 if (body >= 0) and (body < Length(mProxies)) then
1085 begin
1086 with mProxies[body] do begin rw := mWidth; rh := mHeight; end;
1087 result := true;
1088 end
1089 else
1090 begin
1091 rw := 0;
1092 rh := 0;
1093 result := false;
1094 end;
1095 end;
1098 function TBodyGridBase.getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
1099 begin
1100 if (body >= 0) and (body < Length(mProxies)) then
1101 begin
1102 with mProxies[body] do begin rx := mX; ry := mY; rw := mWidth; rh := mHeight; end;
1103 result := true;
1104 end
1105 else
1106 begin
1107 rx := 0;
1108 ry := 0;
1109 rw := 0;
1110 rh := 0;
1111 result := false;
1112 end;
1113 end;
1117 // ////////////////////////////////////////////////////////////////////////// //
1118 function TBodyGridBase.getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
1119 begin
1120 if (pid >= 0) and (pid < Length(mProxies)) then result := ((mProxies[pid].mTag and TagDisabled) = 0) else result := false;
1121 end;
1124 procedure TBodyGridBase.setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
1125 begin
1126 if (pid >= 0) and (pid < Length(mProxies)) then
1127 begin
1128 if val then
1129 begin
1130 mProxies[pid].mTag := mProxies[pid].mTag and not TagDisabled;
1131 end
1132 else
1133 begin
1134 mProxies[pid].mTag := mProxies[pid].mTag or TagDisabled;
1135 end;
1136 end;
1137 end;
1140 function TBodyGridBase.getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
1141 begin
1142 if (idx >= 0) and (idx < Length(mProxies)) then result := @mProxies[idx] else result := nil;
1143 end;
1146 // ////////////////////////////////////////////////////////////////////////// //
1147 function TBodyGridBase.allocCell (): Integer;
1148 var
1149 idx: Integer;
1150 pc: PGridCell;
1151 begin
1152 if (mFreeCell < 0) then
1153 begin
1154 // no free cells, want more
1155 mFreeCell := Length(mCells);
1156 SetLength(mCells, mFreeCell+32768); // arbitrary number
1157 for idx := mFreeCell to High(mCells) do
1158 begin
1159 mCells[idx].bodies[0] := -1;
1160 mCells[idx].bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
1161 mCells[idx].next := idx+1;
1162 end;
1163 mCells[High(mCells)].next := -1; // last cell
1164 end;
1165 result := mFreeCell;
1166 pc := @mCells[result];
1167 mFreeCell := pc.next;
1168 pc.next := -1;
1169 Inc(mUsedCells);
1170 //e_WriteLog(Format('grid: allocated new cell #%d (total: %d)', [result, mUsedCells]), MSG_NOTIFY);
1171 end;
1174 procedure TBodyGridBase.freeCell (idx: Integer);
1175 begin
1176 if (idx >= 0) and (idx < Length(mCells)) then
1177 begin
1178 with mCells[idx] do
1179 begin
1180 bodies[0] := -1;
1181 bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
1182 next := mFreeCell;
1183 end;
1184 mFreeCell := idx;
1185 Dec(mUsedCells);
1186 end;
1187 end;
1190 // ////////////////////////////////////////////////////////////////////////// //
1191 function TBodyGridBase.allocProxy (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer): TBodyProxyId;
1192 var
1193 olen, idx: Integer;
1194 px: PBodyProxyRec;
1195 begin
1196 if (mProxyFree = -1) then
1197 begin
1198 // no free proxies, resize list
1199 olen := Length(mProxies);
1200 SetLength(mProxies, olen+8192); // arbitrary number
1201 for idx := olen to High(mProxies) do mProxies[idx].nextLink := idx+1;
1202 mProxies[High(mProxies)].nextLink := -1;
1203 mProxyFree := olen;
1204 end;
1205 // get one from list
1206 result := mProxyFree;
1207 px := @mProxies[result];
1208 mProxyFree := px.nextLink;
1209 px.setup(aX, aY, aWidth, aHeight, aObj, aTag);
1210 // add to used list
1211 px.nextLink := -1;
1212 // statistics
1213 Inc(mProxyCount);
1214 if (mProxyMaxCount < mProxyCount) then mProxyMaxCount := mProxyCount;
1215 end;
1217 procedure TBodyGridBase.freeProxy (body: TBodyProxyId);
1218 begin
1219 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1220 if (mProxyCount = 0) then raise Exception.Create('wutafuuuuu in grid (no allocated proxies, what i should free now?)');
1221 // add to free list
1222 mProxies[body].mObj := nil;
1223 mProxies[body].nextLink := mProxyFree;
1224 mProxyFree := body;
1225 Dec(mProxyCount);
1226 end;
1229 // ////////////////////////////////////////////////////////////////////////// //
1230 function TBodyGridBase.forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
1231 var
1232 gw, gh: Integer;
1233 ex, ey: Integer;
1234 gx, gy: Integer;
1235 begin
1236 result := false;
1237 if (w < 1) or (h < 1) or not assigned(cb) then exit;
1238 // fix coords
1239 Dec(x, mMinX);
1240 Dec(y, mMinY);
1241 // go on
1242 if (x+w <= 0) or (y+h <= 0) then exit;
1243 gw := mWidth;
1244 gh := mHeight;
1245 if (x >= gw*mTileSize) or (y >= gh*mTileSize) then exit;
1246 ex := (x+w-1) div mTileSize;
1247 ey := (y+h-1) div mTileSize;
1248 x := x div mTileSize;
1249 y := y div mTileSize;
1250 // clip rect
1251 if (x < 0) then x := 0 else if (x >= gw) then x := gw-1;
1252 if (y < 0) then y := 0 else if (y >= gh) then y := gh-1;
1253 if (ex < 0) then ex := 0 else if (ex >= gw) then ex := gw-1;
1254 if (ey < 0) then ey := 0 else if (ey >= gh) then ey := gh-1;
1255 if (x > ex) or (y > ey) then exit; // just in case
1256 // do the work
1257 for gy := y to ey do
1258 begin
1259 for gx := x to ex do
1260 begin
1261 result := cb(gy*gw+gx, bodyId);
1262 if result then exit;
1263 end;
1264 end;
1265 end;
1268 // ////////////////////////////////////////////////////////////////////////// //
1269 function TBodyGridBase.inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
1270 var
1271 ccidx: Integer;
1272 pc: Integer;
1273 pi: PGridCell;
1274 f: Integer;
1275 begin
1276 result := false; // never stop
1277 // add body to the given grid cell
1278 pc := mGrid[grida];
1279 if (pc <> -1) then
1280 begin
1281 {$IF DEFINED(D2F_DEBUG)}
1282 ccidx := pc;
1283 while (ccidx <> -1) do
1284 begin
1285 pi := @mCells[ccidx];
1286 for f := 0 to GridCellBucketSize-1 do
1287 begin
1288 if (pi.bodies[f] = -1) then break;
1289 if (pi.bodies[f] = bodyId) then raise Exception.Create('trying to insert already inserted proxy');
1290 end;
1291 ccidx := pi.next;
1292 end;
1293 {$ENDIF}
1294 ccidx := pc;
1295 while (ccidx <> -1) do
1296 begin
1297 pi := @mCells[ccidx];
1298 // check "has room" flag
1299 if (pi.bodies[GridCellBucketSize-1] = -1) then
1300 begin
1301 // can add here
1302 for f := 0 to GridCellBucketSize-1 do
1303 begin
1304 if (pi.bodies[f] = -1) then
1305 begin
1306 pi.bodies[f] := bodyId;
1307 if (f+1 < GridCellBucketSize) then pi.bodies[f+1] := -1;
1308 exit;
1309 end;
1310 end;
1311 raise Exception.Create('internal error in grid inserter');
1312 end;
1313 // no room, go to next cell in list (if there is any)
1314 ccidx := pi.next;
1315 end;
1316 // no room in cells, add new cell to list
1317 end;
1318 // either no room, or no cell at all
1319 ccidx := allocCell();
1320 pi := @mCells[ccidx];
1321 pi.bodies[0] := bodyId;
1322 pi.bodies[1] := -1;
1323 pi.next := pc;
1324 mGrid[grida] := ccidx;
1325 end;
1328 // assume that we cannot have one object added to bucket twice
1329 function TBodyGridBase.remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
1330 var
1331 f, c: Integer;
1332 pidx, ccidx: Integer;
1333 pc: PGridCell;
1334 begin
1335 result := false; // never stop
1336 // find and remove cell
1337 pidx := -1; // previous cell index
1338 ccidx := mGrid[grida]; // current cell index
1339 while (ccidx <> -1) do
1340 begin
1341 pc := @mCells[ccidx];
1342 for f := 0 to GridCellBucketSize-1 do
1343 begin
1344 if (pc.bodies[f] = bodyId) then
1345 begin
1346 // i found her!
1347 if (f = 0) and (pc.bodies[1] = -1) then
1348 begin
1349 // this cell contains no elements, remove it
1350 if (pidx = -1) then mGrid[grida] := pc.next else mCells[pidx].next := pc.next;
1351 freeCell(ccidx);
1352 exit;
1353 end;
1354 // remove element from bucket
1355 for c := f to GridCellBucketSize-2 do
1356 begin
1357 pc.bodies[c] := pc.bodies[c+1];
1358 if (pc.bodies[c] = -1) then break;
1359 end;
1360 pc.bodies[GridCellBucketSize-1] := -1; // "has free room" flag
1361 exit;
1362 end;
1363 end;
1364 pidx := ccidx;
1365 ccidx := pc.next;
1366 end;
1367 end;
1370 // ////////////////////////////////////////////////////////////////////////// //
1371 function TBodyGridBase.insertBody (aObj: ITP; aX, aY, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
1372 begin
1373 aTag := aTag and TagFullMask;
1374 result := allocProxy(aX, aY, aWidth, aHeight, aObj, aTag);
1375 //insertInternal(result);
1376 forGridRect(aX, aY, aWidth, aHeight, inserter, result);
1377 end;
1380 procedure TBodyGridBase.removeBody (body: TBodyProxyId);
1381 var
1382 px: PBodyProxyRec;
1383 begin
1384 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1385 px := @mProxies[body];
1386 //removeInternal(body);
1387 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1388 freeProxy(body);
1389 end;
1392 // ////////////////////////////////////////////////////////////////////////// //
1393 procedure TBodyGridBase.moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
1394 var
1395 px: PBodyProxyRec;
1396 x0, y0, w, h: Integer;
1397 begin
1398 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1399 px := @mProxies[body];
1400 x0 := px.mX;
1401 y0 := px.mY;
1402 w := px.mWidth;
1403 h := px.mHeight;
1404 {$IF DEFINED(D2F_DEBUG_MOVER)}
1405 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);
1406 {$ENDIF}
1407 if (nx = x0) and (ny = y0) and (nw = w) and (nh = h) then exit;
1408 // map -> grid
1409 Dec(x0, mMinX);
1410 Dec(y0, mMinY);
1411 Dec(nx, mMinX);
1412 Dec(ny, mMinY);
1413 // did any corner crossed tile boundary?
1414 if (x0 div mTileSize <> nx div mTileSize) or
1415 (y0 div mTileSize <> ny div mTileSize) or
1416 ((x0+w-1) div mTileSize <> (nx+nw-1) div mTileSize) or
1417 ((y0+h-1) div mTileSize <> (ny+nh-1) div mTileSize) then
1418 begin
1419 //writeln('moveResizeBody: cell occupation changed! old=(', x0, ',', y0, ')-(', x0+w-1, ',', y0+h-1, '); new=(', nx, ',', ny, ')-(', nx+nw-1, ',', ny+nh-1, ')');
1420 //removeInternal(body);
1421 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1422 px.mX := nx+mMinX;
1423 px.mY := ny+mMinY;
1424 px.mWidth := nw;
1425 px.mHeight := nh;
1426 //insertInternal(body);
1427 forGridRect(px.mX, px.mY, nw, nh, inserter, body);
1428 end
1429 else
1430 begin
1431 px.mX := nx+mMinX;
1432 px.mY := ny+mMinY;
1433 px.mWidth := nw;
1434 px.mHeight := nh;
1435 end;
1436 end;
1439 //TODO: optimize for horizontal/vertical moves
1440 procedure TBodyGridBase.moveBody (body: TBodyProxyId; nx, ny: Integer);
1441 var
1442 px: PBodyProxyRec;
1443 x0, y0: Integer;
1444 ogx0, ogx1, ogy0, ogy1: Integer; // old grid rect
1445 ngx0, ngx1, ngy0, ngy1: Integer; // new grid rect
1446 gx, gy: Integer;
1447 gw, gh: Integer;
1448 pw, ph: Integer;
1449 begin
1450 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1451 // check if tile coords was changed
1452 px := @mProxies[body];
1453 x0 := px.mX;
1454 y0 := px.mY;
1455 if (nx = x0) and (ny = y0) then exit;
1456 // map -> grid
1457 Dec(x0, mMinX);
1458 Dec(y0, mMinY);
1459 Dec(nx, mMinX);
1460 Dec(ny, mMinY);
1461 // check for heavy work
1462 pw := px.mWidth;
1463 ph := px.mHeight;
1464 ogx0 := x0 div mTileSize;
1465 ogy0 := y0 div mTileSize;
1466 ngx0 := nx div mTileSize;
1467 ngy0 := ny div mTileSize;
1468 ogx1 := (x0+pw-1) div mTileSize;
1469 ogy1 := (y0+ph-1) div mTileSize;
1470 ngx1 := (nx+pw-1) div mTileSize;
1471 ngy1 := (ny+ph-1) div mTileSize;
1472 {$IF DEFINED(D2F_DEBUG_MOVER)}
1473 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);
1474 {$ENDIF}
1475 if (ogx0 <> ngx0) or (ogy0 <> ngy0) or (ogx1 <> ngx1) or (ogy1 <> ngy1) then
1476 begin
1477 // crossed tile boundary, do heavy work
1478 gw := mWidth;
1479 gh := mHeight;
1480 // cycle with old rect, remove body where it is necessary
1481 // optimized for horizontal moves
1482 {$IF DEFINED(D2F_DEBUG_MOVER)}
1483 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);
1484 {$ENDIF}
1485 // remove stale marks
1486 if not ((ogy0 >= gh) or (ogy1 < 0)) and
1487 not ((ogx0 >= gw) or (ogx1 < 0)) then
1488 begin
1489 if (ogx0 < 0) then ogx0 := 0;
1490 if (ogy0 < 0) then ogy0 := 0;
1491 if (ogx1 > gw-1) then ogx1 := gw-1;
1492 if (ogy1 > gh-1) then ogy1 := gh-1;
1493 {$IF DEFINED(D2F_DEBUG_MOVER)}
1494 e_WriteLog(Format(' norm og:(%d,%d)-(%d,%d)', [ogx0, ogy0, ogx1, ogy1]), MSG_NOTIFY);
1495 {$ENDIF}
1496 for gx := ogx0 to ogx1 do
1497 begin
1498 if (gx < ngx0) or (gx > ngx1) then
1499 begin
1500 // this column is completely outside of new rect
1501 for gy := ogy0 to ogy1 do
1502 begin
1503 {$IF DEFINED(D2F_DEBUG_MOVER)}
1504 e_WriteLog(Format(' remove0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1505 {$ENDIF}
1506 remover(gy*gw+gx, body);
1507 end;
1508 end
1509 else
1510 begin
1511 // heavy checks
1512 for gy := ogy0 to ogy1 do
1513 begin
1514 if (gy < ngy0) or (gy > ngy1) then
1515 begin
1516 {$IF DEFINED(D2F_DEBUG_MOVER)}
1517 e_WriteLog(Format(' remove1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1518 {$ENDIF}
1519 remover(gy*gw+gx, body);
1520 end;
1521 end;
1522 end;
1523 end;
1524 end;
1525 // cycle with new rect, add body where it is necessary
1526 if not ((ngy0 >= gh) or (ngy1 < 0)) and
1527 not ((ngx0 >= gw) or (ngx1 < 0)) then
1528 begin
1529 if (ngx0 < 0) then ngx0 := 0;
1530 if (ngy0 < 0) then ngy0 := 0;
1531 if (ngx1 > gw-1) then ngx1 := gw-1;
1532 if (ngy1 > gh-1) then ngy1 := gh-1;
1533 {$IF DEFINED(D2F_DEBUG_MOVER)}
1534 e_WriteLog(Format(' norm ng:(%d,%d)-(%d,%d)', [ngx0, ngy0, ngx1, ngy1]), MSG_NOTIFY);
1535 {$ENDIF}
1536 for gx := ngx0 to ngx1 do
1537 begin
1538 if (gx < ogx0) or (gx > ogx1) then
1539 begin
1540 // this column is completely outside of old rect
1541 for gy := ngy0 to ngy1 do
1542 begin
1543 {$IF DEFINED(D2F_DEBUG_MOVER)}
1544 e_WriteLog(Format(' insert0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1545 {$ENDIF}
1546 inserter(gy*gw+gx, body);
1547 end;
1548 end
1549 else
1550 begin
1551 // heavy checks
1552 for gy := ngy0 to ngy1 do
1553 begin
1554 if (gy < ogy0) or (gy > ogy1) then
1555 begin
1556 {$IF DEFINED(D2F_DEBUG_MOVER)}
1557 e_WriteLog(Format(' insert1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1558 {$ENDIF}
1559 inserter(gy*gw+gx, body);
1560 end;
1561 end;
1562 end;
1563 end;
1564 end;
1565 // done
1566 end
1567 else
1568 begin
1569 {$IF DEFINED(D2F_DEBUG_MOVER)}
1570 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);
1571 {$ENDIF}
1572 end;
1573 // update coordinates
1574 px.mX := nx+mMinX;
1575 px.mY := ny+mMinY;
1576 end;
1579 procedure TBodyGridBase.resizeBody (body: TBodyProxyId; nw, nh: Integer);
1580 var
1581 px: PBodyProxyRec;
1582 x0, y0, w, h: Integer;
1583 begin
1584 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1585 // check if tile coords was changed
1586 px := @mProxies[body];
1587 x0 := px.mX-mMinX;
1588 y0 := px.mY-mMinY;
1589 w := px.mWidth;
1590 h := px.mHeight;
1591 {$IF DEFINED(D2F_DEBUG_MOVER)}
1592 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);
1593 {$ENDIF}
1594 if ((x0+w-1) div mTileSize <> (x0+nw-1) div mTileSize) or
1595 ((y0+h-1) div mTileSize <> (y0+nh-1) div mTileSize) then
1596 begin
1597 // crossed tile boundary, do heavy work
1598 //removeInternal(body);
1599 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1600 px.mWidth := nw;
1601 px.mHeight := nh;
1602 //insertInternal(body);
1603 forGridRect(px.mX, px.mY, nw, nh, inserter, body);
1604 end
1605 else
1606 begin
1607 // nothing to do with the grid, just fix size
1608 px.mWidth := nw;
1609 px.mHeight := nh;
1610 end;
1611 end;
1614 // ////////////////////////////////////////////////////////////////////////// //
1615 function TBodyGridBase.atCellInPoint (x, y: Integer): TAtPointEnumerator;
1616 var
1617 ccidx: Integer = -1;
1618 begin
1619 Dec(x, mMinX);
1620 Dec(y, mMinY);
1621 if (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize) then ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1622 result := TAtPointEnumerator.Create(mCells, ccidx, getProxyById);
1623 end;
1626 // ////////////////////////////////////////////////////////////////////////// //
1627 // no callback: return `true` on the first hit
1628 function TBodyGridBase.forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
1629 var
1630 f: Integer;
1631 idx, curci: Integer;
1632 cc: PGridCell = nil;
1633 px: PBodyProxyRec;
1634 lq: LongWord;
1635 ptag: Integer;
1636 begin
1637 result := Default(ITP);
1638 if (exittag <> nil) then exittag^ := 0;
1639 tagmask := tagmask and TagFullMask;
1640 if (tagmask = 0) then exit;
1642 {$IF DEFINED(D2F_DEBUG_XXQ)}
1643 if (assigned(cb)) then e_WriteLog(Format('0: grid pointquery: (%d,%d)', [x, y]), MSG_NOTIFY);
1644 {$ENDIF}
1646 // make coords (0,0)-based
1647 Dec(x, mMinX);
1648 Dec(y, mMinY);
1649 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y >= mHeight*mTileSize) then exit;
1651 curci := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1653 {$IF DEFINED(D2F_DEBUG_XXQ)}
1654 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);
1655 {$ENDIF}
1657 // restore coords
1658 Inc(x, mMinX);
1659 Inc(y, mMinY);
1661 // increase query counter
1662 Inc(mLastQuery);
1663 if (mLastQuery = 0) then
1664 begin
1665 // just in case of overflow
1666 mLastQuery := 1;
1667 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1668 end;
1669 lq := mLastQuery;
1671 {$IF DEFINED(D2F_DEBUG_XXQ)}
1672 if (assigned(cb)) then e_WriteLog(Format('2: grid pointquery: (%d,%d); lq=%u', [x, y, lq]), MSG_NOTIFY);
1673 {$ENDIF}
1675 while (curci <> -1) do
1676 begin
1677 {$IF DEFINED(D2F_DEBUG_XXQ)}
1678 if (assigned(cb)) then e_WriteLog(Format(' cell #%d', [curci]), MSG_NOTIFY);
1679 {$ENDIF}
1680 cc := @mCells[curci];
1681 for f := 0 to GridCellBucketSize-1 do
1682 begin
1683 if (cc.bodies[f] = -1) then break;
1684 px := @mProxies[cc.bodies[f]];
1685 {$IF DEFINED(D2F_DEBUG_XXQ)}
1686 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);
1687 {$ENDIF}
1688 // shit. has to do it this way, so i can change tag in callback
1689 if (px.mQueryMark <> lq) then
1690 begin
1691 px.mQueryMark := lq;
1692 ptag := px.mTag;
1693 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
1694 (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
1695 begin
1696 if assigned(cb) then
1697 begin
1698 if cb(px.mObj, ptag) then
1699 begin
1700 result := px.mObj;
1701 if (exittag <> nil) then exittag^ := ptag;
1702 exit;
1703 end;
1704 end
1705 else
1706 begin
1707 result := px.mObj;
1708 if (exittag <> nil) then exittag^ := ptag;
1709 exit;
1710 end;
1711 end;
1712 end;
1713 end;
1714 curci := cc.next;
1715 end;
1716 end;
1719 // ////////////////////////////////////////////////////////////////////////// //
1720 // no callback: return `true` on the first hit
1721 function TBodyGridBase.forEachInAABB (x, y, w, h: Integer; cb: TGridQueryCB; tagmask: Integer=-1; allowDisabled: Boolean=false): ITP;
1722 var
1723 idx: Integer;
1724 gx, gy: Integer;
1725 curci: Integer;
1726 f: Integer;
1727 cc: PGridCell = nil;
1728 px: PBodyProxyRec;
1729 lq: LongWord;
1730 gw: Integer;
1731 x0, y0: Integer;
1732 ptag: Integer;
1733 begin
1734 result := Default(ITP);
1735 if (w < 1) or (h < 1) then exit;
1736 tagmask := tagmask and TagFullMask;
1737 if (tagmask = 0) then exit;
1739 x0 := x;
1740 y0 := y;
1742 // fix coords
1743 Dec(x, mMinX);
1744 Dec(y, mMinY);
1746 gw := mWidth;
1747 //tsize := mTileSize;
1749 if (x+w <= 0) or (y+h <= 0) then exit;
1750 if (x >= gw*mTileSize) or (y >= mHeight*mTileSize) then exit;
1752 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1753 mInQuery := true;
1755 // increase query counter
1756 Inc(mLastQuery);
1757 if (mLastQuery = 0) then
1758 begin
1759 // just in case of overflow
1760 mLastQuery := 1;
1761 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1762 end;
1763 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
1764 lq := mLastQuery;
1766 // go on
1767 for gy := y div mTileSize to (y+h-1) div mTileSize do
1768 begin
1769 if (gy < 0) then continue;
1770 if (gy >= mHeight) then break;
1771 for gx := x div mTileSize to (x+w-1) div mTileSize do
1772 begin
1773 if (gx < 0) then continue;
1774 if (gx >= gw) then break;
1775 // process cells
1776 curci := mGrid[gy*gw+gx];
1777 while (curci <> -1) do
1778 begin
1779 cc := @mCells[curci];
1780 for f := 0 to GridCellBucketSize-1 do
1781 begin
1782 if (cc.bodies[f] = -1) then break;
1783 px := @mProxies[cc.bodies[f]];
1784 // shit. has to do it this way, so i can change tag in callback
1785 if (px.mQueryMark = lq) then continue;
1786 px.mQueryMark := lq;
1787 ptag := px.mTag;
1788 if (not allowDisabled) and ((ptag and TagDisabled) <> 0) then continue;
1789 if ((ptag and tagmask) = 0) then continue;
1790 if (x0 >= px.mX+px.mWidth) or (y0 >= px.mY+px.mHeight) then continue;
1791 if (x0+w <= px.mX) or (y0+h <= px.mY) then continue;
1792 if assigned(cb) then
1793 begin
1794 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
1795 end
1796 else
1797 begin
1798 result := px.mObj;
1799 mInQuery := false;
1800 exit;
1801 end;
1802 end;
1803 curci := cc.next;
1804 end;
1805 end;
1806 end;
1808 mInQuery := false;
1809 end;
1812 // ////////////////////////////////////////////////////////////////////////// //
1813 function TBodyGridBase.forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
1814 var
1815 lw: TLineWalker;
1816 ccidx: Integer;
1817 cc: PGridCell;
1818 px: PBodyProxyRec;
1819 lq: LongWord;
1820 f, ptag: Integer;
1821 gw, gh, minx, miny: Integer;
1822 x0, y0: Integer;
1823 x1, y1: Integer;
1824 cx, cy: Integer;
1825 //px0, py0, px1, py1: Integer;
1826 begin
1827 log := false;
1828 result := Default(ITP);
1829 tagmask := tagmask and TagFullMask;
1830 if (tagmask = 0) or not assigned(cb) then exit;
1832 gw := mWidth;
1833 gh := mHeight;
1834 minx := mMinX;
1835 miny := mMinY;
1837 // make query coords (0,0)-based
1838 x0 := ax0-minx;
1839 y0 := ay0-miny;
1840 x1 := ax1-minx;
1841 y1 := ay1-miny;
1843 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
1844 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
1846 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1847 mInQuery := true;
1849 // increase query counter
1850 Inc(mLastQuery);
1851 if (mLastQuery = 0) then
1852 begin
1853 // just in case of overflow
1854 mLastQuery := 1;
1855 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1856 end;
1857 lq := mLastQuery;
1859 repeat
1860 lw.getXY(cx, cy);
1861 // check tile
1862 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
1863 // process cells
1864 while (ccidx <> -1) do
1865 begin
1866 cc := @mCells[ccidx];
1867 for f := 0 to GridCellBucketSize-1 do
1868 begin
1869 if (cc.bodies[f] = -1) then break;
1870 px := @mProxies[cc.bodies[f]];
1871 ptag := px.mTag;
1872 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1873 begin
1874 px.mQueryMark := lq; // mark as processed
1875 if cb(px.mObj, ptag) then
1876 begin
1877 result := px.mObj;
1878 mInQuery := false;
1879 exit;
1880 end;
1881 end;
1882 end;
1883 // next cell
1884 ccidx := cc.next;
1885 end;
1886 // done processing cells, move to next tile
1887 until lw.stepToNextTile();
1889 mInQuery := false;
1890 end;
1893 // ////////////////////////////////////////////////////////////////////////// //
1894 // trace box with the given velocity; return object hit (if any)
1895 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
1896 function TBodyGridBase.traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
1897 var
1898 gx, gy: Integer;
1899 ccidx: Integer;
1900 cc: PGridCell;
1901 px: PBodyProxyRec;
1902 lq: LongWord;
1903 f, ptag: Integer;
1904 minu0: Single = 100000.0;
1905 u0: Single;
1906 cx0, cy0, cx1, cy1: Integer;
1907 hitpx: PBodyProxyRec = nil;
1908 begin
1909 result := Default(ITP);
1910 ex := ax0+dx;
1911 ey := ay0+dy;
1912 if (aw < 1) or (ah < 1) then exit;
1914 cx0 := nmin(ax0, ax0+dx);
1915 cy0 := nmin(ay0, ay0+dy);
1916 cx1 := nmax(ax0+aw-1, ax0+aw-1+dx);
1917 cy1 := nmax(ay0+ah-1, ay0+ah-1+dy);
1919 cx0 -= mMinX; cy0 -= mMinY;
1920 cx1 -= mMinX; cy1 -= mMinY;
1922 if (cx1 < 0) or (cy1 < 0) or (cx0 >= mWidth*mTileSize) or (cy0 >= mHeight*mTileSize) then exit;
1924 if (cx0 < 0) then cx0 := 0;
1925 if (cy0 < 0) then cy0 := 0;
1926 if (cx1 >= mWidth*mTileSize) then cx1 := mWidth*mTileSize-1;
1927 if (cy1 >= mHeight*mTileSize) then cy1 := mHeight*mTileSize-1;
1928 // just in case
1929 if (cx0 > cx1) or (cy0 > cy1) then exit;
1931 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1932 mInQuery := true;
1934 // increase query counter
1935 Inc(mLastQuery);
1936 if (mLastQuery = 0) then
1937 begin
1938 // just in case of overflow
1939 mLastQuery := 1;
1940 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1941 end;
1942 lq := mLastQuery;
1944 for gy := cy0 div mTileSize to cy1 div mTileSize do
1945 begin
1946 for gx := cx0 div mTileSize to cx1 div mTileSize do
1947 begin
1948 ccidx := mGrid[gy*mWidth+gx];
1949 while (ccidx <> -1) do
1950 begin
1951 cc := @mCells[ccidx];
1952 for f := 0 to GridCellBucketSize-1 do
1953 begin
1954 if (cc.bodies[f] = -1) then break;
1955 px := @mProxies[cc.bodies[f]];
1956 ptag := px.mTag;
1957 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1958 begin
1959 px.mQueryMark := lq; // mark as processed
1960 if assigned(cb) then
1961 begin
1962 if not cb(px.mObj, ptag) then continue;
1963 end;
1964 if not sweepAABB(ax0, ay0, aw, ah, dx, dy, px.mX, px.mY, px.mWidth, px.mHeight, @u0) then continue;
1965 if (minu0 > u0) then
1966 begin
1967 hitpx := px;
1968 result := px.mObj;
1969 minu0 := u0;
1970 if (u0 = 0.0) then
1971 begin
1972 ex := ax0;
1973 ey := ay0;
1974 mInQuery := false;
1975 exit;
1976 end;
1977 end;
1978 end;
1979 end;
1980 // next cell
1981 ccidx := cc.next;
1982 end;
1983 end;
1984 end;
1986 if (minu0 <= 1.0) then
1987 begin
1988 ex := ax0+round(dx*minu0);
1989 ey := ay0+round(dy*minu0);
1990 // just in case, compensate for floating point inexactness
1991 if (ex >= hitpx.mX) and (ey >= hitpx.mY) and (ex < hitpx.mX+hitpx.mWidth) and (ey < hitpx.mY+hitpx.mHeight) then
1992 begin
1993 ex := ax0+trunc(dx*minu0);
1994 ey := ay0+trunc(dy*minu0);
1995 end;
1996 end;
1998 mInQuery := false;
1999 end;
2002 // ////////////////////////////////////////////////////////////////////////// //
2003 {.$DEFINE D2F_DEBUG_OTR}
2004 function TBodyGridBase.traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
2005 var
2006 ccidx: Integer;
2007 cc: PGridCell;
2008 px: PBodyProxyRec;
2009 ptag: Integer;
2010 minx, miny: Integer;
2011 f, c0, c1: Integer;
2012 x0, y0, x1, y1: Integer;
2013 celly0, celly1: Integer;
2014 dy: Integer;
2015 filled: array[0..mTileSize-1] of Byte;
2016 {$IF DEFINED(D2F_DEBUG_OTR)}
2017 s: AnsiString = '';
2018 {$ENDIF}
2019 begin
2020 result := false;
2021 ex := ax1;
2022 ey := ay1;
2023 if not ((ax0 = ax1) or (ay0 = ay1)) then raise Exception.Create('orthoray is not orthogonal');
2025 tagmask := tagmask and TagFullMask;
2026 if (tagmask = 0) then exit;
2028 if (forEachAtPoint(ax0, ay0, nil, tagmask) = nil) then exit;
2030 minx := mMinX;
2031 miny := mMinY;
2033 // offset query coords to (0,0)-based
2034 x0 := ax0-minx;
2035 y0 := ay0-miny;
2036 x1 := ax1-minx;
2037 y1 := ay1-miny;
2039 if (x0 = x1) then
2040 begin
2041 if (x0 < 0) or (x0 >= mWidth*mTileSize) then exit; // oops
2042 // vertical
2043 if (y0 < y1) then
2044 begin
2045 // down
2046 if (y1 < 0) or (y0 >= mHeight*mTileSize) then exit;
2047 //if (ay0 < 0) then ay0 := 0;
2048 if (y0 < 0) then exit;
2049 if (y1 >= mHeight*mTileSize) then y1 := mHeight*mTileSize-1;
2050 dy := 1;
2051 end
2052 else
2053 begin
2054 // up
2055 if (y0 < 0) or (y1 >= mHeight*mTileSize) then exit;
2056 //if (ay1 < 0) then ay1 := 0;
2057 if (y1 < 0) then exit;
2058 if (y0 >= mHeight*mTileSize) then y0 := mHeight*mTileSize-1;
2059 dy := -1;
2060 end;
2061 // check tile
2062 while true do
2063 begin
2064 ccidx := mGrid[(y0 div mTileSize)*mWidth+(x0 div mTileSize)];
2065 FillChar(filled, sizeof(filled), 0);
2066 celly0 := y0 and (not (mTileSize-1));
2067 celly1 := celly0+mTileSize-1;
2068 while (ccidx <> -1) do
2069 begin
2070 cc := @mCells[ccidx];
2071 for f := 0 to GridCellBucketSize-1 do
2072 begin
2073 if (cc.bodies[f] = -1) then break;
2074 px := @mProxies[cc.bodies[f]];
2075 ptag := px.mTag;
2076 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
2077 (ax0 >= px.x0) and (ax0 <= px.x1) then
2078 begin
2079 // bound c0 and c1 to cell
2080 c0 := nclamp(px.y0-miny, celly0, celly1);
2081 c1 := nclamp(px.y1-miny, celly0, celly1);
2082 // fill the thing
2083 {$IF DEFINED(D2F_DEBUG_OTR)}
2084 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)]);
2085 {$ENDIF}
2086 //assert(c0 <= c1);
2087 FillChar(filled[c0-celly0], c1-c0+1, 1);
2088 end;
2089 end;
2090 // next cell
2091 ccidx := cc.next;
2092 end;
2093 {$IF DEFINED(D2F_DEBUG_OTR)}
2094 s := formatstrf(' x=%s; ay0=%s; ay1=%s; y0=%s; celly0=%s; celly1=%s; dy=%s; [', [ax0, ay0, ay1, y0, celly0, celly1, dy]);
2095 for f := 0 to High(filled) do if (filled[f] <> 0) then s += '1' else s += '0';
2096 s += ']';
2097 e_LogWriteln(s);
2098 {$ENDIF}
2099 // now go till we hit cell boundary or empty space
2100 if (dy < 0) then
2101 begin
2102 // up
2103 while (y0 >= celly0) and (filled[y0-celly0] <> 0) do
2104 begin
2105 {$IF DEFINED(D2F_DEBUG_OTR)}
2106 e_LogWritefln(' filled: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2107 {$ENDIF}
2108 Dec(y0);
2109 Dec(ay0);
2110 end;
2111 {$IF DEFINED(D2F_DEBUG_OTR)}
2112 e_LogWritefln(' span done: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2113 {$ENDIF}
2114 if (ay0 <= ay1) then begin ey := ay1; result := false; exit; end;
2115 if (y0 >= celly0) then begin ey := ay0+1; {assert(forEachAtPoint(ex, ey, nil, tagmask) <> nil);} result := true; exit; end;
2116 end
2117 else
2118 begin
2119 // down
2120 while (y0 <= celly1) and (filled[y0-celly0] <> 0) do begin Inc(y0); Inc(ay0); end;
2121 if (ay0 >= ay1) then begin ey := ay1; result := false; exit; end;
2122 if (y0 <= celly1) then begin ey := ay0-1; result := true; exit; end;
2123 end;
2124 end;
2125 end
2126 else
2127 begin
2128 // horizontal
2129 assert(false);
2130 end;
2131 end;
2134 // ////////////////////////////////////////////////////////////////////////// //
2135 function TBodyGridBase.traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2136 var
2137 ex, ey: Integer;
2138 begin
2139 result := traceRay(ex, ey, x0, y0, x1, y1, cb, tagmask);
2140 end;
2143 // no callback: return `true` on the nearest hit
2144 // you are not supposed to understand this
2145 function TBodyGridBase.traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2146 var
2147 lw, sweepw: TLineWalker;
2148 ccidx: Integer;
2149 cc: PGridCell;
2150 px: PBodyProxyRec;
2151 lq: LongWord;
2152 f, ptag: Integer;
2153 gw, gh, minx, miny: Integer;
2154 x0, y0: Integer;
2155 x1, y1: Integer;
2156 cx, cy: Integer;
2157 px0, py0, px1, py1: Integer;
2158 lastDistSq, distSq, hx, hy: Integer;
2159 firstCell: Boolean = true;
2160 wasHit: Boolean;
2161 begin
2162 result := Default(ITP);
2163 tagmask := tagmask and TagFullMask;
2164 if (tagmask = 0) then exit;
2166 gw := mWidth;
2167 gh := mHeight;
2168 minx := mMinX;
2169 miny := mMinY;
2171 // make query coords (0,0)-based
2172 x0 := ax0-minx;
2173 y0 := ay0-miny;
2174 x1 := ax1-minx;
2175 y1 := ay1-miny;
2177 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
2178 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
2180 sweepw := TLineWalker.Create(0, 0, 1, 1); // doesn't matter, just shut ups the compiler
2182 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
2184 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2185 mInQuery := true;
2187 // increase query counter
2188 Inc(mLastQuery);
2189 if (mLastQuery = 0) then
2190 begin
2191 // just in case of overflow
2192 mLastQuery := 1;
2193 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2194 end;
2195 lq := mLastQuery;
2197 repeat
2198 lw.getXY(cx, cy);
2199 // check tile
2200 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
2201 // process cells
2202 wasHit := false;
2203 while (ccidx <> -1) do
2204 begin
2205 cc := @mCells[ccidx];
2206 for f := 0 to GridCellBucketSize-1 do
2207 begin
2208 if (cc.bodies[f] = -1) then break;
2209 px := @mProxies[cc.bodies[f]];
2210 ptag := px.mTag;
2211 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2212 begin
2213 px.mQueryMark := lq; // mark as processed
2214 if assigned(cb) then
2215 begin
2216 if not cb(px.mObj, ptag) then continue;
2217 end;
2218 // get adjusted proxy coords
2219 px0 := px.mX-minx;
2220 py0 := px.mY-miny;
2221 px1 := px0+px.mWidth-1;
2222 py1 := py0+px.mHeight-1;
2223 // inside?
2224 if firstCell and (x0 >= px0) and (y0 >= py0) and (x0 <= px1) and (y0 <= py1) then
2225 begin
2226 // oops
2227 ex := ax0;
2228 ey := ay0;
2229 result := px.mObj;
2230 mInQuery := false;
2231 exit;
2232 end;
2233 // do line-vs-aabb test
2234 sweepw.setClip(px0, py0, px1, py1);
2235 if sweepw.setup(x0, y0, x1, y1) then
2236 begin
2237 // hit detected
2238 sweepw.getPrevXY(hx, hy);
2239 distSq := distanceSq(x0, y0, hx, hy);
2240 if (distSq < lastDistSq) then
2241 begin
2242 lastDistSq := distSq;
2243 ex := hx+minx;
2244 ey := hy+miny;
2245 result := px.mObj;
2246 // if this is not a first cell, get outta here
2247 if not firstCell then begin mInQuery := false; exit; end;
2248 wasHit := true;
2249 end;
2250 end;
2251 end;
2252 end;
2253 // next cell
2254 ccidx := cc.next;
2255 end;
2256 // done processing cells; exit if we registered a hit
2257 // next cells can't have better candidates, obviously
2258 if wasHit then begin mInQuery := false; exit; end;
2259 firstCell := false;
2260 // move to next tile
2261 until lw.stepToNextTile();
2263 mInQuery := false;
2264 end;
2267 // ////////////////////////////////////////////////////////////////////////// //
2268 // no callback: return `true` on the nearest hit
2269 function TBodyGridBase.traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2270 var
2271 ex, ey: Integer;
2272 begin
2273 result := traceRayOld(ex, ey, x0, y0, x1, y1, cb, tagmask);
2274 end;
2277 // no callback: return `true` on the nearest hit
2278 // you are not supposed to understand this
2279 function TBodyGridBase.traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2280 var
2281 wx0, wy0, wx1, wy1: Integer; // window coordinates
2282 stx, sty: Integer; // "steps" for x and y axes
2283 dsx, dsy: Integer; // "lengthes" for x and y axes
2284 dx2, dy2: Integer; // "double lengthes" for x and y axes
2285 xd, yd: Integer; // current coord
2286 e: Integer; // "error" (as in bresenham algo)
2287 rem: Integer;
2288 term: Integer;
2289 xptr, yptr: PInteger;
2290 xfixed: Boolean;
2291 temp: Integer;
2292 prevx, prevy: Integer;
2293 lastDistSq: Integer;
2294 ccidx, curci: Integer;
2295 hasUntried: Boolean;
2296 lastGA: Integer = -1;
2297 ga, x, y: Integer;
2298 lastObj: ITP;
2299 wasHit: Boolean = false;
2300 gw, gh, minx, miny, maxx, maxy: Integer;
2301 cc: PGridCell;
2302 px: PBodyProxyRec;
2303 lq: LongWord;
2304 f, ptag, distSq: Integer;
2305 x0, y0, x1, y1: Integer;
2306 //swapped: Boolean = false; // true: xd is yd, and vice versa
2307 // horizontal walker
2308 {$IFDEF GRID_USE_ORTHO_ACCEL}
2309 wklen, wkstep: Integer;
2310 //wksign: Integer;
2311 hopt: Boolean;
2312 {$ENDIF}
2313 // skipper
2314 xdist, ydist: Integer;
2315 begin
2316 result := Default(ITP);
2317 lastObj := Default(ITP);
2318 tagmask := tagmask and TagFullMask;
2319 ex := ax1; // why not?
2320 ey := ay1; // why not?
2321 if (tagmask = 0) then exit;
2323 if (ax0 = ax1) and (ay0 = ay1) then
2324 begin
2325 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2326 if (result <> nil) then
2327 begin
2328 if assigned(cb) and not cb(result, ptag, ax0, ay0, ax0, ay0) then result := Default(ITP);
2329 end;
2330 exit;
2331 end;
2333 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
2335 gw := mWidth;
2336 gh := mHeight;
2337 minx := mMinX;
2338 miny := mMinY;
2339 maxx := gw*mTileSize-1;
2340 maxy := gh*mTileSize-1;
2342 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2343 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);
2344 {$ENDIF}
2346 x0 := ax0;
2347 y0 := ay0;
2348 x1 := ax1;
2349 y1 := ay1;
2351 // offset query coords to (0,0)-based
2352 Dec(x0, minx);
2353 Dec(y0, miny);
2354 Dec(x1, minx);
2355 Dec(y1, miny);
2357 // clip rectange
2358 wx0 := 0;
2359 wy0 := 0;
2360 wx1 := maxx;
2361 wy1 := maxy;
2363 // horizontal setup
2364 if (x0 < x1) then
2365 begin
2366 // from left to right
2367 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
2368 stx := 1; // going right
2369 end
2370 else
2371 begin
2372 // from right to left
2373 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
2374 stx := -1; // going left
2375 x0 := -x0;
2376 x1 := -x1;
2377 wx0 := -wx0;
2378 wx1 := -wx1;
2379 swapInt(wx0, wx1);
2380 end;
2382 // vertical setup
2383 if (y0 < y1) then
2384 begin
2385 // from top to bottom
2386 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
2387 sty := 1; // going down
2388 end
2389 else
2390 begin
2391 // from bottom to top
2392 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
2393 sty := -1; // going up
2394 y0 := -y0;
2395 y1 := -y1;
2396 wy0 := -wy0;
2397 wy1 := -wy1;
2398 swapInt(wy0, wy1);
2399 end;
2401 dsx := x1-x0;
2402 dsy := y1-y0;
2404 if (dsx < dsy) then
2405 begin
2406 //swapped := true;
2407 xptr := @yd;
2408 yptr := @xd;
2409 swapInt(x0, y0);
2410 swapInt(x1, y1);
2411 swapInt(dsx, dsy);
2412 swapInt(wx0, wy0);
2413 swapInt(wx1, wy1);
2414 swapInt(stx, sty);
2415 end
2416 else
2417 begin
2418 xptr := @xd;
2419 yptr := @yd;
2420 end;
2422 dx2 := 2*dsx;
2423 dy2 := 2*dsy;
2424 xd := x0;
2425 yd := y0;
2426 e := 2*dsy-dsx;
2427 term := x1;
2429 xfixed := false;
2430 if (y0 < wy0) then
2431 begin
2432 // clip at top
2433 temp := dx2*(wy0-y0)-dsx;
2434 xd += temp div dy2;
2435 rem := temp mod dy2;
2436 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
2437 if (xd+1 >= wx0) then
2438 begin
2439 yd := wy0;
2440 e -= rem+dsx;
2441 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
2442 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
2443 xfixed := true;
2444 end;
2445 end;
2447 if (not xfixed) and (x0 < wx0) then
2448 begin
2449 // clip at left
2450 temp := dy2*(wx0-x0);
2451 yd += temp div dx2;
2452 rem := temp mod dx2;
2453 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
2454 xd := wx0;
2455 e += rem;
2456 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
2457 end;
2459 if (y1 > wy1) then
2460 begin
2461 // clip at bottom
2462 temp := dx2*(wy1-y0)+dsx;
2463 term := x0+temp div dy2;
2464 rem := temp mod dy2;
2465 if (rem = 0) then Dec(term);
2466 end;
2468 if (term > wx1) then term := wx1; // clip at right
2470 Inc(term); // draw last point
2471 //if (term = xd) then exit; // this is the only point, get out of here
2473 if (sty = -1) then yd := -yd;
2474 if (stx = -1) then begin xd := -xd; term := -term; end;
2475 dx2 -= dy2;
2477 // first move, to skip starting point
2478 // DON'T DO THIS! loop will take care of that
2479 if (xd = term) then
2480 begin
2481 //FIXME!
2482 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2483 if (result <> nil) then
2484 begin
2485 if assigned(cb) then
2486 begin
2487 if cb(result, ptag, ax0, ay0, ax0, ay0) then
2488 begin
2489 ex := ax0;
2490 ey := ay0;
2491 end
2492 else
2493 begin
2494 result := nil;
2495 end;
2496 end
2497 else
2498 begin
2499 ex := ax0;
2500 ey := ay0;
2501 end;
2502 end;
2503 exit;
2504 end;
2506 prevx := xptr^+minx;
2507 prevy := yptr^+miny;
2508 (*
2509 // move coords
2510 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2511 xd += stx;
2512 // done?
2513 if (xd = term) then exit;
2514 *)
2516 {$IF DEFINED(D2F_DEBUG)}
2517 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2518 {$ENDIF}
2519 // DON'T DO THIS! loop will take care of that
2520 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
2521 //ccidx := mGrid[lastGA];
2523 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2524 //if assigned(dbgRayTraceTileHitCB) then e_WriteLog('1:TRACING!', MSG_NOTIFY);
2525 {$ENDIF}
2527 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
2529 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2530 mInQuery := true;
2532 // increase query counter
2533 Inc(mLastQuery);
2534 if (mLastQuery = 0) then
2535 begin
2536 // just in case of overflow
2537 mLastQuery := 1;
2538 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2539 end;
2540 lq := mLastQuery;
2542 {$IFDEF GRID_USE_ORTHO_ACCEL}
2543 // if this is strict horizontal/vertical trace, use optimized codepath
2544 if (ax0 = ax1) or (ay0 = ay1) then
2545 begin
2546 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
2547 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
2548 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
2549 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
2550 hopt := (ay0 = ay1); // horizontal?
2551 if (stx < 0) then begin {wksign := -1;} wklen := -(term-xd); end else begin {wksign := 1;} wklen := term-xd; end;
2552 {$IF DEFINED(D2F_DEBUG)}
2553 if dbgShowTraceLog then e_LogWritefln('optimized htrace; wklen=%d', [wklen]);
2554 {$ENDIF}
2555 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2556 // one of those will never change
2557 x := xptr^+minx;
2558 y := yptr^+miny;
2559 while (wklen > 0) do
2560 begin
2561 {$IF DEFINED(D2F_DEBUG)}
2562 if dbgShowTraceLog then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; y=%d; y=%d', [ga, xptr^+minx, yptr^+miny, y, ay0]);
2563 {$ENDIF}
2564 // new tile?
2565 if (ga <> lastGA) then
2566 begin
2567 lastGA := ga;
2568 ccidx := mGrid[lastGA];
2569 // convert coords to map (to avoid ajdusting coords inside the loop)
2570 if hopt then x := xptr^+minx else y := yptr^+miny;
2571 while (ccidx <> -1) do
2572 begin
2573 cc := @mCells[ccidx];
2574 for f := 0 to GridCellBucketSize-1 do
2575 begin
2576 if (cc.bodies[f] = -1) then break;
2577 px := @mProxies[cc.bodies[f]];
2578 ptag := px.mTag;
2579 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) and
2580 // constant coord should be inside
2581 ((hopt and (y >= px.y0) and (y <= px.y1)) or
2582 ((not hopt) and (x >= px.x0) and (x <= px.x1))) then
2583 begin
2584 px.mQueryMark := lq; // mark as processed
2585 // inside the proxy?
2586 if (hopt and (x > px.x0) and (x < px.x1)) or
2587 ((not hopt) and (y > px.y0) and (y < px.y1)) then
2588 begin
2589 // setup prev[xy]
2590 if assigned(cb) then
2591 begin
2592 if cb(px.mObj, ptag, x, y, x, y) then
2593 begin
2594 result := px.mObj;
2595 ex := x;
2596 ey := y;
2597 mInQuery := false;
2598 exit;
2599 end;
2600 end
2601 else
2602 begin
2603 distSq := distanceSq(ax0, ay0, x, y);
2604 {$IF DEFINED(D2F_DEBUG)}
2605 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]);
2606 {$ENDIF}
2607 if (distSq < lastDistSq) then
2608 begin
2609 ex := x;
2610 ey := y;
2611 result := px.mObj;
2612 mInQuery := false;
2613 exit;
2614 end;
2615 end;
2616 continue;
2617 end;
2618 // remember this hitpoint if it is nearer than an old one
2619 // setup prev[xy]
2620 if hopt then
2621 begin
2622 // horizontal trace
2623 prevy := y;
2624 y := yptr^+miny;
2625 if (stx < 0) then
2626 begin
2627 // going left
2628 if (x < px.x1) then continue; // not on the right edge
2629 x := px.x1;
2630 prevx := x+1;
2631 end
2632 else
2633 begin
2634 // going right
2635 if (x > px.x0) then continue; // not on the left edge
2636 x := px.x0;
2637 prevx := x-1;
2638 end;
2639 end
2640 else
2641 begin
2642 // vertical trace
2643 prevx := x;
2644 x := xptr^+minx;
2645 if (stx < 0) then
2646 begin
2647 // going up
2648 if (y < px.y1) then continue; // not on the bottom edge
2649 y := px.y1;
2650 prevy := x+1;
2651 end
2652 else
2653 begin
2654 // going down
2655 if (y > px.y0) then continue; // not on the top edge
2656 y := px.y0;
2657 prevy := y-1;
2658 end;
2659 end;
2660 if assigned(cb) then
2661 begin
2662 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2663 begin
2664 result := px.mObj;
2665 ex := prevx;
2666 ey := prevy;
2667 mInQuery := false;
2668 exit;
2669 end;
2670 end
2671 else
2672 begin
2673 distSq := distanceSq(ax0, ay0, prevx, prevy);
2674 {$IF DEFINED(D2F_DEBUG)}
2675 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]);
2676 {$ENDIF}
2677 if (distSq < lastDistSq) then
2678 begin
2679 wasHit := true;
2680 lastDistSq := distSq;
2681 ex := prevx;
2682 ey := prevy;
2683 lastObj := px.mObj;
2684 end;
2685 end;
2686 end;
2687 end;
2688 // next cell
2689 ccidx := cc.next;
2690 end;
2691 if wasHit and not assigned(cb) then begin result := lastObj; mInQuery := false; exit; end;
2692 if assigned(cb) and cb(nil, 0, x, y, x, y) then begin result := lastObj; mInQuery := false; exit; end;
2693 end;
2694 // skip to next tile
2695 if hopt then
2696 begin
2697 if (stx > 0) then
2698 begin
2699 // to the right
2700 wkstep := ((xptr^ or (mTileSize-1))+1)-xptr^;
2701 {$IF DEFINED(D2F_DEBUG)}
2702 if dbgShowTraceLog then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2703 {$ENDIF}
2704 if (wkstep >= wklen) then break;
2705 Inc(xptr^, wkstep);
2706 Inc(ga);
2707 end
2708 else
2709 begin
2710 // to the left
2711 wkstep := xptr^-((xptr^ and (not (mTileSize-1)))-1);
2712 {$IF DEFINED(D2F_DEBUG)}
2713 if dbgShowTraceLog then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2714 {$ENDIF}
2715 if (wkstep >= wklen) then break;
2716 Dec(xptr^, wkstep);
2717 Dec(ga);
2718 end;
2719 end
2720 else
2721 begin
2722 if (stx > 0) then
2723 begin
2724 // to the down
2725 wkstep := ((yptr^ or (mTileSize-1))+1)-yptr^;
2726 {$IF DEFINED(D2F_DEBUG)}
2727 if dbgShowTraceLog then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2728 {$ENDIF}
2729 if (wkstep >= wklen) then break;
2730 Inc(yptr^, wkstep);
2731 Inc(ga, mWidth);
2732 end
2733 else
2734 begin
2735 // to the up
2736 wkstep := yptr^-((yptr^ and (not (mTileSize-1)))-1);
2737 {$IF DEFINED(D2F_DEBUG)}
2738 if dbgShowTraceLog then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2739 {$ENDIF}
2740 if (wkstep >= wklen) then break;
2741 Dec(yptr^, wkstep);
2742 Dec(ga, mWidth);
2743 end;
2744 end;
2745 Dec(wklen, wkstep);
2746 end;
2747 // we can travel less than one cell
2748 if wasHit and not assigned(cb) then result := lastObj else begin ex := ax1; ey := ay1; end;
2749 mInQuery := false;
2750 exit;
2751 end;
2752 {$ENDIF}
2754 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2755 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2756 {$ENDIF}
2758 //e_LogWritefln('*********************', []);
2759 ccidx := -1;
2760 // can omit checks
2761 while (xd <> term) do
2762 begin
2763 // check cell(s)
2764 {$IF DEFINED(D2F_DEBUG)}
2765 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2766 {$ENDIF}
2767 // new tile?
2768 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2769 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2770 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);
2771 {$ENDIF}
2772 if (ga <> lastGA) then
2773 begin
2774 // yes
2775 {$IF DEFINED(D2F_DEBUG)}
2776 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2777 {$ENDIF}
2778 if (ccidx <> -1) then
2779 begin
2780 // signal cell completion
2781 if assigned(cb) then
2782 begin
2783 if cb(nil, 0, xptr^+minx, yptr^+miny, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2784 end
2785 else if wasHit then
2786 begin
2787 result := lastObj;
2788 mInQuery := false;
2789 exit;
2790 end;
2791 end;
2792 lastGA := ga;
2793 ccidx := mGrid[lastGA];
2794 end;
2795 // has something to process in this tile?
2796 if (ccidx <> -1) then
2797 begin
2798 // process cell
2799 curci := ccidx;
2800 hasUntried := false; // this will be set to `true` if we have some proxies we still want to process at the next step
2801 // convert coords to map (to avoid ajdusting coords inside the loop)
2802 x := xptr^+minx;
2803 y := yptr^+miny;
2804 // process cell list
2805 while (curci <> -1) do
2806 begin
2807 cc := @mCells[curci];
2808 for f := 0 to GridCellBucketSize-1 do
2809 begin
2810 if (cc.bodies[f] = -1) then break;
2811 px := @mProxies[cc.bodies[f]];
2812 ptag := px.mTag;
2813 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2814 begin
2815 // can we process this proxy?
2816 if (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
2817 begin
2818 px.mQueryMark := lq; // mark as processed
2819 if assigned(cb) then
2820 begin
2821 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2822 begin
2823 result := px.mObj;
2824 ex := prevx;
2825 ey := prevy;
2826 mInQuery := false;
2827 exit;
2828 end;
2829 end
2830 else
2831 begin
2832 // remember this hitpoint if it is nearer than an old one
2833 distSq := distanceSq(ax0, ay0, prevx, prevy);
2834 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2835 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);
2836 {$ENDIF}
2837 if (distSq < lastDistSq) then
2838 begin
2839 wasHit := true;
2840 lastDistSq := distSq;
2841 ex := prevx;
2842 ey := prevy;
2843 lastObj := px.mObj;
2844 end;
2845 end;
2846 end
2847 else
2848 begin
2849 // this is possibly interesting proxy, set "has more to check" flag
2850 hasUntried := true;
2851 end;
2852 end;
2853 end;
2854 // next cell
2855 curci := cc.next;
2856 end;
2857 // still has something interesting in this cell?
2858 if not hasUntried then
2859 begin
2860 // nope, don't process this cell anymore; signal cell completion
2861 ccidx := -1;
2862 if assigned(cb) then
2863 begin
2864 if cb(nil, 0, x, y, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2865 end
2866 else if wasHit then
2867 begin
2868 result := lastObj;
2869 mInQuery := false;
2870 exit;
2871 end;
2872 end;
2873 end;
2874 if (ccidx = -1) then
2875 begin
2876 // move to cell edge, as we have nothing to trace here anymore
2877 if (stx < 0) then xdist := xd and (not (mTileSize-1)) else xdist := xd or (mTileSize-1);
2878 if (sty < 0) then ydist := yd and (not (mTileSize-1)) else ydist := yd or (mTileSize-1);
2879 //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]);
2880 while (xd <> xdist) and (yd <> ydist) do
2881 begin
2882 // step
2883 xd += stx;
2884 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2885 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
2886 if (xd = term) then break;
2887 end;
2888 //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]);
2889 if (xd = term) then break;
2890 end;
2891 //putPixel(xptr^, yptr^);
2892 // move coords
2893 prevx := xptr^+minx;
2894 prevy := yptr^+miny;
2895 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2896 xd += stx;
2897 end;
2898 // we can travel less than one cell
2899 if wasHit and not assigned(cb) then
2900 begin
2901 result := lastObj;
2902 end
2903 else
2904 begin
2905 ex := ax1; // why not?
2906 ey := ay1; // why not?
2907 end;
2909 mInQuery := false;
2910 end;
2913 end.