DEADSOFTWARE

don't be *too* smart: `swapInt()` should not do xor trick, 'cause we may pass the...
[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 sx, sy, ex, ey: Integer;
1726 curci: Integer;
1727 f: Integer;
1728 cc: PGridCell = nil;
1729 px: PBodyProxyRec;
1730 lq: LongWord;
1731 gw, gh: Integer;
1732 x0, y0: Integer;
1733 ptag: Integer;
1734 begin
1735 result := Default(ITP);
1736 if (w < 1) or (h < 1) then exit;
1737 tagmask := tagmask and TagFullMask;
1738 if (tagmask = 0) then exit;
1740 x0 := x;
1741 y0 := y;
1743 // fix coords
1744 Dec(x, mMinX);
1745 Dec(y, mMinY);
1747 gw := mWidth;
1748 gh := mHeight;
1750 if (x+w <= 0) or (y+h <= 0) then exit;
1751 if (x >= gw*mTileSize) or (y >= gh*mTileSize) then exit;
1753 sx := x div mTileSize;
1754 sy := y div mTileSize;
1755 ex := (x+w-1) div mTileSize;
1756 ey := (y+h-1) div mTileSize;
1758 // clip rect
1759 if (sx < 0) then sx := 0 else if (sx >= gw) then sx := gw-1;
1760 if (sy < 0) then sy := 0 else if (sy >= gh) then sy := gh-1;
1761 if (ex < 0) then ex := 0 else if (ex >= gw) then ex := gw-1;
1762 if (ey < 0) then ey := 0 else if (ey >= gh) then ey := gh-1;
1763 if (sx > ex) or (sy > ey) then exit; // just in case
1765 // has something to do
1766 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1767 mInQuery := true;
1769 // increase query counter
1770 Inc(mLastQuery);
1771 if (mLastQuery = 0) then
1772 begin
1773 // just in case of overflow
1774 mLastQuery := 1;
1775 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1776 end;
1777 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
1778 lq := mLastQuery;
1780 // go on
1781 for gy := sy to ey do
1782 begin
1783 for gx := sx to ex do
1784 begin
1785 // process cells
1786 curci := mGrid[gy*gw+gx];
1787 while (curci <> -1) do
1788 begin
1789 cc := @mCells[curci];
1790 for f := 0 to GridCellBucketSize-1 do
1791 begin
1792 if (cc.bodies[f] = -1) then break;
1793 px := @mProxies[cc.bodies[f]];
1794 // shit! has to do it this way, so i can change tag in callback
1795 if (px.mQueryMark = lq) then continue;
1796 px.mQueryMark := lq;
1797 ptag := px.mTag;
1798 if (not allowDisabled) and ((ptag and TagDisabled) <> 0) then continue;
1799 if ((ptag and tagmask) = 0) then continue;
1800 if (x0 >= px.mX+px.mWidth) or (y0 >= px.mY+px.mHeight) then continue;
1801 if (x0+w <= px.mX) or (y0+h <= px.mY) then continue;
1802 if assigned(cb) then
1803 begin
1804 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
1805 end
1806 else
1807 begin
1808 result := px.mObj;
1809 mInQuery := false;
1810 exit;
1811 end;
1812 end;
1813 curci := cc.next;
1814 end;
1815 end;
1816 end;
1818 mInQuery := false;
1819 end;
1822 // ////////////////////////////////////////////////////////////////////////// //
1823 function TBodyGridBase.forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
1824 var
1825 lw: TLineWalker;
1826 ccidx: Integer;
1827 cc: PGridCell;
1828 px: PBodyProxyRec;
1829 lq: LongWord;
1830 f, ptag: Integer;
1831 gw, gh, minx, miny: Integer;
1832 x0, y0: Integer;
1833 x1, y1: Integer;
1834 cx, cy: Integer;
1835 //px0, py0, px1, py1: Integer;
1836 begin
1837 log := false;
1838 result := Default(ITP);
1839 tagmask := tagmask and TagFullMask;
1840 if (tagmask = 0) or not assigned(cb) then exit;
1842 gw := mWidth;
1843 gh := mHeight;
1844 minx := mMinX;
1845 miny := mMinY;
1847 // make query coords (0,0)-based
1848 x0 := ax0-minx;
1849 y0 := ay0-miny;
1850 x1 := ax1-minx;
1851 y1 := ay1-miny;
1853 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
1854 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
1856 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1857 mInQuery := true;
1859 // increase query counter
1860 Inc(mLastQuery);
1861 if (mLastQuery = 0) then
1862 begin
1863 // just in case of overflow
1864 mLastQuery := 1;
1865 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1866 end;
1867 lq := mLastQuery;
1869 repeat
1870 lw.getXY(cx, cy);
1871 // check tile
1872 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
1873 // process cells
1874 while (ccidx <> -1) do
1875 begin
1876 cc := @mCells[ccidx];
1877 for f := 0 to GridCellBucketSize-1 do
1878 begin
1879 if (cc.bodies[f] = -1) then break;
1880 px := @mProxies[cc.bodies[f]];
1881 ptag := px.mTag;
1882 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1883 begin
1884 px.mQueryMark := lq; // mark as processed
1885 if cb(px.mObj, ptag) then
1886 begin
1887 result := px.mObj;
1888 mInQuery := false;
1889 exit;
1890 end;
1891 end;
1892 end;
1893 // next cell
1894 ccidx := cc.next;
1895 end;
1896 // done processing cells, move to next tile
1897 until lw.stepToNextTile();
1899 mInQuery := false;
1900 end;
1903 // ////////////////////////////////////////////////////////////////////////// //
1904 // trace box with the given velocity; return object hit (if any)
1905 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
1906 function TBodyGridBase.traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
1907 var
1908 gx, gy: Integer;
1909 ccidx: Integer;
1910 cc: PGridCell;
1911 px: PBodyProxyRec;
1912 lq: LongWord;
1913 f, ptag: Integer;
1914 minu0: Single = 100000.0;
1915 u0: Single;
1916 cx0, cy0, cx1, cy1: Integer;
1917 hitpx: PBodyProxyRec = nil;
1918 begin
1919 result := Default(ITP);
1920 ex := ax0+dx;
1921 ey := ay0+dy;
1922 if (aw < 1) or (ah < 1) then exit;
1924 cx0 := nmin(ax0, ax0+dx);
1925 cy0 := nmin(ay0, ay0+dy);
1926 cx1 := nmax(ax0+aw-1, ax0+aw-1+dx);
1927 cy1 := nmax(ay0+ah-1, ay0+ah-1+dy);
1929 cx0 -= mMinX; cy0 -= mMinY;
1930 cx1 -= mMinX; cy1 -= mMinY;
1932 if (cx1 < 0) or (cy1 < 0) or (cx0 >= mWidth*mTileSize) or (cy0 >= mHeight*mTileSize) then exit;
1934 if (cx0 < 0) then cx0 := 0;
1935 if (cy0 < 0) then cy0 := 0;
1936 if (cx1 >= mWidth*mTileSize) then cx1 := mWidth*mTileSize-1;
1937 if (cy1 >= mHeight*mTileSize) then cy1 := mHeight*mTileSize-1;
1938 // just in case
1939 if (cx0 > cx1) or (cy0 > cy1) then exit;
1941 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1942 mInQuery := true;
1944 // increase query counter
1945 Inc(mLastQuery);
1946 if (mLastQuery = 0) then
1947 begin
1948 // just in case of overflow
1949 mLastQuery := 1;
1950 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1951 end;
1952 lq := mLastQuery;
1954 for gy := cy0 div mTileSize to cy1 div mTileSize do
1955 begin
1956 for gx := cx0 div mTileSize to cx1 div mTileSize do
1957 begin
1958 ccidx := mGrid[gy*mWidth+gx];
1959 while (ccidx <> -1) do
1960 begin
1961 cc := @mCells[ccidx];
1962 for f := 0 to GridCellBucketSize-1 do
1963 begin
1964 if (cc.bodies[f] = -1) then break;
1965 px := @mProxies[cc.bodies[f]];
1966 ptag := px.mTag;
1967 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1968 begin
1969 px.mQueryMark := lq; // mark as processed
1970 if assigned(cb) then
1971 begin
1972 if not cb(px.mObj, ptag) then continue;
1973 end;
1974 if not sweepAABB(ax0, ay0, aw, ah, dx, dy, px.mX, px.mY, px.mWidth, px.mHeight, @u0) then continue;
1975 if (minu0 > u0) then
1976 begin
1977 hitpx := px;
1978 result := px.mObj;
1979 minu0 := u0;
1980 if (u0 = 0.0) then
1981 begin
1982 ex := ax0;
1983 ey := ay0;
1984 mInQuery := false;
1985 exit;
1986 end;
1987 end;
1988 end;
1989 end;
1990 // next cell
1991 ccidx := cc.next;
1992 end;
1993 end;
1994 end;
1996 if (minu0 <= 1.0) then
1997 begin
1998 ex := ax0+round(dx*minu0);
1999 ey := ay0+round(dy*minu0);
2000 // just in case, compensate for floating point inexactness
2001 if (ex >= hitpx.mX) and (ey >= hitpx.mY) and (ex < hitpx.mX+hitpx.mWidth) and (ey < hitpx.mY+hitpx.mHeight) then
2002 begin
2003 ex := ax0+trunc(dx*minu0);
2004 ey := ay0+trunc(dy*minu0);
2005 end;
2006 end;
2008 mInQuery := false;
2009 end;
2012 // ////////////////////////////////////////////////////////////////////////// //
2013 {.$DEFINE D2F_DEBUG_OTR}
2014 function TBodyGridBase.traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
2015 var
2016 ccidx: Integer;
2017 cc: PGridCell;
2018 px: PBodyProxyRec;
2019 ptag: Integer;
2020 minx, miny: Integer;
2021 f, c0, c1: Integer;
2022 x0, y0, x1, y1: Integer;
2023 celly0, celly1: Integer;
2024 dy: Integer;
2025 filled: array[0..mTileSize-1] of Byte;
2026 {$IF DEFINED(D2F_DEBUG_OTR)}
2027 s: AnsiString = '';
2028 {$ENDIF}
2029 begin
2030 result := false;
2031 ex := ax1;
2032 ey := ay1;
2033 if not ((ax0 = ax1) or (ay0 = ay1)) then raise Exception.Create('orthoray is not orthogonal');
2035 tagmask := tagmask and TagFullMask;
2036 if (tagmask = 0) then exit;
2038 if (forEachAtPoint(ax0, ay0, nil, tagmask) = nil) then exit;
2040 minx := mMinX;
2041 miny := mMinY;
2043 // offset query coords to (0,0)-based
2044 x0 := ax0-minx;
2045 y0 := ay0-miny;
2046 x1 := ax1-minx;
2047 y1 := ay1-miny;
2049 if (x0 = x1) then
2050 begin
2051 if (x0 < 0) or (x0 >= mWidth*mTileSize) then exit; // oops
2052 // vertical
2053 if (y0 < y1) then
2054 begin
2055 // down
2056 if (y1 < 0) or (y0 >= mHeight*mTileSize) then exit;
2057 //if (ay0 < 0) then ay0 := 0;
2058 if (y0 < 0) then exit;
2059 if (y1 >= mHeight*mTileSize) then y1 := mHeight*mTileSize-1;
2060 dy := 1;
2061 end
2062 else
2063 begin
2064 // up
2065 if (y0 < 0) or (y1 >= mHeight*mTileSize) then exit;
2066 //if (ay1 < 0) then ay1 := 0;
2067 if (y1 < 0) then exit;
2068 if (y0 >= mHeight*mTileSize) then y0 := mHeight*mTileSize-1;
2069 dy := -1;
2070 end;
2071 // check tile
2072 while true do
2073 begin
2074 ccidx := mGrid[(y0 div mTileSize)*mWidth+(x0 div mTileSize)];
2075 FillChar(filled, sizeof(filled), 0);
2076 celly0 := y0 and (not (mTileSize-1));
2077 celly1 := celly0+mTileSize-1;
2078 while (ccidx <> -1) do
2079 begin
2080 cc := @mCells[ccidx];
2081 for f := 0 to GridCellBucketSize-1 do
2082 begin
2083 if (cc.bodies[f] = -1) then break;
2084 px := @mProxies[cc.bodies[f]];
2085 ptag := px.mTag;
2086 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
2087 (ax0 >= px.x0) and (ax0 <= px.x1) then
2088 begin
2089 // bound c0 and c1 to cell
2090 c0 := nclamp(px.y0-miny, celly0, celly1);
2091 c1 := nclamp(px.y1-miny, celly0, celly1);
2092 // fill the thing
2093 {$IF DEFINED(D2F_DEBUG_OTR)}
2094 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)]);
2095 {$ENDIF}
2096 //assert(c0 <= c1);
2097 FillChar(filled[c0-celly0], c1-c0+1, 1);
2098 end;
2099 end;
2100 // next cell
2101 ccidx := cc.next;
2102 end;
2103 {$IF DEFINED(D2F_DEBUG_OTR)}
2104 s := formatstrf(' x=%s; ay0=%s; ay1=%s; y0=%s; celly0=%s; celly1=%s; dy=%s; [', [ax0, ay0, ay1, y0, celly0, celly1, dy]);
2105 for f := 0 to High(filled) do if (filled[f] <> 0) then s += '1' else s += '0';
2106 s += ']';
2107 e_LogWriteln(s);
2108 {$ENDIF}
2109 // now go till we hit cell boundary or empty space
2110 if (dy < 0) then
2111 begin
2112 // up
2113 while (y0 >= celly0) and (filled[y0-celly0] <> 0) do
2114 begin
2115 {$IF DEFINED(D2F_DEBUG_OTR)}
2116 e_LogWritefln(' filled: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2117 {$ENDIF}
2118 Dec(y0);
2119 Dec(ay0);
2120 end;
2121 {$IF DEFINED(D2F_DEBUG_OTR)}
2122 e_LogWritefln(' span done: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2123 {$ENDIF}
2124 if (ay0 <= ay1) then begin ey := ay1; result := false; exit; end;
2125 if (y0 >= celly0) then begin ey := ay0+1; {assert(forEachAtPoint(ex, ey, nil, tagmask) <> nil);} result := true; exit; end;
2126 end
2127 else
2128 begin
2129 // down
2130 while (y0 <= celly1) and (filled[y0-celly0] <> 0) do begin Inc(y0); Inc(ay0); end;
2131 if (ay0 >= ay1) then begin ey := ay1; result := false; exit; end;
2132 if (y0 <= celly1) then begin ey := ay0-1; result := true; exit; end;
2133 end;
2134 end;
2135 end
2136 else
2137 begin
2138 // horizontal
2139 assert(false);
2140 end;
2141 end;
2144 // ////////////////////////////////////////////////////////////////////////// //
2145 function TBodyGridBase.traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2146 var
2147 ex, ey: Integer;
2148 begin
2149 result := traceRay(ex, ey, x0, y0, x1, y1, cb, tagmask);
2150 end;
2153 // no callback: return `true` on the nearest hit
2154 // you are not supposed to understand this
2155 function TBodyGridBase.traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2156 var
2157 lw, sweepw: TLineWalker;
2158 ccidx: Integer;
2159 cc: PGridCell;
2160 px: PBodyProxyRec;
2161 lq: LongWord;
2162 f, ptag: Integer;
2163 gw, gh, minx, miny: Integer;
2164 x0, y0: Integer;
2165 x1, y1: Integer;
2166 cx, cy: Integer;
2167 px0, py0, px1, py1: Integer;
2168 lastDistSq, distSq, hx, hy: Integer;
2169 firstCell: Boolean = true;
2170 wasHit: Boolean;
2171 begin
2172 result := Default(ITP);
2173 tagmask := tagmask and TagFullMask;
2174 if (tagmask = 0) then exit;
2176 gw := mWidth;
2177 gh := mHeight;
2178 minx := mMinX;
2179 miny := mMinY;
2181 // make query coords (0,0)-based
2182 x0 := ax0-minx;
2183 y0 := ay0-miny;
2184 x1 := ax1-minx;
2185 y1 := ay1-miny;
2187 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
2188 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
2190 sweepw := TLineWalker.Create(0, 0, 1, 1); // doesn't matter, just shut ups the compiler
2192 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
2194 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2195 mInQuery := true;
2197 // increase query counter
2198 Inc(mLastQuery);
2199 if (mLastQuery = 0) then
2200 begin
2201 // just in case of overflow
2202 mLastQuery := 1;
2203 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2204 end;
2205 lq := mLastQuery;
2207 repeat
2208 lw.getXY(cx, cy);
2209 // check tile
2210 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
2211 // process cells
2212 wasHit := false;
2213 while (ccidx <> -1) do
2214 begin
2215 cc := @mCells[ccidx];
2216 for f := 0 to GridCellBucketSize-1 do
2217 begin
2218 if (cc.bodies[f] = -1) then break;
2219 px := @mProxies[cc.bodies[f]];
2220 ptag := px.mTag;
2221 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2222 begin
2223 px.mQueryMark := lq; // mark as processed
2224 if assigned(cb) then
2225 begin
2226 if not cb(px.mObj, ptag) then continue;
2227 end;
2228 // get adjusted proxy coords
2229 px0 := px.mX-minx;
2230 py0 := px.mY-miny;
2231 px1 := px0+px.mWidth-1;
2232 py1 := py0+px.mHeight-1;
2233 // inside?
2234 if firstCell and (x0 >= px0) and (y0 >= py0) and (x0 <= px1) and (y0 <= py1) then
2235 begin
2236 // oops
2237 ex := ax0;
2238 ey := ay0;
2239 result := px.mObj;
2240 mInQuery := false;
2241 exit;
2242 end;
2243 // do line-vs-aabb test
2244 sweepw.setClip(px0, py0, px1, py1);
2245 if sweepw.setup(x0, y0, x1, y1) then
2246 begin
2247 // hit detected
2248 sweepw.getPrevXY(hx, hy);
2249 distSq := distanceSq(x0, y0, hx, hy);
2250 if (distSq < lastDistSq) then
2251 begin
2252 lastDistSq := distSq;
2253 ex := hx+minx;
2254 ey := hy+miny;
2255 result := px.mObj;
2256 // if this is not a first cell, get outta here
2257 if not firstCell then begin mInQuery := false; exit; end;
2258 wasHit := true;
2259 end;
2260 end;
2261 end;
2262 end;
2263 // next cell
2264 ccidx := cc.next;
2265 end;
2266 // done processing cells; exit if we registered a hit
2267 // next cells can't have better candidates, obviously
2268 if wasHit then begin mInQuery := false; exit; end;
2269 firstCell := false;
2270 // move to next tile
2271 until lw.stepToNextTile();
2273 mInQuery := false;
2274 end;
2277 // ////////////////////////////////////////////////////////////////////////// //
2278 // no callback: return `true` on the nearest hit
2279 function TBodyGridBase.traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2280 var
2281 ex, ey: Integer;
2282 begin
2283 result := traceRayOld(ex, ey, x0, y0, x1, y1, cb, tagmask);
2284 end;
2287 // no callback: return `true` on the nearest hit
2288 // you are not supposed to understand this
2289 function TBodyGridBase.traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2290 var
2291 wx0, wy0, wx1, wy1: Integer; // window coordinates
2292 stx, sty: Integer; // "steps" for x and y axes
2293 dsx, dsy: Integer; // "lengthes" for x and y axes
2294 dx2, dy2: Integer; // "double lengthes" for x and y axes
2295 xd, yd: Integer; // current coord
2296 e: Integer; // "error" (as in bresenham algo)
2297 rem: Integer;
2298 term: Integer;
2299 xptr, yptr: PInteger;
2300 xfixed: Boolean;
2301 temp: Integer;
2302 prevx, prevy: Integer;
2303 lastDistSq: Integer;
2304 ccidx, curci: Integer;
2305 hasUntried: Boolean;
2306 lastGA: Integer = -1;
2307 ga, x, y: Integer;
2308 lastObj: ITP;
2309 wasHit: Boolean = false;
2310 gw, gh, minx, miny, maxx, maxy: Integer;
2311 cc: PGridCell;
2312 px: PBodyProxyRec;
2313 lq: LongWord;
2314 f, ptag, distSq: Integer;
2315 x0, y0, x1, y1: Integer;
2316 //swapped: Boolean = false; // true: xd is yd, and vice versa
2317 // horizontal walker
2318 {$IFDEF GRID_USE_ORTHO_ACCEL}
2319 wklen, wkstep: Integer;
2320 //wksign: Integer;
2321 hopt: Boolean;
2322 {$ENDIF}
2323 // skipper
2324 xdist, ydist: Integer;
2325 begin
2326 result := Default(ITP);
2327 lastObj := Default(ITP);
2328 tagmask := tagmask and TagFullMask;
2329 ex := ax1; // why not?
2330 ey := ay1; // why not?
2331 if (tagmask = 0) then exit;
2333 if (ax0 = ax1) and (ay0 = ay1) then
2334 begin
2335 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2336 if (result <> nil) then
2337 begin
2338 if assigned(cb) and not cb(result, ptag, ax0, ay0, ax0, ay0) then result := Default(ITP);
2339 end;
2340 exit;
2341 end;
2343 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
2345 gw := mWidth;
2346 gh := mHeight;
2347 minx := mMinX;
2348 miny := mMinY;
2349 maxx := gw*mTileSize-1;
2350 maxy := gh*mTileSize-1;
2352 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2353 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);
2354 {$ENDIF}
2356 x0 := ax0;
2357 y0 := ay0;
2358 x1 := ax1;
2359 y1 := ay1;
2361 // offset query coords to (0,0)-based
2362 Dec(x0, minx);
2363 Dec(y0, miny);
2364 Dec(x1, minx);
2365 Dec(y1, miny);
2367 // clip rectange
2368 wx0 := 0;
2369 wy0 := 0;
2370 wx1 := maxx;
2371 wy1 := maxy;
2373 // horizontal setup
2374 if (x0 < x1) then
2375 begin
2376 // from left to right
2377 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
2378 stx := 1; // going right
2379 end
2380 else
2381 begin
2382 // from right to left
2383 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
2384 stx := -1; // going left
2385 x0 := -x0;
2386 x1 := -x1;
2387 wx0 := -wx0;
2388 wx1 := -wx1;
2389 swapInt(wx0, wx1);
2390 end;
2392 // vertical setup
2393 if (y0 < y1) then
2394 begin
2395 // from top to bottom
2396 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
2397 sty := 1; // going down
2398 end
2399 else
2400 begin
2401 // from bottom to top
2402 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
2403 sty := -1; // going up
2404 y0 := -y0;
2405 y1 := -y1;
2406 wy0 := -wy0;
2407 wy1 := -wy1;
2408 swapInt(wy0, wy1);
2409 end;
2411 dsx := x1-x0;
2412 dsy := y1-y0;
2414 if (dsx < dsy) then
2415 begin
2416 //swapped := true;
2417 xptr := @yd;
2418 yptr := @xd;
2419 swapInt(x0, y0);
2420 swapInt(x1, y1);
2421 swapInt(dsx, dsy);
2422 swapInt(wx0, wy0);
2423 swapInt(wx1, wy1);
2424 swapInt(stx, sty);
2425 end
2426 else
2427 begin
2428 xptr := @xd;
2429 yptr := @yd;
2430 end;
2432 dx2 := 2*dsx;
2433 dy2 := 2*dsy;
2434 xd := x0;
2435 yd := y0;
2436 e := 2*dsy-dsx;
2437 term := x1;
2439 xfixed := false;
2440 if (y0 < wy0) then
2441 begin
2442 // clip at top
2443 temp := dx2*(wy0-y0)-dsx;
2444 xd += temp div dy2;
2445 rem := temp mod dy2;
2446 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
2447 if (xd+1 >= wx0) then
2448 begin
2449 yd := wy0;
2450 e -= rem+dsx;
2451 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
2452 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
2453 xfixed := true;
2454 end;
2455 end;
2457 if (not xfixed) and (x0 < wx0) then
2458 begin
2459 // clip at left
2460 temp := dy2*(wx0-x0);
2461 yd += temp div dx2;
2462 rem := temp mod dx2;
2463 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
2464 xd := wx0;
2465 e += rem;
2466 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
2467 end;
2469 if (y1 > wy1) then
2470 begin
2471 // clip at bottom
2472 temp := dx2*(wy1-y0)+dsx;
2473 term := x0+temp div dy2;
2474 rem := temp mod dy2;
2475 if (rem = 0) then Dec(term);
2476 end;
2478 if (term > wx1) then term := wx1; // clip at right
2480 Inc(term); // draw last point
2481 //if (term = xd) then exit; // this is the only point, get out of here
2483 if (sty = -1) then yd := -yd;
2484 if (stx = -1) then begin xd := -xd; term := -term; end;
2485 dx2 -= dy2;
2487 // first move, to skip starting point
2488 // DON'T DO THIS! loop will take care of that
2489 if (xd = term) then
2490 begin
2491 //FIXME!
2492 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2493 if (result <> nil) then
2494 begin
2495 if assigned(cb) then
2496 begin
2497 if cb(result, ptag, ax0, ay0, ax0, ay0) then
2498 begin
2499 ex := ax0;
2500 ey := ay0;
2501 end
2502 else
2503 begin
2504 result := nil;
2505 end;
2506 end
2507 else
2508 begin
2509 ex := ax0;
2510 ey := ay0;
2511 end;
2512 end;
2513 exit;
2514 end;
2516 prevx := xptr^+minx;
2517 prevy := yptr^+miny;
2518 (*
2519 // move coords
2520 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2521 xd += stx;
2522 // done?
2523 if (xd = term) then exit;
2524 *)
2526 {$IF DEFINED(D2F_DEBUG)}
2527 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2528 {$ENDIF}
2529 // DON'T DO THIS! loop will take care of that
2530 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
2531 //ccidx := mGrid[lastGA];
2533 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2534 //if assigned(dbgRayTraceTileHitCB) then e_WriteLog('1:TRACING!', MSG_NOTIFY);
2535 {$ENDIF}
2537 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
2539 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2540 mInQuery := true;
2542 // increase query counter
2543 Inc(mLastQuery);
2544 if (mLastQuery = 0) then
2545 begin
2546 // just in case of overflow
2547 mLastQuery := 1;
2548 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2549 end;
2550 lq := mLastQuery;
2552 {$IFDEF GRID_USE_ORTHO_ACCEL}
2553 // if this is strict horizontal/vertical trace, use optimized codepath
2554 if (ax0 = ax1) or (ay0 = ay1) then
2555 begin
2556 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
2557 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
2558 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
2559 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
2560 hopt := (ay0 = ay1); // horizontal?
2561 if (stx < 0) then begin {wksign := -1;} wklen := -(term-xd); end else begin {wksign := 1;} wklen := term-xd; end;
2562 {$IF DEFINED(D2F_DEBUG)}
2563 if dbgShowTraceLog then e_LogWritefln('optimized htrace; wklen=%d', [wklen]);
2564 {$ENDIF}
2565 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2566 // one of those will never change
2567 x := xptr^+minx;
2568 y := yptr^+miny;
2569 while (wklen > 0) do
2570 begin
2571 {$IF DEFINED(D2F_DEBUG)}
2572 if dbgShowTraceLog then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; y=%d; y=%d', [ga, xptr^+minx, yptr^+miny, y, ay0]);
2573 {$ENDIF}
2574 // new tile?
2575 if (ga <> lastGA) then
2576 begin
2577 lastGA := ga;
2578 ccidx := mGrid[lastGA];
2579 // convert coords to map (to avoid ajdusting coords inside the loop)
2580 if hopt then x := xptr^+minx else y := yptr^+miny;
2581 while (ccidx <> -1) do
2582 begin
2583 cc := @mCells[ccidx];
2584 for f := 0 to GridCellBucketSize-1 do
2585 begin
2586 if (cc.bodies[f] = -1) then break;
2587 px := @mProxies[cc.bodies[f]];
2588 ptag := px.mTag;
2589 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) and
2590 // constant coord should be inside
2591 ((hopt and (y >= px.y0) and (y <= px.y1)) or
2592 ((not hopt) and (x >= px.x0) and (x <= px.x1))) then
2593 begin
2594 px.mQueryMark := lq; // mark as processed
2595 // inside the proxy?
2596 if (hopt and (x > px.x0) and (x < px.x1)) or
2597 ((not hopt) and (y > px.y0) and (y < px.y1)) then
2598 begin
2599 // setup prev[xy]
2600 if assigned(cb) then
2601 begin
2602 if cb(px.mObj, ptag, x, y, x, y) then
2603 begin
2604 result := px.mObj;
2605 ex := x;
2606 ey := y;
2607 mInQuery := false;
2608 exit;
2609 end;
2610 end
2611 else
2612 begin
2613 distSq := distanceSq(ax0, ay0, x, y);
2614 {$IF DEFINED(D2F_DEBUG)}
2615 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]);
2616 {$ENDIF}
2617 if (distSq < lastDistSq) then
2618 begin
2619 ex := x;
2620 ey := y;
2621 result := px.mObj;
2622 mInQuery := false;
2623 exit;
2624 end;
2625 end;
2626 continue;
2627 end;
2628 // remember this hitpoint if it is nearer than an old one
2629 // setup prev[xy]
2630 if hopt then
2631 begin
2632 // horizontal trace
2633 prevy := y;
2634 y := yptr^+miny;
2635 if (stx < 0) then
2636 begin
2637 // going left
2638 if (x < px.x1) then continue; // not on the right edge
2639 x := px.x1;
2640 prevx := x+1;
2641 end
2642 else
2643 begin
2644 // going right
2645 if (x > px.x0) then continue; // not on the left edge
2646 x := px.x0;
2647 prevx := x-1;
2648 end;
2649 end
2650 else
2651 begin
2652 // vertical trace
2653 prevx := x;
2654 x := xptr^+minx;
2655 if (stx < 0) then
2656 begin
2657 // going up
2658 if (y < px.y1) then continue; // not on the bottom edge
2659 y := px.y1;
2660 prevy := x+1;
2661 end
2662 else
2663 begin
2664 // going down
2665 if (y > px.y0) then continue; // not on the top edge
2666 y := px.y0;
2667 prevy := y-1;
2668 end;
2669 end;
2670 if assigned(cb) then
2671 begin
2672 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2673 begin
2674 result := px.mObj;
2675 ex := prevx;
2676 ey := prevy;
2677 mInQuery := false;
2678 exit;
2679 end;
2680 end
2681 else
2682 begin
2683 distSq := distanceSq(ax0, ay0, prevx, prevy);
2684 {$IF DEFINED(D2F_DEBUG)}
2685 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]);
2686 {$ENDIF}
2687 if (distSq < lastDistSq) then
2688 begin
2689 wasHit := true;
2690 lastDistSq := distSq;
2691 ex := prevx;
2692 ey := prevy;
2693 lastObj := px.mObj;
2694 end;
2695 end;
2696 end;
2697 end;
2698 // next cell
2699 ccidx := cc.next;
2700 end;
2701 if wasHit and not assigned(cb) then begin result := lastObj; mInQuery := false; exit; end;
2702 if assigned(cb) and cb(nil, 0, x, y, x, y) then begin result := lastObj; mInQuery := false; exit; end;
2703 end;
2704 // skip to next tile
2705 if hopt then
2706 begin
2707 if (stx > 0) then
2708 begin
2709 // to the right
2710 wkstep := ((xptr^ or (mTileSize-1))+1)-xptr^;
2711 {$IF DEFINED(D2F_DEBUG)}
2712 if dbgShowTraceLog then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2713 {$ENDIF}
2714 if (wkstep >= wklen) then break;
2715 Inc(xptr^, wkstep);
2716 Inc(ga);
2717 end
2718 else
2719 begin
2720 // to the left
2721 wkstep := xptr^-((xptr^ and (not (mTileSize-1)))-1);
2722 {$IF DEFINED(D2F_DEBUG)}
2723 if dbgShowTraceLog then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2724 {$ENDIF}
2725 if (wkstep >= wklen) then break;
2726 Dec(xptr^, wkstep);
2727 Dec(ga);
2728 end;
2729 end
2730 else
2731 begin
2732 if (stx > 0) then
2733 begin
2734 // to the down
2735 wkstep := ((yptr^ or (mTileSize-1))+1)-yptr^;
2736 {$IF DEFINED(D2F_DEBUG)}
2737 if dbgShowTraceLog then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2738 {$ENDIF}
2739 if (wkstep >= wklen) then break;
2740 Inc(yptr^, wkstep);
2741 Inc(ga, mWidth);
2742 end
2743 else
2744 begin
2745 // to the up
2746 wkstep := yptr^-((yptr^ and (not (mTileSize-1)))-1);
2747 {$IF DEFINED(D2F_DEBUG)}
2748 if dbgShowTraceLog then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2749 {$ENDIF}
2750 if (wkstep >= wklen) then break;
2751 Dec(yptr^, wkstep);
2752 Dec(ga, mWidth);
2753 end;
2754 end;
2755 Dec(wklen, wkstep);
2756 end;
2757 // we can travel less than one cell
2758 if wasHit and not assigned(cb) then result := lastObj else begin ex := ax1; ey := ay1; end;
2759 mInQuery := false;
2760 exit;
2761 end;
2762 {$ENDIF}
2764 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2765 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2766 {$ENDIF}
2768 //e_LogWritefln('*********************', []);
2769 ccidx := -1;
2770 // can omit checks
2771 while (xd <> term) do
2772 begin
2773 // check cell(s)
2774 {$IF DEFINED(D2F_DEBUG)}
2775 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2776 {$ENDIF}
2777 // new tile?
2778 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2779 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2780 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);
2781 {$ENDIF}
2782 if (ga <> lastGA) then
2783 begin
2784 // yes
2785 {$IF DEFINED(D2F_DEBUG)}
2786 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2787 {$ENDIF}
2788 if (ccidx <> -1) then
2789 begin
2790 // signal cell completion
2791 if assigned(cb) then
2792 begin
2793 if cb(nil, 0, xptr^+minx, yptr^+miny, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2794 end
2795 else if wasHit then
2796 begin
2797 result := lastObj;
2798 mInQuery := false;
2799 exit;
2800 end;
2801 end;
2802 lastGA := ga;
2803 ccidx := mGrid[lastGA];
2804 end;
2805 // has something to process in this tile?
2806 if (ccidx <> -1) then
2807 begin
2808 // process cell
2809 curci := ccidx;
2810 hasUntried := false; // this will be set to `true` if we have some proxies we still want to process at the next step
2811 // convert coords to map (to avoid ajdusting coords inside the loop)
2812 x := xptr^+minx;
2813 y := yptr^+miny;
2814 // process cell list
2815 while (curci <> -1) do
2816 begin
2817 cc := @mCells[curci];
2818 for f := 0 to GridCellBucketSize-1 do
2819 begin
2820 if (cc.bodies[f] = -1) then break;
2821 px := @mProxies[cc.bodies[f]];
2822 ptag := px.mTag;
2823 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2824 begin
2825 // can we process this proxy?
2826 if (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
2827 begin
2828 px.mQueryMark := lq; // mark as processed
2829 if assigned(cb) then
2830 begin
2831 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2832 begin
2833 result := px.mObj;
2834 ex := prevx;
2835 ey := prevy;
2836 mInQuery := false;
2837 exit;
2838 end;
2839 end
2840 else
2841 begin
2842 // remember this hitpoint if it is nearer than an old one
2843 distSq := distanceSq(ax0, ay0, prevx, prevy);
2844 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2845 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);
2846 {$ENDIF}
2847 if (distSq < lastDistSq) then
2848 begin
2849 wasHit := true;
2850 lastDistSq := distSq;
2851 ex := prevx;
2852 ey := prevy;
2853 lastObj := px.mObj;
2854 end;
2855 end;
2856 end
2857 else
2858 begin
2859 // this is possibly interesting proxy, set "has more to check" flag
2860 hasUntried := true;
2861 end;
2862 end;
2863 end;
2864 // next cell
2865 curci := cc.next;
2866 end;
2867 // still has something interesting in this cell?
2868 if not hasUntried then
2869 begin
2870 // nope, don't process this cell anymore; signal cell completion
2871 ccidx := -1;
2872 if assigned(cb) then
2873 begin
2874 if cb(nil, 0, x, y, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2875 end
2876 else if wasHit then
2877 begin
2878 result := lastObj;
2879 mInQuery := false;
2880 exit;
2881 end;
2882 end;
2883 end;
2884 if (ccidx = -1) then
2885 begin
2886 // move to cell edge, as we have nothing to trace here anymore
2887 if (stx < 0) then xdist := xd and (not (mTileSize-1)) else xdist := xd or (mTileSize-1);
2888 if (sty < 0) then ydist := yd and (not (mTileSize-1)) else ydist := yd or (mTileSize-1);
2889 //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]);
2890 while (xd <> xdist) and (yd <> ydist) do
2891 begin
2892 // step
2893 xd += stx;
2894 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2895 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
2896 if (xd = term) then break;
2897 end;
2898 //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]);
2899 if (xd = term) then break;
2900 end;
2901 //putPixel(xptr^, yptr^);
2902 // move coords
2903 prevx := xptr^+minx;
2904 prevy := yptr^+miny;
2905 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2906 xd += stx;
2907 end;
2908 // we can travel less than one cell
2909 if wasHit and not assigned(cb) then
2910 begin
2911 result := lastObj;
2912 end
2913 else
2914 begin
2915 ex := ax1; // why not?
2916 ey := ay1; // why not?
2917 end;
2919 mInQuery := false;
2920 end;
2923 end.