]> git.pond.sub.org Git - empserver/blob - src/lib/common/path.c
Indented with src/scripts/indent-emp.
[empserver] / src / lib / common / path.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2000, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                           Ken Stevens, Steve McClure
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *  ---
21  *
22  *  See the "LEGAL", "LICENSE", "CREDITS" and "README" files for all the
23  *  related information and legal notices. It is expected that any future
24  *  projects/authors will amend these files as needed.
25  *
26  *  ---
27  *
28  *  path.c: Empire/A* Interface code.  Provides callbacks for A* code and
29  *          a sector cache to speed things up.  Define BP_STATS for sector
30  *          cache statistics, AS_STATS for A* statistics.
31  * 
32  *  Known contributors to this file:
33  *     Phil Lapsley, 1991
34  *     Dave Pare, 1991
35  *     Thomas Ruschak, 1993
36  *     Steve McClure, 1997
37  */
38
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include "../as/as.h"
42 #include "misc.h"
43 #include "path.h"
44 #include "xy.h"
45 #include "sect.h"
46 #include "file.h"
47 #include "common.h"
48 #include "gen.h"
49 #include "optlist.h"
50
51 /* STM - The server is now reliant on the sector file being
52  * memory mapped for other things.  So, this code has been
53  * setup to have the sector hashing #ifdef'd instead so that
54  * we don't have to do runtime checking.  If someone moves
55  * the sector file to me non-memory mapped, they have larger
56  * problems than this, and can just turn this back on.  Then
57  * again, their performance will be so bad going to a file
58  * all the time, it won't matter. */
59
60 /*#define DO_EFF_MEM_CHECKING*/
61
62
63 /* XXX won't need sector hash when sect file is memory mapped */
64
65 #define BP_SCTHASHSIZE  128     /* sector cache hash table size */
66 #define BP_ASHASHSIZE   128     /* A* queue hash table size */
67 #define BP_NEIGHBORS    6       /* max number of neighbors */
68
69 struct sctcache {
70     coord x, y;
71     struct sctstr *sp;
72     struct sctcache *next;
73 };
74
75 struct bestp {
76     struct sctcache *sctcachetab[BP_SCTHASHSIZE];
77     int sctcache_hits;
78     int sctcache_misses;
79     int bp_mobtype;
80     struct as_data *adp;
81 };
82
83 #ifdef DO_EFF_MEM_CHECKING
84
85 static struct sctstr *bp_getsect(struct bestp *bp, coord x, coord y);
86 static struct sctstr *bp_sctcache_get(struct bestp *bp, coord x, coord y);
87 static void bp_sctcache_set(struct bestp *bp, coord x, coord y,
88                             struct sctstr *sp);
89 static void bp_sctcache_zap(struct bestp *bp);
90
91 #endif /* DO_EFF_MEM_CHECKING */
92
93 static int bp_path(struct as_path *pp, s_char *buf);
94 static int bp_neighbors(struct as_coord c, struct as_coord *cp,
95                         s_char *pp);
96 static double bp_lbcost(struct as_coord from, struct as_coord to,
97                         s_char *pp);
98 static double bp_realcost(struct as_coord from, struct as_coord to,
99                           s_char *pp);
100 static double bp_seccost(struct as_coord from, struct as_coord to,
101                          s_char *pp);
102 static int bp_coord_hash(struct as_coord c);
103
104 struct empfile *ep;
105
106 /* We use this for caching neighbors.  It never changes except
107  * at reboot time (maybe) so we never need to free it */
108 struct sctstr **neighsects = (struct sctstr **)0;
109
110 s_char *
111 bp_init(void)
112 {
113     struct bestp *bp;
114
115     ep = &empfile[EF_SECTOR];
116
117     bp = (struct bestp *)malloc(sizeof(*bp));
118     bzero((s_char *)bp, sizeof(*bp));
119     bp->adp = as_init(BP_NEIGHBORS, BP_ASHASHSIZE, bp_coord_hash,
120                       bp_neighbors, bp_lbcost, bp_realcost,
121                       bp_seccost, (s_char *)bp);
122
123     if (bp->adp == NULL)
124         return NULL;
125
126     if (neighsects == (struct sctstr **)0)
127         neighsects = (struct sctstr **)calloc(1, (sizeof(struct sctstr *) *
128                                                   ((WORLD_X * WORLD_Y) /
129                                                    2) * 6));
130
131     return (s_char *)bp;
132 }
133
134 /*
135  * Find the best path from sector to to sector, and put the Empire movement
136  * string in path.  Return 0 on success, -1 on error.
137  */
138 int
139 best_path(struct sctstr *from, struct sctstr *to, s_char *path,
140           int mob_type)
141 {
142     static struct bestp *mybestpath;
143     struct as_data *adp;
144     struct as_path *ap;
145
146     if (mybestpath == 0)
147         mybestpath = (struct bestp *)bp_init();
148     adp = mybestpath->adp;
149 #ifdef DO_EFF_MEM_CHECKING
150     bp_sctcache_zap(mybestpath);
151 #endif
152     ap = as_find_cachepath(from->sct_x, from->sct_y, to->sct_x, to->sct_y);
153     if (ap == NULL) {
154         adp->from.x = from->sct_x;
155         adp->from.y = from->sct_y;
156         adp->to.x = to->sct_x;
157         adp->to.y = to->sct_y;
158         mybestpath->bp_mobtype = mob_type;
159
160         if (as_search(adp) < 0)
161             return -1;
162         ap = adp->path;
163     }
164
165     if (bp_path(ap, path) < 0)
166         return -1;
167
168 #ifdef AS_STATS
169     as_stats(adp, stderr);
170 #endif /* AS_STATS */
171 #ifdef BP_STATS
172     fprintf(stderr, "best path %s\n", path);
173     fprintf(stderr, "cache hits/misses: %d/%d\n",
174             bp->sctcache_hits, bp->sctcache_misses);
175 #endif /* BP_STATS */
176     return 0;
177 }
178
179 /*
180  * Translate an A* path into an empire movement string.  Return 0 on
181  * success, -1 on failure.
182  */
183 static int
184 bp_path(struct as_path *pp, s_char *buf)
185 {
186     struct as_path *np;
187     s_char *cp = buf;
188     int dx, dy;
189     int n;
190
191     np = pp->next;
192     while (np) {
193         dx = np->c.x - pp->c.x;
194         /* deal with wraparound from non-neg coords */
195         if (dx < -2)
196             dx += WORLD_X;
197         else if (dx > 2)
198             dx -= WORLD_X;
199         dy = np->c.y - pp->c.y;
200         if (dy < -1)
201             dy += WORLD_Y;
202         else if (dy > 1)
203             dy -= WORLD_Y;
204         for (n = 1; n <= 6; n++)
205             if (dx == diroff[n][0] && dy == diroff[n][1])
206                 break;
207         if (n > 6)
208             return -1;
209
210         *cp++ = dirch[n];
211         pp = np;
212         np = np->next;
213     }
214     *cp = '\0';
215     return 0;
216 }
217
218 /*
219  * Find coords neighboring this sector; return number of such
220  * coords, and coordinartes themselves in an array pointed
221  * to by *cpp.
222  * XXX need to check ownership, sector types, etc.
223  */
224 static int
225 bp_neighbors(struct as_coord c, struct as_coord *cp, s_char *pp)
226 {
227 #ifdef DO_EFF_MEM_CHECKING
228     struct bestp *bp = (struct bestp *)pp;
229 #endif /* DO_EFF_MEM_CHECKING */
230     coord x, y;
231     coord nx, ny;
232     int n = 0, q;
233     struct sctstr *sp, *from, **ssp;
234     /* Six pointers, just in case our cache isn't there */
235     struct sctstr *tsp[] = { 0, 0, 0, 0, 0, 0 };
236     int sx, sy, offset;
237
238     x = c.x;
239     y = c.y;
240 #ifdef DO_EFF_MEM_CHECKING
241     if ((ep->flags & EFF_MEM) == 0) {
242         from = bp_getsect(bp, x, y);
243     } else {
244 #endif /* DO_EFF_MEM_CHECKING */
245         sx = XNORM(x);
246         sy = YNORM(y);
247         offset = (sy * WORLD_X + sx) / 2;
248         from = (struct sctstr *)(ep->cache + ep->size * offset);
249 #ifdef DO_EFF_MEM_CHECKING
250     }
251 #endif /* DO_EFF_MEM_CHECKING */
252
253     if (neighsects == (struct sctstr **)0)
254         ssp = (struct sctstr **)&tsp[0];
255     else
256         ssp = (struct sctstr **)&neighsects[offset * 6];
257     for (q = 1; q <= 6; q++, ssp++) {
258         if (*ssp == (struct sctstr *)0) {
259             /* We haven't cached this neighbor yet */
260             nx = x + diroff[q][0];
261             ny = y + diroff[q][1];
262             sx = XNORM(nx);
263             sy = YNORM(ny);
264 #ifdef DO_EFF_MEM_CHECKING
265             if ((ep->flags & EFF_MEM) == 0) {
266                 sp = bp_getsect(bp, nx, ny);
267             } else {
268 #endif /* DO_EFF_MEM_CHECKING */
269                 offset = (sy * WORLD_X + sx) / 2;
270                 sp = (struct sctstr *)(ep->cache + ep->size * offset);
271                 /* We can only save in our neighbor cache if the
272                    sector file is in memory */
273                 *ssp = sp;
274 #ifdef DO_EFF_MEM_CHECKING
275             }
276 #endif /* DO_EFF_MEM_CHECKING */
277         } else {
278             sp = *ssp;
279             sx = XNORM(sp->sct_x);
280             sy = YNORM(sp->sct_y);
281         }
282         /* No need to calculate cost each time, just make sure we can
283            move through it.  We calculate it later. */
284         if (dchr[sp->sct_type].d_mcst == 0)
285             continue;
286         if (sp->sct_own != from->sct_own)
287             continue;
288         cp[n].x = sx;
289         cp[n].y = sy;
290         n++;
291     }
292     return (n);
293 }
294
295 /*
296  * Compute a lower-bound on the cost from "from" to "to".
297  */
298 /*ARGSUSED*/
299 static double
300 bp_lbcost(struct as_coord from, struct as_coord to, s_char *pp)
301 {
302     struct bestp *bp = (struct bestp *)pp;
303     struct sctstr *ts;
304     float cost;
305     int x, y, sx, sy, offset;
306
307 #ifdef DO_EFF_MEM_CHECKING
308     if ((ep->flags & EFF_MEM) == 0) {
309         ts = bp_getsect(bp, (coord)to.x, (coord)to.y);
310     } else {
311 #endif /* DO_EFF_MEM_CHECKING */
312         x = to.x;
313         y = to.y;
314         sx = XNORM(x);
315         sy = YNORM(y);
316         offset = (sy * WORLD_X + sx) / 2;
317         ts = (struct sctstr *)(ep->cache + ep->size * offset);
318 #ifdef DO_EFF_MEM_CHECKING
319     }
320 #endif /* DO_EFF_MEM_CHECKING */
321     cost = sector_mcost(ts, bp->bp_mobtype);
322     return (cost);
323 }
324
325 /*
326  * Compute the real cost to move from "from" to "to".
327  */
328 static double
329 bp_realcost(struct as_coord from, struct as_coord to, s_char *pp)
330 {
331     return (bp_lbcost(from, to, pp));
332 }
333
334 /*
335  * Tie breaker secondary metric (only used when lower bound costs
336  * are equal).
337  */
338 /*ARGSUSED*/
339 static double
340 bp_seccost(struct as_coord from, struct as_coord to, s_char *pp)
341 {
342     return ((double)mapdist((coord)from.x, (coord)from.y,
343                             (coord)to.x, (coord)to.y));
344 }
345
346 #ifdef DO_EFF_MEM_CHECKING
347
348 /*
349  * Get a sector from the cache.  If it's not in the cache,
350  * get it from disk and add it to the cache.
351  */
352 static struct sctstr *
353 bp_getsect(struct bestp *bp, coord x, coord y)
354 {
355     struct sctstr *sp;
356
357     sp = bp_sctcache_get(bp, x, y);
358     if (sp == NULL) {
359         sp = (struct sctstr *)malloc(sizeof(*sp));
360         getsect(x, y, sp);
361         bp_sctcache_set(bp, x, y, sp);
362         bp->sctcache_misses++;
363     } else {
364         bp->sctcache_hits++;
365     }
366     return (sp);
367 }
368
369 /*
370  * Get a sector from the cache; return NULL if it's not there.
371  */
372 static struct sctstr *
373 bp_sctcache_get(struct bestp *bp, coord x, coord y)
374 {
375     int hashval;
376     struct as_coord c;
377     struct sctcache *hp;
378
379     c.x = x;
380     c.y = y;
381     hashval = bp_coord_hash(c) % BP_SCTHASHSIZE;
382     for (hp = bp->sctcachetab[hashval]; hp; hp = hp->next) {
383         if (hp->x == x && hp->y == y)
384             return (hp->sp);
385     }
386     return (NULL);
387 }
388
389 /*
390  * Put a sector in the cache.
391  */
392 static void
393 bp_sctcache_set(struct bestp *bp, coord x, coord y, struct sctstr *sp)
394 {
395     int hashval;
396     struct as_coord c;
397     struct sctcache *hp;
398
399     hp = (struct sctcache *)calloc(1, sizeof(*hp));
400     hp->x = x;
401     hp->y = y;
402     hp->sp = sp;
403     c.x = x;
404     c.y = y;
405     hashval = bp_coord_hash(c) % BP_SCTHASHSIZE;
406     hp->next = bp->sctcachetab[hashval];
407     bp->sctcachetab[hashval] = hp;
408 }
409
410 /*
411  * Zap the cache and reset statistics.
412  */
413 static void
414 bp_sctcache_zap(struct bestp *bp)
415 {
416     register struct sctcache *hp;
417     register struct sctcache *np;
418     register int i;
419
420     for (i = 0; i < BP_SCTHASHSIZE; i++) {
421         for (hp = bp->sctcachetab[i]; hp; hp = np) {
422             np = hp->next;
423             free(hp->sp);
424             free(hp);
425         }
426         bp->sctcachetab[i] = NULL;
427     }
428     bp->sctcache_hits = 0;
429     bp->sctcache_misses = 0;
430 }
431
432 #endif /* DO_EFF_MEM_CHECKING */
433
434 /*
435  * Hash a coordinate into an integer.
436  */
437 static int
438 bp_coord_hash(struct as_coord c)
439 {
440     return ((abs(c.x) + 1) << 3) ^ abs(c.y);
441 }
442
443 void
444 bp_enable_cachepath()
445 {
446     as_enable_cachepath();
447 }
448
449 void
450 bp_disable_cachepath()
451 {
452     as_disable_cachepath();
453 }
454
455 void
456 bp_clear_cachepath()
457 {
458     as_clear_cachepath();
459 }
460
461 double
462 pathcost(struct sctstr *start, s_char *path, int mob_type)
463 {
464     register int o;
465     register int cx, cy;
466     double cost = 0.0;
467     struct sctstr *sp;
468     int sx, sy, offset;
469
470     cx = start->sct_x;
471     cy = start->sct_y;
472
473     while (*path) {
474         if (*path == 'h') {
475             path++;
476             continue;
477         }
478         o = dirindex[(int)((*path) - 'a')];
479         cx += diroff[o][0];
480         cy += diroff[o][1];
481         sx = XNORM(cx);
482         sy = YNORM(cy);
483         offset = (sy * WORLD_X + sx) / 2;
484         sp = (struct sctstr *)(ep->cache + ep->size * offset);
485         cost += sector_mcost(sp, mob_type);
486         path++;
487     }
488
489     return cost;
490 }
491
492 s_char *
493 BestDistPath(s_char *path,
494              struct sctstr *from,
495              struct sctstr *to, double *cost, int mob_type)
496 {
497     return BestLandPath(path, from, to, cost, mob_type);
498 }
499
500 s_char *
501 BestLandPath(s_char *path,
502              struct sctstr *from,
503              struct sctstr *to, double *cost, int mob_type)
504 {
505     int length;
506
507     *path = 0;
508     *cost = 0.0;
509     if (best_path(from, to, path, mob_type) < 0)
510         return (s_char *)0;
511     *cost = pathcost(from, path, mob_type);
512     length = strlen(path);
513     path[length] = 'h';
514     path[length + 1] = '\0';
515     return path;
516 }
517
518 s_char *
519 BestShipPath(s_char *path, int fx, int fy, int tx, int ty, int owner)
520 {
521     s_char *map;
522
523     /* need to make sector database available to bestpath */
524     map = ef_ptr(EF_BMAP, owner);
525
526     return (bestownedpath(path, map, fx, fy, tx, ty, ".=h", owner));
527 }
528
529 s_char *
530 BestAirPath(s_char *path, int fx, int fy, int tx, int ty)
531 {
532     return (bestownedpath(path, 0, fx, fy, tx, ty, "", -1));
533     /*    return (bestpath(path, fx, fy, tx, ty, "")); */
534 }