DEADSOFTWARE

shitfix (incorrect, but working) for lines starting out of the viewport (almost impos...
[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 procedure swapInt (var a: Integer; var b: Integer); inline; begin a := a xor b; b := b xor a; a := a xor b; end;
331 //function minInt (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
332 //function maxInt (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
334 function distanceSq (x0, y0, x1, y1: Integer): Integer; inline; begin result := (x1-x0)*(x1-x0)+(y1-y0)*(y1-y0); end;
337 // ////////////////////////////////////////////////////////////////////////// //
338 constructor TLineWalker.Create (minx, miny, maxx, maxy: Integer);
339 begin
340 setClip(minx, miny, maxx, maxy);
341 end;
343 procedure TLineWalker.setClip (minx, miny, maxx, maxy: Integer); inline;
344 begin
345 // clip rectange
346 wx0 := minx;
347 wy0 := miny;
348 wx1 := maxx;
349 wy1 := maxy;
350 end;
352 function TLineWalker.done (): Boolean; inline; begin result := (xd = term); end;
354 function TLineWalker.step (): Boolean; inline;
355 begin
356 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
357 xd += stx;
358 result := (xd = term);
359 end;
361 // move to next tile; return `true` if the line is complete (and walker state is undefined then)
362 function TLineWalker.stepToNextTile (): Boolean; inline;
363 var
364 ex, ey, wklen, f: Integer;
365 begin
366 result := false;
368 //writeln('stx=', stx, '; sty=', sty);
370 // ortho?
371 if (sty = 0) then
372 begin
373 // only xd
374 assert(sty <> 0);
375 if (stx < 0) then
376 begin
377 // xd: to left edge
378 xd := (xd and (not (TileSize-1)))-1;
379 result := (xd <= term);
380 exit;
381 end
382 else
383 begin
384 // xd: to right edge
385 xd := (xd or (TileSize-1))+1;
386 result := (xd >= term);
387 exit;
388 end;
389 end;
391 assert(stx <> 0); // invariant
393 // not ortho
394 if (sty < 0) then ey := (yd and (not (TileSize-1)))-1 else ey := (yd or (TileSize-1))+1;
396 //FIXME: do some math to avoid single-stepping
397 if (stx < 0) then
398 begin
399 // xd: to left edge
400 ex := (xd and (not (TileSize-1)))-1;
401 if (ex <= term) then begin result := true; exit; end;
402 wklen := xd-ex;
403 end
404 else
405 begin
406 // xd: to right edge
407 ex := (xd or (TileSize-1))+1;
408 if (ex >= term) then begin result := true; exit; end;
409 wklen := ex-xd;
410 end;
412 //writeln('xd=', xd, '; yd=', yd, '; ex=', ex, '; ey=', ey, '; term=', term, '; wklen=', wklen);
414 for f := wklen downto 1 do
415 begin
416 // do step
417 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
418 xd += stx;
419 if (xd = term) then begin result := true; exit; end;
420 if (xd = ex) or (yd = ey) then exit; // done
421 end;
423 raise Exception.Create('TLineWalker.stepToNextTile: the thing that should not be!');
424 end;
426 // NOT TESTED!
427 procedure TLineWalker.getPrevXY (out ox, oy: Integer); inline;
428 begin
429 //writeln('e=', e, '; dx2=', dx2, '; dy2=', dy2);
430 if xyswapped then
431 begin
432 if (e >= 0) then ox := yd-sty else ox := yd;
433 oy := xd-stx;
434 end
435 else
436 begin
437 if (e >= 0) then oy := yd-sty else oy := yd;
438 ox := xd-stx;
439 end;
440 end;
442 function TLineWalker.x (): Integer; inline; begin if xyswapped then result := yd else result := xd; end;
443 function TLineWalker.y (): Integer; inline; begin if xyswapped then result := xd else result := yd; end;
444 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;
446 function TLineWalker.dx (): Integer; inline; begin if xyswapped then result := stx else result := sty; end;
447 function TLineWalker.dy (): Integer; inline; begin if xyswapped then result := sty else result := stx; end;
449 function TLineWalker.setup (x0, y0, x1, y1: Integer): Boolean;
450 procedure swapInt (var a: Integer; var b: Integer); inline; begin a := a xor b; b := b xor a; a := a xor b; end;
451 var
452 dsx, dsy: Integer; // "lengthes" for x and y axes
453 rem: Integer;
454 xfixed: Boolean;
455 temp: Integer;
456 begin
457 result := false;
458 xyswapped := false;
460 // horizontal setup
461 if (x0 < x1) then
462 begin
463 // from left to right
464 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
465 stx := 1; // going right
466 end
467 else
468 begin
469 // from right to left
470 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
471 stx := -1; // going left
472 x0 := -x0;
473 x1 := -x1;
474 wx0 := -wx0;
475 wx1 := -wx1;
476 swapInt(wx0, wx1);
477 end;
479 // vertical setup
480 if (y0 < y1) then
481 begin
482 // from top to bottom
483 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
484 sty := 1; // going down
485 end
486 else
487 begin
488 // from bottom to top
489 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
490 sty := -1; // going up
491 y0 := -y0;
492 y1 := -y1;
493 wy0 := -wy0;
494 wy1 := -wy1;
495 swapInt(wy0, wy1);
496 end;
498 dsx := x1-x0;
499 dsy := y1-y0;
501 if (dsx < dsy) then
502 begin
503 xyswapped := true;
504 //xptr := @yd;
505 //yptr := @xd;
506 swapInt(x0, y0);
507 swapInt(x1, y1);
508 swapInt(dsx, dsy);
509 swapInt(wx0, wy0);
510 swapInt(wx1, wy1);
511 swapInt(stx, sty);
512 end
513 else
514 begin
515 //xptr := @xd;
516 //yptr := @yd;
517 end;
519 dx2 := 2*dsx;
520 dy2 := 2*dsy;
521 xd := x0;
522 yd := y0;
523 e := 2*dsy-dsx;
524 term := x1;
526 xfixed := false;
527 if (y0 < wy0) then
528 begin
529 // clip at top
530 temp := dx2*(wy0-y0)-dsx;
531 xd += temp div dy2;
532 rem := temp mod dy2;
533 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
534 if (xd+1 >= wx0) then
535 begin
536 yd := wy0;
537 e -= rem+dsx;
538 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
539 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
540 xfixed := true;
541 end;
542 end;
544 if (not xfixed) and (x0 < wx0) then
545 begin
546 // clip at left
547 temp := dy2*(wx0-x0);
548 yd += temp div dx2;
549 rem := temp mod dx2;
550 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
551 xd := wx0;
552 e += rem;
553 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
554 end;
556 if (y1 > wy1) then
557 begin
558 // clip at bottom
559 temp := dx2*(wy1-y0)+dsx;
560 term := x0+temp div dy2;
561 rem := temp mod dy2;
562 if (rem = 0) then Dec(term);
563 end;
565 if (term > wx1) then term := wx1; // clip at right
567 Inc(term); // draw last point (it is ok to inc here, as `term` sign will be changed later
568 //if (term = xd) then exit; // this is the only point, get out of here
570 if (sty = -1) then yd := -yd;
571 if (stx = -1) then begin xd := -xd; term := -term; end;
572 dx2 -= dy2;
574 result := true;
575 end;
578 // ////////////////////////////////////////////////////////////////////////// //
579 // you are not supposed to understand this
580 // returns `true` if there is an intersection, and enter coords
581 // enter coords will be equal to (x0, y0) if starting point is inside the box
582 // if result is `false`, `inx` and `iny` are undefined
583 function lineAABBIntersects (x0, y0, x1, y1: Integer; bx, by, bw, bh: Integer; out inx, iny: Integer): Boolean;
584 var
585 wx0, wy0, wx1, wy1: Integer; // window coordinates
586 stx, sty: Integer; // "steps" for x and y axes
587 dsx, dsy: Integer; // "lengthes" for x and y axes
588 dx2, dy2: Integer; // "double lengthes" for x and y axes
589 xd, yd: Integer; // current coord
590 e: Integer; // "error" (as in bresenham algo)
591 rem: Integer;
592 //!term: Integer;
593 d0, d1: PInteger;
594 xfixed: Boolean;
595 temp: Integer;
596 begin
597 result := false;
598 // why not
599 inx := x0;
600 iny := y0;
601 if (bw < 1) or (bh < 1) then exit; // impossible box
603 if (x0 = x1) and (y0 = y1) then
604 begin
605 // check this point
606 result := (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh);
607 exit;
608 end;
610 // check if staring point is inside the box
611 if (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh) then begin result := true; exit; end;
613 // clip rectange
614 wx0 := bx;
615 wy0 := by;
616 wx1 := bx+bw-1;
617 wy1 := by+bh-1;
619 // horizontal setup
620 if (x0 < x1) then
621 begin
622 // from left to right
623 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
624 stx := 1; // going right
625 end
626 else
627 begin
628 // from right to left
629 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
630 stx := -1; // going left
631 x0 := -x0;
632 x1 := -x1;
633 wx0 := -wx0;
634 wx1 := -wx1;
635 swapInt(wx0, wx1);
636 end;
638 // vertical setup
639 if (y0 < y1) then
640 begin
641 // from top to bottom
642 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
643 sty := 1; // going down
644 end
645 else
646 begin
647 // from bottom to top
648 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
649 sty := -1; // going up
650 y0 := -y0;
651 y1 := -y1;
652 wy0 := -wy0;
653 wy1 := -wy1;
654 swapInt(wy0, wy1);
655 end;
657 dsx := x1-x0;
658 dsy := y1-y0;
660 if (dsx < dsy) then
661 begin
662 d0 := @yd;
663 d1 := @xd;
664 swapInt(x0, y0);
665 swapInt(x1, y1);
666 swapInt(dsx, dsy);
667 swapInt(wx0, wy0);
668 swapInt(wx1, wy1);
669 swapInt(stx, sty);
670 end
671 else
672 begin
673 d0 := @xd;
674 d1 := @yd;
675 end;
677 dx2 := 2*dsx;
678 dy2 := 2*dsy;
679 xd := x0;
680 yd := y0;
681 e := 2*dsy-dsx;
682 //!term := x1;
684 xfixed := false;
685 if (y0 < wy0) then
686 begin
687 // clip at top
688 temp := dx2*(wy0-y0)-dsx;
689 xd += temp div dy2;
690 rem := temp mod dy2;
691 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
692 if (xd+1 >= wx0) then
693 begin
694 yd := wy0;
695 e -= rem+dsx;
696 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
697 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
698 xfixed := true;
699 end;
700 end;
702 if (not xfixed) and (x0 < wx0) then
703 begin
704 // clip at left
705 temp := dy2*(wx0-x0);
706 yd += temp div dx2;
707 rem := temp mod dx2;
708 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
709 xd := wx0;
710 e += rem;
711 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
712 end;
714 (*
715 if (y1 > wy1) then
716 begin
717 // clip at bottom
718 temp := dx2*(wy1-y0)+dsx;
719 term := x0+temp div dy2;
720 rem := temp mod dy2;
721 if (rem = 0) then Dec(term);
722 end;
724 if (term > wx1) then term := wx1; // clip at right
726 Inc(term); // draw last point
727 //if (term = xd) then exit; // this is the only point, get out of here
728 *)
730 if (sty = -1) then yd := -yd;
731 if (stx = -1) then begin xd := -xd; {!term := -term;} end;
732 //!dx2 -= dy2;
734 inx := d0^;
735 iny := d1^;
736 result := true;
737 end;
740 // ////////////////////////////////////////////////////////////////////////// //
741 function sweepAABB (mex0, mey0, mew, meh: Integer; medx, medy: Integer; itx0, ity0, itw, ith: Integer;
742 u0: PSingle=nil; hitedge: PInteger=nil; u1: PSingle=nil): Boolean;
743 var
744 tin, tout: Single;
746 function axisOverlap (me0, me1, it0, it1, d, he0, he1: Integer): Boolean; inline;
747 var
748 t: Single;
749 begin
750 result := false;
752 if (me1 < it0) then
753 begin
754 if (d >= 0) then exit; // oops, no hit
755 t := (me1-it0+1)/d;
756 if (t > tin) then begin tin := t; hitedge^ := he1; end;
757 end
758 else if (it1 < me0) then
759 begin
760 if (d <= 0) then exit; // oops, no hit
761 t := (me0-it1-1)/d;
762 if (t > tin) then begin tin := t; hitedge^ := he0; end;
763 end;
765 if (d < 0) and (it1 > me0) then
766 begin
767 t := (me0-it1-1)/d;
768 if (t < tout) then tout := t;
769 end
770 else if (d > 0) and (me1 > it0) then
771 begin
772 t := (me1-it0+1)/d;
773 if (t < tout) then tout := t;
774 end;
776 result := true;
777 end;
779 var
780 mex1, mey1, itx1, ity1, vx, vy: Integer;
781 htt: Integer = -1;
782 begin
783 result := false;
784 if (u0 <> nil) then u0^ := -1.0;
785 if (u1 <> nil) then u1^ := -1.0;
786 if (hitedge = nil) then hitedge := @htt else hitedge^ := -1;
788 if (mew < 1) or (meh < 1) or (itw < 1) or (ith < 1) then exit;
790 mex1 := mex0+mew-1;
791 mey1 := mey0+meh-1;
792 itx1 := itx0+itw-1;
793 ity1 := ity0+ith-1;
795 // check if they are overlapping right now (SAT)
796 //if (mex1 >= itx0) and (mex0 <= itx1) and (mey1 >= ity0) and (mey0 <= ity1) then begin result := true; exit; end;
798 if (medx = 0) and (medy = 0) then exit; // both boxes are sationary
800 // treat b as stationary, so invert v to get relative velocity
801 vx := -medx;
802 vy := -medy;
804 tin := -100000000.0;
805 tout := 100000000.0;
807 if not axisOverlap(mex0, mex1, itx0, itx1, vx, 1, 3) then exit;
808 if not axisOverlap(mey0, mey1, ity0, ity1, vy, 2, 0) then exit;
810 if (u0 <> nil) then u0^ := tin;
811 if (u1 <> nil) then u1^ := tout;
813 if (tin <= tout) and (tin >= 0.0) and (tin <= 1.0) then
814 begin
815 result := true;
816 end;
817 end;
820 // ////////////////////////////////////////////////////////////////////////// //
821 procedure TBodyGridBase.TBodyProxyRec.setup (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer);
822 begin
823 mX := aX;
824 mY := aY;
825 mWidth := aWidth;
826 mHeight := aHeight;
827 mQueryMark := 0;
828 mObj := aObj;
829 mTag := aTag;
830 nextLink := -1;
831 end;
834 function TBodyGridBase.TBodyProxyRec.getTag (): Integer; inline;
835 begin
836 result := mTag and TagFullMask;
837 end;
839 procedure TBodyGridBase.TBodyProxyRec.setTag (v: Integer); inline;
840 begin
841 mTag := (mTag and TagDisabled) or (v and TagFullMask);
842 end;
844 function TBodyGridBase.TBodyProxyRec.getEnabled (): Boolean; inline;
845 begin
846 result := ((mTag and TagDisabled) = 0);
847 end;
849 procedure TBodyGridBase.TBodyProxyRec.setEnabled (v: Boolean); inline;
850 begin
851 if v then mTag := mTag and (not TagDisabled) else mTag := mTag or TagDisabled;
852 end;
854 function TBodyGridBase.TBodyProxyRec.getX1 (): Integer; inline;
855 begin
856 result := mX+mWidth-1;
857 end;
859 function TBodyGridBase.TBodyProxyRec.getY1 (): Integer; inline;
860 begin
861 result := mY+mHeight-1;
862 end;
865 // ////////////////////////////////////////////////////////////////////////// //
866 constructor TBodyGridBase.TAtPointEnumerator.Create (acells: TCellArray; aidx: Integer; agetpx: TGetProxyFn);
867 begin
868 mCells := acells;
869 curidx := aidx;
870 curbki := -1;
871 getpx := agetpx;
872 end;
875 function TBodyGridBase.TAtPointEnumerator.MoveNext (): Boolean; inline;
876 begin
877 while (curidx <> -1) do
878 begin
879 while (curbki < GridCellBucketSize) do
880 begin
881 Inc(curbki);
882 if (mCells[curidx].bodies[curbki] = -1) then break;
883 result := true;
884 exit;
885 end;
886 curidx := mCells[curidx].next;
887 curbki := -1;
888 end;
889 result := false;
890 end;
893 function TBodyGridBase.TAtPointEnumerator.getCurrent (): PBodyProxyRec; inline;
894 begin
895 result := getpx(mCells[curidx].bodies[curbki]);
896 end;
899 // ////////////////////////////////////////////////////////////////////////// //
900 constructor TBodyGridBase.Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
901 var
902 idx: Integer;
903 begin
904 dbgShowTraceLog := false;
905 {$IF DEFINED(D2F_DEBUG)}
906 dbgRayTraceTileHitCB := nil;
907 {$ENDIF}
909 if aTileSize < 1 then aTileSize := 1;
910 if aTileSize > 8192 then aTileSize := 8192; // arbitrary limit
911 mTileSize := aTileSize;
913 if (aPixWidth < mTileSize) then aPixWidth := mTileSize;
914 if (aPixHeight < mTileSize) then aPixHeight := mTileSize;
915 mMinX := aMinPixX;
916 mMinY := aMinPixY;
917 mWidth := (aPixWidth+mTileSize-1) div mTileSize;
918 mHeight := (aPixHeight+mTileSize-1) div mTileSize;
919 SetLength(mGrid, mWidth*mHeight);
920 SetLength(mCells, mWidth*mHeight);
921 SetLength(mProxies, 8192);
922 mFreeCell := 0;
923 // init free list
924 for idx := 0 to High(mCells) do
925 begin
926 mCells[idx].bodies[0] := -1;
927 mCells[idx].bodies[GridCellBucketSize-1] := -1; // "has free room" flag
928 mCells[idx].next := idx+1;
929 end;
930 mCells[High(mCells)].next := -1; // last cell
931 // init grid
932 for idx := 0 to High(mGrid) do mGrid[idx] := -1;
933 // init proxies
934 for idx := 0 to High(mProxies) do mProxies[idx].nextLink := idx+1;
935 mProxies[High(mProxies)].nextLink := -1;
936 mLastQuery := 0;
937 mUsedCells := 0;
938 mProxyFree := 0;
939 mProxyCount := 0;
940 mProxyMaxCount := 0;
941 e_WriteLog(Format('created grid with size: %dx%d (tile size: %d); pix: %dx%d', [mWidth, mHeight, mTileSize, mWidth*mTileSize, mHeight*mTileSize]), MSG_NOTIFY);
942 end;
945 destructor TBodyGridBase.Destroy ();
946 begin
947 mCells := nil;
948 mGrid := nil;
949 mProxies := nil;
950 inherited;
951 end;
954 // ////////////////////////////////////////////////////////////////////////// //
955 procedure TBodyGridBase.dumpStats ();
956 var
957 idx, mcb, ccidx, cnt: Integer;
958 begin
959 mcb := 0;
960 for idx := 0 to High(mGrid) do
961 begin
962 ccidx := mGrid[idx];
963 cnt := 0;
964 while ccidx >= 0 do
965 begin
966 Inc(cnt);
967 ccidx := mCells[ccidx].next;
968 end;
969 if (mcb < cnt) then mcb := cnt;
970 end;
971 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);
972 end;
975 procedure TBodyGridBase.forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
976 var
977 g, f, ccidx: Integer;
978 cc: PGridCell;
979 begin
980 if (body < 0) or (body > High(mProxies)) or not assigned(cb) then exit;
981 for g := 0 to High(mGrid) do
982 begin
983 ccidx := mGrid[g];
984 while (ccidx <> -1) do
985 begin
986 cc := @mCells[ccidx];
987 for f := 0 to GridCellBucketSize-1 do
988 begin
989 if (cc.bodies[f] = -1) then break;
990 if (cc.bodies[f] = body) then cb((g mod mWidth)*mTileSize+mMinX, (g div mWidth)*mTileSize+mMinY);
991 end;
992 // next cell
993 ccidx := cc.next;
994 end;
995 end;
996 end;
999 function TBodyGridBase.forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
1000 var
1001 f, ccidx: Integer;
1002 cc: PGridCell;
1003 begin
1004 result := Default(ITP);
1005 if not assigned(cb) then exit;
1006 Dec(x, mMinX);
1007 Dec(y, mMinY);
1008 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y > mHeight*mTileSize) then exit;
1009 ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1010 while (ccidx <> -1) do
1011 begin
1012 cc := @mCells[ccidx];
1013 for f := 0 to GridCellBucketSize-1 do
1014 begin
1015 if (cc.bodies[f] = -1) then break;
1016 if cb(mProxies[cc.bodies[f]].mObj, mProxies[cc.bodies[f]].mTag) then begin result := mProxies[cc.bodies[f]].mObj; exit; end;
1017 end;
1018 // next cell
1019 ccidx := cc.next;
1020 end;
1021 end;
1024 // ////////////////////////////////////////////////////////////////////////// //
1025 function TBodyGridBase.getGridWidthPx (): Integer; inline; begin result := mWidth*mTileSize; end;
1026 function TBodyGridBase.getGridHeightPx (): Integer; inline; begin result := mHeight*mTileSize; end;
1029 function TBodyGridBase.insideGrid (x, y: Integer): Boolean; inline;
1030 begin
1031 // fix coords
1032 Dec(x, mMinX);
1033 Dec(y, mMinY);
1034 result := (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize);
1035 end;
1038 function TBodyGridBase.getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
1039 begin
1040 if (body >= 0) and (body < Length(mProxies)) then
1041 begin
1042 with mProxies[body] do begin rx := mX; ry := mY; end;
1043 result := true;
1044 end
1045 else
1046 begin
1047 rx := 0;
1048 ry := 0;
1049 result := false;
1050 end;
1051 end;
1054 function TBodyGridBase.getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
1055 begin
1056 if (body >= 0) and (body < Length(mProxies)) then
1057 begin
1058 with mProxies[body] do begin rw := mWidth; rh := mHeight; end;
1059 result := true;
1060 end
1061 else
1062 begin
1063 rw := 0;
1064 rh := 0;
1065 result := false;
1066 end;
1067 end;
1070 function TBodyGridBase.getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
1071 begin
1072 if (body >= 0) and (body < Length(mProxies)) then
1073 begin
1074 with mProxies[body] do begin rx := mX; ry := mY; rw := mWidth; rh := mHeight; end;
1075 result := true;
1076 end
1077 else
1078 begin
1079 rx := 0;
1080 ry := 0;
1081 rw := 0;
1082 rh := 0;
1083 result := false;
1084 end;
1085 end;
1089 // ////////////////////////////////////////////////////////////////////////// //
1090 function TBodyGridBase.getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
1091 begin
1092 if (pid >= 0) and (pid < Length(mProxies)) then result := ((mProxies[pid].mTag and TagDisabled) = 0) else result := false;
1093 end;
1096 procedure TBodyGridBase.setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
1097 begin
1098 if (pid >= 0) and (pid < Length(mProxies)) then
1099 begin
1100 if val then
1101 begin
1102 mProxies[pid].mTag := mProxies[pid].mTag and not TagDisabled;
1103 end
1104 else
1105 begin
1106 mProxies[pid].mTag := mProxies[pid].mTag or TagDisabled;
1107 end;
1108 end;
1109 end;
1112 function TBodyGridBase.getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
1113 begin
1114 if (idx >= 0) and (idx < Length(mProxies)) then result := @mProxies[idx] else result := nil;
1115 end;
1118 // ////////////////////////////////////////////////////////////////////////// //
1119 function TBodyGridBase.allocCell (): Integer;
1120 var
1121 idx: Integer;
1122 pc: PGridCell;
1123 begin
1124 if (mFreeCell < 0) then
1125 begin
1126 // no free cells, want more
1127 mFreeCell := Length(mCells);
1128 SetLength(mCells, mFreeCell+32768); // arbitrary number
1129 for idx := mFreeCell to High(mCells) do
1130 begin
1131 mCells[idx].bodies[0] := -1;
1132 mCells[idx].bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
1133 mCells[idx].next := idx+1;
1134 end;
1135 mCells[High(mCells)].next := -1; // last cell
1136 end;
1137 result := mFreeCell;
1138 pc := @mCells[result];
1139 mFreeCell := pc.next;
1140 pc.next := -1;
1141 Inc(mUsedCells);
1142 //e_WriteLog(Format('grid: allocated new cell #%d (total: %d)', [result, mUsedCells]), MSG_NOTIFY);
1143 end;
1146 procedure TBodyGridBase.freeCell (idx: Integer);
1147 begin
1148 if (idx >= 0) and (idx < Length(mCells)) then
1149 begin
1150 with mCells[idx] do
1151 begin
1152 bodies[0] := -1;
1153 bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
1154 next := mFreeCell;
1155 end;
1156 mFreeCell := idx;
1157 Dec(mUsedCells);
1158 end;
1159 end;
1162 // ////////////////////////////////////////////////////////////////////////// //
1163 function TBodyGridBase.allocProxy (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer): TBodyProxyId;
1164 var
1165 olen, idx: Integer;
1166 px: PBodyProxyRec;
1167 begin
1168 if (mProxyFree = -1) then
1169 begin
1170 // no free proxies, resize list
1171 olen := Length(mProxies);
1172 SetLength(mProxies, olen+8192); // arbitrary number
1173 for idx := olen to High(mProxies) do mProxies[idx].nextLink := idx+1;
1174 mProxies[High(mProxies)].nextLink := -1;
1175 mProxyFree := olen;
1176 end;
1177 // get one from list
1178 result := mProxyFree;
1179 px := @mProxies[result];
1180 mProxyFree := px.nextLink;
1181 px.setup(aX, aY, aWidth, aHeight, aObj, aTag);
1182 // add to used list
1183 px.nextLink := -1;
1184 // statistics
1185 Inc(mProxyCount);
1186 if (mProxyMaxCount < mProxyCount) then mProxyMaxCount := mProxyCount;
1187 end;
1189 procedure TBodyGridBase.freeProxy (body: TBodyProxyId);
1190 begin
1191 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1192 if (mProxyCount = 0) then raise Exception.Create('wutafuuuuu in grid (no allocated proxies, what i should free now?)');
1193 // add to free list
1194 mProxies[body].mObj := nil;
1195 mProxies[body].nextLink := mProxyFree;
1196 mProxyFree := body;
1197 Dec(mProxyCount);
1198 end;
1201 // ////////////////////////////////////////////////////////////////////////// //
1202 function TBodyGridBase.forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
1203 var
1204 gx, gy: Integer;
1205 gw, gh: Integer;
1206 begin
1207 result := false;
1208 if (w < 1) or (h < 1) or not assigned(cb) then exit;
1209 // fix coords
1210 Dec(x, mMinX);
1211 Dec(y, mMinY);
1212 // go on
1213 if (x+w <= 0) or (y+h <= 0) then exit;
1214 gw := mWidth;
1215 gh := mHeight;
1216 //tsize := mTileSize;
1217 if (x >= gw*mTileSize) or (y >= gh*mTileSize) then exit;
1218 for gy := y div mTileSize to (y+h-1) div mTileSize do
1219 begin
1220 if (gy < 0) then continue;
1221 if (gy >= gh) then break;
1222 for gx := x div mTileSize to (x+w-1) div mTileSize do
1223 begin
1224 if (gx < 0) then continue;
1225 if (gx >= gw) then break;
1226 result := cb(gy*gw+gx, bodyId);
1227 if result then exit;
1228 end;
1229 end;
1230 end;
1233 // ////////////////////////////////////////////////////////////////////////// //
1234 function TBodyGridBase.inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
1235 var
1236 ccidx: Integer;
1237 pc: Integer;
1238 pi: PGridCell;
1239 f: Integer;
1240 begin
1241 result := false; // never stop
1242 // add body to the given grid cell
1243 pc := mGrid[grida];
1244 if (pc <> -1) then
1245 begin
1246 {$IF DEFINED(D2F_DEBUG)}
1247 ccidx := pc;
1248 while (ccidx <> -1) do
1249 begin
1250 pi := @mCells[ccidx];
1251 for f := 0 to GridCellBucketSize-1 do
1252 begin
1253 if (pi.bodies[f] = -1) then break;
1254 if (pi.bodies[f] = bodyId) then raise Exception.Create('trying to insert already inserted proxy');
1255 end;
1256 ccidx := pi.next;
1257 end;
1258 {$ENDIF}
1259 ccidx := pc;
1260 while (ccidx <> -1) do
1261 begin
1262 pi := @mCells[ccidx];
1263 // check "has room" flag
1264 if (pi.bodies[GridCellBucketSize-1] = -1) then
1265 begin
1266 // can add here
1267 for f := 0 to GridCellBucketSize-1 do
1268 begin
1269 if (pi.bodies[f] = -1) then
1270 begin
1271 pi.bodies[f] := bodyId;
1272 if (f+1 < GridCellBucketSize) then pi.bodies[f+1] := -1;
1273 exit;
1274 end;
1275 end;
1276 raise Exception.Create('internal error in grid inserter');
1277 end;
1278 // no room, go to next cell in list (if there is any)
1279 ccidx := pi.next;
1280 end;
1281 // no room in cells, add new cell to list
1282 end;
1283 // either no room, or no cell at all
1284 ccidx := allocCell();
1285 pi := @mCells[ccidx];
1286 pi.bodies[0] := bodyId;
1287 pi.bodies[1] := -1;
1288 pi.next := pc;
1289 mGrid[grida] := ccidx;
1290 end;
1292 procedure TBodyGridBase.insertInternal (body: TBodyProxyId);
1293 var
1294 px: PBodyProxyRec;
1295 begin
1296 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1297 px := @mProxies[body];
1298 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, inserter, body);
1299 end;
1302 // assume that we cannot have one object added to bucket twice
1303 function TBodyGridBase.remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
1304 var
1305 f, c: Integer;
1306 pidx, ccidx: Integer;
1307 pc: PGridCell;
1308 begin
1309 result := false; // never stop
1310 // find and remove cell
1311 pidx := -1; // previous cell index
1312 ccidx := mGrid[grida]; // current cell index
1313 while (ccidx <> -1) do
1314 begin
1315 pc := @mCells[ccidx];
1316 for f := 0 to GridCellBucketSize-1 do
1317 begin
1318 if (pc.bodies[f] = bodyId) then
1319 begin
1320 // i found her!
1321 if (f = 0) and (pc.bodies[1] = -1) then
1322 begin
1323 // this cell contains no elements, remove it
1324 if (pidx = -1) then mGrid[grida] := pc.next else mCells[pidx].next := pc.next;
1325 freeCell(ccidx);
1326 exit;
1327 end;
1328 // remove element from bucket
1329 for c := f to GridCellBucketSize-2 do
1330 begin
1331 pc.bodies[c] := pc.bodies[c+1];
1332 if (pc.bodies[c] = -1) then break;
1333 end;
1334 pc.bodies[GridCellBucketSize-1] := -1; // "has free room" flag
1335 exit;
1336 end;
1337 end;
1338 pidx := ccidx;
1339 ccidx := pc.next;
1340 end;
1341 end;
1343 procedure TBodyGridBase.removeInternal (body: TBodyProxyId);
1344 var
1345 px: PBodyProxyRec;
1346 begin
1347 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1348 px := @mProxies[body];
1349 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1350 end;
1353 // ////////////////////////////////////////////////////////////////////////// //
1354 function TBodyGridBase.insertBody (aObj: ITP; aX, aY, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
1355 begin
1356 aTag := aTag and TagFullMask;
1357 result := allocProxy(aX, aY, aWidth, aHeight, aObj, aTag);
1358 insertInternal(result);
1359 end;
1362 procedure TBodyGridBase.removeBody (body: TBodyProxyId);
1363 begin
1364 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1365 removeInternal(body);
1366 freeProxy(body);
1367 end;
1370 // ////////////////////////////////////////////////////////////////////////// //
1371 procedure TBodyGridBase.moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
1372 var
1373 px: PBodyProxyRec;
1374 x0, y0, w, h: Integer;
1375 begin
1376 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1377 px := @mProxies[body];
1378 x0 := px.mX;
1379 y0 := px.mY;
1380 w := px.mWidth;
1381 h := px.mHeight;
1382 {$IF DEFINED(D2F_DEBUG_MOVER)}
1383 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);
1384 {$ENDIF}
1385 if (nx = x0) and (ny = y0) and (nw = w) and (nh = h) then exit;
1386 // map -> grid
1387 Dec(x0, mMinX);
1388 Dec(y0, mMinY);
1389 Dec(nx, mMinX);
1390 Dec(ny, mMinY);
1391 // did any corner crossed tile boundary?
1392 if (x0 div mTileSize <> nx div mTileSize) or
1393 (y0 div mTileSize <> ny div mTileSize) or
1394 ((x0+w) div mTileSize <> (nx+nw) div mTileSize) or
1395 ((y0+h) div mTileSize <> (ny+nh) div mTileSize) then
1396 begin
1397 removeInternal(body);
1398 px.mX := nx+mMinX;
1399 px.mY := ny+mMinY;
1400 px.mWidth := nw;
1401 px.mHeight := nh;
1402 insertInternal(body);
1403 end
1404 else
1405 begin
1406 px.mX := nx+mMinX;
1407 px.mY := ny+mMinY;
1408 px.mWidth := nw;
1409 px.mHeight := nh;
1410 end;
1411 end;
1413 //TODO: optimize for horizontal/vertical moves
1414 procedure TBodyGridBase.moveBody (body: TBodyProxyId; nx, ny: Integer);
1415 var
1416 px: PBodyProxyRec;
1417 x0, y0: Integer;
1418 ogx0, ogx1, ogy0, ogy1: Integer; // old grid rect
1419 ngx0, ngx1, ngy0, ngy1: Integer; // new grid rect
1420 gx, gy: Integer;
1421 gw, gh: Integer;
1422 pw, ph: Integer;
1423 begin
1424 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1425 // check if tile coords was changed
1426 px := @mProxies[body];
1427 x0 := px.mX;
1428 y0 := px.mY;
1429 if (nx = x0) and (ny = y0) then exit;
1430 // map -> grid
1431 Dec(x0, mMinX);
1432 Dec(y0, mMinY);
1433 Dec(nx, mMinX);
1434 Dec(ny, mMinY);
1435 // check for heavy work
1436 pw := px.mWidth;
1437 ph := px.mHeight;
1438 ogx0 := x0 div mTileSize;
1439 ogy0 := y0 div mTileSize;
1440 ngx0 := nx div mTileSize;
1441 ngy0 := ny div mTileSize;
1442 ogx1 := (x0+pw-1) div mTileSize;
1443 ogy1 := (y0+ph-1) div mTileSize;
1444 ngx1 := (nx+pw-1) div mTileSize;
1445 ngy1 := (ny+ph-1) div mTileSize;
1446 {$IF DEFINED(D2F_DEBUG_MOVER)}
1447 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);
1448 {$ENDIF}
1449 if (ogx0 <> ngx0) or (ogy0 <> ngy0) or (ogx1 <> ngx1) or (ogy1 <> ngy1) then
1450 begin
1451 // crossed tile boundary, do heavy work
1452 gw := mWidth;
1453 gh := mHeight;
1454 // cycle with old rect, remove body where it is necessary
1455 // optimized for horizontal moves
1456 {$IF DEFINED(D2F_DEBUG_MOVER)}
1457 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);
1458 {$ENDIF}
1459 // remove stale marks
1460 if not ((ogy0 >= gh) or (ogy1 < 0)) and
1461 not ((ogx0 >= gw) or (ogx1 < 0)) then
1462 begin
1463 if (ogx0 < 0) then ogx0 := 0;
1464 if (ogy0 < 0) then ogy0 := 0;
1465 if (ogx1 > gw-1) then ogx1 := gw-1;
1466 if (ogy1 > gh-1) then ogy1 := gh-1;
1467 {$IF DEFINED(D2F_DEBUG_MOVER)}
1468 e_WriteLog(Format(' norm og:(%d,%d)-(%d,%d)', [ogx0, ogy0, ogx1, ogy1]), MSG_NOTIFY);
1469 {$ENDIF}
1470 for gx := ogx0 to ogx1 do
1471 begin
1472 if (gx < ngx0) or (gx > ngx1) then
1473 begin
1474 // this column is completely outside of new rect
1475 for gy := ogy0 to ogy1 do
1476 begin
1477 {$IF DEFINED(D2F_DEBUG_MOVER)}
1478 e_WriteLog(Format(' remove0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1479 {$ENDIF}
1480 remover(gy*gw+gx, body);
1481 end;
1482 end
1483 else
1484 begin
1485 // heavy checks
1486 for gy := ogy0 to ogy1 do
1487 begin
1488 if (gy < ngy0) or (gy > ngy1) then
1489 begin
1490 {$IF DEFINED(D2F_DEBUG_MOVER)}
1491 e_WriteLog(Format(' remove1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1492 {$ENDIF}
1493 remover(gy*gw+gx, body);
1494 end;
1495 end;
1496 end;
1497 end;
1498 end;
1499 // cycle with new rect, add body where it is necessary
1500 if not ((ngy0 >= gh) or (ngy1 < 0)) and
1501 not ((ngx0 >= gw) or (ngx1 < 0)) then
1502 begin
1503 if (ngx0 < 0) then ngx0 := 0;
1504 if (ngy0 < 0) then ngy0 := 0;
1505 if (ngx1 > gw-1) then ngx1 := gw-1;
1506 if (ngy1 > gh-1) then ngy1 := gh-1;
1507 {$IF DEFINED(D2F_DEBUG_MOVER)}
1508 e_WriteLog(Format(' norm ng:(%d,%d)-(%d,%d)', [ngx0, ngy0, ngx1, ngy1]), MSG_NOTIFY);
1509 {$ENDIF}
1510 for gx := ngx0 to ngx1 do
1511 begin
1512 if (gx < ogx0) or (gx > ogx1) then
1513 begin
1514 // this column is completely outside of old rect
1515 for gy := ngy0 to ngy1 do
1516 begin
1517 {$IF DEFINED(D2F_DEBUG_MOVER)}
1518 e_WriteLog(Format(' insert0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1519 {$ENDIF}
1520 inserter(gy*gw+gx, body);
1521 end;
1522 end
1523 else
1524 begin
1525 // heavy checks
1526 for gy := ngy0 to ngy1 do
1527 begin
1528 if (gy < ogy0) or (gy > ogy1) then
1529 begin
1530 {$IF DEFINED(D2F_DEBUG_MOVER)}
1531 e_WriteLog(Format(' insert1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1532 {$ENDIF}
1533 inserter(gy*gw+gx, body);
1534 end;
1535 end;
1536 end;
1537 end;
1538 end;
1539 // done
1540 end
1541 else
1542 begin
1543 {$IF DEFINED(D2F_DEBUG_MOVER)}
1544 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);
1545 {$ENDIF}
1546 end;
1547 // update coordinates
1548 px.mX := nx+mMinX;
1549 px.mY := ny+mMinY;
1550 end;
1552 procedure TBodyGridBase.resizeBody (body: TBodyProxyId; nw, nh: Integer);
1553 var
1554 px: PBodyProxyRec;
1555 x0, y0, w, h: Integer;
1556 begin
1557 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1558 // check if tile coords was changed
1559 px := @mProxies[body];
1560 x0 := px.mX-mMinX;
1561 y0 := px.mY-mMinY;
1562 w := px.mWidth;
1563 h := px.mHeight;
1564 {$IF DEFINED(D2F_DEBUG_MOVER)}
1565 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);
1566 {$ENDIF}
1567 if ((x0+w) div mTileSize <> (x0+nw) div mTileSize) or
1568 ((y0+h) div mTileSize <> (y0+nh) div mTileSize) then
1569 begin
1570 // crossed tile boundary, do heavy work
1571 removeInternal(body);
1572 px.mWidth := nw;
1573 px.mHeight := nh;
1574 insertInternal(body);
1575 end
1576 else
1577 begin
1578 // nothing to do with the grid, just fix size
1579 px.mWidth := nw;
1580 px.mHeight := nh;
1581 end;
1582 end;
1585 // ////////////////////////////////////////////////////////////////////////// //
1586 function TBodyGridBase.atCellInPoint (x, y: Integer): TAtPointEnumerator;
1587 var
1588 ccidx: Integer = -1;
1589 begin
1590 Dec(x, mMinX);
1591 Dec(y, mMinY);
1592 if (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize) then ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1593 result := TAtPointEnumerator.Create(mCells, ccidx, getProxyById);
1594 end;
1597 // ////////////////////////////////////////////////////////////////////////// //
1598 // no callback: return `true` on the first hit
1599 function TBodyGridBase.forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
1600 var
1601 f: Integer;
1602 idx, curci: Integer;
1603 cc: PGridCell = nil;
1604 px: PBodyProxyRec;
1605 lq: LongWord;
1606 ptag: Integer;
1607 begin
1608 result := Default(ITP);
1609 if (exittag <> nil) then exittag^ := 0;
1610 tagmask := tagmask and TagFullMask;
1611 if (tagmask = 0) then exit;
1613 {$IF DEFINED(D2F_DEBUG_XXQ)}
1614 if (assigned(cb)) then e_WriteLog(Format('0: grid pointquery: (%d,%d)', [x, y]), MSG_NOTIFY);
1615 {$ENDIF}
1617 // make coords (0,0)-based
1618 Dec(x, mMinX);
1619 Dec(y, mMinY);
1620 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y >= mHeight*mTileSize) then exit;
1622 curci := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1624 {$IF DEFINED(D2F_DEBUG_XXQ)}
1625 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);
1626 {$ENDIF}
1628 // restore coords
1629 Inc(x, mMinX);
1630 Inc(y, mMinY);
1632 // increase query counter
1633 Inc(mLastQuery);
1634 if (mLastQuery = 0) then
1635 begin
1636 // just in case of overflow
1637 mLastQuery := 1;
1638 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1639 end;
1640 lq := mLastQuery;
1642 {$IF DEFINED(D2F_DEBUG_XXQ)}
1643 if (assigned(cb)) then e_WriteLog(Format('2: grid pointquery: (%d,%d); lq=%u', [x, y, lq]), MSG_NOTIFY);
1644 {$ENDIF}
1646 while (curci <> -1) do
1647 begin
1648 {$IF DEFINED(D2F_DEBUG_XXQ)}
1649 if (assigned(cb)) then e_WriteLog(Format(' cell #%d', [curci]), MSG_NOTIFY);
1650 {$ENDIF}
1651 cc := @mCells[curci];
1652 for f := 0 to GridCellBucketSize-1 do
1653 begin
1654 if (cc.bodies[f] = -1) then break;
1655 px := @mProxies[cc.bodies[f]];
1656 {$IF DEFINED(D2F_DEBUG_XXQ)}
1657 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);
1658 {$ENDIF}
1659 // shit. has to do it this way, so i can change tag in callback
1660 if (px.mQueryMark <> lq) then
1661 begin
1662 px.mQueryMark := lq;
1663 ptag := px.mTag;
1664 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
1665 (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
1666 begin
1667 if assigned(cb) then
1668 begin
1669 if cb(px.mObj, ptag) then
1670 begin
1671 result := px.mObj;
1672 if (exittag <> nil) then exittag^ := ptag;
1673 exit;
1674 end;
1675 end
1676 else
1677 begin
1678 result := px.mObj;
1679 if (exittag <> nil) then exittag^ := ptag;
1680 exit;
1681 end;
1682 end;
1683 end;
1684 end;
1685 curci := cc.next;
1686 end;
1687 end;
1690 // ////////////////////////////////////////////////////////////////////////// //
1691 // no callback: return `true` on the first hit
1692 function TBodyGridBase.forEachInAABB (x, y, w, h: Integer; cb: TGridQueryCB; tagmask: Integer=-1; allowDisabled: Boolean=false): ITP;
1693 var
1694 idx: Integer;
1695 gx, gy: Integer;
1696 curci: Integer;
1697 f: Integer;
1698 cc: PGridCell = nil;
1699 px: PBodyProxyRec;
1700 lq: LongWord;
1701 gw: Integer;
1702 x0, y0: Integer;
1703 ptag: Integer;
1704 begin
1705 result := Default(ITP);
1706 if (w < 1) or (h < 1) then exit;
1707 tagmask := tagmask and TagFullMask;
1708 if (tagmask = 0) then exit;
1710 x0 := x;
1711 y0 := y;
1713 // fix coords
1714 Dec(x, mMinX);
1715 Dec(y, mMinY);
1717 gw := mWidth;
1718 //tsize := mTileSize;
1720 if (x+w <= 0) or (y+h <= 0) then exit;
1721 if (x >= gw*mTileSize) or (y >= mHeight*mTileSize) then exit;
1723 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1724 mInQuery := true;
1726 // increase query counter
1727 Inc(mLastQuery);
1728 if (mLastQuery = 0) then
1729 begin
1730 // just in case of overflow
1731 mLastQuery := 1;
1732 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1733 end;
1734 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
1735 lq := mLastQuery;
1737 // go on
1738 for gy := y div mTileSize to (y+h-1) div mTileSize do
1739 begin
1740 if (gy < 0) then continue;
1741 if (gy >= mHeight) then break;
1742 for gx := x div mTileSize to (x+w-1) div mTileSize do
1743 begin
1744 if (gx < 0) then continue;
1745 if (gx >= gw) then break;
1746 // process cells
1747 curci := mGrid[gy*gw+gx];
1748 while (curci <> -1) do
1749 begin
1750 cc := @mCells[curci];
1751 for f := 0 to GridCellBucketSize-1 do
1752 begin
1753 if (cc.bodies[f] = -1) then break;
1754 px := @mProxies[cc.bodies[f]];
1755 // shit. has to do it this way, so i can change tag in callback
1756 if (px.mQueryMark = lq) then continue;
1757 px.mQueryMark := lq;
1758 ptag := px.mTag;
1759 if (not allowDisabled) and ((ptag and TagDisabled) <> 0) then continue;
1760 if ((ptag and tagmask) = 0) then continue;
1761 if (x0 >= px.mX+px.mWidth) or (y0 >= px.mY+px.mHeight) then continue;
1762 if (x0+w <= px.mX) or (y0+h <= px.mY) then continue;
1763 if assigned(cb) then
1764 begin
1765 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
1766 end
1767 else
1768 begin
1769 result := px.mObj;
1770 mInQuery := false;
1771 exit;
1772 end;
1773 end;
1774 curci := cc.next;
1775 end;
1776 end;
1777 end;
1779 mInQuery := false;
1780 end;
1783 // ////////////////////////////////////////////////////////////////////////// //
1784 function TBodyGridBase.forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
1785 var
1786 lw: TLineWalker;
1787 ccidx: Integer;
1788 cc: PGridCell;
1789 px: PBodyProxyRec;
1790 lq: LongWord;
1791 f, ptag: Integer;
1792 gw, gh, minx, miny: Integer;
1793 x0, y0: Integer;
1794 x1, y1: Integer;
1795 cx, cy: Integer;
1796 //px0, py0, px1, py1: Integer;
1797 begin
1798 log := false;
1799 result := Default(ITP);
1800 tagmask := tagmask and TagFullMask;
1801 if (tagmask = 0) or not assigned(cb) then exit;
1803 gw := mWidth;
1804 gh := mHeight;
1805 minx := mMinX;
1806 miny := mMinY;
1808 // make query coords (0,0)-based
1809 x0 := ax0-minx;
1810 y0 := ay0-miny;
1811 x1 := ax1-minx;
1812 y1 := ay1-miny;
1814 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
1815 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
1817 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1818 mInQuery := true;
1820 // increase query counter
1821 Inc(mLastQuery);
1822 if (mLastQuery = 0) then
1823 begin
1824 // just in case of overflow
1825 mLastQuery := 1;
1826 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1827 end;
1828 lq := mLastQuery;
1830 repeat
1831 lw.getXY(cx, cy);
1832 // check tile
1833 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
1834 // process cells
1835 while (ccidx <> -1) do
1836 begin
1837 cc := @mCells[ccidx];
1838 for f := 0 to GridCellBucketSize-1 do
1839 begin
1840 if (cc.bodies[f] = -1) then break;
1841 px := @mProxies[cc.bodies[f]];
1842 ptag := px.mTag;
1843 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1844 begin
1845 px.mQueryMark := lq; // mark as processed
1846 if cb(px.mObj, ptag) then
1847 begin
1848 result := px.mObj;
1849 mInQuery := false;
1850 exit;
1851 end;
1852 end;
1853 end;
1854 // next cell
1855 ccidx := cc.next;
1856 end;
1857 // done processing cells, move to next tile
1858 until lw.stepToNextTile();
1860 mInQuery := false;
1861 end;
1864 // ////////////////////////////////////////////////////////////////////////// //
1865 // trace box with the given velocity; return object hit (if any)
1866 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
1867 function TBodyGridBase.traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
1868 var
1869 gx, gy: Integer;
1870 ccidx: Integer;
1871 cc: PGridCell;
1872 px: PBodyProxyRec;
1873 lq: LongWord;
1874 f, ptag: Integer;
1875 minu0: Single = 100000.0;
1876 u0: Single;
1877 cx0, cy0, cx1, cy1: Integer;
1878 hitpx: PBodyProxyRec = nil;
1879 begin
1880 result := Default(ITP);
1881 ex := ax0+dx;
1882 ey := ay0+dy;
1883 if (aw < 1) or (ah < 1) then exit;
1885 cx0 := nmin(ax0, ax0+dx);
1886 cy0 := nmin(ay0, ay0+dy);
1887 cx1 := nmax(ax0+aw-1, ax0+aw-1+dx);
1888 cy1 := nmax(ay0+ah-1, ay0+ah-1+dy);
1890 cx0 -= mMinX; cy0 -= mMinY;
1891 cx1 -= mMinX; cy1 -= mMinY;
1893 if (cx1 < 0) or (cy1 < 0) or (cx0 >= mWidth*mTileSize) or (cy0 >= mHeight*mTileSize) then exit;
1895 if (cx0 < 0) then cx0 := 0;
1896 if (cy0 < 0) then cy0 := 0;
1897 if (cx1 >= mWidth*mTileSize) then cx1 := mWidth*mTileSize-1;
1898 if (cy1 >= mHeight*mTileSize) then cy1 := mHeight*mTileSize-1;
1899 // just in case
1900 if (cx0 > cx1) or (cy0 > cy1) then exit;
1902 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1903 mInQuery := true;
1905 // increase query counter
1906 Inc(mLastQuery);
1907 if (mLastQuery = 0) then
1908 begin
1909 // just in case of overflow
1910 mLastQuery := 1;
1911 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1912 end;
1913 lq := mLastQuery;
1915 for gy := cy0 div mTileSize to cy1 div mTileSize do
1916 begin
1917 for gx := cx0 div mTileSize to cx1 div mTileSize do
1918 begin
1919 ccidx := mGrid[gy*mWidth+gx];
1920 while (ccidx <> -1) do
1921 begin
1922 cc := @mCells[ccidx];
1923 for f := 0 to GridCellBucketSize-1 do
1924 begin
1925 if (cc.bodies[f] = -1) then break;
1926 px := @mProxies[cc.bodies[f]];
1927 ptag := px.mTag;
1928 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1929 begin
1930 px.mQueryMark := lq; // mark as processed
1931 if assigned(cb) then
1932 begin
1933 if not cb(px.mObj, ptag) then continue;
1934 end;
1935 if not sweepAABB(ax0, ay0, aw, ah, dx, dy, px.mX, px.mY, px.mWidth, px.mHeight, @u0) then continue;
1936 if (minu0 > u0) then
1937 begin
1938 hitpx := px;
1939 result := px.mObj;
1940 minu0 := u0;
1941 if (u0 = 0.0) then
1942 begin
1943 ex := ax0;
1944 ey := ay0;
1945 mInQuery := false;
1946 exit;
1947 end;
1948 end;
1949 end;
1950 end;
1951 // next cell
1952 ccidx := cc.next;
1953 end;
1954 end;
1955 end;
1957 if (minu0 <= 1.0) then
1958 begin
1959 ex := ax0+round(dx*minu0);
1960 ey := ay0+round(dy*minu0);
1961 // just in case, compensate for floating point inexactness
1962 if (ex >= hitpx.mX) and (ey >= hitpx.mY) and (ex < hitpx.mX+hitpx.mWidth) and (ey < hitpx.mY+hitpx.mHeight) then
1963 begin
1964 ex := ax0+trunc(dx*minu0);
1965 ey := ay0+trunc(dy*minu0);
1966 end;
1967 end;
1969 mInQuery := false;
1970 end;
1973 // ////////////////////////////////////////////////////////////////////////// //
1974 {.$DEFINE D2F_DEBUG_OTR}
1975 function TBodyGridBase.traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
1976 var
1977 ccidx: Integer;
1978 cc: PGridCell;
1979 px: PBodyProxyRec;
1980 ptag: Integer;
1981 minx, miny: Integer;
1982 f, c0, c1: Integer;
1983 x0, y0, x1, y1: Integer;
1984 celly0, celly1: Integer;
1985 dy: Integer;
1986 filled: array[0..mTileSize-1] of Byte;
1987 {$IF DEFINED(D2F_DEBUG_OTR)}
1988 s: AnsiString = '';
1989 {$ENDIF}
1990 begin
1991 result := false;
1992 ex := ax1;
1993 ey := ay1;
1994 if not ((ax0 = ax1) or (ay0 = ay1)) then raise Exception.Create('orthoray is not orthogonal');
1996 tagmask := tagmask and TagFullMask;
1997 if (tagmask = 0) then exit;
1999 if (forEachAtPoint(ax0, ay0, nil, tagmask) = nil) then exit;
2001 minx := mMinX;
2002 miny := mMinY;
2004 // offset query coords to (0,0)-based
2005 x0 := ax0-minx;
2006 y0 := ay0-miny;
2007 x1 := ax1-minx;
2008 y1 := ay1-miny;
2010 if (x0 = x1) then
2011 begin
2012 if (x0 < 0) or (x0 >= mWidth*mTileSize) then exit; // oops
2013 // vertical
2014 if (y0 < y1) then
2015 begin
2016 // down
2017 if (y1 < 0) or (y0 >= mHeight*mTileSize) then exit;
2018 //if (ay0 < 0) then ay0 := 0;
2019 if (y0 < 0) then exit;
2020 if (y1 >= mHeight*mTileSize) then y1 := mHeight*mTileSize-1;
2021 dy := 1;
2022 end
2023 else
2024 begin
2025 // up
2026 if (y0 < 0) or (y1 >= mHeight*mTileSize) then exit;
2027 //if (ay1 < 0) then ay1 := 0;
2028 if (y1 < 0) then exit;
2029 if (y0 >= mHeight*mTileSize) then y0 := mHeight*mTileSize-1;
2030 dy := -1;
2031 end;
2032 // check tile
2033 while true do
2034 begin
2035 ccidx := mGrid[(y0 div mTileSize)*mWidth+(x0 div mTileSize)];
2036 FillChar(filled, sizeof(filled), 0);
2037 celly0 := y0 and (not (mTileSize-1));
2038 celly1 := celly0+mTileSize-1;
2039 while (ccidx <> -1) do
2040 begin
2041 cc := @mCells[ccidx];
2042 for f := 0 to GridCellBucketSize-1 do
2043 begin
2044 if (cc.bodies[f] = -1) then break;
2045 px := @mProxies[cc.bodies[f]];
2046 ptag := px.mTag;
2047 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
2048 (ax0 >= px.x0) and (ax0 <= px.x1) then
2049 begin
2050 // bound c0 and c1 to cell
2051 c0 := nclamp(px.y0-miny, celly0, celly1);
2052 c1 := nclamp(px.y1-miny, celly0, celly1);
2053 // fill the thing
2054 {$IF DEFINED(D2F_DEBUG_OTR)}
2055 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)]);
2056 {$ENDIF}
2057 //assert(c0 <= c1);
2058 FillChar(filled[c0-celly0], c1-c0+1, 1);
2059 end;
2060 end;
2061 // next cell
2062 ccidx := cc.next;
2063 end;
2064 {$IF DEFINED(D2F_DEBUG_OTR)}
2065 s := formatstrf(' x=%s; ay0=%s; ay1=%s; y0=%s; celly0=%s; celly1=%s; dy=%s; [', [ax0, ay0, ay1, y0, celly0, celly1, dy]);
2066 for f := 0 to High(filled) do if (filled[f] <> 0) then s += '1' else s += '0';
2067 s += ']';
2068 e_LogWriteln(s);
2069 {$ENDIF}
2070 // now go till we hit cell boundary or empty space
2071 if (dy < 0) then
2072 begin
2073 // up
2074 while (y0 >= celly0) and (filled[y0-celly0] <> 0) do
2075 begin
2076 {$IF DEFINED(D2F_DEBUG_OTR)}
2077 e_LogWritefln(' filled: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2078 {$ENDIF}
2079 Dec(y0);
2080 Dec(ay0);
2081 end;
2082 {$IF DEFINED(D2F_DEBUG_OTR)}
2083 e_LogWritefln(' span done: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2084 {$ENDIF}
2085 if (ay0 <= ay1) then begin ey := ay1; result := false; exit; end;
2086 if (y0 >= celly0) then begin ey := ay0+1; {assert(forEachAtPoint(ex, ey, nil, tagmask) <> nil);} result := true; exit; end;
2087 end
2088 else
2089 begin
2090 // down
2091 while (y0 <= celly1) and (filled[y0-celly0] <> 0) do begin Inc(y0); Inc(ay0); end;
2092 if (ay0 >= ay1) then begin ey := ay1; result := false; exit; end;
2093 if (y0 <= celly1) then begin ey := ay0-1; result := true; exit; end;
2094 end;
2095 end;
2096 end
2097 else
2098 begin
2099 // horizontal
2100 assert(false);
2101 end;
2102 end;
2105 // ////////////////////////////////////////////////////////////////////////// //
2106 function TBodyGridBase.traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2107 var
2108 ex, ey: Integer;
2109 begin
2110 result := traceRay(ex, ey, x0, y0, x1, y1, cb, tagmask);
2111 end;
2114 // no callback: return `true` on the nearest hit
2115 // you are not supposed to understand this
2116 function TBodyGridBase.traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2117 var
2118 lw, sweepw: TLineWalker;
2119 ccidx: Integer;
2120 cc: PGridCell;
2121 px: PBodyProxyRec;
2122 lq: LongWord;
2123 f, ptag: Integer;
2124 gw, gh, minx, miny: Integer;
2125 x0, y0: Integer;
2126 x1, y1: Integer;
2127 cx, cy: Integer;
2128 px0, py0, px1, py1: Integer;
2129 lastDistSq, distSq, hx, hy: Integer;
2130 firstCell: Boolean = true;
2131 wasHit: Boolean;
2132 begin
2133 result := Default(ITP);
2134 tagmask := tagmask and TagFullMask;
2135 if (tagmask = 0) then exit;
2137 gw := mWidth;
2138 gh := mHeight;
2139 minx := mMinX;
2140 miny := mMinY;
2142 // make query coords (0,0)-based
2143 x0 := ax0-minx;
2144 y0 := ay0-miny;
2145 x1 := ax1-minx;
2146 y1 := ay1-miny;
2148 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
2149 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
2151 sweepw := TLineWalker.Create(0, 0, 1, 1); // doesn't matter, just shut ups the compiler
2153 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
2155 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2156 mInQuery := true;
2158 // increase query counter
2159 Inc(mLastQuery);
2160 if (mLastQuery = 0) then
2161 begin
2162 // just in case of overflow
2163 mLastQuery := 1;
2164 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2165 end;
2166 lq := mLastQuery;
2168 repeat
2169 lw.getXY(cx, cy);
2170 // check tile
2171 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
2172 // process cells
2173 wasHit := false;
2174 while (ccidx <> -1) do
2175 begin
2176 cc := @mCells[ccidx];
2177 for f := 0 to GridCellBucketSize-1 do
2178 begin
2179 if (cc.bodies[f] = -1) then break;
2180 px := @mProxies[cc.bodies[f]];
2181 ptag := px.mTag;
2182 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2183 begin
2184 px.mQueryMark := lq; // mark as processed
2185 if assigned(cb) then
2186 begin
2187 if not cb(px.mObj, ptag) then continue;
2188 end;
2189 // get adjusted proxy coords
2190 px0 := px.mX-minx;
2191 py0 := px.mY-miny;
2192 px1 := px0+px.mWidth-1;
2193 py1 := py0+px.mHeight-1;
2194 // inside?
2195 if firstCell and (x0 >= px0) and (y0 >= py0) and (x0 <= px1) and (y0 <= py1) then
2196 begin
2197 // oops
2198 ex := ax0;
2199 ey := ay0;
2200 result := px.mObj;
2201 mInQuery := false;
2202 exit;
2203 end;
2204 // do line-vs-aabb test
2205 sweepw.setClip(px0, py0, px1, py1);
2206 if sweepw.setup(x0, y0, x1, y1) then
2207 begin
2208 // hit detected
2209 sweepw.getPrevXY(hx, hy);
2210 distSq := distanceSq(x0, y0, hx, hy);
2211 if (distSq < lastDistSq) then
2212 begin
2213 lastDistSq := distSq;
2214 ex := hx+minx;
2215 ey := hy+miny;
2216 result := px.mObj;
2217 // if this is not a first cell, get outta here
2218 if not firstCell then begin mInQuery := false; exit; end;
2219 wasHit := true;
2220 end;
2221 end;
2222 end;
2223 end;
2224 // next cell
2225 ccidx := cc.next;
2226 end;
2227 // done processing cells; exit if we registered a hit
2228 // next cells can't have better candidates, obviously
2229 if wasHit then begin mInQuery := false; exit; end;
2230 firstCell := false;
2231 // move to next tile
2232 until lw.stepToNextTile();
2234 mInQuery := false;
2235 end;
2238 // ////////////////////////////////////////////////////////////////////////// //
2239 // no callback: return `true` on the nearest hit
2240 function TBodyGridBase.traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2241 var
2242 ex, ey: Integer;
2243 begin
2244 result := traceRayOld(ex, ey, x0, y0, x1, y1, cb, tagmask);
2245 end;
2248 // no callback: return `true` on the nearest hit
2249 // you are not supposed to understand this
2250 function TBodyGridBase.traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2251 var
2252 wx0, wy0, wx1, wy1: Integer; // window coordinates
2253 stx, sty: Integer; // "steps" for x and y axes
2254 dsx, dsy: Integer; // "lengthes" for x and y axes
2255 dx2, dy2: Integer; // "double lengthes" for x and y axes
2256 xd, yd: Integer; // current coord
2257 e: Integer; // "error" (as in bresenham algo)
2258 rem: Integer;
2259 term: Integer;
2260 xptr, yptr: PInteger;
2261 xfixed: Boolean;
2262 temp: Integer;
2263 prevx, prevy: Integer;
2264 lastDistSq: Integer;
2265 ccidx, curci: Integer;
2266 hasUntried: Boolean;
2267 lastGA: Integer = -1;
2268 ga, x, y: Integer;
2269 lastObj: ITP;
2270 wasHit: Boolean = false;
2271 gw, gh, minx, miny, maxx, maxy: Integer;
2272 cc: PGridCell;
2273 px: PBodyProxyRec;
2274 lq: LongWord;
2275 f, ptag, distSq: Integer;
2276 x0, y0, x1, y1: Integer;
2277 //swapped: Boolean = false; // true: xd is yd, and vice versa
2278 // horizontal walker
2279 {$IFDEF GRID_USE_ORTHO_ACCEL}
2280 wklen, wkstep: Integer;
2281 //wksign: Integer;
2282 hopt: Boolean;
2283 {$ENDIF}
2284 // skipper
2285 xdist, ydist: Integer;
2286 begin
2287 result := Default(ITP);
2288 lastObj := Default(ITP);
2289 tagmask := tagmask and TagFullMask;
2290 ex := ax1; // why not?
2291 ey := ay1; // why not?
2292 if (tagmask = 0) then exit;
2294 if (ax0 = ax1) and (ay0 = ay1) then
2295 begin
2296 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2297 if (result <> nil) then
2298 begin
2299 if assigned(cb) and not cb(result, ptag, ax0, ay0, ax0, ay0) then result := Default(ITP);
2300 end;
2301 exit;
2302 end;
2304 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
2306 gw := mWidth;
2307 gh := mHeight;
2308 minx := mMinX;
2309 miny := mMinY;
2310 maxx := gw*mTileSize-1;
2311 maxy := gh*mTileSize-1;
2313 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2314 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);
2315 {$ENDIF}
2317 x0 := ax0;
2318 y0 := ay0;
2319 x1 := ax1;
2320 y1 := ay1;
2322 // offset query coords to (0,0)-based
2323 Dec(x0, minx);
2324 Dec(y0, miny);
2325 Dec(x1, minx);
2326 Dec(y1, miny);
2328 // clip rectange
2329 wx0 := 0;
2330 wy0 := 0;
2331 wx1 := maxx;
2332 wy1 := maxy;
2334 // horizontal setup
2335 if (x0 < x1) then
2336 begin
2337 // from left to right
2338 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
2339 stx := 1; // going right
2340 end
2341 else
2342 begin
2343 // from right to left
2344 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
2345 stx := -1; // going left
2346 x0 := -x0;
2347 x1 := -x1;
2348 wx0 := -wx0;
2349 wx1 := -wx1;
2350 swapInt(wx0, wx1);
2351 end;
2353 // vertical setup
2354 if (y0 < y1) then
2355 begin
2356 // from top to bottom
2357 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
2358 sty := 1; // going down
2359 end
2360 else
2361 begin
2362 // from bottom to top
2363 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
2364 sty := -1; // going up
2365 y0 := -y0;
2366 y1 := -y1;
2367 wy0 := -wy0;
2368 wy1 := -wy1;
2369 swapInt(wy0, wy1);
2370 end;
2372 dsx := x1-x0;
2373 dsy := y1-y0;
2375 if (dsx < dsy) then
2376 begin
2377 //swapped := true;
2378 xptr := @yd;
2379 yptr := @xd;
2380 swapInt(x0, y0);
2381 swapInt(x1, y1);
2382 swapInt(dsx, dsy);
2383 swapInt(wx0, wy0);
2384 swapInt(wx1, wy1);
2385 swapInt(stx, sty);
2386 end
2387 else
2388 begin
2389 xptr := @xd;
2390 yptr := @yd;
2391 end;
2393 dx2 := 2*dsx;
2394 dy2 := 2*dsy;
2395 xd := x0;
2396 yd := y0;
2397 e := 2*dsy-dsx;
2398 term := x1;
2400 xfixed := false;
2401 if (y0 < wy0) then
2402 begin
2403 // clip at top
2404 temp := dx2*(wy0-y0)-dsx;
2405 xd += temp div dy2;
2406 rem := temp mod dy2;
2407 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
2408 if (xd+1 >= wx0) then
2409 begin
2410 yd := wy0;
2411 e -= rem+dsx;
2412 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
2413 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
2414 xfixed := true;
2415 end;
2416 end;
2418 if (not xfixed) and (x0 < wx0) then
2419 begin
2420 // clip at left
2421 temp := dy2*(wx0-x0);
2422 yd += temp div dx2;
2423 rem := temp mod dx2;
2424 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
2425 xd := wx0;
2426 e += rem;
2427 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
2428 end;
2430 if (y1 > wy1) then
2431 begin
2432 // clip at bottom
2433 temp := dx2*(wy1-y0)+dsx;
2434 term := x0+temp div dy2;
2435 rem := temp mod dy2;
2436 if (rem = 0) then Dec(term);
2437 end;
2439 if (term > wx1) then term := wx1; // clip at right
2441 Inc(term); // draw last point
2442 //if (term = xd) then exit; // this is the only point, get out of here
2444 if (sty = -1) then yd := -yd;
2445 if (stx = -1) then begin xd := -xd; term := -term; end;
2446 dx2 -= dy2;
2448 // first move, to skip starting point
2449 // DON'T DO THIS! loop will take care of that
2450 if (xd = term) then
2451 begin
2452 //FIXME!
2453 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2454 if (result <> nil) then
2455 begin
2456 if assigned(cb) then
2457 begin
2458 if cb(result, ptag, ax0, ay0, ax0, ay0) then
2459 begin
2460 ex := ax0;
2461 ey := ay0;
2462 end
2463 else
2464 begin
2465 result := nil;
2466 end;
2467 end
2468 else
2469 begin
2470 ex := ax0;
2471 ey := ay0;
2472 end;
2473 end;
2474 exit;
2475 end;
2477 prevx := xptr^+minx;
2478 prevy := yptr^+miny;
2479 (*
2480 // move coords
2481 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2482 xd += stx;
2483 // done?
2484 if (xd = term) then exit;
2485 *)
2487 {$IF DEFINED(D2F_DEBUG)}
2488 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2489 {$ENDIF}
2490 // DON'T DO THIS! loop will take care of that
2491 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
2492 //ccidx := mGrid[lastGA];
2494 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2495 //if assigned(dbgRayTraceTileHitCB) then e_WriteLog('1:TRACING!', MSG_NOTIFY);
2496 {$ENDIF}
2498 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
2500 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2501 mInQuery := true;
2503 // increase query counter
2504 Inc(mLastQuery);
2505 if (mLastQuery = 0) then
2506 begin
2507 // just in case of overflow
2508 mLastQuery := 1;
2509 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2510 end;
2511 lq := mLastQuery;
2513 {$IFDEF GRID_USE_ORTHO_ACCEL}
2514 // if this is strict horizontal/vertical trace, use optimized codepath
2515 if (ax0 = ax1) or (ay0 = ay1) then
2516 begin
2517 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
2518 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
2519 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
2520 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
2521 hopt := (ay0 = ay1); // horizontal?
2522 if (stx < 0) then begin {wksign := -1;} wklen := -(term-xd); end else begin {wksign := 1;} wklen := term-xd; end;
2523 {$IF DEFINED(D2F_DEBUG)}
2524 if dbgShowTraceLog then e_LogWritefln('optimized htrace; wklen=%d', [wklen]);
2525 {$ENDIF}
2526 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2527 // one of those will never change
2528 x := xptr^+minx;
2529 y := yptr^+miny;
2530 while (wklen > 0) do
2531 begin
2532 {$IF DEFINED(D2F_DEBUG)}
2533 if dbgShowTraceLog then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; y=%d; y=%d', [ga, xptr^+minx, yptr^+miny, y, ay0]);
2534 {$ENDIF}
2535 // new tile?
2536 if (ga <> lastGA) then
2537 begin
2538 lastGA := ga;
2539 ccidx := mGrid[lastGA];
2540 // convert coords to map (to avoid ajdusting coords inside the loop)
2541 if hopt then x := xptr^+minx else y := yptr^+miny;
2542 while (ccidx <> -1) do
2543 begin
2544 cc := @mCells[ccidx];
2545 for f := 0 to GridCellBucketSize-1 do
2546 begin
2547 if (cc.bodies[f] = -1) then break;
2548 px := @mProxies[cc.bodies[f]];
2549 ptag := px.mTag;
2550 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) and
2551 // constant coord should be inside
2552 ((hopt and (y >= px.y0) and (y <= px.y1)) or
2553 ((not hopt) and (x >= px.x0) and (x <= px.x1))) then
2554 begin
2555 px.mQueryMark := lq; // mark as processed
2556 // inside the proxy?
2557 if (hopt and (x > px.x0) and (x < px.x1)) or
2558 ((not hopt) and (y > px.y0) and (y < px.y1)) then
2559 begin
2560 // setup prev[xy]
2561 if assigned(cb) then
2562 begin
2563 if cb(px.mObj, ptag, x, y, x, y) then
2564 begin
2565 result := px.mObj;
2566 ex := x;
2567 ey := y;
2568 mInQuery := false;
2569 exit;
2570 end;
2571 end
2572 else
2573 begin
2574 distSq := distanceSq(ax0, ay0, x, y);
2575 {$IF DEFINED(D2F_DEBUG)}
2576 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]);
2577 {$ENDIF}
2578 if (distSq < lastDistSq) then
2579 begin
2580 ex := x;
2581 ey := y;
2582 result := px.mObj;
2583 mInQuery := false;
2584 exit;
2585 end;
2586 end;
2587 continue;
2588 end;
2589 // remember this hitpoint if it is nearer than an old one
2590 // setup prev[xy]
2591 if hopt then
2592 begin
2593 // horizontal trace
2594 prevy := y;
2595 y := yptr^+miny;
2596 if (stx < 0) then
2597 begin
2598 // going left
2599 if (x < px.x1) then continue; // not on the right edge
2600 x := px.x1;
2601 prevx := x+1;
2602 end
2603 else
2604 begin
2605 // going right
2606 if (x > px.x0) then continue; // not on the left edge
2607 x := px.x0;
2608 prevx := x-1;
2609 end;
2610 end
2611 else
2612 begin
2613 // vertical trace
2614 prevx := x;
2615 x := xptr^+minx;
2616 if (stx < 0) then
2617 begin
2618 // going up
2619 if (y < px.y1) then continue; // not on the bottom edge
2620 y := px.y1;
2621 prevy := x+1;
2622 end
2623 else
2624 begin
2625 // going down
2626 if (y > px.y0) then continue; // not on the top edge
2627 y := px.y0;
2628 prevy := y-1;
2629 end;
2630 end;
2631 if assigned(cb) then
2632 begin
2633 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2634 begin
2635 result := px.mObj;
2636 ex := prevx;
2637 ey := prevy;
2638 mInQuery := false;
2639 exit;
2640 end;
2641 end
2642 else
2643 begin
2644 distSq := distanceSq(ax0, ay0, prevx, prevy);
2645 {$IF DEFINED(D2F_DEBUG)}
2646 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]);
2647 {$ENDIF}
2648 if (distSq < lastDistSq) then
2649 begin
2650 wasHit := true;
2651 lastDistSq := distSq;
2652 ex := prevx;
2653 ey := prevy;
2654 lastObj := px.mObj;
2655 end;
2656 end;
2657 end;
2658 end;
2659 // next cell
2660 ccidx := cc.next;
2661 end;
2662 if wasHit and not assigned(cb) then begin result := lastObj; mInQuery := false; exit; end;
2663 if assigned(cb) and cb(nil, 0, x, y, x, y) then begin result := lastObj; mInQuery := false; exit; end;
2664 end;
2665 // skip to next tile
2666 if hopt then
2667 begin
2668 if (stx > 0) then
2669 begin
2670 // to the right
2671 wkstep := ((xptr^ or (mTileSize-1))+1)-xptr^;
2672 {$IF DEFINED(D2F_DEBUG)}
2673 if dbgShowTraceLog then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2674 {$ENDIF}
2675 if (wkstep >= wklen) then break;
2676 Inc(xptr^, wkstep);
2677 Inc(ga);
2678 end
2679 else
2680 begin
2681 // to the left
2682 wkstep := xptr^-((xptr^ and (not (mTileSize-1)))-1);
2683 {$IF DEFINED(D2F_DEBUG)}
2684 if dbgShowTraceLog then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2685 {$ENDIF}
2686 if (wkstep >= wklen) then break;
2687 Dec(xptr^, wkstep);
2688 Dec(ga);
2689 end;
2690 end
2691 else
2692 begin
2693 if (stx > 0) then
2694 begin
2695 // to the down
2696 wkstep := ((yptr^ or (mTileSize-1))+1)-yptr^;
2697 {$IF DEFINED(D2F_DEBUG)}
2698 if dbgShowTraceLog then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2699 {$ENDIF}
2700 if (wkstep >= wklen) then break;
2701 Inc(yptr^, wkstep);
2702 Inc(ga, mWidth);
2703 end
2704 else
2705 begin
2706 // to the up
2707 wkstep := yptr^-((yptr^ and (not (mTileSize-1)))-1);
2708 {$IF DEFINED(D2F_DEBUG)}
2709 if dbgShowTraceLog then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2710 {$ENDIF}
2711 if (wkstep >= wklen) then break;
2712 Dec(yptr^, wkstep);
2713 Dec(ga, mWidth);
2714 end;
2715 end;
2716 Dec(wklen, wkstep);
2717 end;
2718 // we can travel less than one cell
2719 if wasHit and not assigned(cb) then result := lastObj else begin ex := ax1; ey := ay1; end;
2720 mInQuery := false;
2721 exit;
2722 end;
2723 {$ENDIF}
2725 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2726 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2727 {$ENDIF}
2729 //e_LogWritefln('*********************', []);
2730 ccidx := -1;
2731 // can omit checks
2732 while (xd <> term) do
2733 begin
2734 // check cell(s)
2735 {$IF DEFINED(D2F_DEBUG)}
2736 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2737 {$ENDIF}
2738 // new tile?
2739 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2740 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2741 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);
2742 {$ENDIF}
2743 if (ga <> lastGA) then
2744 begin
2745 // yes
2746 {$IF DEFINED(D2F_DEBUG)}
2747 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2748 {$ENDIF}
2749 if (ccidx <> -1) then
2750 begin
2751 // signal cell completion
2752 if assigned(cb) then
2753 begin
2754 if cb(nil, 0, xptr^+minx, yptr^+miny, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2755 end
2756 else if wasHit then
2757 begin
2758 result := lastObj;
2759 mInQuery := false;
2760 exit;
2761 end;
2762 end;
2763 lastGA := ga;
2764 ccidx := mGrid[lastGA];
2765 end;
2766 // has something to process in this tile?
2767 if (ccidx <> -1) then
2768 begin
2769 // process cell
2770 curci := ccidx;
2771 hasUntried := false; // this will be set to `true` if we have some proxies we still want to process at the next step
2772 // convert coords to map (to avoid ajdusting coords inside the loop)
2773 x := xptr^+minx;
2774 y := yptr^+miny;
2775 // process cell list
2776 while (curci <> -1) do
2777 begin
2778 cc := @mCells[curci];
2779 for f := 0 to GridCellBucketSize-1 do
2780 begin
2781 if (cc.bodies[f] = -1) then break;
2782 px := @mProxies[cc.bodies[f]];
2783 ptag := px.mTag;
2784 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2785 begin
2786 // can we process this proxy?
2787 if (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
2788 begin
2789 px.mQueryMark := lq; // mark as processed
2790 if assigned(cb) then
2791 begin
2792 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2793 begin
2794 result := px.mObj;
2795 ex := prevx;
2796 ey := prevy;
2797 mInQuery := false;
2798 exit;
2799 end;
2800 end
2801 else
2802 begin
2803 // remember this hitpoint if it is nearer than an old one
2804 distSq := distanceSq(ax0, ay0, prevx, prevy);
2805 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2806 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);
2807 {$ENDIF}
2808 if (distSq < lastDistSq) then
2809 begin
2810 wasHit := true;
2811 lastDistSq := distSq;
2812 ex := prevx;
2813 ey := prevy;
2814 lastObj := px.mObj;
2815 end;
2816 end;
2817 end
2818 else
2819 begin
2820 // this is possibly interesting proxy, set "has more to check" flag
2821 hasUntried := true;
2822 end;
2823 end;
2824 end;
2825 // next cell
2826 curci := cc.next;
2827 end;
2828 // still has something interesting in this cell?
2829 if not hasUntried then
2830 begin
2831 // nope, don't process this cell anymore; signal cell completion
2832 ccidx := -1;
2833 if assigned(cb) then
2834 begin
2835 if cb(nil, 0, x, y, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2836 end
2837 else if wasHit then
2838 begin
2839 result := lastObj;
2840 mInQuery := false;
2841 exit;
2842 end;
2843 end;
2844 end;
2845 if (ccidx = -1) then
2846 begin
2847 // move to cell edge, as we have nothing to trace here anymore
2848 if (stx < 0) then xdist := xd and (not (mTileSize-1)) else xdist := xd or (mTileSize-1);
2849 if (sty < 0) then ydist := yd and (not (mTileSize-1)) else ydist := yd or (mTileSize-1);
2850 //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]);
2851 while (xd <> xdist) and (yd <> ydist) do
2852 begin
2853 // step
2854 xd += stx;
2855 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2856 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
2857 if (xd = term) then break;
2858 end;
2859 //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]);
2860 if (xd = term) then break;
2861 end;
2862 //putPixel(xptr^, yptr^);
2863 // move coords
2864 prevx := xptr^+minx;
2865 prevy := yptr^+miny;
2866 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2867 xd += stx;
2868 end;
2869 // we can travel less than one cell
2870 if wasHit and not assigned(cb) then
2871 begin
2872 result := lastObj;
2873 end
2874 else
2875 begin
2876 ex := ax1; // why not?
2877 ey := ay1; // why not?
2878 end;
2880 mInQuery := false;
2881 end;
2884 end.