DEADSOFTWARE

slightly better `traceBox()`
[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 procedure insertInternal (body: TBodyProxyId);
146 procedure removeInternal (body: TBodyProxyId);
148 function forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
150 function inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
151 function remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
153 function getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
154 procedure setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
156 function getGridWidthPx (): Integer; inline;
157 function getGridHeightPx (): Integer; inline;
159 function getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
161 public
162 constructor Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
163 destructor Destroy (); override;
165 function insertBody (aObj: ITP; ax, ay, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
166 procedure removeBody (body: TBodyProxyId); // WARNING! this WILL destroy proxy!
168 procedure moveBody (body: TBodyProxyId; nx, ny: Integer);
169 procedure resizeBody (body: TBodyProxyId; nw, nh: Integer);
170 procedure moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
172 function insideGrid (x, y: Integer): Boolean; inline;
174 // `false` if `body` is surely invalid
175 function getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
176 function getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
177 function getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
179 //WARNING: don't modify grid while any query is in progress (no checks are made!)
180 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
181 // no callback: return `true` on the first hit
182 function forEachInAABB (x, y, w, h: Integer; cb: TGridQueryCB; tagmask: Integer=-1; allowDisabled: Boolean=false): ITP;
184 //WARNING: don't modify grid while any query is in progress (no checks are made!)
185 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
186 // no callback: return object on the first hit or nil
187 function forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
189 function atCellInPoint (x, y: Integer): TAtPointEnumerator;
191 //WARNING: don't modify grid while any query is in progress (no checks are made!)
192 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
193 // cb with `(nil)` will be called before processing new tile
194 // no callback: return object of the nearest hit or nil
195 // if `inverted` is true, trace will register bodies *exluding* tagmask
196 //WARNING: don't change tags in callbacks here!
197 function traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP; overload;
198 function traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
200 //WARNING: don't modify grid while any query is in progress (no checks are made!)
201 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
202 // cb with `(nil)` will be called before processing new tile
203 // no callback: return object of the nearest hit or nil
204 // if `inverted` is true, trace will register bodies *exluding* tagmask
205 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
206 //WARNING: don't change tags in callbacks here!
207 function traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP; overload;
208 function traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
210 // return `false` if we're still inside at the end
211 // line should be either strict horizontal, or strict vertical, otherwise an exception will be thrown
212 // `true`: endpoint will point at the last "inside" pixel
213 // `false`: endpoint will be (ax1, ay1)
214 //WARNING: don't change tags in callbacks here!
215 function traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
217 //WARNING: don't modify grid while any query is in progress (no checks are made!)
218 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
219 // trace line along the grid, calling `cb` for all objects in passed cells, in no particular order
220 //WARNING: don't change tags in callbacks here!
221 function forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
223 // trace box with the given velocity; return object hit (if any)
224 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
225 //WARNING: don't change tags in callbacks here!
226 function traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
228 // debug
229 procedure forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
230 function forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
231 procedure dumpStats ();
233 public
234 //WARNING! no sanity checks!
235 property proxyEnabled[pid: TBodyProxyId]: Boolean read getProxyEnabled write setProxyEnabled;
237 property gridX0: Integer read mMinX;
238 property gridY0: Integer read mMinY;
239 property gridWidth: Integer read getGridWidthPx; // in pixels
240 property gridHeight: Integer read getGridHeightPx; // in pixels
242 property proxy[idx: TBodyProxyId]: PBodyProxyRec read getProxyById;
243 end;
246 type
247 // common structure for all line tracers
248 TLineWalker = record
249 public
250 const TileSize = GridTileSize;
252 private
253 wx0, wy0, wx1, wy1: Integer; // window coordinates
254 stx, sty: Integer; // "steps" for x and y axes
255 dx2, dy2: Integer; // "double lengthes" for x and y axes
256 xd, yd: Integer; // current coord
257 e: Integer; // "error" (as in bresenham algo)
258 term: Integer; // end for xd (xd = term: done)
259 //xptr, yptr: PInteger;
260 xyswapped: Boolean; // true: xd is y
262 public
263 // call `setyp` after this
264 constructor Create (minx, miny, maxx, maxy: Integer);
266 procedure setClip (minx, miny, maxx, maxy: Integer); inline;
268 // this will use `w[xy][01]` to clip coords
269 // return `false` if the whole line was clipped away
270 // on `true`, you should process first point, and go on
271 function setup (x0, y0, x1, y1: Integer): Boolean;
273 // call this *after* doing a step
274 // WARNING! if you will do a step when this returns `true`, you will fall into limbo
275 function done (): Boolean; inline;
277 // as you will prolly call `done()` after doing a step anyway, this will do it for you
278 // move to next point, return `true` when the line is complete (i.e. you should stop)
279 function step (): Boolean; inline;
281 // move to next tile; return `true` if the line is complete (and walker state is undefined then)
282 function stepToNextTile (): Boolean; inline;
284 // hack for line-vs-aabb; NOT PROPERLY TESTED!
285 procedure getPrevXY (out ox, oy: Integer); inline;
287 // current coords
288 function x (): Integer; inline;
289 function y (): Integer; inline;
291 procedure getXY (out ox, oy: Integer); inline;
293 // move directions; always [-1..1] (can be zero!)
294 function dx (): Integer; inline;
295 function dy (): Integer; inline;
296 end;
299 // you are not supposed to understand this
300 // returns `true` if there is an intersection, and enter coords
301 // enter coords will be equal to (x0, y0) if starting point is inside the box
302 // if result is `false`, `inx` and `iny` are undefined
303 function lineAABBIntersects (x0, y0, x1, y1: Integer; bx, by, bw, bh: Integer; out inx, iny: Integer): Boolean;
305 // sweep two AABB's to see if and when they are overlapping
306 // returns `true` if collision was detected (but boxes doesn't overlap)
307 // u1 and u1 has no sense if no collision was detected
308 // u0 = normalized time of first collision (i.e. collision starts at myMove*u0)
309 // u1 = normalized time of second collision (i.e. collision stops after myMove*u1)
310 // hitedge for `it`: 0: top; 1: right; 2: bottom; 3: left
311 // enter/exit coords will form non-intersecting configuration (i.e. will be before/after the actual collision)
312 function sweepAABB (mex0, mey0, mew, meh: Integer; medx, medy: Integer; itx0, ity0, itw, ith: Integer;
313 u0: PSingle=nil; hitedge: PInteger=nil; u1: PSingle=nil): Boolean;
315 function distanceSq (x0, y0, x1, y1: Integer): Integer; inline;
317 procedure swapInt (var a: Integer; var b: Integer); inline;
318 //function minInt (a, b: Integer): Integer; inline;
319 //function maxInt (a, b: Integer): Integer; inline;
322 implementation
324 uses
325 SysUtils, e_log, g_console, utils;
328 // ////////////////////////////////////////////////////////////////////////// //
329 procedure swapInt (var a: Integer; var b: Integer); inline; var t: Integer; begin t := a; a := b; b := t; end;
330 //function minInt (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
331 //function maxInt (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
333 function distanceSq (x0, y0, x1, y1: Integer): Integer; inline; begin result := (x1-x0)*(x1-x0)+(y1-y0)*(y1-y0); end;
336 // ////////////////////////////////////////////////////////////////////////// //
337 constructor TLineWalker.Create (minx, miny, maxx, maxy: Integer);
338 begin
339 setClip(minx, miny, maxx, maxy);
340 end;
342 procedure TLineWalker.setClip (minx, miny, maxx, maxy: Integer); inline;
343 begin
344 // clip rectange
345 wx0 := minx;
346 wy0 := miny;
347 wx1 := maxx;
348 wy1 := maxy;
349 end;
351 function TLineWalker.done (): Boolean; inline; begin result := (xd = term); end;
353 function TLineWalker.step (): Boolean; inline;
354 begin
355 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
356 xd += stx;
357 result := (xd = term);
358 end;
360 // move to next tile; return `true` if the line is complete (and walker state is undefined then)
361 function TLineWalker.stepToNextTile (): Boolean; inline;
362 var
363 ex, ey, wklen, f: Integer;
364 begin
365 result := false;
367 //writeln('stx=', stx, '; sty=', sty);
369 // ortho?
370 if (sty = 0) then
371 begin
372 // only xd
373 assert(sty <> 0);
374 if (stx < 0) then
375 begin
376 // xd: to left edge
377 xd := (xd and (not (TileSize-1)))-1;
378 result := (xd <= term);
379 exit;
380 end
381 else
382 begin
383 // xd: to right edge
384 xd := (xd or (TileSize-1))+1;
385 result := (xd >= term);
386 exit;
387 end;
388 end;
390 assert(stx <> 0); // invariant
392 // not ortho
393 if (sty < 0) then ey := (yd and (not (TileSize-1)))-1 else ey := (yd or (TileSize-1))+1;
395 //FIXME: do some math to avoid single-stepping
396 if (stx < 0) then
397 begin
398 // xd: to left edge
399 ex := (xd and (not (TileSize-1)))-1;
400 if (ex <= term) then begin result := true; exit; end;
401 wklen := xd-ex;
402 end
403 else
404 begin
405 // xd: to right edge
406 ex := (xd or (TileSize-1))+1;
407 if (ex >= term) then begin result := true; exit; end;
408 wklen := ex-xd;
409 end;
411 //writeln('xd=', xd, '; yd=', yd, '; ex=', ex, '; ey=', ey, '; term=', term, '; wklen=', wklen);
413 for f := wklen downto 1 do
414 begin
415 // do step
416 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
417 xd += stx;
418 if (xd = term) then begin result := true; exit; end;
419 if (xd = ex) or (yd = ey) then exit; // done
420 end;
422 raise Exception.Create('TLineWalker.stepToNextTile: the thing that should not be!');
423 end;
425 // NOT TESTED!
426 procedure TLineWalker.getPrevXY (out ox, oy: Integer); inline;
427 begin
428 //writeln('e=', e, '; dx2=', dx2, '; dy2=', dy2);
429 if xyswapped then
430 begin
431 if (e >= 0) then ox := yd-sty else ox := yd;
432 oy := xd-stx;
433 end
434 else
435 begin
436 if (e >= 0) then oy := yd-sty else oy := yd;
437 ox := xd-stx;
438 end;
439 end;
441 function TLineWalker.x (): Integer; inline; begin if xyswapped then result := yd else result := xd; end;
442 function TLineWalker.y (): Integer; inline; begin if xyswapped then result := xd else result := yd; end;
443 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;
445 function TLineWalker.dx (): Integer; inline; begin if xyswapped then result := stx else result := sty; end;
446 function TLineWalker.dy (): Integer; inline; begin if xyswapped then result := sty else result := stx; end;
448 function TLineWalker.setup (x0, y0, x1, y1: Integer): Boolean;
449 procedure swapInt (var a: Integer; var b: Integer); inline; var t: Integer; begin t := a; a := b; b := t; end;
450 var
451 dsx, dsy: Integer; // "lengthes" for x and y axes
452 rem: Integer;
453 xfixed: Boolean;
454 temp: Integer;
455 begin
456 result := false;
457 xyswapped := false;
459 // horizontal setup
460 if (x0 < x1) then
461 begin
462 // from left to right
463 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
464 stx := 1; // going right
465 end
466 else
467 begin
468 // from right to left
469 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
470 stx := -1; // going left
471 x0 := -x0;
472 x1 := -x1;
473 wx0 := -wx0;
474 wx1 := -wx1;
475 swapInt(wx0, wx1);
476 end;
478 // vertical setup
479 if (y0 < y1) then
480 begin
481 // from top to bottom
482 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
483 sty := 1; // going down
484 end
485 else
486 begin
487 // from bottom to top
488 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
489 sty := -1; // going up
490 y0 := -y0;
491 y1 := -y1;
492 wy0 := -wy0;
493 wy1 := -wy1;
494 swapInt(wy0, wy1);
495 end;
497 dsx := x1-x0;
498 dsy := y1-y0;
500 if (dsx < dsy) then
501 begin
502 xyswapped := true;
503 //xptr := @yd;
504 //yptr := @xd;
505 swapInt(x0, y0);
506 swapInt(x1, y1);
507 swapInt(dsx, dsy);
508 swapInt(wx0, wy0);
509 swapInt(wx1, wy1);
510 swapInt(stx, sty);
511 end
512 else
513 begin
514 //xptr := @xd;
515 //yptr := @yd;
516 end;
518 dx2 := 2*dsx;
519 dy2 := 2*dsy;
520 xd := x0;
521 yd := y0;
522 e := 2*dsy-dsx;
523 term := x1;
525 xfixed := false;
526 if (y0 < wy0) then
527 begin
528 // clip at top
529 temp := dx2*(wy0-y0)-dsx;
530 xd += temp div dy2;
531 rem := temp mod dy2;
532 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
533 if (xd+1 >= wx0) then
534 begin
535 yd := wy0;
536 e -= rem+dsx;
537 if (rem > 0) then begin Inc(xd); e += dy2; end;
538 xfixed := true;
539 end;
540 end;
542 if (not xfixed) and (x0 < wx0) then
543 begin
544 // clip at left
545 temp := dy2*(wx0-x0);
546 yd += temp div dx2;
547 rem := temp mod dx2;
548 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
549 xd := wx0;
550 e += rem;
551 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
552 end;
554 if (y1 > wy1) then
555 begin
556 // clip at bottom
557 temp := dx2*(wy1-y0)+dsx;
558 term := x0+temp div dy2;
559 rem := temp mod dy2;
560 if (rem = 0) then Dec(term);
561 end;
563 if (term > wx1) then term := wx1; // clip at right
565 Inc(term); // draw last point (it is ok to inc here, as `term` sign will be changed later
566 //if (term = xd) then exit; // this is the only point, get out of here
568 if (sty = -1) then yd := -yd;
569 if (stx = -1) then begin xd := -xd; term := -term; end;
570 dx2 -= dy2;
572 result := true;
573 end;
576 // ////////////////////////////////////////////////////////////////////////// //
577 // you are not supposed to understand this
578 // returns `true` if there is an intersection, and enter coords
579 // enter coords will be equal to (x0, y0) if starting point is inside the box
580 // if result is `false`, `inx` and `iny` are undefined
581 function lineAABBIntersects (x0, y0, x1, y1: Integer; bx, by, bw, bh: Integer; out inx, iny: Integer): Boolean;
582 var
583 wx0, wy0, wx1, wy1: Integer; // window coordinates
584 stx, sty: Integer; // "steps" for x and y axes
585 dsx, dsy: Integer; // "lengthes" for x and y axes
586 dx2, dy2: Integer; // "double lengthes" for x and y axes
587 xd, yd: Integer; // current coord
588 e: Integer; // "error" (as in bresenham algo)
589 rem: Integer;
590 //!term: Integer;
591 d0, d1: PInteger;
592 xfixed: Boolean;
593 temp: Integer;
594 begin
595 result := false;
596 // why not
597 inx := x0;
598 iny := y0;
599 if (bw < 1) or (bh < 1) then exit; // impossible box
601 if (x0 = x1) and (y0 = y1) then
602 begin
603 // check this point
604 result := (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh);
605 exit;
606 end;
608 // check if staring point is inside the box
609 if (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh) then begin result := true; exit; end;
611 // clip rectange
612 wx0 := bx;
613 wy0 := by;
614 wx1 := bx+bw-1;
615 wy1 := by+bh-1;
617 // horizontal setup
618 if (x0 < x1) then
619 begin
620 // from left to right
621 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
622 stx := 1; // going right
623 end
624 else
625 begin
626 // from right to left
627 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
628 stx := -1; // going left
629 x0 := -x0;
630 x1 := -x1;
631 wx0 := -wx0;
632 wx1 := -wx1;
633 swapInt(wx0, wx1);
634 end;
636 // vertical setup
637 if (y0 < y1) then
638 begin
639 // from top to bottom
640 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
641 sty := 1; // going down
642 end
643 else
644 begin
645 // from bottom to top
646 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
647 sty := -1; // going up
648 y0 := -y0;
649 y1 := -y1;
650 wy0 := -wy0;
651 wy1 := -wy1;
652 swapInt(wy0, wy1);
653 end;
655 dsx := x1-x0;
656 dsy := y1-y0;
658 if (dsx < dsy) then
659 begin
660 d0 := @yd;
661 d1 := @xd;
662 swapInt(x0, y0);
663 swapInt(x1, y1);
664 swapInt(dsx, dsy);
665 swapInt(wx0, wy0);
666 swapInt(wx1, wy1);
667 swapInt(stx, sty);
668 end
669 else
670 begin
671 d0 := @xd;
672 d1 := @yd;
673 end;
675 dx2 := 2*dsx;
676 dy2 := 2*dsy;
677 xd := x0;
678 yd := y0;
679 e := 2*dsy-dsx;
680 //!term := x1;
682 xfixed := false;
683 if (y0 < wy0) then
684 begin
685 // clip at top
686 temp := dx2*(wy0-y0)-dsx;
687 xd += temp div dy2;
688 rem := temp mod dy2;
689 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
690 if (xd+1 >= wx0) then
691 begin
692 yd := wy0;
693 e -= rem+dsx;
694 if (rem > 0) then begin Inc(xd); e += dy2; end;
695 xfixed := true;
696 end;
697 end;
699 if (not xfixed) and (x0 < wx0) then
700 begin
701 // clip at left
702 temp := dy2*(wx0-x0);
703 yd += temp div dx2;
704 rem := temp mod dx2;
705 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
706 xd := wx0;
707 e += rem;
708 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
709 end;
711 (*
712 if (y1 > wy1) then
713 begin
714 // clip at bottom
715 temp := dx2*(wy1-y0)+dsx;
716 term := x0+temp div dy2;
717 rem := temp mod dy2;
718 if (rem = 0) then Dec(term);
719 end;
721 if (term > wx1) then term := wx1; // clip at right
723 Inc(term); // draw last point
724 //if (term = xd) then exit; // this is the only point, get out of here
725 *)
727 if (sty = -1) then yd := -yd;
728 if (stx = -1) then begin xd := -xd; {!term := -term;} end;
729 //!dx2 -= dy2;
731 inx := d0^;
732 iny := d1^;
733 result := true;
734 end;
737 // ////////////////////////////////////////////////////////////////////////// //
738 function sweepAABB (mex0, mey0, mew, meh: Integer; medx, medy: Integer; itx0, ity0, itw, ith: Integer;
739 u0: PSingle=nil; hitedge: PInteger=nil; u1: PSingle=nil): Boolean;
740 var
741 tin, tout: Single;
743 function axisOverlap (me0, me1, it0, it1, d, he0, he1: Integer): Boolean; inline;
744 var
745 t: Single;
746 begin
747 result := false;
749 if (me1 < it0) then
750 begin
751 if (d >= 0) then exit; // oops, no hit
752 t := (me1-it0+1)/d;
753 if (t > tin) then begin tin := t; hitedge^ := he1; end;
754 end
755 else if (it1 < me0) then
756 begin
757 if (d <= 0) then exit; // oops, no hit
758 t := (me0-it1-1)/d;
759 if (t > tin) then begin tin := t; hitedge^ := he0; end;
760 end;
762 if (d < 0) and (it1 > me0) then
763 begin
764 t := (me0-it1-1)/d;
765 if (t < tout) then tout := t;
766 end
767 else if (d > 0) and (me1 > it0) then
768 begin
769 t := (me1-it0+1)/d;
770 if (t < tout) then tout := t;
771 end;
773 result := true;
774 end;
776 var
777 mex1, mey1, itx1, ity1, vx, vy: Integer;
778 htt: Integer = -1;
779 begin
780 result := false;
781 if (u0 <> nil) then u0^ := -1.0;
782 if (u1 <> nil) then u1^ := -1.0;
783 if (hitedge = nil) then hitedge := @htt else hitedge^ := -1;
785 if (mew < 1) or (meh < 1) or (itw < 1) or (ith < 1) then exit;
787 mex1 := mex0+mew-1;
788 mey1 := mey0+meh-1;
789 itx1 := itx0+itw-1;
790 ity1 := ity0+ith-1;
792 // check if they are overlapping right now (SAT)
793 //if (mex1 >= itx0) and (mex0 <= itx1) and (mey1 >= ity0) and (mey0 <= ity1) then begin result := true; exit; end;
795 if (medx = 0) and (medy = 0) then exit; // both boxes are sationary
797 // treat b as stationary, so invert v to get relative velocity
798 vx := -medx;
799 vy := -medy;
801 tin := -100000000.0;
802 tout := 100000000.0;
804 if not axisOverlap(mex0, mex1, itx0, itx1, vx, 1, 3) then exit;
805 if not axisOverlap(mey0, mey1, ity0, ity1, vy, 2, 0) then exit;
807 if (u0 <> nil) then u0^ := tin;
808 if (u1 <> nil) then u1^ := tout;
810 if (tin <= tout) and (tin >= 0.0) and (tin <= 1.0) then
811 begin
812 result := true;
813 end;
814 end;
817 // ////////////////////////////////////////////////////////////////////////// //
818 procedure TBodyGridBase.TBodyProxyRec.setup (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer);
819 begin
820 mX := aX;
821 mY := aY;
822 mWidth := aWidth;
823 mHeight := aHeight;
824 mQueryMark := 0;
825 mObj := aObj;
826 mTag := aTag;
827 nextLink := -1;
828 end;
831 function TBodyGridBase.TBodyProxyRec.getTag (): Integer; inline;
832 begin
833 result := mTag and TagFullMask;
834 end;
836 procedure TBodyGridBase.TBodyProxyRec.setTag (v: Integer); inline;
837 begin
838 mTag := (mTag and TagDisabled) or (v and TagFullMask);
839 end;
841 function TBodyGridBase.TBodyProxyRec.getEnabled (): Boolean; inline;
842 begin
843 result := ((mTag and TagDisabled) = 0);
844 end;
846 procedure TBodyGridBase.TBodyProxyRec.setEnabled (v: Boolean); inline;
847 begin
848 if v then mTag := mTag and (not TagDisabled) else mTag := mTag or TagDisabled;
849 end;
851 function TBodyGridBase.TBodyProxyRec.getX1 (): Integer; inline;
852 begin
853 result := mX+mWidth-1;
854 end;
856 function TBodyGridBase.TBodyProxyRec.getY1 (): Integer; inline;
857 begin
858 result := mY+mHeight-1;
859 end;
862 // ////////////////////////////////////////////////////////////////////////// //
863 constructor TBodyGridBase.TAtPointEnumerator.Create (acells: TCellArray; aidx: Integer; agetpx: TGetProxyFn);
864 begin
865 mCells := acells;
866 curidx := aidx;
867 curbki := -1;
868 getpx := agetpx;
869 end;
872 function TBodyGridBase.TAtPointEnumerator.MoveNext (): Boolean; inline;
873 begin
874 while (curidx <> -1) do
875 begin
876 while (curbki < GridCellBucketSize) do
877 begin
878 Inc(curbki);
879 if (mCells[curidx].bodies[curbki] = -1) then break;
880 result := true;
881 exit;
882 end;
883 curidx := mCells[curidx].next;
884 curbki := -1;
885 end;
886 result := false;
887 end;
890 function TBodyGridBase.TAtPointEnumerator.getCurrent (): PBodyProxyRec; inline;
891 begin
892 result := getpx(mCells[curidx].bodies[curbki]);
893 end;
896 // ////////////////////////////////////////////////////////////////////////// //
897 constructor TBodyGridBase.Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
898 var
899 idx: Integer;
900 begin
901 dbgShowTraceLog := false;
902 {$IF DEFINED(D2F_DEBUG)}
903 dbgRayTraceTileHitCB := nil;
904 {$ENDIF}
906 if aTileSize < 1 then aTileSize := 1;
907 if aTileSize > 8192 then aTileSize := 8192; // arbitrary limit
908 mTileSize := aTileSize;
910 if (aPixWidth < mTileSize) then aPixWidth := mTileSize;
911 if (aPixHeight < mTileSize) then aPixHeight := mTileSize;
912 mMinX := aMinPixX;
913 mMinY := aMinPixY;
914 mWidth := (aPixWidth+mTileSize-1) div mTileSize;
915 mHeight := (aPixHeight+mTileSize-1) div mTileSize;
916 SetLength(mGrid, mWidth*mHeight);
917 SetLength(mCells, mWidth*mHeight);
918 SetLength(mProxies, 8192);
919 mFreeCell := 0;
920 // init free list
921 for idx := 0 to High(mCells) do
922 begin
923 mCells[idx].bodies[0] := -1;
924 mCells[idx].bodies[GridCellBucketSize-1] := -1; // "has free room" flag
925 mCells[idx].next := idx+1;
926 end;
927 mCells[High(mCells)].next := -1; // last cell
928 // init grid
929 for idx := 0 to High(mGrid) do mGrid[idx] := -1;
930 // init proxies
931 for idx := 0 to High(mProxies) do mProxies[idx].nextLink := idx+1;
932 mProxies[High(mProxies)].nextLink := -1;
933 mLastQuery := 0;
934 mUsedCells := 0;
935 mProxyFree := 0;
936 mProxyCount := 0;
937 mProxyMaxCount := 0;
938 e_WriteLog(Format('created grid with size: %dx%d (tile size: %d); pix: %dx%d', [mWidth, mHeight, mTileSize, mWidth*mTileSize, mHeight*mTileSize]), MSG_NOTIFY);
939 end;
942 destructor TBodyGridBase.Destroy ();
943 begin
944 mCells := nil;
945 mGrid := nil;
946 mProxies := nil;
947 inherited;
948 end;
951 // ////////////////////////////////////////////////////////////////////////// //
952 procedure TBodyGridBase.dumpStats ();
953 var
954 idx, mcb, ccidx, cnt: Integer;
955 begin
956 mcb := 0;
957 for idx := 0 to High(mGrid) do
958 begin
959 ccidx := mGrid[idx];
960 cnt := 0;
961 while ccidx >= 0 do
962 begin
963 Inc(cnt);
964 ccidx := mCells[ccidx].next;
965 end;
966 if (mcb < cnt) then mcb := cnt;
967 end;
968 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);
969 end;
972 procedure TBodyGridBase.forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
973 var
974 g, f, ccidx: Integer;
975 cc: PGridCell;
976 begin
977 if (body < 0) or (body > High(mProxies)) or not assigned(cb) then exit;
978 for g := 0 to High(mGrid) do
979 begin
980 ccidx := mGrid[g];
981 while (ccidx <> -1) do
982 begin
983 cc := @mCells[ccidx];
984 for f := 0 to GridCellBucketSize-1 do
985 begin
986 if (cc.bodies[f] = -1) then break;
987 if (cc.bodies[f] = body) then cb((g mod mWidth)*mTileSize+mMinX, (g div mWidth)*mTileSize+mMinY);
988 end;
989 // next cell
990 ccidx := cc.next;
991 end;
992 end;
993 end;
996 function TBodyGridBase.forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
997 var
998 f, ccidx: Integer;
999 cc: PGridCell;
1000 begin
1001 result := Default(ITP);
1002 if not assigned(cb) then exit;
1003 Dec(x, mMinX);
1004 Dec(y, mMinY);
1005 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y > mHeight*mTileSize) then exit;
1006 ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1007 while (ccidx <> -1) do
1008 begin
1009 cc := @mCells[ccidx];
1010 for f := 0 to GridCellBucketSize-1 do
1011 begin
1012 if (cc.bodies[f] = -1) then break;
1013 if cb(mProxies[cc.bodies[f]].mObj, mProxies[cc.bodies[f]].mTag) then begin result := mProxies[cc.bodies[f]].mObj; exit; end;
1014 end;
1015 // next cell
1016 ccidx := cc.next;
1017 end;
1018 end;
1021 // ////////////////////////////////////////////////////////////////////////// //
1022 function TBodyGridBase.getGridWidthPx (): Integer; inline; begin result := mWidth*mTileSize; end;
1023 function TBodyGridBase.getGridHeightPx (): Integer; inline; begin result := mHeight*mTileSize; end;
1026 function TBodyGridBase.insideGrid (x, y: Integer): Boolean; inline;
1027 begin
1028 // fix coords
1029 Dec(x, mMinX);
1030 Dec(y, mMinY);
1031 result := (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize);
1032 end;
1035 function TBodyGridBase.getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
1036 begin
1037 if (body >= 0) and (body < Length(mProxies)) then
1038 begin
1039 with mProxies[body] do begin rx := mX; ry := mY; end;
1040 result := true;
1041 end
1042 else
1043 begin
1044 rx := 0;
1045 ry := 0;
1046 result := false;
1047 end;
1048 end;
1051 function TBodyGridBase.getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
1052 begin
1053 if (body >= 0) and (body < Length(mProxies)) then
1054 begin
1055 with mProxies[body] do begin rw := mWidth; rh := mHeight; end;
1056 result := true;
1057 end
1058 else
1059 begin
1060 rw := 0;
1061 rh := 0;
1062 result := false;
1063 end;
1064 end;
1067 function TBodyGridBase.getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
1068 begin
1069 if (body >= 0) and (body < Length(mProxies)) then
1070 begin
1071 with mProxies[body] do begin rx := mX; ry := mY; rw := mWidth; rh := mHeight; end;
1072 result := true;
1073 end
1074 else
1075 begin
1076 rx := 0;
1077 ry := 0;
1078 rw := 0;
1079 rh := 0;
1080 result := false;
1081 end;
1082 end;
1086 // ////////////////////////////////////////////////////////////////////////// //
1087 function TBodyGridBase.getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
1088 begin
1089 if (pid >= 0) and (pid < Length(mProxies)) then result := ((mProxies[pid].mTag and TagDisabled) = 0) else result := false;
1090 end;
1093 procedure TBodyGridBase.setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
1094 begin
1095 if (pid >= 0) and (pid < Length(mProxies)) then
1096 begin
1097 if val then
1098 begin
1099 mProxies[pid].mTag := mProxies[pid].mTag and not TagDisabled;
1100 end
1101 else
1102 begin
1103 mProxies[pid].mTag := mProxies[pid].mTag or TagDisabled;
1104 end;
1105 end;
1106 end;
1109 function TBodyGridBase.getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
1110 begin
1111 if (idx >= 0) and (idx < Length(mProxies)) then result := @mProxies[idx] else result := nil;
1112 end;
1115 // ////////////////////////////////////////////////////////////////////////// //
1116 function TBodyGridBase.allocCell (): Integer;
1117 var
1118 idx: Integer;
1119 pc: PGridCell;
1120 begin
1121 if (mFreeCell < 0) then
1122 begin
1123 // no free cells, want more
1124 mFreeCell := Length(mCells);
1125 SetLength(mCells, mFreeCell+32768); // arbitrary number
1126 for idx := mFreeCell to High(mCells) do
1127 begin
1128 mCells[idx].bodies[0] := -1;
1129 mCells[idx].bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
1130 mCells[idx].next := idx+1;
1131 end;
1132 mCells[High(mCells)].next := -1; // last cell
1133 end;
1134 result := mFreeCell;
1135 pc := @mCells[result];
1136 mFreeCell := pc.next;
1137 pc.next := -1;
1138 Inc(mUsedCells);
1139 //e_WriteLog(Format('grid: allocated new cell #%d (total: %d)', [result, mUsedCells]), MSG_NOTIFY);
1140 end;
1143 procedure TBodyGridBase.freeCell (idx: Integer);
1144 begin
1145 if (idx >= 0) and (idx < Length(mCells)) then
1146 begin
1147 with mCells[idx] do
1148 begin
1149 bodies[0] := -1;
1150 bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
1151 next := mFreeCell;
1152 end;
1153 mFreeCell := idx;
1154 Dec(mUsedCells);
1155 end;
1156 end;
1159 // ////////////////////////////////////////////////////////////////////////// //
1160 function TBodyGridBase.allocProxy (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer): TBodyProxyId;
1161 var
1162 olen, idx: Integer;
1163 px: PBodyProxyRec;
1164 begin
1165 if (mProxyFree = -1) then
1166 begin
1167 // no free proxies, resize list
1168 olen := Length(mProxies);
1169 SetLength(mProxies, olen+8192); // arbitrary number
1170 for idx := olen to High(mProxies) do mProxies[idx].nextLink := idx+1;
1171 mProxies[High(mProxies)].nextLink := -1;
1172 mProxyFree := olen;
1173 end;
1174 // get one from list
1175 result := mProxyFree;
1176 px := @mProxies[result];
1177 mProxyFree := px.nextLink;
1178 px.setup(aX, aY, aWidth, aHeight, aObj, aTag);
1179 // add to used list
1180 px.nextLink := -1;
1181 // statistics
1182 Inc(mProxyCount);
1183 if (mProxyMaxCount < mProxyCount) then mProxyMaxCount := mProxyCount;
1184 end;
1186 procedure TBodyGridBase.freeProxy (body: TBodyProxyId);
1187 begin
1188 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1189 if (mProxyCount = 0) then raise Exception.Create('wutafuuuuu in grid (no allocated proxies, what i should free now?)');
1190 // add to free list
1191 mProxies[body].mObj := nil;
1192 mProxies[body].nextLink := mProxyFree;
1193 mProxyFree := body;
1194 Dec(mProxyCount);
1195 end;
1198 // ////////////////////////////////////////////////////////////////////////// //
1199 function TBodyGridBase.forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
1200 const
1201 tsize = mTileSize;
1202 var
1203 gx, gy: Integer;
1204 gw, gh: Integer;
1205 begin
1206 result := false;
1207 if (w < 1) or (h < 1) or not assigned(cb) then exit;
1208 // fix coords
1209 Dec(x, mMinX);
1210 Dec(y, mMinY);
1211 // go on
1212 if (x+w <= 0) or (y+h <= 0) then exit;
1213 gw := mWidth;
1214 gh := mHeight;
1215 //tsize := mTileSize;
1216 if (x >= gw*tsize) or (y >= gh*tsize) then exit;
1217 for gy := y div tsize to (y+h-1) div tsize do
1218 begin
1219 if (gy < 0) then continue;
1220 if (gy >= gh) then break;
1221 for gx := x div tsize to (x+w-1) div tsize do
1222 begin
1223 if (gx < 0) then continue;
1224 if (gx >= gw) then break;
1225 result := cb(gy*gw+gx, bodyId);
1226 if result then exit;
1227 end;
1228 end;
1229 end;
1232 // ////////////////////////////////////////////////////////////////////////// //
1233 function TBodyGridBase.inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
1234 var
1235 ccidx: Integer;
1236 pc: Integer;
1237 pi: PGridCell;
1238 f: Integer;
1239 begin
1240 result := false; // never stop
1241 // add body to the given grid cell
1242 pc := mGrid[grida];
1243 if (pc <> -1) then
1244 begin
1245 {$IF DEFINED(D2F_DEBUG)}
1246 ccidx := pc;
1247 while (ccidx <> -1) do
1248 begin
1249 pi := @mCells[ccidx];
1250 for f := 0 to GridCellBucketSize-1 do
1251 begin
1252 if (pi.bodies[f] = -1) then break;
1253 if (pi.bodies[f] = bodyId) then raise Exception.Create('trying to insert already inserted proxy');
1254 end;
1255 ccidx := pi.next;
1256 end;
1257 {$ENDIF}
1258 ccidx := pc;
1259 while (ccidx <> -1) do
1260 begin
1261 pi := @mCells[ccidx];
1262 // check "has room" flag
1263 if (pi.bodies[GridCellBucketSize-1] = -1) then
1264 begin
1265 // can add here
1266 for f := 0 to GridCellBucketSize-1 do
1267 begin
1268 if (pi.bodies[f] = -1) then
1269 begin
1270 pi.bodies[f] := bodyId;
1271 if (f+1 < GridCellBucketSize) then pi.bodies[f+1] := -1;
1272 exit;
1273 end;
1274 end;
1275 raise Exception.Create('internal error in grid inserter');
1276 end;
1277 // no room, go to next cell in list (if there is any)
1278 ccidx := pi.next;
1279 end;
1280 // no room in cells, add new cell to list
1281 end;
1282 // either no room, or no cell at all
1283 ccidx := allocCell();
1284 pi := @mCells[ccidx];
1285 pi.bodies[0] := bodyId;
1286 pi.bodies[1] := -1;
1287 pi.next := pc;
1288 mGrid[grida] := ccidx;
1289 end;
1291 procedure TBodyGridBase.insertInternal (body: TBodyProxyId);
1292 var
1293 px: PBodyProxyRec;
1294 begin
1295 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1296 px := @mProxies[body];
1297 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, inserter, body);
1298 end;
1301 // assume that we cannot have one object added to bucket twice
1302 function TBodyGridBase.remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
1303 var
1304 f, c: Integer;
1305 pidx, ccidx: Integer;
1306 pc: PGridCell;
1307 begin
1308 result := false; // never stop
1309 // find and remove cell
1310 pidx := -1; // previous cell index
1311 ccidx := mGrid[grida]; // current cell index
1312 while (ccidx <> -1) do
1313 begin
1314 pc := @mCells[ccidx];
1315 for f := 0 to GridCellBucketSize-1 do
1316 begin
1317 if (pc.bodies[f] = bodyId) then
1318 begin
1319 // i found her!
1320 if (f = 0) and (pc.bodies[1] = -1) then
1321 begin
1322 // this cell contains no elements, remove it
1323 if (pidx = -1) then mGrid[grida] := pc.next else mCells[pidx].next := pc.next;
1324 freeCell(ccidx);
1325 exit;
1326 end;
1327 // remove element from bucket
1328 for c := f to GridCellBucketSize-2 do
1329 begin
1330 pc.bodies[c] := pc.bodies[c+1];
1331 if (pc.bodies[c] = -1) then break;
1332 end;
1333 pc.bodies[GridCellBucketSize-1] := -1; // "has free room" flag
1334 exit;
1335 end;
1336 end;
1337 pidx := ccidx;
1338 ccidx := pc.next;
1339 end;
1340 end;
1342 procedure TBodyGridBase.removeInternal (body: TBodyProxyId);
1343 var
1344 px: PBodyProxyRec;
1345 begin
1346 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1347 px := @mProxies[body];
1348 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1349 end;
1352 // ////////////////////////////////////////////////////////////////////////// //
1353 function TBodyGridBase.insertBody (aObj: ITP; aX, aY, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
1354 begin
1355 aTag := aTag and TagFullMask;
1356 result := allocProxy(aX, aY, aWidth, aHeight, aObj, aTag);
1357 insertInternal(result);
1358 end;
1361 procedure TBodyGridBase.removeBody (body: TBodyProxyId);
1362 begin
1363 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1364 removeInternal(body);
1365 freeProxy(body);
1366 end;
1369 // ////////////////////////////////////////////////////////////////////////// //
1370 procedure TBodyGridBase.moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
1371 var
1372 px: PBodyProxyRec;
1373 x0, y0, w, h: Integer;
1374 begin
1375 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1376 px := @mProxies[body];
1377 x0 := px.mX;
1378 y0 := px.mY;
1379 w := px.mWidth;
1380 h := px.mHeight;
1381 {$IF DEFINED(D2F_DEBUG_MOVER)}
1382 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);
1383 {$ENDIF}
1384 if (nx = x0) and (ny = y0) and (nw = w) and (nh = h) then exit;
1385 // map -> grid
1386 Dec(x0, mMinX);
1387 Dec(y0, mMinY);
1388 Dec(nx, mMinX);
1389 Dec(ny, mMinY);
1390 // did any corner crossed tile boundary?
1391 if (x0 div mTileSize <> nx div mTileSize) or
1392 (y0 div mTileSize <> ny div mTileSize) or
1393 ((x0+w) div mTileSize <> (nx+nw) div mTileSize) or
1394 ((y0+h) div mTileSize <> (ny+nh) div mTileSize) then
1395 begin
1396 removeInternal(body);
1397 px.mX := nx+mMinX;
1398 px.mY := ny+mMinY;
1399 px.mWidth := nw;
1400 px.mHeight := nh;
1401 insertInternal(body);
1402 end
1403 else
1404 begin
1405 px.mX := nx+mMinX;
1406 px.mY := ny+mMinY;
1407 px.mWidth := nw;
1408 px.mHeight := nh;
1409 end;
1410 end;
1412 //TODO: optimize for horizontal/vertical moves
1413 procedure TBodyGridBase.moveBody (body: TBodyProxyId; nx, ny: Integer);
1414 var
1415 px: PBodyProxyRec;
1416 x0, y0: Integer;
1417 ogx0, ogx1, ogy0, ogy1: Integer; // old grid rect
1418 ngx0, ngx1, ngy0, ngy1: Integer; // new grid rect
1419 gx, gy: Integer;
1420 gw, gh: Integer;
1421 pw, ph: Integer;
1422 begin
1423 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1424 // check if tile coords was changed
1425 px := @mProxies[body];
1426 x0 := px.mX;
1427 y0 := px.mY;
1428 if (nx = x0) and (ny = y0) then exit;
1429 // map -> grid
1430 Dec(x0, mMinX);
1431 Dec(y0, mMinY);
1432 Dec(nx, mMinX);
1433 Dec(ny, mMinY);
1434 // check for heavy work
1435 pw := px.mWidth;
1436 ph := px.mHeight;
1437 ogx0 := x0 div mTileSize;
1438 ogy0 := y0 div mTileSize;
1439 ngx0 := nx div mTileSize;
1440 ngy0 := ny div mTileSize;
1441 ogx1 := (x0+pw-1) div mTileSize;
1442 ogy1 := (y0+ph-1) div mTileSize;
1443 ngx1 := (nx+pw-1) div mTileSize;
1444 ngy1 := (ny+ph-1) div mTileSize;
1445 {$IF DEFINED(D2F_DEBUG_MOVER)}
1446 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);
1447 {$ENDIF}
1448 if (ogx0 <> ngx0) or (ogy0 <> ngy0) or (ogx1 <> ngx1) or (ogy1 <> ngy1) then
1449 begin
1450 // crossed tile boundary, do heavy work
1451 gw := mWidth;
1452 gh := mHeight;
1453 // cycle with old rect, remove body where it is necessary
1454 // optimized for horizontal moves
1455 {$IF DEFINED(D2F_DEBUG_MOVER)}
1456 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);
1457 {$ENDIF}
1458 // remove stale marks
1459 if not ((ogy0 >= gh) or (ogy1 < 0)) and
1460 not ((ogx0 >= gw) or (ogx1 < 0)) then
1461 begin
1462 if (ogx0 < 0) then ogx0 := 0;
1463 if (ogy0 < 0) then ogy0 := 0;
1464 if (ogx1 > gw-1) then ogx1 := gw-1;
1465 if (ogy1 > gh-1) then ogy1 := gh-1;
1466 {$IF DEFINED(D2F_DEBUG_MOVER)}
1467 e_WriteLog(Format(' norm og:(%d,%d)-(%d,%d)', [ogx0, ogy0, ogx1, ogy1]), MSG_NOTIFY);
1468 {$ENDIF}
1469 for gx := ogx0 to ogx1 do
1470 begin
1471 if (gx < ngx0) or (gx > ngx1) then
1472 begin
1473 // this column is completely outside of new rect
1474 for gy := ogy0 to ogy1 do
1475 begin
1476 {$IF DEFINED(D2F_DEBUG_MOVER)}
1477 e_WriteLog(Format(' remove0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1478 {$ENDIF}
1479 remover(gy*gw+gx, body);
1480 end;
1481 end
1482 else
1483 begin
1484 // heavy checks
1485 for gy := ogy0 to ogy1 do
1486 begin
1487 if (gy < ngy0) or (gy > ngy1) then
1488 begin
1489 {$IF DEFINED(D2F_DEBUG_MOVER)}
1490 e_WriteLog(Format(' remove1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1491 {$ENDIF}
1492 remover(gy*gw+gx, body);
1493 end;
1494 end;
1495 end;
1496 end;
1497 end;
1498 // cycle with new rect, add body where it is necessary
1499 if not ((ngy0 >= gh) or (ngy1 < 0)) and
1500 not ((ngx0 >= gw) or (ngx1 < 0)) then
1501 begin
1502 if (ngx0 < 0) then ngx0 := 0;
1503 if (ngy0 < 0) then ngy0 := 0;
1504 if (ngx1 > gw-1) then ngx1 := gw-1;
1505 if (ngy1 > gh-1) then ngy1 := gh-1;
1506 {$IF DEFINED(D2F_DEBUG_MOVER)}
1507 e_WriteLog(Format(' norm ng:(%d,%d)-(%d,%d)', [ngx0, ngy0, ngx1, ngy1]), MSG_NOTIFY);
1508 {$ENDIF}
1509 for gx := ngx0 to ngx1 do
1510 begin
1511 if (gx < ogx0) or (gx > ogx1) then
1512 begin
1513 // this column is completely outside of old rect
1514 for gy := ngy0 to ngy1 do
1515 begin
1516 {$IF DEFINED(D2F_DEBUG_MOVER)}
1517 e_WriteLog(Format(' insert0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1518 {$ENDIF}
1519 inserter(gy*gw+gx, body);
1520 end;
1521 end
1522 else
1523 begin
1524 // heavy checks
1525 for gy := ngy0 to ngy1 do
1526 begin
1527 if (gy < ogy0) or (gy > ogy1) then
1528 begin
1529 {$IF DEFINED(D2F_DEBUG_MOVER)}
1530 e_WriteLog(Format(' insert1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1531 {$ENDIF}
1532 inserter(gy*gw+gx, body);
1533 end;
1534 end;
1535 end;
1536 end;
1537 end;
1538 // done
1539 end
1540 else
1541 begin
1542 {$IF DEFINED(D2F_DEBUG_MOVER)}
1543 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);
1544 {$ENDIF}
1545 end;
1546 // update coordinates
1547 px.mX := nx+mMinX;
1548 px.mY := ny+mMinY;
1549 end;
1551 procedure TBodyGridBase.resizeBody (body: TBodyProxyId; nw, nh: Integer);
1552 var
1553 px: PBodyProxyRec;
1554 x0, y0, w, h: Integer;
1555 begin
1556 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1557 // check if tile coords was changed
1558 px := @mProxies[body];
1559 x0 := px.mX-mMinX;
1560 y0 := px.mY-mMinY;
1561 w := px.mWidth;
1562 h := px.mHeight;
1563 {$IF DEFINED(D2F_DEBUG_MOVER)}
1564 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);
1565 {$ENDIF}
1566 if ((x0+w) div mTileSize <> (x0+nw) div mTileSize) or
1567 ((y0+h) div mTileSize <> (y0+nh) div mTileSize) then
1568 begin
1569 // crossed tile boundary, do heavy work
1570 removeInternal(body);
1571 px.mWidth := nw;
1572 px.mHeight := nh;
1573 insertInternal(body);
1574 end
1575 else
1576 begin
1577 // nothing to do with the grid, just fix size
1578 px.mWidth := nw;
1579 px.mHeight := nh;
1580 end;
1581 end;
1584 // ////////////////////////////////////////////////////////////////////////// //
1585 function TBodyGridBase.atCellInPoint (x, y: Integer): TAtPointEnumerator;
1586 var
1587 ccidx: Integer = -1;
1588 begin
1589 Dec(x, mMinX);
1590 Dec(y, mMinY);
1591 if (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize) then ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1592 result := TAtPointEnumerator.Create(mCells, ccidx, getProxyById);
1593 end;
1596 // ////////////////////////////////////////////////////////////////////////// //
1597 // no callback: return `true` on the first hit
1598 function TBodyGridBase.forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
1599 var
1600 f: Integer;
1601 idx, curci: Integer;
1602 cc: PGridCell = nil;
1603 px: PBodyProxyRec;
1604 lq: LongWord;
1605 ptag: Integer;
1606 begin
1607 result := Default(ITP);
1608 if (exittag <> nil) then exittag^ := 0;
1609 tagmask := tagmask and TagFullMask;
1610 if (tagmask = 0) then exit;
1612 {$IF DEFINED(D2F_DEBUG_XXQ)}
1613 if (assigned(cb)) then e_WriteLog(Format('0: grid pointquery: (%d,%d)', [x, y]), MSG_NOTIFY);
1614 {$ENDIF}
1616 // make coords (0,0)-based
1617 Dec(x, mMinX);
1618 Dec(y, mMinY);
1619 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y >= mHeight*mTileSize) then exit;
1621 curci := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1623 {$IF DEFINED(D2F_DEBUG_XXQ)}
1624 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);
1625 {$ENDIF}
1627 // restore coords
1628 Inc(x, mMinX);
1629 Inc(y, mMinY);
1631 // increase query counter
1632 Inc(mLastQuery);
1633 if (mLastQuery = 0) then
1634 begin
1635 // just in case of overflow
1636 mLastQuery := 1;
1637 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1638 end;
1639 lq := mLastQuery;
1641 {$IF DEFINED(D2F_DEBUG_XXQ)}
1642 if (assigned(cb)) then e_WriteLog(Format('2: grid pointquery: (%d,%d); lq=%u', [x, y, lq]), MSG_NOTIFY);
1643 {$ENDIF}
1645 while (curci <> -1) do
1646 begin
1647 {$IF DEFINED(D2F_DEBUG_XXQ)}
1648 if (assigned(cb)) then e_WriteLog(Format(' cell #%d', [curci]), MSG_NOTIFY);
1649 {$ENDIF}
1650 cc := @mCells[curci];
1651 for f := 0 to GridCellBucketSize-1 do
1652 begin
1653 if (cc.bodies[f] = -1) then break;
1654 px := @mProxies[cc.bodies[f]];
1655 {$IF DEFINED(D2F_DEBUG_XXQ)}
1656 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);
1657 {$ENDIF}
1658 // shit. has to do it this way, so i can change tag in callback
1659 if (px.mQueryMark <> lq) then
1660 begin
1661 px.mQueryMark := lq;
1662 ptag := px.mTag;
1663 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
1664 (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
1665 begin
1666 if assigned(cb) then
1667 begin
1668 if cb(px.mObj, ptag) then
1669 begin
1670 result := px.mObj;
1671 if (exittag <> nil) then exittag^ := ptag;
1672 exit;
1673 end;
1674 end
1675 else
1676 begin
1677 result := px.mObj;
1678 if (exittag <> nil) then exittag^ := ptag;
1679 exit;
1680 end;
1681 end;
1682 end;
1683 end;
1684 curci := cc.next;
1685 end;
1686 end;
1689 // ////////////////////////////////////////////////////////////////////////// //
1690 // no callback: return `true` on the first hit
1691 function TBodyGridBase.forEachInAABB (x, y, w, h: Integer; cb: TGridQueryCB; tagmask: Integer=-1; allowDisabled: Boolean=false): ITP;
1692 const
1693 tsize = mTileSize;
1694 var
1695 idx: Integer;
1696 gx, gy: Integer;
1697 curci: Integer;
1698 f: Integer;
1699 cc: PGridCell = nil;
1700 px: PBodyProxyRec;
1701 lq: LongWord;
1702 gw: Integer;
1703 x0, y0: Integer;
1704 ptag: Integer;
1705 begin
1706 result := Default(ITP);
1707 if (w < 1) or (h < 1) then exit;
1708 tagmask := tagmask and TagFullMask;
1709 if (tagmask = 0) then exit;
1711 x0 := x;
1712 y0 := y;
1714 // fix coords
1715 Dec(x, mMinX);
1716 Dec(y, mMinY);
1718 gw := mWidth;
1719 //tsize := mTileSize;
1721 if (x+w <= 0) or (y+h <= 0) then exit;
1722 if (x >= gw*tsize) or (y >= mHeight*tsize) then exit;
1724 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1725 mInQuery := true;
1727 // increase query counter
1728 Inc(mLastQuery);
1729 if (mLastQuery = 0) then
1730 begin
1731 // just in case of overflow
1732 mLastQuery := 1;
1733 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1734 end;
1735 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
1736 lq := mLastQuery;
1738 // go on
1739 for gy := y div tsize to (y+h-1) div tsize do
1740 begin
1741 if (gy < 0) then continue;
1742 if (gy >= mHeight) then break;
1743 for gx := x div tsize to (x+w-1) div tsize do
1744 begin
1745 if (gx < 0) then continue;
1746 if (gx >= gw) then break;
1747 // process cells
1748 curci := mGrid[gy*gw+gx];
1749 while (curci <> -1) do
1750 begin
1751 cc := @mCells[curci];
1752 for f := 0 to GridCellBucketSize-1 do
1753 begin
1754 if (cc.bodies[f] = -1) then break;
1755 px := @mProxies[cc.bodies[f]];
1756 // shit. has to do it this way, so i can change tag in callback
1757 if (px.mQueryMark = lq) then continue;
1758 px.mQueryMark := lq;
1759 ptag := px.mTag;
1760 if (not allowDisabled) and ((ptag and TagDisabled) <> 0) then continue;
1761 if ((ptag and tagmask) = 0) then continue;
1762 if (x0 >= px.mX+px.mWidth) or (y0 >= px.mY+px.mHeight) then continue;
1763 if (x0+w <= px.mX) or (y0+h <= px.mY) then continue;
1764 if assigned(cb) then
1765 begin
1766 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
1767 end
1768 else
1769 begin
1770 result := px.mObj;
1771 mInQuery := false;
1772 exit;
1773 end;
1774 end;
1775 curci := cc.next;
1776 end;
1777 end;
1778 end;
1780 mInQuery := false;
1781 end;
1784 // ////////////////////////////////////////////////////////////////////////// //
1785 // no callback: return `true` on the nearest hit
1786 function TBodyGridBase.traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
1787 var
1788 ex, ey: Integer;
1789 begin
1790 result := traceRayOld(ex, ey, x0, y0, x1, y1, cb, tagmask);
1791 end;
1794 // no callback: return `true` on the nearest hit
1795 // you are not supposed to understand this
1796 function TBodyGridBase.traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
1797 const
1798 tsize = mTileSize;
1799 var
1800 wx0, wy0, wx1, wy1: Integer; // window coordinates
1801 stx, sty: Integer; // "steps" for x and y axes
1802 dsx, dsy: Integer; // "lengthes" for x and y axes
1803 dx2, dy2: Integer; // "double lengthes" for x and y axes
1804 xd, yd: Integer; // current coord
1805 e: Integer; // "error" (as in bresenham algo)
1806 rem: Integer;
1807 term: Integer;
1808 xptr, yptr: PInteger;
1809 xfixed: Boolean;
1810 temp: Integer;
1811 prevx, prevy: Integer;
1812 lastDistSq: Integer;
1813 ccidx, curci: Integer;
1814 hasUntried: Boolean;
1815 lastGA: Integer = -1;
1816 ga, x, y: Integer;
1817 lastObj: ITP;
1818 wasHit: Boolean = false;
1819 gw, gh, minx, miny, maxx, maxy: Integer;
1820 cc: PGridCell;
1821 px: PBodyProxyRec;
1822 lq: LongWord;
1823 f, ptag, distSq: Integer;
1824 x0, y0, x1, y1: Integer;
1825 //swapped: Boolean = false; // true: xd is yd, and vice versa
1826 // horizontal walker
1827 {$IFDEF GRID_USE_ORTHO_ACCEL}
1828 wklen, wkstep: Integer;
1829 //wksign: Integer;
1830 hopt: Boolean;
1831 {$ENDIF}
1832 // skipper
1833 xdist, ydist: Integer;
1834 begin
1835 result := Default(ITP);
1836 lastObj := Default(ITP);
1837 tagmask := tagmask and TagFullMask;
1838 ex := ax1; // why not?
1839 ey := ay1; // why not?
1840 if (tagmask = 0) then exit;
1842 if (ax0 = ax1) and (ay0 = ay1) then
1843 begin
1844 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
1845 if (result <> nil) then
1846 begin
1847 if assigned(cb) and not cb(result, ptag, ax0, ay0, ax0, ay0) then result := Default(ITP);
1848 end;
1849 exit;
1850 end;
1852 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
1854 gw := mWidth;
1855 gh := mHeight;
1856 minx := mMinX;
1857 miny := mMinY;
1858 maxx := gw*tsize-1;
1859 maxy := gh*tsize-1;
1861 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1862 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);
1863 {$ENDIF}
1865 x0 := ax0;
1866 y0 := ay0;
1867 x1 := ax1;
1868 y1 := ay1;
1870 // offset query coords to (0,0)-based
1871 Dec(x0, minx);
1872 Dec(y0, miny);
1873 Dec(x1, minx);
1874 Dec(y1, miny);
1876 // clip rectange
1877 wx0 := 0;
1878 wy0 := 0;
1879 wx1 := maxx;
1880 wy1 := maxy;
1882 // horizontal setup
1883 if (x0 < x1) then
1884 begin
1885 // from left to right
1886 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
1887 stx := 1; // going right
1888 end
1889 else
1890 begin
1891 // from right to left
1892 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
1893 stx := -1; // going left
1894 x0 := -x0;
1895 x1 := -x1;
1896 wx0 := -wx0;
1897 wx1 := -wx1;
1898 swapInt(wx0, wx1);
1899 end;
1901 // vertical setup
1902 if (y0 < y1) then
1903 begin
1904 // from top to bottom
1905 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
1906 sty := 1; // going down
1907 end
1908 else
1909 begin
1910 // from bottom to top
1911 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
1912 sty := -1; // going up
1913 y0 := -y0;
1914 y1 := -y1;
1915 wy0 := -wy0;
1916 wy1 := -wy1;
1917 swapInt(wy0, wy1);
1918 end;
1920 dsx := x1-x0;
1921 dsy := y1-y0;
1923 if (dsx < dsy) then
1924 begin
1925 //swapped := true;
1926 xptr := @yd;
1927 yptr := @xd;
1928 swapInt(x0, y0);
1929 swapInt(x1, y1);
1930 swapInt(dsx, dsy);
1931 swapInt(wx0, wy0);
1932 swapInt(wx1, wy1);
1933 swapInt(stx, sty);
1934 end
1935 else
1936 begin
1937 xptr := @xd;
1938 yptr := @yd;
1939 end;
1941 dx2 := 2*dsx;
1942 dy2 := 2*dsy;
1943 xd := x0;
1944 yd := y0;
1945 e := 2*dsy-dsx;
1946 term := x1;
1948 xfixed := false;
1949 if (y0 < wy0) then
1950 begin
1951 // clip at top
1952 temp := dx2*(wy0-y0)-dsx;
1953 xd += temp div dy2;
1954 rem := temp mod dy2;
1955 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
1956 if (xd+1 >= wx0) then
1957 begin
1958 yd := wy0;
1959 e -= rem+dsx;
1960 if (rem > 0) then begin Inc(xd); e += dy2; end;
1961 xfixed := true;
1962 end;
1963 end;
1965 if (not xfixed) and (x0 < wx0) then
1966 begin
1967 // clip at left
1968 temp := dy2*(wx0-x0);
1969 yd += temp div dx2;
1970 rem := temp mod dx2;
1971 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
1972 xd := wx0;
1973 e += rem;
1974 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
1975 end;
1977 if (y1 > wy1) then
1978 begin
1979 // clip at bottom
1980 temp := dx2*(wy1-y0)+dsx;
1981 term := x0+temp div dy2;
1982 rem := temp mod dy2;
1983 if (rem = 0) then Dec(term);
1984 end;
1986 if (term > wx1) then term := wx1; // clip at right
1988 Inc(term); // draw last point
1989 //if (term = xd) then exit; // this is the only point, get out of here
1991 if (sty = -1) then yd := -yd;
1992 if (stx = -1) then begin xd := -xd; term := -term; end;
1993 dx2 -= dy2;
1995 // first move, to skip starting point
1996 // DON'T DO THIS! loop will take care of that
1997 if (xd = term) then
1998 begin
1999 //FIXME!
2000 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2001 if (result <> nil) then
2002 begin
2003 if assigned(cb) then
2004 begin
2005 if cb(result, ptag, ax0, ay0, ax0, ay0) then
2006 begin
2007 ex := ax0;
2008 ey := ay0;
2009 end
2010 else
2011 begin
2012 result := nil;
2013 end;
2014 end
2015 else
2016 begin
2017 ex := ax0;
2018 ey := ay0;
2019 end;
2020 end;
2021 exit;
2022 end;
2024 prevx := xptr^+minx;
2025 prevy := yptr^+miny;
2026 (*
2027 // move coords
2028 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2029 xd += stx;
2030 // done?
2031 if (xd = term) then exit;
2032 *)
2034 {$IF DEFINED(D2F_DEBUG)}
2035 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*tsize) and (yptr^ >= gh*tsize) then raise Exception.Create('raycaster internal error (0)');
2036 {$ENDIF}
2037 // DON'T DO THIS! loop will take care of that
2038 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
2039 //ccidx := mGrid[lastGA];
2041 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2042 //if assigned(dbgRayTraceTileHitCB) then e_WriteLog('1:TRACING!', MSG_NOTIFY);
2043 {$ENDIF}
2045 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
2047 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2048 mInQuery := true;
2050 // increase query counter
2051 Inc(mLastQuery);
2052 if (mLastQuery = 0) then
2053 begin
2054 // just in case of overflow
2055 mLastQuery := 1;
2056 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2057 end;
2058 lq := mLastQuery;
2060 {$IFDEF GRID_USE_ORTHO_ACCEL}
2061 // if this is strict horizontal/vertical trace, use optimized codepath
2062 if (ax0 = ax1) or (ay0 = ay1) then
2063 begin
2064 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
2065 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
2066 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
2067 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
2068 hopt := (ay0 = ay1); // horizontal?
2069 if (stx < 0) then begin {wksign := -1;} wklen := -(term-xd); end else begin {wksign := 1;} wklen := term-xd; end;
2070 {$IF DEFINED(D2F_DEBUG)}
2071 if dbgShowTraceLog then e_LogWritefln('optimized htrace; wklen=%d', [wklen]);
2072 {$ENDIF}
2073 ga := (yptr^ div tsize)*gw+(xptr^ div tsize);
2074 // one of those will never change
2075 x := xptr^+minx;
2076 y := yptr^+miny;
2077 while (wklen > 0) do
2078 begin
2079 {$IF DEFINED(D2F_DEBUG)}
2080 if dbgShowTraceLog then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; y=%d; y=%d', [ga, xptr^+minx, yptr^+miny, y, ay0]);
2081 {$ENDIF}
2082 // new tile?
2083 if (ga <> lastGA) then
2084 begin
2085 lastGA := ga;
2086 ccidx := mGrid[lastGA];
2087 // convert coords to map (to avoid ajdusting coords inside the loop)
2088 if hopt then x := xptr^+minx else y := yptr^+miny;
2089 while (ccidx <> -1) do
2090 begin
2091 cc := @mCells[ccidx];
2092 for f := 0 to GridCellBucketSize-1 do
2093 begin
2094 if (cc.bodies[f] = -1) then break;
2095 px := @mProxies[cc.bodies[f]];
2096 ptag := px.mTag;
2097 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) and
2098 // constant coord should be inside
2099 ((hopt and (y >= px.y0) and (y <= px.y1)) or
2100 ((not hopt) and (x >= px.x0) and (x <= px.x1))) then
2101 begin
2102 px.mQueryMark := lq; // mark as processed
2103 // inside the proxy?
2104 if (hopt and (x > px.x0) and (x < px.x1)) or
2105 ((not hopt) and (y > px.y0) and (y < px.y1)) then
2106 begin
2107 // setup prev[xy]
2108 if assigned(cb) then
2109 begin
2110 if cb(px.mObj, ptag, x, y, x, y) then
2111 begin
2112 result := px.mObj;
2113 ex := x;
2114 ey := y;
2115 mInQuery := false;
2116 exit;
2117 end;
2118 end
2119 else
2120 begin
2121 distSq := distanceSq(ax0, ay0, x, y);
2122 {$IF DEFINED(D2F_DEBUG)}
2123 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]);
2124 {$ENDIF}
2125 if (distSq < lastDistSq) then
2126 begin
2127 ex := x;
2128 ey := y;
2129 result := px.mObj;
2130 mInQuery := false;
2131 exit;
2132 end;
2133 end;
2134 continue;
2135 end;
2136 // remember this hitpoint if it is nearer than an old one
2137 // setup prev[xy]
2138 if hopt then
2139 begin
2140 // horizontal trace
2141 prevy := y;
2142 y := yptr^+miny;
2143 if (stx < 0) then
2144 begin
2145 // going left
2146 if (x < px.x1) then continue; // not on the right edge
2147 x := px.x1;
2148 prevx := x+1;
2149 end
2150 else
2151 begin
2152 // going right
2153 if (x > px.x0) then continue; // not on the left edge
2154 x := px.x0;
2155 prevx := x-1;
2156 end;
2157 end
2158 else
2159 begin
2160 // vertical trace
2161 prevx := x;
2162 x := xptr^+minx;
2163 if (stx < 0) then
2164 begin
2165 // going up
2166 if (y < px.y1) then continue; // not on the bottom edge
2167 y := px.y1;
2168 prevy := x+1;
2169 end
2170 else
2171 begin
2172 // going down
2173 if (y > px.y0) then continue; // not on the top edge
2174 y := px.y0;
2175 prevy := y-1;
2176 end;
2177 end;
2178 if assigned(cb) then
2179 begin
2180 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2181 begin
2182 result := px.mObj;
2183 ex := prevx;
2184 ey := prevy;
2185 mInQuery := false;
2186 exit;
2187 end;
2188 end
2189 else
2190 begin
2191 distSq := distanceSq(ax0, ay0, prevx, prevy);
2192 {$IF DEFINED(D2F_DEBUG)}
2193 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]);
2194 {$ENDIF}
2195 if (distSq < lastDistSq) then
2196 begin
2197 wasHit := true;
2198 lastDistSq := distSq;
2199 ex := prevx;
2200 ey := prevy;
2201 lastObj := px.mObj;
2202 end;
2203 end;
2204 end;
2205 end;
2206 // next cell
2207 ccidx := cc.next;
2208 end;
2209 if wasHit and not assigned(cb) then begin result := lastObj; mInQuery := false; exit; end;
2210 if assigned(cb) and cb(nil, 0, x, y, x, y) then begin result := lastObj; mInQuery := false; exit; end;
2211 end;
2212 // skip to next tile
2213 if hopt then
2214 begin
2215 if (stx > 0) then
2216 begin
2217 // to the right
2218 wkstep := ((xptr^ or (mTileSize-1))+1)-xptr^;
2219 {$IF DEFINED(D2F_DEBUG)}
2220 if dbgShowTraceLog then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2221 {$ENDIF}
2222 if (wkstep >= wklen) then break;
2223 Inc(xptr^, wkstep);
2224 Inc(ga);
2225 end
2226 else
2227 begin
2228 // to the left
2229 wkstep := xptr^-((xptr^ and (not (mTileSize-1)))-1);
2230 {$IF DEFINED(D2F_DEBUG)}
2231 if dbgShowTraceLog then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2232 {$ENDIF}
2233 if (wkstep >= wklen) then break;
2234 Dec(xptr^, wkstep);
2235 Dec(ga);
2236 end;
2237 end
2238 else
2239 begin
2240 if (stx > 0) then
2241 begin
2242 // to the down
2243 wkstep := ((yptr^ or (mTileSize-1))+1)-yptr^;
2244 {$IF DEFINED(D2F_DEBUG)}
2245 if dbgShowTraceLog then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2246 {$ENDIF}
2247 if (wkstep >= wklen) then break;
2248 Inc(yptr^, wkstep);
2249 Inc(ga, mWidth);
2250 end
2251 else
2252 begin
2253 // to the up
2254 wkstep := yptr^-((yptr^ and (not (mTileSize-1)))-1);
2255 {$IF DEFINED(D2F_DEBUG)}
2256 if dbgShowTraceLog then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2257 {$ENDIF}
2258 if (wkstep >= wklen) then break;
2259 Dec(yptr^, wkstep);
2260 Dec(ga, mWidth);
2261 end;
2262 end;
2263 Dec(wklen, wkstep);
2264 end;
2265 // we can travel less than one cell
2266 if wasHit and not assigned(cb) then result := lastObj else begin ex := ax1; ey := ay1; end;
2267 mInQuery := false;
2268 exit;
2269 end;
2270 {$ENDIF}
2272 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2273 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div tsize*tsize)+minx, (yptr^ div tsize*tsize)+miny);
2274 {$ENDIF}
2276 //e_LogWritefln('*********************', []);
2277 ccidx := -1;
2278 // can omit checks
2279 while (xd <> term) do
2280 begin
2281 // check cell(s)
2282 {$IF DEFINED(D2F_DEBUG)}
2283 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*tsize) and (yptr^ >= gh*tsize) then raise Exception.Create('raycaster internal error (0)');
2284 {$ENDIF}
2285 // new tile?
2286 ga := (yptr^ div tsize)*gw+(xptr^ div tsize);
2287 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2288 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);
2289 {$ENDIF}
2290 if (ga <> lastGA) then
2291 begin
2292 // yes
2293 {$IF DEFINED(D2F_DEBUG)}
2294 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div tsize*tsize)+minx, (yptr^ div tsize*tsize)+miny);
2295 {$ENDIF}
2296 if (ccidx <> -1) then
2297 begin
2298 // signal cell completion
2299 if assigned(cb) then
2300 begin
2301 if cb(nil, 0, xptr^+minx, yptr^+miny, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2302 end
2303 else if wasHit then
2304 begin
2305 result := lastObj;
2306 mInQuery := false;
2307 exit;
2308 end;
2309 end;
2310 lastGA := ga;
2311 ccidx := mGrid[lastGA];
2312 end;
2313 // has something to process in this tile?
2314 if (ccidx <> -1) then
2315 begin
2316 // process cell
2317 curci := ccidx;
2318 hasUntried := false; // this will be set to `true` if we have some proxies we still want to process at the next step
2319 // convert coords to map (to avoid ajdusting coords inside the loop)
2320 x := xptr^+minx;
2321 y := yptr^+miny;
2322 // process cell list
2323 while (curci <> -1) do
2324 begin
2325 cc := @mCells[curci];
2326 for f := 0 to GridCellBucketSize-1 do
2327 begin
2328 if (cc.bodies[f] = -1) then break;
2329 px := @mProxies[cc.bodies[f]];
2330 ptag := px.mTag;
2331 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2332 begin
2333 // can we process this proxy?
2334 if (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
2335 begin
2336 px.mQueryMark := lq; // mark as processed
2337 if assigned(cb) then
2338 begin
2339 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2340 begin
2341 result := px.mObj;
2342 ex := prevx;
2343 ey := prevy;
2344 mInQuery := false;
2345 exit;
2346 end;
2347 end
2348 else
2349 begin
2350 // remember this hitpoint if it is nearer than an old one
2351 distSq := distanceSq(ax0, ay0, prevx, prevy);
2352 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2353 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);
2354 {$ENDIF}
2355 if (distSq < lastDistSq) then
2356 begin
2357 wasHit := true;
2358 lastDistSq := distSq;
2359 ex := prevx;
2360 ey := prevy;
2361 lastObj := px.mObj;
2362 end;
2363 end;
2364 end
2365 else
2366 begin
2367 // this is possibly interesting proxy, set "has more to check" flag
2368 hasUntried := true;
2369 end;
2370 end;
2371 end;
2372 // next cell
2373 curci := cc.next;
2374 end;
2375 // still has something interesting in this cell?
2376 if not hasUntried then
2377 begin
2378 // nope, don't process this cell anymore; signal cell completion
2379 ccidx := -1;
2380 if assigned(cb) then
2381 begin
2382 if cb(nil, 0, x, y, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2383 end
2384 else if wasHit then
2385 begin
2386 result := lastObj;
2387 mInQuery := false;
2388 exit;
2389 end;
2390 end;
2391 end;
2392 if (ccidx = -1) then
2393 begin
2394 // move to cell edge, as we have nothing to trace here anymore
2395 if (stx < 0) then xdist := xd and (not (mTileSize-1)) else xdist := xd or (mTileSize-1);
2396 if (sty < 0) then ydist := yd and (not (mTileSize-1)) else ydist := yd or (mTileSize-1);
2397 //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]);
2398 while (xd <> xdist) and (yd <> ydist) do
2399 begin
2400 // step
2401 xd += stx;
2402 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2403 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
2404 if (xd = term) then break;
2405 end;
2406 //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]);
2407 if (xd = term) then break;
2408 end;
2409 //putPixel(xptr^, yptr^);
2410 // move coords
2411 prevx := xptr^+minx;
2412 prevy := yptr^+miny;
2413 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2414 xd += stx;
2415 end;
2416 // we can travel less than one cell
2417 if wasHit and not assigned(cb) then
2418 begin
2419 result := lastObj;
2420 end
2421 else
2422 begin
2423 ex := ax1; // why not?
2424 ey := ay1; // why not?
2425 end;
2427 mInQuery := false;
2428 end;
2431 // ////////////////////////////////////////////////////////////////////////// //
2432 //FIXME! optimize this with real tile walking
2433 function TBodyGridBase.forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
2434 const
2435 tsize = mTileSize;
2436 var
2437 wx0, wy0, wx1, wy1: Integer; // window coordinates
2438 stx, sty: Integer; // "steps" for x and y axes
2439 dsx, dsy: Integer; // "lengthes" for x and y axes
2440 dx2, dy2: Integer; // "double lengthes" for x and y axes
2441 xd, yd: Integer; // current coord
2442 e: Integer; // "error" (as in bresenham algo)
2443 rem: Integer;
2444 term: Integer;
2445 xptr, yptr: PInteger;
2446 xfixed: Boolean;
2447 temp: Integer;
2448 ccidx, curci: Integer;
2449 lastGA: Integer = -1;
2450 ga: Integer;
2451 gw, gh, minx, miny, maxx, maxy: Integer;
2452 cc: PGridCell;
2453 px: PBodyProxyRec;
2454 lq: LongWord;
2455 f, ptag: Integer;
2456 x0, y0, x1, y1: Integer;
2457 //swapped: Boolean = false; // true: xd is yd, and vice versa
2458 // horizontal walker
2459 {$IFDEF GRID_USE_ORTHO_ACCEL}
2460 wklen, wkstep: Integer;
2461 //wksign: Integer;
2462 hopt: Boolean;
2463 {$ENDIF}
2464 // skipper
2465 xdist, ydist: Integer;
2466 begin
2467 log := false;
2468 result := Default(ITP);
2469 tagmask := tagmask and TagFullMask;
2470 if (tagmask = 0) or not assigned(cb) then exit;
2472 if (ax0 = ax1) and (ay0 = ay1) then
2473 begin
2474 result := forEachAtPoint(ax0, ay0, cb, tagmask, @ptag);
2475 exit;
2476 end;
2478 gw := mWidth;
2479 gh := mHeight;
2480 minx := mMinX;
2481 miny := mMinY;
2482 maxx := gw*tsize-1;
2483 maxy := gh*tsize-1;
2485 x0 := ax0;
2486 y0 := ay0;
2487 x1 := ax1;
2488 y1 := ay1;
2490 // offset query coords to (0,0)-based
2491 Dec(x0, minx);
2492 Dec(y0, miny);
2493 Dec(x1, minx);
2494 Dec(y1, miny);
2496 // clip rectange
2497 wx0 := 0;
2498 wy0 := 0;
2499 wx1 := maxx;
2500 wy1 := maxy;
2502 // horizontal setup
2503 if (x0 < x1) then
2504 begin
2505 // from left to right
2506 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
2507 stx := 1; // going right
2508 end
2509 else
2510 begin
2511 // from right to left
2512 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
2513 stx := -1; // going left
2514 x0 := -x0;
2515 x1 := -x1;
2516 wx0 := -wx0;
2517 wx1 := -wx1;
2518 swapInt(wx0, wx1);
2519 end;
2521 // vertical setup
2522 if (y0 < y1) then
2523 begin
2524 // from top to bottom
2525 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
2526 sty := 1; // going down
2527 end
2528 else
2529 begin
2530 // from bottom to top
2531 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
2532 sty := -1; // going up
2533 y0 := -y0;
2534 y1 := -y1;
2535 wy0 := -wy0;
2536 wy1 := -wy1;
2537 swapInt(wy0, wy1);
2538 end;
2540 dsx := x1-x0;
2541 dsy := y1-y0;
2543 if (dsx < dsy) then
2544 begin
2545 //swapped := true;
2546 xptr := @yd;
2547 yptr := @xd;
2548 swapInt(x0, y0);
2549 swapInt(x1, y1);
2550 swapInt(dsx, dsy);
2551 swapInt(wx0, wy0);
2552 swapInt(wx1, wy1);
2553 swapInt(stx, sty);
2554 end
2555 else
2556 begin
2557 xptr := @xd;
2558 yptr := @yd;
2559 end;
2561 dx2 := 2*dsx;
2562 dy2 := 2*dsy;
2563 xd := x0;
2564 yd := y0;
2565 e := 2*dsy-dsx;
2566 term := x1;
2568 xfixed := false;
2569 if (y0 < wy0) then
2570 begin
2571 // clip at top
2572 temp := dx2*(wy0-y0)-dsx;
2573 xd += temp div dy2;
2574 rem := temp mod dy2;
2575 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
2576 if (xd+1 >= wx0) then
2577 begin
2578 yd := wy0;
2579 e -= rem+dsx;
2580 if (rem > 0) then begin Inc(xd); e += dy2; end;
2581 xfixed := true;
2582 end;
2583 end;
2585 if (not xfixed) and (x0 < wx0) then
2586 begin
2587 // clip at left
2588 temp := dy2*(wx0-x0);
2589 yd += temp div dx2;
2590 rem := temp mod dx2;
2591 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
2592 xd := wx0;
2593 e += rem;
2594 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
2595 end;
2597 if (y1 > wy1) then
2598 begin
2599 // clip at bottom
2600 temp := dx2*(wy1-y0)+dsx;
2601 term := x0+temp div dy2;
2602 rem := temp mod dy2;
2603 if (rem = 0) then Dec(term);
2604 end;
2606 if (term > wx1) then term := wx1; // clip at right
2608 Inc(term); // draw last point
2609 //if (term = xd) then exit; // this is the only point, get out of here
2611 if (sty = -1) then yd := -yd;
2612 if (stx = -1) then begin xd := -xd; term := -term; end;
2613 dx2 -= dy2;
2615 // first move, to skip starting point
2616 // DON'T DO THIS! loop will take care of that
2617 if (xd = term) then
2618 begin
2619 result := forEachAtPoint(ax0, ay0, cb, tagmask, @ptag);
2620 exit;
2621 end;
2623 (*
2624 // move coords
2625 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2626 xd += stx;
2627 // done?
2628 if (xd = term) then exit;
2629 *)
2631 {$IF DEFINED(D2F_DEBUG)}
2632 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*tsize) and (yptr^ >= gh*tsize) then raise Exception.Create('raycaster internal error (0)');
2633 {$ENDIF}
2634 // DON'T DO THIS! loop will take care of that
2635 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
2636 //ccidx := mGrid[lastGA];
2638 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2639 mInQuery := true;
2641 // increase query counter
2642 Inc(mLastQuery);
2643 if (mLastQuery = 0) then
2644 begin
2645 // just in case of overflow
2646 mLastQuery := 1;
2647 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2648 end;
2649 lq := mLastQuery;
2651 {$IFDEF GRID_USE_ORTHO_ACCEL}
2652 // if this is strict horizontal/vertical trace, use optimized codepath
2653 if (ax0 = ax1) or (ay0 = ay1) then
2654 begin
2655 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
2656 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
2657 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
2658 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
2659 hopt := (ay0 = ay1); // horizontal?
2660 if (stx < 0) then begin {wksign := -1;} wklen := -(term-xd); end else begin {wksign := 1;} wklen := term-xd; end;
2661 {$IF DEFINED(D2F_DEBUG)}
2662 if dbgShowTraceLog then e_LogWritefln('optimized htrace; wklen=%d', [wklen]);
2663 {$ENDIF}
2664 ga := (yptr^ div tsize)*gw+(xptr^ div tsize);
2665 while (wklen > 0) do
2666 begin
2667 {$IF DEFINED(D2F_DEBUG)}
2668 if dbgShowTraceLog then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; ay0=%d', [ga, xptr^+minx, yptr^+miny, ay0]);
2669 {$ENDIF}
2670 // new tile?
2671 if (ga <> lastGA) then
2672 begin
2673 lastGA := ga;
2674 ccidx := mGrid[lastGA];
2675 // convert coords to map (to avoid ajdusting coords inside the loop)
2676 while (ccidx <> -1) do
2677 begin
2678 cc := @mCells[ccidx];
2679 for f := 0 to GridCellBucketSize-1 do
2680 begin
2681 if (cc.bodies[f] = -1) then break;
2682 px := @mProxies[cc.bodies[f]];
2683 ptag := px.mTag;
2684 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2685 begin
2686 px.mQueryMark := lq; // mark as processed
2687 if assigned(cb) then
2688 begin
2689 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
2690 end
2691 else
2692 begin
2693 result := px.mObj;
2694 mInQuery := false;
2695 exit;
2696 end;
2697 end;
2698 end;
2699 // next cell
2700 ccidx := cc.next;
2701 end;
2702 end;
2703 // skip to next tile
2704 if hopt then
2705 begin
2706 if (stx > 0) then
2707 begin
2708 // to the right
2709 wkstep := ((xptr^ or (mTileSize-1))+1)-xptr^;
2710 {$IF DEFINED(D2F_DEBUG)}
2711 if dbgShowTraceLog then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2712 {$ENDIF}
2713 if (wkstep >= wklen) then break;
2714 Inc(xptr^, wkstep);
2715 Inc(ga);
2716 end
2717 else
2718 begin
2719 // to the left
2720 wkstep := xptr^-((xptr^ and (not (mTileSize-1)))-1);
2721 {$IF DEFINED(D2F_DEBUG)}
2722 if dbgShowTraceLog then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2723 {$ENDIF}
2724 if (wkstep >= wklen) then break;
2725 Dec(xptr^, wkstep);
2726 Dec(ga);
2727 end;
2728 end
2729 else
2730 begin
2731 if (stx > 0) then
2732 begin
2733 // to the down
2734 wkstep := ((yptr^ or (mTileSize-1))+1)-yptr^;
2735 {$IF DEFINED(D2F_DEBUG)}
2736 if dbgShowTraceLog then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2737 {$ENDIF}
2738 if (wkstep >= wklen) then break;
2739 Inc(yptr^, wkstep);
2740 Inc(ga, mWidth);
2741 end
2742 else
2743 begin
2744 // to the up
2745 wkstep := yptr^-((yptr^ and (not (mTileSize-1)))-1);
2746 {$IF DEFINED(D2F_DEBUG)}
2747 if dbgShowTraceLog then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2748 {$ENDIF}
2749 if (wkstep >= wklen) then break;
2750 Dec(yptr^, wkstep);
2751 Dec(ga, mWidth);
2752 end;
2753 end;
2754 Dec(wklen, wkstep);
2755 end;
2756 mInQuery := false;
2757 exit;
2758 end;
2759 {$ENDIF}
2761 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2762 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div tsize*tsize)+minx, (yptr^ div tsize*tsize)+miny);
2763 {$ENDIF}
2765 ccidx := -1;
2766 // can omit checks
2767 while (xd <> term) do
2768 begin
2769 // check cell(s)
2770 {$IF DEFINED(D2F_DEBUG)}
2771 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*tsize) and (yptr^ >= gh*tsize) then raise Exception.Create('raycaster internal error (0)');
2772 {$ENDIF}
2773 // new tile?
2774 ga := (yptr^ div tsize)*gw+(xptr^ div tsize);
2775 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2776 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);
2777 {$ENDIF}
2778 if (ga <> lastGA) then
2779 begin
2780 // yes
2781 {$IF DEFINED(D2F_DEBUG)}
2782 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div tsize*tsize)+minx, (yptr^ div tsize*tsize)+miny);
2783 {$ENDIF}
2784 lastGA := ga;
2785 ccidx := mGrid[lastGA];
2786 end;
2787 // has something to process in this tile?
2788 if (ccidx <> -1) then
2789 begin
2790 // process cell
2791 curci := ccidx;
2792 // process cell list
2793 while (curci <> -1) do
2794 begin
2795 cc := @mCells[curci];
2796 for f := 0 to GridCellBucketSize-1 do
2797 begin
2798 if (cc.bodies[f] = -1) then break;
2799 px := @mProxies[cc.bodies[f]];
2800 ptag := px.mTag;
2801 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2802 begin
2803 px.mQueryMark := lq; // mark as processed
2804 if assigned(cb) then
2805 begin
2806 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
2807 end
2808 else
2809 begin
2810 result := px.mObj;
2811 mInQuery := false;
2812 exit;
2813 end;
2814 end;
2815 end;
2816 // next cell
2817 curci := cc.next;
2818 end;
2819 // nothing more interesting in this cell
2820 ccidx := -1;
2821 end;
2822 // move to cell edge, as we have nothing to trace here anymore
2823 if (stx < 0) then xdist := xd and (not (mTileSize-1)) else xdist := xd or (mTileSize-1);
2824 if (sty < 0) then ydist := yd and (not (mTileSize-1)) else ydist := yd or (mTileSize-1);
2825 //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]);
2826 while (xd <> xdist) and (yd <> ydist) do
2827 begin
2828 // step
2829 xd += stx;
2830 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2831 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
2832 if (xd = term) then break;
2833 end;
2834 //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]);
2835 if (xd = term) then break;
2836 //putPixel(xptr^, yptr^);
2837 // move coords
2838 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2839 xd += stx;
2840 end;
2842 mInQuery := false;
2843 end;
2846 // ////////////////////////////////////////////////////////////////////////// //
2847 // trace box with the given velocity; return object hit (if any)
2848 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
2849 function TBodyGridBase.traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2850 var
2851 gx, gy: Integer;
2852 ccidx: Integer;
2853 cc: PGridCell;
2854 px: PBodyProxyRec;
2855 lq: LongWord;
2856 f, ptag: Integer;
2857 minu0: Single = 100000.0;
2858 u0: Single;
2859 cx0, cy0, cx1, cy1: Integer;
2860 hitpx: PBodyProxyRec = nil;
2861 begin
2862 result := Default(ITP);
2863 ex := ax0+dx;
2864 ey := ay0+dy;
2865 if (aw < 1) or (ah < 1) then exit;
2867 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2868 mInQuery := true;
2870 cx0 := nmin(ax0, ax0+dx);
2871 cy0 := nmin(ay0, ay0+dy);
2872 cx1 := nmax(ax0+aw-1, ax0+aw-1+dx);
2873 cy1 := nmax(ay0+ah-1, ay0+ah-1+dy);
2875 cx0 -= mMinX; cy0 -= mMinY;
2876 cx1 -= mMinX; cy1 -= mMinY;
2878 if (cx1 < 0) or (cy1 < 0) or (cx0 >= mWidth*mTileSize) or (cy0 >= mHeight*mTileSize) then exit;
2880 if (cx0 < 0) then cx0 := 0;
2881 if (cy0 < 0) then cy0 := 0;
2882 if (cx1 >= mWidth*mTileSize) then cx1 := mWidth*mTileSize-1;
2883 if (cy1 >= mHeight*mTileSize) then cy1 := mHeight*mTileSize-1;
2884 // just in case
2885 if (cx0 > cx1) or (cy0 > cy1) then exit;
2887 // increase query counter
2888 Inc(mLastQuery);
2889 if (mLastQuery = 0) then
2890 begin
2891 // just in case of overflow
2892 mLastQuery := 1;
2893 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2894 end;
2895 lq := mLastQuery;
2897 for gy := cy0 div mTileSize to cy1 div mTileSize do
2898 begin
2899 for gx := cx0 div mTileSize to cx1 div mTileSize do
2900 begin
2901 ccidx := mGrid[gy*mWidth+gx];
2902 while (ccidx <> -1) do
2903 begin
2904 cc := @mCells[ccidx];
2905 for f := 0 to GridCellBucketSize-1 do
2906 begin
2907 if (cc.bodies[f] = -1) then break;
2908 px := @mProxies[cc.bodies[f]];
2909 ptag := px.mTag;
2910 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2911 begin
2912 px.mQueryMark := lq; // mark as processed
2913 if assigned(cb) then
2914 begin
2915 if not cb(px.mObj, ptag) then continue;
2916 end;
2917 if not sweepAABB(ax0, ay0, aw, ah, dx, dy, px.mX, px.mY, px.mWidth, px.mHeight, @u0) then continue;
2918 if (minu0 > u0) then
2919 begin
2920 hitpx := px;
2921 result := px.mObj;
2922 minu0 := u0;
2923 if (u0 = 0.0) then
2924 begin
2925 ex := ax0;
2926 ey := ay0;
2927 mInQuery := false;
2928 exit;
2929 end;
2930 end;
2931 end;
2932 end;
2933 // next cell
2934 ccidx := cc.next;
2935 end;
2936 end;
2937 end;
2939 if (minu0 <= 1.0) then
2940 begin
2941 ex := ax0+round(dx*minu0);
2942 ey := ay0+round(dy*minu0);
2943 // just in case, compensate for floating point inexactness
2944 if (ex >= hitpx.mX) and (ey >= hitpx.mY) and (ex < hitpx.mX+hitpx.mWidth) and (ey < hitpx.mY+hitpx.mHeight) then
2945 begin
2946 ex := ax0+trunc(dx*minu0);
2947 ey := ay0+trunc(dy*minu0);
2948 end;
2949 end;
2951 mInQuery := false;
2952 end;
2955 // ////////////////////////////////////////////////////////////////////////// //
2956 {.$DEFINE D2F_DEBUG_OTR}
2957 function TBodyGridBase.traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
2958 var
2959 ccidx: Integer;
2960 cc: PGridCell;
2961 px: PBodyProxyRec;
2962 ptag: Integer;
2963 minx, miny: Integer;
2964 f, c0, c1: Integer;
2965 x0, y0, x1, y1: Integer;
2966 celly0, celly1: Integer;
2967 dy: Integer;
2968 filled: array[0..mTileSize-1] of Byte;
2969 {$IF DEFINED(D2F_DEBUG_OTR)}
2970 s: AnsiString = '';
2971 {$ENDIF}
2972 begin
2973 result := false;
2974 ex := ax1;
2975 ey := ay1;
2976 if not ((ax0 = ax1) or (ay0 = ay1)) then raise Exception.Create('orthoray is not orthogonal');
2978 tagmask := tagmask and TagFullMask;
2979 if (tagmask = 0) then exit;
2981 if (forEachAtPoint(ax0, ay0, nil, tagmask) = nil) then exit;
2983 minx := mMinX;
2984 miny := mMinY;
2986 // offset query coords to (0,0)-based
2987 x0 := ax0-minx;
2988 y0 := ay0-miny;
2989 x1 := ax1-minx;
2990 y1 := ay1-miny;
2992 if (x0 = x1) then
2993 begin
2994 if (x0 < 0) or (x0 >= mWidth*mTileSize) then exit; // oops
2995 // vertical
2996 if (y0 < y1) then
2997 begin
2998 // down
2999 if (y1 < 0) or (y0 >= mHeight*mTileSize) then exit;
3000 //if (ay0 < 0) then ay0 := 0;
3001 if (y0 < 0) then exit;
3002 if (y1 >= mHeight*mTileSize) then y1 := mHeight*mTileSize-1;
3003 dy := 1;
3004 end
3005 else
3006 begin
3007 // up
3008 if (y0 < 0) or (y1 >= mHeight*mTileSize) then exit;
3009 //if (ay1 < 0) then ay1 := 0;
3010 if (y1 < 0) then exit;
3011 if (y0 >= mHeight*mTileSize) then y0 := mHeight*mTileSize-1;
3012 dy := -1;
3013 end;
3014 // check tile
3015 while true do
3016 begin
3017 ccidx := mGrid[(y0 div mTileSize)*mWidth+(x0 div mTileSize)];
3018 FillChar(filled, sizeof(filled), 0);
3019 celly0 := y0 and (not (mTileSize-1));
3020 celly1 := celly0+mTileSize-1;
3021 while (ccidx <> -1) do
3022 begin
3023 cc := @mCells[ccidx];
3024 for f := 0 to GridCellBucketSize-1 do
3025 begin
3026 if (cc.bodies[f] = -1) then break;
3027 px := @mProxies[cc.bodies[f]];
3028 ptag := px.mTag;
3029 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
3030 (ax0 >= px.x0) and (ax0 <= px.x1) then
3031 begin
3032 // bound c0 and c1 to cell
3033 c0 := nclamp(px.y0-miny, celly0, celly1);
3034 c1 := nclamp(px.y1-miny, celly0, celly1);
3035 // fill the thing
3036 {$IF DEFINED(D2F_DEBUG_OTR)}
3037 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)]);
3038 {$ENDIF}
3039 //assert(c0 <= c1);
3040 FillChar(filled[c0-celly0], c1-c0+1, 1);
3041 end;
3042 end;
3043 // next cell
3044 ccidx := cc.next;
3045 end;
3046 {$IF DEFINED(D2F_DEBUG_OTR)}
3047 s := formatstrf(' x=%s; ay0=%s; ay1=%s; y0=%s; celly0=%s; celly1=%s; dy=%s; [', [ax0, ay0, ay1, y0, celly0, celly1, dy]);
3048 for f := 0 to High(filled) do if (filled[f] <> 0) then s += '1' else s += '0';
3049 s += ']';
3050 e_LogWriteln(s);
3051 {$ENDIF}
3052 // now go till we hit cell boundary or empty space
3053 if (dy < 0) then
3054 begin
3055 // up
3056 while (y0 >= celly0) and (filled[y0-celly0] <> 0) do
3057 begin
3058 {$IF DEFINED(D2F_DEBUG_OTR)}
3059 e_LogWritefln(' filled: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
3060 {$ENDIF}
3061 Dec(y0);
3062 Dec(ay0);
3063 end;
3064 {$IF DEFINED(D2F_DEBUG_OTR)}
3065 e_LogWritefln(' span done: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
3066 {$ENDIF}
3067 if (ay0 <= ay1) then begin ey := ay1; result := false; exit; end;
3068 if (y0 >= celly0) then begin ey := ay0+1; {assert(forEachAtPoint(ex, ey, nil, tagmask) <> nil);} result := true; exit; end;
3069 end
3070 else
3071 begin
3072 // down
3073 while (y0 <= celly1) and (filled[y0-celly0] <> 0) do begin Inc(y0); Inc(ay0); end;
3074 if (ay0 >= ay1) then begin ey := ay1; result := false; exit; end;
3075 if (y0 <= celly1) then begin ey := ay0-1; result := true; exit; end;
3076 end;
3077 end;
3078 end
3079 else
3080 begin
3081 // horizontal
3082 assert(false);
3083 end;
3084 end;
3087 // ////////////////////////////////////////////////////////////////////////// //
3088 function TBodyGridBase.traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
3089 var
3090 ex, ey: Integer;
3091 begin
3092 result := traceRay(ex, ey, x0, y0, x1, y1, cb, tagmask);
3093 end;
3096 // no callback: return `true` on the nearest hit
3097 // you are not supposed to understand this
3098 function TBodyGridBase.traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
3099 var
3100 lw, sweepw: TLineWalker;
3101 ccidx: Integer;
3102 gw, gh, minx, miny: Integer;
3103 cc: PGridCell;
3104 px: PBodyProxyRec;
3105 lq: LongWord;
3106 f, ptag: Integer;
3107 x0, y0, x1, y1, cx, cy, px0, py0, px1, py1: Integer;
3108 lastDistSq, distSq, hx, hy: Integer;
3109 firstCell: Boolean = true;
3110 wasHit: Boolean;
3111 begin
3112 result := Default(ITP);
3113 tagmask := tagmask and TagFullMask;
3114 if (tagmask = 0) then exit;
3116 gw := mWidth;
3117 gh := mHeight;
3118 minx := mMinX;
3119 miny := mMinY;
3121 // make query coords to (0,0)-based
3122 x0 := ax0-minx;
3123 y0 := ay0-miny;
3124 x1 := ax1-minx;
3125 y1 := ay1-miny;
3127 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
3128 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
3130 sweepw := TLineWalker.Create(0, 0, 1, 1); // doesn't matter, just shut ups the compiler
3132 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
3134 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
3135 mInQuery := true;
3137 // increase query counter
3138 Inc(mLastQuery);
3139 if (mLastQuery = 0) then
3140 begin
3141 // just in case of overflow
3142 mLastQuery := 1;
3143 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
3144 end;
3145 lq := mLastQuery;
3147 ccidx := -1;
3148 repeat
3149 lw.getXY(cx, cy);
3150 // check tile
3151 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
3152 // process cells
3153 wasHit := false;
3154 while (ccidx <> -1) do
3155 begin
3156 cc := @mCells[ccidx];
3157 for f := 0 to GridCellBucketSize-1 do
3158 begin
3159 if (cc.bodies[f] = -1) then break;
3160 px := @mProxies[cc.bodies[f]];
3161 ptag := px.mTag;
3162 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
3163 begin
3164 px.mQueryMark := lq; // mark as processed
3165 if assigned(cb) then
3166 begin
3167 if not cb(px.mObj, ptag) then continue;
3168 end;
3169 // get adjusted proxy coords
3170 px0 := px.mX-minx;
3171 py0 := px.mY-miny;
3172 px1 := px0+px.mWidth-1;
3173 py1 := py0+px.mHeight-1;
3174 // inside?
3175 if firstCell and (x0 >= px0) and (y0 >= py0) and (x0 <= px1) and (y0 <= py1) then
3176 begin
3177 // oops
3178 ex := ax0;
3179 ey := ay0;
3180 result := px.mObj;
3181 mInQuery := false;
3182 exit;
3183 end;
3184 // do line-vs-aabb test
3185 sweepw.setClip(px0, py0, px1, py1);
3186 if sweepw.setup(x0, y0, x1, y1) then
3187 begin
3188 // hit detected
3189 sweepw.getPrevXY(hx, hy);
3190 distSq := distanceSq(x0, y0, hx, hy);
3191 if (distSq < lastDistSq) then
3192 begin
3193 lastDistSq := distSq;
3194 ex := hx+minx;
3195 ey := hy+miny;
3196 result := px.mObj;
3197 // if this is not a first cell, get outta here
3198 if not firstCell then begin mInQuery := false; exit; end;
3199 wasHit := true;
3200 end;
3201 end;
3202 end;
3203 end;
3204 // next cell
3205 ccidx := cc.next;
3206 end;
3207 // done processing cells; exit if we registered a hit
3208 // next cells can't have better candidates, obviously
3209 if wasHit then begin mInQuery := false; exit; end;
3210 firstCell := false;
3211 // move to next tile
3212 until lw.stepToNextTile();
3214 mInQuery := false;
3215 end;
3218 end.