]> git.pond.sub.org Git - empserver/blob - src/lib/common/path.c
58fded85820a86dd5c5280b8c188abb1f70c2ae6
[empserver] / src / lib / common / path.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2010, 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 files README, COPYING and CREDITS in the root of the source
23  *  tree for related information and legal notices.  It is expected
24  *  that future projects/authors will amend these files as needed.
25  *
26  *  ---
27  *
28  *  path.c: Empire/A* Interface code.
29  *
30  *  Known contributors to this file:
31  *     Phil Lapsley, 1991
32  *     Dave Pare, 1991
33  *     Thomas Ruschak, 1993
34  *     Steve McClure, 1997
35  */
36
37 /*
38  * Define AS_STATS for A* statistics on stderr.
39  *
40  * Define AS_NO_PATH_CACHE to disable the path cache.  The path cache
41  * saves a lot of work, but uses lots of memory.  It should be a
42  * significant net win, unless you run out of memory.
43  *
44  * Define AS_NO_NEIGHBOR_CACHE to disable the neighbor cache.  The
45  * neighbor cache trades a modest amount of memory to save a bit of
46  * work.  In its current form, it doesn't really make a difference.
47  */
48
49 #include <config.h>
50
51 #include <stdio.h>
52 #include "../as/as.h"
53 #include "file.h"
54 #include "misc.h"
55 #include "optlist.h"
56 #include "path.h"
57 #include "prototypes.h"
58 #include "sect.h"
59 #include "xy.h"
60
61 #define BP_ASHASHSIZE   128     /* A* queue hash table size */
62 #define BP_NEIGHBORS    6       /* max number of neighbors */
63
64 struct bestp {
65     int bp_mobtype;
66     struct as_data *adp;
67 };
68
69 static int bp_path(struct as_path *pp, char *buf);
70 static int bp_neighbors(struct as_coord c, struct as_coord *cp, void *);
71 static double bp_lbcost(struct as_coord from, struct as_coord to, void *);
72 static double bp_realcost(struct as_coord from, struct as_coord to, void *);
73 static double bp_seccost(struct as_coord from, struct as_coord to, void *);
74 static int bp_coord_hash(struct as_coord c);
75
76 /* We use this for caching neighbors.  It never changes except
77  * at reboot time (maybe) so we never need to free it */
78 static struct sctstr **neighsects;
79
80 static struct bestp *
81 bp_init(void)
82 {
83     struct bestp *bp;
84
85     bp = malloc(sizeof(*bp));
86     memset(bp, 0, sizeof(*bp));
87     bp->adp = as_init(BP_NEIGHBORS, BP_ASHASHSIZE, bp_coord_hash,
88                       bp_neighbors, bp_lbcost, bp_realcost,
89                       bp_seccost, bp);
90
91     if (bp->adp == NULL)
92         return NULL;
93
94 #ifndef AS_NO_NEIGHBOR_CACHE
95     if (neighsects == NULL)
96         neighsects = calloc(WORLD_SZ() * 6, sizeof(struct sctstr *));
97 #endif
98
99     return bp;
100 }
101
102 /*
103  * Find the best path from sector to to sector, and put the Empire movement
104  * string in path.  Return 0 on success, -1 on error.
105  * FIXME unsafe by design: assumes path[] has space; buffer overrun
106  * when path gets long!
107  */
108 static int
109 best_path(struct sctstr *from, struct sctstr *to, char *path, int mob_type)
110 {
111     static struct bestp *mybestpath;
112     struct as_data *adp;
113     struct as_path *ap;
114     int res;
115
116     if (!mybestpath)
117         mybestpath = bp_init();
118     adp = mybestpath->adp;
119 #ifdef AS_NO_PATH_CACHE
120     ap = NULL;
121 #else
122     ap = as_find_cachepath(from->sct_x, from->sct_y, to->sct_x, to->sct_y);
123 #endif
124     if (ap == NULL) {
125         adp->from.x = from->sct_x;
126         adp->from.y = from->sct_y;
127         adp->to.x = to->sct_x;
128         adp->to.y = to->sct_y;
129         mybestpath->bp_mobtype = mob_type;
130
131         res = as_search(adp);
132 #ifdef AS_STATS
133         as_stats(adp, stderr);
134 #ifndef AS_NO_NEIGHBOR_CACHE
135         fprintf(stderr, "neighbor cache %zu bytes\n",
136                 WORLD_SZ() * 6 * sizeof(struct sctstr *));
137 #endif
138 #endif
139         if (res < 0)
140             return -1;
141         ap = adp->path;
142     }
143
144     if (bp_path(ap, path) < 0)
145         return -1;
146     return 0;
147 }
148
149 /*
150  * Translate an A* path into an empire movement string.  Return 0 on
151  * success, -1 on failure.
152  */
153 static int
154 bp_path(struct as_path *pp, char *buf)
155 {
156     struct as_path *np;
157     char *cp = buf;
158     int dx, dy;
159     int n;
160
161     np = pp->next;
162     while (np) {
163         dx = np->c.x - pp->c.x;
164         /* deal with wraparound from non-neg coords */
165         if (dx < -2)
166             dx += WORLD_X;
167         else if (dx > 2)
168             dx -= WORLD_X;
169         dy = np->c.y - pp->c.y;
170         if (dy < -1)
171             dy += WORLD_Y;
172         else if (dy > 1)
173             dy -= WORLD_Y;
174         for (n = 1; n <= 6; n++)
175             if (dx == diroff[n][0] && dy == diroff[n][1])
176                 break;
177         if (n > 6)
178             return -1;
179
180         *cp++ = dirch[n];
181         pp = np;
182         np = np->next;
183     }
184     *cp = '\0';
185     return 0;
186 }
187
188 /*
189  * Find coords neighboring this sector; return number of such
190  * coords, and coordinartes themselves in an array pointed
191  * to by *cpp.
192  * XXX need to check ownership, sector types, etc.
193  */
194 static int
195 bp_neighbors(struct as_coord c, struct as_coord *cp, void *pp)
196 {
197     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
198     struct bestp *bp = pp;
199     coord x, y;
200     coord nx, ny;
201     int n = 0, i;
202     struct sctstr *sp, *from, **ssp;
203     /* Six pointers, just in case our cache isn't there */
204     struct sctstr *tsp[] = { NULL, NULL, NULL, NULL, NULL, NULL };
205     int sx, sy, offset;
206
207     x = c.x;
208     y = c.y;
209     sx = XNORM(x);
210     sy = YNORM(y);
211     offset = XYOFFSET(sx, sy);
212     from = &sectp[offset];
213
214     if (neighsects == NULL)
215         ssp = (struct sctstr **)&tsp[0];
216     else
217         ssp = (struct sctstr **)&neighsects[offset * 6];
218     for (i = 1; i <= 6; i++, ssp++) {
219         if (*ssp == NULL) {
220             /* We haven't cached this neighbor yet */
221             nx = x + diroff[i][0];
222             ny = y + diroff[i][1];
223             sx = XNORM(nx);
224             sy = YNORM(ny);
225             offset = XYOFFSET(sx, sy);
226             sp = &sectp[offset];
227             *ssp = sp;
228         } else {
229             sp = *ssp;
230             sx = XNORM(sp->sct_x);
231             sy = YNORM(sp->sct_y);
232         }
233         /* No need to calculate cost each time, just make sure we can
234            move through it.  We calculate it later. */
235         if (dchr[sp->sct_type].d_mob0 < 0)
236             continue;
237         if (bp->bp_mobtype == MOB_RAIL && !SCT_HAS_RAIL(sp))
238             continue;
239         if (sp->sct_own != from->sct_own)
240             continue;
241         cp[n].x = sx;
242         cp[n].y = sy;
243         n++;
244     }
245     return n;
246 }
247
248 /*
249  * Compute a lower-bound on the cost from "from" to "to".
250  */
251 /*ARGSUSED*/
252 static double
253 bp_lbcost(struct as_coord from, struct as_coord to, void *pp)
254 {
255     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
256     struct bestp *bp = pp;
257     int x, y, sx, sy, offset;
258
259     x = to.x;
260     y = to.y;
261     sx = XNORM(x);
262     sy = YNORM(y);
263     offset = XYOFFSET(sx, sy);
264     return sector_mcost(&sectp[offset], bp->bp_mobtype);
265 }
266
267 /*
268  * Compute the real cost to move from "from" to "to".
269  */
270 static double
271 bp_realcost(struct as_coord from, struct as_coord to, void *pp)
272 {
273     return bp_lbcost(from, to, pp);
274 }
275
276 /*
277  * Tie breaker secondary metric (only used when lower bound costs
278  * are equal).
279  */
280 /*ARGSUSED*/
281 static double
282 bp_seccost(struct as_coord from, struct as_coord to, void *pp)
283 {
284     return mapdist((coord)from.x, (coord)from.y,
285                    (coord)to.x, (coord)to.y);
286 }
287
288 /*
289  * Hash a coordinate into an integer.
290  */
291 static int
292 bp_coord_hash(struct as_coord c)
293 {
294     return ((abs(c.x) + 1) << 3) ^ abs(c.y);
295 }
296
297 void
298 bp_enable_cachepath(void)
299 {
300 #ifndef AS_NO_PATH_CACHE
301     as_enable_cachepath();
302 #endif
303 }
304
305 void
306 bp_disable_cachepath(void)
307 {
308 #ifndef AS_NO_PATH_CACHE
309     as_disable_cachepath();
310 #endif
311 }
312
313 void
314 bp_clear_cachepath(void)
315 {
316 #ifndef AS_NO_PATH_CACHE
317     as_clear_cachepath();
318 #endif
319 }
320
321 double
322 pathcost(struct sctstr *start, char *path, int mob_type)
323 {
324     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
325     unsigned i;
326     int o;
327     int cx, cy;
328     double cost = 0.0;
329     struct sctstr *sp;
330     int sx, sy, offset;
331
332     cx = start->sct_x;
333     cy = start->sct_y;
334
335     while (*path) {
336         if (*path == 'h') {
337             path++;
338             continue;
339         }
340         i = *path - 'a';
341         if (CANT_HAPPEN(i >= sizeof(dirindex) / sizeof(*dirindex)))
342             break;
343         o = dirindex[i];
344         if (CANT_HAPPEN(o < 0))
345             break;
346         cx += diroff[o][0];
347         cy += diroff[o][1];
348         sx = XNORM(cx);
349         sy = YNORM(cy);
350         offset = XYOFFSET(sx, sy);
351         sp = &sectp[offset];
352         cost += sector_mcost(sp, mob_type);
353         path++;
354     }
355
356     return cost;
357 }
358
359 char *
360 BestDistPath(char *path,
361              struct sctstr *from,
362              struct sctstr *to, double *cost)
363 {
364     return BestLandPath(path, from, to, cost, MOB_MOVE);
365 }
366
367 char *
368 BestLandPath(char *path,
369              struct sctstr *from,
370              struct sctstr *to, double *cost, int mob_type)
371 {
372     int length;
373
374     *path = 0;
375     *cost = 0.0;
376     if (best_path(from, to, path, mob_type) < 0)
377         return NULL;
378     *cost = pathcost(from, path, mob_type);
379     length = strlen(path);
380     path[length] = 'h';
381     path[length + 1] = '\0';
382     return path;
383 }
384
385 char *
386 BestShipPath(char *path, int fx, int fy, int tx, int ty, int owner)
387 {
388     char *map;
389
390     map = ef_ptr(EF_BMAP, owner);
391     if (!map)
392         return NULL;
393     return bestownedpath(path, map, fx, fy, tx, ty, owner);
394 }
395
396 char *
397 BestAirPath(char *path, int fx, int fy, int tx, int ty)
398 {
399     return bestownedpath(path, NULL, fx, fy, tx, ty, -1);
400 }