added initializing level data from level template if no level file exists
[rocksndiamonds.git] / src / files.c
1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // files.c
10 // ============================================================================
11
12 #include <ctype.h>
13 #include <sys/stat.h>
14 #include <dirent.h>
15 #include <math.h>
16
17 #include "libgame/libgame.h"
18
19 #include "files.h"
20 #include "init.h"
21 #include "tools.h"
22 #include "tape.h"
23
24 #define ENABLE_UNUSED_CODE      0       /* currently unused functions */
25 #define ENABLE_HISTORIC_CHUNKS  0       /* only for historic reference */
26 #define ENABLE_RESERVED_CODE    0       /* reserved for later use */
27
28 #define CHUNK_ID_LEN            4       /* IFF style chunk id length  */
29 #define CHUNK_SIZE_UNDEFINED    0       /* undefined chunk size == 0  */
30 #define CHUNK_SIZE_NONE         -1      /* do not write chunk size    */
31
32 #define LEVEL_CHUNK_NAME_SIZE   MAX_LEVEL_NAME_LEN
33 #define LEVEL_CHUNK_AUTH_SIZE   MAX_LEVEL_AUTHOR_LEN
34
35 #define LEVEL_CHUNK_VERS_SIZE   8       /* size of file version chunk */
36 #define LEVEL_CHUNK_DATE_SIZE   4       /* size of file date chunk    */
37 #define LEVEL_CHUNK_HEAD_SIZE   80      /* size of level file header  */
38 #define LEVEL_CHUNK_HEAD_UNUSED 0       /* unused level header bytes  */
39 #define LEVEL_CHUNK_CNT2_SIZE   160     /* size of level CNT2 chunk   */
40 #define LEVEL_CHUNK_CNT2_UNUSED 11      /* unused CNT2 chunk bytes    */
41 #define LEVEL_CHUNK_CNT3_HEADER 16      /* size of level CNT3 header  */
42 #define LEVEL_CHUNK_CNT3_UNUSED 10      /* unused CNT3 chunk bytes    */
43 #define LEVEL_CPART_CUS3_SIZE   134     /* size of CUS3 chunk part    */
44 #define LEVEL_CPART_CUS3_UNUSED 15      /* unused CUS3 bytes / part   */
45 #define LEVEL_CHUNK_GRP1_SIZE   74      /* size of level GRP1 chunk   */
46
47 /* (element number, number of change pages, change page number) */
48 #define LEVEL_CHUNK_CUSX_UNCHANGED      (2 + (1 + 1) + (1 + 1))
49
50 /* (element number only) */
51 #define LEVEL_CHUNK_GRPX_UNCHANGED      2
52 #define LEVEL_CHUNK_NOTE_UNCHANGED      2
53
54 /* (nothing at all if unchanged) */
55 #define LEVEL_CHUNK_ELEM_UNCHANGED      0
56
57 #define TAPE_CHUNK_VERS_SIZE    8       /* size of file version chunk */
58 #define TAPE_CHUNK_HEAD_SIZE    20      /* size of tape file header   */
59 #define TAPE_CHUNK_HEAD_UNUSED  3       /* unused tape header bytes   */
60
61 #define LEVEL_CHUNK_CNT3_SIZE(x)         (LEVEL_CHUNK_CNT3_HEADER + (x))
62 #define LEVEL_CHUNK_CUS3_SIZE(x)         (2 + (x) * LEVEL_CPART_CUS3_SIZE)
63 #define LEVEL_CHUNK_CUS4_SIZE(x)         (96 + (x) * 48)
64
65 /* file identifier strings */
66 #define LEVEL_COOKIE_TMPL               "ROCKSNDIAMONDS_LEVEL_FILE_VERSION_x.x"
67 #define TAPE_COOKIE_TMPL                "ROCKSNDIAMONDS_TAPE_FILE_VERSION_x.x"
68 #define SCORE_COOKIE                    "ROCKSNDIAMONDS_SCORE_FILE_VERSION_1.2"
69
70 /* values for deciding when (not) to save configuration data */
71 #define SAVE_CONF_NEVER                 0
72 #define SAVE_CONF_ALWAYS                1
73 #define SAVE_CONF_WHEN_CHANGED          -1
74
75 /* values for chunks using micro chunks */
76 #define CONF_MASK_1_BYTE                0x00
77 #define CONF_MASK_2_BYTE                0x40
78 #define CONF_MASK_4_BYTE                0x80
79 #define CONF_MASK_MULTI_BYTES           0xc0
80
81 #define CONF_MASK_BYTES                 0xc0
82 #define CONF_MASK_TOKEN                 0x3f
83
84 #define CONF_VALUE_1_BYTE(x)            (CONF_MASK_1_BYTE       | (x))
85 #define CONF_VALUE_2_BYTE(x)            (CONF_MASK_2_BYTE       | (x))
86 #define CONF_VALUE_4_BYTE(x)            (CONF_MASK_4_BYTE       | (x))
87 #define CONF_VALUE_MULTI_BYTES(x)       (CONF_MASK_MULTI_BYTES  | (x))
88
89 /* these definitions are just for convenience of use and readability */
90 #define CONF_VALUE_8_BIT(x)             CONF_VALUE_1_BYTE(x)
91 #define CONF_VALUE_16_BIT(x)            CONF_VALUE_2_BYTE(x)
92 #define CONF_VALUE_32_BIT(x)            CONF_VALUE_4_BYTE(x)
93 #define CONF_VALUE_BYTES(x)             CONF_VALUE_MULTI_BYTES(x)
94
95 #define CONF_VALUE_NUM_BYTES(x)         ((x) == CONF_MASK_1_BYTE ? 1 :  \
96                                          (x) == CONF_MASK_2_BYTE ? 2 :  \
97                                          (x) == CONF_MASK_4_BYTE ? 4 : 0)
98
99 #define CONF_CONTENT_NUM_ELEMENTS       (3 * 3)
100 #define CONF_CONTENT_NUM_BYTES          (CONF_CONTENT_NUM_ELEMENTS * 2)
101 #define CONF_ELEMENT_NUM_BYTES          (2)
102
103 #define CONF_ENTITY_NUM_BYTES(t)        ((t) == TYPE_ELEMENT ||         \
104                                          (t) == TYPE_ELEMENT_LIST ?     \
105                                          CONF_ELEMENT_NUM_BYTES :       \
106                                          (t) == TYPE_CONTENT ||         \
107                                          (t) == TYPE_CONTENT_LIST ?     \
108                                          CONF_CONTENT_NUM_BYTES : 1)
109
110 #define CONF_ELEMENT_BYTE_POS(i)        ((i) * CONF_ELEMENT_NUM_BYTES)
111 #define CONF_ELEMENTS_ELEMENT(b,i)     ((b[CONF_ELEMENT_BYTE_POS(i)] << 8) |  \
112                                         (b[CONF_ELEMENT_BYTE_POS(i) + 1]))
113
114 #define CONF_CONTENT_ELEMENT_POS(c,x,y) ((c) * CONF_CONTENT_NUM_ELEMENTS +    \
115                                          (y) * 3 + (x))
116 #define CONF_CONTENT_BYTE_POS(c,x,y)    (CONF_CONTENT_ELEMENT_POS(c,x,y) *    \
117                                          CONF_ELEMENT_NUM_BYTES)
118 #define CONF_CONTENTS_ELEMENT(b,c,x,y) ((b[CONF_CONTENT_BYTE_POS(c,x,y)]<< 8)|\
119                                         (b[CONF_CONTENT_BYTE_POS(c,x,y) + 1]))
120
121 /* temporary variables used to store pointers to structure members */
122 static struct LevelInfo li;
123 static struct ElementInfo xx_ei, yy_ei;
124 static struct ElementChangeInfo xx_change;
125 static struct ElementGroupInfo xx_group;
126 static struct EnvelopeInfo xx_envelope;
127 static unsigned int xx_event_bits[NUM_CE_BITFIELDS];
128 static char xx_default_description[MAX_ELEMENT_NAME_LEN + 1];
129 static int xx_num_contents;
130 static int xx_current_change_page;
131 static char xx_default_string_empty[1] = "";
132 static int xx_string_length_unused;
133
134 struct LevelFileConfigInfo
135 {
136   int element;                  /* element for which data is to be stored */
137   int save_type;                /* save data always, never or when changed */
138   int data_type;                /* data type (used internally, not stored) */
139   int conf_type;                /* micro chunk identifier (stored in file) */
140
141   /* (mandatory) */
142   void *value;                  /* variable that holds the data to be stored */
143   int default_value;            /* initial default value for this variable */
144
145   /* (optional) */
146   void *value_copy;             /* variable that holds the data to be copied */
147   void *num_entities;           /* number of entities for multi-byte data */
148   int default_num_entities;     /* default number of entities for this data */
149   int max_num_entities;         /* maximal number of entities for this data */
150   char *default_string;         /* optional default string for string data */
151 };
152
153 static struct LevelFileConfigInfo chunk_config_INFO[] =
154 {
155   /* ---------- values not related to single elements ----------------------- */
156
157   {
158     -1,                                 SAVE_CONF_ALWAYS,
159     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
160     &li.game_engine_type,               GAME_ENGINE_TYPE_RND
161   },
162
163   {
164     -1,                                 SAVE_CONF_ALWAYS,
165     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
166     &li.fieldx,                         STD_LEV_FIELDX
167   },
168   {
169     -1,                                 SAVE_CONF_ALWAYS,
170     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
171     &li.fieldy,                         STD_LEV_FIELDY
172   },
173
174   {
175     -1,                                 SAVE_CONF_ALWAYS,
176     TYPE_INTEGER,                       CONF_VALUE_16_BIT(3),
177     &li.time,                           100
178   },
179
180   {
181     -1,                                 SAVE_CONF_ALWAYS,
182     TYPE_INTEGER,                       CONF_VALUE_16_BIT(4),
183     &li.gems_needed,                    0
184   },
185
186   {
187     -1,                                 -1,
188     TYPE_INTEGER,                       CONF_VALUE_32_BIT(2),
189     &li.random_seed,                    0
190   },
191
192   {
193     -1,                                 -1,
194     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
195     &li.use_step_counter,               FALSE
196   },
197
198   {
199     -1,                                 -1,
200     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(4),
201     &li.wind_direction_initial,         MV_NONE
202   },
203
204   {
205     -1,                                 -1,
206     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(5),
207     &li.em_slippery_gems,               FALSE
208   },
209
210   {
211     -1,                                 -1,
212     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(6),
213     &li.use_custom_template,            FALSE
214   },
215
216   {
217     -1,                                 -1,
218     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(1),
219     &li.can_move_into_acid_bits,        ~0      /* default: everything can */
220   },
221
222   {
223     -1,                                 -1,
224     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(7),
225     &li.dont_collide_with_bits,         ~0      /* default: always deadly */
226   },
227
228   {
229     -1,                                 -1,
230     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
231     &li.em_explodes_by_fire,            FALSE
232   },
233
234   {
235     -1,                                 -1,
236     TYPE_INTEGER,                       CONF_VALUE_16_BIT(5),
237     &li.score[SC_TIME_BONUS],           1
238   },
239
240   {
241     -1,                                 -1,
242     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
243     &li.auto_exit_sokoban,              FALSE
244   },
245
246   {
247     -1,                                 -1,
248     -1,                                 -1,
249     NULL,                               -1
250   }
251 };
252
253 static struct LevelFileConfigInfo chunk_config_ELEM[] =
254 {
255   /* (these values are the same for each player) */
256   {
257     EL_PLAYER_1,                        -1,
258     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
259     &li.block_last_field,               FALSE   /* default case for EM levels */
260   },
261   {
262     EL_PLAYER_1,                        -1,
263     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
264     &li.sp_block_last_field,            TRUE    /* default case for SP levels */
265   },
266   {
267     EL_PLAYER_1,                        -1,
268     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
269     &li.instant_relocation,             FALSE
270   },
271   {
272     EL_PLAYER_1,                        -1,
273     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(4),
274     &li.can_pass_to_walkable,           FALSE
275   },
276   {
277     EL_PLAYER_1,                        -1,
278     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(5),
279     &li.block_snap_field,               TRUE
280   },
281   {
282     EL_PLAYER_1,                        -1,
283     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(6),
284     &li.continuous_snapping,            TRUE
285   },
286   {
287     EL_PLAYER_1,                        -1,
288     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(12),
289     &li.shifted_relocation,             FALSE
290   },
291   {
292     EL_PLAYER_1,                        -1,
293     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(15),
294     &li.lazy_relocation,                FALSE
295   },
296
297   /* (these values are different for each player) */
298   {
299     EL_PLAYER_1,                        -1,
300     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
301     &li.initial_player_stepsize[0],     STEPSIZE_NORMAL
302   },
303   {
304     EL_PLAYER_1,                        -1,
305     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
306     &li.initial_player_gravity[0],      FALSE
307   },
308   {
309     EL_PLAYER_1,                        -1,
310     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
311     &li.use_start_element[0],           FALSE
312   },
313   {
314     EL_PLAYER_1,                        -1,
315     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
316     &li.start_element[0],               EL_PLAYER_1
317   },
318   {
319     EL_PLAYER_1,                        -1,
320     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
321     &li.use_artwork_element[0],         FALSE
322   },
323   {
324     EL_PLAYER_1,                        -1,
325     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
326     &li.artwork_element[0],             EL_PLAYER_1
327   },
328   {
329     EL_PLAYER_1,                        -1,
330     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
331     &li.use_explosion_element[0],       FALSE
332   },
333   {
334     EL_PLAYER_1,                        -1,
335     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
336     &li.explosion_element[0],           EL_PLAYER_1
337   },
338   {
339     EL_PLAYER_1,                        -1,
340     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
341     &li.use_initial_inventory[0],       FALSE
342   },
343   {
344     EL_PLAYER_1,                        -1,
345     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
346     &li.initial_inventory_size[0],      1
347   },
348   {
349     EL_PLAYER_1,                        -1,
350     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
351     &li.initial_inventory_content[0][0],EL_EMPTY, NULL,
352     &li.initial_inventory_size[0],      1, MAX_INITIAL_INVENTORY_SIZE
353   },
354
355   {
356     EL_PLAYER_2,                        -1,
357     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
358     &li.initial_player_stepsize[1],     STEPSIZE_NORMAL
359   },
360   {
361     EL_PLAYER_2,                        -1,
362     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
363     &li.initial_player_gravity[1],      FALSE
364   },
365   {
366     EL_PLAYER_2,                        -1,
367     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
368     &li.use_start_element[1],           FALSE
369   },
370   {
371     EL_PLAYER_2,                        -1,
372     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
373     &li.start_element[1],               EL_PLAYER_2
374   },
375   {
376     EL_PLAYER_2,                        -1,
377     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
378     &li.use_artwork_element[1],         FALSE
379   },
380   {
381     EL_PLAYER_2,                        -1,
382     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
383     &li.artwork_element[1],             EL_PLAYER_2
384   },
385   {
386     EL_PLAYER_2,                        -1,
387     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
388     &li.use_explosion_element[1],       FALSE
389   },
390   {
391     EL_PLAYER_2,                        -1,
392     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
393     &li.explosion_element[1],           EL_PLAYER_2
394   },
395   {
396     EL_PLAYER_2,                        -1,
397     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
398     &li.use_initial_inventory[1],       FALSE
399   },
400   {
401     EL_PLAYER_2,                        -1,
402     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
403     &li.initial_inventory_size[1],      1
404   },
405   {
406     EL_PLAYER_2,                        -1,
407     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
408     &li.initial_inventory_content[1][0],EL_EMPTY, NULL,
409     &li.initial_inventory_size[1],      1, MAX_INITIAL_INVENTORY_SIZE
410   },
411
412   {
413     EL_PLAYER_3,                        -1,
414     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
415     &li.initial_player_stepsize[2],     STEPSIZE_NORMAL
416   },
417   {
418     EL_PLAYER_3,                        -1,
419     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
420     &li.initial_player_gravity[2],      FALSE
421   },
422   {
423     EL_PLAYER_3,                        -1,
424     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
425     &li.use_start_element[2],           FALSE
426   },
427   {
428     EL_PLAYER_3,                        -1,
429     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
430     &li.start_element[2],               EL_PLAYER_3
431   },
432   {
433     EL_PLAYER_3,                        -1,
434     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
435     &li.use_artwork_element[2],         FALSE
436   },
437   {
438     EL_PLAYER_3,                        -1,
439     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
440     &li.artwork_element[2],             EL_PLAYER_3
441   },
442   {
443     EL_PLAYER_3,                        -1,
444     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
445     &li.use_explosion_element[2],       FALSE
446   },
447   {
448     EL_PLAYER_3,                        -1,
449     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
450     &li.explosion_element[2],           EL_PLAYER_3
451   },
452   {
453     EL_PLAYER_3,                        -1,
454     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
455     &li.use_initial_inventory[2],       FALSE
456   },
457   {
458     EL_PLAYER_3,                        -1,
459     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
460     &li.initial_inventory_size[2],      1
461   },
462   {
463     EL_PLAYER_3,                        -1,
464     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
465     &li.initial_inventory_content[2][0],EL_EMPTY, NULL,
466     &li.initial_inventory_size[2],      1, MAX_INITIAL_INVENTORY_SIZE
467   },
468
469   {
470     EL_PLAYER_4,                        -1,
471     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
472     &li.initial_player_stepsize[3],     STEPSIZE_NORMAL
473   },
474   {
475     EL_PLAYER_4,                        -1,
476     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
477     &li.initial_player_gravity[3],      FALSE
478   },
479   {
480     EL_PLAYER_4,                        -1,
481     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
482     &li.use_start_element[3],           FALSE
483   },
484   {
485     EL_PLAYER_4,                        -1,
486     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
487     &li.start_element[3],               EL_PLAYER_4
488   },
489   {
490     EL_PLAYER_4,                        -1,
491     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
492     &li.use_artwork_element[3],         FALSE
493   },
494   {
495     EL_PLAYER_4,                        -1,
496     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
497     &li.artwork_element[3],             EL_PLAYER_4
498   },
499   {
500     EL_PLAYER_4,                        -1,
501     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
502     &li.use_explosion_element[3],       FALSE
503   },
504   {
505     EL_PLAYER_4,                        -1,
506     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
507     &li.explosion_element[3],           EL_PLAYER_4
508   },
509   {
510     EL_PLAYER_4,                        -1,
511     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
512     &li.use_initial_inventory[3],       FALSE
513   },
514   {
515     EL_PLAYER_4,                        -1,
516     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
517     &li.initial_inventory_size[3],      1
518   },
519   {
520     EL_PLAYER_4,                        -1,
521     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
522     &li.initial_inventory_content[3][0],EL_EMPTY, NULL,
523     &li.initial_inventory_size[3],      1, MAX_INITIAL_INVENTORY_SIZE
524   },
525
526   {
527     EL_EMERALD,                         -1,
528     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
529     &li.score[SC_EMERALD],              10
530   },
531
532   {
533     EL_DIAMOND,                         -1,
534     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
535     &li.score[SC_DIAMOND],              10
536   },
537
538   {
539     EL_BUG,                             -1,
540     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
541     &li.score[SC_BUG],                  10
542   },
543
544   {
545     EL_SPACESHIP,                       -1,
546     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
547     &li.score[SC_SPACESHIP],            10
548   },
549
550   {
551     EL_PACMAN,                          -1,
552     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
553     &li.score[SC_PACMAN],               10
554   },
555
556   {
557     EL_NUT,                             -1,
558     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
559     &li.score[SC_NUT],                  10
560   },
561
562   {
563     EL_DYNAMITE,                        -1,
564     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
565     &li.score[SC_DYNAMITE],             10
566   },
567
568   {
569     EL_KEY_1,                           -1,
570     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
571     &li.score[SC_KEY],                  10
572   },
573
574   {
575     EL_PEARL,                           -1,
576     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
577     &li.score[SC_PEARL],                10
578   },
579
580   {
581     EL_CRYSTAL,                         -1,
582     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
583     &li.score[SC_CRYSTAL],              10
584   },
585
586   {
587     EL_BD_AMOEBA,                       -1,
588     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
589     &li.amoeba_content,                 EL_DIAMOND
590   },
591   {
592     EL_BD_AMOEBA,                       -1,
593     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
594     &li.amoeba_speed,                   10
595   },
596   {
597     EL_BD_AMOEBA,                       -1,
598     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
599     &li.grow_into_diggable,             TRUE
600   },
601
602   {
603     EL_YAMYAM,                          -1,
604     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(1),
605     &li.yamyam_content,                 EL_ROCK, NULL,
606     &li.num_yamyam_contents,            4, MAX_ELEMENT_CONTENTS
607   },
608   {
609     EL_YAMYAM,                          -1,
610     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
611     &li.score[SC_YAMYAM],               10
612   },
613
614   {
615     EL_ROBOT,                           -1,
616     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
617     &li.score[SC_ROBOT],                10
618   },
619   {
620     EL_ROBOT,                           -1,
621     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
622     &li.slurp_score,                    10
623   },
624
625   {
626     EL_ROBOT_WHEEL,                     -1,
627     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
628     &li.time_wheel,                     10
629   },
630
631   {
632     EL_MAGIC_WALL,                      -1,
633     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
634     &li.time_magic_wall,                10
635   },
636
637   {
638     EL_GAME_OF_LIFE,                    -1,
639     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
640     &li.game_of_life[0],                2
641   },
642   {
643     EL_GAME_OF_LIFE,                    -1,
644     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
645     &li.game_of_life[1],                3
646   },
647   {
648     EL_GAME_OF_LIFE,                    -1,
649     TYPE_INTEGER,                       CONF_VALUE_8_BIT(3),
650     &li.game_of_life[2],                3
651   },
652   {
653     EL_GAME_OF_LIFE,                    -1,
654     TYPE_INTEGER,                       CONF_VALUE_8_BIT(4),
655     &li.game_of_life[3],                3
656   },
657
658   {
659     EL_BIOMAZE,                         -1,
660     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
661     &li.biomaze[0],                     2
662   },
663   {
664     EL_BIOMAZE,                         -1,
665     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
666     &li.biomaze[1],                     3
667   },
668   {
669     EL_BIOMAZE,                         -1,
670     TYPE_INTEGER,                       CONF_VALUE_8_BIT(3),
671     &li.biomaze[2],                     3
672   },
673   {
674     EL_BIOMAZE,                         -1,
675     TYPE_INTEGER,                       CONF_VALUE_8_BIT(4),
676     &li.biomaze[3],                     3
677   },
678
679   {
680     EL_TIMEGATE_SWITCH,                 -1,
681     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
682     &li.time_timegate,                  10
683   },
684
685   {
686     EL_LIGHT_SWITCH_ACTIVE,             -1,
687     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
688     &li.time_light,                     10
689   },
690
691   {
692     EL_SHIELD_NORMAL,                   -1,
693     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
694     &li.shield_normal_time,             10
695   },
696   {
697     EL_SHIELD_NORMAL,                   -1,
698     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
699     &li.score[SC_SHIELD],               10
700   },
701
702   {
703     EL_SHIELD_DEADLY,                   -1,
704     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
705     &li.shield_deadly_time,             10
706   },
707   {
708     EL_SHIELD_DEADLY,                   -1,
709     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
710     &li.score[SC_SHIELD],               10
711   },
712
713   {
714     EL_EXTRA_TIME,                      -1,
715     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
716     &li.extra_time,                     10
717   },
718   {
719     EL_EXTRA_TIME,                      -1,
720     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
721     &li.extra_time_score,               10
722   },
723
724   {
725     EL_TIME_ORB_FULL,                   -1,
726     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
727     &li.time_orb_time,                  10
728   },
729   {
730     EL_TIME_ORB_FULL,                   -1,
731     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
732     &li.use_time_orb_bug,               FALSE
733   },
734
735   {
736     EL_SPRING,                          -1,
737     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
738     &li.use_spring_bug,                 FALSE
739   },
740
741   {
742     EL_EMC_ANDROID,                     -1,
743     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
744     &li.android_move_time,              10
745   },
746   {
747     EL_EMC_ANDROID,                     -1,
748     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
749     &li.android_clone_time,             10
750   },
751   {
752     EL_EMC_ANDROID,                     -1,
753     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
754     &li.android_clone_element[0],       EL_EMPTY, NULL,
755     &li.num_android_clone_elements,     1, MAX_ANDROID_ELEMENTS
756   },
757
758   {
759     EL_EMC_LENSES,                      -1,
760     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
761     &li.lenses_score,                   10
762   },
763   {
764     EL_EMC_LENSES,                      -1,
765     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
766     &li.lenses_time,                    10
767   },
768
769   {
770     EL_EMC_MAGNIFIER,                   -1,
771     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
772     &li.magnify_score,                  10
773   },
774   {
775     EL_EMC_MAGNIFIER,                   -1,
776     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
777     &li.magnify_time,                   10
778   },
779
780   {
781     EL_EMC_MAGIC_BALL,                  -1,
782     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
783     &li.ball_time,                      10
784   },
785   {
786     EL_EMC_MAGIC_BALL,                  -1,
787     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
788     &li.ball_random,                    FALSE
789   },
790   {
791     EL_EMC_MAGIC_BALL,                  -1,
792     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
793     &li.ball_state_initial,             FALSE
794   },
795   {
796     EL_EMC_MAGIC_BALL,                  -1,
797     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(1),
798     &li.ball_content,                   EL_EMPTY, NULL,
799     &li.num_ball_contents,              4, MAX_ELEMENT_CONTENTS
800   },
801
802   /* ---------- unused values ----------------------------------------------- */
803
804   {
805     EL_UNKNOWN,                         SAVE_CONF_NEVER,
806     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
807     &li.score[SC_UNKNOWN_14],           10
808   },
809   {
810     EL_UNKNOWN,                         SAVE_CONF_NEVER,
811     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
812     &li.score[SC_UNKNOWN_15],           10
813   },
814
815   {
816     -1,                                 -1,
817     -1,                                 -1,
818     NULL,                               -1
819   }
820 };
821
822 static struct LevelFileConfigInfo chunk_config_NOTE[] =
823 {
824   {
825     -1,                                 -1,
826     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
827     &xx_envelope.xsize,                 MAX_ENVELOPE_XSIZE,
828   },
829   {
830     -1,                                 -1,
831     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
832     &xx_envelope.ysize,                 MAX_ENVELOPE_YSIZE,
833   },
834
835   {
836     -1,                                 -1,
837     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
838     &xx_envelope.autowrap,              FALSE
839   },
840   {
841     -1,                                 -1,
842     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(4),
843     &xx_envelope.centered,              FALSE
844   },
845
846   {
847     -1,                                 -1,
848     TYPE_STRING,                        CONF_VALUE_BYTES(1),
849     &xx_envelope.text,                  -1, NULL,
850     &xx_string_length_unused,           -1, MAX_ENVELOPE_TEXT_LEN,
851     &xx_default_string_empty[0]
852   },
853
854   {
855     -1,                                 -1,
856     -1,                                 -1,
857     NULL,                               -1
858   }
859 };
860
861 static struct LevelFileConfigInfo chunk_config_CUSX_base[] =
862 {
863   {
864     -1,                                 -1,
865     TYPE_STRING,                        CONF_VALUE_BYTES(1),
866     &xx_ei.description[0],              -1,
867     &yy_ei.description[0],
868     &xx_string_length_unused,           -1, MAX_ELEMENT_NAME_LEN,
869     &xx_default_description[0]
870   },
871
872   {
873     -1,                                 -1,
874     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(1),
875     &xx_ei.properties[EP_BITFIELD_BASE_NR], EP_BITMASK_BASE_DEFAULT,
876     &yy_ei.properties[EP_BITFIELD_BASE_NR]
877   },
878 #if ENABLE_RESERVED_CODE
879   /* (reserved for later use) */
880   {
881     -1,                                 -1,
882     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(2),
883     &xx_ei.properties[EP_BITFIELD_BASE_NR + 1], EP_BITMASK_DEFAULT,
884     &yy_ei.properties[EP_BITFIELD_BASE_NR + 1]
885   },
886 #endif
887
888   {
889     -1,                                 -1,
890     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
891     &xx_ei.use_gfx_element,             FALSE,
892     &yy_ei.use_gfx_element
893   },
894   {
895     -1,                                 -1,
896     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
897     &xx_ei.gfx_element_initial,         EL_EMPTY_SPACE,
898     &yy_ei.gfx_element_initial
899   },
900
901   {
902     -1,                                 -1,
903     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(2),
904     &xx_ei.access_direction,            MV_ALL_DIRECTIONS,
905     &yy_ei.access_direction
906   },
907
908   {
909     -1,                                 -1,
910     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
911     &xx_ei.collect_score_initial,       10,
912     &yy_ei.collect_score_initial
913   },
914   {
915     -1,                                 -1,
916     TYPE_INTEGER,                       CONF_VALUE_16_BIT(3),
917     &xx_ei.collect_count_initial,       1,
918     &yy_ei.collect_count_initial
919   },
920
921   {
922     -1,                                 -1,
923     TYPE_INTEGER,                       CONF_VALUE_16_BIT(4),
924     &xx_ei.ce_value_fixed_initial,      0,
925     &yy_ei.ce_value_fixed_initial
926   },
927   {
928     -1,                                 -1,
929     TYPE_INTEGER,                       CONF_VALUE_16_BIT(5),
930     &xx_ei.ce_value_random_initial,     0,
931     &yy_ei.ce_value_random_initial
932   },
933   {
934     -1,                                 -1,
935     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
936     &xx_ei.use_last_ce_value,           FALSE,
937     &yy_ei.use_last_ce_value
938   },
939
940   {
941     -1,                                 -1,
942     TYPE_INTEGER,                       CONF_VALUE_16_BIT(6),
943     &xx_ei.push_delay_fixed,            8,
944     &yy_ei.push_delay_fixed
945   },
946   {
947     -1,                                 -1,
948     TYPE_INTEGER,                       CONF_VALUE_16_BIT(7),
949     &xx_ei.push_delay_random,           8,
950     &yy_ei.push_delay_random
951   },
952   {
953     -1,                                 -1,
954     TYPE_INTEGER,                       CONF_VALUE_16_BIT(8),
955     &xx_ei.drop_delay_fixed,            0,
956     &yy_ei.drop_delay_fixed
957   },
958   {
959     -1,                                 -1,
960     TYPE_INTEGER,                       CONF_VALUE_16_BIT(9),
961     &xx_ei.drop_delay_random,           0,
962     &yy_ei.drop_delay_random
963   },
964   {
965     -1,                                 -1,
966     TYPE_INTEGER,                       CONF_VALUE_16_BIT(10),
967     &xx_ei.move_delay_fixed,            0,
968     &yy_ei.move_delay_fixed
969   },
970   {
971     -1,                                 -1,
972     TYPE_INTEGER,                       CONF_VALUE_16_BIT(11),
973     &xx_ei.move_delay_random,           0,
974     &yy_ei.move_delay_random
975   },
976
977   {
978     -1,                                 -1,
979     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(3),
980     &xx_ei.move_pattern,                MV_ALL_DIRECTIONS,
981     &yy_ei.move_pattern
982   },
983   {
984     -1,                                 -1,
985     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(4),
986     &xx_ei.move_direction_initial,      MV_START_AUTOMATIC,
987     &yy_ei.move_direction_initial
988   },
989   {
990     -1,                                 -1,
991     TYPE_INTEGER,                       CONF_VALUE_8_BIT(5),
992     &xx_ei.move_stepsize,               TILEX / 8,
993     &yy_ei.move_stepsize
994   },
995
996   {
997     -1,                                 -1,
998     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(12),
999     &xx_ei.move_enter_element,          EL_EMPTY_SPACE,
1000     &yy_ei.move_enter_element
1001   },
1002   {
1003     -1,                                 -1,
1004     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(13),
1005     &xx_ei.move_leave_element,          EL_EMPTY_SPACE,
1006     &yy_ei.move_leave_element
1007   },
1008   {
1009     -1,                                 -1,
1010     TYPE_INTEGER,                       CONF_VALUE_8_BIT(6),
1011     &xx_ei.move_leave_type,             LEAVE_TYPE_UNLIMITED,
1012     &yy_ei.move_leave_type
1013   },
1014
1015   {
1016     -1,                                 -1,
1017     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
1018     &xx_ei.slippery_type,               SLIPPERY_ANY_RANDOM,
1019     &yy_ei.slippery_type
1020   },
1021
1022   {
1023     -1,                                 -1,
1024     TYPE_INTEGER,                       CONF_VALUE_8_BIT(8),
1025     &xx_ei.explosion_type,              EXPLODES_3X3,
1026     &yy_ei.explosion_type
1027   },
1028   {
1029     -1,                                 -1,
1030     TYPE_INTEGER,                       CONF_VALUE_16_BIT(14),
1031     &xx_ei.explosion_delay,             16,
1032     &yy_ei.explosion_delay
1033   },
1034   {
1035     -1,                                 -1,
1036     TYPE_INTEGER,                       CONF_VALUE_16_BIT(15),
1037     &xx_ei.ignition_delay,              8,
1038     &yy_ei.ignition_delay
1039   },
1040
1041   {
1042     -1,                                 -1,
1043     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(2),
1044     &xx_ei.content,                     EL_EMPTY_SPACE,
1045     &yy_ei.content,
1046     &xx_num_contents,                   1, 1
1047   },
1048
1049   /* ---------- "num_change_pages" must be the last entry ------------------- */
1050
1051   {
1052     -1,                                 SAVE_CONF_ALWAYS,
1053     TYPE_INTEGER,                       CONF_VALUE_8_BIT(9),
1054     &xx_ei.num_change_pages,            1,
1055     &yy_ei.num_change_pages
1056   },
1057
1058   {
1059     -1,                                 -1,
1060     -1,                                 -1,
1061     NULL,                               -1,
1062     NULL
1063   }
1064 };
1065
1066 static struct LevelFileConfigInfo chunk_config_CUSX_change[] =
1067 {
1068   /* ---------- "current_change_page" must be the first entry --------------- */
1069
1070   {
1071     -1,                                 SAVE_CONF_ALWAYS,
1072     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
1073     &xx_current_change_page,            -1
1074   },
1075
1076   /* ---------- (the remaining entries can be in any order) ----------------- */
1077
1078   {
1079     -1,                                 -1,
1080     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
1081     &xx_change.can_change,              FALSE
1082   },
1083
1084   {
1085     -1,                                 -1,
1086     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(1),
1087     &xx_event_bits[0],                  0
1088   },
1089   {
1090     -1,                                 -1,
1091     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(2),
1092     &xx_event_bits[1],                  0
1093   },
1094
1095   {
1096     -1,                                 -1,
1097     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(3),
1098     &xx_change.trigger_player,          CH_PLAYER_ANY
1099   },
1100   {
1101     -1,                                 -1,
1102     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(4),
1103     &xx_change.trigger_side,            CH_SIDE_ANY
1104   },
1105   {
1106     -1,                                 -1,
1107     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(3),
1108     &xx_change.trigger_page,            CH_PAGE_ANY
1109   },
1110
1111   {
1112     -1,                                 -1,
1113     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1114     &xx_change.target_element,          EL_EMPTY_SPACE
1115   },
1116
1117   {
1118     -1,                                 -1,
1119     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
1120     &xx_change.delay_fixed,             0
1121   },
1122   {
1123     -1,                                 -1,
1124     TYPE_INTEGER,                       CONF_VALUE_16_BIT(3),
1125     &xx_change.delay_random,            0
1126   },
1127   {
1128     -1,                                 -1,
1129     TYPE_INTEGER,                       CONF_VALUE_16_BIT(4),
1130     &xx_change.delay_frames,            FRAMES_PER_SECOND
1131   },
1132
1133   {
1134     -1,                                 -1,
1135     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(5),
1136     &xx_change.initial_trigger_element, EL_EMPTY_SPACE
1137   },
1138
1139   {
1140     -1,                                 -1,
1141     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(6),
1142     &xx_change.explode,                 FALSE
1143   },
1144   {
1145     -1,                                 -1,
1146     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(7),
1147     &xx_change.use_target_content,      FALSE
1148   },
1149   {
1150     -1,                                 -1,
1151     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
1152     &xx_change.only_if_complete,        FALSE
1153   },
1154   {
1155     -1,                                 -1,
1156     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
1157     &xx_change.use_random_replace,      FALSE
1158   },
1159   {
1160     -1,                                 -1,
1161     TYPE_INTEGER,                       CONF_VALUE_8_BIT(10),
1162     &xx_change.random_percentage,       100
1163   },
1164   {
1165     -1,                                 -1,
1166     TYPE_INTEGER,                       CONF_VALUE_8_BIT(11),
1167     &xx_change.replace_when,            CP_WHEN_EMPTY
1168   },
1169
1170   {
1171     -1,                                 -1,
1172     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(12),
1173     &xx_change.has_action,              FALSE
1174   },
1175   {
1176     -1,                                 -1,
1177     TYPE_INTEGER,                       CONF_VALUE_8_BIT(13),
1178     &xx_change.action_type,             CA_NO_ACTION
1179   },
1180   {
1181     -1,                                 -1,
1182     TYPE_INTEGER,                       CONF_VALUE_8_BIT(14),
1183     &xx_change.action_mode,             CA_MODE_UNDEFINED
1184   },
1185   {
1186     -1,                                 -1,
1187     TYPE_INTEGER,                       CONF_VALUE_16_BIT(6),
1188     &xx_change.action_arg,              CA_ARG_UNDEFINED
1189   },
1190
1191   {
1192     -1,                                 -1,
1193     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(7),
1194     &xx_change.action_element,          EL_EMPTY_SPACE
1195   },
1196
1197   {
1198     -1,                                 -1,
1199     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(1),
1200     &xx_change.target_content,          EL_EMPTY_SPACE, NULL,
1201     &xx_num_contents,                   1, 1
1202   },
1203
1204   {
1205     -1,                                 -1,
1206     -1,                                 -1,
1207     NULL,                               -1
1208   }
1209 };
1210
1211 static struct LevelFileConfigInfo chunk_config_GRPX[] =
1212 {
1213   {
1214     -1,                                 -1,
1215     TYPE_STRING,                        CONF_VALUE_BYTES(1),
1216     &xx_ei.description[0],              -1, NULL,
1217     &xx_string_length_unused,           -1, MAX_ELEMENT_NAME_LEN,
1218     &xx_default_description[0]
1219   },
1220
1221   {
1222     -1,                                 -1,
1223     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
1224     &xx_ei.use_gfx_element,             FALSE
1225   },
1226   {
1227     -1,                                 -1,
1228     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1229     &xx_ei.gfx_element_initial,         EL_EMPTY_SPACE
1230   },
1231
1232   {
1233     -1,                                 -1,
1234     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
1235     &xx_group.choice_mode,              ANIM_RANDOM
1236   },
1237
1238   {
1239     -1,                                 -1,
1240     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(2),
1241     &xx_group.element[0],               EL_EMPTY_SPACE, NULL,
1242     &xx_group.num_elements,             1, MAX_ELEMENTS_IN_GROUP
1243   },
1244
1245   {
1246     -1,                                 -1,
1247     -1,                                 -1,
1248     NULL,                               -1
1249   }
1250 };
1251
1252 static struct LevelFileConfigInfo chunk_config_CONF[] =         /* (OBSOLETE) */
1253 {
1254   {
1255     EL_PLAYER_1,                        -1,
1256     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
1257     &li.block_snap_field,               TRUE
1258   },
1259   {
1260     EL_PLAYER_1,                        -1,
1261     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
1262     &li.continuous_snapping,            TRUE
1263   },
1264   {
1265     EL_PLAYER_1,                        -1,
1266     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
1267     &li.initial_player_stepsize[0],     STEPSIZE_NORMAL
1268   },
1269   {
1270     EL_PLAYER_1,                        -1,
1271     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
1272     &li.use_start_element[0],           FALSE
1273   },
1274   {
1275     EL_PLAYER_1,                        -1,
1276     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1277     &li.start_element[0],               EL_PLAYER_1
1278   },
1279   {
1280     EL_PLAYER_1,                        -1,
1281     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
1282     &li.use_artwork_element[0],         FALSE
1283   },
1284   {
1285     EL_PLAYER_1,                        -1,
1286     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
1287     &li.artwork_element[0],             EL_PLAYER_1
1288   },
1289   {
1290     EL_PLAYER_1,                        -1,
1291     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(12),
1292     &li.use_explosion_element[0],       FALSE
1293   },
1294   {
1295     EL_PLAYER_1,                        -1,
1296     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
1297     &li.explosion_element[0],           EL_PLAYER_1
1298   },
1299
1300   {
1301     -1,                                 -1,
1302     -1,                                 -1,
1303     NULL,                               -1
1304   }
1305 };
1306
1307 static struct
1308 {
1309   int filetype;
1310   char *id;
1311 }
1312 filetype_id_list[] =
1313 {
1314   { LEVEL_FILE_TYPE_RND,        "RND"   },
1315   { LEVEL_FILE_TYPE_BD,         "BD"    },
1316   { LEVEL_FILE_TYPE_EM,         "EM"    },
1317   { LEVEL_FILE_TYPE_SP,         "SP"    },
1318   { LEVEL_FILE_TYPE_DX,         "DX"    },
1319   { LEVEL_FILE_TYPE_SB,         "SB"    },
1320   { LEVEL_FILE_TYPE_DC,         "DC"    },
1321   { -1,                         NULL    },
1322 };
1323
1324
1325 /* ========================================================================= */
1326 /* level file functions                                                      */
1327 /* ========================================================================= */
1328
1329 static boolean check_special_flags(char *flag)
1330 {
1331   if (strEqual(options.special_flags, flag) ||
1332       strEqual(leveldir_current->special_flags, flag))
1333     return TRUE;
1334
1335   return FALSE;
1336 }
1337
1338 static struct DateInfo getCurrentDate()
1339 {
1340   time_t epoch_seconds = time(NULL);
1341   struct tm *now = localtime(&epoch_seconds);
1342   struct DateInfo date;
1343
1344   date.year  = now->tm_year + 1900;
1345   date.month = now->tm_mon  + 1;
1346   date.day   = now->tm_mday;
1347
1348   date.src   = DATE_SRC_CLOCK;
1349
1350   return date;
1351 }
1352
1353 static void resetEventFlags(struct ElementChangeInfo *change)
1354 {
1355   int i;
1356
1357   for (i = 0; i < NUM_CHANGE_EVENTS; i++)
1358     change->has_event[i] = FALSE;
1359 }
1360
1361 static void resetEventBits()
1362 {
1363   int i;
1364
1365   for (i = 0; i < NUM_CE_BITFIELDS; i++)
1366     xx_event_bits[i] = 0;
1367 }
1368
1369 static void setEventFlagsFromEventBits(struct ElementChangeInfo *change)
1370 {
1371   int i;
1372
1373   /* important: only change event flag if corresponding event bit is set
1374      (this is because all xx_event_bits[] values are loaded separately,
1375      and all xx_event_bits[] values are set back to zero before loading
1376      another value xx_event_bits[x] (each value representing 32 flags)) */
1377
1378   for (i = 0; i < NUM_CHANGE_EVENTS; i++)
1379     if (xx_event_bits[CH_EVENT_BITFIELD_NR(i)] & CH_EVENT_BIT(i))
1380       change->has_event[i] = TRUE;
1381 }
1382
1383 static void setEventBitsFromEventFlags(struct ElementChangeInfo *change)
1384 {
1385   int i;
1386
1387   /* in contrast to the above function setEventFlagsFromEventBits(), it
1388      would also be possible to set all bits in xx_event_bits[] to 0 or 1
1389      depending on the corresponding change->has_event[i] values here, as
1390      all xx_event_bits[] values are reset in resetEventBits() before */
1391
1392   for (i = 0; i < NUM_CHANGE_EVENTS; i++)
1393     if (change->has_event[i])
1394       xx_event_bits[CH_EVENT_BITFIELD_NR(i)] |= CH_EVENT_BIT(i);
1395 }
1396
1397 static char *getDefaultElementDescription(struct ElementInfo *ei)
1398 {
1399   static char description[MAX_ELEMENT_NAME_LEN + 1];
1400   char *default_description = (ei->custom_description != NULL ?
1401                                ei->custom_description :
1402                                ei->editor_description);
1403   int i;
1404
1405   /* always start with reliable default values */
1406   for (i = 0; i < MAX_ELEMENT_NAME_LEN + 1; i++)
1407     description[i] = '\0';
1408
1409   /* truncate element description to MAX_ELEMENT_NAME_LEN bytes */
1410   strncpy(description, default_description, MAX_ELEMENT_NAME_LEN);
1411
1412   return &description[0];
1413 }
1414
1415 static void setElementDescriptionToDefault(struct ElementInfo *ei)
1416 {
1417   char *default_description = getDefaultElementDescription(ei);
1418   int i;
1419
1420   for (i = 0; i < MAX_ELEMENT_NAME_LEN + 1; i++)
1421     ei->description[i] = default_description[i];
1422 }
1423
1424 static void setConfigToDefaultsFromConfigList(struct LevelFileConfigInfo *conf)
1425 {
1426   int i;
1427
1428   for (i = 0; conf[i].data_type != -1; i++)
1429   {
1430     int default_value = conf[i].default_value;
1431     int data_type = conf[i].data_type;
1432     int conf_type = conf[i].conf_type;
1433     int byte_mask = conf_type & CONF_MASK_BYTES;
1434
1435     if (byte_mask == CONF_MASK_MULTI_BYTES)
1436     {
1437       int default_num_entities = conf[i].default_num_entities;
1438       int max_num_entities = conf[i].max_num_entities;
1439
1440       *(int *)(conf[i].num_entities) = default_num_entities;
1441
1442       if (data_type == TYPE_STRING)
1443       {
1444         char *default_string = conf[i].default_string;
1445         char *string = (char *)(conf[i].value);
1446
1447         strncpy(string, default_string, max_num_entities);
1448       }
1449       else if (data_type == TYPE_ELEMENT_LIST)
1450       {
1451         int *element_array = (int *)(conf[i].value);
1452         int j;
1453
1454         for (j = 0; j < max_num_entities; j++)
1455           element_array[j] = default_value;
1456       }
1457       else if (data_type == TYPE_CONTENT_LIST)
1458       {
1459         struct Content *content = (struct Content *)(conf[i].value);
1460         int c, x, y;
1461
1462         for (c = 0; c < max_num_entities; c++)
1463           for (y = 0; y < 3; y++)
1464             for (x = 0; x < 3; x++)
1465               content[c].e[x][y] = default_value;
1466       }
1467     }
1468     else        /* constant size configuration data (1, 2 or 4 bytes) */
1469     {
1470       if (data_type == TYPE_BOOLEAN)
1471         *(boolean *)(conf[i].value) = default_value;
1472       else
1473         *(int *)    (conf[i].value) = default_value;
1474     }
1475   }
1476 }
1477
1478 static void copyConfigFromConfigList(struct LevelFileConfigInfo *conf)
1479 {
1480   int i;
1481
1482   for (i = 0; conf[i].data_type != -1; i++)
1483   {
1484     int data_type = conf[i].data_type;
1485     int conf_type = conf[i].conf_type;
1486     int byte_mask = conf_type & CONF_MASK_BYTES;
1487
1488     if (byte_mask == CONF_MASK_MULTI_BYTES)
1489     {
1490       int max_num_entities = conf[i].max_num_entities;
1491
1492       if (data_type == TYPE_STRING)
1493       {
1494         char *string      = (char *)(conf[i].value);
1495         char *string_copy = (char *)(conf[i].value_copy);
1496
1497         strncpy(string_copy, string, max_num_entities);
1498       }
1499       else if (data_type == TYPE_ELEMENT_LIST)
1500       {
1501         int *element_array      = (int *)(conf[i].value);
1502         int *element_array_copy = (int *)(conf[i].value_copy);
1503         int j;
1504
1505         for (j = 0; j < max_num_entities; j++)
1506           element_array_copy[j] = element_array[j];
1507       }
1508       else if (data_type == TYPE_CONTENT_LIST)
1509       {
1510         struct Content *content      = (struct Content *)(conf[i].value);
1511         struct Content *content_copy = (struct Content *)(conf[i].value_copy);
1512         int c, x, y;
1513
1514         for (c = 0; c < max_num_entities; c++)
1515           for (y = 0; y < 3; y++)
1516             for (x = 0; x < 3; x++)
1517               content_copy[c].e[x][y] = content[c].e[x][y];
1518       }
1519     }
1520     else        /* constant size configuration data (1, 2 or 4 bytes) */
1521     {
1522       if (data_type == TYPE_BOOLEAN)
1523         *(boolean *)(conf[i].value_copy) = *(boolean *)(conf[i].value);
1524       else
1525         *(int *)    (conf[i].value_copy) = *(int *)    (conf[i].value);
1526     }
1527   }
1528 }
1529
1530 void copyElementInfo(struct ElementInfo *ei_from, struct ElementInfo *ei_to)
1531 {
1532   int i;
1533
1534   xx_ei = *ei_from;     /* copy element data into temporary buffer */
1535   yy_ei = *ei_to;       /* copy element data into temporary buffer */
1536
1537   copyConfigFromConfigList(chunk_config_CUSX_base);
1538
1539   *ei_from = xx_ei;
1540   *ei_to   = yy_ei;
1541
1542   /* ---------- reinitialize and copy change pages ---------- */
1543
1544   ei_to->num_change_pages = ei_from->num_change_pages;
1545   ei_to->current_change_page = ei_from->current_change_page;
1546
1547   setElementChangePages(ei_to, ei_to->num_change_pages);
1548
1549   for (i = 0; i < ei_to->num_change_pages; i++)
1550     ei_to->change_page[i] = ei_from->change_page[i];
1551
1552   /* ---------- copy group element info ---------- */
1553   if (ei_from->group != NULL && ei_to->group != NULL)   /* group or internal */
1554     *ei_to->group = *ei_from->group;
1555
1556   /* mark this custom element as modified */
1557   ei_to->modified_settings = TRUE;
1558 }
1559
1560 void setElementChangePages(struct ElementInfo *ei, int change_pages)
1561 {
1562   int change_page_size = sizeof(struct ElementChangeInfo);
1563
1564   ei->num_change_pages = MAX(1, change_pages);
1565
1566   ei->change_page =
1567     checked_realloc(ei->change_page, ei->num_change_pages * change_page_size);
1568
1569   if (ei->current_change_page >= ei->num_change_pages)
1570     ei->current_change_page = ei->num_change_pages - 1;
1571
1572   ei->change = &ei->change_page[ei->current_change_page];
1573 }
1574
1575 void setElementChangeInfoToDefaults(struct ElementChangeInfo *change)
1576 {
1577   xx_change = *change;          /* copy change data into temporary buffer */
1578
1579   setConfigToDefaultsFromConfigList(chunk_config_CUSX_change);
1580
1581   *change = xx_change;
1582
1583   resetEventFlags(change);
1584
1585   change->direct_action = 0;
1586   change->other_action = 0;
1587
1588   change->pre_change_function = NULL;
1589   change->change_function = NULL;
1590   change->post_change_function = NULL;
1591 }
1592
1593 static void setLevelInfoToDefaults_Level(struct LevelInfo *level)
1594 {
1595   int i, x, y;
1596
1597   li = *level;          /* copy level data into temporary buffer */
1598   setConfigToDefaultsFromConfigList(chunk_config_INFO);
1599   *level = li;          /* copy temporary buffer back to level data */
1600
1601   setLevelInfoToDefaults_EM();
1602   setLevelInfoToDefaults_SP();
1603
1604   level->native_em_level = &native_em_level;
1605   level->native_sp_level = &native_sp_level;
1606
1607   level->file_version = FILE_VERSION_ACTUAL;
1608   level->game_version = GAME_VERSION_ACTUAL;
1609
1610   level->creation_date = getCurrentDate();
1611
1612   level->encoding_16bit_field  = TRUE;
1613   level->encoding_16bit_yamyam = TRUE;
1614   level->encoding_16bit_amoeba = TRUE;
1615
1616   /* clear level name and level author string buffers */
1617   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
1618     level->name[i] = '\0';
1619   for (i = 0; i < MAX_LEVEL_AUTHOR_LEN; i++)
1620     level->author[i] = '\0';
1621
1622   /* set level name and level author to default values */
1623   strcpy(level->name, NAMELESS_LEVEL_NAME);
1624   strcpy(level->author, ANONYMOUS_NAME);
1625
1626   /* set level playfield to playable default level with player and exit */
1627   for (x = 0; x < MAX_LEV_FIELDX; x++)
1628     for (y = 0; y < MAX_LEV_FIELDY; y++)
1629       level->field[x][y] = EL_SAND;
1630
1631   level->field[0][0] = EL_PLAYER_1;
1632   level->field[STD_LEV_FIELDX - 1][STD_LEV_FIELDY - 1] = EL_EXIT_CLOSED;
1633
1634   BorderElement = EL_STEELWALL;
1635
1636   /* set all bug compatibility flags to "false" => do not emulate this bug */
1637   level->use_action_after_change_bug = FALSE;
1638
1639   if (leveldir_current)
1640   {
1641     /* try to determine better author name than 'anonymous' */
1642     if (!strEqual(leveldir_current->author, ANONYMOUS_NAME))
1643     {
1644       strncpy(level->author, leveldir_current->author, MAX_LEVEL_AUTHOR_LEN);
1645       level->author[MAX_LEVEL_AUTHOR_LEN] = '\0';
1646     }
1647     else
1648     {
1649       switch (LEVELCLASS(leveldir_current))
1650       {
1651         case LEVELCLASS_TUTORIAL:
1652           strcpy(level->author, PROGRAM_AUTHOR_STRING);
1653           break;
1654
1655         case LEVELCLASS_CONTRIB:
1656           strncpy(level->author, leveldir_current->name, MAX_LEVEL_AUTHOR_LEN);
1657           level->author[MAX_LEVEL_AUTHOR_LEN] = '\0';
1658           break;
1659
1660         case LEVELCLASS_PRIVATE:
1661           strncpy(level->author, getRealName(), MAX_LEVEL_AUTHOR_LEN);
1662           level->author[MAX_LEVEL_AUTHOR_LEN] = '\0';
1663           break;
1664
1665         default:
1666           /* keep default value */
1667           break;
1668       }
1669     }
1670   }
1671 }
1672
1673 static void setLevelInfoToDefaults_Elements(struct LevelInfo *level)
1674 {
1675   static boolean clipboard_elements_initialized = FALSE;
1676   int i;
1677
1678   InitElementPropertiesStatic();
1679
1680   li = *level;          /* copy level data into temporary buffer */
1681   setConfigToDefaultsFromConfigList(chunk_config_ELEM);
1682   *level = li;          /* copy temporary buffer back to level data */
1683
1684   for (i = 0; i < MAX_NUM_ELEMENTS; i++)
1685   {
1686     int element = i;
1687     struct ElementInfo *ei = &element_info[element];
1688
1689     /* never initialize clipboard elements after the very first time */
1690     /* (to be able to use clipboard elements between several levels) */
1691     if (IS_CLIPBOARD_ELEMENT(element) && clipboard_elements_initialized)
1692       continue;
1693
1694     if (IS_ENVELOPE(element))
1695     {
1696       int envelope_nr = element - EL_ENVELOPE_1;
1697
1698       setConfigToDefaultsFromConfigList(chunk_config_NOTE);
1699
1700       level->envelope[envelope_nr] = xx_envelope;
1701     }
1702
1703     if (IS_CUSTOM_ELEMENT(element) ||
1704         IS_GROUP_ELEMENT(element) ||
1705         IS_INTERNAL_ELEMENT(element))
1706     {
1707       xx_ei = *ei;      /* copy element data into temporary buffer */
1708
1709       setConfigToDefaultsFromConfigList(chunk_config_CUSX_base);
1710
1711       *ei = xx_ei;
1712     }
1713
1714     setElementChangePages(ei, 1);
1715     setElementChangeInfoToDefaults(ei->change);
1716
1717     if (IS_CUSTOM_ELEMENT(element) ||
1718         IS_GROUP_ELEMENT(element) ||
1719         IS_INTERNAL_ELEMENT(element))
1720     {
1721       setElementDescriptionToDefault(ei);
1722
1723       ei->modified_settings = FALSE;
1724     }
1725
1726     if (IS_CUSTOM_ELEMENT(element) ||
1727         IS_INTERNAL_ELEMENT(element))
1728     {
1729       /* internal values used in level editor */
1730
1731       ei->access_type = 0;
1732       ei->access_layer = 0;
1733       ei->access_protected = 0;
1734       ei->walk_to_action = 0;
1735       ei->smash_targets = 0;
1736       ei->deadliness = 0;
1737
1738       ei->can_explode_by_fire = FALSE;
1739       ei->can_explode_smashed = FALSE;
1740       ei->can_explode_impact = FALSE;
1741
1742       ei->current_change_page = 0;
1743     }
1744
1745     if (IS_GROUP_ELEMENT(element) ||
1746         IS_INTERNAL_ELEMENT(element))
1747     {
1748       struct ElementGroupInfo *group;
1749
1750       /* initialize memory for list of elements in group */
1751       if (ei->group == NULL)
1752         ei->group = checked_malloc(sizeof(struct ElementGroupInfo));
1753
1754       group = ei->group;
1755
1756       xx_group = *group;        /* copy group data into temporary buffer */
1757
1758       setConfigToDefaultsFromConfigList(chunk_config_GRPX);
1759
1760       *group = xx_group;
1761     }
1762   }
1763
1764   clipboard_elements_initialized = TRUE;
1765 }
1766
1767 static void setLevelInfoToDefaults(struct LevelInfo *level,
1768                                    boolean level_info_only,
1769                                    boolean reset_file_status)
1770 {
1771   setLevelInfoToDefaults_Level(level);
1772
1773   if (!level_info_only)
1774     setLevelInfoToDefaults_Elements(level);
1775
1776   if (reset_file_status)
1777   {
1778     level->no_valid_file = FALSE;
1779     level->no_level_file = FALSE;
1780   }
1781
1782   level->changed = FALSE;
1783 }
1784
1785 static void setFileInfoToDefaults(struct LevelFileInfo *level_file_info)
1786 {
1787   level_file_info->nr = 0;
1788   level_file_info->type = LEVEL_FILE_TYPE_UNKNOWN;
1789   level_file_info->packed = FALSE;
1790   level_file_info->basename = NULL;
1791   level_file_info->filename = NULL;
1792 }
1793
1794 int getMappedElement_SB(int, boolean);
1795
1796 static void ActivateLevelTemplate()
1797 {
1798   int x, y;
1799
1800   if (check_special_flags("load_xsb_to_ces"))
1801   {
1802     /* fill smaller playfields with padding "beyond border wall" elements */
1803     if (level.fieldx < level_template.fieldx ||
1804         level.fieldy < level_template.fieldy)
1805     {
1806       short field[level.fieldx][level.fieldy];
1807       int new_fieldx = MAX(level.fieldx, level_template.fieldx);
1808       int new_fieldy = MAX(level.fieldy, level_template.fieldy);
1809       int pos_fieldx = (new_fieldx - level.fieldx) / 2;
1810       int pos_fieldy = (new_fieldy - level.fieldy) / 2;
1811
1812       /* copy old playfield (which is smaller than the visible area) */
1813       for (y = 0; y < level.fieldy; y++) for (x = 0; x < level.fieldx; x++)
1814         field[x][y] = level.field[x][y];
1815
1816       /* fill new, larger playfield with "beyond border wall" elements */
1817       for (y = 0; y < new_fieldy; y++) for (x = 0; x < new_fieldx; x++)
1818         level.field[x][y] = getMappedElement_SB('_', TRUE);
1819
1820       /* copy the old playfield to the middle of the new playfield */
1821       for (y = 0; y < level.fieldy; y++) for (x = 0; x < level.fieldx; x++)
1822         level.field[pos_fieldx + x][pos_fieldy + y] = field[x][y];
1823
1824       level.fieldx = new_fieldx;
1825       level.fieldy = new_fieldy;
1826     }
1827   }
1828
1829   /* Currently there is no special action needed to activate the template
1830      data, because 'element_info' property settings overwrite the original
1831      level data, while all other variables do not change. */
1832
1833   /* Exception: 'from_level_template' elements in the original level playfield
1834      are overwritten with the corresponding elements at the same position in
1835      playfield from the level template. */
1836
1837   for (x = 0; x < level.fieldx; x++)
1838     for (y = 0; y < level.fieldy; y++)
1839       if (level.field[x][y] == EL_FROM_LEVEL_TEMPLATE)
1840         level.field[x][y] = level_template.field[x][y];
1841
1842   if (check_special_flags("load_xsb_to_ces"))
1843   {
1844     struct LevelInfo level_backup = level;
1845
1846     /* overwrite all individual level settings from template level settings */
1847     level = level_template;
1848
1849     /* restore playfield size */
1850     level.fieldx = level_backup.fieldx;
1851     level.fieldy = level_backup.fieldy;
1852
1853     /* restore playfield content */
1854     for (x = 0; x < level.fieldx; x++)
1855       for (y = 0; y < level.fieldy; y++)
1856         level.field[x][y] = level_backup.field[x][y];
1857
1858     /* restore name and author from individual level */
1859     strcpy(level.name,   level_backup.name);
1860     strcpy(level.author, level_backup.author);
1861
1862     /* restore flag "use_custom_template" */
1863     level.use_custom_template = level_backup.use_custom_template;
1864   }
1865 }
1866
1867 static char *getLevelFilenameFromBasename(char *basename)
1868 {
1869   static char *filename[2] = { NULL, NULL };
1870   int pos = (strEqual(basename, LEVELTEMPLATE_FILENAME) ? 0 : 1);
1871
1872   checked_free(filename[pos]);
1873
1874   filename[pos] = getPath2(getCurrentLevelDir(), basename);
1875
1876   return filename[pos];
1877 }
1878
1879 static int getFileTypeFromBasename(char *basename)
1880 {
1881   /* !!! ALSO SEE COMMENT IN checkForPackageFromBasename() !!! */
1882
1883   static char *filename = NULL;
1884   struct stat file_status;
1885
1886   /* ---------- try to determine file type from filename ---------- */
1887
1888   /* check for typical filename of a Supaplex level package file */
1889   if (strlen(basename) == 10 && strPrefixLower(basename, "levels.d"))
1890     return LEVEL_FILE_TYPE_SP;
1891
1892   /* check for typical filename of a Diamond Caves II level package file */
1893   if (strSuffixLower(basename, ".dc") ||
1894       strSuffixLower(basename, ".dc2"))
1895     return LEVEL_FILE_TYPE_DC;
1896
1897   /* check for typical filename of a Sokoban level package file */
1898   if (strSuffixLower(basename, ".xsb") &&
1899       strchr(basename, '%') == NULL)
1900     return LEVEL_FILE_TYPE_SB;
1901
1902   /* ---------- try to determine file type from filesize ---------- */
1903
1904   checked_free(filename);
1905   filename = getPath2(getCurrentLevelDir(), basename);
1906
1907   if (stat(filename, &file_status) == 0)
1908   {
1909     /* check for typical filesize of a Supaplex level package file */
1910     if (file_status.st_size == 170496)
1911       return LEVEL_FILE_TYPE_SP;
1912   }
1913
1914   return LEVEL_FILE_TYPE_UNKNOWN;
1915 }
1916
1917 static boolean checkForPackageFromBasename(char *basename)
1918 {
1919   /* !!! WON'T WORK ANYMORE IF getFileTypeFromBasename() ALSO DETECTS !!!
1920      !!! SINGLE LEVELS (CURRENTLY ONLY DETECTS LEVEL PACKAGES         !!! */
1921
1922   return (getFileTypeFromBasename(basename) != LEVEL_FILE_TYPE_UNKNOWN);
1923 }
1924
1925 static char *getSingleLevelBasenameExt(int nr, char *extension)
1926 {
1927   static char basename[MAX_FILENAME_LEN];
1928
1929   if (nr < 0)
1930     sprintf(basename, "%s", LEVELTEMPLATE_FILENAME);
1931   else
1932     sprintf(basename, "%03d.%s", nr, extension);
1933
1934   return basename;
1935 }
1936
1937 static char *getSingleLevelBasename(int nr)
1938 {
1939   return getSingleLevelBasenameExt(nr, LEVELFILE_EXTENSION);
1940 }
1941
1942 static char *getPackedLevelBasename(int type)
1943 {
1944   static char basename[MAX_FILENAME_LEN];
1945   char *directory = getCurrentLevelDir();
1946   Directory *dir;
1947   DirectoryEntry *dir_entry;
1948
1949   strcpy(basename, UNDEFINED_FILENAME);         /* default: undefined file */
1950
1951   if ((dir = openDirectory(directory)) == NULL)
1952   {
1953     Error(ERR_WARN, "cannot read current level directory '%s'", directory);
1954
1955     return basename;
1956   }
1957
1958   while ((dir_entry = readDirectory(dir)) != NULL)      /* loop all entries */
1959   {
1960     char *entry_basename = dir_entry->basename;
1961     int entry_type = getFileTypeFromBasename(entry_basename);
1962
1963     if (entry_type != LEVEL_FILE_TYPE_UNKNOWN)  /* found valid level package */
1964     {
1965       if (type == LEVEL_FILE_TYPE_UNKNOWN ||
1966           type == entry_type)
1967       {
1968         strcpy(basename, entry_basename);
1969
1970         break;
1971       }
1972     }
1973   }
1974
1975   closeDirectory(dir);
1976
1977   return basename;
1978 }
1979
1980 static char *getSingleLevelFilename(int nr)
1981 {
1982   return getLevelFilenameFromBasename(getSingleLevelBasename(nr));
1983 }
1984
1985 #if ENABLE_UNUSED_CODE
1986 static char *getPackedLevelFilename(int type)
1987 {
1988   return getLevelFilenameFromBasename(getPackedLevelBasename(type));
1989 }
1990 #endif
1991
1992 char *getDefaultLevelFilename(int nr)
1993 {
1994   return getSingleLevelFilename(nr);
1995 }
1996
1997 #if ENABLE_UNUSED_CODE
1998 static void setLevelFileInfo_SingleLevelFilename(struct LevelFileInfo *lfi,
1999                                                  int type)
2000 {
2001   lfi->type = type;
2002   lfi->packed = FALSE;
2003   lfi->basename = getSingleLevelBasename(lfi->nr, lfi->type);
2004   lfi->filename = getLevelFilenameFromBasename(lfi->basename);
2005 }
2006 #endif
2007
2008 static void setLevelFileInfo_FormatLevelFilename(struct LevelFileInfo *lfi,
2009                                                  int type, char *format, ...)
2010 {
2011   static char basename[MAX_FILENAME_LEN];
2012   va_list ap;
2013
2014   va_start(ap, format);
2015   vsprintf(basename, format, ap);
2016   va_end(ap);
2017
2018   lfi->type = type;
2019   lfi->packed = FALSE;
2020   lfi->basename = basename;
2021   lfi->filename = getLevelFilenameFromBasename(lfi->basename);
2022 }
2023
2024 static void setLevelFileInfo_PackedLevelFilename(struct LevelFileInfo *lfi,
2025                                                  int type)
2026 {
2027   lfi->type = type;
2028   lfi->packed = TRUE;
2029   lfi->basename = getPackedLevelBasename(lfi->type);
2030   lfi->filename = getLevelFilenameFromBasename(lfi->basename);
2031 }
2032
2033 static int getFiletypeFromID(char *filetype_id)
2034 {
2035   char *filetype_id_lower;
2036   int filetype = LEVEL_FILE_TYPE_UNKNOWN;
2037   int i;
2038
2039   if (filetype_id == NULL)
2040     return LEVEL_FILE_TYPE_UNKNOWN;
2041
2042   filetype_id_lower = getStringToLower(filetype_id);
2043
2044   for (i = 0; filetype_id_list[i].id != NULL; i++)
2045   {
2046     char *id_lower = getStringToLower(filetype_id_list[i].id);
2047     
2048     if (strEqual(filetype_id_lower, id_lower))
2049       filetype = filetype_id_list[i].filetype;
2050
2051     free(id_lower);
2052
2053     if (filetype != LEVEL_FILE_TYPE_UNKNOWN)
2054       break;
2055   }
2056
2057   free(filetype_id_lower);
2058
2059   return filetype;
2060 }
2061
2062 char *getLocalLevelTemplateFilename()
2063 {
2064   return getDefaultLevelFilename(-1);
2065 }
2066
2067 char *getGlobalLevelTemplateFilename()
2068 {
2069   /* global variable "leveldir_current" must be modified in the loop below */
2070   LevelDirTree *leveldir_current_last = leveldir_current;
2071   char *filename = NULL;
2072
2073   /* check for template level in path from current to topmost tree node */
2074
2075   while (leveldir_current != NULL)
2076   {
2077     filename = getDefaultLevelFilename(-1);
2078
2079     if (fileExists(filename))
2080       break;
2081
2082     leveldir_current = leveldir_current->node_parent;
2083   }
2084
2085   /* restore global variable "leveldir_current" modified in above loop */
2086   leveldir_current = leveldir_current_last;
2087
2088   return filename;
2089 }
2090
2091 static void determineLevelFileInfo_Filename(struct LevelFileInfo *lfi)
2092 {
2093   int nr = lfi->nr;
2094
2095   /* special case: level number is negative => check for level template file */
2096   if (nr < 0)
2097   {
2098     setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_RND,
2099                                          getSingleLevelBasename(-1));
2100
2101     /* replace local level template filename with global template filename */
2102     lfi->filename = getGlobalLevelTemplateFilename();
2103
2104     /* no fallback if template file not existing */
2105     return;
2106   }
2107
2108   /* special case: check for file name/pattern specified in "levelinfo.conf" */
2109   if (leveldir_current->level_filename != NULL)
2110   {
2111     int filetype = getFiletypeFromID(leveldir_current->level_filetype);
2112
2113     setLevelFileInfo_FormatLevelFilename(lfi, filetype,
2114                                          leveldir_current->level_filename, nr);
2115
2116     lfi->packed = checkForPackageFromBasename(leveldir_current->level_filename);
2117
2118     if (fileExists(lfi->filename))
2119       return;
2120   }
2121
2122   /* check for native Rocks'n'Diamonds level file */
2123   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_RND,
2124                                        "%03d.%s", nr, LEVELFILE_EXTENSION);
2125   if (fileExists(lfi->filename))
2126     return;
2127
2128   /* check for Emerald Mine level file (V1) */
2129   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "a%c%c",
2130                                        'a' + (nr / 10) % 26, '0' + nr % 10);
2131   if (fileExists(lfi->filename))
2132     return;
2133   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "A%c%c",
2134                                        'A' + (nr / 10) % 26, '0' + nr % 10);
2135   if (fileExists(lfi->filename))
2136     return;
2137
2138   /* check for Emerald Mine level file (V2 to V5) */
2139   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%d", nr);
2140   if (fileExists(lfi->filename))
2141     return;
2142
2143   /* check for Emerald Mine level file (V6 / single mode) */
2144   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02ds", nr);
2145   if (fileExists(lfi->filename))
2146     return;
2147   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02dS", nr);
2148   if (fileExists(lfi->filename))
2149     return;
2150
2151   /* check for Emerald Mine level file (V6 / teamwork mode) */
2152   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02dt", nr);
2153   if (fileExists(lfi->filename))
2154     return;
2155   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02dT", nr);
2156   if (fileExists(lfi->filename))
2157     return;
2158
2159   /* check for various packed level file formats */
2160   setLevelFileInfo_PackedLevelFilename(lfi, LEVEL_FILE_TYPE_UNKNOWN);
2161   if (fileExists(lfi->filename))
2162     return;
2163
2164   /* no known level file found -- use default values (and fail later) */
2165   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_RND,
2166                                        "%03d.%s", nr, LEVELFILE_EXTENSION);
2167 }
2168
2169 static void determineLevelFileInfo_Filetype(struct LevelFileInfo *lfi)
2170 {
2171   if (lfi->type == LEVEL_FILE_TYPE_UNKNOWN)
2172     lfi->type = getFileTypeFromBasename(lfi->basename);
2173 }
2174
2175 static void setLevelFileInfo(struct LevelFileInfo *level_file_info, int nr)
2176 {
2177   /* always start with reliable default values */
2178   setFileInfoToDefaults(level_file_info);
2179
2180   level_file_info->nr = nr;     /* set requested level number */
2181
2182   determineLevelFileInfo_Filename(level_file_info);
2183   determineLevelFileInfo_Filetype(level_file_info);
2184 }
2185
2186 /* ------------------------------------------------------------------------- */
2187 /* functions for loading R'n'D level                                         */
2188 /* ------------------------------------------------------------------------- */
2189
2190 int getMappedElement(int element)
2191 {
2192   /* remap some (historic, now obsolete) elements */
2193
2194   switch (element)
2195   {
2196     case EL_PLAYER_OBSOLETE:
2197       element = EL_PLAYER_1;
2198       break;
2199
2200     case EL_KEY_OBSOLETE:
2201       element = EL_KEY_1;
2202       break;
2203
2204     case EL_EM_KEY_1_FILE_OBSOLETE:
2205       element = EL_EM_KEY_1;
2206       break;
2207
2208     case EL_EM_KEY_2_FILE_OBSOLETE:
2209       element = EL_EM_KEY_2;
2210       break;
2211
2212     case EL_EM_KEY_3_FILE_OBSOLETE:
2213       element = EL_EM_KEY_3;
2214       break;
2215
2216     case EL_EM_KEY_4_FILE_OBSOLETE:
2217       element = EL_EM_KEY_4;
2218       break;
2219
2220     case EL_ENVELOPE_OBSOLETE:
2221       element = EL_ENVELOPE_1;
2222       break;
2223
2224     case EL_SP_EMPTY:
2225       element = EL_EMPTY;
2226       break;
2227
2228     default:
2229       if (element >= NUM_FILE_ELEMENTS)
2230       {
2231         Error(ERR_WARN, "invalid level element %d", element);
2232
2233         element = EL_UNKNOWN;
2234       }
2235       break;
2236   }
2237
2238   return element;
2239 }
2240
2241 int getMappedElementByVersion(int element, int game_version)
2242 {
2243   /* remap some elements due to certain game version */
2244
2245   if (game_version <= VERSION_IDENT(2,2,0,0))
2246   {
2247     /* map game font elements */
2248     element = (element == EL_CHAR('[')  ? EL_CHAR_AUMLAUT :
2249                element == EL_CHAR('\\') ? EL_CHAR_OUMLAUT :
2250                element == EL_CHAR(']')  ? EL_CHAR_UUMLAUT :
2251                element == EL_CHAR('^')  ? EL_CHAR_COPYRIGHT : element);
2252   }
2253
2254   if (game_version < VERSION_IDENT(3,0,0,0))
2255   {
2256     /* map Supaplex gravity tube elements */
2257     element = (element == EL_SP_GRAVITY_PORT_LEFT  ? EL_SP_PORT_LEFT  :
2258                element == EL_SP_GRAVITY_PORT_RIGHT ? EL_SP_PORT_RIGHT :
2259                element == EL_SP_GRAVITY_PORT_UP    ? EL_SP_PORT_UP    :
2260                element == EL_SP_GRAVITY_PORT_DOWN  ? EL_SP_PORT_DOWN  :
2261                element);
2262   }
2263
2264   return element;
2265 }
2266
2267 static int LoadLevel_VERS(File *file, int chunk_size, struct LevelInfo *level)
2268 {
2269   level->file_version = getFileVersion(file);
2270   level->game_version = getFileVersion(file);
2271
2272   return chunk_size;
2273 }
2274
2275 static int LoadLevel_DATE(File *file, int chunk_size, struct LevelInfo *level)
2276 {
2277   level->creation_date.year  = getFile16BitBE(file);
2278   level->creation_date.month = getFile8Bit(file);
2279   level->creation_date.day   = getFile8Bit(file);
2280
2281   level->creation_date.src   = DATE_SRC_LEVELFILE;
2282
2283   return chunk_size;
2284 }
2285
2286 static int LoadLevel_HEAD(File *file, int chunk_size, struct LevelInfo *level)
2287 {
2288   int initial_player_stepsize;
2289   int initial_player_gravity;
2290   int i, x, y;
2291
2292   level->fieldx = getFile8Bit(file);
2293   level->fieldy = getFile8Bit(file);
2294
2295   level->time           = getFile16BitBE(file);
2296   level->gems_needed    = getFile16BitBE(file);
2297
2298   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
2299     level->name[i] = getFile8Bit(file);
2300   level->name[MAX_LEVEL_NAME_LEN] = 0;
2301
2302   for (i = 0; i < LEVEL_SCORE_ELEMENTS; i++)
2303     level->score[i] = getFile8Bit(file);
2304
2305   level->num_yamyam_contents = STD_ELEMENT_CONTENTS;
2306   for (i = 0; i < STD_ELEMENT_CONTENTS; i++)
2307     for (y = 0; y < 3; y++)
2308       for (x = 0; x < 3; x++)
2309         level->yamyam_content[i].e[x][y] = getMappedElement(getFile8Bit(file));
2310
2311   level->amoeba_speed           = getFile8Bit(file);
2312   level->time_magic_wall        = getFile8Bit(file);
2313   level->time_wheel             = getFile8Bit(file);
2314   level->amoeba_content         = getMappedElement(getFile8Bit(file));
2315
2316   initial_player_stepsize       = (getFile8Bit(file) == 1 ? STEPSIZE_FAST :
2317                                    STEPSIZE_NORMAL);
2318
2319   for (i = 0; i < MAX_PLAYERS; i++)
2320     level->initial_player_stepsize[i] = initial_player_stepsize;
2321
2322   initial_player_gravity        = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2323
2324   for (i = 0; i < MAX_PLAYERS; i++)
2325     level->initial_player_gravity[i] = initial_player_gravity;
2326
2327   level->encoding_16bit_field   = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2328   level->em_slippery_gems       = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2329
2330   level->use_custom_template    = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2331
2332   level->block_last_field       = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2333   level->sp_block_last_field    = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2334   level->can_move_into_acid_bits = getFile32BitBE(file);
2335   level->dont_collide_with_bits = getFile8Bit(file);
2336
2337   level->use_spring_bug         = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2338   level->use_step_counter       = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2339
2340   level->instant_relocation     = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2341   level->can_pass_to_walkable   = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2342   level->grow_into_diggable     = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2343
2344   level->game_engine_type       = getFile8Bit(file);
2345
2346   ReadUnusedBytesFromFile(file, LEVEL_CHUNK_HEAD_UNUSED);
2347
2348   return chunk_size;
2349 }
2350
2351 static int LoadLevel_NAME(File *file, int chunk_size, struct LevelInfo *level)
2352 {
2353   int i;
2354
2355   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
2356     level->name[i] = getFile8Bit(file);
2357   level->name[MAX_LEVEL_NAME_LEN] = 0;
2358
2359   return chunk_size;
2360 }
2361
2362 static int LoadLevel_AUTH(File *file, int chunk_size, struct LevelInfo *level)
2363 {
2364   int i;
2365
2366   for (i = 0; i < MAX_LEVEL_AUTHOR_LEN; i++)
2367     level->author[i] = getFile8Bit(file);
2368   level->author[MAX_LEVEL_AUTHOR_LEN] = 0;
2369
2370   return chunk_size;
2371 }
2372
2373 static int LoadLevel_BODY(File *file, int chunk_size, struct LevelInfo *level)
2374 {
2375   int x, y;
2376   int chunk_size_expected = level->fieldx * level->fieldy;
2377
2378   /* Note: "chunk_size" was wrong before version 2.0 when elements are
2379      stored with 16-bit encoding (and should be twice as big then).
2380      Even worse, playfield data was stored 16-bit when only yamyam content
2381      contained 16-bit elements and vice versa. */
2382
2383   if (level->encoding_16bit_field && level->file_version >= FILE_VERSION_2_0)
2384     chunk_size_expected *= 2;
2385
2386   if (chunk_size_expected != chunk_size)
2387   {
2388     ReadUnusedBytesFromFile(file, chunk_size);
2389     return chunk_size_expected;
2390   }
2391
2392   for (y = 0; y < level->fieldy; y++)
2393     for (x = 0; x < level->fieldx; x++)
2394       level->field[x][y] =
2395         getMappedElement(level->encoding_16bit_field ? getFile16BitBE(file) :
2396                          getFile8Bit(file));
2397   return chunk_size;
2398 }
2399
2400 static int LoadLevel_CONT(File *file, int chunk_size, struct LevelInfo *level)
2401 {
2402   int i, x, y;
2403   int header_size = 4;
2404   int content_size = MAX_ELEMENT_CONTENTS * 3 * 3;
2405   int chunk_size_expected = header_size + content_size;
2406
2407   /* Note: "chunk_size" was wrong before version 2.0 when elements are
2408      stored with 16-bit encoding (and should be twice as big then).
2409      Even worse, playfield data was stored 16-bit when only yamyam content
2410      contained 16-bit elements and vice versa. */
2411
2412   if (level->encoding_16bit_field && level->file_version >= FILE_VERSION_2_0)
2413     chunk_size_expected += content_size;
2414
2415   if (chunk_size_expected != chunk_size)
2416   {
2417     ReadUnusedBytesFromFile(file, chunk_size);
2418     return chunk_size_expected;
2419   }
2420
2421   getFile8Bit(file);
2422   level->num_yamyam_contents = getFile8Bit(file);
2423   getFile8Bit(file);
2424   getFile8Bit(file);
2425
2426   /* correct invalid number of content fields -- should never happen */
2427   if (level->num_yamyam_contents < 1 ||
2428       level->num_yamyam_contents > MAX_ELEMENT_CONTENTS)
2429     level->num_yamyam_contents = STD_ELEMENT_CONTENTS;
2430
2431   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
2432     for (y = 0; y < 3; y++)
2433       for (x = 0; x < 3; x++)
2434         level->yamyam_content[i].e[x][y] =
2435           getMappedElement(level->encoding_16bit_field ?
2436                            getFile16BitBE(file) : getFile8Bit(file));
2437   return chunk_size;
2438 }
2439
2440 static int LoadLevel_CNT2(File *file, int chunk_size, struct LevelInfo *level)
2441 {
2442   int i, x, y;
2443   int element;
2444   int num_contents;
2445   int content_array[MAX_ELEMENT_CONTENTS][3][3];
2446
2447   element = getMappedElement(getFile16BitBE(file));
2448   num_contents = getFile8Bit(file);
2449
2450   getFile8Bit(file);    /* content x size (unused) */
2451   getFile8Bit(file);    /* content y size (unused) */
2452
2453   ReadUnusedBytesFromFile(file, LEVEL_CHUNK_CNT2_UNUSED);
2454
2455   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
2456     for (y = 0; y < 3; y++)
2457       for (x = 0; x < 3; x++)
2458         content_array[i][x][y] = getMappedElement(getFile16BitBE(file));
2459
2460   /* correct invalid number of content fields -- should never happen */
2461   if (num_contents < 1 || num_contents > MAX_ELEMENT_CONTENTS)
2462     num_contents = STD_ELEMENT_CONTENTS;
2463
2464   if (element == EL_YAMYAM)
2465   {
2466     level->num_yamyam_contents = num_contents;
2467
2468     for (i = 0; i < num_contents; i++)
2469       for (y = 0; y < 3; y++)
2470         for (x = 0; x < 3; x++)
2471           level->yamyam_content[i].e[x][y] = content_array[i][x][y];
2472   }
2473   else if (element == EL_BD_AMOEBA)
2474   {
2475     level->amoeba_content = content_array[0][0][0];
2476   }
2477   else
2478   {
2479     Error(ERR_WARN, "cannot load content for element '%d'", element);
2480   }
2481
2482   return chunk_size;
2483 }
2484
2485 static int LoadLevel_CNT3(File *file, int chunk_size, struct LevelInfo *level)
2486 {
2487   int i;
2488   int element;
2489   int envelope_nr;
2490   int envelope_len;
2491   int chunk_size_expected;
2492
2493   element = getMappedElement(getFile16BitBE(file));
2494   if (!IS_ENVELOPE(element))
2495     element = EL_ENVELOPE_1;
2496
2497   envelope_nr = element - EL_ENVELOPE_1;
2498
2499   envelope_len = getFile16BitBE(file);
2500
2501   level->envelope[envelope_nr].xsize = getFile8Bit(file);
2502   level->envelope[envelope_nr].ysize = getFile8Bit(file);
2503
2504   ReadUnusedBytesFromFile(file, LEVEL_CHUNK_CNT3_UNUSED);
2505
2506   chunk_size_expected = LEVEL_CHUNK_CNT3_SIZE(envelope_len);
2507   if (chunk_size_expected != chunk_size)
2508   {
2509     ReadUnusedBytesFromFile(file, chunk_size - LEVEL_CHUNK_CNT3_HEADER);
2510     return chunk_size_expected;
2511   }
2512
2513   for (i = 0; i < envelope_len; i++)
2514     level->envelope[envelope_nr].text[i] = getFile8Bit(file);
2515
2516   return chunk_size;
2517 }
2518
2519 static int LoadLevel_CUS1(File *file, int chunk_size, struct LevelInfo *level)
2520 {
2521   int num_changed_custom_elements = getFile16BitBE(file);
2522   int chunk_size_expected = 2 + num_changed_custom_elements * 6;
2523   int i;
2524
2525   if (chunk_size_expected != chunk_size)
2526   {
2527     ReadUnusedBytesFromFile(file, chunk_size - 2);
2528     return chunk_size_expected;
2529   }
2530
2531   for (i = 0; i < num_changed_custom_elements; i++)
2532   {
2533     int element = getMappedElement(getFile16BitBE(file));
2534     int properties = getFile32BitBE(file);
2535
2536     if (IS_CUSTOM_ELEMENT(element))
2537       element_info[element].properties[EP_BITFIELD_BASE_NR] = properties;
2538     else
2539       Error(ERR_WARN, "invalid custom element number %d", element);
2540
2541     /* older game versions that wrote level files with CUS1 chunks used
2542        different default push delay values (not yet stored in level file) */
2543     element_info[element].push_delay_fixed = 2;
2544     element_info[element].push_delay_random = 8;
2545   }
2546
2547   return chunk_size;
2548 }
2549
2550 static int LoadLevel_CUS2(File *file, int chunk_size, struct LevelInfo *level)
2551 {
2552   int num_changed_custom_elements = getFile16BitBE(file);
2553   int chunk_size_expected = 2 + num_changed_custom_elements * 4;
2554   int i;
2555
2556   if (chunk_size_expected != chunk_size)
2557   {
2558     ReadUnusedBytesFromFile(file, chunk_size - 2);
2559     return chunk_size_expected;
2560   }
2561
2562   for (i = 0; i < num_changed_custom_elements; i++)
2563   {
2564     int element = getMappedElement(getFile16BitBE(file));
2565     int custom_target_element = getMappedElement(getFile16BitBE(file));
2566
2567     if (IS_CUSTOM_ELEMENT(element))
2568       element_info[element].change->target_element = custom_target_element;
2569     else
2570       Error(ERR_WARN, "invalid custom element number %d", element);
2571   }
2572
2573   return chunk_size;
2574 }
2575
2576 static int LoadLevel_CUS3(File *file, int chunk_size, struct LevelInfo *level)
2577 {
2578   int num_changed_custom_elements = getFile16BitBE(file);
2579   int chunk_size_expected = LEVEL_CHUNK_CUS3_SIZE(num_changed_custom_elements);
2580   int i, j, x, y;
2581
2582   if (chunk_size_expected != chunk_size)
2583   {
2584     ReadUnusedBytesFromFile(file, chunk_size - 2);
2585     return chunk_size_expected;
2586   }
2587
2588   for (i = 0; i < num_changed_custom_elements; i++)
2589   {
2590     int element = getMappedElement(getFile16BitBE(file));
2591     struct ElementInfo *ei = &element_info[element];
2592     unsigned int event_bits;
2593
2594     if (!IS_CUSTOM_ELEMENT(element))
2595     {
2596       Error(ERR_WARN, "invalid custom element number %d", element);
2597
2598       element = EL_INTERNAL_DUMMY;
2599     }
2600
2601     for (j = 0; j < MAX_ELEMENT_NAME_LEN; j++)
2602       ei->description[j] = getFile8Bit(file);
2603     ei->description[MAX_ELEMENT_NAME_LEN] = 0;
2604
2605     ei->properties[EP_BITFIELD_BASE_NR] = getFile32BitBE(file);
2606
2607     /* some free bytes for future properties and padding */
2608     ReadUnusedBytesFromFile(file, 7);
2609
2610     ei->use_gfx_element = getFile8Bit(file);
2611     ei->gfx_element_initial = getMappedElement(getFile16BitBE(file));
2612
2613     ei->collect_score_initial = getFile8Bit(file);
2614     ei->collect_count_initial = getFile8Bit(file);
2615
2616     ei->push_delay_fixed = getFile16BitBE(file);
2617     ei->push_delay_random = getFile16BitBE(file);
2618     ei->move_delay_fixed = getFile16BitBE(file);
2619     ei->move_delay_random = getFile16BitBE(file);
2620
2621     ei->move_pattern = getFile16BitBE(file);
2622     ei->move_direction_initial = getFile8Bit(file);
2623     ei->move_stepsize = getFile8Bit(file);
2624
2625     for (y = 0; y < 3; y++)
2626       for (x = 0; x < 3; x++)
2627         ei->content.e[x][y] = getMappedElement(getFile16BitBE(file));
2628
2629     event_bits = getFile32BitBE(file);
2630     for (j = 0; j < NUM_CHANGE_EVENTS; j++)
2631       if (event_bits & (1 << j))
2632         ei->change->has_event[j] = TRUE;
2633
2634     ei->change->target_element = getMappedElement(getFile16BitBE(file));
2635
2636     ei->change->delay_fixed = getFile16BitBE(file);
2637     ei->change->delay_random = getFile16BitBE(file);
2638     ei->change->delay_frames = getFile16BitBE(file);
2639
2640     ei->change->initial_trigger_element= getMappedElement(getFile16BitBE(file));
2641
2642     ei->change->explode = getFile8Bit(file);
2643     ei->change->use_target_content = getFile8Bit(file);
2644     ei->change->only_if_complete = getFile8Bit(file);
2645     ei->change->use_random_replace = getFile8Bit(file);
2646
2647     ei->change->random_percentage = getFile8Bit(file);
2648     ei->change->replace_when = getFile8Bit(file);
2649
2650     for (y = 0; y < 3; y++)
2651       for (x = 0; x < 3; x++)
2652         ei->change->target_content.e[x][y] =
2653           getMappedElement(getFile16BitBE(file));
2654
2655     ei->slippery_type = getFile8Bit(file);
2656
2657     /* some free bytes for future properties and padding */
2658     ReadUnusedBytesFromFile(file, LEVEL_CPART_CUS3_UNUSED);
2659
2660     /* mark that this custom element has been modified */
2661     ei->modified_settings = TRUE;
2662   }
2663
2664   return chunk_size;
2665 }
2666
2667 static int LoadLevel_CUS4(File *file, int chunk_size, struct LevelInfo *level)
2668 {
2669   struct ElementInfo *ei;
2670   int chunk_size_expected;
2671   int element;
2672   int i, j, x, y;
2673
2674   /* ---------- custom element base property values (96 bytes) ------------- */
2675
2676   element = getMappedElement(getFile16BitBE(file));
2677
2678   if (!IS_CUSTOM_ELEMENT(element))
2679   {
2680     Error(ERR_WARN, "invalid custom element number %d", element);
2681
2682     ReadUnusedBytesFromFile(file, chunk_size - 2);
2683     return chunk_size;
2684   }
2685
2686   ei = &element_info[element];
2687
2688   for (i = 0; i < MAX_ELEMENT_NAME_LEN; i++)
2689     ei->description[i] = getFile8Bit(file);
2690   ei->description[MAX_ELEMENT_NAME_LEN] = 0;
2691
2692   ei->properties[EP_BITFIELD_BASE_NR] = getFile32BitBE(file);
2693
2694   ReadUnusedBytesFromFile(file, 4);     /* reserved for more base properties */
2695
2696   ei->num_change_pages = getFile8Bit(file);
2697
2698   chunk_size_expected = LEVEL_CHUNK_CUS4_SIZE(ei->num_change_pages);
2699   if (chunk_size_expected != chunk_size)
2700   {
2701     ReadUnusedBytesFromFile(file, chunk_size - 43);
2702     return chunk_size_expected;
2703   }
2704
2705   ei->ce_value_fixed_initial = getFile16BitBE(file);
2706   ei->ce_value_random_initial = getFile16BitBE(file);
2707   ei->use_last_ce_value = getFile8Bit(file);
2708
2709   ei->use_gfx_element = getFile8Bit(file);
2710   ei->gfx_element_initial = getMappedElement(getFile16BitBE(file));
2711
2712   ei->collect_score_initial = getFile8Bit(file);
2713   ei->collect_count_initial = getFile8Bit(file);
2714
2715   ei->drop_delay_fixed = getFile8Bit(file);
2716   ei->push_delay_fixed = getFile8Bit(file);
2717   ei->drop_delay_random = getFile8Bit(file);
2718   ei->push_delay_random = getFile8Bit(file);
2719   ei->move_delay_fixed = getFile16BitBE(file);
2720   ei->move_delay_random = getFile16BitBE(file);
2721
2722   /* bits 0 - 15 of "move_pattern" ... */
2723   ei->move_pattern = getFile16BitBE(file);
2724   ei->move_direction_initial = getFile8Bit(file);
2725   ei->move_stepsize = getFile8Bit(file);
2726
2727   ei->slippery_type = getFile8Bit(file);
2728
2729   for (y = 0; y < 3; y++)
2730     for (x = 0; x < 3; x++)
2731       ei->content.e[x][y] = getMappedElement(getFile16BitBE(file));
2732
2733   ei->move_enter_element = getMappedElement(getFile16BitBE(file));
2734   ei->move_leave_element = getMappedElement(getFile16BitBE(file));
2735   ei->move_leave_type = getFile8Bit(file);
2736
2737   /* ... bits 16 - 31 of "move_pattern" (not nice, but downward compatible) */
2738   ei->move_pattern |= (getFile16BitBE(file) << 16);
2739
2740   ei->access_direction = getFile8Bit(file);
2741
2742   ei->explosion_delay = getFile8Bit(file);
2743   ei->ignition_delay = getFile8Bit(file);
2744   ei->explosion_type = getFile8Bit(file);
2745
2746   /* some free bytes for future custom property values and padding */
2747   ReadUnusedBytesFromFile(file, 1);
2748
2749   /* ---------- change page property values (48 bytes) --------------------- */
2750
2751   setElementChangePages(ei, ei->num_change_pages);
2752
2753   for (i = 0; i < ei->num_change_pages; i++)
2754   {
2755     struct ElementChangeInfo *change = &ei->change_page[i];
2756     unsigned int event_bits;
2757
2758     /* always start with reliable default values */
2759     setElementChangeInfoToDefaults(change);
2760
2761     /* bits 0 - 31 of "has_event[]" ... */
2762     event_bits = getFile32BitBE(file);
2763     for (j = 0; j < MIN(NUM_CHANGE_EVENTS, 32); j++)
2764       if (event_bits & (1 << j))
2765         change->has_event[j] = TRUE;
2766
2767     change->target_element = getMappedElement(getFile16BitBE(file));
2768
2769     change->delay_fixed = getFile16BitBE(file);
2770     change->delay_random = getFile16BitBE(file);
2771     change->delay_frames = getFile16BitBE(file);
2772
2773     change->initial_trigger_element = getMappedElement(getFile16BitBE(file));
2774
2775     change->explode = getFile8Bit(file);
2776     change->use_target_content = getFile8Bit(file);
2777     change->only_if_complete = getFile8Bit(file);
2778     change->use_random_replace = getFile8Bit(file);
2779
2780     change->random_percentage = getFile8Bit(file);
2781     change->replace_when = getFile8Bit(file);
2782
2783     for (y = 0; y < 3; y++)
2784       for (x = 0; x < 3; x++)
2785         change->target_content.e[x][y]= getMappedElement(getFile16BitBE(file));
2786
2787     change->can_change = getFile8Bit(file);
2788
2789     change->trigger_side = getFile8Bit(file);
2790
2791     change->trigger_player = getFile8Bit(file);
2792     change->trigger_page = getFile8Bit(file);
2793
2794     change->trigger_page = (change->trigger_page == CH_PAGE_ANY_FILE ?
2795                             CH_PAGE_ANY : (1 << change->trigger_page));
2796
2797     change->has_action = getFile8Bit(file);
2798     change->action_type = getFile8Bit(file);
2799     change->action_mode = getFile8Bit(file);
2800     change->action_arg = getFile16BitBE(file);
2801
2802     /* ... bits 32 - 39 of "has_event[]" (not nice, but downward compatible) */
2803     event_bits = getFile8Bit(file);
2804     for (j = 32; j < NUM_CHANGE_EVENTS; j++)
2805       if (event_bits & (1 << (j - 32)))
2806         change->has_event[j] = TRUE;
2807   }
2808
2809   /* mark this custom element as modified */
2810   ei->modified_settings = TRUE;
2811
2812   return chunk_size;
2813 }
2814
2815 static int LoadLevel_GRP1(File *file, int chunk_size, struct LevelInfo *level)
2816 {
2817   struct ElementInfo *ei;
2818   struct ElementGroupInfo *group;
2819   int element;
2820   int i;
2821
2822   element = getMappedElement(getFile16BitBE(file));
2823
2824   if (!IS_GROUP_ELEMENT(element))
2825   {
2826     Error(ERR_WARN, "invalid group element number %d", element);
2827
2828     ReadUnusedBytesFromFile(file, chunk_size - 2);
2829     return chunk_size;
2830   }
2831
2832   ei = &element_info[element];
2833
2834   for (i = 0; i < MAX_ELEMENT_NAME_LEN; i++)
2835     ei->description[i] = getFile8Bit(file);
2836   ei->description[MAX_ELEMENT_NAME_LEN] = 0;
2837
2838   group = element_info[element].group;
2839
2840   group->num_elements = getFile8Bit(file);
2841
2842   ei->use_gfx_element = getFile8Bit(file);
2843   ei->gfx_element_initial = getMappedElement(getFile16BitBE(file));
2844
2845   group->choice_mode = getFile8Bit(file);
2846
2847   /* some free bytes for future values and padding */
2848   ReadUnusedBytesFromFile(file, 3);
2849
2850   for (i = 0; i < MAX_ELEMENTS_IN_GROUP; i++)
2851     group->element[i] = getMappedElement(getFile16BitBE(file));
2852
2853   /* mark this group element as modified */
2854   element_info[element].modified_settings = TRUE;
2855
2856   return chunk_size;
2857 }
2858
2859 static int LoadLevel_MicroChunk(File *file, struct LevelFileConfigInfo *conf,
2860                                 int element, int real_element)
2861 {
2862   int micro_chunk_size = 0;
2863   int conf_type = getFile8Bit(file);
2864   int byte_mask = conf_type & CONF_MASK_BYTES;
2865   boolean element_found = FALSE;
2866   int i;
2867
2868   micro_chunk_size += 1;
2869
2870   if (byte_mask == CONF_MASK_MULTI_BYTES)
2871   {
2872     int num_bytes = getFile16BitBE(file);
2873     byte *buffer = checked_malloc(num_bytes);
2874
2875     ReadBytesFromFile(file, buffer, num_bytes);
2876
2877     for (i = 0; conf[i].data_type != -1; i++)
2878     {
2879       if (conf[i].element == element &&
2880           conf[i].conf_type == conf_type)
2881       {
2882         int data_type = conf[i].data_type;
2883         int num_entities = num_bytes / CONF_ENTITY_NUM_BYTES(data_type);
2884         int max_num_entities = conf[i].max_num_entities;
2885
2886         if (num_entities > max_num_entities)
2887         {
2888           Error(ERR_WARN,
2889                 "truncating number of entities for element %d from %d to %d",
2890                 element, num_entities, max_num_entities);
2891
2892           num_entities = max_num_entities;
2893         }
2894
2895         if (num_entities == 0 && (data_type == TYPE_ELEMENT_LIST ||
2896                                   data_type == TYPE_CONTENT_LIST))
2897         {
2898           /* for element and content lists, zero entities are not allowed */
2899           Error(ERR_WARN, "found empty list of entities for element %d",
2900                 element);
2901
2902           /* do not set "num_entities" here to prevent reading behind buffer */
2903
2904           *(int *)(conf[i].num_entities) = 1;   /* at least one is required */
2905         }
2906         else
2907         {
2908           *(int *)(conf[i].num_entities) = num_entities;
2909         }
2910
2911         element_found = TRUE;
2912
2913         if (data_type == TYPE_STRING)
2914         {
2915           char *string = (char *)(conf[i].value);
2916           int j;
2917
2918           for (j = 0; j < max_num_entities; j++)
2919             string[j] = (j < num_entities ? buffer[j] : '\0');
2920         }
2921         else if (data_type == TYPE_ELEMENT_LIST)
2922         {
2923           int *element_array = (int *)(conf[i].value);
2924           int j;
2925
2926           for (j = 0; j < num_entities; j++)
2927             element_array[j] =
2928               getMappedElement(CONF_ELEMENTS_ELEMENT(buffer, j));
2929         }
2930         else if (data_type == TYPE_CONTENT_LIST)
2931         {
2932           struct Content *content= (struct Content *)(conf[i].value);
2933           int c, x, y;
2934
2935           for (c = 0; c < num_entities; c++)
2936             for (y = 0; y < 3; y++)
2937               for (x = 0; x < 3; x++)
2938                 content[c].e[x][y] =
2939                   getMappedElement(CONF_CONTENTS_ELEMENT(buffer, c, x, y));
2940         }
2941         else
2942           element_found = FALSE;
2943
2944         break;
2945       }
2946     }
2947
2948     checked_free(buffer);
2949
2950     micro_chunk_size += 2 + num_bytes;
2951   }
2952   else          /* constant size configuration data (1, 2 or 4 bytes) */
2953   {
2954     int value = (byte_mask == CONF_MASK_1_BYTE ? getFile8Bit   (file) :
2955                  byte_mask == CONF_MASK_2_BYTE ? getFile16BitBE(file) :
2956                  byte_mask == CONF_MASK_4_BYTE ? getFile32BitBE(file) : 0);
2957
2958     for (i = 0; conf[i].data_type != -1; i++)
2959     {
2960       if (conf[i].element == element &&
2961           conf[i].conf_type == conf_type)
2962       {
2963         int data_type = conf[i].data_type;
2964
2965         if (data_type == TYPE_ELEMENT)
2966           value = getMappedElement(value);
2967
2968         if (data_type == TYPE_BOOLEAN)
2969           *(boolean *)(conf[i].value) = value;
2970         else
2971           *(int *)    (conf[i].value) = value;
2972
2973         element_found = TRUE;
2974
2975         break;
2976       }
2977     }
2978
2979     micro_chunk_size += CONF_VALUE_NUM_BYTES(byte_mask);
2980   }
2981
2982   if (!element_found)
2983   {
2984     char *error_conf_chunk_bytes =
2985       (byte_mask == CONF_MASK_1_BYTE ? "CONF_VALUE_8_BIT" :
2986        byte_mask == CONF_MASK_2_BYTE ? "CONF_VALUE_16_BIT" :
2987        byte_mask == CONF_MASK_4_BYTE ? "CONF_VALUE_32_BIT" :"CONF_VALUE_BYTES");
2988     int error_conf_chunk_token = conf_type & CONF_MASK_TOKEN;
2989     int error_element = real_element;
2990
2991     Error(ERR_WARN, "cannot load micro chunk '%s(%d)' value for element %d ['%s']",
2992           error_conf_chunk_bytes, error_conf_chunk_token,
2993           error_element, EL_NAME(error_element));
2994   }
2995
2996   return micro_chunk_size;
2997 }
2998
2999 static int LoadLevel_INFO(File *file, int chunk_size, struct LevelInfo *level)
3000 {
3001   int real_chunk_size = 0;
3002
3003   li = *level;          /* copy level data into temporary buffer */
3004
3005   while (!checkEndOfFile(file))
3006   {
3007     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_INFO, -1, -1);
3008
3009     if (real_chunk_size >= chunk_size)
3010       break;
3011   }
3012
3013   *level = li;          /* copy temporary buffer back to level data */
3014
3015   return real_chunk_size;
3016 }
3017
3018 static int LoadLevel_CONF(File *file, int chunk_size, struct LevelInfo *level)
3019 {
3020   int real_chunk_size = 0;
3021
3022   li = *level;          /* copy level data into temporary buffer */
3023
3024   while (!checkEndOfFile(file))
3025   {
3026     int element = getMappedElement(getFile16BitBE(file));
3027
3028     real_chunk_size += 2;
3029     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_CONF,
3030                                             element, element);
3031     if (real_chunk_size >= chunk_size)
3032       break;
3033   }
3034
3035   *level = li;          /* copy temporary buffer back to level data */
3036
3037   return real_chunk_size;
3038 }
3039
3040 static int LoadLevel_ELEM(File *file, int chunk_size, struct LevelInfo *level)
3041 {
3042   int real_chunk_size = 0;
3043
3044   li = *level;          /* copy level data into temporary buffer */
3045
3046   while (!checkEndOfFile(file))
3047   {
3048     int element = getMappedElement(getFile16BitBE(file));
3049
3050     real_chunk_size += 2;
3051     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_ELEM,
3052                                             element, element);
3053     if (real_chunk_size >= chunk_size)
3054       break;
3055   }
3056
3057   *level = li;          /* copy temporary buffer back to level data */
3058
3059   return real_chunk_size;
3060 }
3061
3062 static int LoadLevel_NOTE(File *file, int chunk_size, struct LevelInfo *level)
3063 {
3064   int element = getMappedElement(getFile16BitBE(file));
3065   int envelope_nr = element - EL_ENVELOPE_1;
3066   int real_chunk_size = 2;
3067
3068   xx_envelope = level->envelope[envelope_nr];   /* copy into temporary buffer */
3069
3070   while (!checkEndOfFile(file))
3071   {
3072     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_NOTE,
3073                                             -1, element);
3074
3075     if (real_chunk_size >= chunk_size)
3076       break;
3077   }
3078
3079   level->envelope[envelope_nr] = xx_envelope;   /* copy from temporary buffer */
3080
3081   return real_chunk_size;
3082 }
3083
3084 static int LoadLevel_CUSX(File *file, int chunk_size, struct LevelInfo *level)
3085 {
3086   int element = getMappedElement(getFile16BitBE(file));
3087   int real_chunk_size = 2;
3088   struct ElementInfo *ei = &element_info[element];
3089   int i;
3090
3091   xx_ei = *ei;          /* copy element data into temporary buffer */
3092
3093   xx_ei.num_change_pages = -1;
3094
3095   while (!checkEndOfFile(file))
3096   {
3097     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_CUSX_base,
3098                                             -1, element);
3099     if (xx_ei.num_change_pages != -1)
3100       break;
3101
3102     if (real_chunk_size >= chunk_size)
3103       break;
3104   }
3105
3106   *ei = xx_ei;
3107
3108   if (ei->num_change_pages == -1)
3109   {
3110     Error(ERR_WARN, "LoadLevel_CUSX(): missing 'num_change_pages' for '%s'",
3111           EL_NAME(element));
3112
3113     ei->num_change_pages = 1;
3114
3115     setElementChangePages(ei, 1);
3116     setElementChangeInfoToDefaults(ei->change);
3117
3118     return real_chunk_size;
3119   }
3120
3121   /* initialize number of change pages stored for this custom element */
3122   setElementChangePages(ei, ei->num_change_pages);
3123   for (i = 0; i < ei->num_change_pages; i++)
3124     setElementChangeInfoToDefaults(&ei->change_page[i]);
3125
3126   /* start with reading properties for the first change page */
3127   xx_current_change_page = 0;
3128
3129   while (!checkEndOfFile(file))
3130   {
3131     struct ElementChangeInfo *change = &ei->change_page[xx_current_change_page];
3132
3133     xx_change = *change;        /* copy change data into temporary buffer */
3134
3135     resetEventBits();           /* reset bits; change page might have changed */
3136
3137     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_CUSX_change,
3138                                             -1, element);
3139
3140     *change = xx_change;
3141
3142     setEventFlagsFromEventBits(change);
3143
3144     if (real_chunk_size >= chunk_size)
3145       break;
3146   }
3147
3148   return real_chunk_size;
3149 }
3150
3151 static int LoadLevel_GRPX(File *file, int chunk_size, struct LevelInfo *level)
3152 {
3153   int element = getMappedElement(getFile16BitBE(file));
3154   int real_chunk_size = 2;
3155   struct ElementInfo *ei = &element_info[element];
3156   struct ElementGroupInfo *group = ei->group;
3157
3158   xx_ei = *ei;          /* copy element data into temporary buffer */
3159   xx_group = *group;    /* copy group data into temporary buffer */
3160
3161   while (!checkEndOfFile(file))
3162   {
3163     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_GRPX,
3164                                             -1, element);
3165
3166     if (real_chunk_size >= chunk_size)
3167       break;
3168   }
3169
3170   *ei = xx_ei;
3171   *group = xx_group;
3172
3173   return real_chunk_size;
3174 }
3175
3176 static void LoadLevelFromFileInfo_RND(struct LevelInfo *level,
3177                                       struct LevelFileInfo *level_file_info,
3178                                       boolean level_info_only)
3179 {
3180   char *filename = level_file_info->filename;
3181   char cookie[MAX_LINE_LEN];
3182   char chunk_name[CHUNK_ID_LEN + 1];
3183   int chunk_size;
3184   File *file;
3185
3186   if (!(file = openFile(filename, MODE_READ)))
3187   {
3188     level->no_valid_file = TRUE;
3189     level->no_level_file = TRUE;
3190
3191     if (level_info_only)
3192       return;
3193
3194     Error(ERR_WARN, "cannot read level '%s' -- using empty level", filename);
3195
3196     /* if level file not found, try to initialize level data from template */
3197     filename = getGlobalLevelTemplateFilename();
3198
3199     if (!(file = openFile(filename, MODE_READ)))
3200       return;
3201
3202     /* default: for empty levels, use level template for custom elements */
3203     level->use_custom_template = TRUE;
3204
3205     level->no_valid_file = FALSE;
3206   }
3207
3208   getFileChunkBE(file, chunk_name, NULL);
3209   if (strEqual(chunk_name, "RND1"))
3210   {
3211     getFile32BitBE(file);               /* not used */
3212
3213     getFileChunkBE(file, chunk_name, NULL);
3214     if (!strEqual(chunk_name, "CAVE"))
3215     {
3216       level->no_valid_file = TRUE;
3217
3218       Error(ERR_WARN, "unknown format of level file '%s'", filename);
3219
3220       closeFile(file);
3221
3222       return;
3223     }
3224   }
3225   else  /* check for pre-2.0 file format with cookie string */
3226   {
3227     strcpy(cookie, chunk_name);
3228     if (getStringFromFile(file, &cookie[4], MAX_LINE_LEN - 4) == NULL)
3229       cookie[4] = '\0';
3230     if (strlen(cookie) > 0 && cookie[strlen(cookie) - 1] == '\n')
3231       cookie[strlen(cookie) - 1] = '\0';
3232
3233     if (!checkCookieString(cookie, LEVEL_COOKIE_TMPL))
3234     {
3235       level->no_valid_file = TRUE;
3236
3237       Error(ERR_WARN, "unknown format of level file '%s'", filename);
3238
3239       closeFile(file);
3240
3241       return;
3242     }
3243
3244     if ((level->file_version = getFileVersionFromCookieString(cookie)) == -1)
3245     {
3246       level->no_valid_file = TRUE;
3247
3248       Error(ERR_WARN, "unsupported version of level file '%s'", filename);
3249
3250       closeFile(file);
3251
3252       return;
3253     }
3254
3255     /* pre-2.0 level files have no game version, so use file version here */
3256     level->game_version = level->file_version;
3257   }
3258
3259   if (level->file_version < FILE_VERSION_1_2)
3260   {
3261     /* level files from versions before 1.2.0 without chunk structure */
3262     LoadLevel_HEAD(file, LEVEL_CHUNK_HEAD_SIZE,         level);
3263     LoadLevel_BODY(file, level->fieldx * level->fieldy, level);
3264   }
3265   else
3266   {
3267     static struct
3268     {
3269       char *name;
3270       int size;
3271       int (*loader)(File *, int, struct LevelInfo *);
3272     }
3273     chunk_info[] =
3274     {
3275       { "VERS", LEVEL_CHUNK_VERS_SIZE,  LoadLevel_VERS },
3276       { "DATE", LEVEL_CHUNK_DATE_SIZE,  LoadLevel_DATE },
3277       { "HEAD", LEVEL_CHUNK_HEAD_SIZE,  LoadLevel_HEAD },
3278       { "NAME", LEVEL_CHUNK_NAME_SIZE,  LoadLevel_NAME },
3279       { "AUTH", LEVEL_CHUNK_AUTH_SIZE,  LoadLevel_AUTH },
3280       { "INFO", -1,                     LoadLevel_INFO },
3281       { "BODY", -1,                     LoadLevel_BODY },
3282       { "CONT", -1,                     LoadLevel_CONT },
3283       { "CNT2", LEVEL_CHUNK_CNT2_SIZE,  LoadLevel_CNT2 },
3284       { "CNT3", -1,                     LoadLevel_CNT3 },
3285       { "CUS1", -1,                     LoadLevel_CUS1 },
3286       { "CUS2", -1,                     LoadLevel_CUS2 },
3287       { "CUS3", -1,                     LoadLevel_CUS3 },
3288       { "CUS4", -1,                     LoadLevel_CUS4 },
3289       { "GRP1", -1,                     LoadLevel_GRP1 },
3290       { "CONF", -1,                     LoadLevel_CONF },
3291       { "ELEM", -1,                     LoadLevel_ELEM },
3292       { "NOTE", -1,                     LoadLevel_NOTE },
3293       { "CUSX", -1,                     LoadLevel_CUSX },
3294       { "GRPX", -1,                     LoadLevel_GRPX },
3295
3296       {  NULL,  0,                      NULL }
3297     };
3298
3299     while (getFileChunkBE(file, chunk_name, &chunk_size))
3300     {
3301       int i = 0;
3302
3303       while (chunk_info[i].name != NULL &&
3304              !strEqual(chunk_name, chunk_info[i].name))
3305         i++;
3306
3307       if (chunk_info[i].name == NULL)
3308       {
3309         Error(ERR_WARN, "unknown chunk '%s' in level file '%s'",
3310               chunk_name, filename);
3311         ReadUnusedBytesFromFile(file, chunk_size);
3312       }
3313       else if (chunk_info[i].size != -1 &&
3314                chunk_info[i].size != chunk_size)
3315       {
3316         Error(ERR_WARN, "wrong size (%d) of chunk '%s' in level file '%s'",
3317               chunk_size, chunk_name, filename);
3318         ReadUnusedBytesFromFile(file, chunk_size);
3319       }
3320       else
3321       {
3322         /* call function to load this level chunk */
3323         int chunk_size_expected =
3324           (chunk_info[i].loader)(file, chunk_size, level);
3325
3326         /* the size of some chunks cannot be checked before reading other
3327            chunks first (like "HEAD" and "BODY") that contain some header
3328            information, so check them here */
3329         if (chunk_size_expected != chunk_size)
3330         {
3331           Error(ERR_WARN, "wrong size (%d) of chunk '%s' in level file '%s'",
3332                 chunk_size, chunk_name, filename);
3333         }
3334       }
3335     }
3336   }
3337
3338   closeFile(file);
3339 }
3340
3341
3342 /* ------------------------------------------------------------------------- */
3343 /* functions for loading EM level                                            */
3344 /* ------------------------------------------------------------------------- */
3345
3346 void CopyNativeLevel_RND_to_EM(struct LevelInfo *level)
3347 {
3348   static int ball_xy[8][2] =
3349   {
3350     { 0, 0 },
3351     { 1, 0 },
3352     { 2, 0 },
3353     { 0, 1 },
3354     { 2, 1 },
3355     { 0, 2 },
3356     { 1, 2 },
3357     { 2, 2 },
3358   };
3359   struct LevelInfo_EM *level_em = level->native_em_level;
3360   struct LEVEL *lev = level_em->lev;
3361   struct PLAYER **ply = level_em->ply;
3362   int i, j, x, y;
3363
3364   lev->width  = MIN(level->fieldx, EM_MAX_CAVE_WIDTH);
3365   lev->height = MIN(level->fieldy, EM_MAX_CAVE_HEIGHT);
3366
3367   lev->time_seconds     = level->time;
3368   lev->required_initial = level->gems_needed;
3369
3370   lev->emerald_score    = level->score[SC_EMERALD];
3371   lev->diamond_score    = level->score[SC_DIAMOND];
3372   lev->alien_score      = level->score[SC_ROBOT];
3373   lev->tank_score       = level->score[SC_SPACESHIP];
3374   lev->bug_score        = level->score[SC_BUG];
3375   lev->eater_score      = level->score[SC_YAMYAM];
3376   lev->nut_score        = level->score[SC_NUT];
3377   lev->dynamite_score   = level->score[SC_DYNAMITE];
3378   lev->key_score        = level->score[SC_KEY];
3379   lev->exit_score       = level->score[SC_TIME_BONUS];
3380
3381   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3382     for (y = 0; y < 3; y++)
3383       for (x = 0; x < 3; x++)
3384         lev->eater_array[i][y * 3 + x] =
3385           map_element_RND_to_EM(level->yamyam_content[i].e[x][y]);
3386
3387   lev->amoeba_time              = level->amoeba_speed;
3388   lev->wonderwall_time_initial  = level->time_magic_wall;
3389   lev->wheel_time               = level->time_wheel;
3390
3391   lev->android_move_time        = level->android_move_time;
3392   lev->android_clone_time       = level->android_clone_time;
3393   lev->ball_random              = level->ball_random;
3394   lev->ball_state_initial       = level->ball_state_initial;
3395   lev->ball_time                = level->ball_time;
3396   lev->num_ball_arrays          = level->num_ball_contents;
3397
3398   lev->lenses_score             = level->lenses_score;
3399   lev->magnify_score            = level->magnify_score;
3400   lev->slurp_score              = level->slurp_score;
3401
3402   lev->lenses_time              = level->lenses_time;
3403   lev->magnify_time             = level->magnify_time;
3404
3405   lev->wind_direction_initial =
3406     map_direction_RND_to_EM(level->wind_direction_initial);
3407   lev->wind_cnt_initial = (level->wind_direction_initial != MV_NONE ?
3408                            lev->wind_time : 0);
3409
3410   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3411     for (j = 0; j < 8; j++)
3412       lev->ball_array[i][j] =
3413         map_element_RND_to_EM(level->
3414                               ball_content[i].e[ball_xy[j][0]][ball_xy[j][1]]);
3415
3416   map_android_clone_elements_RND_to_EM(level);
3417
3418   /* first fill the complete playfield with the default border element */
3419   for (y = 0; y < EM_MAX_CAVE_HEIGHT; y++)
3420     for (x = 0; x < EM_MAX_CAVE_WIDTH; x++)
3421       level_em->cave[x][y] = ZBORDER;
3422
3423   if (BorderElement == EL_STEELWALL)
3424   {
3425     for (y = 0; y < lev->height + 2; y++)
3426       for (x = 0; x < lev->width + 2; x++)
3427         level_em->cave[x + 1][y + 1] = map_element_RND_to_EM(EL_STEELWALL);
3428   }
3429
3430   /* then copy the real level contents from level file into the playfield */
3431   for (y = 0; y < lev->height; y++) for (x = 0; x < lev->width; x++)
3432   {
3433     int new_element = map_element_RND_to_EM(level->field[x][y]);
3434     int offset = (BorderElement == EL_STEELWALL ? 1 : 0);
3435     int xx = x + 1 + offset;
3436     int yy = y + 1 + offset;
3437
3438     if (level->field[x][y] == EL_AMOEBA_DEAD)
3439       new_element = map_element_RND_to_EM(EL_AMOEBA_WET);
3440
3441     level_em->cave[xx][yy] = new_element;
3442   }
3443
3444   for (i = 0; i < MAX_PLAYERS; i++)
3445   {
3446     ply[i]->x_initial = 0;
3447     ply[i]->y_initial = 0;
3448   }
3449
3450   /* initialize player positions and delete players from the playfield */
3451   for (y = 0; y < lev->height; y++) for (x = 0; x < lev->width; x++)
3452   {
3453     if (ELEM_IS_PLAYER(level->field[x][y]))
3454     {
3455       int player_nr = GET_PLAYER_NR(level->field[x][y]);
3456       int offset = (BorderElement == EL_STEELWALL ? 1 : 0);
3457       int xx = x + 1 + offset;
3458       int yy = y + 1 + offset;
3459
3460       ply[player_nr]->x_initial = xx;
3461       ply[player_nr]->y_initial = yy;
3462
3463       level_em->cave[xx][yy] = map_element_RND_to_EM(EL_EMPTY);
3464     }
3465   }
3466
3467   if (BorderElement == EL_STEELWALL)
3468   {
3469     lev->width  += 2;
3470     lev->height += 2;
3471   }
3472 }
3473
3474 void CopyNativeLevel_EM_to_RND(struct LevelInfo *level)
3475 {
3476   static int ball_xy[8][2] =
3477   {
3478     { 0, 0 },
3479     { 1, 0 },
3480     { 2, 0 },
3481     { 0, 1 },
3482     { 2, 1 },
3483     { 0, 2 },
3484     { 1, 2 },
3485     { 2, 2 },
3486   };
3487   struct LevelInfo_EM *level_em = level->native_em_level;
3488   struct LEVEL *lev = level_em->lev;
3489   struct PLAYER **ply = level_em->ply;
3490   int i, j, x, y;
3491
3492   level->fieldx = MIN(lev->width,  MAX_LEV_FIELDX);
3493   level->fieldy = MIN(lev->height, MAX_LEV_FIELDY);
3494
3495   level->time        = lev->time_seconds;
3496   level->gems_needed = lev->required_initial;
3497
3498   sprintf(level->name, "Level %d", level->file_info.nr);
3499
3500   level->score[SC_EMERALD]      = lev->emerald_score;
3501   level->score[SC_DIAMOND]      = lev->diamond_score;
3502   level->score[SC_ROBOT]        = lev->alien_score;
3503   level->score[SC_SPACESHIP]    = lev->tank_score;
3504   level->score[SC_BUG]          = lev->bug_score;
3505   level->score[SC_YAMYAM]       = lev->eater_score;
3506   level->score[SC_NUT]          = lev->nut_score;
3507   level->score[SC_DYNAMITE]     = lev->dynamite_score;
3508   level->score[SC_KEY]          = lev->key_score;
3509   level->score[SC_TIME_BONUS]   = lev->exit_score;
3510
3511   level->num_yamyam_contents = MAX_ELEMENT_CONTENTS;
3512
3513   for (i = 0; i < level->num_yamyam_contents; i++)
3514     for (y = 0; y < 3; y++)
3515       for (x = 0; x < 3; x++)
3516         level->yamyam_content[i].e[x][y] =
3517           map_element_EM_to_RND(lev->eater_array[i][y * 3 + x]);
3518
3519   level->amoeba_speed           = lev->amoeba_time;
3520   level->time_magic_wall        = lev->wonderwall_time_initial;
3521   level->time_wheel             = lev->wheel_time;
3522
3523   level->android_move_time      = lev->android_move_time;
3524   level->android_clone_time     = lev->android_clone_time;
3525   level->ball_random            = lev->ball_random;
3526   level->ball_state_initial     = lev->ball_state_initial;
3527   level->ball_time              = lev->ball_time;
3528   level->num_ball_contents      = lev->num_ball_arrays;
3529
3530   level->lenses_score           = lev->lenses_score;
3531   level->magnify_score          = lev->magnify_score;
3532   level->slurp_score            = lev->slurp_score;
3533
3534   level->lenses_time            = lev->lenses_time;
3535   level->magnify_time           = lev->magnify_time;
3536
3537   level->wind_direction_initial =
3538     map_direction_EM_to_RND(lev->wind_direction_initial);
3539
3540   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3541     for (j = 0; j < 8; j++)
3542       level->ball_content[i].e[ball_xy[j][0]][ball_xy[j][1]] =
3543         map_element_EM_to_RND(lev->ball_array[i][j]);
3544
3545   map_android_clone_elements_EM_to_RND(level);
3546
3547   /* convert the playfield (some elements need special treatment) */
3548   for (y = 0; y < level->fieldy; y++) for (x = 0; x < level->fieldx; x++)
3549   {
3550     int new_element = map_element_EM_to_RND(level_em->cave[x + 1][y + 1]);
3551
3552     if (new_element == EL_AMOEBA_WET && level->amoeba_speed == 0)
3553       new_element = EL_AMOEBA_DEAD;
3554
3555     level->field[x][y] = new_element;
3556   }
3557
3558   for (i = 0; i < MAX_PLAYERS; i++)
3559   {
3560     /* in case of all players set to the same field, use the first player */
3561     int nr = MAX_PLAYERS - i - 1;
3562     int jx = ply[nr]->x_initial - 1;
3563     int jy = ply[nr]->y_initial - 1;
3564
3565     if (jx != -1 && jy != -1)
3566       level->field[jx][jy] = EL_PLAYER_1 + nr;
3567   }
3568 }
3569
3570
3571 /* ------------------------------------------------------------------------- */
3572 /* functions for loading SP level                                            */
3573 /* ------------------------------------------------------------------------- */
3574
3575 void CopyNativeLevel_RND_to_SP(struct LevelInfo *level)
3576 {
3577   struct LevelInfo_SP *level_sp = level->native_sp_level;
3578   LevelInfoType *header = &level_sp->header;
3579   int i, x, y;
3580
3581   level_sp->width  = level->fieldx;
3582   level_sp->height = level->fieldy;
3583
3584   for (x = 0; x < level->fieldx; x++)
3585     for (y = 0; y < level->fieldy; y++)
3586       level_sp->playfield[x][y] = map_element_RND_to_SP(level->field[x][y]);
3587
3588   header->InitialGravity = (level->initial_player_gravity[0] ? 1 : 0);
3589
3590   for (i = 0; i < SP_LEVEL_NAME_LEN; i++)
3591     header->LevelTitle[i] = level->name[i];
3592   /* !!! NO STRING TERMINATION IN SUPAPLEX VB CODE YET -- FIX THIS !!! */
3593
3594   header->InfotronsNeeded = level->gems_needed;
3595
3596   header->SpecialPortCount = 0;
3597
3598   for (x = 0; x < level->fieldx; x++) for (y = 0; y < level->fieldy; y++)
3599   {
3600     boolean gravity_port_found = FALSE;
3601     boolean gravity_port_valid = FALSE;
3602     int gravity_port_flag;
3603     int gravity_port_base_element;
3604     int element = level->field[x][y];
3605
3606     if (element >= EL_SP_GRAVITY_ON_PORT_RIGHT &&
3607         element <= EL_SP_GRAVITY_ON_PORT_UP)
3608     {
3609       gravity_port_found = TRUE;
3610       gravity_port_valid = TRUE;
3611       gravity_port_flag = 1;
3612       gravity_port_base_element = EL_SP_GRAVITY_ON_PORT_RIGHT;
3613     }
3614     else if (element >= EL_SP_GRAVITY_OFF_PORT_RIGHT &&
3615              element <= EL_SP_GRAVITY_OFF_PORT_UP)
3616     {
3617       gravity_port_found = TRUE;
3618       gravity_port_valid = TRUE;
3619       gravity_port_flag = 0;
3620       gravity_port_base_element = EL_SP_GRAVITY_OFF_PORT_RIGHT;
3621     }
3622     else if (element >= EL_SP_GRAVITY_PORT_RIGHT &&
3623              element <= EL_SP_GRAVITY_PORT_UP)
3624     {
3625       /* change R'n'D style gravity inverting special port to normal port
3626          (there are no gravity inverting ports in native Supaplex engine) */
3627
3628       gravity_port_found = TRUE;
3629       gravity_port_valid = FALSE;
3630       gravity_port_base_element = EL_SP_GRAVITY_PORT_RIGHT;
3631     }
3632
3633     if (gravity_port_found)
3634     {
3635       if (gravity_port_valid &&
3636           header->SpecialPortCount < SP_MAX_SPECIAL_PORTS)
3637       {
3638         SpecialPortType *port = &header->SpecialPort[header->SpecialPortCount];
3639
3640         port->PortLocation = (y * level->fieldx + x) * 2;
3641         port->Gravity = gravity_port_flag;
3642
3643         element += EL_SP_GRAVITY_PORT_RIGHT - gravity_port_base_element;
3644
3645         header->SpecialPortCount++;
3646       }
3647       else
3648       {
3649         /* change special gravity port to normal port */
3650
3651         element += EL_SP_PORT_RIGHT - gravity_port_base_element;
3652       }
3653
3654       level_sp->playfield[x][y] = element - EL_SP_START;
3655     }
3656   }
3657 }
3658
3659 void CopyNativeLevel_SP_to_RND(struct LevelInfo *level)
3660 {
3661   struct LevelInfo_SP *level_sp = level->native_sp_level;
3662   LevelInfoType *header = &level_sp->header;
3663   int i, x, y;
3664
3665   level->fieldx = level_sp->width;
3666   level->fieldy = level_sp->height;
3667
3668   for (x = 0; x < level->fieldx; x++)
3669   {
3670     for (y = 0; y < level->fieldy; y++)
3671     {
3672       int element_old = level_sp->playfield[x][y];
3673       int element_new = getMappedElement(map_element_SP_to_RND(element_old));
3674
3675       if (element_new == EL_UNKNOWN)
3676         Error(ERR_WARN, "invalid element %d at position %d, %d",
3677               element_old, x, y);
3678
3679       level->field[x][y] = element_new;
3680     }
3681   }
3682
3683   for (i = 0; i < MAX_PLAYERS; i++)
3684     level->initial_player_gravity[i] =
3685       (header->InitialGravity == 1 ? TRUE : FALSE);
3686
3687   for (i = 0; i < SP_LEVEL_NAME_LEN; i++)
3688     level->name[i] = header->LevelTitle[i];
3689   level->name[SP_LEVEL_NAME_LEN] = '\0';
3690
3691   level->gems_needed = header->InfotronsNeeded;
3692
3693   for (i = 0; i < header->SpecialPortCount; i++)
3694   {
3695     SpecialPortType *port = &header->SpecialPort[i];
3696     int port_location = port->PortLocation;
3697     int gravity = port->Gravity;
3698     int port_x, port_y, port_element;
3699
3700     port_x = (port_location / 2) % level->fieldx;
3701     port_y = (port_location / 2) / level->fieldx;
3702
3703     if (port_x < 0 || port_x >= level->fieldx ||
3704         port_y < 0 || port_y >= level->fieldy)
3705     {
3706       Error(ERR_WARN, "special port position (%d, %d) out of bounds",
3707             port_x, port_y);
3708
3709       continue;
3710     }
3711
3712     port_element = level->field[port_x][port_y];
3713
3714     if (port_element < EL_SP_GRAVITY_PORT_RIGHT ||
3715         port_element > EL_SP_GRAVITY_PORT_UP)
3716     {
3717       Error(ERR_WARN, "no special port at position (%d, %d)", port_x, port_y);
3718
3719       continue;
3720     }
3721
3722     /* change previous (wrong) gravity inverting special port to either
3723        gravity enabling special port or gravity disabling special port */
3724     level->field[port_x][port_y] +=
3725       (gravity == 1 ? EL_SP_GRAVITY_ON_PORT_RIGHT :
3726        EL_SP_GRAVITY_OFF_PORT_RIGHT) - EL_SP_GRAVITY_PORT_RIGHT;
3727   }
3728