ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/common/map.C
Revision: 1.1
Committed: Sun Aug 13 17:16:00 2006 UTC (17 years, 9 months ago) by elmex
Content type: text/plain
Branch: MAIN
Log Message:
Made server compile with C++.
Removed cfanim plugin and crossedit.
C++ here we come.

File Contents

# User Rev Content
1 elmex 1.1 /*
2     * static char *rcsid_map_c =
3     * "$Id$";
4     */
5    
6     /*
7     CrossFire, A Multiplayer game for X-windows
8    
9     Copyright (C) 2001-2003 Mark Wedel & Crossfire Development Team
10     Copyright (C) 1992 Frank Tore Johansen
11    
12     This program is free software; you can redistribute it and/or modify
13     it under the terms of the GNU General Public License as published by
14     the Free Software Foundation; either version 2 of the License, or
15     (at your option) any later version.
16    
17     This program is distributed in the hope that it will be useful,
18     but WITHOUT ANY WARRANTY; without even the implied warranty of
19     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20     GNU General Public License for more details.
21    
22     You should have received a copy of the GNU General Public License
23     along with this program; if not, write to the Free Software
24     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25    
26     The authors can be reached via e-mail at crossfire-devel@real-time.com
27     */
28    
29    
30     #include <global.h>
31     #include <funcpoint.h>
32    
33     #include <loader.h>
34     #ifndef WIN32 /* ---win32 exclude header */
35     #include <unistd.h>
36     #endif /* win32 */
37    
38     #include "path.h"
39    
40    
41     extern int nrofallocobjects,nroffreeobjects;
42    
43     void (*load_original_map_callback)(mapstruct *map);
44     void (*load_temporary_map_callback)(mapstruct *map);
45     void (*clean_temporary_map_callback)(mapstruct *map);
46    
47     /*
48     * Returns the mapstruct which has a name matching the given argument.
49     * return NULL if no match is found.
50     */
51    
52     mapstruct *has_been_loaded (const char *name) {
53     mapstruct *map;
54    
55     if (!name || !*name)
56     return 0;
57     for (map = first_map; map; map = map->next)
58     if (!strcmp (name, map->path))
59     break;
60     return (map);
61     }
62    
63     /*
64     * This makes a path absolute outside the world of Crossfire.
65     * In other words, it prepends LIBDIR/MAPDIR/ to the given path
66     * and returns the pointer to a static array containing the result.
67     * it really should be called create_mapname
68     */
69    
70     const char *create_pathname (const char *name) {
71     static char buf[MAX_BUF];
72    
73     /* Why? having extra / doesn't confuse unix anyplace? Dependancies
74     * someplace else in the code? msw 2-17-97
75     */
76     if (*name == '/')
77     sprintf (buf, "%s/%s%s", settings.datadir, settings.mapdir, name);
78     else
79     sprintf (buf, "%s/%s/%s", settings.datadir, settings.mapdir, name);
80     return (buf);
81     }
82    
83     /*
84     * same as create_pathname, but for the overlay maps.
85     */
86    
87     const char *create_overlay_pathname (const char *name) {
88     static char buf[MAX_BUF];
89    
90     /* Why? having extra / doesn't confuse unix anyplace? Dependancies
91     * someplace else in the code? msw 2-17-97
92     */
93     if (*name == '/')
94     sprintf (buf, "%s/%s%s", settings.localdir, settings.mapdir, name);
95     else
96     sprintf (buf, "%s/%s/%s", settings.localdir, settings.mapdir, name);
97     return (buf);
98     }
99    
100     /*
101     * same as create_pathname, but for the template maps.
102     */
103    
104     const char *create_template_pathname (const char *name) {
105     static char buf[MAX_BUF];
106    
107     /* Why? having extra / doesn't confuse unix anyplace? Dependancies
108     * someplace else in the code? msw 2-17-97
109     */
110     if (*name == '/')
111     sprintf (buf, "%s/%s%s", settings.localdir, settings.templatedir, name);
112     else
113     sprintf (buf, "%s/%s/%s", settings.localdir, settings.templatedir, name);
114     return (buf);
115     }
116    
117     /*
118     * This makes absolute path to the itemfile where unique objects
119     * will be saved. Converts '/' to '@'. I think it's essier maintain
120     * files than full directory structure, but if this is problem it can
121     * be changed.
122     */
123     static const char *create_items_path (const char *s) {
124     static char buf[MAX_BUF];
125     char *t;
126    
127     if (*s == '/')
128     s++;
129    
130     sprintf (buf, "%s/%s/", settings.localdir, settings.uniquedir);
131    
132     for (t=buf+strlen(buf); *s; s++,t++)
133     if (*s == '/')
134     *t = '@';
135     else
136     *t = *s;
137     *t = 0;
138     return (buf);
139     }
140    
141    
142     /*
143     * This function checks if a file with the given path exists.
144     * -1 is returned if it fails, otherwise the mode of the file
145     * is returned.
146     * It tries out all the compression suffixes listed in the uncomp[] array.
147     *
148     * If prepend_dir is set, then we call create_pathname (which prepends
149     * libdir & mapdir). Otherwise, we assume the name given is fully
150     * complete.
151     * Only the editor actually cares about the writablity of this -
152     * the rest of the code only cares that the file is readable.
153     * when the editor goes away, the call to stat should probably be
154     * replaced by an access instead (similar to the windows one, but
155     * that seems to be missing the prepend_dir processing
156     */
157    
158     int check_path (const char *name, int prepend_dir)
159     {
160     char buf[MAX_BUF];
161     #ifndef WIN32
162     char *endbuf;
163     struct stat statbuf;
164     int mode = 0, i;
165     #endif
166    
167     if (prepend_dir)
168     strcpy (buf, create_pathname(name));
169     else
170     strcpy(buf, name);
171     #ifdef WIN32 /* ***win32: check this sucker in windows style. */
172     return(_access(buf,0));
173     #else
174    
175     /* old method (strchr(buf, '\0')) seemd very odd to me -
176     * this method should be equivalant and is clearer.
177     * Can not use strcat because we need to cycle through
178     * all the names.
179     */
180     endbuf = buf + strlen(buf);
181    
182     for (i = 0; i < NROF_COMPRESS_METHODS; i++) {
183     if (uncomp[i][0])
184     strcpy(endbuf, uncomp[i][0]);
185     else
186     *endbuf = '\0';
187     if (!stat (buf, &statbuf))
188     break;
189     }
190     if (i == NROF_COMPRESS_METHODS)
191     return (-1);
192     if (!S_ISREG (statbuf.st_mode))
193     return (-1);
194    
195     if (((statbuf.st_mode & S_IRGRP) && getegid() == statbuf.st_gid) ||
196     ((statbuf.st_mode & S_IRUSR) && geteuid() == statbuf.st_uid) ||
197     (statbuf.st_mode & S_IROTH))
198     mode |= 4;
199    
200     if ((statbuf.st_mode & S_IWGRP && getegid() == statbuf.st_gid) ||
201     (statbuf.st_mode & S_IWUSR && geteuid() == statbuf.st_uid) ||
202     (statbuf.st_mode & S_IWOTH))
203     mode |= 2;
204    
205     return (mode);
206     #endif
207     }
208    
209     /*
210     * Prints out debug-information about a map.
211     * Dumping these at llevError doesn't seem right, but is
212     * necessary to make sure the information is in fact logged.
213     */
214    
215     void dump_map(const mapstruct *m) {
216     LOG(llevError,"Map %s status: %d.\n",m->path,m->in_memory);
217     LOG(llevError,"Size: %dx%d Start: %d,%d\n",
218     MAP_WIDTH(m), MAP_HEIGHT(m),
219     MAP_ENTER_X(m), MAP_ENTER_Y(m));
220    
221     if(m->msg!=NULL)
222     LOG(llevError,"Message:\n%s",m->msg);
223    
224     if(m->maplore!=NULL)
225     LOG(llevError,"Lore:\n%s",m->maplore);
226    
227     if(m->tmpname!=NULL)
228     LOG(llevError,"Tmpname: %s\n",m->tmpname);
229    
230     LOG(llevError,"Difficulty: %d\n",m->difficulty);
231     LOG(llevError,"Darkness: %d\n",m->darkness);
232     }
233    
234     /*
235     * Prints out debug-information about all maps.
236     * This basically just goes through all the maps and calls
237     * dump_map on each one.
238     */
239    
240     void dump_all_maps(void) {
241     mapstruct *m;
242     for(m=first_map;m!=NULL;m=m->next) {
243     dump_map(m);
244     }
245     }
246    
247     /* This rolls up wall, blocks_magic, blocks_view, etc, all into
248     * one function that just returns a P_.. value (see map.h)
249     * it will also do map translation for tiled maps, returning
250     * new values into newmap, nx, and ny. Any and all of those
251     * values can be null, in which case if a new map is needed (returned
252     * by a P_NEW_MAP value, another call to get_map_from_coord
253     * is needed. The case of not passing values is if we're just
254     * checking for the existence of something on those spaces, but
255     * don't expect to insert/remove anything from those spaces.
256     */
257     int get_map_flags(mapstruct *oldmap, mapstruct **newmap, sint16 x, sint16 y, sint16 *nx, sint16 *ny)
258     {
259     sint16 newx, newy;
260     int retval=0;
261     mapstruct *mp;
262    
263     if (out_of_map(oldmap, x, y)) return P_OUT_OF_MAP;
264     newx = x;
265     newy = y;
266     mp = get_map_from_coord(oldmap, &newx, &newy);
267     if (mp != oldmap)
268     retval |= P_NEW_MAP;
269     if (newmap) *newmap = mp;
270     if (nx) *nx = newx;
271     if (ny) *ny = newy;
272     retval |= mp->spaces[newx + mp->width * newy].flags;
273     return retval;
274     }
275    
276    
277     /*
278     * Returns true if the given coordinate is blocked except by the
279     * object passed is not blocking. This is used with
280     * multipart monsters - if we want to see if a 2x2 monster
281     * can move 1 space to the left, we don't want its own area
282     * to block it from moving there.
283     * Returns TRUE if the space is blocked by something other than the
284     * monster.
285     * m, x, y are the target map/coordinates - needed for map tiling.
286     * the coordinates & map passed in should have been updated for tiling
287     * by the caller.
288     */
289    
290     int blocked_link(object *ob, mapstruct *m, int sx, int sy) {
291     object *tmp;
292     int mflags, blocked;
293    
294     /* Make sure the coordinates are valid - they should be, as caller should
295     * have already checked this.
296     */
297     if (OUT_OF_REAL_MAP(m, sx, sy)) {
298     LOG(llevError,"blocked_link: Passed map, x, y coordinates outside of map\n");
299     return 1;
300     }
301    
302     /* Save some cycles - instead of calling get_map_flags(), just get the value
303     * directly.
304     */
305     mflags = m->spaces[sx + m->width * sy].flags;
306    
307     blocked = GET_MAP_MOVE_BLOCK(m, sx, sy);
308    
309     /* If space is currently not blocked by anything, no need to
310     * go further. Not true for players - all sorts of special
311     * things we need to do for players.
312     */
313     if (ob->type != PLAYER && ! (mflags & P_IS_ALIVE) && (blocked==0)) return 0;
314    
315     /* if there isn't anytyhing alive on this space, and this space isn't
316     * otherwise blocked, we can return now. Only if there is a living
317     * creature do we need to investigate if it is part of this creature
318     * or another. Likewise, only if something is blocking us do we
319     * need to investigate if there is a special circumstance that would
320     * let the player through (inventory checkers for example)
321     */
322     if (!(mflags & P_IS_ALIVE) && !OB_TYPE_MOVE_BLOCK(ob, blocked)) return 0;
323    
324     if(ob->head != NULL)
325     ob=ob->head;
326    
327     /* We basically go through the stack of objects, and if there is
328     * some other object that has NO_PASS or FLAG_ALIVE set, return
329     * true. If we get through the entire stack, that must mean
330     * ob is blocking it, so return 0.
331     */
332     for(tmp = GET_MAP_OB(m,sx,sy); tmp!= NULL; tmp = tmp->above) {
333    
334     /* This must be before the checks below. Code for inventory checkers. */
335     if (tmp->type==CHECK_INV && OB_MOVE_BLOCK(ob, tmp)) {
336     /* If last_sp is set, the player/monster needs an object,
337     * so we check for it. If they don't have it, they can't
338     * pass through this space.
339     */
340     if (tmp->last_sp) {
341     if (check_inv_recursive(ob,tmp)==NULL)
342     return 1;
343     else
344     continue;
345     } else {
346     /* In this case, the player must not have the object -
347     * if they do, they can't pass through.
348     */
349     if (check_inv_recursive(ob,tmp)!=NULL) /* player has object */
350     return 1;
351     else
352     continue;
353     }
354     } /* if check_inv */
355     else {
356     /* Broke apart a big nasty if into several here to make
357     * this more readable. first check - if the space blocks
358     * movement, can't move here.
359     * second - if a monster, can't move there, unles it is a
360     * hidden dm
361     */
362     if (OB_MOVE_BLOCK(ob, tmp)) return 1;
363     if (QUERY_FLAG(tmp,FLAG_ALIVE) && tmp->head != ob && tmp != ob &&
364     tmp->type != DOOR && !(QUERY_FLAG(tmp,FLAG_WIZ) && tmp->contr->hidden))
365     return 1;
366     }
367    
368     }
369     return 0;
370     }
371    
372    
373     /*
374     * Returns true if the given object can't fit in the given spot.
375     * This is meant for multi space objects - for single space objecs,
376     * just calling get_map_blocked and checking that against movement type
377     * of object. This function goes through all the parts of the
378     * multipart object and makes sure they can be inserted.
379     *
380     * While this doesn't call out of map, the get_map_flags does.
381     *
382     * This function has been used to deprecate arch_out_of_map -
383     * this function also does that check, and since in most cases,
384     * a call to one would follow the other, doesn't make a lot of sense to
385     * have two seperate functions for this.
386     *
387     * This returns nonzero if this arch can not go on the space provided,
388     * 0 otherwise. the return value will contain the P_.. value
389     * so the caller can know why this object can't go on the map.
390     * Note that callers should not expect P_NEW_MAP to be set
391     * in return codes - since the object is multispace - if
392     * we did return values, what do you return if half the object
393     * is one map, half on another.
394     *
395     * Note this used to be arch_blocked, but with new movement
396     * code, we need to have actual object to check its move_type
397     * against the move_block values.
398     */
399    
400     int ob_blocked(const object *ob,mapstruct *m,sint16 x,sint16 y) {
401     archetype *tmp;
402     int flag;
403     mapstruct *m1;
404     sint16 sx, sy;
405    
406     if(ob==NULL) {
407     flag= get_map_flags(m,&m1, x,y, &sx, &sy);
408     if (flag & P_OUT_OF_MAP) return P_OUT_OF_MAP;
409    
410     /* don't have object, so don't know what types would block */
411     return(GET_MAP_MOVE_BLOCK(m1, sx, sy));
412     }
413    
414     for(tmp=ob->arch; tmp!=NULL;tmp=tmp->more) {
415     flag = get_map_flags(m, &m1, x+tmp->clone.x,y+tmp->clone.y, &sx, &sy);
416    
417     if (flag & P_OUT_OF_MAP) return P_OUT_OF_MAP;
418     if (flag & P_IS_ALIVE) return P_IS_ALIVE;
419    
420     /* find_first_free_spot() calls this function. However, often
421     * ob doesn't have any move type (when used to place exits)
422     * so the AND operation in OB_TYPE_MOVE_BLOCK doesn't work.
423     */
424    
425     if (ob->move_type == 0 && GET_MAP_MOVE_BLOCK(m1, sx, sy) != MOVE_ALL) continue;
426    
427     /* Note it is intentional that we check ob - the movement type of the
428     * head of the object should correspond for the entire object.
429     */
430     if (OB_TYPE_MOVE_BLOCK(ob, GET_MAP_MOVE_BLOCK(m1, sx, sy)))
431     return AB_NO_PASS;
432    
433     }
434     return 0;
435     }
436    
437     /* When the map is loaded, load_object does not actually insert objects
438     * into inventory, but just links them. What this does is go through
439     * and insert them properly.
440     * The object 'container' is the object that contains the inventory.
441     * This is needed so that we can update the containers weight.
442     */
443    
444     void fix_container(object *container)
445     {
446     object *tmp=container->inv, *next;
447    
448     container->inv=NULL;
449     while (tmp!=NULL) {
450     next = tmp->below;
451     if (tmp->inv)
452     fix_container(tmp);
453     (void) insert_ob_in_ob(tmp,container);
454     tmp = next;
455     }
456     /* sum_weight will go through and calculate what all the containers are
457     * carrying.
458     */
459     sum_weight(container);
460     }
461    
462     /* link_multipart_objects go through all the objects on the map looking
463     * for objects whose arch says they are multipart yet according to the
464     * info we have, they only have the head (as would be expected when
465     * they are saved). We do have to look for the old maps that did save
466     * the more sections and not re-add sections for them.
467     */
468    
469     static void link_multipart_objects(mapstruct *m)
470     {
471     int x,y;
472     object *tmp, *op, *last, *above;
473     archetype *at;
474    
475     for(x=0;x<MAP_WIDTH(m);x++)
476     for(y=0;y<MAP_HEIGHT(m);y++)
477     for(tmp=get_map_ob(m,x,y);tmp!=NULL;tmp=above) {
478     above=tmp->above;
479    
480     /* already multipart - don't do anything more */
481     if (tmp->head || tmp->more) continue;
482    
483     /* If there is nothing more to this object, this for loop
484     * won't do anything.
485     */
486     for (at = tmp->arch->more, last=tmp; at != NULL; at=at->more, last=op) {
487     op = arch_to_object(at);
488    
489     /* update x,y coordinates */
490     op->x += tmp->x;
491     op->y += tmp->y;
492     op->head = tmp;
493     op->map = m;
494     last->more = op;
495     if (tmp->name != op->name) {
496     if (op->name) free_string(op->name);
497     op->name = add_string(tmp->name);
498     }
499     if (tmp->title != op->title) {
500     if (op->title) free_string(op->title);
501     op->title = add_string(tmp->title);
502     }
503     /* we could link all the parts onto tmp, and then just
504     * call insert_ob_in_map once, but the effect is the same,
505     * as insert_ob_in_map will call itself with each part, and
506     * the coding is simpler to just to it here with each part.
507     */
508     insert_ob_in_map(op, op->map, tmp,INS_NO_MERGE|INS_ABOVE_FLOOR_ONLY|INS_NO_WALK_ON);
509     } /* for at = tmp->arch->more */
510     } /* for objects on this space */
511     }
512    
513    
514    
515     /*
516     * Loads (ands parses) the objects into a given map from the specified
517     * file pointer.
518     * mapflags is the same as we get with load_original_map
519     */
520    
521     void load_objects (mapstruct *m, FILE *fp, int mapflags) {
522     int i,j,bufstate=LO_NEWFILE;
523     int unique;
524     object *op, *prev=NULL,*last_more=NULL, *otmp;
525    
526     op=get_object();
527     op->map = m; /* To handle buttons correctly */
528    
529     while((i=load_object(fp,op,bufstate, mapflags))) {
530     /* Since the loading of the map header does not load an object
531     * anymore, we need to pass LO_NEWFILE for the first object loaded,
532     * and then switch to LO_REPEAT for faster loading.
533     */
534     bufstate = LO_REPEAT;
535    
536     /* if the archetype for the object is null, means that we
537     * got an invalid object. Don't do anything with it - the game
538     * or editor will not be able to do anything with it either.
539     */
540     if (op->arch==NULL) {
541     LOG(llevDebug,"Discarding object without arch: %s\n", op->name?op->name:"(null)");
542     continue;
543     }
544    
545    
546     switch(i) {
547     case LL_NORMAL:
548     /* if we are loading an overlay, put the floors on the bottom */
549     if ((QUERY_FLAG(op, FLAG_IS_FLOOR) ||
550     QUERY_FLAG(op, FLAG_OVERLAY_FLOOR)) && mapflags & MAP_OVERLAY)
551     insert_ob_in_map(op,m,op,INS_NO_MERGE | INS_NO_WALK_ON | INS_ABOVE_FLOOR_ONLY | INS_MAP_LOAD);
552     else
553     insert_ob_in_map(op,m,op,INS_NO_MERGE | INS_NO_WALK_ON | INS_ON_TOP | INS_MAP_LOAD);
554    
555     if (op->inv)
556     sum_weight(op);
557    
558     prev=op,last_more=op;
559     break;
560    
561     case LL_MORE:
562     insert_ob_in_map(op,m, op, INS_NO_MERGE | INS_NO_WALK_ON | INS_ABOVE_FLOOR_ONLY);
563     op->head=prev,last_more->more=op,last_more=op;
564     break;
565     }
566     if (mapflags & MAP_STYLE) {
567     remove_from_active_list(op);
568     }
569     op=get_object();
570     op->map = m;
571     }
572     for (i=0;i<m->width;i++){
573     for (j=0;j<m->height;j++){
574     unique =0;
575     /* check for unique items, or unique squares */
576     for (otmp = get_map_ob(m, i, j); otmp; otmp = otmp->above) {
577     if (QUERY_FLAG(otmp, FLAG_UNIQUE) || QUERY_FLAG(otmp, FLAG_OBJ_SAVE_ON_OVL))
578     unique = 1;
579     if (!(mapflags & (MAP_OVERLAY|MAP_PLAYER_UNIQUE) || unique))
580     SET_FLAG(otmp, FLAG_OBJ_ORIGINAL);
581     }
582     }
583     }
584     free_object(op);
585     link_multipart_objects(m);
586     }
587    
588     /* This saves all the objects on the map in a non destructive fashion.
589     * Modified by MSW 2001-07-01 to do in a single pass - reduces code,
590     * and we only save the head of multi part objects - this is needed
591     * in order to do map tiling properly.
592     */
593     void save_objects (mapstruct *m, FILE *fp, FILE *fp2, int flag) {
594     int i, j = 0,unique=0;
595     object *op;
596     /* first pass - save one-part objects */
597     for(i = 0; i < MAP_WIDTH(m); i++)
598     for (j = 0; j < MAP_HEIGHT(m); j++) {
599     unique=0;
600     for(op = get_map_ob (m, i, j); op; op = op->above) {
601     if (QUERY_FLAG(op,FLAG_IS_FLOOR) && QUERY_FLAG(op, FLAG_UNIQUE))
602     unique=1;
603    
604     if(op->type == PLAYER) {
605     LOG(llevDebug, "Player on map that is being saved\n");
606     continue;
607     }
608    
609     if (op->head || op->owner)
610     continue;
611    
612     if (unique || QUERY_FLAG(op, FLAG_UNIQUE))
613     save_object( fp2 , op, 3);
614     else
615     if (flag == 0 ||
616     (flag == 2 && (!QUERY_FLAG(op, FLAG_OBJ_ORIGINAL) &&
617     !QUERY_FLAG(op, FLAG_UNPAID))))
618     save_object(fp, op, 3);
619    
620     } /* for this space */
621     } /* for this j */
622     }
623    
624     /*
625     * Allocates, initialises, and returns a pointer to a mapstruct.
626     * Modified to no longer take a path option which was not being
627     * used anyways. MSW 2001-07-01
628     */
629    
630     mapstruct *get_linked_map(void) {
631     mapstruct *map=(mapstruct *) calloc(1,sizeof(mapstruct));
632     mapstruct *mp;
633    
634     if(map==NULL)
635     fatal(OUT_OF_MEMORY);
636    
637     for(mp=first_map;mp!=NULL&&mp->next!=NULL;mp=mp->next);
638     if(mp==NULL)
639     first_map=map;
640     else
641     mp->next=map;
642    
643     map->in_memory=MAP_SWAPPED;
644     /* The maps used to pick up default x and y values from the
645     * map archetype. Mimic that behaviour.
646     */
647     MAP_WIDTH(map)=16;
648     MAP_HEIGHT(map)=16;
649     MAP_RESET_TIMEOUT(map)=0;
650     MAP_TIMEOUT(map)=300;
651     MAP_ENTER_X(map)=0;
652     MAP_ENTER_Y(map)=0;
653     /*set part to -1 indicating conversion to weather map not yet done*/
654     MAP_WORLDPARTX(map)=-1;
655     MAP_WORLDPARTY(map)=-1;
656     return map;
657     }
658    
659     /*
660     * Allocates the arrays contained in a mapstruct.
661     * This basically allocates the dynamic array of spaces for the
662     * map.
663     */
664    
665     void allocate_map(mapstruct *m) {
666     m->in_memory = MAP_IN_MEMORY;
667     /* Log this condition and free the storage. We could I suppose
668     * realloc, but if the caller is presuming the data will be intact,
669     * that is their poor assumption.
670     */
671     if (m->spaces) {
672     LOG(llevError,"allocate_map called with already allocated map (%s)\n", m->path);
673     free(m->spaces);
674     }
675    
676     m->spaces = (MapSpace *) calloc(1, MAP_WIDTH(m) * MAP_HEIGHT(m) * sizeof(MapSpace));
677    
678     if(m->spaces==NULL)
679     fatal(OUT_OF_MEMORY);
680     }
681    
682     /* Create and returns a map of the specific size. Used
683     * in random map code and the editor.
684     */
685     mapstruct *get_empty_map(int sizex, int sizey) {
686     mapstruct *m = get_linked_map();
687     m->width = sizex;
688     m->height = sizey;
689     m->in_memory = MAP_SWAPPED;
690     allocate_map(m);
691     return m;
692     }
693    
694     /* Takes a string from a map definition and outputs a pointer to the array of shopitems
695     * corresponding to that string. Memory is allocated for this, it must be freed
696     * at a later date.
697     * Called by parse_map_headers below.
698     */
699    
700     static shopitems *parse_shop_string (const char *input_string) {
701     char *shop_string, *p, *q, *next_semicolon, *next_colon;
702     shopitems *items=NULL;
703     int i=0, number_of_entries=0;
704     const typedata *current_type;
705    
706     shop_string=strdup_local(input_string);
707     p=shop_string;
708     /* first we'll count the entries, we'll need that for allocating the array shortly */
709     while (p) {
710     p=strchr(p, ';');
711     number_of_entries++;
712     if (p) p++;
713     }
714     p=shop_string;
715     strip_endline(p);
716     items=(shopitems *) CALLOC(number_of_entries+1, sizeof(shopitems));
717     memset(items, 0, (sizeof(shopitems) * number_of_entries+1));
718     for (i=0; i<number_of_entries; i++) {
719     if (!p) {
720     LOG(llevError, "parse_shop_string: I seem to have run out of string, that shouldn't happen.\n");
721     break;
722     }
723     next_semicolon=strchr(p, ';');
724     next_colon=strchr(p, ':');
725     /* if there is a stregth specified, figure out what it is, we'll need it soon. */
726     if (next_colon &&( !next_semicolon || next_colon<next_semicolon))
727     items[i].strength=atoi(strchr(p,':')+1);
728    
729     if (isdigit(*p) || *p=='*') {
730     items[i].typenum = atoi(p); /* atoi returns 0 when we have an asterisk */
731     current_type=get_typedata(items[i].typenum);
732     if (current_type) {
733     items[i].name=current_type->name;
734     items[i].name_pl=current_type->name_pl;
735     }
736     }
737     else { /*we have a named type, let's figure out what it is */
738     q=strpbrk(p,";:");
739     if (q) *q='\0';
740    
741     current_type=get_typedata_by_name(p);
742     if (current_type) {
743     items[i].name=current_type->name;
744     items[i].typenum=current_type->number;
745     items[i].name_pl=current_type->name_pl;
746     }
747     else { /* oh uh, something's wrong, let's free up this one, and try
748     * the next entry while we're at it, better print a warning
749     */
750     LOG(llevError, "invalid type %s defined in shopitems in string %s\n",
751     p, input_string);
752     }
753     }
754     items[i].index=number_of_entries;
755     if (next_semicolon) p=++next_semicolon;
756     else p=NULL;
757     }
758     free(shop_string);
759     return items;
760     }
761    
762     /* opposite of parse string, this puts the string that was originally fed in to
763     * the map (or something equivilent) into output_string. */
764     static void print_shop_string(mapstruct *m, char *output_string) {
765     int i;
766     char tmp[MAX_BUF];
767     strcpy(output_string, "");
768     for (i=0; i< m->shopitems[0].index; i++) {
769     if (m->shopitems[i].typenum) {
770     if (m->shopitems[i].strength) {
771     sprintf(tmp, "%s:%d;", m->shopitems[i].name, m->shopitems[i].strength);
772     }
773     else sprintf(tmp, "%s;", m->shopitems[i].name);
774     }
775     else {
776     if (m->shopitems[i].strength) {
777     sprintf(tmp, "*:%d;", m->shopitems[i].strength);
778     }
779     else sprintf(tmp, "*");
780     }
781     strcat(output_string, tmp);
782     }
783     }
784    
785     /* This loads the header information of the map. The header
786     * contains things like difficulty, size, timeout, etc.
787     * this used to be stored in the map object, but with the
788     * addition of tiling, fields beyond that easily named in an
789     * object structure were needed, so it just made sense to
790     * put all the stuff in the map object so that names actually make
791     * sense.
792     * This could be done in lex (like the object loader), but I think
793     * currently, there are few enough fields this is not a big deal.
794     * MSW 2001-07-01
795     * return 0 on success, 1 on failure.
796     */
797    
798     static int load_map_header(FILE *fp, mapstruct *m)
799     {
800     char buf[HUGE_BUF], msgbuf[HUGE_BUF], maplorebuf[HUGE_BUF], *key=NULL, *value, *end;
801     int msgpos=0;
802     int maplorepos=0;
803    
804     while (fgets(buf, HUGE_BUF-1, fp)!=NULL) {
805     buf[HUGE_BUF-1] = 0;
806     key = buf;
807     while (isspace(*key)) key++;
808     if (*key == 0) continue; /* empty line */
809     value = strchr(key, ' ');
810     if (!value) {
811     end = strchr(key, '\n');
812     if (end != NULL) {
813     *end = 0;
814     }
815     } else {
816     *value = 0;
817     value++;
818     end = strchr(value, '\n');
819     while (isspace(*value)) {
820     value++;
821     if (*value == '\0' || value == end) {
822     /* Nothing but spaces. */
823     value = NULL;
824     break;
825     }
826     }
827     }
828     if (!end) {
829     LOG(llevError, "Error loading map header - did not find a newline - perhaps file is truncated? Buf=%s\n",
830     buf);
831     return 1;
832     }
833    
834    
835     /* key is the field name, value is what it should be set
836     * to. We've already done the work to null terminate key,
837     * and strip off any leading spaces for both of these.
838     * We have not touched the newline at the end of the line -
839     * these are needed for some values. the end pointer
840     * points to the first of the newlines.
841     * value could be NULL! It would be easy enough to just point
842     * this to "" to prevent cores, but that would let more errors slide
843     * through.
844     *
845     * First check for entries that do not use the value parameter, then
846     * validate that value is given and check for the remaining entries
847     * that use the parameter.
848     */
849    
850     if (!strcmp(key,"msg")) {
851     while (fgets(buf, HUGE_BUF-1, fp)!=NULL) {
852     if (!strcmp(buf,"endmsg\n")) break;
853     else {
854     /* slightly more efficient than strcat */
855     strcpy(msgbuf+msgpos, buf);
856     msgpos += strlen(buf);
857     }
858     }
859     /* There are lots of maps that have empty messages (eg, msg/endmsg
860     * with nothing between). There is no reason in those cases to
861     * keep the empty message. Also, msgbuf contains garbage data
862     * when msgpos is zero, so copying it results in crashes
863     */
864     if (msgpos != 0)
865     m->msg = strdup_local(msgbuf);
866     }
867     else if (!strcmp(key,"maplore")) {
868     while (fgets(buf, HUGE_BUF-1, fp)!=NULL) {
869     if (!strcmp(buf,"endmaplore\n")) break;
870     else {
871     /* slightly more efficient than strcat */
872     strcpy(maplorebuf+maplorepos, buf);
873     maplorepos += strlen(buf);
874     }
875     }
876     if (maplorepos != 0)
877     m->maplore = strdup_local(maplorebuf);
878     }
879     else if (!strcmp(key,"end")) {
880     break;
881     }
882     else if (value == NULL) {
883     LOG(llevError, "Got '%s' line without parameter in map header\n", key);
884     }
885     else if (!strcmp(key, "arch")) {
886     /* This is an oddity, but not something we care about much. */
887     if (strcmp(value,"map\n"))
888     LOG(llevError,"loading map and got a non 'arch map' line(%s %s)?\n",key,value);
889     }
890     else if (!strcmp(key,"name")) {
891     *end=0;
892     m->name = strdup_local(value);
893     }
894     /* first strcmp value on these are old names supported
895     * for compatibility reasons. The new values (second) are
896     * what really should be used.
897     */
898     else if (!strcmp(key,"hp") || !strcmp(key, "enter_x")) {
899     m->enter_x = atoi(value);
900     } else if (!strcmp(key,"sp") || !strcmp(key, "enter_y")) {
901     m->enter_y = atoi(value);
902     } else if (!strcmp(key,"x") || !strcmp(key, "width")) {
903     m->width = atoi(value);
904     } else if (!strcmp(key,"y") || !strcmp(key, "height")) {
905     m->height = atoi(value);
906     } else if (!strcmp(key,"weight") || !strcmp(key, "reset_timeout")) {
907     m->reset_timeout = atoi(value);
908     } else if (!strcmp(key,"value") || !strcmp(key, "swap_time")) {
909     m->timeout = atoi(value);
910     } else if (!strcmp(key,"level") || !strcmp(key, "difficulty")) {
911     m->difficulty = atoi(value);
912     } else if (!strcmp(key,"invisible") || !strcmp(key, "darkness")) {
913     m->darkness = atoi(value);
914     } else if (!strcmp(key,"stand_still") || !strcmp(key, "fixed_resettime")) {
915     m->fixed_resettime = atoi(value);
916     } else if (!strcmp(key,"unique")) {
917     m->unique = atoi(value);
918     } else if (!strcmp(key,"template")) {
919     m->templatemap = atoi(value);
920     } else if (!strcmp(key,"region")) {
921     m->region = get_region_by_name(value);
922     } else if (!strcmp(key,"shopitems")) {
923     *end=0;
924     m->shopitems = parse_shop_string(value);
925     } else if (!strcmp(key,"shopgreed")) {
926     m->shopgreed = atof(value);
927     } else if (!strcmp(key,"shopmin")) {
928     m->shopmin = atol(value);
929     } else if (!strcmp(key,"shopmax")) {
930     m->shopmax = atol(value);
931     } else if (!strcmp(key,"shoprace")) {
932     *end=0;
933     m->shoprace = strdup_local(value);
934     } else if (!strcmp(key,"outdoor")) {
935     m->outdoor = atoi(value);
936     } else if (!strcmp(key, "temp")) {
937     m->temp = atoi(value);
938     } else if (!strcmp(key, "pressure")) {
939     m->pressure = atoi(value);
940     } else if (!strcmp(key, "humid")) {
941     m->humid = atoi(value);
942     } else if (!strcmp(key, "windspeed")) {
943     m->windspeed = atoi(value);
944     } else if (!strcmp(key, "winddir")) {
945     m->winddir = atoi(value);
946     } else if (!strcmp(key, "sky")) {
947     m->sky = atoi(value);
948     } else if (!strcmp(key, "nosmooth")) {
949     m->nosmooth = atoi(value);
950     }
951     else if (!strncmp(key,"tile_path_", 10)) {
952     int tile=atoi(key+10);
953    
954     if (tile<1 || tile>4) {
955     LOG(llevError,"load_map_header: tile location %d out of bounds (%s)\n",
956     tile, m->path);
957     } else {
958     char *path;
959    
960     *end = 0;
961    
962     if (m->tile_path[tile-1]) {
963     LOG(llevError,"load_map_header: tile location %d duplicated (%s)\n",
964     tile, m->path);
965     free(m->tile_path[tile-1]);
966     m->tile_path[tile-1] = NULL;
967     }
968    
969     if (check_path(value, 1) != -1) {
970     /* The unadorned path works. */
971     path = value;
972     } else {
973     /* Try again; it could be a relative exit. */
974    
975     path = path_combine_and_normalize(m->path, value);
976    
977     if (check_path(path, 1) == -1) {
978     LOG(llevError, "get_map_header: Bad tile path %s %s\n", m->path, value);
979     path = NULL;
980     }
981     }
982    
983     if (editor) {
984     /* Use the value as in the file. */
985     m->tile_path[tile-1] = strdup_local(value);
986     } else if (path != NULL) {
987     /* Use the normalized value. */
988     m->tile_path[tile-1] = strdup_local(path);
989     }
990     } /* end if tile direction (in)valid */
991     }
992     else {
993     LOG(llevError,"Got unknown value in map header: %s %s\n", key, value);
994     }
995     }
996     if (!key || strcmp(key,"end")) {
997     LOG(llevError,"Got premature eof on map header!\n");
998     return 1;
999     }
1000     return 0;
1001     }
1002    
1003     /*
1004     * Opens the file "filename" and reads information about the map
1005     * from the given file, and stores it in a newly allocated
1006     * mapstruct. A pointer to this structure is returned, or NULL on failure.
1007     * flags correspond to those in map.h. Main ones used are
1008     * MAP_PLAYER_UNIQUE, in which case we don't do any name changes, and
1009     * MAP_BLOCK, in which case we block on this load. This happens in all
1010     * cases, no matter if this flag is set or not.
1011     * MAP_STYLE: style map - don't add active objects, don't add to server
1012     * managed map list.
1013     */
1014    
1015     mapstruct *load_original_map(const char *filename, int flags) {
1016     FILE *fp;
1017     mapstruct *m;
1018     int comp;
1019     char pathname[MAX_BUF];
1020    
1021     LOG(llevDebug, "load_original_map: %s (%x)\n", filename,flags);
1022     if (flags & MAP_PLAYER_UNIQUE)
1023     strcpy(pathname, filename);
1024     else if (flags & MAP_OVERLAY)
1025     strcpy(pathname, create_overlay_pathname(filename));
1026     else
1027     strcpy(pathname, create_pathname(filename));
1028    
1029     if((fp=open_and_uncompress(pathname, 0, &comp))==NULL) {
1030     LOG(llevError, "Can't open %s: %s\n", pathname, strerror_local(errno));
1031     return (NULL);
1032     }
1033    
1034     m = get_linked_map();
1035    
1036     strcpy (m->path, filename);
1037     if (load_map_header(fp, m)) {
1038     LOG(llevError,"Error loading map header for %s, flags=%d\n",
1039     filename, flags);
1040     delete_map(m);
1041     return NULL;
1042     }
1043    
1044     allocate_map(m);
1045     m->compressed = comp;
1046    
1047     m->in_memory=MAP_LOADING;
1048     load_objects (m, fp, flags & (MAP_BLOCK|MAP_STYLE));
1049     close_and_delete(fp, comp);
1050     m->in_memory=MAP_IN_MEMORY;
1051     if (!MAP_DIFFICULTY(m))
1052     MAP_DIFFICULTY(m)=calculate_difficulty(m);
1053     set_map_reset_time(m);
1054     if (load_original_map_callback)
1055     load_original_map_callback(m);
1056     return (m);
1057     }
1058    
1059     /*
1060     * Loads a map, which has been loaded earlier, from file.
1061     * Return the map object we load into (this can change from the passed
1062     * option if we can't find the original map)
1063     */
1064    
1065     static mapstruct *load_temporary_map(mapstruct *m) {
1066     FILE *fp;
1067     int comp;
1068     char buf[MAX_BUF];
1069    
1070     if (!m->tmpname) {
1071     LOG(llevError, "No temporary filename for map %s\n", m->path);
1072     strcpy(buf, m->path);
1073     delete_map(m);
1074     m = load_original_map(buf, 0);
1075     if(m==NULL) return NULL;
1076     fix_auto_apply(m); /* Chests which open as default */
1077     return m;
1078     }
1079    
1080     if((fp=open_and_uncompress(m->tmpname,0, &comp))==NULL) {
1081     LOG(llevError, "Cannot open %s: %s\n",m->tmpname, strerror_local(errno));
1082     strcpy(buf, m->path);
1083     delete_map(m);
1084     m = load_original_map(buf, 0);
1085     if(m==NULL) return NULL;
1086     fix_auto_apply(m); /* Chests which open as default */
1087     return m;
1088     }
1089    
1090    
1091     if (load_map_header(fp, m)) {
1092     LOG(llevError,"Error loading map header for %s (%s)\n",
1093     m->path, m->tmpname);
1094     delete_map(m);
1095     m = load_original_map(m->path, 0);
1096     return NULL;
1097     }
1098     m->compressed = comp;
1099     allocate_map(m);
1100    
1101     m->in_memory=MAP_LOADING;
1102     load_objects (m, fp, 0);
1103     close_and_delete(fp, comp);
1104     m->in_memory=MAP_IN_MEMORY;
1105     if (load_temporary_map_callback)
1106     load_temporary_map_callback(m);
1107     return m;
1108     }
1109    
1110     /*
1111     * Loads a map, which has been loaded earlier, from file.
1112     * Return the map object we load into (this can change from the passed
1113     * option if we can't find the original map)
1114     */
1115    
1116     mapstruct *load_overlay_map(const char *filename, mapstruct *m) {
1117     FILE *fp;
1118     int comp;
1119     char pathname[MAX_BUF];
1120    
1121     strcpy(pathname, create_overlay_pathname(filename));
1122    
1123     if((fp=open_and_uncompress(pathname, 0, &comp))==NULL) {
1124     /* LOG(llevDebug,"Can't open overlay %s\n", pathname);*/
1125     return m;
1126     }
1127    
1128     if (load_map_header(fp, m)) {
1129     LOG(llevError,"Error loading map header for overlay %s (%s)\n",
1130     m->path, pathname);
1131     delete_map(m);
1132     m = load_original_map(m->path, 0);
1133     return NULL;
1134     }
1135     m->compressed = comp;
1136     /*allocate_map(m);*/
1137    
1138     m->in_memory=MAP_LOADING;
1139     load_objects (m, fp, MAP_OVERLAY);
1140     close_and_delete(fp, comp);
1141     m->in_memory=MAP_IN_MEMORY;
1142     return m;
1143     }
1144    
1145     /******************************************************************************
1146     * This is the start of unique map handling code
1147     *****************************************************************************/
1148    
1149     /* This goes through map 'm' and removed any unique items on the map. */
1150     static void delete_unique_items(mapstruct *m)
1151     {
1152     int i,j,unique;
1153     object *op, *next;
1154    
1155     for(i=0; i<MAP_WIDTH(m); i++)
1156     for(j=0; j<MAP_HEIGHT(m); j++) {
1157     unique=0;
1158     for (op=get_map_ob(m, i, j); op; op=next) {
1159     next = op->above;
1160     if (QUERY_FLAG(op, FLAG_IS_FLOOR) && QUERY_FLAG(op, FLAG_UNIQUE))
1161     unique=1;
1162     if(op->head == NULL && (QUERY_FLAG(op, FLAG_UNIQUE) || unique)) {
1163     clean_object(op);
1164     if (QUERY_FLAG(op, FLAG_IS_LINKED))
1165     remove_button_link(op);
1166     remove_ob(op);
1167     free_object(op);
1168     }
1169     }
1170     }
1171     }
1172    
1173    
1174     /*
1175     * Loads unique objects from file(s) into the map which is in memory
1176     * m is the map to load unique items into.
1177     */
1178     static void load_unique_objects(mapstruct *m) {
1179     FILE *fp;
1180     int comp,count;
1181     char firstname[MAX_BUF];
1182    
1183     for (count=0; count<10; count++) {
1184     sprintf(firstname, "%s.v%02d", create_items_path(m->path), count);
1185     if (!access(firstname, R_OK)) break;
1186     }
1187     /* If we get here, we did not find any map */
1188     if (count==10) return;
1189    
1190     if ((fp=open_and_uncompress(firstname, 0, &comp))==NULL) {
1191     /* There is no expectation that every map will have unique items, but this
1192     * is debug output, so leave it in.
1193     */
1194     LOG(llevDebug, "Can't open unique items file for %s\n", create_items_path(m->path));
1195     return;
1196     }
1197    
1198     m->in_memory=MAP_LOADING;
1199     if (m->tmpname == NULL) /* if we have loaded unique items from */
1200     delete_unique_items(m); /* original map before, don't duplicate them */
1201     load_object(fp, NULL, LO_NOREAD,0);
1202     load_objects (m, fp, 0);
1203     close_and_delete(fp, comp);
1204     m->in_memory=MAP_IN_MEMORY;
1205     }
1206    
1207    
1208     /*
1209     * Saves a map to file. If flag is set, it is saved into the same
1210     * file it was (originally) loaded from. Otherwise a temporary
1211     * filename will be genarated, and the file will be stored there.
1212     * The temporary filename will be stored in the mapstructure.
1213     * If the map is unique, we also save to the filename in the map
1214     * (this should have been updated when first loaded)
1215     */
1216    
1217     int new_save_map(mapstruct *m, int flag) {
1218     FILE *fp, *fp2;
1219     char filename[MAX_BUF],buf[MAX_BUF], shop[MAX_BUF];
1220     int i;
1221    
1222     if (flag && !*m->path) {
1223     LOG(llevError,"Tried to save map without path.\n");
1224     return -1;
1225     }
1226    
1227     if (flag || (m->unique) || (m->templatemap)) {
1228     if (!m->unique && !m->templatemap) { /* flag is set */
1229     if (flag == 2)
1230     strcpy(filename, create_overlay_pathname(m->path));
1231     else
1232     strcpy (filename, create_pathname (m->path));
1233     } else
1234     strcpy (filename, m->path);
1235    
1236     /* If the compression suffix already exists on the filename, don't
1237     * put it on again. This nasty looking strcmp checks to see if the
1238     * compression suffix is at the end of the filename already.
1239     */
1240     if (m->compressed &&
1241     strcmp((filename + strlen(filename)-strlen(uncomp[m->compressed][0])),
1242     uncomp[m->compressed][0]))
1243     strcat(filename, uncomp[m->compressed][0]);
1244     make_path_to_file(filename);
1245     } else {
1246     if (!m->tmpname)
1247     m->tmpname = tempnam_local(settings.tmpdir,NULL);
1248     strcpy(filename, m->tmpname);
1249     }
1250     LOG(llevDebug,"Saving map %s\n",m->path);
1251     m->in_memory = MAP_SAVING;
1252    
1253     unlink (filename); // do not overwrite backups if done via hardlinks
1254    
1255     /* Compress if it isn't a temporary save. Do compress if unique */
1256     if (m->compressed && (m->unique || m->templatemap || flag)) {
1257     char buf[MAX_BUF];
1258     strcpy(buf, uncomp[m->compressed][2]);
1259     strcat(buf, " > ");
1260     strcat(buf, filename);
1261     fp = popen(buf, "w");
1262     } else
1263     fp = fopen(filename, "w");
1264    
1265     if(fp == NULL) {
1266     LOG(llevError, "Cannot write %s: %s\n", filename, strerror_local(errno));
1267     return -1;
1268     }
1269    
1270     /* legacy */
1271     fprintf(fp,"arch map\n");
1272     if (m->name) fprintf(fp,"name %s\n", m->name);
1273     if (!flag) fprintf(fp,"swap_time %d\n", m->swap_time);
1274     if (m->reset_timeout) fprintf(fp,"reset_timeout %d\n", m->reset_timeout);
1275     if (m->fixed_resettime) fprintf(fp,"fixed_resettime %d\n", m->fixed_resettime);
1276     /* we unfortunately have no idea if this is a value the creator set
1277     * or a difficulty value we generated when the map was first loaded
1278     */
1279     if (m->difficulty) fprintf(fp,"difficulty %d\n", m->difficulty);
1280     if (m->region) fprintf(fp,"region %s\n", m->region->name);
1281     if (m->shopitems) {
1282     print_shop_string(m, shop);
1283     fprintf(fp,"shopitems %s\n", shop);
1284     }
1285     if (m->shopgreed) fprintf(fp,"shopgreed %f\n", m->shopgreed);
1286     #ifndef WIN32
1287     if (m->shopmin) fprintf(fp,"shopmin %llu\n", m->shopmin);
1288     if (m->shopmax) fprintf(fp,"shopmax %llu\n", m->shopmax);
1289     #else
1290     if (m->shopmin) fprintf(fp,"shopmin %I64u\n", m->shopmin);
1291     if (m->shopmax) fprintf(fp,"shopmax %I64u\n", m->shopmax);
1292     #endif
1293     if (m->shoprace) fprintf(fp,"shoprace %s\n", m->shoprace);
1294     if (m->darkness) fprintf(fp,"darkness %d\n", m->darkness);
1295     if (m->width) fprintf(fp,"width %d\n", m->width);
1296     if (m->height) fprintf(fp,"height %d\n", m->height);
1297     if (m->enter_x) fprintf(fp,"enter_x %d\n", m->enter_x);
1298     if (m->enter_y) fprintf(fp,"enter_y %d\n", m->enter_y);
1299     if (m->msg) fprintf(fp,"msg\n%sendmsg\n", m->msg);
1300     if (m->maplore) fprintf(fp,"maplore\n%sendmaplore\n", m->maplore);
1301     if (m->unique) fprintf(fp,"unique %d\n", m->unique);
1302     if (m->templatemap) fprintf(fp,"template %d\n", m->templatemap);
1303     if (m->outdoor) fprintf(fp,"outdoor %d\n", m->outdoor);
1304     if (m->temp) fprintf(fp, "temp %d\n", m->temp);
1305     if (m->pressure) fprintf(fp, "pressure %d\n", m->pressure);
1306     if (m->humid) fprintf(fp, "humid %d\n", m->humid);
1307     if (m->windspeed) fprintf(fp, "windspeed %d\n", m->windspeed);
1308     if (m->winddir) fprintf(fp, "winddir %d\n", m->winddir);
1309     if (m->sky) fprintf(fp, "sky %d\n", m->sky);
1310     if (m->nosmooth) fprintf(fp, "nosmooth %d\n", m->nosmooth);
1311    
1312     /* Save any tiling information, except on overlays */
1313     if (flag != 2)
1314     for (i=0; i<4; i++)
1315     if (m->tile_path[i])
1316     fprintf(fp,"tile_path_%d %s\n", i+1, m->tile_path[i]);
1317    
1318     fprintf(fp,"end\n");
1319    
1320     /* In the game save unique items in the different file, but
1321     * in the editor save them to the normal map file.
1322     * If unique map, save files in the proper destination (set by
1323     * player)
1324     */
1325     fp2 = fp; /* save unique items into fp2 */
1326     if ((flag == 0 || flag == 2) && !m->unique && !m->templatemap) {
1327     sprintf (buf,"%s.v00",create_items_path (m->path));
1328     if ((fp2 = fopen (buf, "w")) == NULL) {
1329     LOG(llevError, "Can't open unique items file %s\n", buf);
1330     }
1331     if (flag == 2)
1332     save_objects(m, fp, fp2, 2);
1333     else
1334     save_objects (m, fp, fp2, 0);
1335     if (fp2 != NULL) {
1336     if (ftell (fp2) == 0) {
1337     fclose (fp2);
1338     unlink (buf);
1339     } else {
1340     fclose (fp2);
1341     chmod (buf, SAVE_MODE);
1342     }
1343     }
1344     } else { /* save same file when not playing, like in editor */
1345     save_objects(m, fp, fp, 0);
1346     }
1347    
1348     if (m->compressed && (m->unique || m->templatemap || flag))
1349     pclose(fp);
1350     else
1351     fclose(fp);
1352    
1353     chmod (filename, SAVE_MODE);
1354     return 0;
1355     }
1356    
1357    
1358     /*
1359     * Remove and free all objects in the inventory of the given object.
1360     * object.c ?
1361     */
1362    
1363     void clean_object(object *op)
1364     {
1365     object *tmp, *next;
1366    
1367     for(tmp = op->inv; tmp; tmp = next)
1368     {
1369     next = tmp->below;
1370     clean_object(tmp);
1371     if (QUERY_FLAG(tmp, FLAG_IS_LINKED))
1372     remove_button_link(tmp);
1373     remove_ob(tmp);
1374     free_object(tmp);
1375     }
1376     }
1377    
1378     /*
1379     * Remove and free all objects in the given map.
1380     */
1381    
1382     void free_all_objects(mapstruct *m) {
1383     int i,j;
1384     object *op;
1385    
1386     for(i=0;i<MAP_WIDTH(m);i++)
1387     for(j=0;j<MAP_HEIGHT(m);j++) {
1388     object *previous_obj=NULL;
1389     while((op=GET_MAP_OB(m,i,j))!=NULL) {
1390     if (op==previous_obj) {
1391     LOG(llevDebug, "free_all_objects: Link error, bailing out.\n");
1392     break;
1393     }
1394     previous_obj=op;
1395     if(op->head!=NULL)
1396     op = op->head;
1397    
1398     /* If the map isn't in memory, free_object will remove and
1399     * free objects in op's inventory. So let it do the job.
1400     */
1401     if (m->in_memory==MAP_IN_MEMORY)
1402     clean_object(op);
1403     remove_ob(op);
1404     free_object(op);
1405     }
1406     }
1407     #ifdef MANY_CORES
1408     /* I see periodic cores on metalforge where a map has been swapped out, but apparantly
1409     * an item on that map was not saved - look for that condition and die as appropriate -
1410     * this leaves more of the map data intact for better debugging.
1411     */
1412     for (op=objects; op!=NULL; op=op->next) {
1413     if (!QUERY_FLAG(op, FLAG_REMOVED) && op->map == m) {
1414     LOG(llevDebug,"free_all_objects: object %s still on map after it should have been freed\n", op->name);
1415     abort();
1416     }
1417     }
1418     #endif
1419     }
1420    
1421     /*
1422     * Frees everything allocated by the given mapstructure.
1423     * don't free tmpname - our caller is left to do that
1424     */
1425    
1426     void free_map(mapstruct *m,int flag) {
1427     int i;
1428    
1429     if (!m->in_memory) {
1430     LOG(llevError,"Trying to free freed map.\n");
1431     return;
1432     }
1433     if (flag && m->spaces) free_all_objects(m);
1434     if (m->name) FREE_AND_CLEAR(m->name);
1435     if (m->spaces) FREE_AND_CLEAR(m->spaces);
1436     if (m->msg) FREE_AND_CLEAR(m->msg);
1437     if (m->maplore) FREE_AND_CLEAR(m->maplore);
1438     if (m->shopitems) FREE_AND_CLEAR(m->shopitems);
1439     if (m->shoprace) FREE_AND_CLEAR(m->shoprace);
1440     if (m->buttons)
1441     free_objectlinkpt(m->buttons);
1442     m->buttons = NULL;
1443     for (i=0; i<4; i++) {
1444     if (m->tile_path[i]) FREE_AND_CLEAR(m->tile_path[i]);
1445     m->tile_map[i] = NULL;
1446     }
1447     m->in_memory = MAP_SWAPPED;
1448     }
1449    
1450     /*
1451     * function: vanish mapstruct
1452     * m : pointer to mapstruct, if NULL no action
1453     * this deletes all the data on the map (freeing pointers)
1454     * and then removes this map from the global linked list of maps.
1455     */
1456    
1457     void delete_map(mapstruct *m) {
1458     mapstruct *tmp, *last;
1459     int i;
1460    
1461     if (!m)
1462     return;
1463     if (m->in_memory == MAP_IN_MEMORY) {
1464     /* change to MAP_SAVING, even though we are not,
1465     * so that remove_ob doesn't do as much work.
1466     */
1467     m->in_memory = MAP_SAVING;
1468     free_map (m, 1);
1469     }
1470     /* move this out of free_map, since tmpname can still be needed if
1471     * the map is swapped out.
1472     */
1473     if (m->tmpname) {
1474     free(m->tmpname);
1475     m->tmpname=NULL;
1476     }
1477     last = NULL;
1478     /* We need to look through all the maps and see if any maps
1479     * are pointing at this one for tiling information. Since
1480     * tiling can be assymetric, we just can not look to see which
1481     * maps this map tiles with and clears those.
1482     */
1483     for (tmp = first_map; tmp != NULL; tmp = tmp->next) {
1484     if (tmp->next == m) last = tmp;
1485    
1486     /* This should hopefully get unrolled on a decent compiler */
1487     for (i=0; i<4; i++)
1488     if (tmp->tile_map[i] == m) tmp->tile_map[i]=NULL;
1489     }
1490    
1491     /* If last is null, then this should be the first map in the list */
1492     if (!last) {
1493     if (m == first_map)
1494     first_map = m->next;
1495     else
1496     /* m->path is a static char, so should hopefully still have
1497     * some useful data in it.
1498     */
1499     LOG(llevError,"delete_map: Unable to find map %s in list\n",
1500     m->path);
1501     }
1502     else
1503     last->next = m->next;
1504    
1505     free (m);
1506     }
1507    
1508    
1509    
1510     /*
1511     * Makes sure the given map is loaded and swapped in.
1512     * name is path name of the map.
1513     * flags meaning:
1514     * 0x1 (MAP_FLUSH): flush the map - always load from the map directory,
1515     * and don't do unique items or the like.
1516     * 0x2 (MAP_PLAYER_UNIQUE) - this is a unique map for each player.
1517     * dont do any more name translation on it.
1518     *
1519     * Returns a pointer to the given map.
1520     */
1521    
1522     mapstruct *ready_map_name(const char *name, int flags) {
1523     mapstruct *m;
1524    
1525     if (!name)
1526     return (NULL);
1527    
1528     /* Have we been at this level before? */
1529     m = has_been_loaded (name);
1530    
1531     /* Map is good to go, so just return it */
1532     if (m && (m->in_memory == MAP_LOADING || m->in_memory == MAP_IN_MEMORY)) {
1533     return m;
1534     }
1535    
1536     /* unique maps always get loaded from their original location, and never
1537     * a temp location. Likewise, if map_flush is set, or we have never loaded
1538     * this map, load it now. I removed the reset checking from here -
1539     * it seems the probability of a player trying to enter a map that should
1540     * reset but hasn't yet is quite low, and removing that makes this function
1541     * a bit cleaner (and players probably shouldn't rely on exact timing for
1542     * resets in any case - if they really care, they should use the 'maps command.
1543     */
1544     if ((flags & (MAP_FLUSH|MAP_PLAYER_UNIQUE)) || !m) {
1545    
1546     /* first visit or time to reset */
1547     if (m) {
1548     clean_tmp_map(m); /* Doesn't make much difference */
1549     delete_map(m);
1550     }
1551    
1552     /* create and load a map */
1553     if (flags & MAP_PLAYER_UNIQUE)
1554     LOG(llevDebug, "Trying to load map %s.\n", name);
1555     else
1556     LOG(llevDebug, "Trying to load map %s.\n", create_pathname(name));
1557    
1558     if (!(m = load_original_map(name, (flags & MAP_PLAYER_UNIQUE))))
1559     return (NULL);
1560    
1561     fix_auto_apply(m); /* Chests which open as default */
1562    
1563     /* If a player unique map, no extra unique object file to load.
1564     * if from the editor, likewise.
1565     */
1566     if (! (flags & (MAP_FLUSH|MAP_PLAYER_UNIQUE)))
1567     load_unique_objects(m);
1568    
1569     if (! (flags & (MAP_FLUSH|MAP_PLAYER_UNIQUE|MAP_OVERLAY))) {
1570     m=load_overlay_map(name, m);
1571     if (m==NULL)
1572     return NULL;
1573     }
1574    
1575     } else {
1576     /* If in this loop, we found a temporary map, so load it up. */
1577    
1578     m=load_temporary_map (m);
1579     if(m==NULL) return NULL;
1580     load_unique_objects(m);
1581    
1582     clean_tmp_map(m);
1583     m->in_memory = MAP_IN_MEMORY;
1584     /* tempnam() on sun systems (probably others) uses malloc
1585     * to allocated space for the string. Free it here.
1586     * In some cases, load_temporary_map above won't find the
1587     * temporary map, and so has reloaded a new map. If that
1588     * is the case, tmpname is now null
1589     */
1590     if (m->tmpname) free(m->tmpname);
1591     m->tmpname = NULL;
1592     /* It's going to be saved anew anyway */
1593     }
1594    
1595     /* Below here is stuff common to both first time loaded maps and
1596     * temp maps.
1597     */
1598    
1599     decay_objects(m); /* start the decay */
1600     /* In case other objects press some buttons down */
1601     update_buttons(m);
1602     if (m->outdoor)
1603     set_darkness_map(m);
1604     /* run the weather over this map */
1605     weather_effect(name);
1606     return m;
1607     }
1608    
1609    
1610     /*
1611     * This routine is supposed to find out the difficulty of the map.
1612     * difficulty does not have a lot to do with character level,
1613     * but does have a lot to do with treasure on the map.
1614     *
1615     * Difficulty can now be set by the map creature. If the value stored
1616     * in the map is zero, then use this routine. Maps should really
1617     * have a difficulty set than using this function - human calculation
1618     * is much better than this functions guesswork.
1619     */
1620    
1621     int calculate_difficulty(mapstruct *m) {
1622     object *op;
1623     archetype *at;
1624     int x, y, i, diff;
1625     long monster_cnt = 0;
1626     double avgexp = 0;
1627     sint64 total_exp = 0;
1628    
1629     if (MAP_DIFFICULTY (m))
1630     {
1631     LOG(llevDebug, "Using stored map difficulty: %d\n", MAP_DIFFICULTY (m));
1632     return MAP_DIFFICULTY (m);
1633     }
1634    
1635     for(x = 0; x < MAP_WIDTH(m); x++)
1636     for(y = 0; y < MAP_HEIGHT(m); y++)
1637     for(op = get_map_ob(m, x, y); op != NULL; op = op->above)
1638     {
1639     if(QUERY_FLAG (op, FLAG_MONSTER))
1640     {
1641     total_exp += op->stats.exp;
1642     monster_cnt++;
1643     }
1644    
1645     if(QUERY_FLAG (op, FLAG_GENERATOR))
1646     {
1647     total_exp += op->stats.exp;
1648     at = type_to_archetype(GENERATE_TYPE (op));
1649    
1650     if(at != NULL)
1651     total_exp += at->clone.stats.exp * 8;
1652    
1653     monster_cnt++;
1654     }
1655     }
1656    
1657     avgexp = (double) total_exp / monster_cnt;
1658    
1659     for (i = 1; i <= settings.max_level; i++)
1660     {
1661     if ((level_exp (i, 1) - level_exp (i - 1, 1)) > (100 * avgexp))
1662     {
1663     /* LOG(llevDebug, "Calculated difficulty for map: %s: %d\n", m->name, i); */
1664     return i;
1665     }
1666     }
1667    
1668     return 1;
1669     }
1670    
1671     void clean_tmp_map(mapstruct *m) {
1672     if(m->tmpname == NULL)
1673     return;
1674     if (clean_temporary_map_callback)
1675     clean_temporary_map_callback (m);
1676     (void) unlink(m->tmpname);
1677     }
1678    
1679     void free_all_maps(void)
1680     {
1681     int real_maps=0;
1682    
1683     while (first_map) {
1684     /* I think some of the callers above before it gets here set this to be
1685     * saving, but we still want to free this data
1686     */
1687     if (first_map->in_memory == MAP_SAVING) first_map->in_memory = MAP_IN_MEMORY;
1688     delete_map(first_map);
1689     real_maps++;
1690     }
1691     LOG(llevDebug,"free_all_maps: Freed %d maps\n", real_maps);
1692     }
1693    
1694     /* change_map_light() - used to change map light level (darkness)
1695     * up or down. Returns true if successful. It should now be
1696     * possible to change a value by more than 1.
1697     * Move this from los.c to map.c since this is more related
1698     * to maps than los.
1699     * postive values make it darker, negative make it brighter
1700     */
1701    
1702     int change_map_light(mapstruct *m, int change) {
1703     int new_level = m->darkness + change;
1704    
1705     /* Nothing to do */
1706     if(!change || (new_level <= 0 && m->darkness == 0) ||
1707     (new_level >= MAX_DARKNESS && m->darkness >=MAX_DARKNESS)) {
1708     return 0;
1709     }
1710    
1711     /* inform all players on the map */
1712     if (change>0)
1713     new_info_map(NDI_BLACK|NDI_UNIQUE, m,"It becomes darker.");
1714     else
1715     new_info_map(NDI_BLACK|NDI_UNIQUE, m,"It becomes brighter.");
1716    
1717     /* Do extra checking. since m->darkness is a unsigned value,
1718     * we need to be extra careful about negative values.
1719     * In general, the checks below are only needed if change
1720     * is not +/-1
1721     */
1722     if (new_level < 0) m->darkness = 0;
1723     else if (new_level >=MAX_DARKNESS) m->darkness = MAX_DARKNESS;
1724     else m->darkness=new_level;
1725    
1726     /* All clients need to get re-updated for the change */
1727     update_all_map_los(m);
1728     return 1;
1729     }
1730    
1731    
1732     /*
1733     * This function updates various attributes about a specific space
1734     * on the map (what it looks like, whether it blocks magic,
1735     * has a living creatures, prevents people from passing
1736     * through, etc)
1737     */
1738     void update_position (mapstruct *m, int x, int y) {
1739     object *tmp, *last = NULL;
1740     uint8 flags = 0, oldflags, light=0, anywhere=0;
1741     New_Face *top,*floor, *middle;
1742     object *top_obj, *floor_obj, *middle_obj;
1743     MoveType move_block=0, move_slow=0, move_on=0, move_off=0, move_allow=0;
1744    
1745     oldflags = GET_MAP_FLAGS(m,x,y);
1746     if (!(oldflags & P_NEED_UPDATE)) {
1747     LOG(llevDebug,"update_position called with P_NEED_UPDATE not set: %s (%d, %d)\n",
1748     m->path, x, y);
1749     return;
1750     }
1751    
1752     middle=blank_face;
1753     top=blank_face;
1754     floor=blank_face;
1755    
1756     middle_obj = NULL;
1757     top_obj = NULL;
1758     floor_obj = NULL;
1759    
1760     for (tmp = get_map_ob (m, x, y); tmp; last = tmp, tmp = tmp->above) {
1761    
1762     /* This could be made additive I guess (two lights better than
1763     * one). But if so, it shouldn't be a simple additive - 2
1764     * light bulbs do not illuminate twice as far as once since
1765     * it is a disapation factor that is squared (or is it cubed?)
1766     */
1767     if (tmp->glow_radius > light) light = tmp->glow_radius;
1768    
1769     /* This call is needed in order to update objects the player
1770     * is standing in that have animations (ie, grass, fire, etc).
1771     * However, it also causes the look window to be re-drawn
1772     * 3 times each time the player moves, because many of the
1773     * functions the move_player calls eventualy call this.
1774     *
1775     * Always put the player down for drawing.
1776     */
1777     if (!tmp->invisible) {
1778     if ((tmp->type==PLAYER || QUERY_FLAG(tmp, FLAG_MONSTER))) {
1779     top = tmp->face;
1780     top_obj = tmp;
1781     }
1782     else if (QUERY_FLAG(tmp,FLAG_IS_FLOOR)) {
1783     /* If we got a floor, that means middle and top were below it,
1784     * so should not be visible, so we clear them.
1785     */
1786     middle=blank_face;
1787     top=blank_face;
1788     floor = tmp->face;
1789     floor_obj = tmp;
1790     }
1791     /* Flag anywhere have high priority */
1792     else if (QUERY_FLAG(tmp, FLAG_SEE_ANYWHERE)) {
1793     middle = tmp->face;
1794    
1795     middle_obj = tmp;
1796     anywhere =1;
1797     }
1798     /* Find the highest visible face around. If equal
1799     * visibilities, we still want the one nearer to the
1800     * top
1801     */
1802     else if (middle == blank_face || (tmp->face->visibility > middle->visibility && !anywhere)) {
1803     middle = tmp->face;
1804     middle_obj = tmp;
1805     }
1806     }
1807     if (tmp==tmp->above) {
1808     LOG(llevError, "Error in structure of map\n");
1809     exit (-1);
1810     }
1811    
1812     move_slow |= tmp->move_slow;
1813     move_block |= tmp->move_block;
1814     move_on |= tmp->move_on;
1815     move_off |= tmp->move_off;
1816     move_allow |= tmp->move_allow;
1817    
1818     if (QUERY_FLAG(tmp,FLAG_ALIVE))
1819     flags |= P_IS_ALIVE;
1820     if (QUERY_FLAG(tmp,FLAG_NO_MAGIC))
1821     flags |= P_NO_MAGIC;
1822     if (QUERY_FLAG(tmp,FLAG_DAMNED))
1823     flags |= P_NO_CLERIC;
1824    
1825     if (QUERY_FLAG(tmp,FLAG_BLOCKSVIEW))
1826     flags |= P_BLOCKSVIEW;
1827     } /* for stack of objects */
1828    
1829     /* we don't want to rely on this function to have accurate flags, but
1830     * since we're already doing the work, we calculate them here.
1831     * if they don't match, logic is broken someplace.
1832     */
1833     if (((oldflags & ~(P_NEED_UPDATE|P_NO_ERROR)) != flags) &&
1834     (!(oldflags & P_NO_ERROR))) {
1835     LOG(llevDebug,"update_position: updated flags do not match old flags: %s (old=%d,new=%d) %x != %x\n",
1836     m->path, x, y,
1837     (oldflags & ~P_NEED_UPDATE), flags);
1838     }
1839     SET_MAP_FLAGS(m, x, y, flags);
1840     SET_MAP_MOVE_BLOCK(m, x, y, move_block & ~move_allow);
1841     SET_MAP_MOVE_ON(m, x, y, move_on);
1842     SET_MAP_MOVE_OFF(m, x, y, move_off);
1843     SET_MAP_MOVE_SLOW(m, x, y, move_slow);
1844    
1845     /* At this point, we have a floor face (if there is a floor),
1846     * and the floor is set - we are not going to touch it at
1847     * this point.
1848     * middle contains the highest visibility face.
1849     * top contains a player/monster face, if there is one.
1850     *
1851     * We now need to fill in top.face and/or middle.face.
1852     */
1853    
1854     /* If the top face also happens to be high visibility, re-do our
1855     * middle face. This should not happen, as we already have the
1856     * else statement above so middle should not get set. OTOH, it
1857     * may be possible for the faces to match but be different objects.
1858     */
1859     if (top == middle) middle=blank_face;
1860    
1861     /* There are three posibilities at this point:
1862     * 1) top face is set, need middle to be set.
1863     * 2) middle is set, need to set top.
1864     * 3) neither middle or top is set - need to set both.
1865     */
1866    
1867     for (tmp=last; tmp; tmp=tmp->below) {
1868     /* Once we get to a floor, stop, since we already have a floor object */
1869     if (QUERY_FLAG(tmp,FLAG_IS_FLOOR)) break;
1870    
1871     /* If two top faces are already set, quit processing */
1872     if ((top != blank_face) && (middle != blank_face)) break;
1873    
1874     /* Only show visible faces, unless its the editor - show all */
1875     if (!tmp->invisible || editor) {
1876     /* Fill in top if needed */
1877     if (top == blank_face) {
1878     top = tmp->face;
1879     top_obj = tmp;
1880     if (top == middle) middle=blank_face;
1881     } else {
1882     /* top is already set - we should only get here if
1883     * middle is not set
1884     *
1885     * Set the middle face and break out, since there is nothing
1886     * more to fill in. We don't check visiblity here, since
1887     *
1888     */
1889     if (tmp->face != top ) {
1890     middle = tmp->face;
1891     middle_obj = tmp;
1892     break;
1893     }
1894     }
1895     }
1896     }
1897     if (middle == floor) middle = blank_face;
1898     if (top == middle) middle = blank_face;
1899     SET_MAP_FACE(m,x,y,top,0);
1900     if(top != blank_face)
1901     SET_MAP_FACE_OBJ(m,x,y,top_obj,0);
1902     else
1903     SET_MAP_FACE_OBJ(m,x,y,NULL,0);
1904     SET_MAP_FACE(m,x,y,middle,1);
1905     if(middle != blank_face)
1906     SET_MAP_FACE_OBJ(m,x,y,middle_obj,1);
1907     else
1908     SET_MAP_FACE_OBJ(m,x,y,NULL,1);
1909     SET_MAP_FACE(m,x,y,floor,2);
1910     if(floor != blank_face)
1911     SET_MAP_FACE_OBJ(m,x,y,floor_obj,2);
1912     else
1913     SET_MAP_FACE_OBJ(m,x,y,NULL,2);
1914     SET_MAP_LIGHT(m,x,y,light);
1915     }
1916    
1917    
1918     void set_map_reset_time(mapstruct *map) {
1919     int timeout;
1920    
1921     timeout = MAP_RESET_TIMEOUT(map);
1922     if (timeout <= 0)
1923     timeout = MAP_DEFAULTRESET;
1924     if (timeout >= MAP_MAXRESET)
1925     timeout = MAP_MAXRESET;
1926     MAP_WHEN_RESET(map) = seconds()+timeout;
1927     }
1928    
1929     /* this updates the orig_map->tile_map[tile_num] value after loading
1930     * the map. It also takes care of linking back the freshly loaded
1931     * maps tile_map values if it tiles back to this one. It returns
1932     * the value of orig_map->tile_map[tile_num]. It really only does this
1933     * so that it is easier for calling functions to verify success.
1934     */
1935    
1936     static mapstruct *load_and_link_tiled_map(mapstruct *orig_map, int tile_num)
1937     {
1938     int dest_tile = (tile_num +2) % 4;
1939     char *path = path_combine_and_normalize(orig_map->path, orig_map->tile_path[tile_num]);
1940    
1941     orig_map->tile_map[tile_num] = ready_map_name(path, 0);
1942    
1943     /* need to do a strcmp here as the orig_map->path is not a shared string */
1944     if (orig_map->tile_map[tile_num]->tile_path[dest_tile] &&
1945     !strcmp(orig_map->tile_map[tile_num]->tile_path[dest_tile], orig_map->path))
1946     orig_map->tile_map[tile_num]->tile_map[dest_tile] = orig_map;
1947    
1948     return orig_map->tile_map[tile_num];
1949     }
1950    
1951     /* this returns TRUE if the coordinates (x,y) are out of
1952     * map m. This function also takes into account any
1953     * tiling considerations, loading adjacant maps as needed.
1954     * This is the function should always be used when it
1955     * necessary to check for valid coordinates.
1956     * This function will recursively call itself for the
1957     * tiled maps.
1958     *
1959     *
1960     */
1961     int out_of_map(mapstruct *m, int x, int y)
1962     {
1963    
1964     /* If we get passed a null map, this is obviously the
1965     * case. This generally shouldn't happen, but if the
1966     * map loads fail below, it could happen.
1967     */
1968     if (!m) return 0;
1969    
1970     if (x<0) {
1971     if (!m->tile_path[3]) return 1;
1972     if (!m->tile_map[3] || m->tile_map[3]->in_memory != MAP_IN_MEMORY) {
1973     load_and_link_tiled_map(m, 3);
1974     }
1975     return (out_of_map(m->tile_map[3], x + MAP_WIDTH(m->tile_map[3]), y));
1976     }
1977     if (x>=MAP_WIDTH(m)) {
1978     if (!m->tile_path[1]) return 1;
1979     if (!m->tile_map[1] || m->tile_map[1]->in_memory != MAP_IN_MEMORY) {
1980     load_and_link_tiled_map(m, 1);
1981     }
1982     return (out_of_map(m->tile_map[1], x - MAP_WIDTH(m), y));
1983     }
1984     if (y<0) {
1985     if (!m->tile_path[0]) return 1;
1986     if (!m->tile_map[0] || m->tile_map[0]->in_memory != MAP_IN_MEMORY) {
1987     load_and_link_tiled_map(m, 0);
1988     }
1989     return (out_of_map(m->tile_map[0], x, y + MAP_HEIGHT(m->tile_map[0])));
1990     }
1991     if (y>=MAP_HEIGHT(m)) {
1992     if (!m->tile_path[2]) return 1;
1993     if (!m->tile_map[2] || m->tile_map[2]->in_memory != MAP_IN_MEMORY) {
1994     load_and_link_tiled_map(m, 2);
1995     }
1996     return (out_of_map(m->tile_map[2], x, y - MAP_HEIGHT(m)));
1997     }
1998    
1999     /* Simple case - coordinates are within this local
2000     * map.
2001     */
2002     return 0;
2003     }
2004    
2005     /* This is basically the same as out_of_map above, but
2006     * instead we return NULL if no map is valid (coordinates
2007     * out of bounds and no tiled map), otherwise it returns
2008     * the map as that the coordinates are really on, and
2009     * updates x and y to be the localized coordinates.
2010     * Using this is more efficient of calling out_of_map
2011     * and then figuring out what the real map is
2012     */
2013     mapstruct *get_map_from_coord(mapstruct *m, sint16 *x, sint16 *y)
2014     {
2015    
2016     if (*x<0) {
2017     if (!m->tile_path[3]) return NULL;
2018     if (!m->tile_map[3] || m->tile_map[3]->in_memory != MAP_IN_MEMORY)
2019     load_and_link_tiled_map(m, 3);
2020    
2021     *x += MAP_WIDTH(m->tile_map[3]);
2022     return (get_map_from_coord(m->tile_map[3], x, y));
2023     }
2024     if (*x>=MAP_WIDTH(m)) {
2025     if (!m->tile_path[1]) return NULL;
2026     if (!m->tile_map[1] || m->tile_map[1]->in_memory != MAP_IN_MEMORY)
2027     load_and_link_tiled_map(m, 1);
2028    
2029     *x -= MAP_WIDTH(m);
2030     return (get_map_from_coord(m->tile_map[1], x, y));
2031     }
2032     if (*y<0) {
2033     if (!m->tile_path[0]) return NULL;
2034     if (!m->tile_map[0] || m->tile_map[0]->in_memory != MAP_IN_MEMORY)
2035     load_and_link_tiled_map(m, 0);
2036    
2037     *y += MAP_HEIGHT(m->tile_map[0]);
2038     return (get_map_from_coord(m->tile_map[0], x, y));
2039     }
2040     if (*y>=MAP_HEIGHT(m)) {
2041     if (!m->tile_path[2]) return NULL;
2042     if (!m->tile_map[2] || m->tile_map[2]->in_memory != MAP_IN_MEMORY)
2043     load_and_link_tiled_map(m, 2);
2044    
2045     *y -= MAP_HEIGHT(m);
2046     return (get_map_from_coord(m->tile_map[2], x, y));
2047     }
2048    
2049     /* Simple case - coordinates are within this local
2050     * map.
2051     */
2052    
2053     return m;
2054     }
2055    
2056     /**
2057     * Return whether map2 is adjacent to map1. If so, store the distance from
2058     * map1 to map2 in dx/dy.
2059     */
2060     static int adjacent_map(const mapstruct *map1, const mapstruct *map2, int *dx, int *dy) {
2061     if (!map1 || !map2)
2062     return 0;
2063    
2064     if (map1 == map2) {
2065     *dx = 0;
2066     *dy = 0;
2067    
2068     } else if (map1->tile_map[0] == map2) { /* up */
2069     *dx = 0;
2070     *dy = -MAP_HEIGHT(map2);
2071     } else if (map1->tile_map[1] == map2) { /* right */
2072     *dx = MAP_WIDTH(map1);
2073     *dy = 0;
2074     } else if (map1->tile_map[2] == map2) { /* down */
2075     *dx = 0;
2076     *dy = MAP_HEIGHT(map1);
2077     } else if (map1->tile_map[3] == map2) { /* left */
2078     *dx = -MAP_WIDTH(map2);
2079     *dy = 0;
2080    
2081     } else if (map1->tile_map[0] && map1->tile_map[0]->tile_map[1] == map2) { /* up right */
2082     *dx = MAP_WIDTH(map1->tile_map[0]);
2083     *dy = -MAP_HEIGHT(map1->tile_map[0]);
2084     } else if (map1->tile_map[0] && map1->tile_map[0]->tile_map[3] == map2) { /* up left */
2085     *dx = -MAP_WIDTH(map2);
2086     *dy = -MAP_HEIGHT(map1->tile_map[0]);
2087     } else if (map1->tile_map[1] && map1->tile_map[1]->tile_map[0] == map2) { /* right up */
2088     *dx = MAP_WIDTH(map1);
2089     *dy = -MAP_HEIGHT(map2);
2090     } else if (map1->tile_map[1] && map1->tile_map[1]->tile_map[2] == map2) { /* right down */
2091     *dx = MAP_WIDTH(map1);
2092     *dy = MAP_HEIGHT(map1->tile_map[1]);
2093     } else if (map1->tile_map[2] && map1->tile_map[2]->tile_map[1] == map2) { /* down right */
2094     *dx = MAP_WIDTH(map1->tile_map[2]);
2095     *dy = MAP_HEIGHT(map1);
2096     } else if (map1->tile_map[2] && map1->tile_map[2]->tile_map[3] == map2) { /* down left */
2097     *dx = -MAP_WIDTH(map2);
2098     *dy = MAP_HEIGHT(map1);
2099     } else if (map1->tile_map[3] && map1->tile_map[3]->tile_map[0] == map2) { /* left up */
2100     *dx = -MAP_WIDTH(map1->tile_map[3]);
2101     *dy = -MAP_HEIGHT(map2);
2102     } else if (map1->tile_map[3] && map1->tile_map[3]->tile_map[2] == map2) { /* left down */
2103     *dx = -MAP_WIDTH(map1->tile_map[3]);
2104     *dy = MAP_HEIGHT(map1->tile_map[3]);
2105    
2106     } else { /* not "adjacent" enough */
2107     return 0;
2108     }
2109    
2110     return 1;
2111     }
2112    
2113     /* From map.c
2114     * This is used by get_player to determine where the other
2115     * creature is. get_rangevector takes into account map tiling,
2116     * so you just can not look the the map coordinates and get the
2117     * righte value. distance_x/y are distance away, which
2118     * can be negativbe. direction is the crossfire direction scheme
2119     * that the creature should head. part is the part of the
2120     * monster that is closest.
2121     *
2122     * get_rangevector looks at op1 and op2, and fills in the
2123     * structure for op1 to get to op2.
2124     * We already trust that the caller has verified that the
2125     * two objects are at least on adjacent maps. If not,
2126     * results are not likely to be what is desired.
2127     * if the objects are not on maps, results are also likely to
2128     * be unexpected
2129     *
2130     * currently, the only flag supported (0x1) is don't translate for
2131     * closest body part of 'op1'
2132     */
2133    
2134     void get_rangevector(object *op1, object *op2, rv_vector *retval, int flags) {
2135     if (!adjacent_map(op1->map, op2->map, &retval->distance_x, &retval->distance_y)) {
2136     /* be conservative and fill in _some_ data */
2137     retval->distance = 100000;
2138     retval->distance_x = 32767;
2139     retval->distance_y = 32767;
2140     retval->direction = 0;
2141     retval->part = 0;
2142     } else {
2143     object *best;
2144    
2145     retval->distance_x += op2->x-op1->x;
2146     retval->distance_y += op2->y-op1->y;
2147    
2148     best = op1;
2149     /* If this is multipart, find the closest part now */
2150     if (!(flags&0x1) && op1->more) {
2151     object *tmp;
2152     int best_distance = retval->distance_x*retval->distance_x+
2153     retval->distance_y*retval->distance_y, tmpi;
2154    
2155     /* we just take the offset of the piece to head to figure
2156     * distance instead of doing all that work above again
2157     * since the distance fields we set above are positive in the
2158     * same axis as is used for multipart objects, the simply arithmetic
2159     * below works.
2160     */
2161     for (tmp = op1->more; tmp != NULL; tmp = tmp->more) {
2162     tmpi = (op1->x-tmp->x+retval->distance_x)*(op1->x-tmp->x+retval->distance_x)+
2163     (op1->y-tmp->y+retval->distance_y)*(op1->y-tmp->y+retval->distance_y);
2164     if (tmpi < best_distance) {
2165     best_distance = tmpi;
2166     best = tmp;
2167     }
2168     }
2169     if (best != op1) {
2170     retval->distance_x += op1->x-best->x;
2171     retval->distance_y += op1->y-best->y;
2172     }
2173     }
2174     retval->part = best;
2175     retval->distance = isqrt(retval->distance_x*retval->distance_x+retval->distance_y*retval->distance_y);
2176     retval->direction = find_dir_2(-retval->distance_x, -retval->distance_y);
2177     }
2178     }
2179    
2180     /* this is basically the same as get_rangevector above, but instead of
2181     * the first parameter being an object, it instead is the map
2182     * and x,y coordinates - this is used for path to player -
2183     * since the object is not infact moving but we are trying to traverse
2184     * the path, we need this.
2185     * flags has no meaning for this function at this time - I kept it in to
2186     * be more consistant with the above function and also in case they are needed
2187     * for something in the future. Also, since no object is pasted, the best
2188     * field of the rv_vector is set to NULL.
2189     */
2190    
2191     void get_rangevector_from_mapcoord(const mapstruct *m, int x, int y, const object *op2, rv_vector *retval, int flags) {
2192     if (!adjacent_map(m, op2->map, &retval->distance_x, &retval->distance_y)) {
2193     /* be conservative and fill in _some_ data */
2194     retval->distance = 100000;
2195     retval->distance_x = 32767;
2196     retval->distance_y = 32767;
2197     retval->direction = 0;
2198     retval->part = 0;
2199     } else {
2200     retval->distance_x += op2->x-x;
2201     retval->distance_y += op2->y-y;
2202    
2203     retval->part = NULL;
2204     retval->distance = isqrt(retval->distance_x*retval->distance_x+retval->distance_y*retval->distance_y);
2205     retval->direction = find_dir_2(-retval->distance_x, -retval->distance_y);
2206     }
2207     }
2208    
2209     /* Returns true of op1 and op2 are effectively on the same map
2210     * (as related to map tiling). Note that this looks for a path from
2211     * op1 to op2, so if the tiled maps are assymetric and op2 has a path
2212     * to op1, this will still return false.
2213     * Note we only look one map out to keep the processing simple
2214     * and efficient. This could probably be a macro.
2215     * MSW 2001-08-05
2216     */
2217     int on_same_map(const object *op1, const object *op2) {
2218     int dx, dy;
2219    
2220     return adjacent_map(op1->map, op2->map, &dx, &dy);
2221     }