a041e1854ac2017d50514fa8493d9d55ed6797c1
[rocksndiamonds.git] / src / tools.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 //                  https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // tools.c
10 // ============================================================================
11
12 #include <math.h>
13
14 #include "libgame/libgame.h"
15
16 #include "tools.h"
17 #include "init.h"
18 #include "game.h"
19 #include "events.h"
20 #include "anim.h"
21 #include "network.h"
22 #include "tape.h"
23 #include "screens.h"
24
25
26 #define DEBUG_FRAME_TIME        FALSE
27
28 // tool button identifiers
29 #define TOOL_CTRL_ID_YES        0
30 #define TOOL_CTRL_ID_NO         1
31 #define TOOL_CTRL_ID_CONFIRM    2
32 #define TOOL_CTRL_ID_PLAYER_1   3
33 #define TOOL_CTRL_ID_PLAYER_2   4
34 #define TOOL_CTRL_ID_PLAYER_3   5
35 #define TOOL_CTRL_ID_PLAYER_4   6
36 #define TOOL_CTRL_ID_TOUCH_YES  7
37 #define TOOL_CTRL_ID_TOUCH_NO   8
38 #define TOOL_CTRL_ID_TOUCH_CONFIRM 9
39
40 #define NUM_TOOL_BUTTONS        10
41
42 // constants for number of doors and door parts
43 #define NUM_DOORS               2
44 #define NUM_PANELS              NUM_DOORS
45 // #define NUM_PANELS           0
46 #define MAX_PARTS_PER_DOOR      8
47 #define MAX_DOOR_PARTS          (NUM_DOORS * MAX_PARTS_PER_DOOR + NUM_PANELS)
48 #define DOOR_PART_IS_PANEL(i)   ((i) >= NUM_DOORS * MAX_PARTS_PER_DOOR)
49
50
51 struct DoorPartOrderInfo
52 {
53   int nr;
54   int sort_priority;
55 };
56
57 static struct DoorPartOrderInfo door_part_order[MAX_DOOR_PARTS];
58
59 struct DoorPartControlInfo
60 {
61   int door_token;
62   int graphic;
63   struct DoorPartPosInfo *pos;
64 };
65
66 static struct DoorPartControlInfo door_part_controls[] =
67 {
68   {
69     DOOR_1,
70     IMG_GFX_DOOR_1_PART_1,
71     &door_1.part_1
72   },
73   {
74     DOOR_1,
75     IMG_GFX_DOOR_1_PART_2,
76     &door_1.part_2
77   },
78   {
79     DOOR_1,
80     IMG_GFX_DOOR_1_PART_3,
81     &door_1.part_3
82   },
83   {
84     DOOR_1,
85     IMG_GFX_DOOR_1_PART_4,
86     &door_1.part_4
87   },
88   {
89     DOOR_1,
90     IMG_GFX_DOOR_1_PART_5,
91     &door_1.part_5
92   },
93   {
94     DOOR_1,
95     IMG_GFX_DOOR_1_PART_6,
96     &door_1.part_6
97   },
98   {
99     DOOR_1,
100     IMG_GFX_DOOR_1_PART_7,
101     &door_1.part_7
102   },
103   {
104     DOOR_1,
105     IMG_GFX_DOOR_1_PART_8,
106     &door_1.part_8
107   },
108
109   {
110     DOOR_2,
111     IMG_GFX_DOOR_2_PART_1,
112     &door_2.part_1
113   },
114   {
115     DOOR_2,
116     IMG_GFX_DOOR_2_PART_2,
117     &door_2.part_2
118   },
119   {
120     DOOR_2,
121     IMG_GFX_DOOR_2_PART_3,
122     &door_2.part_3
123   },
124   {
125     DOOR_2,
126     IMG_GFX_DOOR_2_PART_4,
127     &door_2.part_4
128   },
129   {
130     DOOR_2,
131     IMG_GFX_DOOR_2_PART_5,
132     &door_2.part_5
133   },
134   {
135     DOOR_2,
136     IMG_GFX_DOOR_2_PART_6,
137     &door_2.part_6
138   },
139   {
140     DOOR_2,
141     IMG_GFX_DOOR_2_PART_7,
142     &door_2.part_7
143   },
144   {
145     DOOR_2,
146     IMG_GFX_DOOR_2_PART_8,
147     &door_2.part_8
148   },
149
150   {
151     DOOR_1,
152     IMG_BACKGROUND_PANEL,
153     &door_1.panel
154   },
155   {
156     DOOR_2,
157     IMG_BACKGROUND_TAPE,
158     &door_2.panel
159   },
160
161   {
162     -1,
163     -1,
164     NULL
165   }
166 };
167
168
169 // forward declaration for internal use
170 static void UnmapToolButtons(void);
171 static void HandleToolButtons(struct GadgetInfo *);
172 static int el_act_dir2crm(int, int, int);
173 static int el_act2crm(int, int);
174
175 static struct GadgetInfo *tool_gadget[NUM_TOOL_BUTTONS];
176 static int request_gadget_id = -1;
177
178 static char *print_if_not_empty(int element)
179 {
180   static char *s = NULL;
181   char *token_name = element_info[element].token_name;
182
183   if (s != NULL)
184     free(s);
185
186   s = checked_malloc(strlen(token_name) + 10 + 1);
187
188   if (element != EL_EMPTY)
189     sprintf(s, "%d\t['%s']", element, token_name);
190   else
191     sprintf(s, "%d", element);
192
193   return s;
194 }
195
196 int getFieldbufferOffsetX_RND(int dir, int pos)
197 {
198   int full_lev_fieldx = lev_fieldx + (BorderElement != EL_EMPTY ? 2 : 0);
199   int dx = (dir & MV_HORIZONTAL ? pos : 0);
200   int dx_var = dx * TILESIZE_VAR / TILESIZE;
201   int fx = FX;
202
203   if (EVEN(SCR_FIELDX))
204   {
205     int sbx_right = SBX_Right + (BorderElement != EL_EMPTY ? 1 : 0);
206     int ffx = (scroll_x - SBX_Left) * TILEX_VAR + dx_var;
207
208     if (ffx < sbx_right * TILEX_VAR + TILEX_VAR / 2)
209       fx += dx_var - MIN(ffx, TILEX_VAR / 2) + TILEX_VAR;
210     else
211       fx += (dx_var > 0 ? TILEX_VAR : 0);
212   }
213   else
214   {
215     fx += dx_var;
216   }
217
218   if (full_lev_fieldx <= SCR_FIELDX)
219   {
220     if (EVEN(SCR_FIELDX))
221       fx = 2 * TILEX_VAR - (ODD(lev_fieldx)  ? TILEX_VAR / 2 : 0);
222     else
223       fx = 2 * TILEX_VAR - (EVEN(lev_fieldx) ? TILEX_VAR / 2 : 0);
224   }
225
226   return fx;
227 }
228
229 int getFieldbufferOffsetY_RND(int dir, int pos)
230 {
231   int full_lev_fieldy = lev_fieldy + (BorderElement != EL_EMPTY ? 2 : 0);
232   int dy = (dir & MV_VERTICAL ? pos : 0);
233   int dy_var = dy * TILESIZE_VAR / TILESIZE;
234   int fy = FY;
235
236   if (EVEN(SCR_FIELDY))
237   {
238     int sby_lower = SBY_Lower + (BorderElement != EL_EMPTY ? 1 : 0);
239     int ffy = (scroll_y - SBY_Upper) * TILEY_VAR + dy_var;
240
241     if (ffy < sby_lower * TILEY_VAR + TILEY_VAR / 2)
242       fy += dy_var - MIN(ffy, TILEY_VAR / 2) + TILEY_VAR;
243     else
244       fy += (dy_var > 0 ? TILEY_VAR : 0);
245   }
246   else
247   {
248     fy += dy_var;
249   }
250
251   if (full_lev_fieldy <= SCR_FIELDY)
252   {
253     if (EVEN(SCR_FIELDY))
254       fy = 2 * TILEY_VAR - (ODD(lev_fieldy)  ? TILEY_VAR / 2 : 0);
255     else
256       fy = 2 * TILEY_VAR - (EVEN(lev_fieldy) ? TILEY_VAR / 2 : 0);
257   }
258
259   return fy;
260 }
261
262 static int getLevelFromScreenX_RND(int sx)
263 {
264   int fx = getFieldbufferOffsetX_RND(ScreenMovDir, ScreenGfxPos);
265   int dx = fx - FX;
266   int px = sx - SX;
267   int lx = LEVELX((px + dx) / TILESIZE_VAR);
268
269   return lx;
270 }
271
272 static int getLevelFromScreenY_RND(int sy)
273 {
274   int fy = getFieldbufferOffsetY_RND(ScreenMovDir, ScreenGfxPos);
275   int dy = fy - FY;
276   int py = sy - SY;
277   int ly = LEVELY((py + dy) / TILESIZE_VAR);
278
279   return ly;
280 }
281
282 static int getLevelFromScreenX_EM(int sx)
283 {
284   int level_xsize = level.native_em_level->cav->width;
285   int full_xsize = level_xsize * TILESIZE_VAR;
286
287   sx -= (full_xsize < SXSIZE ? (SXSIZE - full_xsize) / 2 : 0);
288
289   int fx = getFieldbufferOffsetX_EM();
290   int dx = fx;
291   int px = sx - SX;
292   int lx = LEVELX((px + dx) / TILESIZE_VAR);
293
294   return lx;
295 }
296
297 static int getLevelFromScreenY_EM(int sy)
298 {
299   int level_ysize = level.native_em_level->cav->height;
300   int full_ysize = level_ysize * TILESIZE_VAR;
301
302   sy -= (full_ysize < SYSIZE ? (SYSIZE - full_ysize) / 2 : 0);
303
304   int fy = getFieldbufferOffsetY_EM();
305   int dy = fy;
306   int py = sy - SY;
307   int ly = LEVELY((py + dy) / TILESIZE_VAR);
308
309   return ly;
310 }
311
312 static int getLevelFromScreenX_SP(int sx)
313 {
314   int menBorder = setup.sp_show_border_elements;
315   int level_xsize = level.native_sp_level->width;
316   int full_xsize = (level_xsize - (menBorder ? 0 : 1)) * TILESIZE_VAR;
317
318   sx += (full_xsize < SXSIZE ? (SXSIZE - full_xsize) / 2 : 0);
319
320   int fx = getFieldbufferOffsetX_SP();
321   int dx = fx - FX;
322   int px = sx - SX;
323   int lx = LEVELX((px + dx) / TILESIZE_VAR);
324
325   return lx;
326 }
327
328 static int getLevelFromScreenY_SP(int sy)
329 {
330   int menBorder = setup.sp_show_border_elements;
331   int level_ysize = level.native_sp_level->height;
332   int full_ysize = (level_ysize - (menBorder ? 0 : 1)) * TILESIZE_VAR;
333
334   sy += (full_ysize < SYSIZE ? (SYSIZE - full_ysize) / 2 : 0);
335
336   int fy = getFieldbufferOffsetY_SP();
337   int dy = fy - FY;
338   int py = sy - SY;
339   int ly = LEVELY((py + dy) / TILESIZE_VAR);
340
341   return ly;
342 }
343
344 static int getLevelFromScreenX_MM(int sx)
345 {
346   int level_xsize = level.native_mm_level->fieldx;
347   int full_xsize = level_xsize * TILESIZE_VAR;
348
349   sx -= (full_xsize < SXSIZE ? (SXSIZE - full_xsize) / 2 : 0);
350
351   int px = sx - SX;
352   int lx = (px + TILESIZE_VAR) / TILESIZE_VAR - 1;
353
354   return lx;
355 }
356
357 static int getLevelFromScreenY_MM(int sy)
358 {
359   int level_ysize = level.native_mm_level->fieldy;
360   int full_ysize = level_ysize * TILESIZE_VAR;
361
362   sy -= (full_ysize < SYSIZE ? (SYSIZE - full_ysize) / 2 : 0);
363
364   int py = sy - SY;
365   int ly = (py + TILESIZE_VAR) / TILESIZE_VAR - 1;
366
367   return ly;
368 }
369
370 int getLevelFromScreenX(int x)
371 {
372   if (level.game_engine_type == GAME_ENGINE_TYPE_EM)
373     return getLevelFromScreenX_EM(x);
374   if (level.game_engine_type == GAME_ENGINE_TYPE_SP)
375     return getLevelFromScreenX_SP(x);
376   if (level.game_engine_type == GAME_ENGINE_TYPE_MM)
377     return getLevelFromScreenX_MM(x);
378   else
379     return getLevelFromScreenX_RND(x);
380 }
381
382 int getLevelFromScreenY(int y)
383 {
384   if (level.game_engine_type == GAME_ENGINE_TYPE_EM)
385     return getLevelFromScreenY_EM(y);
386   if (level.game_engine_type == GAME_ENGINE_TYPE_SP)
387     return getLevelFromScreenY_SP(y);
388   if (level.game_engine_type == GAME_ENGINE_TYPE_MM)
389     return getLevelFromScreenY_MM(y);
390   else
391     return getLevelFromScreenY_RND(y);
392 }
393
394 void DumpTile(int x, int y)
395 {
396   int sx = SCREENX(x);
397   int sy = SCREENY(y);
398   char *token_name;
399
400   Info("---");
401   Info("Field Info: SCREEN(%d, %d), LEVEL(%d, %d)", sx, sy, x, y);
402   Info("---");
403
404   if (!IN_LEV_FIELD(x, y))
405   {
406     Info("(not in level field)");
407     Info("");
408
409     return;
410   }
411
412   token_name = element_info[Tile[x][y]].token_name;
413
414   Info("Tile:        %d\t['%s']",       Tile[x][y], token_name);
415   Info("Back:        %s",               print_if_not_empty(Back[x][y]));
416   Info("Store:       %s",               print_if_not_empty(Store[x][y]));
417   Info("Store2:      %s",               print_if_not_empty(Store2[x][y]));
418   Info("StorePlayer: %s",               print_if_not_empty(StorePlayer[x][y]));
419   Info("MovPos:      %d",               MovPos[x][y]);
420   Info("MovDir:      %d",               MovDir[x][y]);
421   Info("MovDelay:    %d",               MovDelay[x][y]);
422   Info("ChangeDelay: %d",               ChangeDelay[x][y]);
423   Info("CustomValue: %d",               CustomValue[x][y]);
424   Info("GfxElement:  %d",               GfxElement[x][y]);
425   Info("GfxAction:   %d",               GfxAction[x][y]);
426   Info("GfxFrame:    %d [%d]",          GfxFrame[x][y], FrameCounter);
427   Info("Player x/y:  %d, %d",           local_player->jx, local_player->jy);
428   Info("");
429 }
430
431 void DumpTileFromScreen(int sx, int sy)
432 {
433   int lx = getLevelFromScreenX(sx);
434   int ly = getLevelFromScreenY(sy);
435
436   DumpTile(lx, ly);
437 }
438
439 void SetDrawtoField(int mode)
440 {
441   if (mode == DRAW_TO_FIELDBUFFER)
442   {
443     FX = 2 * TILEX_VAR;
444     FY = 2 * TILEY_VAR;
445     BX1 = -2;
446     BY1 = -2;
447     BX2 = SCR_FIELDX + 1;
448     BY2 = SCR_FIELDY + 1;
449
450     drawto_field = fieldbuffer;
451   }
452   else  // DRAW_TO_BACKBUFFER
453   {
454     FX = SX;
455     FY = SY;
456     BX1 = 0;
457     BY1 = 0;
458     BX2 = SCR_FIELDX - 1;
459     BY2 = SCR_FIELDY - 1;
460
461     drawto_field = backbuffer;
462   }
463 }
464
465 static void RedrawPlayfield_RND(void)
466 {
467   if (game.envelope_active)
468     return;
469
470   DrawLevel(REDRAW_ALL);
471   DrawAllPlayers();
472 }
473
474 void RedrawPlayfield(void)
475 {
476   if (game_status != GAME_MODE_PLAYING)
477     return;
478
479   if (level.game_engine_type == GAME_ENGINE_TYPE_EM)
480     RedrawPlayfield_EM(TRUE);
481   else if (level.game_engine_type == GAME_ENGINE_TYPE_SP)
482     RedrawPlayfield_SP(TRUE);
483   else if (level.game_engine_type == GAME_ENGINE_TYPE_MM)
484     RedrawPlayfield_MM();
485   else if (level.game_engine_type == GAME_ENGINE_TYPE_RND)
486     RedrawPlayfield_RND();
487
488   BlitScreenToBitmap(backbuffer);
489
490   BlitBitmap(drawto, window, gfx.sx, gfx.sy, gfx.sxsize, gfx.sysize,
491              gfx.sx, gfx.sy);
492 }
493
494 static void DrawMaskedBorderExt_Rect(int x, int y, int width, int height,
495                                      int draw_target)
496 {
497   Bitmap *src_bitmap = getGlobalBorderBitmapFromStatus(global.border_status);
498   Bitmap *dst_bitmap = gfx.masked_border_bitmap_ptr;
499
500   if (x == -1 && y == -1)
501     return;
502
503   if (draw_target == DRAW_TO_SCREEN)
504     BlitToScreenMasked(src_bitmap, x, y, width, height, x, y);
505   else
506     BlitBitmapMasked(src_bitmap, dst_bitmap, x, y, width, height, x, y);
507 }
508
509 static void DrawMaskedBorderExt_FIELD(int draw_target)
510 {
511   if (global.border_status >= GAME_MODE_MAIN &&
512       global.border_status <= GAME_MODE_PLAYING &&
513       border.draw_masked[global.border_status])
514     DrawMaskedBorderExt_Rect(REAL_SX, REAL_SY, FULL_SXSIZE, FULL_SYSIZE,
515                              draw_target);
516 }
517
518 static void DrawMaskedBorderExt_DOOR_1(int draw_target)
519 {
520   // when drawing to backbuffer, never draw border over open doors
521   if (draw_target == DRAW_TO_BACKBUFFER &&
522       (GetDoorState() & DOOR_OPEN_1))
523     return;
524
525   if (border.draw_masked[GFX_SPECIAL_ARG_DOOR] &&
526       (global.border_status != GAME_MODE_EDITOR ||
527        border.draw_masked[GFX_SPECIAL_ARG_EDITOR]))
528     DrawMaskedBorderExt_Rect(DX, DY, DXSIZE, DYSIZE, draw_target);
529 }
530
531 static void DrawMaskedBorderExt_DOOR_2(int draw_target)
532 {
533   // when drawing to backbuffer, never draw border over open doors
534   if (draw_target == DRAW_TO_BACKBUFFER &&
535       (GetDoorState() & DOOR_OPEN_2))
536     return;
537
538   if (border.draw_masked[GFX_SPECIAL_ARG_DOOR] &&
539       global.border_status != GAME_MODE_EDITOR)
540     DrawMaskedBorderExt_Rect(VX, VY, VXSIZE, VYSIZE, draw_target);
541 }
542
543 static void DrawMaskedBorderExt_DOOR_3(int draw_target)
544 {
545   // currently not available
546 }
547
548 static void DrawMaskedBorderExt_ALL(int draw_target)
549 {
550   DrawMaskedBorderExt_FIELD(draw_target);
551   DrawMaskedBorderExt_DOOR_1(draw_target);
552   DrawMaskedBorderExt_DOOR_2(draw_target);
553   DrawMaskedBorderExt_DOOR_3(draw_target);
554 }
555
556 static void DrawMaskedBorderExt(int redraw_mask, int draw_target)
557 {
558   // never draw masked screen borders on borderless screens
559   if (global.border_status == GAME_MODE_LOADING ||
560       global.border_status == GAME_MODE_TITLE)
561     return;
562
563   if (redraw_mask & REDRAW_ALL)
564     DrawMaskedBorderExt_ALL(draw_target);
565   else
566   {
567     if (redraw_mask & REDRAW_FIELD)
568       DrawMaskedBorderExt_FIELD(draw_target);
569     if (redraw_mask & REDRAW_DOOR_1)
570       DrawMaskedBorderExt_DOOR_1(draw_target);
571     if (redraw_mask & REDRAW_DOOR_2)
572       DrawMaskedBorderExt_DOOR_2(draw_target);
573     if (redraw_mask & REDRAW_DOOR_3)
574       DrawMaskedBorderExt_DOOR_3(draw_target);
575   }
576 }
577
578 void DrawMaskedBorder_FIELD(void)
579 {
580   DrawMaskedBorderExt_FIELD(DRAW_TO_BACKBUFFER);
581 }
582
583 void DrawMaskedBorder(int redraw_mask)
584 {
585   DrawMaskedBorderExt(redraw_mask, DRAW_TO_BACKBUFFER);
586 }
587
588 void DrawMaskedBorderToTarget(int draw_target)
589 {
590   if (draw_target == DRAW_TO_BACKBUFFER ||
591       draw_target == DRAW_TO_SCREEN)
592   {
593     DrawMaskedBorderExt(REDRAW_ALL, draw_target);
594   }
595   else
596   {
597     int last_border_status = global.border_status;
598
599     if (draw_target == DRAW_TO_FADE_SOURCE)
600     {
601       global.border_status = gfx.fade_border_source_status;
602       gfx.masked_border_bitmap_ptr = gfx.fade_bitmap_source;
603     }
604     else if (draw_target == DRAW_TO_FADE_TARGET)
605     {
606       global.border_status = gfx.fade_border_target_status;
607       gfx.masked_border_bitmap_ptr = gfx.fade_bitmap_target;
608     }
609
610     DrawMaskedBorderExt(REDRAW_ALL, draw_target);
611
612     global.border_status = last_border_status;
613     gfx.masked_border_bitmap_ptr = backbuffer;
614   }
615 }
616
617 void DrawTileCursor(int draw_target)
618 {
619   Bitmap *fade_bitmap;
620   Bitmap *src_bitmap;
621   int src_x, src_y;
622   int dst_x, dst_y;
623   int graphic = IMG_GLOBAL_TILE_CURSOR;
624   int frame = 0;
625   int tilesize = TILESIZE_VAR;
626   int width = tilesize;
627   int height = tilesize;
628
629   if (game_status != GAME_MODE_PLAYING)
630     return;
631
632   if (!tile_cursor.enabled ||
633       !tile_cursor.active)
634     return;
635
636   if (tile_cursor.moving)
637   {
638     int step = TILESIZE_VAR / 4;
639     int dx = tile_cursor.target_x - tile_cursor.x;
640     int dy = tile_cursor.target_y - tile_cursor.y;
641
642     if (ABS(dx) < step)
643       tile_cursor.x = tile_cursor.target_x;
644     else
645       tile_cursor.x += SIGN(dx) * step;
646
647     if (ABS(dy) < step)
648       tile_cursor.y = tile_cursor.target_y;
649     else
650       tile_cursor.y += SIGN(dy) * step;
651
652     if (tile_cursor.x == tile_cursor.target_x &&
653         tile_cursor.y == tile_cursor.target_y)
654       tile_cursor.moving = FALSE;
655   }
656
657   dst_x = tile_cursor.x;
658   dst_y = tile_cursor.y;
659
660   frame = getGraphicAnimationFrame(graphic, -1);
661
662   getSizedGraphicSource(graphic, frame, tilesize, &src_bitmap, &src_x, &src_y);
663
664   fade_bitmap =
665     (draw_target == DRAW_TO_FADE_SOURCE ? gfx.fade_bitmap_source :
666      draw_target == DRAW_TO_FADE_TARGET ? gfx.fade_bitmap_target : NULL);
667
668   if (draw_target == DRAW_TO_SCREEN)
669     BlitToScreenMasked(src_bitmap, src_x, src_y, width, height, dst_x, dst_y);
670   else
671     BlitBitmapMasked(src_bitmap, fade_bitmap, src_x, src_y, width, height,
672                      dst_x, dst_y);
673 }
674
675 void BlitScreenToBitmapExt_RND(Bitmap *target_bitmap, int fx, int fy)
676 {
677   BlitBitmap(drawto_field, target_bitmap, fx, fy, SXSIZE, SYSIZE, SX, SY);
678 }
679
680 void BlitScreenToBitmap_RND(Bitmap *target_bitmap)
681 {
682   int fx = getFieldbufferOffsetX_RND(ScreenMovDir, ScreenGfxPos);
683   int fy = getFieldbufferOffsetY_RND(ScreenMovDir, ScreenGfxPos);
684
685   BlitScreenToBitmapExt_RND(target_bitmap, fx, fy);
686 }
687
688 void BlitScreenToBitmap(Bitmap *target_bitmap)
689 {
690   if (level.game_engine_type == GAME_ENGINE_TYPE_EM)
691     BlitScreenToBitmap_EM(target_bitmap);
692   else if (level.game_engine_type == GAME_ENGINE_TYPE_SP)
693     BlitScreenToBitmap_SP(target_bitmap);
694   else if (level.game_engine_type == GAME_ENGINE_TYPE_MM)
695     BlitScreenToBitmap_MM(target_bitmap);
696   else if (level.game_engine_type == GAME_ENGINE_TYPE_RND)
697     BlitScreenToBitmap_RND(target_bitmap);
698
699   redraw_mask |= REDRAW_FIELD;
700 }
701
702 static void DrawFramesPerSecond(void)
703 {
704   char text[100];
705   int font_nr = FONT_TEXT_2;
706   int font_width = getFontWidth(font_nr);
707   int draw_deactivation_mask = GetDrawDeactivationMask();
708   boolean draw_masked = (draw_deactivation_mask == REDRAW_NONE);
709
710   // draw FPS with leading space (needed if field buffer deactivated)
711   sprintf(text, " %04.1f fps", global.frames_per_second);
712
713   // override draw deactivation mask (required for invisible warp mode)
714   SetDrawDeactivationMask(REDRAW_NONE);
715
716   // draw opaque FPS if field buffer deactivated, else draw masked FPS
717   DrawTextExt(backbuffer, SX + SXSIZE - font_width * strlen(text), SY, text,
718               font_nr, (draw_masked ? BLIT_MASKED : BLIT_OPAQUE));
719
720   // set draw deactivation mask to previous value
721   SetDrawDeactivationMask(draw_deactivation_mask);
722
723   // force full-screen redraw in this frame
724   redraw_mask = REDRAW_ALL;
725 }
726
727 #if DEBUG_FRAME_TIME
728 static void PrintFrameTimeDebugging(void)
729 {
730   static unsigned int last_counter = 0;
731   unsigned int counter = Counter();
732   int diff_1 = counter - last_counter;
733   int diff_2 = diff_1 - GAME_FRAME_DELAY;
734   int diff_2_max = 20;
735   int diff_2_cut = MIN(ABS(diff_2), diff_2_max);
736   char diff_bar[2 * diff_2_max + 5];
737   int pos = 0;
738   int i;
739
740   diff_bar[pos++] = (diff_2 < -diff_2_max ? '<' : ' ');
741
742   for (i = 0; i < diff_2_max; i++)
743     diff_bar[pos++] = (diff_2 >= 0 ? ' ' :
744                        i >= diff_2_max - diff_2_cut ? '-' : ' ');
745
746   diff_bar[pos++] = '|';
747
748   for (i = 0; i < diff_2_max; i++)
749     diff_bar[pos++] = (diff_2 <= 0 ? ' ' : i < diff_2_cut ? '+' : ' ');
750
751   diff_bar[pos++] = (diff_2 > diff_2_max ? '>' : ' ');
752
753   diff_bar[pos++] = '\0';
754
755   Debug("time:frame", "%06d [%02d] [%c%02d] %s",
756         counter,
757         diff_1,
758         (diff_2 < 0 ? '-' : diff_2 > 0 ? '+' : ' '), ABS(diff_2),
759         diff_bar);
760
761   last_counter = counter;
762 }
763 #endif
764
765 static int unifiedRedrawMask(int mask)
766 {
767   if (mask & REDRAW_ALL)
768     return REDRAW_ALL;
769
770   if (mask & REDRAW_FIELD && mask & REDRAW_DOORS)
771     return REDRAW_ALL;
772
773   return mask;
774 }
775
776 static boolean equalRedrawMasks(int mask_1, int mask_2)
777 {
778   return unifiedRedrawMask(mask_1) == unifiedRedrawMask(mask_2);
779 }
780
781 void BackToFront(void)
782 {
783   static int last_redraw_mask = REDRAW_NONE;
784
785   // force screen redraw in every frame to continue drawing global animations
786   // (but always use the last redraw mask to prevent unwanted side effects)
787   if (redraw_mask == REDRAW_NONE)
788     redraw_mask = last_redraw_mask;
789
790   last_redraw_mask = redraw_mask;
791
792 #if 1
793   // masked border now drawn immediately when blitting backbuffer to window
794 #else
795   // draw masked border to all viewports, if defined
796   DrawMaskedBorder(redraw_mask);
797 #endif
798
799   // draw frames per second (only if debug mode is enabled)
800   if (redraw_mask & REDRAW_FPS)
801     DrawFramesPerSecond();
802
803   // remove playfield redraw before potentially merging with doors redraw
804   if (DrawingDeactivated(REAL_SX, REAL_SY, FULL_SXSIZE, FULL_SYSIZE))
805     redraw_mask &= ~REDRAW_FIELD;
806
807   // redraw complete window if both playfield and (some) doors need redraw
808   if (redraw_mask & REDRAW_FIELD && redraw_mask & REDRAW_DOORS)
809     redraw_mask = REDRAW_ALL;
810
811   /* although redrawing the whole window would be fine for normal gameplay,
812      being able to only redraw the playfield is required for deactivating
813      certain drawing areas (mainly playfield) to work, which is needed for
814      warp-forward to be fast enough (by skipping redraw of most frames) */
815
816   if (redraw_mask & REDRAW_ALL)
817   {
818     BlitBitmap(backbuffer, window, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
819   }
820   else if (redraw_mask & REDRAW_FIELD)
821   {
822     BlitBitmap(backbuffer, window,
823                REAL_SX, REAL_SY, FULL_SXSIZE, FULL_SYSIZE, REAL_SX, REAL_SY);
824   }
825   else if (redraw_mask & REDRAW_DOORS)
826   {
827     // merge door areas to prevent calling screen redraw more than once
828     int x1 = WIN_XSIZE;
829     int y1 = WIN_YSIZE;
830     int x2 = 0;
831     int y2 = 0;
832
833     if (redraw_mask & REDRAW_DOOR_1)
834     {
835       x1 = MIN(x1, DX);
836       y1 = MIN(y1, DY);
837       x2 = MAX(x2, DX + DXSIZE);
838       y2 = MAX(y2, DY + DYSIZE);
839     }
840
841     if (redraw_mask & REDRAW_DOOR_2)
842     {
843       x1 = MIN(x1, VX);
844       y1 = MIN(y1, VY);
845       x2 = MAX(x2, VX + VXSIZE);
846       y2 = MAX(y2, VY + VYSIZE);
847     }
848
849     if (redraw_mask & REDRAW_DOOR_3)
850     {
851       x1 = MIN(x1, EX);
852       y1 = MIN(y1, EY);
853       x2 = MAX(x2, EX + EXSIZE);
854       y2 = MAX(y2, EY + EYSIZE);
855     }
856
857     // make sure that at least one pixel is blitted, and inside the screen
858     // (else nothing is blitted, causing the animations not to be updated)
859     x1 = MIN(MAX(0, x1), WIN_XSIZE - 1);
860     y1 = MIN(MAX(0, y1), WIN_YSIZE - 1);
861     x2 = MIN(MAX(1, x2), WIN_XSIZE);
862     y2 = MIN(MAX(1, y2), WIN_YSIZE);
863
864     BlitBitmap(backbuffer, window, x1, y1, x2 - x1, y2 - y1, x1, y1);
865   }
866
867   redraw_mask = REDRAW_NONE;
868
869 #if DEBUG_FRAME_TIME
870   PrintFrameTimeDebugging();
871 #endif
872 }
873
874 void BackToFront_WithFrameDelay(unsigned int frame_delay_value)
875 {
876   unsigned int frame_delay_value_old = GetVideoFrameDelay();
877
878   SetVideoFrameDelay(frame_delay_value);
879
880   BackToFront();
881
882   SetVideoFrameDelay(frame_delay_value_old);
883 }
884
885 static int fade_type_skip = FADE_TYPE_NONE;
886
887 static void FadeExt(int fade_mask, int fade_mode, int fade_type)
888 {
889   void (*draw_border_function)(void) = NULL;
890   int x, y, width, height;
891   int fade_delay, post_delay;
892
893   if (fade_type == FADE_TYPE_FADE_OUT)
894   {
895     if (fade_type_skip != FADE_TYPE_NONE)
896     {
897       // skip all fade operations until specified fade operation
898       if (fade_type & fade_type_skip)
899         fade_type_skip = FADE_TYPE_NONE;
900
901       return;
902     }
903
904     if (fading.fade_mode & FADE_TYPE_TRANSFORM)
905       return;
906   }
907
908   redraw_mask |= fade_mask;
909
910   if (fade_type == FADE_TYPE_SKIP)
911   {
912     fade_type_skip = fade_mode;
913
914     return;
915   }
916
917   fade_delay = fading.fade_delay;
918   post_delay = (fade_mode == FADE_MODE_FADE_OUT ? fading.post_delay : 0);
919
920   if (fade_type_skip != FADE_TYPE_NONE)
921   {
922     // skip all fade operations until specified fade operation
923     if (fade_type & fade_type_skip)
924       fade_type_skip = FADE_TYPE_NONE;
925
926     fade_delay = 0;
927   }
928
929   if (global.autoplay_leveldir)
930   {
931     return;
932   }
933
934   if (fade_mask == REDRAW_FIELD)
935   {
936     x = FADE_SX;
937     y = FADE_SY;
938     width  = FADE_SXSIZE;
939     height = FADE_SYSIZE;
940
941     if (border.draw_masked_when_fading)
942       draw_border_function = DrawMaskedBorder_FIELD;    // update when fading
943     else
944       DrawMaskedBorder_FIELD();                         // draw once
945   }
946   else          // REDRAW_ALL
947   {
948     x = 0;
949     y = 0;
950     width  = WIN_XSIZE;
951     height = WIN_YSIZE;
952   }
953
954   // when switching screens without fading, set fade delay to zero
955   if (!setup.fade_screens || fading.fade_mode == FADE_MODE_NONE)
956     fade_delay = 0;
957
958   // do not display black frame when fading out without fade delay
959   if (fade_mode == FADE_MODE_FADE_OUT && fade_delay == 0)
960     return;
961
962   FadeRectangle(x, y, width, height, fade_mode, fade_delay, post_delay,
963                 draw_border_function);
964
965   redraw_mask &= ~fade_mask;
966
967   ClearAutoRepeatKeyEvents();
968 }
969
970 static void SetScreenStates_BeforeFadingIn(void)
971 {
972   // temporarily set screen mode for animations to screen after fading in
973   global.anim_status = global.anim_status_next;
974
975   // store backbuffer with all animations that will be started after fading in
976   PrepareFadeBitmap(DRAW_TO_FADE_TARGET);
977
978   // set screen mode for animations back to fading
979   global.anim_status = GAME_MODE_PSEUDO_FADING;
980 }
981
982 static void SetScreenStates_AfterFadingIn(void)
983 {
984   // store new source screen (to use correct masked border for fading)
985   gfx.fade_border_source_status = global.border_status;
986
987   global.anim_status = global.anim_status_next;
988 }
989
990 static void SetScreenStates_BeforeFadingOut(void)
991 {
992   // store new target screen (to use correct masked border for fading)
993   gfx.fade_border_target_status = game_status;
994
995   // set screen mode for animations to fading
996   global.anim_status = GAME_MODE_PSEUDO_FADING;
997
998   // store backbuffer with all animations that will be stopped for fading out
999   PrepareFadeBitmap(DRAW_TO_FADE_SOURCE);
1000 }
1001
1002 static void SetScreenStates_AfterFadingOut(void)
1003 {
1004   global.border_status = game_status;
1005 }
1006
1007 void FadeIn(int fade_mask)
1008 {
1009   SetScreenStates_BeforeFadingIn();
1010
1011 #if 1
1012   DrawMaskedBorder(REDRAW_ALL);
1013 #endif
1014
1015   if (fading.fade_mode & FADE_TYPE_TRANSFORM)
1016     FadeExt(fade_mask, fading.fade_mode, FADE_TYPE_FADE_IN);
1017   else
1018     FadeExt(fade_mask, FADE_MODE_FADE_IN, FADE_TYPE_FADE_IN);
1019
1020   FADE_SX = REAL_SX;
1021   FADE_SY = REAL_SY;
1022   FADE_SXSIZE = FULL_SXSIZE;
1023   FADE_SYSIZE = FULL_SYSIZE;
1024
1025   // activate virtual buttons depending on upcoming game status
1026   if (strEqual(setup.touch.control_type, TOUCH_CONTROL_VIRTUAL_BUTTONS) &&
1027       game_status == GAME_MODE_PLAYING && !tape.playing)
1028     SetOverlayActive(TRUE);
1029
1030   SetScreenStates_AfterFadingIn();
1031
1032   // force update of global animation status in case of rapid screen changes
1033   redraw_mask = REDRAW_ALL;
1034   BackToFront();
1035 }
1036
1037 void FadeOut(int fade_mask)
1038 {
1039   // update screen if areas covered by "fade_mask" and "redraw_mask" differ
1040   if (!equalRedrawMasks(fade_mask, redraw_mask) &&
1041       fade_type_skip != FADE_MODE_SKIP_FADE_OUT)
1042     BackToFront();
1043
1044   SetScreenStates_BeforeFadingOut();
1045
1046   SetTileCursorActive(FALSE);
1047   SetOverlayActive(FALSE);
1048
1049 #if 0
1050   DrawMaskedBorder(REDRAW_ALL);
1051 #endif
1052
1053   if (fading.fade_mode & FADE_TYPE_TRANSFORM)
1054     FadeExt(fade_mask, fading.fade_mode, FADE_TYPE_FADE_OUT);
1055   else
1056     FadeExt(fade_mask, FADE_MODE_FADE_OUT, FADE_TYPE_FADE_OUT);
1057
1058   SetScreenStates_AfterFadingOut();
1059 }
1060
1061 static void FadeSetLeaveNext(struct TitleFadingInfo fading_leave, boolean set)
1062 {
1063   static struct TitleFadingInfo fading_leave_stored;
1064
1065   if (set)
1066     fading_leave_stored = fading_leave;
1067   else
1068     fading = fading_leave_stored;
1069 }
1070
1071 void FadeSetEnterMenu(void)
1072 {
1073   fading = menu.enter_menu;
1074
1075   FadeSetLeaveNext(fading, TRUE);       // (keep same fade mode)
1076 }
1077
1078 void FadeSetLeaveMenu(void)
1079 {
1080   fading = menu.leave_menu;
1081
1082   FadeSetLeaveNext(fading, TRUE);       // (keep same fade mode)
1083 }
1084
1085 void FadeSetEnterScreen(void)
1086 {
1087   fading = menu.enter_screen[game_status];
1088
1089   FadeSetLeaveNext(menu.leave_screen[game_status], TRUE);       // store
1090 }
1091
1092 void FadeSetNextScreen(void)
1093 {
1094   fading = menu.next_screen[game_status];
1095
1096   // (do not overwrite fade mode set by FadeSetEnterScreen)
1097   // FadeSetLeaveNext(fading, TRUE);    // (keep same fade mode)
1098 }
1099
1100 void FadeSetLeaveScreen(void)
1101 {
1102   FadeSetLeaveNext(menu.leave_screen[game_status], FALSE);      // recall
1103 }
1104
1105 void FadeSetFromType(int type)
1106 {
1107   if (type & TYPE_ENTER_SCREEN)
1108     FadeSetEnterScreen();
1109   else if (type & TYPE_ENTER)
1110     FadeSetEnterMenu();
1111   else if (type & TYPE_LEAVE)
1112     FadeSetLeaveMenu();
1113 }
1114
1115 void FadeSetDisabled(void)
1116 {
1117   static struct TitleFadingInfo fading_none = { FADE_MODE_NONE, -1, -1, -1 };
1118
1119   fading = fading_none;
1120 }
1121
1122 void FadeSkipNextFadeIn(void)
1123 {
1124   FadeExt(0, FADE_MODE_SKIP_FADE_IN, FADE_TYPE_SKIP);
1125 }
1126
1127 void FadeSkipNextFadeOut(void)
1128 {
1129   FadeExt(0, FADE_MODE_SKIP_FADE_OUT, FADE_TYPE_SKIP);
1130 }
1131
1132 static Bitmap *getBitmapFromGraphicOrDefault(int graphic, int default_graphic)
1133 {
1134   if (graphic == IMG_UNDEFINED)
1135     return NULL;
1136
1137   boolean redefined = getImageListEntryFromImageID(graphic)->redefined;
1138
1139   return (graphic_info[graphic].bitmap != NULL || redefined ?
1140           graphic_info[graphic].bitmap :
1141           graphic_info[default_graphic].bitmap);
1142 }
1143
1144 static Bitmap *getBackgroundBitmap(int graphic)
1145 {
1146   return getBitmapFromGraphicOrDefault(graphic, IMG_BACKGROUND);
1147 }
1148
1149 static Bitmap *getGlobalBorderBitmap(int graphic)
1150 {
1151   return getBitmapFromGraphicOrDefault(graphic, IMG_GLOBAL_BORDER);
1152 }
1153
1154 Bitmap *getGlobalBorderBitmapFromStatus(int status)
1155 {
1156   int graphic =
1157     (status == GAME_MODE_MAIN ||
1158      status == GAME_MODE_PSEUDO_TYPENAME        ? IMG_GLOBAL_BORDER_MAIN :
1159      status == GAME_MODE_SCORES                 ? IMG_GLOBAL_BORDER_SCORES :
1160      status == GAME_MODE_EDITOR                 ? IMG_GLOBAL_BORDER_EDITOR :
1161      status == GAME_MODE_PLAYING                ? IMG_GLOBAL_BORDER_PLAYING :
1162      IMG_GLOBAL_BORDER);
1163
1164   return getGlobalBorderBitmap(graphic);
1165 }
1166
1167 void SetWindowBackgroundImageIfDefined(int graphic)
1168 {
1169   if (graphic_info[graphic].bitmap)
1170     SetWindowBackgroundBitmap(graphic_info[graphic].bitmap);
1171 }
1172
1173 void SetMainBackgroundImageIfDefined(int graphic)
1174 {
1175   if (graphic_info[graphic].bitmap)
1176     SetMainBackgroundBitmap(graphic_info[graphic].bitmap);
1177 }
1178
1179 void SetDoorBackgroundImageIfDefined(int graphic)
1180 {
1181   if (graphic_info[graphic].bitmap)
1182     SetDoorBackgroundBitmap(graphic_info[graphic].bitmap);
1183 }
1184
1185 void SetWindowBackgroundImage(int graphic)
1186 {
1187   SetWindowBackgroundBitmap(getBackgroundBitmap(graphic));
1188 }
1189
1190 void SetMainBackgroundImage(int graphic)
1191 {
1192   SetMainBackgroundBitmap(getBackgroundBitmap(graphic));
1193 }
1194
1195 void SetDoorBackgroundImage(int graphic)
1196 {
1197   SetDoorBackgroundBitmap(getBackgroundBitmap(graphic));
1198 }
1199
1200 void SetPanelBackground(void)
1201 {
1202   struct GraphicInfo *gfx = &graphic_info[IMG_BACKGROUND_PANEL];
1203
1204   BlitBitmapTiled(gfx->bitmap, bitmap_db_panel, gfx->src_x, gfx->src_y,
1205                   gfx->width, gfx->height, 0, 0, DXSIZE, DYSIZE);
1206
1207   SetDoorBackgroundBitmap(bitmap_db_panel);
1208 }
1209
1210 void DrawBackground(int x, int y, int width, int height)
1211 {
1212   // "drawto" might still point to playfield buffer here (hall of fame)
1213   ClearRectangleOnBackground(backbuffer, x, y, width, height);
1214
1215   if (IN_GFX_FIELD_FULL(x, y))
1216     redraw_mask |= REDRAW_FIELD;
1217   else if (IN_GFX_DOOR_1(x, y))
1218     redraw_mask |= REDRAW_DOOR_1;
1219   else if (IN_GFX_DOOR_2(x, y))
1220     redraw_mask |= REDRAW_DOOR_2;
1221   else if (IN_GFX_DOOR_3(x, y))
1222     redraw_mask |= REDRAW_DOOR_3;
1223 }
1224
1225 void DrawBackgroundForFont(int x, int y, int width, int height, int font_nr)
1226 {
1227   struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
1228
1229   if (font->bitmap == NULL)
1230     return;
1231
1232   DrawBackground(x, y, width, height);
1233 }
1234
1235 void DrawBackgroundForGraphic(int x, int y, int width, int height, int graphic)
1236 {
1237   struct GraphicInfo *g = &graphic_info[graphic];
1238
1239   if (g->bitmap == NULL)
1240     return;
1241
1242   DrawBackground(x, y, width, height);
1243 }
1244
1245 static int game_status_last = -1;
1246 static Bitmap *global_border_bitmap_last = NULL;
1247 static Bitmap *global_border_bitmap = NULL;
1248 static int real_sx_last = -1, real_sy_last = -1;
1249 static int full_sxsize_last = -1, full_sysize_last = -1;
1250 static int dx_last = -1, dy_last = -1;
1251 static int dxsize_last = -1, dysize_last = -1;
1252 static int vx_last = -1, vy_last = -1;
1253 static int vxsize_last = -1, vysize_last = -1;
1254 static int ex_last = -1, ey_last = -1;
1255 static int exsize_last = -1, eysize_last = -1;
1256
1257 boolean CheckIfGlobalBorderHasChanged(void)
1258 {
1259   // if game status has not changed, global border has not changed either
1260   if (game_status == game_status_last)
1261     return FALSE;
1262
1263   // determine and store new global border bitmap for current game status
1264   global_border_bitmap = getGlobalBorderBitmapFromStatus(game_status);
1265
1266   return (global_border_bitmap_last != global_border_bitmap);
1267 }
1268
1269 #define ONLY_REDRAW_GLOBAL_BORDER_IF_NEEDED             0
1270
1271 #if ONLY_REDRAW_GLOBAL_BORDER_IF_NEEDED
1272 static boolean CheckIfGlobalBorderRedrawIsNeeded(void)
1273 {
1274   // if game status has not changed, nothing has to be redrawn
1275   if (game_status == game_status_last)
1276     return FALSE;
1277
1278   // redraw if last screen was title screen
1279   if (game_status_last == GAME_MODE_TITLE)
1280     return TRUE;
1281
1282   // redraw if global screen border has changed
1283   if (CheckIfGlobalBorderHasChanged())
1284     return TRUE;
1285
1286   // redraw if position or size of playfield area has changed
1287   if (real_sx_last != REAL_SX || real_sy_last != REAL_SY ||
1288       full_sxsize_last != FULL_SXSIZE || full_sysize_last != FULL_SYSIZE)
1289     return TRUE;
1290
1291   // redraw if position or size of door area has changed
1292   if (dx_last != DX || dy_last != DY ||
1293       dxsize_last != DXSIZE || dysize_last != DYSIZE)
1294     return TRUE;
1295
1296   // redraw if position or size of tape area has changed
1297   if (vx_last != VX || vy_last != VY ||
1298       vxsize_last != VXSIZE || vysize_last != VYSIZE)
1299     return TRUE;
1300
1301   // redraw if position or size of editor area has changed
1302   if (ex_last != EX || ey_last != EY ||
1303       exsize_last != EXSIZE || eysize_last != EYSIZE)
1304     return TRUE;
1305
1306   return FALSE;
1307 }
1308 #endif
1309
1310 static void RedrawGlobalBorderFromBitmap(Bitmap *bitmap)
1311 {
1312   if (bitmap)
1313     BlitBitmap(bitmap, backbuffer, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
1314   else
1315     ClearRectangle(backbuffer, 0, 0, WIN_XSIZE, WIN_YSIZE);
1316 }
1317
1318 void RedrawGlobalBorder(void)
1319 {
1320   Bitmap *bitmap = getGlobalBorderBitmapFromStatus(game_status);
1321
1322   RedrawGlobalBorderFromBitmap(bitmap);
1323
1324   redraw_mask = REDRAW_ALL;
1325 }
1326
1327 static void RedrawGlobalBorderIfNeeded(void)
1328 {
1329 #if ONLY_REDRAW_GLOBAL_BORDER_IF_NEEDED
1330   if (game_status == game_status_last)
1331     return;
1332 #endif
1333
1334   // copy current draw buffer to later copy back areas that have not changed
1335   if (game_status_last != GAME_MODE_TITLE)
1336     BlitBitmap(backbuffer, bitmap_db_store_1, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
1337
1338 #if ONLY_REDRAW_GLOBAL_BORDER_IF_NEEDED
1339   if (CheckIfGlobalBorderRedrawIsNeeded())
1340 #else
1341   // determine and store new global border bitmap for current game status
1342   global_border_bitmap = getGlobalBorderBitmapFromStatus(game_status);
1343 #endif
1344   {
1345     // redraw global screen border (or clear, if defined to be empty)
1346     RedrawGlobalBorderFromBitmap(global_border_bitmap);
1347
1348     if (game_status == GAME_MODE_EDITOR)
1349       DrawSpecialEditorDoor();
1350
1351     // copy previous playfield and door areas, if they are defined on both
1352     // previous and current screen and if they still have the same size
1353
1354     if (real_sx_last != -1 && real_sy_last != -1 &&
1355         REAL_SX != -1 && REAL_SY != -1 &&
1356         full_sxsize_last == FULL_SXSIZE && full_sysize_last == FULL_SYSIZE)
1357       BlitBitmap(bitmap_db_store_1, backbuffer,
1358                  real_sx_last, real_sy_last, FULL_SXSIZE, FULL_SYSIZE,
1359                  REAL_SX, REAL_SY);
1360
1361     if (dx_last != -1 && dy_last != -1 &&
1362         DX != -1 && DY != -1 &&
1363         dxsize_last == DXSIZE && dysize_last == DYSIZE)
1364       BlitBitmap(bitmap_db_store_1, backbuffer,
1365                  dx_last, dy_last, DXSIZE, DYSIZE, DX, DY);
1366
1367     if (game_status != GAME_MODE_EDITOR)
1368     {
1369       if (vx_last != -1 && vy_last != -1 &&
1370           VX != -1 && VY != -1 &&
1371           vxsize_last == VXSIZE && vysize_last == VYSIZE)
1372         BlitBitmap(bitmap_db_store_1, backbuffer,
1373                    vx_last, vy_last, VXSIZE, VYSIZE, VX, VY);
1374     }
1375     else
1376     {
1377       if (ex_last != -1 && ey_last != -1 &&
1378           EX != -1 && EY != -1 &&
1379           exsize_last == EXSIZE && eysize_last == EYSIZE)
1380         BlitBitmap(bitmap_db_store_1, backbuffer,
1381                    ex_last, ey_last, EXSIZE, EYSIZE, EX, EY);
1382     }
1383
1384     redraw_mask = REDRAW_ALL;
1385   }
1386
1387   game_status_last = game_status;
1388
1389   global_border_bitmap_last = global_border_bitmap;
1390
1391   real_sx_last = REAL_SX;
1392   real_sy_last = REAL_SY;
1393   full_sxsize_last = FULL_SXSIZE;
1394   full_sysize_last = FULL_SYSIZE;
1395   dx_last = DX;
1396   dy_last = DY;
1397   dxsize_last = DXSIZE;
1398   dysize_last = DYSIZE;
1399   vx_last = VX;
1400   vy_last = VY;
1401   vxsize_last = VXSIZE;
1402   vysize_last = VYSIZE;
1403   ex_last = EX;
1404   ey_last = EY;
1405   exsize_last = EXSIZE;
1406   eysize_last = EYSIZE;
1407 }
1408
1409 void ClearField(void)
1410 {
1411   RedrawGlobalBorderIfNeeded();
1412
1413   // !!! "drawto" might still point to playfield buffer here (see above) !!!
1414   // (when entering hall of fame after playing)
1415   DrawBackground(REAL_SX, REAL_SY, FULL_SXSIZE, FULL_SYSIZE);
1416
1417   // !!! maybe this should be done before clearing the background !!!
1418   if (game_status == GAME_MODE_PLAYING)
1419   {
1420     ClearRectangle(fieldbuffer, 0, 0, FXSIZE, FYSIZE);
1421     SetDrawtoField(DRAW_TO_FIELDBUFFER);
1422   }
1423   else
1424   {
1425     SetDrawtoField(DRAW_TO_BACKBUFFER);
1426   }
1427 }
1428
1429 void MarkTileDirty(int x, int y)
1430 {
1431   redraw_mask |= REDRAW_FIELD;
1432 }
1433
1434 void SetBorderElement(void)
1435 {
1436   int x, y;
1437
1438   BorderElement = EL_EMPTY;
1439
1440   // only the R'n'D game engine may use an additional steelwall border
1441   if (level.game_engine_type != GAME_ENGINE_TYPE_RND)
1442     return;
1443
1444   for (y = 0; y < lev_fieldy && BorderElement == EL_EMPTY; y++)
1445   {
1446     for (x = 0; x < lev_fieldx; x++)
1447     {
1448       if (!IS_INDESTRUCTIBLE(Tile[x][y]))
1449         BorderElement = EL_STEELWALL;
1450
1451       if (y != 0 && y != lev_fieldy - 1 && x != lev_fieldx - 1)
1452         x = lev_fieldx - 2;
1453     }
1454   }
1455 }
1456
1457 void FloodFillLevelExt(int from_x, int from_y, int fill_element,
1458                        int max_array_fieldx, int max_array_fieldy,
1459                        short field[max_array_fieldx][max_array_fieldy],
1460                        int max_fieldx, int max_fieldy)
1461 {
1462   int i,x,y;
1463   int old_element;
1464   static int check[4][2] = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } };
1465   static int safety = 0;
1466
1467   // check if starting field still has the desired content
1468   if (field[from_x][from_y] == fill_element)
1469     return;
1470
1471   safety++;
1472
1473   if (safety > max_fieldx * max_fieldy)
1474     Fail("Something went wrong in 'FloodFill()'. Please debug.");
1475
1476   old_element = field[from_x][from_y];
1477   field[from_x][from_y] = fill_element;
1478
1479   for (i = 0; i < 4; i++)
1480   {
1481     x = from_x + check[i][0];
1482     y = from_y + check[i][1];
1483
1484     if (IN_FIELD(x, y, max_fieldx, max_fieldy) && field[x][y] == old_element)
1485       FloodFillLevelExt(x, y, fill_element, max_array_fieldx, max_array_fieldy,
1486                         field, max_fieldx, max_fieldy);
1487   }
1488
1489   safety--;
1490 }
1491
1492 void FloodFillLevel(int from_x, int from_y, int fill_element,
1493                     short field[MAX_LEV_FIELDX][MAX_LEV_FIELDY],
1494                     int max_fieldx, int max_fieldy)
1495 {
1496   FloodFillLevelExt(from_x, from_y, fill_element,
1497                     MAX_LEV_FIELDX, MAX_LEV_FIELDY, field,
1498                     max_fieldx, max_fieldy);
1499 }
1500
1501 void SetRandomAnimationValue(int x, int y)
1502 {
1503   gfx.anim_random_frame = GfxRandom[x][y];
1504 }
1505
1506 int getGraphicAnimationFrame(int graphic, int sync_frame)
1507 {
1508   // animation synchronized with global frame counter, not move position
1509   if (graphic_info[graphic].anim_global_sync || sync_frame < 0)
1510     sync_frame = FrameCounter;
1511
1512   return getAnimationFrame(graphic_info[graphic].anim_frames,
1513                            graphic_info[graphic].anim_delay,
1514                            graphic_info[graphic].anim_mode,
1515                            graphic_info[graphic].anim_start_frame,
1516                            sync_frame);
1517 }
1518
1519 void getGraphicSourceBitmap(int graphic, int tilesize, Bitmap **bitmap)
1520 {
1521   struct GraphicInfo *g = &graphic_info[graphic];
1522   int tilesize_capped = MIN(MAX(1, tilesize), TILESIZE);
1523
1524   if (tilesize == gfx.standard_tile_size)
1525     *bitmap = g->bitmaps[IMG_BITMAP_STANDARD];
1526   else if (tilesize == game.tile_size)
1527     *bitmap = g->bitmaps[IMG_BITMAP_GAME];
1528   else
1529     *bitmap = g->bitmaps[IMG_BITMAP_1x1 - log_2(tilesize_capped)];
1530 }
1531
1532 void getGraphicSourceXY(int graphic, int frame, int *x, int *y,
1533                         boolean get_backside)
1534 {
1535   struct GraphicInfo *g = &graphic_info[graphic];
1536   int src_x = g->src_x + (get_backside ? g->offset2_x : 0);
1537   int src_y = g->src_y + (get_backside ? g->offset2_y : 0);
1538
1539   if (g->offset_y == 0)         // frames are ordered horizontally
1540   {
1541     int max_width = g->anim_frames_per_line * g->width;
1542     int pos = (src_y / g->height) * max_width + src_x + frame * g->offset_x;
1543
1544     *x = pos % max_width;
1545     *y = src_y % g->height + pos / max_width * g->height;
1546   }
1547   else if (g->offset_x == 0)    // frames are ordered vertically
1548   {
1549     int max_height = g->anim_frames_per_line * g->height;
1550     int pos = (src_x / g->width) * max_height + src_y + frame * g->offset_y;
1551
1552     *x = src_x % g->width + pos / max_height * g->width;
1553     *y = pos % max_height;
1554   }
1555   else                          // frames are ordered diagonally
1556   {
1557     *x = src_x + frame * g->offset_x;
1558     *y = src_y + frame * g->offset_y;
1559   }
1560 }
1561
1562 void getSizedGraphicSourceExt(int graphic, int frame, int tilesize,
1563                               Bitmap **bitmap, int *x, int *y,
1564                               boolean get_backside)
1565 {
1566   struct GraphicInfo *g = &graphic_info[graphic];
1567
1568   // if no graphics defined at all, use fallback graphics
1569   if (g->bitmaps == NULL)
1570     *g = graphic_info[IMG_CHAR_EXCLAM];
1571
1572   // if no in-game graphics defined, always use standard graphic size
1573   if (g->bitmaps[IMG_BITMAP_GAME] == NULL)
1574     tilesize = TILESIZE;
1575
1576   getGraphicSourceBitmap(graphic, tilesize, bitmap);
1577   getGraphicSourceXY(graphic, frame, x, y, get_backside);
1578
1579   *x = *x * tilesize / g->tile_size;
1580   *y = *y * tilesize / g->tile_size;
1581 }
1582
1583 void getSizedGraphicSource(int graphic, int frame, int tilesize,
1584                            Bitmap **bitmap, int *x, int *y)
1585 {
1586   getSizedGraphicSourceExt(graphic, frame, tilesize, bitmap, x, y, FALSE);
1587 }
1588
1589 void getFixedGraphicSource(int graphic, int frame,
1590                            Bitmap **bitmap, int *x, int *y)
1591 {
1592   getSizedGraphicSourceExt(graphic, frame, TILESIZE, bitmap, x, y, FALSE);
1593 }
1594
1595 void getMiniGraphicSource(int graphic, Bitmap **bitmap, int *x, int *y)
1596 {
1597   getSizedGraphicSource(graphic, 0, MINI_TILESIZE, bitmap, x, y);
1598 }
1599
1600 static void getGraphicSourceExt(int graphic, int frame, Bitmap **bitmap,
1601                                 int *x, int *y, boolean get_backside)
1602 {
1603   getSizedGraphicSourceExt(graphic, frame, TILESIZE_VAR, bitmap, x, y,
1604                            get_backside);
1605 }
1606
1607 void getGraphicSource(int graphic, int frame, Bitmap **bitmap, int *x, int *y)
1608 {
1609   getGraphicSourceExt(graphic, frame, bitmap, x, y, FALSE);
1610 }
1611
1612 void DrawGraphic(int x, int y, int graphic, int frame)
1613 {
1614 #if DEBUG
1615   if (!IN_SCR_FIELD(x, y))
1616   {
1617     Debug("draw:DrawGraphic", "x = %d, y = %d, graphic = %d", x, y, graphic);
1618     Debug("draw:DrawGraphic", "This should never happen!");
1619
1620     return;
1621   }
1622 #endif
1623
1624   DrawGraphicExt(drawto_field, FX + x * TILEX_VAR, FY + y * TILEY_VAR, graphic,
1625                  frame);
1626
1627   MarkTileDirty(x, y);
1628 }
1629
1630 void DrawFixedGraphic(int x, int y, int graphic, int frame)
1631 {
1632 #if DEBUG
1633   if (!IN_SCR_FIELD(x, y))
1634   {
1635     Debug("draw:DrawFixedGraphic", "x = %d, y = %d, graphic = %d",
1636           x, y, graphic);
1637     Debug("draw:DrawFixedGraphic", "This should never happen!");
1638
1639     return;
1640   }
1641 #endif
1642
1643   DrawFixedGraphicExt(drawto_field, FX + x * TILEX, FY + y * TILEY, graphic,
1644                       frame);
1645   MarkTileDirty(x, y);
1646 }
1647
1648 void DrawGraphicExt(DrawBuffer *dst_bitmap, int x, int y, int graphic,
1649                     int frame)
1650 {
1651   Bitmap *src_bitmap;
1652   int src_x, src_y;
1653
1654   getGraphicSource(graphic, frame, &src_bitmap, &src_x, &src_y);
1655
1656   BlitBitmap(src_bitmap, dst_bitmap, src_x, src_y, TILEX_VAR, TILEY_VAR, x, y);
1657 }
1658
1659 void DrawFixedGraphicExt(DrawBuffer *dst_bitmap, int x, int y, int graphic,
1660                          int frame)
1661 {
1662   Bitmap *src_bitmap;
1663   int src_x, src_y;
1664
1665   getFixedGraphicSource(graphic, frame, &src_bitmap, &src_x, &src_y);
1666   BlitBitmap(src_bitmap, dst_bitmap, src_x, src_y, TILEX, TILEY, x, y);
1667 }
1668
1669 void DrawGraphicThruMask(int x, int y, int graphic, int frame)
1670 {
1671 #if DEBUG
1672   if (!IN_SCR_FIELD(x, y))
1673   {
1674     Debug("draw:DrawGraphicThruMask", "x = %d,y = %d, graphic = %d",
1675           x, y, graphic);
1676     Debug("draw:DrawGraphicThruMask", "This should never happen!");
1677
1678     return;
1679   }
1680 #endif
1681
1682   DrawGraphicThruMaskExt(drawto_field, FX + x * TILEX_VAR, FY + y * TILEY_VAR,
1683                          graphic, frame);
1684
1685   MarkTileDirty(x, y);
1686 }
1687
1688 void DrawFixedGraphicThruMask(int x, int y, int graphic, int frame)
1689 {
1690 #if DEBUG
1691   if (!IN_SCR_FIELD(x, y))
1692   {
1693     Debug("draw:DrawFixedGraphicThruMask", "x = %d,y = %d, graphic = %d",
1694           x, y, graphic);
1695     Debug("draw:DrawFixedGraphicThruMask", "This should never happen!");
1696
1697     return;
1698   }
1699 #endif
1700
1701   DrawFixedGraphicThruMaskExt(drawto_field, FX + x * TILEX, FY + y * TILEY,
1702                               graphic, frame);
1703   MarkTileDirty(x, y);
1704 }
1705
1706 void DrawGraphicThruMaskExt(DrawBuffer *d, int dst_x, int dst_y, int graphic,
1707                             int frame)
1708 {
1709   Bitmap *src_bitmap;
1710   int src_x, src_y;
1711
1712   getGraphicSource(graphic, frame, &src_bitmap, &src_x, &src_y);
1713
1714   BlitBitmapMasked(src_bitmap, d, src_x, src_y, TILEX_VAR, TILEY_VAR,
1715                    dst_x, dst_y);
1716 }
1717
1718 void DrawFixedGraphicThruMaskExt(DrawBuffer *d, int dst_x, int dst_y,
1719                                  int graphic, int frame)
1720 {
1721   Bitmap *src_bitmap;
1722   int src_x, src_y;
1723
1724   getFixedGraphicSource(graphic, frame, &src_bitmap, &src_x, &src_y);
1725
1726   BlitBitmapMasked(src_bitmap, d, src_x, src_y, TILEX, TILEY,
1727                    dst_x, dst_y);
1728 }
1729
1730 void DrawSizedGraphic(int x, int y, int graphic, int frame, int tilesize)
1731 {
1732   DrawSizedGraphicExt(drawto, SX + x * tilesize, SY + y * tilesize, graphic,
1733                       frame, tilesize);
1734   MarkTileDirty(x / tilesize, y / tilesize);
1735 }
1736
1737 void DrawSizedGraphicThruMask(int x, int y, int graphic, int frame,
1738                               int tilesize)
1739 {
1740   DrawSizedGraphicThruMaskExt(drawto, SX + x * tilesize, SY + y * tilesize,
1741                               graphic, frame, tilesize);
1742   MarkTileDirty(x / tilesize, y / tilesize);
1743 }
1744
1745 void DrawSizedGraphicExt(DrawBuffer *d, int x, int y, int graphic, int frame,
1746                          int tilesize)
1747 {
1748   Bitmap *src_bitmap;
1749   int src_x, src_y;
1750
1751   getSizedGraphicSource(graphic, frame, tilesize, &src_bitmap, &src_x, &src_y);
1752   BlitBitmap(src_bitmap, d, src_x, src_y, tilesize, tilesize, x, y);
1753 }
1754
1755 void DrawSizedGraphicThruMaskExt(DrawBuffer *d, int x, int y, int graphic,
1756                                  int frame, int tilesize)
1757 {
1758   Bitmap *src_bitmap;
1759   int src_x, src_y;
1760
1761   getSizedGraphicSource(graphic, frame, tilesize, &src_bitmap, &src_x, &src_y);
1762   BlitBitmapMasked(src_bitmap, d, src_x, src_y, tilesize, tilesize, x, y);
1763 }
1764
1765 void DrawMiniGraphic(int x, int y, int graphic)
1766 {
1767   DrawMiniGraphicExt(drawto, SX + x * MINI_TILEX,SY + y * MINI_TILEY, graphic);
1768   MarkTileDirty(x / 2, y / 2);
1769 }
1770
1771 void DrawMiniGraphicExt(DrawBuffer *d, int x, int y, int graphic)
1772 {
1773   Bitmap *src_bitmap;
1774   int src_x, src_y;
1775
1776   getMiniGraphicSource(graphic, &src_bitmap, &src_x, &src_y);
1777   BlitBitmap(src_bitmap, d, src_x, src_y, MINI_TILEX, MINI_TILEY, x, y);
1778 }
1779
1780 static void DrawGraphicShiftedNormal(int x, int y, int dx, int dy,
1781                                      int graphic, int frame,
1782                                      int cut_mode, int mask_mode)
1783 {
1784   Bitmap *src_bitmap;
1785   int src_x, src_y;
1786   int dst_x, dst_y;
1787   int width = TILEX, height = TILEY;
1788   int cx = 0, cy = 0;
1789
1790   if (dx || dy)                 // shifted graphic
1791   {
1792     if (x < BX1)                // object enters playfield from the left
1793     {
1794       x = BX1;
1795       width = dx;
1796       cx = TILEX - dx;
1797       dx = 0;
1798     }
1799     else if (x > BX2)           // object enters playfield from the right
1800     {
1801       x = BX2;
1802       width = -dx;
1803       dx = TILEX + dx;
1804     }
1805     else if (x == BX1 && dx < 0) // object leaves playfield to the left
1806     {
1807       width += dx;
1808       cx = -dx;
1809       dx = 0;
1810     }
1811     else if (x == BX2 && dx > 0) // object leaves playfield to the right
1812       width -= dx;
1813     else if (dx)                // general horizontal movement
1814       MarkTileDirty(x + SIGN(dx), y);
1815
1816     if (y < BY1)                // object enters playfield from the top
1817     {
1818       if (cut_mode == CUT_BELOW) // object completely above top border
1819         return;
1820
1821       y = BY1;
1822       height = dy;
1823       cy = TILEY - dy;
1824       dy = 0;
1825     }
1826     else if (y > BY2)           // object enters playfield from the bottom
1827     {
1828       y = BY2;
1829       height = -dy;
1830       dy = TILEY + dy;
1831     }
1832     else if (y == BY1 && dy < 0) // object leaves playfield to the top
1833     {
1834       height += dy;
1835       cy = -dy;
1836       dy = 0;
1837     }
1838     else if (dy > 0 && cut_mode == CUT_ABOVE)
1839     {
1840       if (y == BY2)             // object completely above bottom border
1841         return;
1842
1843       height = dy;
1844       cy = TILEY - dy;
1845       dy = TILEY;
1846       MarkTileDirty(x, y + 1);
1847     }                           // object leaves playfield to the bottom
1848     else if (dy > 0 && (y == BY2 || cut_mode == CUT_BELOW))
1849       height -= dy;
1850     else if (dy)                // general vertical movement
1851       MarkTileDirty(x, y + SIGN(dy));
1852   }
1853
1854 #if DEBUG
1855   if (!IN_SCR_FIELD(x, y))
1856   {
1857     Debug("draw:DrawGraphicShiftedNormal", "x = %d, y = %d, graphic = %d",
1858           x, y, graphic);
1859     Debug("draw:DrawGraphicShiftedNormal", "This should never happen!");
1860
1861     return;
1862   }
1863 #endif
1864
1865   width = width * TILESIZE_VAR / TILESIZE;
1866   height = height * TILESIZE_VAR / TILESIZE;
1867   cx = cx * TILESIZE_VAR / TILESIZE;
1868   cy = cy * TILESIZE_VAR / TILESIZE;
1869   dx = dx * TILESIZE_VAR / TILESIZE;
1870   dy = dy * TILESIZE_VAR / TILESIZE;
1871
1872   if (width > 0 && height > 0)
1873   {
1874     getGraphicSource(graphic, frame, &src_bitmap, &src_x, &src_y);
1875
1876     src_x += cx;
1877     src_y += cy;
1878
1879     dst_x = FX + x * TILEX_VAR + dx;
1880     dst_y = FY + y * TILEY_VAR + dy;
1881
1882     if (mask_mode == USE_MASKING)
1883       BlitBitmapMasked(src_bitmap, drawto_field, src_x, src_y, width, height,
1884                        dst_x, dst_y);
1885     else
1886       BlitBitmap(src_bitmap, drawto_field, src_x, src_y, width, height,
1887                  dst_x, dst_y);
1888
1889     MarkTileDirty(x, y);
1890   }
1891 }
1892
1893 static void DrawGraphicShiftedDouble(int x, int y, int dx, int dy,
1894                                      int graphic, int frame,
1895                                      int cut_mode, int mask_mode)
1896 {
1897   Bitmap *src_bitmap;
1898   int src_x, src_y;
1899   int dst_x, dst_y;
1900   int width = TILEX_VAR, height = TILEY_VAR;
1901   int x1 = x;
1902   int y1 = y;
1903   int x2 = x + SIGN(dx);
1904   int y2 = y + SIGN(dy);
1905
1906   // movement with two-tile animations must be sync'ed with movement position,
1907   // not with current GfxFrame (which can be higher when using slow movement)
1908   int anim_pos = (dx ? ABS(dx) : ABS(dy));
1909   int anim_frames = graphic_info[graphic].anim_frames;
1910
1911   // (we also need anim_delay here for movement animations with less frames)
1912   int anim_delay = graphic_info[graphic].anim_delay;
1913   int sync_frame = anim_pos * anim_frames * anim_delay / TILESIZE;
1914
1915   boolean draw_start_tile = (cut_mode != CUT_ABOVE);    // only for falling!
1916   boolean draw_end_tile   = (cut_mode != CUT_BELOW);    // only for falling!
1917
1918   // re-calculate animation frame for two-tile movement animation
1919   frame = getGraphicAnimationFrame(graphic, sync_frame);
1920
1921   // check if movement start graphic inside screen area and should be drawn
1922   if (draw_start_tile && IN_SCR_FIELD(x1, y1))
1923   {
1924     getGraphicSourceExt(graphic, frame, &src_bitmap, &src_x, &src_y, TRUE);
1925
1926     dst_x = FX + x1 * TILEX_VAR;
1927     dst_y = FY + y1 * TILEY_VAR;
1928
1929     if (mask_mode == USE_MASKING)
1930       BlitBitmapMasked(src_bitmap, drawto_field, src_x, src_y, width, height,
1931                        dst_x, dst_y);
1932     else
1933       BlitBitmap(src_bitmap, drawto_field, src_x, src_y, width, height,
1934                  dst_x, dst_y);
1935
1936     MarkTileDirty(x1, y1);
1937   }
1938
1939   // check if movement end graphic inside screen area and should be drawn
1940   if (draw_end_tile && IN_SCR_FIELD(x2, y2))
1941   {
1942     getGraphicSourceExt(graphic, frame, &src_bitmap, &src_x, &src_y, FALSE);
1943
1944     dst_x = FX + x2 * TILEX_VAR;
1945     dst_y = FY + y2 * TILEY_VAR;
1946
1947     if (mask_mode == USE_MASKING)
1948       BlitBitmapMasked(src_bitmap, drawto_field, src_x, src_y, width, height,
1949                        dst_x, dst_y);
1950     else
1951       BlitBitmap(src_bitmap, drawto_field, src_x, src_y, width, height,
1952                  dst_x, dst_y);
1953
1954     MarkTileDirty(x2, y2);
1955   }
1956 }
1957
1958 static void DrawGraphicShifted(int x, int y, int dx, int dy,
1959                                int graphic, int frame,
1960                                int cut_mode, int mask_mode)
1961 {
1962   if (graphic < 0)
1963   {
1964     DrawGraphic(x, y, graphic, frame);
1965
1966     return;
1967   }
1968
1969   if (graphic_info[graphic].double_movement)    // EM style movement images
1970     DrawGraphicShiftedDouble(x, y, dx, dy, graphic, frame, cut_mode,mask_mode);
1971   else
1972     DrawGraphicShiftedNormal(x, y, dx, dy, graphic, frame, cut_mode,mask_mode);
1973 }
1974
1975 static void DrawGraphicShiftedThruMask(int x, int y, int dx, int dy,
1976                                        int graphic, int frame, int cut_mode)
1977 {
1978   DrawGraphicShifted(x, y, dx, dy, graphic, frame, cut_mode, USE_MASKING);
1979 }
1980
1981 void DrawScreenElementExt(int x, int y, int dx, int dy, int element,
1982                           int cut_mode, int mask_mode)
1983 {
1984   int lx = LEVELX(x), ly = LEVELY(y);
1985   int graphic;
1986   int frame;
1987
1988   if (IN_LEV_FIELD(lx, ly))
1989   {
1990     SetRandomAnimationValue(lx, ly);
1991
1992     graphic = el_act_dir2img(element, GfxAction[lx][ly], GfxDir[lx][ly]);
1993     frame = getGraphicAnimationFrame(graphic, GfxFrame[lx][ly]);
1994
1995     // do not use double (EM style) movement graphic when not moving
1996     if (graphic_info[graphic].double_movement && !dx && !dy)
1997     {
1998       graphic = el_act_dir2img(element, ACTION_DEFAULT, GfxDir[lx][ly]);
1999       frame = getGraphicAnimationFrame(graphic, GfxFrame[lx][ly]);
2000     }
2001   }
2002   else  // border element
2003   {
2004     graphic = el2img(element);
2005     frame = getGraphicAnimationFrame(graphic, -1);
2006   }
2007
2008   if (element == EL_EXPANDABLE_WALL)
2009   {
2010     boolean left_stopped = FALSE, right_stopped = FALSE;
2011
2012     if (!IN_LEV_FIELD(lx - 1, ly) || IS_WALL(Tile[lx - 1][ly]))
2013       left_stopped = TRUE;
2014     if (!IN_LEV_FIELD(lx + 1, ly) || IS_WALL(Tile[lx + 1][ly]))
2015       right_stopped = TRUE;
2016
2017     if (left_stopped && right_stopped)
2018       graphic = IMG_WALL;
2019     else if (left_stopped)
2020     {
2021       graphic = IMG_EXPANDABLE_WALL_GROWING_RIGHT;
2022       frame = graphic_info[graphic].anim_frames - 1;
2023     }
2024     else if (right_stopped)
2025     {
2026       graphic = IMG_EXPANDABLE_WALL_GROWING_LEFT;
2027       frame = graphic_info[graphic].anim_frames - 1;
2028     }
2029   }
2030
2031   if (dx || dy)
2032     DrawGraphicShifted(x, y, dx, dy, graphic, frame, cut_mode, mask_mode);
2033   else if (mask_mode == USE_MASKING)
2034     DrawGraphicThruMask(x, y, graphic, frame);
2035   else
2036     DrawGraphic(x, y, graphic, frame);
2037 }
2038
2039 void DrawLevelElementExt(int x, int y, int dx, int dy, int element,
2040                          int cut_mode, int mask_mode)
2041 {
2042   if (IN_LEV_FIELD(x, y) && IN_SCR_FIELD(SCREENX(x), SCREENY(y)))
2043     DrawScreenElementExt(SCREENX(x), SCREENY(y), dx, dy, element,
2044                          cut_mode, mask_mode);
2045 }
2046
2047 void DrawScreenElementShifted(int x, int y, int dx, int dy, int element,
2048                               int cut_mode)
2049 {
2050   DrawScreenElementExt(x, y, dx, dy, element, cut_mode, NO_MASKING);
2051 }
2052
2053 void DrawLevelElementShifted(int x, int y, int dx, int dy, int element,
2054                              int cut_mode)
2055 {
2056   DrawLevelElementExt(x, y, dx, dy, element, cut_mode, NO_MASKING);
2057 }
2058
2059 void DrawLevelElementThruMask(int x, int y, int element)
2060 {
2061   DrawLevelElementExt(x, y, 0, 0, element, NO_CUTTING, USE_MASKING);
2062 }
2063
2064 void DrawLevelFieldThruMask(int x, int y)
2065 {
2066   DrawLevelElementExt(x, y, 0, 0, Tile[x][y], NO_CUTTING, USE_MASKING);
2067 }
2068
2069 // !!! implementation of quicksand is totally broken !!!
2070 #define IS_CRUMBLED_TILE(x, y, e)                                       \
2071         (GFX_CRUMBLED(e) && (!IN_LEV_FIELD(x, y) ||                     \
2072                              !IS_MOVING(x, y) ||                        \
2073                              (e) == EL_QUICKSAND_EMPTYING ||            \
2074                              (e) == EL_QUICKSAND_FAST_EMPTYING))
2075
2076 static void DrawLevelFieldCrumbledInnerCorners(int x, int y, int dx, int dy,
2077                                                int graphic)
2078 {
2079   Bitmap *src_bitmap;
2080   int src_x, src_y;
2081   int width, height, cx, cy;
2082   int sx = SCREENX(x), sy = SCREENY(y);
2083   int crumbled_border_size = graphic_info[graphic].border_size;
2084   int crumbled_tile_size = graphic_info[graphic].tile_size;
2085   int crumbled_border_size_var =
2086     crumbled_border_size * TILESIZE_VAR / crumbled_tile_size;
2087   int i;
2088
2089   getGraphicSource(graphic, 0, &src_bitmap, &src_x, &src_y);
2090
2091   for (i = 1; i < 4; i++)
2092   {
2093     int dxx = (i & 1 ? dx : 0);
2094     int dyy = (i & 2 ? dy : 0);
2095     int xx = x + dxx;
2096     int yy = y + dyy;
2097     int element = (IN_LEV_FIELD(xx, yy) ? TILE_GFX_ELEMENT(xx, yy) :
2098                    BorderElement);
2099
2100     // check if neighbour field is of same crumble type
2101     boolean same = (IS_CRUMBLED_TILE(xx, yy, element) &&
2102                     graphic_info[graphic].class ==
2103                     graphic_info[el_act2crm(element, ACTION_DEFAULT)].class);
2104
2105     // return if check prevents inner corner
2106     if (same == (dxx == dx && dyy == dy))
2107       return;
2108   }
2109
2110   // if we reach this point, we have an inner corner
2111
2112   getGraphicSource(graphic, 1, &src_bitmap, &src_x, &src_y);
2113
2114   width  = crumbled_border_size_var;
2115   height = crumbled_border_size_var;
2116   cx = (dx > 0 ? TILESIZE_VAR - width  : 0);
2117   cy = (dy > 0 ? TILESIZE_VAR - height : 0);
2118
2119   BlitBitmap(src_bitmap, drawto_field, src_x + cx, src_y + cy,
2120              width, height, FX + sx * TILEX_VAR + cx, FY + sy * TILEY_VAR + cy);
2121 }
2122
2123 static void DrawLevelFieldCrumbledBorders(int x, int y, int graphic, int frame,
2124                                           int dir)
2125 {
2126   Bitmap *src_bitmap;
2127   int src_x, src_y;
2128   int width, height, bx, by, cx, cy;
2129   int sx = SCREENX(x), sy = SCREENY(y);
2130   int crumbled_border_size = graphic_info[graphic].border_size;
2131   int crumbled_tile_size = graphic_info[graphic].tile_size;
2132   int crumbled_border_size_var =
2133     crumbled_border_size * TILESIZE_VAR / crumbled_tile_size;
2134   int crumbled_border_pos_var = TILESIZE_VAR - crumbled_border_size_var;
2135   int i;
2136
2137   getGraphicSource(graphic, frame, &src_bitmap, &src_x, &src_y);
2138
2139   // draw simple, sloppy, non-corner-accurate crumbled border
2140
2141   width  = (dir == 1 || dir == 2 ? crumbled_border_size_var : TILESIZE_VAR);
2142   height = (dir == 0 || dir == 3 ? crumbled_border_size_var : TILESIZE_VAR);
2143   cx = (dir == 2 ? crumbled_border_pos_var : 0);
2144   cy = (dir == 3 ? crumbled_border_pos_var : 0);
2145
2146   BlitBitmap(src_bitmap, drawto_field, src_x + cx, src_y + cy, width, height,
2147              FX + sx * TILEX_VAR + cx,
2148              FY + sy * TILEY_VAR + cy);
2149
2150   // (remaining middle border part must be at least as big as corner part)
2151   if (!(graphic_info[graphic].style & STYLE_ACCURATE_BORDERS) ||
2152       crumbled_border_size_var >= TILESIZE_VAR / 3)
2153     return;
2154
2155   // correct corners of crumbled border, if needed
2156
2157   for (i = -1; i <= 1; i += 2)
2158   {
2159     int xx = x + (dir == 0 || dir == 3 ? i : 0);
2160     int yy = y + (dir == 1 || dir == 2 ? i : 0);
2161     int element = (IN_LEV_FIELD(xx, yy) ? TILE_GFX_ELEMENT(xx, yy) :
2162                    BorderElement);
2163
2164     // check if neighbour field is of same crumble type
2165     if (IS_CRUMBLED_TILE(xx, yy, element) &&
2166         graphic_info[graphic].class ==
2167         graphic_info[el_act2crm(element, ACTION_DEFAULT)].class)
2168     {
2169       // no crumbled corner, but continued crumbled border
2170
2171       int c1 = (dir == 2 || dir == 3 ? crumbled_border_pos_var : 0);
2172       int c2 = (i == 1 ? crumbled_border_pos_var : 0);
2173       int b1 = (i == 1 ? crumbled_border_size_var :
2174                 TILESIZE_VAR - 2 * crumbled_border_size_var);
2175
2176       width  = crumbled_border_size_var;
2177       height = crumbled_border_size_var;
2178
2179       if (dir == 1 || dir == 2)
2180       {
2181         cx = c1;
2182         cy = c2;
2183         bx = cx;
2184         by = b1;
2185       }
2186       else
2187       {
2188         cx = c2;
2189         cy = c1;
2190         bx = b1;
2191         by = cy;
2192       }
2193
2194       BlitBitmap(src_bitmap, drawto_field, src_x + bx, src_y + by,
2195                  width, height,
2196                  FX + sx * TILEX_VAR + cx,
2197                  FY + sy * TILEY_VAR + cy);
2198     }
2199   }
2200 }
2201
2202 static void DrawLevelFieldCrumbledExt(int x, int y, int graphic, int frame)
2203 {
2204   int sx = SCREENX(x), sy = SCREENY(y);
2205   int element;
2206   int i;
2207   static int xy[4][2] =
2208   {
2209     { 0, -1 },
2210     { -1, 0 },
2211     { +1, 0 },
2212     { 0, +1 }
2213   };
2214
2215   if (!IN_LEV_FIELD(x, y))
2216     return;
2217
2218   element = TILE_GFX_ELEMENT(x, y);
2219
2220   if (IS_CRUMBLED_TILE(x, y, element))          // crumble field itself
2221   {
2222     if (!IN_SCR_FIELD(sx, sy))
2223       return;
2224
2225     // crumble field borders towards direct neighbour fields
2226     for (i = 0; i < 4; i++)
2227     {
2228       int xx = x + xy[i][0];
2229       int yy = y + xy[i][1];
2230
2231       element = (IN_LEV_FIELD(xx, yy) ? TILE_GFX_ELEMENT(xx, yy) :
2232                  BorderElement);
2233
2234       // check if neighbour field is of same crumble type
2235       if (IS_CRUMBLED_TILE(xx, yy, element) &&
2236           graphic_info[graphic].class ==
2237           graphic_info[el_act2crm(element, ACTION_DEFAULT)].class)
2238         continue;
2239
2240       DrawLevelFieldCrumbledBorders(x, y, graphic, frame, i);
2241     }
2242
2243     // crumble inner field corners towards corner neighbour fields
2244     if ((graphic_info[graphic].style & STYLE_INNER_CORNERS) &&
2245         graphic_info[graphic].anim_frames == 2)
2246     {
2247       for (i = 0; i < 4; i++)
2248       {
2249         int dx = (i & 1 ? +1 : -1);
2250         int dy = (i & 2 ? +1 : -1);
2251
2252         DrawLevelFieldCrumbledInnerCorners(x, y, dx, dy, graphic);
2253       }
2254     }
2255
2256     MarkTileDirty(sx, sy);
2257   }
2258   else          // center field is not crumbled -- crumble neighbour fields
2259   {
2260     // crumble field borders of direct neighbour fields
2261     for (i = 0; i < 4; i++)
2262     {
2263       int xx = x + xy[i][0];
2264       int yy = y + xy[i][1];
2265       int sxx = sx + xy[i][0];
2266       int syy = sy + xy[i][1];
2267
2268       if (!IN_LEV_FIELD(xx, yy) ||
2269           !IN_SCR_FIELD(sxx, syy))
2270         continue;
2271
2272       // do not crumble fields that are being digged or snapped
2273       if (Tile[xx][yy] == EL_EMPTY ||
2274           Tile[xx][yy] == EL_ELEMENT_SNAPPING)
2275         continue;
2276
2277       element = TILE_GFX_ELEMENT(xx, yy);
2278
2279       if (!IS_CRUMBLED_TILE(xx, yy, element))
2280         continue;
2281
2282       graphic = el_act2crm(element, ACTION_DEFAULT);
2283
2284       DrawLevelFieldCrumbledBorders(xx, yy, graphic, 0, 3 - i);
2285
2286       MarkTileDirty(sxx, syy);
2287     }
2288
2289     // crumble inner field corners of corner neighbour fields
2290     for (i = 0; i < 4; i++)
2291     {
2292       int dx = (i & 1 ? +1 : -1);
2293       int dy = (i & 2 ? +1 : -1);
2294       int xx = x + dx;
2295       int yy = y + dy;
2296       int sxx = sx + dx;
2297       int syy = sy + dy;
2298
2299       if (!IN_LEV_FIELD(xx, yy) ||
2300           !IN_SCR_FIELD(sxx, syy))
2301         continue;
2302
2303       if (Tile[xx][yy] == EL_ELEMENT_SNAPPING)
2304         continue;
2305
2306       element = TILE_GFX_ELEMENT(xx, yy);
2307
2308       if (!IS_CRUMBLED_TILE(xx, yy, element))
2309         continue;
2310
2311       graphic = el_act2crm(element, ACTION_DEFAULT);
2312
2313       if ((graphic_info[graphic].style & STYLE_INNER_CORNERS) &&
2314           graphic_info[graphic].anim_frames == 2)
2315         DrawLevelFieldCrumbledInnerCorners(xx, yy, -dx, -dy, graphic);
2316
2317       MarkTileDirty(sxx, syy);
2318     }
2319   }
2320 }
2321
2322 void DrawLevelFieldCrumbled(int x, int y)
2323 {
2324   int graphic;
2325
2326   if (!IN_LEV_FIELD(x, y))
2327     return;
2328
2329   if (Tile[x][y] == EL_ELEMENT_SNAPPING &&
2330       GfxElement[x][y] != EL_UNDEFINED &&
2331       GFX_CRUMBLED(GfxElement[x][y]))
2332   {
2333     DrawLevelFieldCrumbledDigging(x, y, GfxDir[x][y], GfxFrame[x][y]);
2334
2335     return;
2336   }
2337
2338   graphic = el_act2crm(TILE_GFX_ELEMENT(x, y), ACTION_DEFAULT);
2339
2340   DrawLevelFieldCrumbledExt(x, y, graphic, 0);
2341 }
2342
2343 void DrawLevelFieldCrumbledDigging(int x, int y, int direction,
2344                                    int step_frame)
2345 {
2346   int graphic1 = el_act_dir2img(GfxElement[x][y], ACTION_DIGGING, direction);
2347   int graphic2 = el_act_dir2crm(GfxElement[x][y], ACTION_DIGGING, direction);
2348   int frame1 = getGraphicAnimationFrame(graphic1, step_frame);
2349   int frame2 = getGraphicAnimationFrame(graphic2, step_frame);
2350   int sx = SCREENX(x), sy = SCREENY(y);
2351
2352   DrawGraphic(sx, sy, graphic1, frame1);
2353   DrawLevelFieldCrumbledExt(x, y, graphic2, frame2);
2354 }
2355
2356 void DrawLevelFieldCrumbledNeighbours(int x, int y)
2357 {
2358   int sx = SCREENX(x), sy = SCREENY(y);
2359   static int xy[4][2] =
2360   {
2361     { 0, -1 },
2362     { -1, 0 },
2363     { +1, 0 },
2364     { 0, +1 }
2365   };
2366   int i;
2367
2368   // crumble direct neighbour fields (required for field borders)
2369   for (i = 0; i < 4; i++)
2370   {
2371     int xx = x + xy[i][0];
2372     int yy = y + xy[i][1];
2373     int sxx = sx + xy[i][0];
2374     int syy = sy + xy[i][1];
2375
2376     if (!IN_LEV_FIELD(xx, yy) ||
2377         !IN_SCR_FIELD(sxx, syy) ||
2378         !GFX_CRUMBLED(Tile[xx][yy]) ||
2379         IS_MOVING(xx, yy))
2380       continue;
2381
2382     DrawLevelField(xx, yy);
2383   }
2384
2385   // crumble corner neighbour fields (required for inner field corners)
2386   for (i = 0; i < 4; i++)
2387   {
2388     int dx = (i & 1 ? +1 : -1);
2389     int dy = (i & 2 ? +1 : -1);
2390     int xx = x + dx;
2391     int yy = y + dy;
2392     int sxx = sx + dx;
2393     int syy = sy + dy;
2394
2395     if (!IN_LEV_FIELD(xx, yy) ||
2396         !IN_SCR_FIELD(sxx, syy) ||
2397         !GFX_CRUMBLED(Tile[xx][yy]) ||
2398         IS_MOVING(xx, yy))
2399       continue;
2400
2401     int element = TILE_GFX_ELEMENT(xx, yy);
2402     int graphic = el_act2crm(element, ACTION_DEFAULT);
2403
2404     if ((graphic_info[graphic].style & STYLE_INNER_CORNERS) &&
2405         graphic_info[graphic].anim_frames == 2)
2406       DrawLevelField(xx, yy);
2407   }
2408 }
2409
2410 static int getBorderElement(int x, int y)
2411 {
2412   int border[7][2] =
2413   {
2414     { EL_STEELWALL_TOPLEFT,             EL_INVISIBLE_STEELWALL_TOPLEFT     },
2415     { EL_STEELWALL_TOPRIGHT,            EL_INVISIBLE_STEELWALL_TOPRIGHT    },
2416     { EL_STEELWALL_BOTTOMLEFT,          EL_INVISIBLE_STEELWALL_BOTTOMLEFT  },
2417     { EL_STEELWALL_BOTTOMRIGHT,         EL_INVISIBLE_STEELWALL_BOTTOMRIGHT },
2418     { EL_STEELWALL_VERTICAL,            EL_INVISIBLE_STEELWALL_VERTICAL    },
2419     { EL_STEELWALL_HORIZONTAL,          EL_INVISIBLE_STEELWALL_HORIZONTAL  },
2420     { EL_STEELWALL,                     EL_INVISIBLE_STEELWALL             }
2421   };
2422   int steel_type = (BorderElement == EL_STEELWALL ? 0 : 1);
2423   int steel_position = (x == -1         && y == -1              ? 0 :
2424                         x == lev_fieldx && y == -1              ? 1 :
2425                         x == -1         && y == lev_fieldy      ? 2 :
2426                         x == lev_fieldx && y == lev_fieldy      ? 3 :
2427                         x == -1         || x == lev_fieldx      ? 4 :
2428                         y == -1         || y == lev_fieldy      ? 5 : 6);
2429
2430   return border[steel_position][steel_type];
2431 }
2432
2433 void DrawScreenElement(int x, int y, int element)
2434 {
2435   DrawScreenElementExt(x, y, 0, 0, element, NO_CUTTING, NO_MASKING);
2436   DrawLevelFieldCrumbled(LEVELX(x), LEVELY(y));
2437 }
2438
2439 void DrawLevelElement(int x, int y, int element)
2440 {
2441   if (IN_LEV_FIELD(x, y) && IN_SCR_FIELD(SCREENX(x), SCREENY(y)))
2442     DrawScreenElement(SCREENX(x), SCREENY(y), element);
2443 }
2444
2445 void DrawScreenField(int x, int y)
2446 {
2447   int lx = LEVELX(x), ly = LEVELY(y);
2448   int element, content;
2449
2450   if (!IN_LEV_FIELD(lx, ly))
2451   {
2452     if (lx < -1 || lx > lev_fieldx || ly < -1 || ly > lev_fieldy)
2453       element = EL_EMPTY;
2454     else
2455       element = getBorderElement(lx, ly);
2456
2457     DrawScreenElement(x, y, element);
2458
2459     return;
2460   }
2461
2462   element = Tile[lx][ly];
2463   content = Store[lx][ly];
2464
2465   if (IS_MOVING(lx, ly))
2466   {
2467     int horiz_move = (MovDir[lx][ly] == MV_LEFT || MovDir[lx][ly] == MV_RIGHT);
2468     boolean cut_mode = NO_CUTTING;
2469
2470     if (element == EL_QUICKSAND_EMPTYING ||
2471         element == EL_QUICKSAND_FAST_EMPTYING ||
2472         element == EL_MAGIC_WALL_EMPTYING ||
2473         element == EL_BD_MAGIC_WALL_EMPTYING ||
2474         element == EL_DC_MAGIC_WALL_EMPTYING ||
2475         element == EL_AMOEBA_DROPPING)
2476       cut_mode = CUT_ABOVE;
2477     else if (element == EL_QUICKSAND_FILLING ||
2478              element == EL_QUICKSAND_FAST_FILLING ||
2479              element == EL_MAGIC_WALL_FILLING ||
2480              element == EL_BD_MAGIC_WALL_FILLING ||
2481              element == EL_DC_MAGIC_WALL_FILLING)
2482       cut_mode = CUT_BELOW;
2483
2484     if (cut_mode == CUT_ABOVE)
2485       DrawScreenElement(x, y, element);
2486     else
2487       DrawScreenElement(x, y, EL_EMPTY);
2488
2489     if (horiz_move)
2490       DrawScreenElementShifted(x, y, MovPos[lx][ly], 0, element, NO_CUTTING);
2491     else if (cut_mode == NO_CUTTING)
2492       DrawScreenElementShifted(x, y, 0, MovPos[lx][ly], element, cut_mode);
2493     else
2494     {
2495       DrawScreenElementShifted(x, y, 0, MovPos[lx][ly], content, cut_mode);
2496
2497       if (cut_mode == CUT_BELOW &&
2498           IN_LEV_FIELD(lx, ly + 1) && IN_SCR_FIELD(x, y + 1))
2499         DrawLevelElement(lx, ly + 1, element);
2500     }
2501
2502     if (content == EL_ACID)
2503     {
2504       int dir = MovDir[lx][ly];
2505       int newlx = lx + (dir == MV_LEFT ? -1 : dir == MV_RIGHT ? +1 : 0);
2506       int newly = ly + (dir == MV_UP   ? -1 : dir == MV_DOWN  ? +1 : 0);
2507
2508       DrawLevelElementThruMask(newlx, newly, EL_ACID);
2509
2510       // prevent target field from being drawn again (but without masking)
2511       // (this would happen if target field is scanned after moving element)
2512       Stop[newlx][newly] = TRUE;
2513     }
2514   }
2515   else if (IS_BLOCKED(lx, ly))
2516   {
2517     int oldx, oldy;
2518     int sx, sy;
2519     int horiz_move;
2520     boolean cut_mode = NO_CUTTING;
2521     int element_old, content_old;
2522
2523     Blocked2Moving(lx, ly, &oldx, &oldy);
2524     sx = SCREENX(oldx);
2525     sy = SCREENY(oldy);
2526     horiz_move = (MovDir[oldx][oldy] == MV_LEFT ||
2527                   MovDir[oldx][oldy] == MV_RIGHT);
2528
2529     element_old = Tile[oldx][oldy];
2530     content_old = Store[oldx][oldy];
2531
2532     if (element_old == EL_QUICKSAND_EMPTYING ||
2533         element_old == EL_QUICKSAND_FAST_EMPTYING ||
2534         element_old == EL_MAGIC_WALL_EMPTYING ||
2535         element_old == EL_BD_MAGIC_WALL_EMPTYING ||
2536         element_old == EL_DC_MAGIC_WALL_EMPTYING ||
2537         element_old == EL_AMOEBA_DROPPING)
2538       cut_mode = CUT_ABOVE;
2539
2540     DrawScreenElement(x, y, EL_EMPTY);
2541
2542     if (horiz_move)
2543       DrawScreenElementShifted(sx, sy, MovPos[oldx][oldy], 0, element_old,
2544                                NO_CUTTING);
2545     else if (cut_mode == NO_CUTTING)
2546       DrawScreenElementShifted(sx, sy, 0, MovPos[oldx][oldy], element_old,
2547                                cut_mode);
2548     else
2549       DrawScreenElementShifted(sx, sy, 0, MovPos[oldx][oldy], content_old,
2550                                cut_mode);
2551   }
2552   else if (IS_DRAWABLE(element))
2553     DrawScreenElement(x, y, element);
2554   else
2555     DrawScreenElement(x, y, EL_EMPTY);
2556 }
2557
2558 void DrawLevelField(int x, int y)
2559 {
2560   if (IN_SCR_FIELD(SCREENX(x), SCREENY(y)))
2561     DrawScreenField(SCREENX(x), SCREENY(y));
2562   else if (IS_MOVING(x, y))
2563   {
2564     int newx,newy;
2565
2566     Moving2Blocked(x, y, &newx, &newy);
2567     if (IN_SCR_FIELD(SCREENX(newx), SCREENY(newy)))
2568       DrawScreenField(SCREENX(newx), SCREENY(newy));
2569   }
2570   else if (IS_BLOCKED(x, y))
2571   {
2572     int oldx, oldy;
2573
2574     Blocked2Moving(x, y, &oldx, &oldy);
2575     if (IN_SCR_FIELD(SCREENX(oldx), SCREENY(oldy)))
2576       DrawScreenField(SCREENX(oldx), SCREENY(oldy));
2577   }
2578 }
2579
2580 static void DrawSizedWallExt_MM(int dst_x, int dst_y, int element, int tilesize,
2581                                 int (*el2img_function)(int), boolean masked,
2582                                 int element_bits_draw)
2583 {
2584   int element_base = map_mm_wall_element(element);
2585   int element_bits = (IS_DF_WALL(element) ?
2586                       element - EL_DF_WALL_START :
2587                       IS_MM_WALL(element) ?
2588                       element - EL_MM_WALL_START : EL_EMPTY) & 0x000f;
2589   int graphic = el2img_function(element_base);
2590   int tilesize_draw = tilesize / 2;
2591   Bitmap *src_bitmap;
2592   int src_x, src_y;
2593   int i;
2594
2595   getSizedGraphicSource(graphic, 0, tilesize_draw, &src_bitmap, &src_x, &src_y);
2596
2597   for (i = 0; i < 4; i++)
2598   {
2599     int dst_draw_x = dst_x + (i % 2) * tilesize_draw;
2600     int dst_draw_y = dst_y + (i / 2) * tilesize_draw;
2601
2602     if (!(element_bits_draw & (1 << i)))
2603       continue;
2604
2605     if (element_bits & (1 << i))
2606     {
2607       if (masked)
2608         BlitBitmapMasked(src_bitmap, drawto, src_x, src_y,
2609                          tilesize_draw, tilesize_draw, dst_draw_x, dst_draw_y);
2610       else
2611         BlitBitmap(src_bitmap, drawto, src_x, src_y,
2612                    tilesize_draw, tilesize_draw, dst_draw_x, dst_draw_y);
2613     }
2614     else
2615     {
2616       if (!masked)
2617         ClearRectangle(drawto, dst_draw_x, dst_draw_y,
2618                        tilesize_draw, tilesize_draw);
2619     }
2620   }
2621 }
2622
2623 void DrawSizedWallParts_MM(int x, int y, int element, int tilesize,
2624                            boolean masked, int element_bits_draw)
2625 {
2626   DrawSizedWallExt_MM(SX + x * tilesize, SY + y * tilesize,
2627                       element, tilesize, el2edimg, masked, element_bits_draw);
2628 }
2629
2630 static void DrawSizedWall_MM(int dst_x, int dst_y, int element, int tilesize,
2631                              int (*el2img_function)(int))
2632 {
2633   DrawSizedWallExt_MM(dst_x, dst_y, element, tilesize, el2img_function, FALSE,
2634                       0x000f);
2635 }
2636
2637 static void DrawSizedElementExt(int x, int y, int element, int tilesize,
2638                                 boolean masked)
2639 {
2640   if (IS_MM_WALL(element))
2641   {
2642     DrawSizedWallExt_MM(SX + x * tilesize, SY + y * tilesize,
2643                         element, tilesize, el2edimg, masked, 0x000f);
2644   }
2645   else
2646   {
2647     int graphic = el2edimg(element);
2648
2649     if (masked)
2650       DrawSizedGraphicThruMask(x, y, graphic, 0, tilesize);
2651     else
2652       DrawSizedGraphic(x, y, graphic, 0, tilesize);
2653   }
2654 }
2655
2656 void DrawSizedElement(int x, int y, int element, int tilesize)
2657 {
2658   DrawSizedElementExt(x, y, element, tilesize, FALSE);
2659 }
2660
2661 void DrawSizedElementThruMask(int x, int y, int element, int tilesize)
2662 {
2663   DrawSizedElementExt(x, y, element, tilesize, TRUE);
2664 }
2665
2666 void DrawMiniElement(int x, int y, int element)
2667 {
2668   int graphic;
2669
2670   graphic = el2edimg(element);
2671   DrawMiniGraphic(x, y, graphic);
2672 }
2673
2674 void DrawSizedElementOrWall(int sx, int sy, int scroll_x, int scroll_y,
2675                             int tilesize)
2676 {
2677   int x = sx + scroll_x, y = sy + scroll_y;
2678
2679   if (x < -1 || x > lev_fieldx || y < -1 || y > lev_fieldy)
2680     DrawSizedElement(sx, sy, EL_EMPTY, tilesize);
2681   else if (x > -1 && x < lev_fieldx && y > -1 && y < lev_fieldy)
2682     DrawSizedElement(sx, sy, Tile[x][y], tilesize);
2683   else
2684     DrawSizedGraphic(sx, sy, el2edimg(getBorderElement(x, y)), 0, tilesize);
2685 }
2686
2687 void DrawMiniElementOrWall(int sx, int sy, int scroll_x, int scroll_y)
2688 {
2689   int x = sx + scroll_x, y = sy + scroll_y;
2690
2691   if (x < -1 || x > lev_fieldx || y < -1 || y > lev_fieldy)
2692     DrawMiniElement(sx, sy, EL_EMPTY);
2693   else if (x > -1 && x < lev_fieldx && y > -1 && y < lev_fieldy)
2694     DrawMiniElement(sx, sy, Tile[x][y]);
2695   else
2696     DrawMiniGraphic(sx, sy, el2edimg(getBorderElement(x, y)));
2697 }
2698
2699 static void DrawEnvelopeBackgroundTiles(int graphic, int startx, int starty,
2700                                         int x, int y, int xsize, int ysize,
2701                                         int tile_width, int tile_height)
2702 {
2703   Bitmap *src_bitmap;
2704   int src_x, src_y;
2705   int dst_x = startx + x * tile_width;
2706   int dst_y = starty + y * tile_height;
2707   int width  = graphic_info[graphic].width;
2708   int height = graphic_info[graphic].height;
2709   int inner_width_raw  = MAX(width  - 2 * tile_width,  tile_width);
2710   int inner_height_raw = MAX(height - 2 * tile_height, tile_height);
2711   int inner_width  = inner_width_raw  - (inner_width_raw  % tile_width);
2712   int inner_height = inner_height_raw - (inner_height_raw % tile_height);
2713   int inner_sx = (width  >= 3 * tile_width  ? tile_width  : 0);
2714   int inner_sy = (height >= 3 * tile_height ? tile_height : 0);
2715   boolean draw_masked = graphic_info[graphic].draw_masked;
2716
2717   getFixedGraphicSource(graphic, 0, &src_bitmap, &src_x, &src_y);
2718
2719   if (src_bitmap == NULL || width < tile_width || height < tile_height)
2720   {
2721     ClearRectangle(drawto, dst_x, dst_y, tile_width, tile_height);
2722     return;
2723   }
2724
2725   src_x += (x == 0 ? 0 : x == xsize - 1 ? width  - tile_width  :
2726             inner_sx + (x - 1) * tile_width  % inner_width);
2727   src_y += (y == 0 ? 0 : y == ysize - 1 ? height - tile_height :
2728             inner_sy + (y - 1) * tile_height % inner_height);
2729
2730   if (draw_masked)
2731     BlitBitmapMasked(src_bitmap, drawto, src_x, src_y, tile_width, tile_height,
2732                      dst_x, dst_y);
2733   else
2734     BlitBitmap(src_bitmap, drawto, src_x, src_y, tile_width, tile_height,
2735                dst_x, dst_y);
2736 }
2737
2738 static void DrawEnvelopeBackground(int graphic, int startx, int starty,
2739                                    int x, int y, int xsize, int ysize,
2740                                    int font_nr)
2741 {
2742   int font_width  = getFontWidth(font_nr);
2743   int font_height = getFontHeight(font_nr);
2744
2745   DrawEnvelopeBackgroundTiles(graphic, startx, starty, x, y, xsize, ysize,
2746                               font_width, font_height);
2747 }
2748
2749 static void AnimateEnvelope(int envelope_nr, int anim_mode, int action)
2750 {
2751   int graphic = IMG_BACKGROUND_ENVELOPE_1 + envelope_nr;
2752   Bitmap *src_bitmap = graphic_info[graphic].bitmap;
2753   int mask_mode = (src_bitmap != NULL ? BLIT_MASKED : BLIT_ON_BACKGROUND);
2754   boolean ffwd_delay = (tape.playing && tape.fast_forward);
2755   boolean no_delay = (tape.warp_forward);
2756   unsigned int anim_delay = 0;
2757   int frame_delay_value = (ffwd_delay ? FfwdFrameDelay : GameFrameDelay);
2758   int anim_delay_value = MAX(1, (no_delay ? 0 : frame_delay_value) / 2);
2759   int font_nr = FONT_ENVELOPE_1 + envelope_nr;
2760   int font_width = getFontWidth(font_nr);
2761   int font_height = getFontHeight(font_nr);
2762   int max_xsize = level.envelope[envelope_nr].xsize;
2763   int max_ysize = level.envelope[envelope_nr].ysize;
2764   int xstart = (anim_mode & ANIM_VERTICAL ? max_xsize : 0);
2765   int ystart = (anim_mode & ANIM_HORIZONTAL ? max_ysize : 0);
2766   int xend = max_xsize;
2767   int yend = (anim_mode != ANIM_DEFAULT ? max_ysize : 0);
2768   int xstep = (xstart < xend ? 1 : 0);
2769   int ystep = (ystart < yend || xstep == 0 ? 1 : 0);
2770   int start = 0;
2771   int end = MAX(xend - xstart, yend - ystart);
2772   int i;
2773
2774   for (i = start; i <= end; i++)
2775   {
2776     int last_frame = end;       // last frame of this "for" loop
2777     int x = xstart + i * xstep;
2778     int y = ystart + i * ystep;
2779     int xsize = (action == ACTION_CLOSING ? xend - (x - xstart) : x) + 2;
2780     int ysize = (action == ACTION_CLOSING ? yend - (y - ystart) : y) + 2;
2781     int sx = SX + (SXSIZE - xsize * font_width)  / 2;
2782     int sy = SY + (SYSIZE - ysize * font_height) / 2;
2783     int xx, yy;
2784
2785     SetDrawtoField(DRAW_TO_FIELDBUFFER);
2786
2787     BlitScreenToBitmap(backbuffer);
2788
2789     SetDrawtoField(DRAW_TO_BACKBUFFER);
2790
2791     for (yy = 0; yy < ysize; yy++)
2792       for (xx = 0; xx < xsize; xx++)
2793         DrawEnvelopeBackground(graphic, sx, sy, xx, yy, xsize, ysize, font_nr);
2794
2795     DrawTextBuffer(sx + font_width, sy + font_height,
2796                    level.envelope[envelope_nr].text, font_nr, max_xsize,
2797                    xsize - 2, ysize - 2, 0, mask_mode,
2798                    level.envelope[envelope_nr].autowrap,
2799                    level.envelope[envelope_nr].centered, FALSE);
2800
2801     redraw_mask |= REDRAW_FIELD;
2802     BackToFront();
2803
2804     SkipUntilDelayReached(&anim_delay, anim_delay_value, &i, last_frame);
2805   }
2806
2807   ClearAutoRepeatKeyEvents();
2808 }
2809
2810 void ShowEnvelope(int envelope_nr)
2811 {
2812   int element = EL_ENVELOPE_1 + envelope_nr;
2813   int graphic = IMG_BACKGROUND_ENVELOPE_1 + envelope_nr;
2814   int sound_opening = element_info[element].sound[ACTION_OPENING];
2815   int sound_closing = element_info[element].sound[ACTION_CLOSING];
2816   boolean ffwd_delay = (tape.playing && tape.fast_forward);
2817   boolean no_delay = (tape.warp_forward);
2818   int normal_delay_value = ONE_SECOND_DELAY / (ffwd_delay ? 2 : 1);
2819   int wait_delay_value = (no_delay ? 0 : normal_delay_value);
2820   int anim_mode = graphic_info[graphic].anim_mode;
2821   int main_anim_mode = (anim_mode == ANIM_NONE ? ANIM_VERTICAL|ANIM_HORIZONTAL:
2822                         anim_mode == ANIM_DEFAULT ? ANIM_VERTICAL : anim_mode);
2823
2824   game.envelope_active = TRUE;  // needed for RedrawPlayfield() events
2825
2826   PlayMenuSoundStereo(sound_opening, SOUND_MIDDLE);
2827
2828   if (anim_mode == ANIM_DEFAULT)
2829     AnimateEnvelope(envelope_nr, ANIM_DEFAULT, ACTION_OPENING);
2830
2831   AnimateEnvelope(envelope_nr, main_anim_mode, ACTION_OPENING);
2832
2833   if (tape.playing)
2834     Delay_WithScreenUpdates(wait_delay_value);
2835   else
2836     WaitForEventToContinue();
2837
2838   PlayMenuSoundStereo(sound_closing, SOUND_MIDDLE);
2839
2840   if (anim_mode != ANIM_NONE)
2841     AnimateEnvelope(envelope_nr, main_anim_mode, ACTION_CLOSING);
2842
2843   if (anim_mode == ANIM_DEFAULT)
2844     AnimateEnvelope(envelope_nr, ANIM_DEFAULT, ACTION_CLOSING);
2845
2846   game.envelope_active = FALSE;
2847
2848   SetDrawtoField(DRAW_TO_FIELDBUFFER);
2849
2850   redraw_mask |= REDRAW_FIELD;
2851   BackToFront();
2852 }
2853
2854 static void setRequestBasePosition(int *x, int *y)
2855 {
2856   int sx_base, sy_base;
2857
2858   if (request.x != -1)
2859     sx_base = request.x;
2860   else if (request.align == ALIGN_LEFT)
2861     sx_base = SX;
2862   else if (request.align == ALIGN_RIGHT)
2863     sx_base = SX + SXSIZE;
2864   else
2865     sx_base = SX + SXSIZE / 2;
2866
2867   if (request.y != -1)
2868     sy_base = request.y;
2869   else if (request.valign == VALIGN_TOP)
2870     sy_base = SY;
2871   else if (request.valign == VALIGN_BOTTOM)
2872     sy_base = SY + SYSIZE;
2873   else
2874     sy_base = SY + SYSIZE / 2;
2875
2876   *x = sx_base;
2877   *y = sy_base;
2878 }
2879
2880 static void setRequestPositionExt(int *x, int *y, int width, int height,
2881                                   boolean add_border_size)
2882 {
2883   int border_size = request.border_size;
2884   int sx_base, sy_base;
2885   int sx, sy;
2886
2887   setRequestBasePosition(&sx_base, &sy_base);
2888
2889   if (request.align == ALIGN_LEFT)
2890     sx = sx_base;
2891   else if (request.align == ALIGN_RIGHT)
2892     sx = sx_base - width;
2893   else
2894     sx = sx_base - width  / 2;
2895
2896   if (request.valign == VALIGN_TOP)
2897     sy = sy_base;
2898   else if (request.valign == VALIGN_BOTTOM)
2899     sy = sy_base - height;
2900   else
2901     sy = sy_base - height / 2;
2902
2903   sx = MAX(0, MIN(sx, WIN_XSIZE - width));
2904   sy = MAX(0, MIN(sy, WIN_YSIZE - height));
2905
2906   if (add_border_size)
2907   {
2908     sx += border_size;
2909     sy += border_size;
2910   }
2911
2912   *x = sx;
2913   *y = sy;
2914 }
2915
2916 static void setRequestPosition(int *x, int *y, boolean add_border_size)
2917 {
2918   setRequestPositionExt(x, y, request.width, request.height, add_border_size);
2919 }
2920
2921 static void DrawEnvelopeRequest(char *text)
2922 {
2923   char *text_final = text;
2924   char *text_door_style = NULL;
2925   int graphic = IMG_BACKGROUND_REQUEST;
2926   Bitmap *src_bitmap = graphic_info[graphic].bitmap;
2927   int mask_mode = (src_bitmap != NULL ? BLIT_MASKED : BLIT_ON_BACKGROUND);
2928   int font_nr = FONT_REQUEST;
2929   int font_width = getFontWidth(font_nr);
2930   int font_height = getFontHeight(font_nr);
2931   int border_size = request.border_size;
2932   int line_spacing = request.line_spacing;
2933   int line_height = font_height + line_spacing;
2934   int max_text_width  = request.width  - 2 * border_size;
2935   int max_text_height = request.height - 2 * border_size;
2936   int line_length = max_text_width  / font_width;
2937   int max_lines   = max_text_height / line_height;
2938   int text_width = line_length * font_width;
2939   int width = request.width;
2940   int height = request.height;
2941   int tile_size = MAX(request.step_offset, 1);
2942   int x_steps = width  / tile_size;
2943   int y_steps = height / tile_size;
2944   int sx_offset = border_size;
2945   int sy_offset = border_size;
2946   int sx, sy;
2947   int i, x, y;
2948
2949   if (request.centered)
2950     sx_offset = (request.width - text_width) / 2;
2951
2952   if (request.wrap_single_words && !request.autowrap)
2953   {
2954     char *src_text_ptr, *dst_text_ptr;
2955
2956     text_door_style = checked_malloc(2 * strlen(text) + 1);
2957
2958     src_text_ptr = text;
2959     dst_text_ptr = text_door_style;
2960
2961     while (*src_text_ptr)
2962     {
2963       if (*src_text_ptr == ' ' ||
2964           *src_text_ptr == '?' ||
2965           *src_text_ptr == '!')
2966         *dst_text_ptr++ = '\n';
2967
2968       if (*src_text_ptr != ' ')
2969         *dst_text_ptr++ = *src_text_ptr;
2970
2971       src_text_ptr++;
2972     }
2973
2974     *dst_text_ptr = '\0';
2975
2976     text_final = text_door_style;
2977   }
2978
2979   setRequestPosition(&sx, &sy, FALSE);
2980
2981   ClearRectangle(backbuffer, 0, 0, WIN_XSIZE, WIN_YSIZE);
2982
2983   for (y = 0; y < y_steps; y++)
2984     for (x = 0; x < x_steps; x++)
2985       DrawEnvelopeBackgroundTiles(graphic, sx, sy,
2986                                   x, y, x_steps, y_steps,
2987                                   tile_size, tile_size);
2988
2989   // force DOOR font inside door area
2990   SetFontStatus(GAME_MODE_PSEUDO_DOOR);
2991
2992   DrawTextBuffer(sx + sx_offset, sy + sy_offset, text_final, font_nr,
2993                  line_length, -1, max_lines, line_spacing, mask_mode,
2994                  request.autowrap, request.centered, FALSE);
2995
2996   ResetFontStatus();
2997
2998   for (i = 0; i < NUM_TOOL_BUTTONS; i++)
2999     RedrawGadget(tool_gadget[i]);
3000
3001   // store readily prepared envelope request for later use when animating
3002   BlitBitmap(backbuffer, bitmap_db_store_2, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
3003
3004   if (text_door_style)
3005     free(text_door_style);
3006 }
3007
3008 static void AnimateEnvelopeRequest(int anim_mode, int action)
3009 {
3010   int graphic = IMG_BACKGROUND_REQUEST;
3011   boolean draw_masked = graphic_info[graphic].draw_masked;
3012   int delay_value_normal = request.step_delay;
3013   int delay_value_fast = delay_value_normal / 2;
3014   boolean ffwd_delay = (tape.playing && tape.fast_forward);
3015   boolean no_delay = (tape.warp_forward);
3016   int delay_value = (ffwd_delay ? delay_value_fast : delay_value_normal);
3017   int anim_delay_value = MAX(1, (no_delay ? 0 : delay_value + 500 * 0) / 2);
3018   unsigned int anim_delay = 0;
3019
3020   int tile_size = MAX(request.step_offset, 1);
3021   int max_xsize = request.width  / tile_size;
3022   int max_ysize = request.height / tile_size;
3023   int max_xsize_inner = max_xsize - 2;
3024   int max_ysize_inner = max_ysize - 2;
3025
3026   int xstart = (anim_mode & ANIM_VERTICAL ? max_xsize_inner : 0);
3027   int ystart = (anim_mode & ANIM_HORIZONTAL ? max_ysize_inner : 0);
3028   int xend = max_xsize_inner;
3029   int yend = (anim_mode != ANIM_DEFAULT ? max_ysize_inner : 0);
3030   int xstep = (xstart < xend ? 1 : 0);
3031   int ystep = (ystart < yend || xstep == 0 ? 1 : 0);
3032   int start = 0;
3033   int end = MAX(xend - xstart, yend - ystart);
3034   int i;
3035
3036   if (setup.quick_doors)
3037   {
3038     xstart = xend;
3039     ystart = yend;
3040     end = 0;
3041   }
3042
3043   for (i = start; i <= end; i++)
3044   {
3045     int last_frame = end;       // last frame of this "for" loop
3046     int x = xstart + i * xstep;
3047     int y = ystart + i * ystep;
3048     int xsize = (action == ACTION_CLOSING ? xend - (x - xstart) : x) + 2;
3049     int ysize = (action == ACTION_CLOSING ? yend - (y - ystart) : y) + 2;
3050     int xsize_size_left = (xsize - 1) * tile_size;
3051     int ysize_size_top  = (ysize - 1) * tile_size;
3052     int max_xsize_pos = (max_xsize - 1) * tile_size;
3053     int max_ysize_pos = (max_ysize - 1) * tile_size;
3054     int width  = xsize * tile_size;
3055     int height = ysize * tile_size;
3056     int src_x, src_y;
3057     int dst_x, dst_y;
3058     int xx, yy;
3059
3060     setRequestPosition(&src_x, &src_y, FALSE);
3061     setRequestPositionExt(&dst_x, &dst_y, width, height, FALSE);
3062
3063     BlitBitmap(bitmap_db_store_1, backbuffer, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
3064
3065     for (yy = 0; yy < 2; yy++)
3066     {
3067       for (xx = 0; xx < 2; xx++)
3068       {
3069         int src_xx = src_x + xx * max_xsize_pos;
3070         int src_yy = src_y + yy * max_ysize_pos;
3071         int dst_xx = dst_x + xx * xsize_size_left;
3072         int dst_yy = dst_y + yy * ysize_size_top;
3073         int xx_size = (xx ? tile_size : xsize_size_left);
3074         int yy_size = (yy ? tile_size : ysize_size_top);
3075
3076         if (draw_masked)
3077           BlitBitmapMasked(bitmap_db_store_2, backbuffer,
3078                            src_xx, src_yy, xx_size, yy_size, dst_xx, dst_yy);
3079         else
3080           BlitBitmap(bitmap_db_store_2, backbuffer,
3081                      src_xx, src_yy, xx_size, yy_size, dst_xx, dst_yy);
3082       }
3083     }
3084
3085     redraw_mask |= REDRAW_FIELD;
3086
3087     BackToFront();
3088
3089     SkipUntilDelayReached(&anim_delay, anim_delay_value, &i, last_frame);
3090   }
3091
3092   ClearAutoRepeatKeyEvents();
3093 }
3094
3095 static void ShowEnvelopeRequest(char *text, unsigned int req_state, int action)
3096 {
3097   int graphic = IMG_BACKGROUND_REQUEST;
3098   int sound_opening = SND_REQUEST_OPENING;
3099   int sound_closing = SND_REQUEST_CLOSING;
3100   int anim_mode_1 = request.anim_mode;                  // (higher priority)
3101   int anim_mode_2 = graphic_info[graphic].anim_mode;    // (lower priority)
3102   int anim_mode = (anim_mode_1 != ANIM_DEFAULT ? anim_mode_1 : anim_mode_2);
3103   int main_anim_mode = (anim_mode == ANIM_NONE ? ANIM_VERTICAL|ANIM_HORIZONTAL:
3104                         anim_mode == ANIM_DEFAULT ? ANIM_VERTICAL : anim_mode);
3105
3106   if (game_status == GAME_MODE_PLAYING)
3107     BlitScreenToBitmap(backbuffer);
3108
3109   SetDrawtoField(DRAW_TO_BACKBUFFER);
3110
3111   // SetDrawBackgroundMask(REDRAW_NONE);
3112
3113   if (action == ACTION_OPENING)
3114   {
3115     BlitBitmap(backbuffer, bitmap_db_store_1, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
3116
3117     if (req_state & REQ_ASK)
3118     {
3119       MapGadget(tool_gadget[TOOL_CTRL_ID_YES]);
3120       MapGadget(tool_gadget[TOOL_CTRL_ID_NO]);
3121       MapGadget(tool_gadget[TOOL_CTRL_ID_TOUCH_YES]);
3122       MapGadget(tool_gadget[TOOL_CTRL_ID_TOUCH_NO]);
3123     }
3124     else if (req_state & REQ_CONFIRM)
3125     {
3126       MapGadget(tool_gadget[TOOL_CTRL_ID_CONFIRM]);
3127       MapGadget(tool_gadget[TOOL_CTRL_ID_TOUCH_CONFIRM]);
3128     }
3129     else if (req_state & REQ_PLAYER)
3130     {
3131       MapGadget(tool_gadget[TOOL_CTRL_ID_PLAYER_1]);
3132       MapGadget(tool_gadget[TOOL_CTRL_ID_PLAYER_2]);
3133       MapGadget(tool_gadget[TOOL_CTRL_ID_PLAYER_3]);
3134       MapGadget(tool_gadget[TOOL_CTRL_ID_PLAYER_4]);
3135     }
3136
3137     DrawEnvelopeRequest(text);
3138   }
3139
3140   game.envelope_active = TRUE;  // needed for RedrawPlayfield() events
3141
3142   if (action == ACTION_OPENING)
3143   {
3144     PlayMenuSoundStereo(sound_opening, SOUND_MIDDLE);
3145
3146     if (anim_mode == ANIM_DEFAULT)
3147       AnimateEnvelopeRequest(ANIM_DEFAULT, ACTION_OPENING);
3148
3149     AnimateEnvelopeRequest(main_anim_mode, ACTION_OPENING);
3150   }
3151   else
3152   {
3153     PlayMenuSoundStereo(sound_closing, SOUND_MIDDLE);
3154
3155     if (anim_mode != ANIM_NONE)
3156       AnimateEnvelopeRequest(main_anim_mode, ACTION_CLOSING);
3157
3158     if (anim_mode == ANIM_DEFAULT)
3159       AnimateEnvelopeRequest(ANIM_DEFAULT, ACTION_CLOSING);
3160   }
3161
3162   game.envelope_active = FALSE;
3163
3164   if (action == ACTION_CLOSING)
3165     BlitBitmap(bitmap_db_store_1, backbuffer, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
3166
3167   // SetDrawBackgroundMask(last_draw_background_mask);
3168
3169   redraw_mask |= REDRAW_FIELD;
3170
3171   BackToFront();
3172
3173   if (action == ACTION_CLOSING &&
3174       game_status == GAME_MODE_PLAYING &&
3175       level.game_engine_type == GAME_ENGINE_TYPE_RND)
3176     SetDrawtoField(DRAW_TO_FIELDBUFFER);
3177 }
3178
3179 static void DrawPreviewElement(int dst_x, int dst_y, int element, int tilesize)
3180 {
3181   if (IS_MM_WALL(element))
3182   {
3183     DrawSizedWall_MM(dst_x, dst_y, element, tilesize, el2preimg);
3184   }
3185   else
3186   {
3187     Bitmap *src_bitmap;
3188     int src_x, src_y;
3189     int graphic = el2preimg(element);
3190
3191     getSizedGraphicSource(graphic, 0, tilesize, &src_bitmap, &src_x, &src_y);
3192     BlitBitmap(src_bitmap, drawto, src_x, src_y, tilesize, tilesize,
3193                dst_x, dst_y);
3194   }
3195 }
3196
3197 void DrawLevel(int draw_background_mask)
3198 {
3199   int x,y;
3200
3201   SetMainBackgroundImage(IMG_BACKGROUND_PLAYING);
3202   SetDrawBackgroundMask(draw_background_mask);
3203
3204   ClearField();
3205
3206   for (x = BX1; x <= BX2; x++)
3207     for (y = BY1; y <= BY2; y++)
3208       DrawScreenField(x, y);
3209
3210   redraw_mask |= REDRAW_FIELD;
3211 }
3212
3213 void DrawSizedLevel(int size_x, int size_y, int scroll_x, int scroll_y,
3214                     int tilesize)
3215 {
3216   int x,y;
3217
3218   for (x = 0; x < size_x; x++)
3219     for (y = 0; y < size_y; y++)
3220       DrawSizedElementOrWall(x, y, scroll_x, scroll_y, tilesize);
3221
3222   redraw_mask |= REDRAW_FIELD;
3223 }
3224
3225 void DrawMiniLevel(int size_x, int size_y, int scroll_x, int scroll_y)
3226 {
3227   int x,y;
3228
3229   for (x = 0; x < size_x; x++)
3230     for (y = 0; y < size_y; y++)
3231       DrawMiniElementOrWall(x, y, scroll_x, scroll_y);
3232
3233   redraw_mask |= REDRAW_FIELD;
3234 }
3235
3236 static void DrawPreviewLevelPlayfield(int from_x, int from_y)
3237 {
3238   boolean show_level_border = (BorderElement != EL_EMPTY);
3239   int level_xsize = lev_fieldx + (show_level_border ? 2 : 0);
3240   int level_ysize = lev_fieldy + (show_level_border ? 2 : 0);
3241   int tile_size = preview.tile_size;
3242   int preview_width  = preview.xsize * tile_size;
3243   int preview_height = preview.ysize * tile_size;
3244   int real_preview_xsize = MIN(level_xsize, preview.xsize);
3245   int real_preview_ysize = MIN(level_ysize, preview.ysize);
3246   int real_preview_width  = real_preview_xsize * tile_size;
3247   int real_preview_height = real_preview_ysize * tile_size;
3248   int dst_x = SX + ALIGNED_XPOS(preview.x, preview_width, preview.align);
3249   int dst_y = SY + ALIGNED_YPOS(preview.y, preview_height, preview.valign);
3250   int x, y;
3251
3252   if (!IN_GFX_FIELD_FULL(dst_x, dst_y + preview_height - 1))
3253     return;
3254
3255   DrawBackground(dst_x, dst_y, preview_width, preview_height);
3256
3257   dst_x += (preview_width  - real_preview_width)  / 2;
3258   dst_y += (preview_height - real_preview_height) / 2;
3259
3260   for (x = 0; x < real_preview_xsize; x++)
3261   {
3262     for (y = 0; y < real_preview_ysize; y++)
3263     {
3264       int lx = from_x + x + (show_level_border ? -1 : 0);
3265       int ly = from_y + y + (show_level_border ? -1 : 0);
3266       int element = (IN_LEV_FIELD(lx, ly) ? level.field[lx][ly] :
3267                      getBorderElement(lx, ly));
3268
3269       DrawPreviewElement(dst_x + x * tile_size, dst_y + y * tile_size,
3270                          element, tile_size);
3271     }
3272   }
3273
3274   redraw_mask |= REDRAW_FIELD;
3275 }
3276
3277 #define MICROLABEL_EMPTY                0
3278 #define MICROLABEL_LEVEL_NAME           1
3279 #define MICROLABEL_LEVEL_AUTHOR_HEAD    2
3280 #define MICROLABEL_LEVEL_AUTHOR         3
3281 #define MICROLABEL_IMPORTED_FROM_HEAD   4
3282 #define MICROLABEL_IMPORTED_FROM        5
3283 #define MICROLABEL_IMPORTED_BY_HEAD     6
3284 #define MICROLABEL_IMPORTED_BY          7
3285
3286 static int getMaxTextLength(struct TextPosInfo *pos, int font_nr)
3287 {
3288   int max_text_width = SXSIZE;
3289   int font_width = getFontWidth(font_nr);
3290
3291   if (pos->align == ALIGN_CENTER)
3292     max_text_width = (pos->x < SXSIZE / 2 ? pos->x * 2 : (SXSIZE - pos->x) * 2);
3293   else if (pos->align == ALIGN_RIGHT)
3294     max_text_width = pos->x;
3295   else
3296     max_text_width = SXSIZE - pos->x;
3297
3298   return max_text_width / font_width;
3299 }
3300
3301 static void DrawPreviewLevelLabelExt(int mode, struct TextPosInfo *pos)
3302 {
3303   char label_text[MAX_OUTPUT_LINESIZE + 1];
3304   int max_len_label_text;
3305   int font_nr = pos->font;
3306   int i;
3307
3308   if (!IN_GFX_FIELD_FULL(pos->x, pos->y + getFontHeight(pos->font)))
3309     return;
3310
3311   if (mode == MICROLABEL_LEVEL_AUTHOR_HEAD ||
3312       mode == MICROLABEL_IMPORTED_FROM_HEAD ||
3313       mode == MICROLABEL_IMPORTED_BY_HEAD)
3314     font_nr = pos->font_alt;
3315
3316   max_len_label_text = getMaxTextLength(pos, font_nr);
3317
3318   if (pos->size != -1)
3319     max_len_label_text = pos->size;
3320
3321   for (i = 0; i < max_len_label_text; i++)
3322     label_text[i] = ' ';
3323   label_text[max_len_label_text] = '\0';
3324
3325   if (strlen(label_text) > 0)
3326     DrawTextSAligned(pos->x, pos->y, label_text, font_nr, pos->align);
3327
3328   strncpy(label_text,
3329           (mode == MICROLABEL_LEVEL_NAME ? level.name :
3330            mode == MICROLABEL_LEVEL_AUTHOR_HEAD ? "created by" :
3331            mode == MICROLABEL_LEVEL_AUTHOR ? level.author :
3332            mode == MICROLABEL_IMPORTED_FROM_HEAD ? "imported from" :
3333            mode == MICROLABEL_IMPORTED_FROM ? leveldir_current->imported_from :
3334            mode == MICROLABEL_IMPORTED_BY_HEAD ? "imported by" :
3335            mode == MICROLABEL_IMPORTED_BY ? leveldir_current->imported_by :""),
3336           max_len_label_text);
3337   label_text[max_len_label_text] = '\0';
3338
3339   if (strlen(label_text) > 0)
3340     DrawTextSAligned(pos->x, pos->y, label_text, font_nr, pos->align);
3341
3342   redraw_mask |= REDRAW_FIELD;
3343 }
3344
3345 static void DrawPreviewLevelLabel(int mode)
3346 {
3347   DrawPreviewLevelLabelExt(mode, &menu.main.text.level_info_2);
3348 }
3349
3350 static void DrawPreviewLevelInfo(int mode)
3351 {
3352   if (mode == MICROLABEL_LEVEL_NAME)
3353     DrawPreviewLevelLabelExt(mode, &menu.main.text.level_name);
3354   else if (mode == MICROLABEL_LEVEL_AUTHOR)
3355     DrawPreviewLevelLabelExt(mode, &menu.main.text.level_author);
3356 }
3357
3358 static void DrawPreviewLevelExt(boolean restart)
3359 {
3360   static unsigned int scroll_delay = 0;
3361   static unsigned int label_delay = 0;
3362   static int from_x, from_y, scroll_direction;
3363   static int label_state, label_counter;
3364   unsigned int scroll_delay_value = preview.step_delay;
3365   boolean show_level_border = (BorderElement != EL_EMPTY);
3366   int level_xsize = lev_fieldx + (show_level_border ? 2 : 0);
3367   int level_ysize = lev_fieldy + (show_level_border ? 2 : 0);
3368
3369   if (restart)
3370   {
3371     from_x = 0;
3372     from_y = 0;
3373
3374     if (preview.anim_mode == ANIM_CENTERED)
3375     {
3376       if (level_xsize > preview.xsize)
3377         from_x = (level_xsize - preview.xsize) / 2;
3378       if (level_ysize > preview.ysize)
3379         from_y = (level_ysize - preview.ysize) / 2;
3380     }
3381
3382     from_x += preview.xoffset;
3383     from_y += preview.yoffset;
3384
3385     scroll_direction = MV_RIGHT;
3386     label_state = 1;
3387     label_counter = 0;
3388
3389     DrawPreviewLevelPlayfield(from_x, from_y);
3390     DrawPreviewLevelLabel(label_state);
3391
3392     DrawPreviewLevelInfo(MICROLABEL_LEVEL_NAME);
3393     DrawPreviewLevelInfo(MICROLABEL_LEVEL_AUTHOR);
3394
3395     // initialize delay counters
3396     DelayReached(&scroll_delay, 0);
3397     DelayReached(&label_delay, 0);
3398
3399     if (leveldir_current->name)
3400     {
3401       struct TextPosInfo *pos = &menu.main.text.level_info_1;
3402       char label_text[MAX_OUTPUT_LINESIZE + 1];
3403       int font_nr = pos->font;
3404       int max_len_label_text = getMaxTextLength(pos, font_nr);
3405
3406       if (pos->size != -1)
3407         max_len_label_text = pos->size;
3408
3409       strncpy(label_text, leveldir_current->name, max_len_label_text);
3410       label_text[max_len_label_text] = '\0';
3411
3412       if (IN_GFX_FIELD_FULL(pos->x, pos->y + getFontHeight(pos->font)))
3413         DrawTextSAligned(pos->x, pos->y, label_text, font_nr, pos->align);
3414     }
3415
3416     return;
3417   }
3418
3419   // scroll preview level, if needed
3420   if (preview.anim_mode != ANIM_NONE &&
3421       (level_xsize > preview.xsize || level_ysize > preview.ysize) &&
3422       DelayReached(&scroll_delay, scroll_delay_value))
3423   {
3424     switch (scroll_direction)
3425     {
3426       case MV_LEFT:
3427         if (from_x > 0)
3428         {
3429           from_x -= preview.step_offset;
3430           from_x = (from_x < 0 ? 0 : from_x);
3431         }
3432         else
3433           scroll_direction = MV_UP;
3434         break;
3435
3436       case MV_RIGHT:
3437         if (from_x < level_xsize - preview.xsize)
3438         {
3439           from_x += preview.step_offset;
3440           from_x = (from_x > level_xsize - preview.xsize ?
3441                     level_xsize - preview.xsize : from_x);
3442         }
3443         else
3444           scroll_direction = MV_DOWN;
3445         break;
3446
3447       case MV_UP:
3448         if (from_y > 0)
3449         {
3450           from_y -= preview.step_offset;
3451           from_y = (from_y < 0 ? 0 : from_y);
3452         }
3453         else
3454           scroll_direction = MV_RIGHT;
3455         break;
3456
3457       case MV_DOWN:
3458         if (from_y < level_ysize - preview.ysize)
3459         {
3460           from_y += preview.step_offset;
3461           from_y = (from_y > level_ysize - preview.ysize ?
3462                     level_ysize - preview.ysize : from_y);
3463         }
3464         else
3465           scroll_direction = MV_LEFT;
3466         break;
3467
3468       default:
3469         break;
3470     }
3471
3472     DrawPreviewLevelPlayfield(from_x, from_y);
3473   }
3474
3475   // !!! THIS ALL SUCKS -- SHOULD BE CLEANLY REWRITTEN !!!
3476   // redraw micro level label, if needed
3477   if (!strEqual(level.name, NAMELESS_LEVEL_NAME) &&
3478       !strEqual(level.author, ANONYMOUS_NAME) &&
3479       !strEqual(level.author, leveldir_current->name) &&
3480       DelayReached(&label_delay, MICROLEVEL_LABEL_DELAY))
3481   {
3482     int max_label_counter = 23;
3483
3484     if (leveldir_current->imported_from != NULL &&
3485         strlen(leveldir_current->imported_from) > 0)
3486       max_label_counter += 14;
3487     if (leveldir_current->imported_by != NULL &&
3488         strlen(leveldir_current->imported_by) > 0)
3489       max_label_counter += 14;
3490
3491     label_counter = (label_counter + 1) % max_label_counter;
3492     label_state = (label_counter >= 0 && label_counter <= 7 ?
3493                    MICROLABEL_LEVEL_NAME :
3494                    label_counter >= 9 && label_counter <= 12 ?
3495                    MICROLABEL_LEVEL_AUTHOR_HEAD :
3496                    label_counter >= 14 && label_counter <= 21 ?
3497                    MICROLABEL_LEVEL_AUTHOR :
3498                    label_counter >= 23 && label_counter <= 26 ?
3499                    MICROLABEL_IMPORTED_FROM_HEAD :
3500                    label_counter >= 28 && label_counter <= 35 ?
3501                    MICROLABEL_IMPORTED_FROM :
3502                    label_counter >= 37 && label_counter <= 40 ?
3503                    MICROLABEL_IMPORTED_BY_HEAD :
3504                    label_counter >= 42 && label_counter <= 49 ?
3505                    MICROLABEL_IMPORTED_BY : MICROLABEL_EMPTY);
3506
3507     if (leveldir_current->imported_from == NULL &&
3508         (label_state == MICROLABEL_IMPORTED_FROM_HEAD ||
3509          label_state == MICROLABEL_IMPORTED_FROM))
3510       label_state = (label_state == MICROLABEL_IMPORTED_FROM_HEAD ?
3511                      MICROLABEL_IMPORTED_BY_HEAD : MICROLABEL_IMPORTED_BY);
3512
3513     DrawPreviewLevelLabel(label_state);
3514   }
3515 }
3516
3517 void DrawPreviewPlayers(void)
3518 {
3519   if (game_status != GAME_MODE_MAIN)
3520     return;
3521
3522   // do not draw preview players if level preview redefined, but players aren't
3523   if (preview.redefined && !menu.main.preview_players.redefined)
3524     return;
3525
3526   boolean player_found[MAX_PLAYERS];
3527   int num_players = 0;
3528   int i, x, y;
3529
3530   for (i = 0; i < MAX_PLAYERS; i++)
3531     player_found[i] = FALSE;
3532
3533   // check which players can be found in the level (simple approach)
3534   for (x = 0; x < lev_fieldx; x++)
3535   {
3536     for (y = 0; y < lev_fieldy; y++)
3537     {
3538       int element = level.field[x][y];
3539
3540       if (ELEM_IS_PLAYER(element))
3541       {
3542         int player_nr = GET_PLAYER_NR(element);
3543
3544         player_nr = MIN(MAX(0, player_nr), MAX_PLAYERS - 1);
3545
3546         if (!player_found[player_nr])
3547           num_players++;
3548
3549         player_found[player_nr] = TRUE;
3550       }
3551     }
3552   }
3553
3554   struct TextPosInfo *pos = &menu.main.preview_players;
3555   int tile_size = pos->tile_size;
3556   int border_size = pos->border_size;
3557   int player_xoffset_raw = (pos->vertical ? 0 : tile_size + border_size);
3558   int player_yoffset_raw = (pos->vertical ? tile_size + border_size : 0);
3559   int player_xoffset = (pos->xoffset != -1 ? pos->xoffset : player_xoffset_raw);
3560   int player_yoffset = (pos->yoffset != -1 ? pos->yoffset : player_yoffset_raw);
3561   int max_players_width  = (MAX_PLAYERS - 1) * player_xoffset + tile_size;
3562   int max_players_height = (MAX_PLAYERS - 1) * player_yoffset + tile_size;
3563   int all_players_width  = (num_players - 1) * player_xoffset + tile_size;
3564   int all_players_height = (num_players - 1) * player_yoffset + tile_size;
3565   int max_xpos = SX + ALIGNED_XPOS(pos->x, max_players_width,  pos->align);
3566   int max_ypos = SY + ALIGNED_YPOS(pos->y, max_players_height, pos->valign);
3567   int xpos = SX + ALIGNED_XPOS(pos->x, all_players_width,  pos->align);
3568   int ypos = SY + ALIGNED_YPOS(pos->y, all_players_height, pos->valign);
3569
3570   // clear area in which the players will be drawn
3571   ClearRectangleOnBackground(drawto, max_xpos, max_ypos,
3572                              max_players_width, max_players_height);
3573
3574   if (!network.enabled && !setup.team_mode)
3575     return;
3576
3577   // only draw players if level is suited for team mode
3578   if (num_players < 2)
3579     return;
3580
3581   // draw all players that were found in the level
3582   for (i = 0; i < MAX_PLAYERS; i++)
3583   {
3584     if (player_found[i])
3585     {
3586       int graphic = el2img(EL_PLAYER_1 + i);
3587
3588       DrawSizedGraphicThruMaskExt(drawto, xpos, ypos, graphic, 0, tile_size);
3589
3590       xpos += player_xoffset;
3591       ypos += player_yoffset;
3592     }
3593   }
3594 }
3595
3596 void DrawPreviewLevelInitial(void)
3597 {
3598   DrawPreviewLevelExt(TRUE);
3599   DrawPreviewPlayers();
3600 }
3601
3602 void DrawPreviewLevelAnimation(void)
3603 {
3604   DrawPreviewLevelExt(FALSE);
3605 }
3606
3607 static void DrawNetworkPlayer(int x, int y, int player_nr, int tile_size,
3608                               int border_size, int font_nr)
3609 {
3610   int graphic = el2img(EL_PLAYER_1 + player_nr);
3611   int font_height = getFontHeight(font_nr);
3612   int player_height = MAX(tile_size, font_height);
3613   int xoffset_text = tile_size + border_size;
3614   int yoffset_text    = (player_height - font_height) / 2;
3615   int yoffset_graphic = (player_height - tile_size) / 2;
3616   char *player_name = getNetworkPlayerName(player_nr + 1);
3617
3618   DrawSizedGraphicThruMaskExt(drawto, x, y + yoffset_graphic, graphic, 0,
3619                               tile_size);
3620   DrawText(x + xoffset_text, y + yoffset_text, player_name, font_nr);
3621 }
3622
3623 static void DrawNetworkPlayersExt(boolean force)
3624 {
3625   if (game_status != GAME_MODE_MAIN)
3626     return;
3627
3628   if (!network.connected && !force)
3629     return;
3630
3631   // do not draw network players if level preview redefined, but players aren't
3632   if (preview.redefined && !menu.main.network_players.redefined)
3633     return;
3634
3635   int num_players = 0;
3636   int i;
3637
3638   for (i = 0; i < MAX_PLAYERS; i++)
3639     if (stored_player[i].connected_network)
3640       num_players++;
3641
3642   struct TextPosInfo *pos = &menu.main.network_players;
3643   int tile_size = pos->tile_size;
3644   int border_size = pos->border_size;
3645   int xoffset_text = tile_size + border_size;
3646   int font_nr = pos->font;
3647   int font_width = getFontWidth(font_nr);
3648   int font_height = getFontHeight(font_nr);
3649   int player_height = MAX(tile_size, font_height);
3650   int player_yoffset = player_height + border_size;
3651   int max_players_width = xoffset_text + MAX_PLAYER_NAME_LEN * font_width;
3652   int max_players_height = MAX_PLAYERS * player_yoffset - border_size;
3653   int all_players_height = num_players * player_yoffset - border_size;
3654   int max_xpos = SX + ALIGNED_XPOS(pos->x, max_players_width,  pos->align);
3655   int max_ypos = SY + ALIGNED_YPOS(pos->y, max_players_height, pos->valign);
3656   int ypos = SY + ALIGNED_YPOS(pos->y, all_players_height, pos->valign);
3657
3658   ClearRectangleOnBackground(drawto, max_xpos, max_ypos,
3659                              max_players_width, max_players_height);
3660
3661   // first draw local network player ...
3662   for (i = 0; i < MAX_PLAYERS; i++)
3663   {
3664     if (stored_player[i].connected_network &&
3665         stored_player[i].connected_locally)
3666     {
3667       char *player_name = getNetworkPlayerName(i + 1);
3668       int player_width = xoffset_text + getTextWidth(player_name, font_nr);
3669       int xpos = SX + ALIGNED_XPOS(pos->x, player_width,  pos->align);
3670
3671       DrawNetworkPlayer(xpos, ypos, i, tile_size, border_size, font_nr);
3672
3673       ypos += player_yoffset;
3674     }
3675   }
3676
3677   // ... then draw all other network players
3678   for (i = 0; i < MAX_PLAYERS; i++)
3679   {
3680     if (stored_player[i].connected_network &&
3681         !stored_player[i].connected_locally)
3682     {
3683       char *player_name = getNetworkPlayerName(i + 1);
3684       int player_width = xoffset_text + getTextWidth(player_name, font_nr);
3685       int xpos = SX + ALIGNED_XPOS(pos->x, player_width,  pos->align);
3686
3687       DrawNetworkPlayer(xpos, ypos, i, tile_size, border_size, font_nr);
3688
3689       ypos += player_yoffset;
3690     }
3691   }
3692 }
3693
3694 void DrawNetworkPlayers(void)
3695 {
3696   DrawNetworkPlayersExt(FALSE);
3697 }
3698
3699 void ClearNetworkPlayers(void)
3700 {
3701   DrawNetworkPlayersExt(TRUE);
3702 }
3703
3704 static void DrawGraphicAnimationExt(DrawBuffer *dst_bitmap, int x, int y,
3705                                     int graphic, int sync_frame,
3706                                     int mask_mode)
3707 {
3708   int frame = getGraphicAnimationFrame(graphic, sync_frame);
3709
3710   if (mask_mode == USE_MASKING)
3711     DrawGraphicThruMaskExt(dst_bitmap, x, y, graphic, frame);
3712   else
3713     DrawGraphicExt(dst_bitmap, x, y, graphic, frame);
3714 }
3715
3716 void DrawFixedGraphicAnimationExt(DrawBuffer *dst_bitmap, int x, int y,
3717                                   int graphic, int sync_frame, int mask_mode)
3718 {
3719   int frame = getGraphicAnimationFrame(graphic, sync_frame);
3720
3721   if (mask_mode == USE_MASKING)
3722     DrawFixedGraphicThruMaskExt(dst_bitmap, x, y, graphic, frame);
3723   else
3724     DrawFixedGraphicExt(dst_bitmap, x, y, graphic, frame);
3725 }
3726
3727 static void DrawGraphicAnimation(int x, int y, int graphic)
3728 {
3729   int lx = LEVELX(x), ly = LEVELY(y);
3730
3731   if (!IN_SCR_FIELD(x, y))
3732     return;
3733
3734   DrawGraphicAnimationExt(drawto_field, FX + x * TILEX_VAR, FY + y * TILEY_VAR,
3735                           graphic, GfxFrame[lx][ly], NO_MASKING);
3736
3737   MarkTileDirty(x, y);
3738 }
3739
3740 void DrawFixedGraphicAnimation(int x, int y, int graphic)
3741 {
3742   int lx = LEVELX(x), ly = LEVELY(y);
3743
3744   if (!IN_SCR_FIELD(x, y))
3745     return;
3746
3747   DrawGraphicAnimationExt(drawto_field, FX + x * TILEX, FY + y * TILEY,
3748                           graphic, GfxFrame[lx][ly], NO_MASKING);
3749   MarkTileDirty(x, y);
3750 }
3751
3752 void DrawLevelGraphicAnimation(int x, int y, int graphic)
3753 {
3754   DrawGraphicAnimation(SCREENX(x), SCREENY(y), graphic);
3755 }
3756
3757 void DrawLevelElementAnimation(int x, int y, int element)
3758 {
3759   int graphic = el_act_dir2img(element, GfxAction[x][y], GfxDir[x][y]);
3760
3761   DrawGraphicAnimation(SCREENX(x), SCREENY(y), graphic);
3762 }
3763
3764 void DrawLevelGraphicAnimationIfNeeded(int x, int y, int graphic)
3765 {
3766   int sx = SCREENX(x), sy = SCREENY(y);
3767
3768   if (!IN_LEV_FIELD(x, y) || !IN_SCR_FIELD(sx, sy))
3769     return;
3770
3771   if (!IS_NEW_FRAME(GfxFrame[x][y], graphic))
3772     return;
3773
3774   DrawGraphicAnimation(sx, sy, graphic);
3775
3776 #if 1
3777   if (GFX_CRUMBLED(TILE_GFX_ELEMENT(x, y)))
3778     DrawLevelFieldCrumbled(x, y);
3779 #else
3780   if (GFX_CRUMBLED(Tile[x][y]))
3781     DrawLevelFieldCrumbled(x, y);
3782 #endif
3783 }
3784
3785 void DrawLevelElementAnimationIfNeeded(int x, int y, int element)
3786 {
3787   int sx = SCREENX(x), sy = SCREENY(y);
3788   int graphic;
3789
3790   if (!IN_LEV_FIELD(x, y) || !IN_SCR_FIELD(sx, sy))
3791     return;
3792
3793   graphic = el_act_dir2img(element, GfxAction[x][y], GfxDir[x][y]);
3794
3795   if (!IS_NEW_FRAME(GfxFrame[x][y], graphic))
3796     return;
3797
3798   DrawGraphicAnimation(sx, sy, graphic);
3799
3800   if (GFX_CRUMBLED(element))
3801     DrawLevelFieldCrumbled(x, y);
3802 }
3803
3804 static int getPlayerGraphic(struct PlayerInfo *player, int move_dir)
3805 {
3806   if (player->use_murphy)
3807   {
3808     // this works only because currently only one player can be "murphy" ...
3809     static int last_horizontal_dir = MV_LEFT;
3810     int graphic = el_act_dir2img(EL_SP_MURPHY, player->GfxAction, move_dir);
3811
3812     if (move_dir == MV_LEFT || move_dir == MV_RIGHT)
3813       last_horizontal_dir = move_dir;
3814
3815     if (graphic == IMG_SP_MURPHY)       // undefined => use special graphic
3816     {
3817       int direction = (player->is_snapping ? move_dir : last_horizontal_dir);
3818
3819       graphic = el_act_dir2img(EL_SP_MURPHY, player->GfxAction, direction);
3820     }
3821
3822     return graphic;
3823   }
3824   else
3825     return el_act_dir2img(player->artwork_element, player->GfxAction,move_dir);
3826 }
3827
3828 static boolean equalGraphics(int graphic1, int graphic2)
3829 {
3830   struct GraphicInfo *g1 = &graphic_info[graphic1];
3831   struct GraphicInfo *g2 = &graphic_info[graphic2];
3832
3833   return (g1->bitmap      == g2->bitmap &&
3834           g1->src_x       == g2->src_x &&
3835           g1->src_y       == g2->src_y &&
3836           g1->anim_frames == g2->anim_frames &&
3837           g1->anim_delay  == g2->anim_delay &&
3838           g1->anim_mode   == g2->anim_mode);
3839 }
3840
3841 #define DRAW_PLAYER_OVER_PUSHED_ELEMENT 1
3842
3843 enum
3844 {
3845   DRAW_PLAYER_STAGE_INIT = 0,
3846   DRAW_PLAYER_STAGE_LAST_FIELD,
3847   DRAW_PLAYER_STAGE_FIELD_UNDER_PLAYER,
3848 #if DRAW_PLAYER_OVER_PUSHED_ELEMENT
3849   DRAW_PLAYER_STAGE_ELEMENT_PUSHED,
3850   DRAW_PLAYER_STAGE_PLAYER,
3851 #else
3852   DRAW_PLAYER_STAGE_PLAYER,
3853   DRAW_PLAYER_STAGE_ELEMENT_PUSHED,
3854 #endif
3855   DRAW_PLAYER_STAGE_ELEMENT_OVER_PLAYER,
3856   DRAW_PLAYER_STAGE_FIELD_OVER_PLAYER,
3857
3858   NUM_DRAW_PLAYER_STAGES
3859 };
3860
3861 static void DrawPlayerExt(struct PlayerInfo *player, int drawing_stage)
3862 {
3863   static int static_last_player_graphic[MAX_PLAYERS];
3864   static int static_last_player_frame[MAX_PLAYERS];
3865   static boolean static_player_is_opaque[MAX_PLAYERS];
3866   static boolean draw_player[MAX_PLAYERS];
3867   int pnr = player->index_nr;
3868
3869   if (drawing_stage == DRAW_PLAYER_STAGE_INIT)
3870   {
3871     static_last_player_graphic[pnr] = getPlayerGraphic(player, player->MovDir);
3872     static_last_player_frame[pnr] = player->Frame;
3873     static_player_is_opaque[pnr] = FALSE;
3874
3875     draw_player[pnr] = TRUE;
3876   }
3877
3878   if (!draw_player[pnr])
3879     return;
3880
3881 #if DEBUG
3882   if (!IN_LEV_FIELD(player->jx, player->jy))
3883   {
3884     Debug("draw:DrawPlayerExt", "x = %d, y = %d", player->jx, player->jy);
3885     Debug("draw:DrawPlayerExt", "This should never happen!");
3886
3887     draw_player[pnr] = FALSE;
3888
3889     return;
3890   }
3891 #endif
3892
3893   int last_player_graphic  = static_last_player_graphic[pnr];
3894   int last_player_frame    = static_last_player_frame[pnr];
3895   boolean player_is_opaque = static_player_is_opaque[pnr];
3896
3897   int jx = player->jx;
3898   int jy = player->jy;
3899   int move_dir = (player->is_waiting ? player->dir_waiting : player->MovDir);
3900   int dx = (move_dir == MV_LEFT ? -1 : move_dir == MV_RIGHT ? +1 : 0);
3901   int dy = (move_dir == MV_UP   ? -1 : move_dir == MV_DOWN  ? +1 : 0);
3902   int last_jx = (player->is_moving ? jx - dx : jx);
3903   int last_jy = (player->is_moving ? jy - dy : jy);
3904   int next_jx = jx + dx;
3905   int next_jy = jy + dy;
3906   boolean player_is_moving = (player->MovPos != 0 ? TRUE : FALSE);
3907   int sx = SCREENX(jx);
3908   int sy = SCREENY(jy);
3909   int sxx = (move_dir == MV_LEFT || move_dir == MV_RIGHT ? player->GfxPos : 0);
3910   int syy = (move_dir == MV_UP   || move_dir == MV_DOWN  ? player->GfxPos : 0);
3911   int element = Tile[jx][jy];
3912   int last_element = Tile[last_jx][last_jy];
3913   int action = (player->is_pushing    ? ACTION_PUSHING         :
3914                 player->is_digging    ? ACTION_DIGGING         :
3915                 player->is_collecting ? ACTION_COLLECTING      :
3916                 player->is_moving     ? ACTION_MOVING          :
3917                 player->is_snapping   ? ACTION_SNAPPING        :
3918                 player->is_dropping   ? ACTION_DROPPING        :
3919                 player->is_waiting    ? player->action_waiting :
3920                 ACTION_DEFAULT);
3921
3922   if (drawing_stage == DRAW_PLAYER_STAGE_INIT)
3923   {
3924     // ------------------------------------------------------------------------
3925     // initialize drawing the player
3926     // ------------------------------------------------------------------------
3927
3928     draw_player[pnr] = FALSE;
3929
3930     // GfxElement[][] is set to the element the player is digging or collecting;
3931     // remove also for off-screen player if the player is not moving anymore
3932     if (IN_LEV_FIELD(jx, jy) && !player_is_moving)
3933       GfxElement[jx][jy] = EL_UNDEFINED;
3934
3935     if (!player->active || !IN_SCR_FIELD(SCREENX(last_jx), SCREENY(last_jy)))
3936       return;
3937
3938     if (element == EL_EXPLOSION)
3939       return;
3940
3941     InitPlayerGfxAnimation(player, action, move_dir);
3942
3943     draw_player[pnr] = TRUE;
3944   }
3945   else if (drawing_stage == DRAW_PLAYER_STAGE_LAST_FIELD)
3946   {
3947     // ------------------------------------------------------------------------
3948     // draw things in the field the player is leaving, if needed
3949     // ------------------------------------------------------------------------
3950
3951     if (!IN_SCR_FIELD(sx, sy))
3952       draw_player[pnr] = FALSE;
3953
3954     if (!player->is_moving)
3955       return;
3956
3957     if (Back[last_jx][last_jy] && IS_DRAWABLE(last_element))
3958     {
3959       DrawLevelElement(last_jx, last_jy, Back[last_jx][last_jy]);
3960
3961       if (last_element == EL_DYNAMITE_ACTIVE ||
3962           last_element == EL_EM_DYNAMITE_ACTIVE ||
3963           last_element == EL_SP_DISK_RED_ACTIVE)
3964         DrawDynamite(last_jx, last_jy);
3965       else
3966         DrawLevelFieldThruMask(last_jx, last_jy);
3967     }
3968     else if (last_element == EL_DYNAMITE_ACTIVE ||
3969              last_element == EL_EM_DYNAMITE_ACTIVE ||
3970              last_element == EL_SP_DISK_RED_ACTIVE)
3971       DrawDynamite(last_jx, last_jy);
3972     else
3973       DrawLevelField(last_jx, last_jy);
3974
3975     if (player->is_pushing && IN_SCR_FIELD(SCREENX(next_jx), SCREENY(next_jy)))
3976       DrawLevelElement(next_jx, next_jy, EL_EMPTY);
3977   }
3978   else if (drawing_stage == DRAW_PLAYER_STAGE_FIELD_UNDER_PLAYER)
3979   {
3980     // ------------------------------------------------------------------------
3981     // draw things behind the player, if needed
3982     // ------------------------------------------------------------------------
3983
3984     if (Back[jx][jy])
3985     {
3986       DrawLevelElement(jx, jy, Back[jx][jy]);
3987
3988       return;
3989     }
3990
3991     if (IS_ACTIVE_BOMB(element))
3992     {
3993       DrawLevelElement(jx, jy, EL_EMPTY);
3994
3995       return;
3996     }
3997
3998     if (player_is_moving && GfxElement[jx][jy] != EL_UNDEFINED)
3999     {
4000       int old_element = GfxElement[jx][jy];
4001       int old_graphic = el_act_dir2img(old_element, action, move_dir);
4002       int frame = getGraphicAnimationFrame(old_graphic, player->StepFrame);
4003
4004       if (GFX_CRUMBLED(old_element))
4005         DrawLevelFieldCrumbledDigging(jx, jy, move_dir, player->StepFrame);
4006       else
4007         DrawGraphic(sx, sy, old_graphic, frame);
4008
4009       if (graphic_info[old_graphic].anim_mode & ANIM_OPAQUE_PLAYER)
4010         static_player_is_opaque[pnr] = TRUE;
4011     }
4012     else
4013     {
4014       GfxElement[jx][jy] = EL_UNDEFINED;
4015
4016       // make sure that pushed elements are drawn with correct frame rate
4017       int graphic = el_act_dir2img(element, ACTION_PUSHING, move_dir);
4018
4019       if (player->is_pushing && player->is_moving && !IS_ANIM_MODE_CE(graphic))
4020         GfxFrame[jx][jy] = player->StepFrame;
4021
4022       DrawLevelField(jx, jy);
4023     }
4024   }
4025   else if (drawing_stage == DRAW_PLAYER_STAGE_ELEMENT_PUSHED)
4026   {
4027     // ------------------------------------------------------------------------
4028     // draw things the player is pushing, if needed
4029     // ------------------------------------------------------------------------
4030
4031     if (!player->is_pushing || !player->is_moving)
4032       return;
4033
4034     int gfx_frame = GfxFrame[jx][jy];
4035
4036     if (!IS_MOVING(jx, jy))             // push movement already finished
4037     {
4038       element = Tile[next_jx][next_jy];
4039       gfx_frame = GfxFrame[next_jx][next_jy];
4040     }
4041
4042     int graphic = el_act_dir2img(element, ACTION_PUSHING, move_dir);
4043     int sync_frame = (IS_ANIM_MODE_CE(graphic) ? gfx_frame : player->StepFrame);
4044     int frame = getGraphicAnimationFrame(graphic, sync_frame);
4045
4046     // draw background element under pushed element (like the Sokoban field)
4047     if (game.use_masked_pushing && IS_MOVING(jx, jy))
4048     {
4049       // this allows transparent pushing animation over non-black background
4050
4051       if (Back[jx][jy])
4052         DrawLevelElement(jx, jy, Back[jx][jy]);
4053       else
4054         DrawLevelElement(jx, jy, EL_EMPTY);
4055
4056       if (Back[next_jx][next_jy])
4057         DrawLevelElement(next_jx, next_jy, Back[next_jx][next_jy]);
4058       else
4059         DrawLevelElement(next_jx, next_jy, EL_EMPTY);
4060     }
4061     else if (Back[next_jx][next_jy])
4062       DrawLevelElement(next_jx, next_jy, Back[next_jx][next_jy]);
4063
4064     int px = SCREENX(jx), py = SCREENY(jy);
4065     int pxx = (TILEX - ABS(sxx)) * dx;
4066     int pyy = (TILEY - ABS(syy)) * dy;
4067
4068 #if 1
4069     // do not draw (EM style) pushing animation when pushing is finished
4070     // (two-tile animations usually do not contain start and end frame)
4071     if (graphic_info[graphic].double_movement && !IS_MOVING(jx, jy))
4072       DrawLevelElement(next_jx, next_jy, Tile[next_jx][next_jy]);
4073     else
4074       DrawGraphicShiftedThruMask(px, py, pxx, pyy, graphic, frame, NO_CUTTING);
4075 #else
4076     // masked drawing is needed for EMC style (double) movement graphics
4077     // !!! (ONLY WHEN DRAWING PUSHED ELEMENT OVER THE PLAYER) !!!
4078     DrawGraphicShiftedThruMask(px, py, pxx, pyy, graphic, frame, NO_CUTTING);
4079 #endif
4080   }
4081   else if (drawing_stage == DRAW_PLAYER_STAGE_PLAYER)
4082   {
4083     // ------------------------------------------------------------------------
4084     // draw player himself
4085     // ------------------------------------------------------------------------
4086
4087     int graphic = getPlayerGraphic(player, move_dir);
4088
4089     // in the case of changed player action or direction, prevent the current
4090     // animation frame from being restarted for identical animations
4091     if (player->Frame == 0 && equalGraphics(graphic, last_player_graphic))
4092       player->Frame = last_player_frame;
4093
4094     int frame = getGraphicAnimationFrame(graphic, player->Frame);
4095
4096     if (player_is_opaque)
4097       DrawGraphicShifted(sx,sy, sxx,syy, graphic, frame, NO_CUTTING,NO_MASKING);
4098     else
4099       DrawGraphicShiftedThruMask(sx, sy, sxx, syy, graphic, frame, NO_CUTTING);
4100
4101     if (SHIELD_ON(player))
4102     {
4103       graphic = (player->shield_deadly_time_left ? IMG_SHIELD_DEADLY_ACTIVE :
4104                  IMG_SHIELD_NORMAL_ACTIVE);
4105       frame = getGraphicAnimationFrame(graphic, -1);
4106
4107       DrawGraphicShiftedThruMask(sx, sy, sxx, syy, graphic, frame, NO_CUTTING);
4108     }
4109   }
4110   else if (drawing_stage == DRAW_PLAYER_STAGE_ELEMENT_OVER_PLAYER)
4111   {
4112     // ------------------------------------------------------------------------
4113     // draw things in front of player (active dynamite or dynabombs)
4114     // ------------------------------------------------------------------------
4115
4116     if (IS_ACTIVE_BOMB(element))
4117     {
4118       int graphic = el2img(element);
4119       int frame = getGraphicAnimationFrame(graphic, GfxFrame[jx][jy]);
4120
4121       if (game.emulation == EMU_SUPAPLEX)
4122         DrawGraphic(sx, sy, IMG_SP_DISK_RED, frame);
4123       else
4124         DrawGraphicThruMask(sx, sy, graphic, frame);
4125     }
4126
4127     if (player_is_moving && last_element == EL_EXPLOSION)
4128     {
4129       int element = (GfxElement[last_jx][last_jy] != EL_UNDEFINED ?
4130                      GfxElement[last_jx][last_jy] :  EL_EMPTY);
4131       int graphic = el_act2img(element, ACTION_EXPLODING);
4132       int delay = (game.emulation == EMU_SUPAPLEX ? 3 : 2);
4133       int phase = ExplodePhase[last_jx][last_jy] - 1;
4134       int frame = getGraphicAnimationFrame(graphic, phase - delay);
4135
4136       if (phase >= delay)
4137         DrawGraphicThruMask(SCREENX(last_jx), SCREENY(last_jy), graphic, frame);
4138     }
4139   }
4140   else if (drawing_stage == DRAW_PLAYER_STAGE_FIELD_OVER_PLAYER)
4141   {
4142     // ------------------------------------------------------------------------
4143     // draw elements the player is just walking/passing through/under
4144     // ------------------------------------------------------------------------
4145
4146     if (player_is_moving)
4147     {
4148       // handle the field the player is leaving ...
4149       if (IS_ACCESSIBLE_INSIDE(last_element))
4150         DrawLevelField(last_jx, last_jy);
4151       else if (IS_ACCESSIBLE_UNDER(last_element))
4152         DrawLevelFieldThruMask(last_jx, last_jy);
4153     }
4154
4155     // do not redraw accessible elements if the player is just pushing them
4156     if (!player_is_moving || !player->is_pushing)
4157     {
4158       // ... and the field the player is entering
4159       if (IS_ACCESSIBLE_INSIDE(element))
4160         DrawLevelField(jx, jy);
4161       else if (IS_ACCESSIBLE_UNDER(element))
4162         DrawLevelFieldThruMask(jx, jy);
4163     }
4164
4165     MarkTileDirty(sx, sy);
4166   }
4167 }
4168
4169 void DrawPlayer(struct PlayerInfo *player)
4170 {
4171   int i;
4172
4173   for (i = 0; i < NUM_DRAW_PLAYER_STAGES; i++)
4174     DrawPlayerExt(player, i);
4175 }
4176
4177 void DrawAllPlayers(void)
4178 {
4179   int i, j;
4180
4181   for (i = 0; i < NUM_DRAW_PLAYER_STAGES; i++)
4182     for (j = 0; j < MAX_PLAYERS; j++)
4183       if (stored_player[j].active)
4184         DrawPlayerExt(&stored_player[j], i);
4185 }
4186
4187 void DrawPlayerField(int x, int y)
4188 {
4189   if (!IS_PLAYER(x, y))
4190     return;
4191
4192   DrawPlayer(PLAYERINFO(x, y));
4193 }
4194
4195 // ----------------------------------------------------------------------------
4196
4197 void WaitForEventToContinue(void)
4198 {
4199   boolean still_wait = TRUE;
4200
4201   if (program.headless)
4202     return;
4203
4204   // simulate releasing mouse button over last gadget, if still pressed
4205   if (button_status)
4206     HandleGadgets(-1, -1, 0);
4207
4208   button_status = MB_RELEASED;
4209
4210   ClearEventQueue();
4211
4212   while (still_wait)
4213   {
4214     Event event;
4215
4216     if (NextValidEvent(&event))
4217     {
4218       switch (event.type)
4219       {
4220         case EVENT_BUTTONRELEASE:
4221         case EVENT_KEYPRESS:
4222         case SDL_CONTROLLERBUTTONDOWN:
4223         case SDL_JOYBUTTONDOWN:
4224           still_wait = FALSE;
4225           break;
4226
4227         case EVENT_KEYRELEASE:
4228           ClearPlayerAction();
4229           break;
4230
4231         default:
4232           HandleOtherEvents(&event);
4233           break;
4234       }
4235     }
4236     else if (AnyJoystickButton() == JOY_BUTTON_NEW_PRESSED)
4237     {
4238       still_wait = FALSE;
4239     }
4240
4241     BackToFront();
4242   }
4243 }
4244
4245 #define MAX_REQUEST_LINES               13
4246 #define MAX_REQUEST_LINE_FONT1_LEN      7
4247 #define MAX_REQUEST_LINE_FONT2_LEN      10
4248
4249 static int RequestHandleEvents(unsigned int req_state)
4250 {
4251   boolean game_just_ended = (game_status == GAME_MODE_PLAYING &&
4252                              checkGameEnded());
4253   int width  = request.width;
4254   int height = request.height;
4255   int sx, sy;
4256   int result;
4257
4258   // when showing request dialog after game ended, deactivate game panel
4259   if (game_just_ended)
4260     game.panel.active = FALSE;
4261
4262   game.request_active = TRUE;
4263
4264   setRequestPosition(&sx, &sy, FALSE);
4265
4266   button_status = MB_RELEASED;
4267
4268   request_gadget_id = -1;
4269   result = -1;
4270
4271   while (result < 0)
4272   {
4273     if (game_just_ended)
4274     {
4275       // the MM game engine does not use a special (scrollable) field buffer
4276       if (level.game_engine_type != GAME_ENGINE_TYPE_MM)
4277         SetDrawtoField(DRAW_TO_FIELDBUFFER);
4278
4279       HandleGameActions();
4280
4281       SetDrawtoField(DRAW_TO_BACKBUFFER);
4282
4283       if (global.use_envelope_request)
4284       {
4285         // copy current state of request area to middle of playfield area
4286         BlitBitmap(bitmap_db_store_2, drawto, sx, sy, width, height, sx, sy);
4287       }
4288     }
4289
4290     if (PendingEvent())
4291     {
4292       Event event;
4293
4294       while (NextValidEvent(&event))
4295       {
4296         switch (event.type)
4297         {
4298           case EVENT_BUTTONPRESS:
4299           case EVENT_BUTTONRELEASE:
4300           case EVENT_MOTIONNOTIFY:
4301           {
4302             int mx, my;
4303
4304             if (event.type == EVENT_MOTIONNOTIFY)
4305             {
4306               if (!button_status)
4307                 continue;
4308
4309               motion_status = TRUE;
4310               mx = ((MotionEvent *) &event)->x;
4311               my = ((MotionEvent *) &event)->y;
4312             }
4313             else
4314             {
4315               motion_status = FALSE;
4316               mx = ((ButtonEvent *) &event)->x;
4317               my = ((ButtonEvent *) &event)->y;
4318               if (event.type == EVENT_BUTTONPRESS)
4319                 button_status = ((ButtonEvent *) &event)->button;
4320               else
4321                 button_status = MB_RELEASED;
4322             }
4323
4324             // this sets 'request_gadget_id'
4325             HandleGadgets(mx, my, button_status);
4326
4327             switch (request_gadget_id)
4328             {
4329               case TOOL_CTRL_ID_YES:
4330               case TOOL_CTRL_ID_TOUCH_YES:
4331                 result = TRUE;
4332                 break;
4333               case TOOL_CTRL_ID_NO:
4334               case TOOL_CTRL_ID_TOUCH_NO:
4335                 result = FALSE;
4336                 break;
4337               case TOOL_CTRL_ID_CONFIRM:
4338               case TOOL_CTRL_ID_TOUCH_CONFIRM:
4339                 result = TRUE | FALSE;
4340                 break;
4341
4342               case TOOL_CTRL_ID_PLAYER_1:
4343                 result = 1;
4344                 break;
4345               case TOOL_CTRL_ID_PLAYER_2:
4346                 result = 2;
4347                 break;
4348               case TOOL_CTRL_ID_PLAYER_3:
4349                 result = 3;
4350                 break;
4351               case TOOL_CTRL_ID_PLAYER_4:
4352                 result = 4;
4353                 break;
4354
4355               default:
4356                 // only check clickable animations if no request gadget clicked
4357                 HandleGlobalAnimClicks(mx, my, button_status, FALSE);
4358                 break;
4359             }
4360
4361             break;
4362           }
4363
4364           case SDL_WINDOWEVENT:
4365             HandleWindowEvent((WindowEvent *) &event);
4366             break;
4367
4368           case SDL_APP_WILLENTERBACKGROUND:
4369           case SDL_APP_DIDENTERBACKGROUND:
4370           case SDL_APP_WILLENTERFOREGROUND:
4371           case SDL_APP_DIDENTERFOREGROUND:
4372             HandlePauseResumeEvent((PauseResumeEvent *) &event);
4373             break;
4374
4375           case EVENT_KEYPRESS:
4376           {
4377             Key key = GetEventKey((KeyEvent *)&event, TRUE);
4378
4379             switch (key)
4380             {
4381               case KSYM_space:
4382                 if (req_state & REQ_CONFIRM)
4383                   result = 1;
4384                 break;
4385
4386               case KSYM_Return:
4387               case KSYM_y:
4388               case KSYM_Y:
4389               case KSYM_Select:
4390               case KSYM_Menu:
4391 #if defined(KSYM_Rewind)
4392               case KSYM_Rewind:         // for Amazon Fire TV remote
4393 #endif
4394                 result = 1;
4395                 break;
4396
4397               case KSYM_Escape:
4398               case KSYM_n:
4399               case KSYM_N:
4400               case KSYM_Back:
4401 #if defined(KSYM_FastForward)
4402               case KSYM_FastForward:    // for Amazon Fire TV remote
4403 #endif
4404                 result = 0;
4405                 break;
4406
4407               default:
4408                 HandleKeysDebug(key, KEY_PRESSED);
4409                 break;
4410             }
4411
4412             if (req_state & REQ_PLAYER)
4413             {
4414               int old_player_nr = setup.network_player_nr;
4415
4416               if (result != -1)
4417                 result = old_player_nr + 1;
4418
4419               switch (key)
4420               {
4421                 case KSYM_space:
4422                   result = old_player_nr + 1;
4423                   break;
4424
4425                 case KSYM_Up:
4426                 case KSYM_1:
4427                   result = 1;
4428                   break;
4429
4430                 case KSYM_Right:
4431                 case KSYM_2:
4432                   result = 2;
4433                   break;
4434
4435                 case KSYM_Down:
4436                 case KSYM_3:
4437                   result = 3;
4438                   break;
4439
4440                 case KSYM_Left:
4441                 case KSYM_4:
4442                   result = 4;
4443                   break;
4444
4445                 default:
4446                   break;
4447               }
4448             }
4449
4450             break;
4451           }
4452
4453           case EVENT_KEYRELEASE:
4454             ClearPlayerAction();
4455             break;
4456
4457           case SDL_CONTROLLERBUTTONDOWN:
4458             switch (event.cbutton.button)
4459             {
4460               case SDL_CONTROLLER_BUTTON_A:
4461               case SDL_CONTROLLER_BUTTON_X:
4462               case SDL_CONTROLLER_BUTTON_LEFTSHOULDER:
4463               case SDL_CONTROLLER_BUTTON_LEFTSTICK:
4464                 result = 1;
4465                 break;
4466
4467               case SDL_CONTROLLER_BUTTON_B:
4468               case SDL_CONTROLLER_BUTTON_Y:
4469               case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER:
4470               case SDL_CONTROLLER_BUTTON_RIGHTSTICK:
4471               case SDL_CONTROLLER_BUTTON_BACK:
4472                 result = 0;
4473                 break;
4474             }
4475
4476             if (req_state & REQ_PLAYER)
4477             {
4478               int old_player_nr = setup.network_player_nr;
4479
4480               if (result != -1)
4481                 result = old_player_nr + 1;
4482
4483               switch (event.cbutton.button)
4484               {
4485                 case SDL_CONTROLLER_BUTTON_DPAD_UP:
4486                 case SDL_CONTROLLER_BUTTON_Y:
4487                   result = 1;
4488                   break;
4489
4490                 case SDL_CONTROLLER_BUTTON_DPAD_RIGHT:
4491                 case SDL_CONTROLLER_BUTTON_B:
4492                   result = 2;
4493                   break;
4494
4495                 case SDL_CONTROLLER_BUTTON_DPAD_DOWN:
4496                 case SDL_CONTROLLER_BUTTON_A:
4497                   result = 3;
4498                   break;
4499
4500                 case SDL_CONTROLLER_BUTTON_DPAD_LEFT:
4501                 case SDL_CONTROLLER_BUTTON_X:
4502                   result = 4;
4503                   break;
4504
4505                 default:
4506                   break;
4507               }
4508             }
4509
4510             break;
4511
4512           case SDL_CONTROLLERBUTTONUP:
4513             HandleJoystickEvent(&event);
4514             ClearPlayerAction();
4515             break;
4516
4517           default:
4518             HandleOtherEvents(&event);
4519             break;
4520         }
4521       }
4522     }
4523     else if (AnyJoystickButton() == JOY_BUTTON_NEW_PRESSED)
4524     {
4525       int joy = AnyJoystick();
4526
4527       if (joy & JOY_BUTTON_1)
4528         result = 1;
4529       else if (joy & JOY_BUTTON_2)
4530         result = 0;
4531     }
4532     else if (AnyJoystick())
4533     {
4534       int joy = AnyJoystick();
4535
4536       if (req_state & REQ_PLAYER)
4537       {
4538         if (joy & JOY_UP)
4539           result = 1;
4540         else if (joy & JOY_RIGHT)
4541           result = 2;
4542         else if (joy & JOY_DOWN)
4543           result = 3;
4544         else if (joy & JOY_LEFT)
4545           result = 4;
4546       }
4547     }
4548
4549     if (game_just_ended)
4550     {
4551       if (global.use_envelope_request)
4552       {
4553         // copy back current state of pressed buttons inside request area
4554         BlitBitmap(drawto, bitmap_db_store_2, sx, sy, width, height, sx, sy);
4555       }
4556     }
4557
4558     BackToFront();
4559   }
4560
4561   game.request_active = FALSE;
4562
4563   return result;
4564 }
4565
4566 static boolean RequestDoor(char *text, unsigned int req_state)
4567 {
4568   unsigned int old_door_state;
4569   int max_request_line_len = MAX_REQUEST_LINE_FONT1_LEN;
4570   int font_nr = FONT_TEXT_2;
4571   char *text_ptr;
4572   int result;
4573   int ty;
4574
4575   if (maxWordLengthInRequestString(text) > MAX_REQUEST_LINE_FONT1_LEN)
4576   {
4577     max_request_line_len = MAX_REQUEST_LINE_FONT2_LEN;
4578     font_nr = FONT_TEXT_1;
4579   }
4580
4581   if (game_status == GAME_MODE_PLAYING)
4582     BlitScreenToBitmap(backbuffer);
4583
4584   // disable deactivated drawing when quick-loading level tape recording
4585   if (tape.playing && tape.deactivate_display)
4586     TapeDeactivateDisplayOff(TRUE);
4587
4588   SetMouseCursor(CURSOR_DEFAULT);
4589
4590   // pause network game while waiting for request to answer
4591   if (network.enabled &&
4592       game_status == GAME_MODE_PLAYING &&
4593       !game.all_players_gone &&
4594       req_state & REQUEST_WAIT_FOR_INPUT)
4595     SendToServer_PausePlaying();
4596
4597   old_door_state = GetDoorState();
4598
4599   // simulate releasing mouse button over last gadget, if still pressed
4600   if (button_status)
4601     HandleGadgets(-1, -1, 0);
4602
4603   UnmapAllGadgets();
4604
4605   // draw released gadget before proceeding
4606   // BackToFront();
4607
4608   if (old_door_state & DOOR_OPEN_1)
4609   {
4610     CloseDoor(DOOR_CLOSE_1);
4611
4612     // save old door content
4613     BlitBitmap(bitmap_db_door_1, bitmap_db_door_1,
4614                0 * DXSIZE, 0, DXSIZE, DYSIZE, 1 * DXSIZE, 0);
4615   }
4616
4617   SetDoorBackgroundImage(IMG_BACKGROUND_DOOR);
4618   SetDrawBackgroundMask(REDRAW_FIELD | REDRAW_DOOR_1);
4619
4620   // clear door drawing field
4621   DrawBackground(DX, DY, DXSIZE, DYSIZE);
4622
4623   // force DOOR font inside door area
4624   SetFontStatus(GAME_MODE_PSEUDO_DOOR);
4625
4626   // write text for request
4627   for (text_ptr = text, ty = 0; ty < MAX_REQUEST_LINES; ty++)
4628   {
4629     char text_line[max_request_line_len + 1];
4630     int tx, tl, tc = 0;
4631
4632     if (!*text_ptr)
4633       break;
4634
4635     for (tl = 0, tx = 0; tx < max_request_line_len; tl++, tx++)
4636     {
4637       tc = *(text_ptr + tx);
4638       // if (!tc || tc == ' ')
4639       if (!tc || tc == ' ' || tc == '?' || tc == '!')
4640         break;
4641     }
4642
4643     if ((tc == '?' || tc == '!') && tl == 0)
4644       tl = 1;
4645
4646     if (!tl)
4647     { 
4648       text_ptr++; 
4649       ty--; 
4650       continue; 
4651     }
4652
4653     strncpy(text_line, text_ptr, tl);
4654     text_line[tl] = 0;
4655
4656     DrawText(DX + (DXSIZE - tl * getFontWidth(font_nr)) / 2,
4657              DY + 8 + ty * (getFontHeight(font_nr) + 2),
4658              text_line, font_nr);
4659
4660     text_ptr += tl + (tc == ' ' ? 1 : 0);
4661     // text_ptr += tl + (tc == ' ' || tc == '?' || tc == '!' ? 1 : 0);
4662   }
4663
4664   ResetFontStatus();
4665
4666   if (req_state & REQ_ASK)
4667   {
4668     MapGadget(tool_gadget[TOOL_CTRL_ID_YES]);
4669     MapGadget(tool_gadget[TOOL_CTRL_ID_NO]);
4670     MapGadget(tool_gadget[TOOL_CTRL_ID_TOUCH_YES]);
4671     MapGadget(tool_gadget[TOOL_CTRL_ID_TOUCH_NO]);
4672   }
4673   else if (req_state & REQ_CONFIRM)
4674   {
4675     MapGadget(tool_gadget[TOOL_CTRL_ID_CONFIRM]);
4676     MapGadget(tool_gadget[TOOL_CTRL_ID_TOUCH_CONFIRM]);
4677   }
4678   else if (req_state & REQ_PLAYER)
4679   {
4680     MapGadget(tool_gadget[TOOL_CTRL_ID_PLAYER_1]);
4681     MapGadget(tool_gadget[TOOL_CTRL_ID_PLAYER_2]);
4682     MapGadget(tool_gadget[TOOL_CTRL_ID_PLAYER_3]);
4683     MapGadget(tool_gadget[TOOL_CTRL_ID_PLAYER_4]);
4684   }
4685
4686   // copy request gadgets to door backbuffer
4687   BlitBitmap(drawto, bitmap_db_door_1, DX, DY, DXSIZE, DYSIZE, 0, 0);
4688
4689   OpenDoor(DOOR_OPEN_1);
4690
4691   if (!(req_state & REQUEST_WAIT_FOR_INPUT))
4692   {
4693     if (game_status == GAME_MODE_PLAYING)
4694     {
4695       SetPanelBackground();
4696       SetDrawBackgroundMask(REDRAW_DOOR_1);
4697     }
4698     else
4699     {
4700       SetDrawBackgroundMask(REDRAW_FIELD);
4701     }
4702
4703     return FALSE;
4704   }
4705
4706   SetDrawBackgroundMask(REDRAW_FIELD | REDRAW_DOOR_1);
4707
4708   // ---------- handle request buttons ----------
4709   result = RequestHandleEvents(req_state);
4710
4711   UnmapToolButtons();
4712
4713   if (!(req_state & REQ_STAY_OPEN))
4714   {
4715     CloseDoor(DOOR_CLOSE_1);
4716
4717     if (((old_door_state & DOOR_OPEN_1) && !(req_state & REQ_STAY_CLOSED)) ||
4718         (req_state & REQ_REOPEN))
4719       OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
4720   }
4721
4722   RemapAllGadgets();
4723
4724   if (game_status == GAME_MODE_PLAYING)
4725   {
4726     SetPanelBackground();
4727     SetDrawBackgroundMask(REDRAW_DOOR_1);
4728   }
4729   else
4730   {
4731     SetDrawBackgroundMask(REDRAW_FIELD);
4732   }
4733
4734   // continue network game after request
4735   if (network.enabled &&
4736       game_status == GAME_MODE_PLAYING &&
4737       !game.all_players_gone &&
4738       req_state & REQUEST_WAIT_FOR_INPUT)
4739     SendToServer_ContinuePlaying();
4740
4741   // restore deactivated drawing when quick-loading level tape recording
4742   if (tape.playing && tape.deactivate_display)
4743     TapeDeactivateDisplayOn();
4744
4745   return result;
4746 }
4747
4748 static boolean RequestEnvelope(char *text, unsigned int req_state)
4749 {
4750   int result;
4751
4752   if (game_status == GAME_MODE_PLAYING)
4753     BlitScreenToBitmap(backbuffer);
4754
4755   // disable deactivated drawing when quick-loading level tape recording
4756   if (tape.playing && tape.deactivate_display)
4757     TapeDeactivateDisplayOff(TRUE);
4758
4759   SetMouseCursor(CURSOR_DEFAULT);
4760
4761   // pause network game while waiting for request to answer
4762   if (network.enabled &&
4763       game_status == GAME_MODE_PLAYING &&
4764       !game.all_players_gone &&
4765       req_state & REQUEST_WAIT_FOR_INPUT)
4766     SendToServer_PausePlaying();
4767
4768   // simulate releasing mouse button over last gadget, if still pressed
4769   if (button_status)
4770     HandleGadgets(-1, -1, 0);
4771
4772   UnmapAllGadgets();
4773
4774   // (replace with setting corresponding request background)
4775   // SetDoorBackgroundImage(IMG_BACKGROUND_DOOR);
4776   // SetDrawBackgroundMask(REDRAW_FIELD | REDRAW_DOOR_1);
4777
4778   // clear door drawing field
4779   // DrawBackground(DX, DY, DXSIZE, DYSIZE);
4780
4781   ShowEnvelopeRequest(text, req_state, ACTION_OPENING);
4782
4783   if (!(req_state & REQUEST_WAIT_FOR_INPUT))
4784   {
4785     if (game_status == GAME_MODE_PLAYING)
4786     {
4787       SetPanelBackground();
4788       SetDrawBackgroundMask(REDRAW_DOOR_1);
4789     }
4790     else
4791     {
4792       SetDrawBackgroundMask(REDRAW_FIELD);
4793     }
4794
4795     return FALSE;
4796   }
4797
4798   SetDrawBackgroundMask(REDRAW_FIELD | REDRAW_DOOR_1);
4799
4800   // ---------- handle request buttons ----------
4801   result = RequestHandleEvents(req_state);
4802
4803   UnmapToolButtons();
4804
4805   ShowEnvelopeRequest(text, req_state, ACTION_CLOSING);
4806
4807   RemapAllGadgets();
4808
4809   if (game_status == GAME_MODE_PLAYING)
4810   {
4811     SetPanelBackground();
4812     SetDrawBackgroundMask(REDRAW_DOOR_1);
4813   }
4814   else
4815   {
4816     SetDrawBackgroundMask(REDRAW_FIELD);
4817   }
4818
4819   // continue network game after request
4820   if (network.enabled &&
4821       game_status == GAME_MODE_PLAYING &&
4822       !game.all_players_gone &&
4823       req_state & REQUEST_WAIT_FOR_INPUT)
4824     SendToServer_ContinuePlaying();
4825
4826   // restore deactivated drawing when quick-loading level tape recording
4827   if (tape.playing && tape.deactivate_display)
4828     TapeDeactivateDisplayOn();
4829
4830   return result;
4831 }
4832
4833 boolean Request(char *text, unsigned int req_state)
4834 {
4835   boolean overlay_enabled = GetOverlayEnabled();
4836   boolean result;
4837
4838   SetOverlayEnabled(FALSE);
4839
4840   if (global.use_envelope_request)
4841     result = RequestEnvelope(text, req_state);
4842   else
4843     result = RequestDoor(text, req_state);
4844
4845   SetOverlayEnabled(overlay_enabled);
4846
4847   return result;
4848 }
4849
4850 static int compareDoorPartOrderInfo(const void *object1, const void *object2)
4851 {
4852   const struct DoorPartOrderInfo *dpo1 = (struct DoorPartOrderInfo *)object1;
4853   const struct DoorPartOrderInfo *dpo2 = (struct DoorPartOrderInfo *)object2;
4854   int compare_result;
4855
4856   if (dpo1->sort_priority != dpo2->sort_priority)
4857     compare_result = dpo1->sort_priority - dpo2->sort_priority;
4858   else
4859     compare_result = dpo1->nr - dpo2->nr;
4860
4861   return compare_result;
4862 }
4863
4864 void InitGraphicCompatibilityInfo_Doors(void)
4865 {
4866   struct
4867   {
4868     int door_token;
4869     int part_1, part_8;
4870     struct DoorInfo *door;
4871   }
4872   doors[] =
4873   {
4874     { DOOR_1,   IMG_GFX_DOOR_1_PART_1,  IMG_GFX_DOOR_1_PART_8,  &door_1 },
4875     { DOOR_2,   IMG_GFX_DOOR_2_PART_1,  IMG_GFX_DOOR_2_PART_8,  &door_2 },
4876
4877     { -1,       -1,                     -1,                     NULL    }
4878   };
4879   struct Rect door_rect_list[] =
4880   {
4881     { DX, DY, DXSIZE, DYSIZE },
4882     { VX, VY, VXSIZE, VYSIZE }
4883   };
4884   int i, j;
4885
4886   for (i = 0; doors[i].door_token != -1; i++)
4887   {
4888     int door_token = doors[i].door_token;
4889     int door_index = DOOR_INDEX_FROM_TOKEN(door_token);
4890     int part_1 = doors[i].part_1;
4891     int part_8 = doors[i].part_8;
4892     int part_2 = part_1 + 1;
4893     int part_3 = part_1 + 2;
4894     struct DoorInfo *door = doors[i].door;
4895     struct Rect *door_rect = &door_rect_list[door_index];
4896     boolean door_gfx_redefined = FALSE;
4897
4898     // check if any door part graphic definitions have been redefined
4899
4900     for (j = 0; door_part_controls[j].door_token != -1; j++)
4901     {
4902       struct DoorPartControlInfo *dpc = &door_part_controls[j];
4903       struct FileInfo *fi = getImageListEntryFromImageID(dpc->graphic);
4904
4905       if (dpc->door_token == door_token && fi->redefined)
4906         door_gfx_redefined = TRUE;
4907     }
4908
4909     // check for old-style door graphic/animation modifications
4910
4911     if (!door_gfx_redefined)
4912     {
4913       if (door->anim_mode & ANIM_STATIC_PANEL)
4914       {
4915         door->panel.step_xoffset = 0;
4916         door->panel.step_yoffset = 0;
4917       }
4918
4919       if (door->anim_mode & (ANIM_HORIZONTAL | ANIM_VERTICAL))
4920       {
4921         struct GraphicInfo *g_part_1 = &graphic_info[part_1];
4922         struct GraphicInfo *g_part_2 = &graphic_info[part_2];
4923         int num_door_steps, num_panel_steps;
4924
4925         // remove door part graphics other than the two default wings
4926
4927         for (j = 0; door_part_controls[j].door_token != -1; j++)
4928         {
4929           struct DoorPartControlInfo *dpc = &door_part_controls[j];
4930           struct GraphicInfo *g = &graphic_info[dpc->graphic];
4931
4932           if (dpc->graphic >= part_3 &&
4933               dpc->graphic <= part_8)
4934             g->bitmap = NULL;
4935         }
4936
4937         // set graphics and screen positions of the default wings
4938
4939         g_part_1->width  = door_rect->width;
4940         g_part_1->height = door_rect->height;
4941         g_part_2->width  = door_rect->width;
4942         g_part_2->height = door_rect->height;
4943         g_part_2->src_x = door_rect->width;
4944         g_part_2->src_y = g_part_1->src_y;
4945
4946         door->part_2.x = door->part_1.x;
4947         door->part_2.y = door->part_1.y;
4948
4949         if (door->width != -1)
4950         {
4951           g_part_1->width = door->width;
4952           g_part_2->width = door->width;
4953
4954           // special treatment for graphics and screen position of right wing
4955           g_part_2->src_x += door_rect->width - door->width;
4956           door->part_2.x  += door_rect->width - door->width;
4957         }
4958
4959         if (door->height != -1)
4960         {
4961           g_part_1->height = door->height;
4962           g_part_2->height = door->height;
4963
4964           // special treatment for graphics and screen position of bottom wing
4965           g_part_2->src_y += door_rect->height - door->height;
4966           door->part_2.y  += door_rect->height - door->height;
4967         }
4968
4969         // set animation delays for the default wings and panels
4970
4971         door->part_1.step_delay = door->step_delay;
4972         door->part_2.step_delay = door->step_delay;
4973         door->panel.step_delay  = door->step_delay;
4974
4975         // set animation draw order for the default wings
4976
4977         door->part_1.sort_priority = 2; // draw left wing over ...
4978         door->part_2.sort_priority = 1; //          ... right wing
4979
4980         // set animation draw offset for the default wings
4981
4982         if (door->anim_mode & ANIM_HORIZONTAL)
4983         {
4984           door->part_1.step_xoffset = door->step_offset;
4985           door->part_1.step_yoffset = 0;
4986           door->part_2.step_xoffset = door->step_offset * -1;
4987           door->part_2.step_yoffset = 0;
4988
4989           num_door_steps = g_part_1->width / door->step_offset;
4990         }
4991         else    // ANIM_VERTICAL
4992         {
4993           door->part_1.step_xoffset = 0;
4994           door->part_1.step_yoffset = door->step_offset;
4995           door->part_2.step_xoffset = 0;
4996           door->part_2.step_yoffset = door->step_offset * -1;
4997
4998           num_door_steps = g_part_1->height / door->step_offset;
4999         }
5000
5001         // set animation draw offset for the default panels
5002
5003         if (door->step_offset > 1)
5004         {
5005           num_panel_steps = 2 * door_rect->height / door->step_offset;
5006           door->panel.start_step = num_panel_steps - num_door_steps;
5007           door->panel.start_step_closing = door->panel.start_step;
5008         }
5009         else
5010         {
5011           num_panel_steps = door_rect->height / door->step_offset;
5012           door->panel.start_step = num_panel_steps - num_door_steps / 2;
5013           door->panel.start_step_closing = door->panel.start_step;
5014           door->panel.step_delay *= 2;
5015         }
5016       }
5017     }
5018   }
5019 }
5020
5021 void InitDoors(void)
5022 {
5023   int i;
5024
5025   for (i = 0; door_part_controls[i].door_token != -1; i++)
5026   {
5027     struct DoorPartControlInfo *dpc = &door_part_controls[i];
5028     struct DoorPartOrderInfo *dpo = &door_part_order[i];
5029
5030     // initialize "start_step_opening" and "start_step_closing", if needed
5031     if (dpc->pos->start_step_opening == 0 &&
5032         dpc->pos->start_step_closing == 0)
5033     {
5034       // dpc->pos->start_step_opening = dpc->pos->start_step;
5035       dpc->pos->start_step_closing = dpc->pos->start_step;
5036     }
5037
5038     // fill structure for door part draw order (sorted below)
5039     dpo->nr = i;
5040     dpo->sort_priority = dpc->pos->sort_priority;
5041   }
5042
5043   // sort door part controls according to sort_priority and graphic number
5044   qsort(door_part_order, MAX_DOOR_PARTS,
5045         sizeof(struct DoorPartOrderInfo), compareDoorPartOrderInfo);
5046 }
5047
5048 unsigned int OpenDoor(unsigned int door_state)
5049 {
5050   if (door_state & DOOR_COPY_BACK)
5051   {
5052     if (door_state & DOOR_OPEN_1)
5053       BlitBitmap(bitmap_db_door_1, bitmap_db_door_1,
5054                  1 * DXSIZE, 0, DXSIZE, DYSIZE, 0 * DXSIZE, 0);
5055
5056     if (door_state & DOOR_OPEN_2)
5057       BlitBitmap(bitmap_db_door_2, bitmap_db_door_2,
5058                  1 * VXSIZE, 0, VXSIZE, VYSIZE, 0 * VXSIZE, 0);
5059
5060     door_state &= ~DOOR_COPY_BACK;
5061   }
5062
5063   return MoveDoor(door_state);
5064 }
5065
5066 unsigned int CloseDoor(unsigned int door_state)
5067 {
5068   unsigned int old_door_state = GetDoorState();
5069
5070   if (!(door_state & DOOR_NO_COPY_BACK))
5071   {
5072     if (old_door_state & DOOR_OPEN_1)
5073       BlitBitmap(backbuffer, bitmap_db_door_1,
5074                  DX, DY, DXSIZE, DYSIZE, 0, 0);
5075
5076     if (old_door_state & DOOR_OPEN_2)
5077       BlitBitmap(backbuffer, bitmap_db_door_2,
5078                  VX, VY, VXSIZE, VYSIZE, 0, 0);
5079
5080     door_state &= ~DOOR_NO_COPY_BACK;
5081   }
5082
5083   return MoveDoor(door_state);
5084 }
5085
5086 unsigned int GetDoorState(void)
5087 {
5088   return MoveDoor(DOOR_GET_STATE);
5089 }
5090
5091 unsigned int SetDoorState(unsigned int door_state)
5092 {
5093   return MoveDoor(door_state | DOOR_SET_STATE);
5094 }
5095
5096 static int euclid(int a, int b)
5097 {
5098   return (b ? euclid(b, a % b) : a);
5099 }
5100
5101 unsigned int MoveDoor(unsigned int door_state)
5102 {
5103   struct Rect door_rect_list[] =
5104   {
5105     { DX, DY, DXSIZE, DYSIZE },
5106     { VX, VY, VXSIZE, VYSIZE }
5107   };
5108   static int door1 = DOOR_CLOSE_1;
5109   static int door2 = DOOR_CLOSE_2;
5110   unsigned int door_delay = 0;
5111   unsigned int door_delay_value;
5112   int i;
5113
5114   if (door_state == DOOR_GET_STATE)
5115     return (door1 | door2);
5116
5117   if (door_state & DOOR_SET_STATE)
5118   {
5119     if (door_state & DOOR_ACTION_1)
5120       door1 = door_state & DOOR_ACTION_1;
5121     if (door_state & DOOR_ACTION_2)
5122       door2 = door_state & DOOR_ACTION_2;
5123
5124     return (door1 | door2);
5125   }
5126
5127   if (!(door_state & DOOR_FORCE_REDRAW))
5128   {
5129     if (door1 == DOOR_OPEN_1 && door_state & DOOR_OPEN_1)
5130       door_state &= ~DOOR_OPEN_1;
5131     else if (door1 == DOOR_CLOSE_1 && door_state & DOOR_CLOSE_1)
5132       door_state &= ~DOOR_CLOSE_1;
5133     if (door2 == DOOR_OPEN_2 && door_state & DOOR_OPEN_2)
5134       door_state &= ~DOOR_OPEN_2;
5135     else if (door2 == DOOR_CLOSE_2 && door_state & DOOR_CLOSE_2)
5136       door_state &= ~DOOR_CLOSE_2;
5137   }
5138
5139   if (global.autoplay_leveldir)
5140   {
5141     door_state |= DOOR_NO_DELAY;
5142     door_state &= ~DOOR_CLOSE_ALL;
5143   }
5144
5145   if (game_status == GAME_MODE_EDITOR && !(door_state & DOOR_FORCE_ANIM))
5146     door_state |= DOOR_NO_DELAY;
5147
5148   if (door_state & DOOR_ACTION)
5149   {
5150     boolean door_panel_drawn[NUM_DOORS];
5151     boolean panel_has_doors[NUM_DOORS];
5152     boolean door_part_skip[MAX_DOOR_PARTS];
5153     boolean door_part_done[MAX_DOOR_PARTS];
5154     boolean door_part_done_all;
5155     int num_steps[MAX_DOOR_PARTS];
5156     int max_move_delay = 0;     // delay for complete animations of all doors
5157     int max_step_delay = 0;     // delay (ms) between two animation frames
5158     int num_move_steps = 0;     // number of animation steps for all doors
5159     int max_move_delay_doors_only = 0;  // delay for doors only (no panel)
5160     int num_move_steps_doors_only = 0;  // steps for doors only (no panel)
5161     int current_move_delay = 0;
5162     int start = 0;
5163     int k;
5164
5165     for (i = 0; i < NUM_DOORS; i++)
5166       panel_has_doors[i] = FALSE;
5167
5168     for (i = 0; i < MAX_DOOR_PARTS; i++)
5169     {
5170       struct DoorPartControlInfo *dpc = &door_part_controls[i];
5171       struct GraphicInfo *g = &graphic_info[dpc->graphic];
5172       int door_token = dpc->door_token;
5173
5174       door_part_done[i] = FALSE;
5175       door_part_skip[i] = (!(door_state & door_token) ||
5176                            !g->bitmap);
5177     }
5178
5179     for (i = 0; i < MAX_DOOR_PARTS; i++)
5180     {
5181       int nr = door_part_order[i].nr;
5182       struct DoorPartControlInfo *dpc = &door_part_controls[nr];
5183       struct DoorPartPosInfo *pos = dpc->pos;
5184       struct GraphicInfo *g = &graphic_info[dpc->graphic];
5185       int door_token = dpc->door_token;
5186       int door_index = DOOR_INDEX_FROM_TOKEN(door_token);
5187       boolean is_panel = DOOR_PART_IS_PANEL(nr);
5188       int step_xoffset = ABS(pos->step_xoffset);
5189       int step_yoffset = ABS(pos->step_yoffset);
5190       int step_delay = pos->step_delay;
5191       int current_door_state = door_state & door_token;
5192       boolean door_opening = ((current_door_state & DOOR_OPEN)  != 0);
5193       boolean door_closing = ((current_door_state & DOOR_CLOSE) != 0);
5194       boolean part_opening = (is_panel ? door_closing : door_opening);
5195       int start_step = (part_opening ? pos->start_step_opening :
5196                         pos->start_step_closing);
5197       float move_xsize = (step_xoffset ? g->width  : 0);
5198       float move_ysize = (step_yoffset ? g->height : 0);
5199       int move_xsteps = (step_xoffset ? ceil(move_xsize / step_xoffset) : 0);
5200       int move_ysteps = (step_yoffset ? ceil(move_ysize / step_yoffset) : 0);
5201       int move_steps = (move_xsteps && move_ysteps ?
5202                         MIN(move_xsteps, move_ysteps) :
5203                         move_xsteps ? move_xsteps : move_ysteps) - start_step;
5204       int move_delay = move_steps * step_delay;
5205
5206       if (door_part_skip[nr])
5207         continue;
5208
5209       max_move_delay = MAX(max_move_delay, move_delay);
5210       max_step_delay = (max_step_delay == 0 ? step_delay :
5211                         euclid(max_step_delay, step_delay));
5212       num_steps[nr] = move_steps;
5213
5214       if (!is_panel)
5215       {
5216         max_move_delay_doors_only = MAX(max_move_delay_doors_only, move_delay);
5217
5218         panel_has_doors[door_index] = TRUE;
5219       }
5220     }
5221
5222     max_step_delay = MAX(1, max_step_delay);    // prevent division by zero
5223
5224     num_move_steps = max_move_delay / max_step_delay;
5225     num_move_steps_doors_only = max_move_delay_doors_only / max_step_delay;
5226
5227     door_delay_value = max_step_delay;
5228
5229     if ((door_state & DOOR_NO_DELAY) || setup.quick_doors)
5230     {
5231       start = num_move_steps - 1;
5232     }
5233     else
5234     {
5235       // opening door sound has priority over simultaneously closing door
5236       if (door_state & (DOOR_OPEN_1 | DOOR_OPEN_2))
5237       {
5238         PlayMenuSoundStereo(SND_DOOR_OPENING, SOUND_MIDDLE);
5239
5240         if (door_state & DOOR_OPEN_1)
5241           PlayMenuSoundStereo(SND_DOOR_1_OPENING, SOUND_MIDDLE);
5242         if (door_state & DOOR_OPEN_2)
5243           PlayMenuSoundStereo(SND_DOOR_2_OPENING, SOUND_MIDDLE);
5244       }
5245       else if (door_state & (DOOR_CLOSE_1 | DOOR_CLOSE_2))
5246       {
5247         PlayMenuSoundStereo(SND_DOOR_CLOSING, SOUND_MIDDLE);
5248
5249         if (door_state & DOOR_CLOSE_1)
5250           PlayMenuSoundStereo(SND_DOOR_1_CLOSING, SOUND_MIDDLE);
5251         if (door_state & DOOR_CLOSE_2)
5252           PlayMenuSoundStereo(SND_DOOR_2_CLOSING, SOUND_MIDDLE);
5253       }
5254     }
5255
5256     for (k = start; k < num_move_steps; k++)
5257     {
5258       int last_frame = num_move_steps - 1;      // last frame of this "for" loop
5259
5260       door_part_done_all = TRUE;
5261
5262       for (i = 0; i < NUM_DOORS; i++)
5263         door_panel_drawn[i] = FALSE;
5264
5265       for (i = 0; i < MAX_DOOR_PARTS; i++)
5266       {
5267         int nr = door_part_order[i].nr;
5268         struct DoorPartControlInfo *dpc = &door_part_controls[nr];
5269         struct DoorPartPosInfo *pos = dpc->pos;
5270         struct GraphicInfo *g = &graphic_info[dpc->graphic];
5271         int door_token = dpc->door_token;
5272         int door_index = DOOR_INDEX_FROM_TOKEN(door_token);
5273         boolean is_panel = DOOR_PART_IS_PANEL(nr);
5274         boolean is_panel_and_door_has_closed = FALSE;
5275         struct Rect *door_rect = &door_rect_list[door_index];
5276         Bitmap *bitmap_db_door = (door_token == DOOR_1 ? bitmap_db_door_1 :
5277                                   bitmap_db_door_2);
5278         Bitmap *bitmap = (is_panel ? bitmap_db_door : g->bitmap);
5279         int current_door_state = door_state & door_token;
5280         boolean door_opening = ((current_door_state & DOOR_OPEN)  != 0);
5281         boolean door_closing = !door_opening;
5282         boolean part_opening = (is_panel ? door_closing : door_opening);
5283         boolean part_closing = !part_opening;
5284         int start_step = (part_opening ? pos->start_step_opening :
5285                           pos->start_step_closing);
5286         int step_delay = pos->step_delay;
5287         int step_factor = step_delay / max_step_delay;
5288         int k1 = (step_factor ? k / step_factor + 1 : k);
5289         int k2 = (part_opening ? k1 + start_step : num_steps[nr] - k1);
5290         int kk = MAX(0, k2);
5291         int g_src_x = 0;
5292         int g_src_y = 0;
5293         int src_x, src_y, src_xx, src_yy;
5294         int dst_x, dst_y, dst_xx, dst_yy;
5295         int width, height;
5296
5297         if (door_part_skip[nr])
5298           continue;
5299
5300         if (!(door_state & door_token))
5301           continue;
5302
5303         if (!g->bitmap)
5304           continue;
5305
5306         if (!is_panel)
5307         {
5308           int k2_door = (door_opening ? k : num_move_steps_doors_only - k - 1);
5309           int kk_door = MAX(0, k2_door);
5310           int sync_frame = kk_door * door_delay_value;
5311           int frame = getGraphicAnimationFrame(dpc->graphic, sync_frame);
5312
5313           getFixedGraphicSource(dpc->graphic, frame, &bitmap,
5314                                 &g_src_x, &g_src_y);
5315         }
5316
5317         // draw door panel
5318
5319         if (!door_panel_drawn[door_index])
5320         {
5321           ClearRectangle(drawto, door_rect->x, door_rect->y,
5322                          door_rect->width, door_rect->height);
5323
5324           door_panel_drawn[door_index] = TRUE;
5325         }
5326
5327         // draw opening or closing door parts
5328
5329         if (pos->step_xoffset < 0)      // door part on right side
5330         {
5331           src_xx = 0;
5332           dst_xx = pos->x + ABS(kk * pos->step_xoffset);
5333           width = g->width;
5334
5335           if (dst_xx + width > door_rect->width)
5336             width = door_rect->width - dst_xx;
5337         }
5338         else                            // door part on left side
5339         {
5340           src_xx = 0;
5341           dst_xx = pos->x - kk * pos->step_xoffset;
5342
5343           if (dst_xx < 0)
5344           {
5345             src_xx = ABS(dst_xx);
5346             dst_xx = 0;
5347           }
5348
5349           width = g->width - src_xx;
5350
5351           if (width > door_rect->width)
5352             width = door_rect->width;
5353
5354           // Debug("tools:MoveDoor", "k == %d [%d]", k, start_step);
5355         }
5356
5357         if (pos->step_yoffset < 0)      // door part on bottom side
5358         {
5359           src_yy = 0;
5360           dst_yy = pos->y + ABS(kk * pos->step_yoffset);
5361           height = g->height;
5362
5363           if (dst_yy + height > door_rect->height)
5364             height = door_rect->height - dst_yy;
5365         }
5366         else                            // door part on top side
5367         {
5368           src_yy = 0;
5369           dst_yy = pos->y - kk * pos->step_yoffset;
5370
5371           if (dst_yy < 0)
5372           {
5373             src_yy = ABS(dst_yy);
5374             dst_yy = 0;
5375           }
5376
5377           height = g->height - src_yy;
5378         }
5379
5380         src_x = g_src_x + src_xx;
5381         src_y = g_src_y + src_yy;
5382
5383         dst_x = door_rect->x + dst_xx;
5384         dst_y = door_rect->y + dst_yy;
5385
5386         is_panel_and_door_has_closed =
5387           (is_panel &&
5388            door_closing &&
5389            panel_has_doors[door_index] &&
5390            k >= num_move_steps_doors_only - 1);
5391
5392         if (width  >= 0 && width  <= g->width &&
5393             height >= 0 && height <= g->height &&
5394             !is_panel_and_door_has_closed)
5395         {
5396           if (is_panel || !pos->draw_masked)
5397             BlitBitmap(bitmap, drawto, src_x, src_y, width, height,
5398                        dst_x, dst_y);
5399           else
5400             BlitBitmapMasked(bitmap, drawto, src_x, src_y, width, height,
5401                              dst_x, dst_y);
5402         }
5403
5404         redraw_mask |= REDRAW_DOOR_FROM_TOKEN(door_token);
5405
5406         if ((part_opening && (width < 0         || height < 0)) ||
5407             (part_closing && (width >= g->width && height >= g->height)))
5408           door_part_done[nr] = TRUE;
5409
5410         // continue door part animations, but not panel after door has closed
5411         if (!door_part_done[nr] && !is_panel_and_door_has_closed)
5412           door_part_done_all = FALSE;
5413       }
5414
5415       if (!(door_state & DOOR_NO_DELAY))
5416       {
5417         BackToFront();
5418
5419         SkipUntilDelayReached(&door_delay, door_delay_value, &k, last_frame);
5420
5421         current_move_delay += max_step_delay;
5422
5423         // prevent OS (Windows) from complaining about program not responding
5424         CheckQuitEvent();
5425       }
5426
5427       if (door_part_done_all)
5428         break;
5429     }
5430
5431     if (!(door_state & DOOR_NO_DELAY))
5432     {
5433       // wait for specified door action post delay
5434       if (door_state & DOOR_ACTION_1 && door_state & DOOR_ACTION_2)
5435         door_delay_value = MAX(door_1.post_delay, door_2.post_delay);
5436       else if (door_state & DOOR_ACTION_1)
5437         door_delay_value = door_1.post_delay;
5438       else if (door_state & DOOR_ACTION_2)
5439         door_delay_value = door_2.post_delay;
5440
5441       while (!DelayReached(&door_delay, door_delay_value))
5442         BackToFront();
5443     }
5444   }
5445
5446   if (door_state & DOOR_ACTION_1)
5447     door1 = door_state & DOOR_ACTION_1;
5448   if (door_state & DOOR_ACTION_2)
5449     door2 = door_state & DOOR_ACTION_2;
5450
5451   // draw masked border over door area
5452   DrawMaskedBorder(REDRAW_DOOR_1);
5453   DrawMaskedBorder(REDRAW_DOOR_2);
5454
5455   ClearAutoRepeatKeyEvents();
5456
5457   return (door1 | door2);
5458 }
5459
5460 static boolean useSpecialEditorDoor(void)
5461 {
5462   int graphic = IMG_GLOBAL_BORDER_EDITOR;
5463   boolean redefined = getImageListEntryFromImageID(graphic)->redefined;
5464
5465   // do not draw special editor door if editor border defined or redefined
5466   if (graphic_info[graphic].bitmap != NULL || redefined)
5467     return FALSE;
5468
5469   // do not draw special editor door if global border defined to be empty
5470   if (graphic_info[IMG_GLOBAL_BORDER].bitmap == NULL)
5471     return FALSE;
5472
5473   // do not draw special editor door if viewport definitions do not match
5474   if (EX != VX ||
5475       EY >= VY ||
5476       EXSIZE != VXSIZE ||
5477       EY + EYSIZE != VY + VYSIZE)
5478     return FALSE;
5479
5480   return TRUE;
5481 }
5482
5483 void DrawSpecialEditorDoor(void)
5484 {
5485   struct GraphicInfo *gfx1 = &graphic_info[IMG_DOOR_2_TOP_BORDER_CORRECTION];
5486   int top_border_width = gfx1->width;
5487   int top_border_height = gfx1->height;
5488   int outer_border = viewport.door_2[GAME_MODE_EDITOR].border_size;
5489   int ex = EX - outer_border;
5490   int ey = EY - outer_border;
5491   int vy = VY - outer_border;
5492   int exsize = EXSIZE + 2 * outer_border;
5493
5494   if (!useSpecialEditorDoor())
5495     return;
5496
5497   // draw bigger level editor toolbox window
5498   BlitBitmap(gfx1->bitmap, drawto, gfx1->src_x, gfx1->src_y,
5499              top_border_width, top_border_height, ex, ey - top_border_height);
5500   BlitBitmap(graphic_info[IMG_GLOBAL_BORDER].bitmap, drawto, ex, vy,
5501              exsize, EYSIZE - VYSIZE + outer_border, ex, ey);
5502
5503   redraw_mask |= REDRAW_ALL;
5504 }
5505
5506 void UndrawSpecialEditorDoor(void)
5507 {
5508   struct GraphicInfo *gfx1 = &graphic_info[IMG_DOOR_2_TOP_BORDER_CORRECTION];
5509   int top_border_width = gfx1->width;
5510   int top_border_height = gfx1->height;
5511   int outer_border = viewport.door_2[GAME_MODE_EDITOR].border_size;
5512   int ex = EX - outer_border;
5513   int ey = EY - outer_border;
5514   int ey_top = ey - top_border_height;
5515   int exsize = EXSIZE + 2 * outer_border;
5516   int eysize = EYSIZE + 2 * outer_border;
5517
5518   if (!useSpecialEditorDoor())
5519     return;
5520
5521   // draw normal tape recorder window
5522   if (graphic_info[IMG_GLOBAL_BORDER].bitmap)
5523   {
5524     BlitBitmap(graphic_info[IMG_GLOBAL_BORDER].bitmap, drawto,
5525                ex, ey_top, top_border_width, top_border_height,
5526                ex, ey_top);
5527     BlitBitmap(graphic_info[IMG_GLOBAL_BORDER].bitmap, drawto,
5528                ex, ey, exsize, eysize, ex, ey);
5529   }
5530   else
5531   {
5532     // if screen background is set to "[NONE]", clear editor toolbox window
5533     ClearRectangle(drawto, ex, ey_top, top_border_width, top_border_height);
5534     ClearRectangle(drawto, ex, ey, exsize, eysize);
5535   }
5536
5537   redraw_mask |= REDRAW_ALL;
5538 }
5539
5540
5541 // ---------- new tool button stuff -------------------------------------------
5542
5543 static struct
5544 {
5545   int graphic;
5546   struct TextPosInfo *pos;
5547   int gadget_id;
5548   boolean is_touch_button;
5549   char *infotext;
5550 } toolbutton_info[NUM_TOOL_BUTTONS] =
5551 {
5552   {
5553     IMG_GFX_REQUEST_BUTTON_YES,         &request.button.yes,
5554     TOOL_CTRL_ID_YES, FALSE,            "yes"
5555   },
5556   {
5557     IMG_GFX_REQUEST_BUTTON_NO,          &request.button.no,
5558     TOOL_CTRL_ID_NO, FALSE,             "no"
5559   },
5560   {
5561     IMG_GFX_REQUEST_BUTTON_CONFIRM,     &request.button.confirm,
5562     TOOL_CTRL_ID_CONFIRM, FALSE,        "confirm"
5563   },
5564   {
5565     IMG_GFX_REQUEST_BUTTON_PLAYER_1,    &request.button.player_1,
5566     TOOL_CTRL_ID_PLAYER_1, FALSE,       "player 1"
5567   },
5568   {
5569     IMG_GFX_REQUEST_BUTTON_PLAYER_2,    &request.button.player_2,
5570     TOOL_CTRL_ID_PLAYER_2, FALSE,       "player 2"
5571   },
5572   {
5573     IMG_GFX_REQUEST_BUTTON_PLAYER_3,    &request.button.player_3,
5574     TOOL_CTRL_ID_PLAYER_3, FALSE,       "player 3"
5575   },
5576   {
5577     IMG_GFX_REQUEST_BUTTON_PLAYER_4,    &request.button.player_4,
5578     TOOL_CTRL_ID_PLAYER_4, FALSE,       "player 4"
5579   },
5580   {
5581     IMG_GFX_REQUEST_BUTTON_TOUCH_YES,   &request.button.touch_yes,
5582     TOOL_CTRL_ID_TOUCH_YES, TRUE,       "yes"
5583   },
5584   {
5585     IMG_GFX_REQUEST_BUTTON_TOUCH_NO,    &request.button.touch_no,
5586     TOOL_CTRL_ID_TOUCH_NO, TRUE,        "no"
5587   },
5588   {
5589     IMG_GFX_REQUEST_BUTTON_TOUCH_CONFIRM, &request.button.touch_confirm,
5590     TOOL_CTRL_ID_TOUCH_CONFIRM, TRUE,   "confirm"
5591   }
5592 };
5593
5594 void CreateToolButtons(void)
5595 {
5596   int i;
5597
5598   for (i = 0; i < NUM_TOOL_BUTTONS; i++)
5599   {
5600     int graphic = toolbutton_info[i].graphic;
5601     struct GraphicInfo *gfx = &graphic_info[graphic];
5602     struct TextPosInfo *pos = toolbutton_info[i].pos;
5603     struct GadgetInfo *gi;
5604     Bitmap *deco_bitmap = None;
5605     int deco_x = 0, deco_y = 0, deco_xpos = 0, deco_ypos = 0;
5606     unsigned int event_mask = GD_EVENT_RELEASED;
5607     boolean is_touch_button = toolbutton_info[i].is_touch_button;
5608     int base_x = (is_touch_button ? 0 : DX);
5609     int base_y = (is_touch_button ? 0 : DY);
5610     int gd_x = gfx->src_x;
5611     int gd_y = gfx->src_y;
5612     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
5613     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
5614     int x = pos->x;
5615     int y = pos->y;
5616     int id = i;
5617
5618     if (global.use_envelope_request && !is_touch_button)
5619     {
5620       setRequestPosition(&base_x, &base_y, TRUE);
5621
5622       // check if request buttons are outside of envelope and fix, if needed
5623       if (x < 0 || x + gfx->width  > request.width ||
5624           y < 0 || y + gfx->height > request.height)
5625       {
5626         if (id == TOOL_CTRL_ID_YES)
5627         {
5628           x = 0;
5629           y = request.height - 2 * request.border_size - gfx->height;
5630         }
5631         else if (id == TOOL_CTRL_ID_NO)
5632         {
5633           x = request.width  - 2 * request.border_size - gfx->width;
5634           y = request.height - 2 * request.border_size - gfx->height;
5635         }
5636         else if (id == TOOL_CTRL_ID_CONFIRM)
5637         {
5638           x = (request.width - 2 * request.border_size - gfx->width) / 2;
5639           y = request.height - 2 * request.border_size - gfx->height;
5640         }
5641         else if (id >= TOOL_CTRL_ID_PLAYER_1 && id <= TOOL_CTRL_ID_PLAYER_4)
5642         {
5643           int player_nr = id - TOOL_CTRL_ID_PLAYER_1;
5644
5645           x = (request.width - 2 * request.border_size - gfx->width) / 2;
5646           y = request.height - 2 * request.border_size - gfx->height * 2;
5647
5648           x += (player_nr == 3 ? -1 : player_nr == 1 ? +1 : 0) * gfx->width;
5649           y += (player_nr == 0 ? -1 : player_nr == 2 ? +1 : 0) * gfx->height;
5650         }
5651       }
5652     }
5653
5654     if (id >= TOOL_CTRL_ID_PLAYER_1 && id <= TOOL_CTRL_ID_PLAYER_4)
5655     {
5656       int player_nr = id - TOOL_CTRL_ID_PLAYER_1;
5657
5658       getSizedGraphicSource(PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0,
5659                             pos->size, &deco_bitmap, &deco_x, &deco_y);
5660       deco_xpos = (gfx->width  - pos->size) / 2;
5661       deco_ypos = (gfx->height - pos->size) / 2;
5662     }
5663
5664     gi = CreateGadget(GDI_CUSTOM_ID, id,
5665                       GDI_IMAGE_ID, graphic,
5666                       GDI_INFO_TEXT, toolbutton_info[i].infotext,
5667                       GDI_X, base_x + x,
5668                       GDI_Y, base_y + y,
5669                       GDI_WIDTH, gfx->width,
5670                       GDI_HEIGHT, gfx->height,
5671                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
5672                       GDI_STATE, GD_BUTTON_UNPRESSED,
5673                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
5674                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
5675                       GDI_DECORATION_DESIGN, deco_bitmap, deco_x, deco_y,
5676                       GDI_DECORATION_POSITION, deco_xpos, deco_ypos,
5677                       GDI_DECORATION_SIZE, pos->size, pos->size,
5678                       GDI_DECORATION_SHIFTING, 1, 1,
5679                       GDI_DIRECT_DRAW, FALSE,
5680                       GDI_OVERLAY_TOUCH_BUTTON, is_touch_button,
5681                       GDI_EVENT_MASK, event_mask,
5682                       GDI_CALLBACK_ACTION, HandleToolButtons,
5683                       GDI_END);
5684
5685     if (gi == NULL)
5686       Fail("cannot create gadget");
5687
5688     tool_gadget[id] = gi;
5689   }
5690 }
5691
5692 void FreeToolButtons(void)
5693 {
5694   int i;
5695
5696   for (i = 0; i < NUM_TOOL_BUTTONS; i++)
5697     FreeGadget(tool_gadget[i]);
5698 }
5699
5700 static void UnmapToolButtons(void)
5701 {
5702   int i;
5703
5704   for (i = 0; i < NUM_TOOL_BUTTONS; i++)
5705     UnmapGadget(tool_gadget[i]);
5706 }
5707
5708 static void HandleToolButtons(struct GadgetInfo *gi)
5709 {
5710   request_gadget_id = gi->custom_id;
5711 }
5712
5713 static struct Mapping_EM_to_RND_object
5714 {
5715   int element_em;
5716   boolean is_rnd_to_em_mapping;         // unique mapping EM <-> RND
5717   boolean is_backside;                  // backside of moving element
5718
5719   int element_rnd;
5720   int action;
5721   int direction;
5722 }
5723 em_object_mapping_list[GAME_TILE_MAX + 1] =
5724 {
5725   {
5726     Zborder,                            FALSE,  FALSE,
5727     EL_EMPTY,                           -1, -1
5728   },
5729   {
5730     Zplayer,                            FALSE,  FALSE,
5731     EL_EMPTY,                           -1, -1
5732   },
5733
5734   {
5735     Zbug,                               FALSE,  FALSE,
5736     EL_EMPTY,                           -1, -1
5737   },
5738   {
5739     Ztank,                              FALSE,  FALSE,
5740     EL_EMPTY,                           -1, -1
5741   },
5742   {
5743     Zeater,                             FALSE,  FALSE,
5744     EL_EMPTY,                           -1, -1
5745   },
5746   {
5747     Zdynamite,                          FALSE,  FALSE,
5748     EL_EMPTY,                           -1, -1
5749   },
5750   {
5751     Zboom,                              FALSE,  FALSE,
5752     EL_EMPTY,                           -1, -1
5753   },
5754
5755   {
5756     Xchain,                             FALSE,  FALSE,
5757     EL_DEFAULT,                         ACTION_EXPLODING, -1
5758   },
5759   {
5760     Xboom_bug,                          FALSE,  FALSE,
5761     EL_BUG,                             ACTION_EXPLODING, -1
5762   },
5763   {
5764     Xboom_tank,                         FALSE,  FALSE,
5765     EL_SPACESHIP,                       ACTION_EXPLODING, -1
5766   },
5767   {
5768     Xboom_android,                      FALSE,  FALSE,
5769     EL_EMC_ANDROID,                     ACTION_OTHER, -1
5770   },
5771   {
5772     Xboom_1,                            FALSE,  FALSE,
5773     EL_DEFAULT,                         ACTION_EXPLODING, -1
5774   },
5775   {
5776     Xboom_2,                            FALSE,  FALSE,
5777     EL_DEFAULT,                         ACTION_EXPLODING, -1
5778   },
5779
5780   {
5781     Xblank,                             TRUE,   FALSE,
5782     EL_EMPTY,                           -1, -1
5783   },
5784
5785   {
5786     Xsplash_e,                          FALSE,  FALSE,
5787     EL_ACID_SPLASH_RIGHT,               -1, -1
5788   },
5789   {
5790     Xsplash_w,                          FALSE,  FALSE,
5791     EL_ACID_SPLASH_LEFT,                -1, -1
5792   },
5793
5794   {
5795     Xplant,                             TRUE,   FALSE,
5796     EL_EMC_PLANT,                       -1, -1
5797   },
5798   {
5799     Yplant,                             FALSE,  FALSE,
5800     EL_EMC_PLANT,                       -1, -1
5801   },
5802
5803   {
5804     Xacid_1,                            TRUE,   FALSE,
5805     EL_ACID,                            -1, -1
5806   },
5807   {
5808     Xacid_2,                            FALSE,  FALSE,
5809     EL_ACID,                            -1, -1
5810   },
5811   {
5812     Xacid_3,                            FALSE,  FALSE,
5813     EL_ACID,                            -1, -1
5814   },
5815   {
5816     Xacid_4,                            FALSE,  FALSE,
5817     EL_ACID,                            -1, -1
5818   },
5819   {
5820     Xacid_5,                            FALSE,  FALSE,
5821     EL_ACID,                            -1, -1
5822   },
5823   {
5824     Xacid_6,                            FALSE,  FALSE,
5825     EL_ACID,                            -1, -1
5826   },
5827   {
5828     Xacid_7,                            FALSE,  FALSE,
5829     EL_ACID,                            -1, -1
5830   },
5831   {
5832     Xacid_8,                            FALSE,  FALSE,
5833     EL_ACID,                            -1, -1
5834   },
5835
5836   {
5837     Xfake_acid_1,                       TRUE,   FALSE,
5838     EL_EMC_FAKE_ACID,                   -1, -1
5839   },
5840   {
5841     Xfake_acid_2,                       FALSE,  FALSE,
5842     EL_EMC_FAKE_ACID,                   -1, -1
5843   },
5844   {
5845     Xfake_acid_3,                       FALSE,  FALSE,
5846     EL_EMC_FAKE_ACID,                   -1, -1
5847   },
5848   {
5849     Xfake_acid_4,                       FALSE,  FALSE,
5850     EL_EMC_FAKE_ACID,                   -1, -1
5851   },
5852   {
5853     Xfake_acid_5,                       FALSE,  FALSE,
5854     EL_EMC_FAKE_ACID,                   -1, -1
5855   },
5856   {
5857     Xfake_acid_6,                       FALSE,  FALSE,
5858     EL_EMC_FAKE_ACID,                   -1, -1
5859   },
5860   {
5861     Xfake_acid_7,                       FALSE,  FALSE,
5862     EL_EMC_FAKE_ACID,                   -1, -1
5863   },
5864   {
5865     Xfake_acid_8,                       FALSE,  FALSE,
5866     EL_EMC_FAKE_ACID,                   -1, -1
5867   },
5868
5869   {
5870     Xgrass,                             TRUE,   FALSE,
5871     EL_EMC_GRASS,                       -1, -1
5872   },
5873   {
5874     Ygrass_nB,                          FALSE,  FALSE,
5875     EL_EMC_GRASS,                       ACTION_DIGGING, MV_BIT_UP
5876   },
5877   {
5878     Ygrass_eB,                          FALSE,  FALSE,
5879     EL_EMC_GRASS,                       ACTION_DIGGING, MV_BIT_RIGHT
5880   },
5881   {
5882     Ygrass_sB,                          FALSE,  FALSE,
5883     EL_EMC_GRASS,                       ACTION_DIGGING, MV_BIT_DOWN
5884   },
5885   {
5886     Ygrass_wB,                          FALSE,  FALSE,
5887     EL_EMC_GRASS,                       ACTION_DIGGING, MV_BIT_LEFT
5888   },
5889
5890   {
5891     Xdirt,                              TRUE,   FALSE,
5892     EL_SAND,                            -1, -1
5893   },
5894   {
5895     Ydirt_nB,                           FALSE,  FALSE,
5896     EL_SAND,                            ACTION_DIGGING, MV_BIT_UP
5897   },
5898   {
5899     Ydirt_eB,                           FALSE,  FALSE,
5900     EL_SAND,                            ACTION_DIGGING, MV_BIT_RIGHT
5901   },
5902   {
5903     Ydirt_sB,                           FALSE,  FALSE,
5904     EL_SAND,                            ACTION_DIGGING, MV_BIT_DOWN
5905   },
5906   {
5907     Ydirt_wB,                           FALSE,  FALSE,
5908     EL_SAND,                            ACTION_DIGGING, MV_BIT_LEFT
5909   },
5910
5911   {
5912     Xandroid,                           TRUE,   FALSE,
5913     EL_EMC_ANDROID,                     ACTION_ACTIVE, -1
5914   },
5915   {
5916     Xandroid_1_n,                       FALSE,  FALSE,
5917     EL_EMC_ANDROID,                     ACTION_ACTIVE, MV_BIT_UP
5918   },
5919   {
5920     Xandroid_2_n,                       FALSE,  FALSE,
5921     EL_EMC_ANDROID,                     ACTION_ACTIVE, MV_BIT_UP
5922   },
5923   {
5924     Xandroid_1_e,                       FALSE,  FALSE,
5925     EL_EMC_ANDROID,                     ACTION_ACTIVE, MV_BIT_RIGHT
5926   },
5927   {
5928     Xandroid_2_e,                       FALSE,  FALSE,
5929     EL_EMC_ANDROID,                     ACTION_ACTIVE, MV_BIT_RIGHT
5930   },
5931   {
5932     Xandroid_1_w,                       FALSE,  FALSE,
5933     EL_EMC_ANDROID,                     ACTION_ACTIVE, MV_BIT_LEFT
5934   },
5935   {
5936     Xandroid_2_w,                       FALSE,  FALSE,
5937     EL_EMC_ANDROID,                     ACTION_ACTIVE, MV_BIT_LEFT
5938   },
5939   {
5940     Xandroid_1_s,                       FALSE,  FALSE,
5941     EL_EMC_ANDROID,                     ACTION_ACTIVE, MV_BIT_DOWN
5942   },
5943   {
5944     Xandroid_2_s,                       FALSE,  FALSE,
5945     EL_EMC_ANDROID,                     ACTION_ACTIVE, MV_BIT_DOWN
5946   },
5947   {
5948     Yandroid_n,                         FALSE,  FALSE,
5949     EL_EMC_ANDROID,                     ACTION_MOVING, MV_BIT_UP
5950   },
5951   {
5952     Yandroid_nB,                        FALSE,  TRUE,
5953     EL_EMC_ANDROID,                     ACTION_MOVING, MV_BIT_UP
5954   },
5955   {
5956     Yandroid_ne,                        FALSE,  FALSE,
5957     EL_EMC_ANDROID,                     ACTION_GROWING, MV_BIT_UPRIGHT
5958   },
5959   {
5960     Yandroid_neB,                       FALSE,  TRUE,
5961     EL_EMC_ANDROID,                     ACTION_SHRINKING, MV_BIT_UPRIGHT
5962   },
5963   {
5964     Yandroid_e,                         FALSE,  FALSE,
5965     EL_EMC_ANDROID,                     ACTION_MOVING, MV_BIT_RIGHT
5966   },
5967   {
5968     Yandroid_eB,                        FALSE,  TRUE,
5969     EL_EMC_ANDROID,                     ACTION_MOVING, MV_BIT_RIGHT
5970   },
5971   {
5972     Yandroid_se,                        FALSE,  FALSE,
5973     EL_EMC_ANDROID,                     ACTION_GROWING, MV_BIT_DOWNRIGHT
5974   },
5975   {
5976     Yandroid_seB,                       FALSE,  TRUE,
5977     EL_EMC_ANDROID,                     ACTION_SHRINKING, MV_BIT_DOWNRIGHT
5978   },
5979   {
5980     Yandroid_s,                         FALSE,  FALSE,
5981     EL_EMC_ANDROID,                     ACTION_MOVING, MV_BIT_DOWN
5982   },
5983   {
5984     Yandroid_sB,                        FALSE,  TRUE,
5985     EL_EMC_ANDROID,                     ACTION_MOVING, MV_BIT_DOWN
5986   },
5987   {
5988     Yandroid_sw,                        FALSE,  FALSE,
5989     EL_EMC_ANDROID,                     ACTION_GROWING, MV_BIT_DOWNLEFT
5990   },
5991   {
5992     Yandroid_swB,                       FALSE,  TRUE,
5993     EL_EMC_ANDROID,                     ACTION_SHRINKING, MV_BIT_DOWNLEFT
5994   },
5995   {
5996     Yandroid_w,                         FALSE,  FALSE,
5997     EL_EMC_ANDROID,                     ACTION_MOVING, MV_BIT_LEFT
5998   },
5999   {
6000     Yandroid_wB,                        FALSE,  TRUE,
6001     EL_EMC_ANDROID,                     ACTION_MOVING, MV_BIT_LEFT
6002   },
6003   {
6004     Yandroid_nw,                        FALSE,  FALSE,
6005     EL_EMC_ANDROID,                     ACTION_GROWING, MV_BIT_UPLEFT
6006   },
6007   {
6008     Yandroid_nwB,                       FALSE,  TRUE,
6009     EL_EMC_ANDROID,                     ACTION_SHRINKING, MV_BIT_UPLEFT
6010   },
6011
6012   {
6013     Xeater_n,                           TRUE,   FALSE,
6014     EL_YAMYAM_UP,                       -1, -1
6015   },
6016   {
6017     Xeater_e,                           TRUE,   FALSE,
6018     EL_YAMYAM_RIGHT,                    -1, -1
6019   },
6020   {
6021     Xeater_w,                           TRUE,   FALSE,
6022     EL_YAMYAM_LEFT,                     -1, -1
6023   },
6024   {
6025     Xeater_s,                           TRUE,   FALSE,
6026     EL_YAMYAM_DOWN,                     -1, -1
6027   },
6028   {
6029     Yeater_n,                           FALSE,  FALSE,
6030     EL_YAMYAM,                          ACTION_MOVING, MV_BIT_UP
6031   },
6032   {
6033     Yeater_nB,                          FALSE,  TRUE,
6034     EL_YAMYAM,                          ACTION_MOVING, MV_BIT_UP
6035   },
6036   {
6037     Yeater_e,                           FALSE,  FALSE,
6038     EL_YAMYAM,                          ACTION_MOVING, MV_BIT_RIGHT
6039   },
6040   {
6041     Yeater_eB,                          FALSE,  TRUE,
6042     EL_YAMYAM,                          ACTION_MOVING, MV_BIT_RIGHT
6043   },
6044   {
6045     Yeater_s,                           FALSE,  FALSE,
6046     EL_YAMYAM,                          ACTION_MOVING, MV_BIT_DOWN
6047   },
6048   {
6049     Yeater_sB,                          FALSE,  TRUE,
6050     EL_YAMYAM,                          ACTION_MOVING, MV_BIT_DOWN
6051   },
6052   {
6053     Yeater_w,                           FALSE,  FALSE,
6054     EL_YAMYAM,                          ACTION_MOVING, MV_BIT_LEFT
6055   },
6056   {
6057     Yeater_wB,                          FALSE,  TRUE,
6058     EL_YAMYAM,                          ACTION_MOVING, MV_BIT_LEFT
6059   },
6060   {
6061     Yeater_stone,                       FALSE,  FALSE,
6062     EL_YAMYAM,                          ACTION_SMASHED_BY_ROCK, -1
6063   },
6064   {
6065     Yeater_spring,                      FALSE,  FALSE,
6066     EL_YAMYAM,                          ACTION_SMASHED_BY_SPRING, -1
6067   },
6068
6069   {
6070     Xalien,                             TRUE,   FALSE,
6071     EL_ROBOT,                           -1, -1
6072   },
6073   {
6074     Xalien_pause,                       FALSE,  FALSE,
6075     EL_ROBOT,                           -1, -1
6076   },
6077   {
6078     Yalien_n,                           FALSE,  FALSE,
6079     EL_ROBOT,                           ACTION_MOVING, MV_BIT_UP
6080   },
6081   {
6082     Yalien_nB,                          FALSE,  TRUE,
6083     EL_ROBOT,                           ACTION_MOVING, MV_BIT_UP
6084   },
6085   {
6086     Yalien_e,                           FALSE,  FALSE,
6087     EL_ROBOT,                           ACTION_MOVING, MV_BIT_RIGHT
6088   },
6089   {
6090     Yalien_eB,                          FALSE,  TRUE,
6091     EL_ROBOT,                           ACTION_MOVING, MV_BIT_RIGHT
6092   },
6093   {
6094     Yalien_s,                           FALSE,  FALSE,
6095     EL_ROBOT,                           ACTION_MOVING, MV_BIT_DOWN
6096   },
6097   {
6098     Yalien_sB,                          FALSE,  TRUE,
6099     EL_ROBOT,                           ACTION_MOVING, MV_BIT_DOWN
6100   },
6101   {
6102     Yalien_w,                           FALSE,  FALSE,
6103     EL_ROBOT,                           ACTION_MOVING, MV_BIT_LEFT
6104   },
6105   {
6106     Yalien_wB,                          FALSE,  TRUE,
6107     EL_ROBOT,                           ACTION_MOVING, MV_BIT_LEFT
6108   },
6109   {
6110     Yalien_stone,                       FALSE,  FALSE,
6111     EL_ROBOT,                           ACTION_SMASHED_BY_ROCK, -1
6112   },
6113   {
6114     Yalien_spring,                      FALSE,  FALSE,
6115     EL_ROBOT,                           ACTION_SMASHED_BY_SPRING, -1
6116   },
6117
6118   {
6119     Xbug_1_n,                           TRUE,   FALSE,
6120     EL_BUG_UP,                          -1, -1
6121   },
6122   {
6123     Xbug_1_e,                           TRUE,   FALSE,
6124     EL_BUG_RIGHT,                       -1, -1
6125   },
6126   {
6127     Xbug_1_s,                           TRUE,   FALSE,
6128     EL_BUG_DOWN,                        -1, -1
6129   },
6130   {
6131     Xbug_1_w,                           TRUE,   FALSE,
6132     EL_BUG_LEFT,                        -1, -1
6133   },
6134   {
6135     Xbug_2_n,                           FALSE,  FALSE,
6136     EL_BUG_UP,                          -1, -1
6137   },
6138   {
6139     Xbug_2_e,                           FALSE,  FALSE,
6140     EL_BUG_RIGHT,                       -1, -1
6141   },
6142   {
6143     Xbug_2_s,                           FALSE,  FALSE,
6144     EL_BUG_DOWN,                        -1, -1
6145   },
6146   {
6147     Xbug_2_w,                           FALSE,  FALSE,
6148     EL_BUG_LEFT,                        -1, -1
6149   },
6150   {
6151     Ybug_n,                             FALSE,  FALSE,
6152     EL_BUG,                             ACTION_MOVING, MV_BIT_UP
6153   },
6154   {
6155     Ybug_nB,                            FALSE,  TRUE,
6156     EL_BUG,                             ACTION_MOVING, MV_BIT_UP
6157   },
6158   {
6159     Ybug_e,                             FALSE,  FALSE,
6160     EL_BUG,                             ACTION_MOVING, MV_BIT_RIGHT
6161   },
6162   {
6163     Ybug_eB,                            FALSE,  TRUE,
6164     EL_BUG,                             ACTION_MOVING, MV_BIT_RIGHT
6165   },
6166   {
6167     Ybug_s,                             FALSE,  FALSE,
6168     EL_BUG,                             ACTION_MOVING, MV_BIT_DOWN
6169   },
6170   {
6171     Ybug_sB,                            FALSE,  TRUE,
6172     EL_BUG,                             ACTION_MOVING, MV_BIT_DOWN
6173   },
6174   {
6175     Ybug_w,                             FALSE,  FALSE,
6176     EL_BUG,                             ACTION_MOVING, MV_BIT_LEFT
6177   },
6178   {
6179     Ybug_wB,                            FALSE,  TRUE,
6180     EL_BUG,                             ACTION_MOVING, MV_BIT_LEFT
6181   },
6182   {
6183     Ybug_w_n,                           FALSE,  FALSE,
6184     EL_BUG,                             ACTION_TURNING_FROM_LEFT, MV_BIT_UP
6185   },
6186   {
6187     Ybug_n_e,                           FALSE,  FALSE,
6188     EL_BUG,                             ACTION_TURNING_FROM_UP, MV_BIT_RIGHT
6189   },
6190   {
6191     Ybug_e_s,                           FALSE,  FALSE,
6192     EL_BUG,                             ACTION_TURNING_FROM_RIGHT, MV_BIT_DOWN
6193   },
6194   {
6195     Ybug_s_w,                           FALSE,  FALSE,
6196     EL_BUG,                             ACTION_TURNING_FROM_DOWN, MV_BIT_LEFT
6197   },
6198   {
6199     Ybug_e_n,                           FALSE,  FALSE,
6200     EL_BUG,                             ACTION_TURNING_FROM_RIGHT, MV_BIT_UP
6201   },
6202   {
6203     Ybug_s_e,                           FALSE,  FALSE,
6204     EL_BUG,                             ACTION_TURNING_FROM_DOWN, MV_BIT_RIGHT
6205   },
6206   {
6207     Ybug_w_s,                           FALSE,  FALSE,
6208     EL_BUG,                             ACTION_TURNING_FROM_LEFT, MV_BIT_DOWN
6209   },
6210   {
6211     Ybug_n_w,                           FALSE,  FALSE,
6212     EL_BUG,                             ACTION_TURNING_FROM_UP, MV_BIT_LEFT
6213   },
6214   {
6215     Ybug_stone,                         FALSE,  FALSE,
6216     EL_BUG,                             ACTION_SMASHED_BY_ROCK, -1
6217   },
6218   {
6219     Ybug_spring,                        FALSE,  FALSE,
6220     EL_BUG,                             ACTION_SMASHED_BY_SPRING, -1
6221   },
6222
6223   {
6224     Xtank_1_n,                          TRUE,   FALSE,
6225     EL_SPACESHIP_UP,                    -1, -1
6226   },
6227   {
6228     Xtank_1_e,                          TRUE,   FALSE,
6229     EL_SPACESHIP_RIGHT,                 -1, -1
6230   },
6231   {
6232     Xtank_1_s,                          TRUE,   FALSE,
6233     EL_SPACESHIP_DOWN,                  -1, -1
6234   },
6235   {
6236     Xtank_1_w,                          TRUE,   FALSE,
6237     EL_SPACESHIP_LEFT,                  -1, -1
6238   },
6239   {
6240     Xtank_2_n,                          FALSE,  FALSE,
6241     EL_SPACESHIP_UP,                    -1, -1
6242   },
6243   {
6244     Xtank_2_e,                          FALSE,  FALSE,
6245     EL_SPACESHIP_RIGHT,                 -1, -1
6246   },
6247   {
6248     Xtank_2_s,                          FALSE,  FALSE,
6249     EL_SPACESHIP_DOWN,                  -1, -1
6250   },
6251   {
6252     Xtank_2_w,                          FALSE,  FALSE,
6253     EL_SPACESHIP_LEFT,                  -1, -1
6254   },
6255   {
6256     Ytank_n,                            FALSE,  FALSE,
6257     EL_SPACESHIP,                       ACTION_MOVING, MV_BIT_UP
6258   },
6259   {
6260     Ytank_nB,                           FALSE,  TRUE,
6261     EL_SPACESHIP,                       ACTION_MOVING, MV_BIT_UP
6262   },
6263   {
6264     Ytank_e,                            FALSE,  FALSE,
6265     EL_SPACESHIP,                       ACTION_MOVING, MV_BIT_RIGHT
6266   },
6267   {
6268     Ytank_eB,                           FALSE,  TRUE,
6269     EL_SPACESHIP,                       ACTION_MOVING, MV_BIT_RIGHT
6270   },
6271   {
6272     Ytank_s,                            FALSE,  FALSE,
6273     EL_SPACESHIP,                       ACTION_MOVING, MV_BIT_DOWN
6274   },
6275   {
6276     Ytank_sB,                           FALSE,  TRUE,
6277     EL_SPACESHIP,                       ACTION_MOVING, MV_BIT_DOWN
6278   },
6279   {
6280     Ytank_w,                            FALSE,  FALSE,
6281     EL_SPACESHIP,                       ACTION_MOVING, MV_BIT_LEFT
6282   },
6283   {
6284     Ytank_wB,                           FALSE,  TRUE,
6285     EL_SPACESHIP,                       ACTION_MOVING, MV_BIT_LEFT
6286   },
6287   {
6288     Ytank_w_n,                          FALSE,  FALSE,
6289     EL_SPACESHIP,                       ACTION_TURNING_FROM_LEFT, MV_BIT_UP
6290   },
6291   {
6292     Ytank_n_e,                          FALSE,  FALSE,
6293     EL_SPACESHIP,                       ACTION_TURNING_FROM_UP, MV_BIT_RIGHT
6294   },
6295   {
6296     Ytank_e_s,                          FALSE,  FALSE,
6297     EL_SPACESHIP,                       ACTION_TURNING_FROM_RIGHT, MV_BIT_DOWN
6298   },
6299   {
6300     Ytank_s_w,                          FALSE,  FALSE,
6301     EL_SPACESHIP,                       ACTION_TURNING_FROM_DOWN, MV_BIT_LEFT
6302   },
6303   {
6304     Ytank_e_n,                          FALSE,  FALSE,
6305     EL_SPACESHIP,                       ACTION_TURNING_FROM_RIGHT, MV_BIT_UP
6306   },
6307   {
6308     Ytank_s_e,                          FALSE,  FALSE,
6309     EL_SPACESHIP,                       ACTION_TURNING_FROM_DOWN, MV_BIT_RIGHT
6310   },
6311   {
6312     Ytank_w_s,                          FALSE,  FALSE,
6313     EL_SPACESHIP,                       ACTION_TURNING_FROM_LEFT, MV_BIT_DOWN
6314   },
6315   {
6316     Ytank_n_w,                          FALSE,  FALSE,
6317     EL_SPACESHIP,                       ACTION_TURNING_FROM_UP, MV_BIT_LEFT
6318   },
6319   {
6320     Ytank_stone,                        FALSE,  FALSE,
6321     EL_SPACESHIP,                       ACTION_SMASHED_BY_ROCK, -1
6322   },
6323   {
6324     Ytank_spring,                       FALSE,  FALSE,
6325     EL_SPACESHIP,                       ACTION_SMASHED_BY_SPRING, -1
6326   },
6327
6328   {
6329     Xemerald,                           TRUE,   FALSE,
6330     EL_EMERALD,                         -1, -1
6331   },
6332   {
6333     Xemerald_pause,                     FALSE,  FALSE,
6334     EL_EMERALD,                         -1, -1
6335   },
6336   {
6337     Xemerald_fall,                      FALSE,  FALSE,
6338     EL_EMERALD,                         -1, -1
6339   },
6340   {
6341     Xemerald_shine,                     FALSE,  FALSE,
6342     EL_EMERALD,                         ACTION_TWINKLING, -1
6343   },
6344   {
6345     Yemerald_s,                         FALSE,  FALSE,
6346     EL_EMERALD,                         ACTION_FALLING, -1
6347   },
6348   {
6349     Yemerald_sB,                        FALSE,  TRUE,
6350     EL_EMERALD,                         ACTION_FALLING, -1
6351   },
6352   {
6353     Yemerald_e,                         FALSE,  FALSE,
6354     EL_EMERALD,                         ACTION_MOVING, MV_BIT_RIGHT
6355   },
6356   {
6357     Yemerald_eB,                        FALSE,  TRUE,
6358     EL_EMERALD,                         ACTION_MOVING, MV_BIT_RIGHT
6359   },
6360   {
6361     Yemerald_w,                         FALSE,  FALSE,
6362     EL_EMERALD,                         ACTION_MOVING, MV_BIT_LEFT
6363   },
6364   {
6365     Yemerald_wB,                        FALSE,  TRUE,
6366     EL_EMERALD,                         ACTION_MOVING, MV_BIT_LEFT
6367   },
6368   {
6369     Yemerald_blank,                     FALSE,  FALSE,
6370     EL_EMERALD,                         ACTION_COLLECTING, -1
6371   },
6372
6373   {
6374     Xdiamond,                           TRUE,   FALSE,
6375     EL_DIAMOND,                         -1, -1
6376   },
6377   {
6378     Xdiamond_pause,                     FALSE,  FALSE,
6379     EL_DIAMOND,                         -1, -1
6380   },
6381   {
6382     Xdiamond_fall,                      FALSE,  FALSE,
6383     EL_DIAMOND,                         -1, -1
6384   },
6385   {
6386     Xdiamond_shine,                     FALSE,  FALSE,
6387     EL_DIAMOND,                         ACTION_TWINKLING, -1
6388   },
6389   {
6390     Ydiamond_s,                         FALSE,  FALSE,
6391     EL_DIAMOND,                         ACTION_FALLING, -1
6392   },
6393   {
6394     Ydiamond_sB,                        FALSE,  TRUE,
6395     EL_DIAMOND,                         ACTION_FALLING, -1
6396   },
6397   {
6398     Ydiamond_e,                         FALSE,  FALSE,
6399     EL_DIAMOND,                         ACTION_MOVING, MV_BIT_RIGHT
6400   },
6401   {
6402     Ydiamond_eB,                        FALSE,  TRUE,
6403     EL_DIAMOND,                         ACTION_MOVING, MV_BIT_RIGHT
6404   },
6405   {
6406     Ydiamond_w,                         FALSE,  FALSE,
6407     EL_DIAMOND,                         ACTION_MOVING, MV_BIT_LEFT
6408   },
6409   {
6410     Ydiamond_wB,                        FALSE,  TRUE,
6411     EL_DIAMOND,                         ACTION_MOVING, MV_BIT_LEFT
6412   },
6413   {
6414     Ydiamond_blank,                     FALSE,  FALSE,
6415     EL_DIAMOND,                         ACTION_COLLECTING, -1
6416   },
6417   {
6418     Ydiamond_stone,                     FALSE,  FALSE,
6419     EL_DIAMOND,                         ACTION_SMASHED_BY_ROCK, -1
6420   },
6421
6422   {
6423     Xstone,                             TRUE,   FALSE,
6424     EL_ROCK,                            -1, -1
6425   },
6426   {
6427     Xstone_pause,                       FALSE,  FALSE,
6428     EL_ROCK,                            -1, -1
6429   },
6430   {
6431     Xstone_fall,                        FALSE,  FALSE,
6432     EL_ROCK,                            -1, -1
6433   },
6434   {
6435     Ystone_s,                           FALSE,  FALSE,
6436     EL_ROCK,                            ACTION_FALLING, -1
6437   },
6438   {
6439     Ystone_sB,                          FALSE,  TRUE,
6440     EL_ROCK,                            ACTION_FALLING, -1
6441   },
6442   {
6443     Ystone_e,                           FALSE,  FALSE,
6444     EL_ROCK,                            ACTION_MOVING, MV_BIT_RIGHT
6445   },
6446   {
6447     Ystone_eB,                          FALSE,  TRUE,
6448     EL_ROCK,                            ACTION_MOVING, MV_BIT_RIGHT
6449   },
6450   {
6451     Ystone_w,                           FALSE,  FALSE,
6452     EL_ROCK,                            ACTION_MOVING, MV_BIT_LEFT
6453   },
6454   {
6455     Ystone_wB,                          FALSE,  TRUE,
6456     EL_ROCK,                            ACTION_MOVING, MV_BIT_LEFT
6457   },
6458
6459   {
6460     Xbomb,                              TRUE,   FALSE,
6461     EL_BOMB,                            -1, -1
6462   },
6463   {
6464     Xbomb_pause,                        FALSE,  FALSE,
6465     EL_BOMB,                            -1, -1
6466   },
6467   {
6468     Xbomb_fall,                         FALSE,  FALSE,
6469     EL_BOMB,                            -1, -1
6470   },
6471   {
6472     Ybomb_s,                            FALSE,  FALSE,
6473     EL_BOMB,                            ACTION_FALLING, -1
6474   },
6475   {
6476     Ybomb_sB,                           FALSE,  TRUE,
6477     EL_BOMB,                            ACTION_FALLING, -1
6478   },
6479   {
6480     Ybomb_e,                            FALSE,  FALSE,
6481     EL_BOMB,                            ACTION_MOVING, MV_BIT_RIGHT
6482   },
6483   {
6484     Ybomb_eB,                           FALSE,  TRUE,
6485     EL_BOMB,                            ACTION_MOVING, MV_BIT_RIGHT
6486   },
6487   {
6488     Ybomb_w,                            FALSE,  FALSE,
6489     EL_BOMB,                            ACTION_MOVING, MV_BIT_LEFT
6490   },
6491   {
6492     Ybomb_wB,                           FALSE,  TRUE,
6493     EL_BOMB,                            ACTION_MOVING, MV_BIT_LEFT
6494   },
6495   {
6496     Ybomb_blank,                        FALSE,  FALSE,
6497     EL_BOMB,                            ACTION_ACTIVATING, -1
6498   },
6499
6500   {
6501     Xnut,                               TRUE,   FALSE,
6502     EL_NUT,                             -1, -1
6503   },
6504   {
6505     Xnut_pause,                         FALSE,  FALSE,
6506     EL_NUT,                             -1, -1
6507   },
6508   {
6509     Xnut_fall,                          FALSE,  FALSE,
6510     EL_NUT,                             -1, -1
6511   },
6512   {
6513     Ynut_s,                             FALSE,  FALSE,
6514     EL_NUT,                             ACTION_FALLING, -1
6515   },
6516   {
6517     Ynut_sB,                            FALSE,  TRUE,
6518     EL_NUT,                             ACTION_FALLING, -1
6519   },
6520   {
6521     Ynut_e,                             FALSE,  FALSE,
6522     EL_NUT,                             ACTION_MOVING, MV_BIT_RIGHT
6523   },
6524   {
6525     Ynut_eB,                            FALSE,  TRUE,
6526     EL_NUT,                             ACTION_MOVING, MV_BIT_RIGHT
6527   },
6528   {
6529     Ynut_w,                             FALSE,  FALSE,
6530     EL_NUT,                             ACTION_MOVING, MV_BIT_LEFT
6531   },
6532   {
6533     Ynut_wB,                            FALSE,  TRUE,
6534     EL_NUT,                             ACTION_MOVING, MV_BIT_LEFT
6535   },
6536   {
6537     Ynut_stone,                         FALSE,  FALSE,
6538     EL_NUT,                             ACTION_BREAKING, -1
6539   },
6540
6541   {
6542     Xspring,                            TRUE,   FALSE,
6543     EL_SPRING,                          -1, -1
6544   },
6545   {
6546     Xspring_pause,                      FALSE,  FALSE,
6547     EL_SPRING,                          -1, -1
6548   },
6549   {
6550     Xspring_e,                          TRUE,   FALSE,
6551     EL_SPRING_RIGHT,                    -1, -1
6552   },
6553   {
6554     Xspring_w,                          TRUE,   FALSE,
6555     EL_SPRING_LEFT,                     -1, -1
6556   },
6557   {
6558     Xspring_fall,                       FALSE,  FALSE,
6559     EL_SPRING,                          -1, -1
6560   },
6561   {
6562     Yspring_s,                          FALSE,  FALSE,
6563     EL_SPRING,                          ACTION_FALLING, -1
6564   },
6565   {
6566     Yspring_sB,                         FALSE,  TRUE,
6567     EL_SPRING,                          ACTION_FALLING, -1
6568   },
6569   {
6570     Yspring_e,                          FALSE,  FALSE,
6571     EL_SPRING,                          ACTION_MOVING, MV_BIT_RIGHT
6572   },
6573   {
6574     Yspring_eB,                         FALSE,  TRUE,
6575     EL_SPRING,                          ACTION_MOVING, MV_BIT_RIGHT
6576   },
6577   {
6578     Yspring_w,                          FALSE,  FALSE,
6579     EL_SPRING,                          ACTION_MOVING, MV_BIT_LEFT
6580   },
6581   {
6582     Yspring_wB,                         FALSE,  TRUE,
6583     EL_SPRING,                          ACTION_MOVING, MV_BIT_LEFT
6584   },
6585   {
6586     Yspring_alien_e,                    FALSE,  FALSE,
6587     EL_SPRING,                          ACTION_EATING, MV_BIT_RIGHT
6588   },
6589   {
6590     Yspring_alien_eB,                   FALSE,  TRUE,
6591     EL_SPRING,                          ACTION_EATING, MV_BIT_RIGHT
6592   },
6593   {
6594     Yspring_alien_w,                    FALSE,  FALSE,
6595     EL_SPRING,                          ACTION_EATING, MV_BIT_LEFT
6596   },
6597   {
6598     Yspring_alien_wB,                   FALSE,  TRUE,
6599     EL_SPRING,                          ACTION_EATING, MV_BIT_LEFT
6600   },
6601
6602   {
6603     Xpush_emerald_e,                    FALSE,  FALSE,
6604     EL_EMERALD,                         -1, MV_BIT_RIGHT
6605   },
6606   {
6607     Xpush_emerald_w,                    FALSE,  FALSE,
6608     EL_EMERALD,                         -1, MV_BIT_LEFT
6609   },
6610   {
6611     Xpush_diamond_e,                    FALSE,  FALSE,
6612     EL_DIAMOND,                         -1, MV_BIT_RIGHT
6613   },
6614   {
6615     Xpush_diamond_w,                    FALSE,  FALSE,
6616     EL_DIAMOND,                         -1, MV_BIT_LEFT
6617   },
6618   {
6619     Xpush_stone_e,                      FALSE,  FALSE,
6620     EL_ROCK,                            -1, MV_BIT_RIGHT
6621   },
6622   {
6623     Xpush_stone_w,                      FALSE,  FALSE,
6624     EL_ROCK,                            -1, MV_BIT_LEFT
6625   },
6626   {
6627     Xpush_bomb_e,                       FALSE,  FALSE,
6628     EL_BOMB,                            -1, MV_BIT_RIGHT
6629   },
6630   {
6631     Xpush_bomb_w,                       FALSE,  FALSE,
6632     EL_BOMB,                            -1, MV_BIT_LEFT
6633   },
6634   {
6635     Xpush_nut_e,                        FALSE,  FALSE,
6636     EL_NUT,                             -1, MV_BIT_RIGHT
6637   },
6638   {
6639     Xpush_nut_w,                        FALSE,  FALSE,
6640     EL_NUT,                             -1, MV_BIT_LEFT
6641   },
6642   {
6643     Xpush_spring_e,                     FALSE,  FALSE,
6644     EL_SPRING_RIGHT,                    -1, MV_BIT_RIGHT
6645   },
6646   {
6647     Xpush_spring_w,                     FALSE,  FALSE,
6648     EL_SPRING_LEFT,                     -1, MV_BIT_LEFT
6649   },
6650
6651   {
6652     Xdynamite,                          TRUE,   FALSE,
6653     EL_EM_DYNAMITE,                     -1, -1
6654   },
6655   {
6656     Ydynamite_blank,                    FALSE,  FALSE,
6657     EL_EM_DYNAMITE,                     ACTION_COLLECTING, -1
6658   },
6659   {
6660     Xdynamite_1,                        TRUE,   FALSE,
6661     EL_EM_DYNAMITE_ACTIVE,              -1, -1
6662   },
6663   {
6664     Xdynamite_2,                        FALSE,  FALSE,
6665     EL_EM_DYNAMITE_ACTIVE,              -1, -1
6666   },
6667   {
6668     Xdynamite_3,                        FALSE,  FALSE,
6669     EL_EM_DYNAMITE_ACTIVE,              -1, -1
6670   },
6671   {
6672     Xdynamite_4,                        FALSE,  FALSE,
6673     EL_EM_DYNAMITE_ACTIVE,              -1, -1
6674   },
6675
6676   {
6677     Xkey_1,                             TRUE,   FALSE,
6678     EL_EM_KEY_1,                        -1, -1
6679   },
6680   {
6681     Xkey_2,                             TRUE,   FALSE,
6682     EL_EM_KEY_2,                        -1, -1
6683   },
6684   {
6685     Xkey_3,                             TRUE,   FALSE,
6686     EL_EM_KEY_3,                        -1, -1
6687   },
6688   {
6689     Xkey_4,                             TRUE,   FALSE,
6690     EL_EM_KEY_4,                        -1, -1
6691   },
6692   {
6693     Xkey_5,                             TRUE,   FALSE,
6694     EL_EMC_KEY_5,                       -1, -1
6695   },
6696   {
6697     Xkey_6,                             TRUE,   FALSE,
6698     EL_EMC_KEY_6,                       -1, -1
6699   },
6700   {
6701     Xkey_7,                             TRUE,   FALSE,
6702     EL_EMC_KEY_7,                       -1, -1
6703   },
6704   {
6705     Xkey_8,                             TRUE,   FALSE,
6706     EL_EMC_KEY_8,                       -1, -1
6707   },
6708
6709   {
6710     Xdoor_1,                            TRUE,   FALSE,
6711     EL_EM_GATE_1,                       -1, -1
6712   },
6713   {
6714     Xdoor_2,                            TRUE,   FALSE,
6715     EL_EM_GATE_2,                       -1, -1
6716   },
6717   {
6718     Xdoor_3,                            TRUE,   FALSE,
6719     EL_EM_GATE_3,                       -1, -1
6720   },
6721   {
6722     Xdoor_4,                            TRUE,   FALSE,
6723     EL_EM_GATE_4,                       -1, -1
6724   },
6725   {
6726     Xdoor_5,                            TRUE,   FALSE,
6727     EL_EMC_GATE_5,                      -1, -1
6728   },
6729   {
6730     Xdoor_6,                            TRUE,   FALSE,
6731     EL_EMC_GATE_6,                      -1, -1
6732   },
6733   {
6734     Xdoor_7,                            TRUE,   FALSE,
6735     EL_EMC_GATE_7,                      -1, -1
6736   },
6737   {
6738     Xdoor_8,                            TRUE,   FALSE,
6739     EL_EMC_GATE_8,                      -1, -1
6740   },
6741
6742   {
6743     Xfake_door_1,                       TRUE,   FALSE,
6744     EL_EM_GATE_1_GRAY,                  -1, -1
6745   },
6746   {
6747     Xfake_door_2,                       TRUE,   FALSE,
6748     EL_EM_GATE_2_GRAY,                  -1, -1
6749   },
6750   {
6751     Xfake_door_3,                       TRUE,   FALSE,
6752     EL_EM_GATE_3_GRAY,                  -1, -1
6753   },
6754   {
6755     Xfake_door_4,                       TRUE,   FALSE,
6756     EL_EM_GATE_4_GRAY,                  -1, -1
6757   },
6758   {
6759     Xfake_door_5,                       TRUE,   FALSE,
6760     EL_EMC_GATE_5_GRAY,                 -1, -1
6761   },
6762   {
6763     Xfake_door_6,                       TRUE,   FALSE,
6764     EL_EMC_GATE_6_GRAY,                 -1, -1
6765   },
6766   {
6767     Xfake_door_7,                       TRUE,   FALSE,
6768     EL_EMC_GATE_7_GRAY,                 -1, -1
6769   },
6770   {
6771     Xfake_door_8,                       TRUE,   FALSE,
6772     EL_EMC_GATE_8_GRAY,                 -1, -1
6773   },
6774
6775   {
6776     Xballoon,                           TRUE,   FALSE,
6777     EL_BALLOON,                         -1, -1
6778   },
6779   {
6780     Yballoon_n,                         FALSE,  FALSE,
6781     EL_BALLOON,                         ACTION_MOVING, MV_BIT_UP
6782   },
6783   {
6784     Yballoon_nB,                        FALSE,  TRUE,
6785     EL_BALLOON,                         ACTION_MOVING, MV_BIT_UP
6786   },
6787   {
6788     Yballoon_e,                         FALSE,  FALSE,
6789     EL_BALLOON,                         ACTION_MOVING, MV_BIT_RIGHT
6790   },
6791   {
6792     Yballoon_eB,                        FALSE,  TRUE,
6793     EL_BALLOON,                         ACTION_MOVING, MV_BIT_RIGHT
6794   },
6795   {
6796     Yballoon_s,                         FALSE,  FALSE,
6797     EL_BALLOON,                         ACTION_MOVING, MV_BIT_DOWN
6798   },
6799   {
6800     Yballoon_sB,                        FALSE,  TRUE,
6801     EL_BALLOON,                         ACTION_MOVING, MV_BIT_DOWN
6802   },
6803   {
6804     Yballoon_w,                         FALSE,  FALSE,
6805     EL_BALLOON,                         ACTION_MOVING, MV_BIT_LEFT
6806   },
6807   {
6808     Yballoon_wB,                        FALSE,  TRUE,
6809     EL_BALLOON,                         ACTION_MOVING, MV_BIT_LEFT
6810   },
6811
6812   {
6813     Xball_1,                            TRUE,   FALSE,
6814     EL_EMC_MAGIC_BALL,                  -1, -1
6815   },
6816   {
6817     Yball_1,                            FALSE,  FALSE,
6818     EL_EMC_MAGIC_BALL,                  ACTION_ACTIVE, -1
6819   },
6820   {
6821     Xball_2,                            FALSE,  FALSE,
6822     EL_EMC_MAGIC_BALL,                  ACTION_ACTIVE, -1
6823   },
6824   {
6825     Yball_2,                            FALSE,  FALSE,
6826     EL_EMC_MAGIC_BALL,                  ACTION_ACTIVE, -1
6827   },
6828   {
6829     Yball_blank,                        FALSE,  FALSE,
6830     EL_EMC_MAGIC_BALL,                  ACTION_DROPPING, -1
6831   },
6832
6833   {
6834     Xamoeba_1,                          TRUE,   FALSE,
6835     EL_AMOEBA_DRY,                      ACTION_OTHER, -1
6836   },
6837   {
6838     Xamoeba_2,                          FALSE,  FALSE,
6839     EL_AMOEBA_DRY,                      ACTION_OTHER, -1
6840   },
6841   {
6842     Xamoeba_3,                          FALSE,  FALSE,
6843     EL_AMOEBA_DRY,                      ACTION_OTHER, -1
6844   },
6845   {
6846     Xamoeba_4,                          FALSE,  FALSE,
6847     EL_AMOEBA_DRY,                      ACTION_OTHER, -1
6848   },
6849   {
6850     Xamoeba_5,                          TRUE,   FALSE,
6851     EL_AMOEBA_WET,                      ACTION_OTHER, -1
6852   },
6853   {
6854     Xamoeba_6,                          FALSE,  FALSE,
6855     EL_AMOEBA_WET,                      ACTION_OTHER, -1
6856   },
6857   {
6858     Xamoeba_7,                          FALSE,  FALSE,
6859     EL_AMOEBA_WET,                      ACTION_OTHER, -1
6860   },
6861   {
6862     Xamoeba_8,                          FALSE,  FALSE,
6863     EL_AMOEBA_WET,                      ACTION_OTHER, -1
6864   },
6865
6866   {
6867     Xdrip,                              TRUE,   FALSE,
6868     EL_AMOEBA_DROP,                     ACTION_GROWING, -1
6869   },
6870   {
6871     Xdrip_fall,                         FALSE,  FALSE,
6872     EL_AMOEBA_DROP,                     -1, -1
6873   },
6874   {
6875     Xdrip_stretch,                      FALSE,  FALSE,
6876     EL_AMOEBA_DROP,                     ACTION_FALLING, -1
6877   },
6878   {
6879     Xdrip_stretchB,                     FALSE,  TRUE,
6880     EL_AMOEBA_DROP,                     ACTION_FALLING, -1
6881   },
6882   {
6883     Ydrip_1_s,                          FALSE,  FALSE,
6884     EL_AMOEBA_DROP,                     ACTION_FALLING, -1
6885   },
6886   {
6887     Ydrip_1_sB,                         FALSE,  TRUE,
6888     EL_AMOEBA_DROP,                     ACTION_FALLING, -1
6889   },
6890   {
6891     Ydrip_2_s,                          FALSE,  FALSE,
6892     EL_AMOEBA_DROP,                     ACTION_FALLING, -1
6893   },
6894   {
6895     Ydrip_2_sB,                         FALSE,  TRUE,
6896     EL_AMOEBA_DROP,                     ACTION_FALLING, -1
6897   },
6898
6899   {
6900     Xwonderwall,                        TRUE,   FALSE,
6901     EL_MAGIC_WALL,                      -1, -1
6902   },
6903   {
6904     Ywonderwall,                        FALSE,  FALSE,
6905     EL_MAGIC_WALL,                      ACTION_ACTIVE, -1
6906   },
6907
6908   {
6909     Xwheel,                             TRUE,   FALSE,
6910     EL_ROBOT_WHEEL,                     -1, -1
6911   },
6912   {
6913     Ywheel,                             FALSE,  FALSE,
6914     EL_ROBOT_WHEEL,                     ACTION_ACTIVE, -1
6915   },
6916
6917   {
6918     Xswitch,                            TRUE,   FALSE,
6919     EL_EMC_MAGIC_BALL_SWITCH,           -1, -1
6920   },
6921   {
6922     Yswitch,                            FALSE,  FALSE,
6923     EL_EMC_MAGIC_BALL_SWITCH,           ACTION_ACTIVE, -1
6924   },
6925
6926   {
6927     Xbumper,                            TRUE,   FALSE,
6928     EL_EMC_SPRING_BUMPER,               -1, -1
6929   },
6930   {
6931     Ybumper,                            FALSE,  FALSE,
6932     EL_EMC_SPRING_BUMPER,               ACTION_ACTIVE, -1
6933   },
6934
6935   {
6936     Xacid_nw,                           TRUE,   FALSE,
6937     EL_ACID_POOL_TOPLEFT,               -1, -1
6938   },
6939   {
6940     Xacid_ne,                           TRUE,   FALSE,
6941     EL_ACID_POOL_TOPRIGHT,              -1, -1
6942   },
6943   {
6944     Xacid_sw,                           TRUE,   FALSE,
6945     EL_ACID_POOL_BOTTOMLEFT,            -1, -1
6946   },
6947   {
6948     Xacid_s,                            TRUE,   FALSE,
6949     EL_ACID_POOL_BOTTOM,                -1, -1
6950   },
6951   {
6952     Xacid_se,                           TRUE,   FALSE,
6953     EL_ACID_POOL_BOTTOMRIGHT,           -1, -1
6954   },
6955
6956   {
6957     Xfake_blank,                        TRUE,   FALSE,
6958     EL_INVISIBLE_WALL,                  -1, -1
6959   },
6960   {
6961     Yfake_blank,                        FALSE,  FALSE,
6962     EL_INVISIBLE_WALL,                  ACTION_ACTIVE, -1
6963   },
6964
6965   {
6966     Xfake_grass,                        TRUE,   FALSE,
6967     EL_EMC_FAKE_GRASS,                  -1, -1
6968   },
6969   {
6970     Yfake_grass,                        FALSE,  FALSE,
6971     EL_EMC_FAKE_GRASS,                  ACTION_ACTIVE, -1
6972   },
6973
6974   {
6975     Xfake_amoeba,                       TRUE,   FALSE,
6976     EL_EMC_DRIPPER,                     -1, -1
6977   },
6978   {
6979     Yfake_amoeba,                       FALSE,  FALSE,
6980     EL_EMC_DRIPPER,                     ACTION_ACTIVE, -1
6981   },
6982
6983   {
6984     Xlenses,                            TRUE,   FALSE,
6985     EL_EMC_LENSES,                      -1, -1
6986   },
6987
6988   {
6989     Xmagnify,                           TRUE,   FALSE,
6990     EL_EMC_MAGNIFIER,                   -1, -1
6991   },
6992
6993   {
6994     Xsand,                              TRUE,   FALSE,
6995     EL_QUICKSAND_EMPTY,                 -1, -1
6996   },
6997   {
6998     Xsand_stone,                        TRUE,   FALSE,
6999     EL_QUICKSAND_FULL,                  -1, -1
7000   },
7001   {
7002     Xsand_stonein_1,                    FALSE,  TRUE,
7003     EL_ROCK,                            ACTION_FILLING, -1
7004   },
7005   {
7006     Xsand_stonein_2,                    FALSE,  TRUE,
7007     EL_ROCK,                            ACTION_FILLING, -1
7008   },
7009   {
7010     Xsand_stonein_3,                    FALSE,  TRUE,
7011     EL_ROCK,                            ACTION_FILLING, -1
7012   },
7013   {
7014     Xsand_stonein_4,                    FALSE,  TRUE,
7015     EL_ROCK,                            ACTION_FILLING, -1
7016   },
7017   {
7018     Xsand_sandstone_1,                  FALSE,  FALSE,
7019     EL_QUICKSAND_FILLING,               -1, -1
7020   },
7021   {
7022     Xsand_sandstone_2,                  FALSE,  FALSE,
7023     EL_QUICKSAND_FILLING,               -1, -1
7024   },
7025   {
7026     Xsand_sandstone_3,                  FALSE,  FALSE,
7027     EL_QUICKSAND_FILLING,               -1, -1
7028   },
7029   {
7030     Xsand_sandstone_4,                  FALSE,  FALSE,
7031     EL_QUICKSAND_FILLING,               -1, -1
7032   },
7033   {
7034     Xsand_stonesand_1,                  FALSE,  FALSE,
7035     EL_QUICKSAND_EMPTYING,              -1, -1
7036   },
7037   {
7038     Xsand_stonesand_2,                  FALSE,  FALSE,
7039     EL_QUICKSAND_EMPTYING,              -1, -1
7040   },
7041   {
7042     Xsand_stonesand_3,                  FALSE,  FALSE,
7043     EL_QUICKSAND_EMPTYING,              -1, -1
7044   },
7045   {
7046     Xsand_stonesand_4,                  FALSE,  FALSE,
7047     EL_QUICKSAND_EMPTYING,              -1, -1
7048   },
7049   {
7050     Xsand_stoneout_1,                   FALSE,  FALSE,
7051     EL_ROCK,                            ACTION_EMPTYING, -1
7052   },
7053   {
7054     Xsand_stoneout_2,                   FALSE,  FALSE,
7055     EL_ROCK,                            ACTION_EMPTYING, -1
7056   },
7057   {
7058     Xsand_stonesand_quickout_1,         FALSE,  FALSE,
7059     EL_QUICKSAND_EMPTYING,              -1, -1
7060   },
7061   {
7062     Xsand_stonesand_quickout_2,         FALSE,  FALSE,
7063     EL_QUICKSAND_EMPTYING,              -1, -1
7064   },
7065
7066   {
7067     Xslide_ns,                          TRUE,   FALSE,
7068     EL_EXPANDABLE_WALL_VERTICAL,        -1, -1
7069   },
7070   {
7071     Yslide_ns_blank,                    FALSE,  FALSE,
7072     EL_EXPANDABLE_WALL_VERTICAL,        ACTION_GROWING, -1
7073   },
7074   {
7075     Xslide_ew,                          TRUE,   FALSE,
7076     EL_EXPANDABLE_WALL_HORIZONTAL,      -1, -1
7077   },
7078   {
7079     Yslide_ew_blank,                    FALSE,  FALSE,
7080     EL_EXPANDABLE_WALL_HORIZONTAL,      ACTION_GROWING, -1
7081   },
7082
7083   {
7084     Xwind_n,                            TRUE,   FALSE,
7085     EL_BALLOON_SWITCH_UP,               -1, -1
7086   },
7087   {
7088     Xwind_e,                            TRUE,   FALSE,
7089     EL_BALLOON_SWITCH_RIGHT,            -1, -1
7090   },
7091   {
7092     Xwind_s,                            TRUE,   FALSE,
7093     EL_BALLOON_SWITCH_DOWN,             -1, -1
7094   },
7095   {
7096     Xwind_w,                            TRUE,   FALSE,
7097     EL_BALLOON_SWITCH_LEFT,             -1, -1
7098   },
7099   {
7100     Xwind_any,                          TRUE,   FALSE,
7101     EL_BALLOON_SWITCH_ANY,              -1, -1
7102   },
7103   {
7104     Xwind_stop,                         TRUE,   FALSE,
7105     EL_BALLOON_SWITCH_NONE,             -1, -1
7106   },
7107
7108   {
7109     Xexit,                              TRUE,   FALSE,
7110     EL_EM_EXIT_CLOSED,                  -1, -1
7111   },
7112   {
7113     Xexit_1,                            TRUE,   FALSE,
7114     EL_EM_EXIT_OPEN,                    -1, -1
7115   },
7116   {
7117     Xexit_2,                            FALSE,  FALSE,
7118     EL_EM_EXIT_OPEN,                    -1, -1
7119   },
7120   {
7121     Xexit_3,                            FALSE,  FALSE,
7122     EL_EM_EXIT_OPEN,                    -1, -1
7123   },
7124
7125   {
7126     Xpause,                             FALSE,  FALSE,
7127     EL_EMPTY,                           -1, -1
7128   },
7129
7130   {
7131     Xwall_1,                            TRUE,   FALSE,
7132     EL_WALL,                            -1, -1
7133   },
7134   {
7135     Xwall_2,                            TRUE,   FALSE,
7136     EL_EMC_WALL_14,                     -1, -1
7137   },
7138   {
7139     Xwall_3,                            TRUE,   FALSE,
7140     EL_EMC_WALL_15,                     -1, -1
7141   },
7142   {
7143     Xwall_4,                            TRUE,   FALSE,
7144     EL_EMC_WALL_16,                     -1, -1
7145   },
7146
7147   {
7148     Xroundwall_1,                       TRUE,   FALSE,
7149     EL_WALL_SLIPPERY,                   -1, -1
7150   },
7151   {
7152     Xroundwall_2,                       TRUE,   FALSE,
7153     EL_EMC_WALL_SLIPPERY_2,             -1, -1
7154   },
7155   {
7156     Xroundwall_3,                       TRUE,   FALSE,
7157     EL_EMC_WALL_SLIPPERY_3,             -1, -1
7158   },
7159   {
7160     Xroundwall_4,                       TRUE,   FALSE,
7161     EL_EMC_WALL_SLIPPERY_4,             -1, -1
7162   },
7163
7164   {
7165     Xsteel_1,                           TRUE,   FALSE,
7166     EL_STEELWALL,                       -1, -1
7167   },
7168   {
7169     Xsteel_2,                           TRUE,   FALSE,
7170     EL_EMC_STEELWALL_2,                 -1, -1
7171   },
7172   {
7173     Xsteel_3,                           TRUE,   FALSE,
7174     EL_EMC_STEELWALL_3,                 -1, -1
7175   },
7176   {
7177     Xsteel_4,                           TRUE,   FALSE,
7178     EL_EMC_STEELWALL_4,                 -1, -1
7179   },
7180
7181   {
7182     Xdecor_1,                           TRUE,   FALSE,
7183     EL_EMC_WALL_8,                      -1, -1
7184   },
7185   {
7186     Xdecor_2,                           TRUE,   FALSE,
7187     EL_EMC_WALL_6,                      -1, -1
7188   },
7189   {
7190     Xdecor_3,                           TRUE,   FALSE,
7191     EL_EMC_WALL_4,                      -1, -1
7192   },
7193   {
7194     Xdecor_4,                           TRUE,   FALSE,
7195     EL_EMC_WALL_7,                      -1, -1
7196   },
7197   {
7198     Xdecor_5,                           TRUE,   FALSE,
7199     EL_EMC_WALL_5,                      -1, -1
7200   },
7201   {
7202     Xdecor_6,                           TRUE,   FALSE,
7203     EL_EMC_WALL_9,                      -1, -1
7204   },
7205   {
7206     Xdecor_7,                           TRUE,   FALSE,
7207     EL_EMC_WALL_10,                     -1, -1
7208   },
7209   {
7210     Xdecor_8,                           TRUE,   FALSE,
7211     EL_EMC_WALL_1,                      -1, -1
7212   },
7213   {
7214     Xdecor_9,                           TRUE,   FALSE,
7215     EL_EMC_WALL_2,                      -1, -1
7216   },
7217   {
7218     Xdecor_10,                          TRUE,   FALSE,
7219     EL_EMC_WALL_3,                      -1, -1
7220   },
7221   {
7222     Xdecor_11,                          TRUE,   FALSE,
7223     EL_EMC_WALL_11,                     -1, -1
7224   },
7225   {
7226     Xdecor_12,                          TRUE,   FALSE,
7227     EL_EMC_WALL_12,                     -1, -1
7228   },
7229
7230   {
7231     Xalpha_0,                           TRUE,   FALSE,
7232     EL_CHAR('0'),                       -1, -1
7233   },
7234   {
7235     Xalpha_1,                           TRUE,   FALSE,
7236     EL_CHAR('1'),                       -1, -1
7237   },
7238   {
7239     Xalpha_2,                           TRUE,   FALSE,
7240     EL_CHAR('2'),                       -1, -1
7241   },
7242   {
7243     Xalpha_3,                           TRUE,   FALSE,
7244     EL_CHAR('3'),                       -1, -1
7245   },
7246   {
7247     Xalpha_4,                           TRUE,   FALSE,
7248     EL_CHAR('4'),                       -1, -1
7249   },
7250   {
7251     Xalpha_5,                           TRUE,   FALSE,
7252     EL_CHAR('5'),                       -1, -1
7253   },
7254   {
7255     Xalpha_6,                           TRUE,   FALSE,
7256     EL_CHAR('6'),                       -1, -1
7257   },
7258   {
7259     Xalpha_7,                           TRUE,   FALSE,
7260     EL_CHAR('7'),                       -1, -1
7261   },
7262   {
7263     Xalpha_8,                           TRUE,   FALSE,
7264     EL_CHAR('8'),                       -1, -1
7265   },
7266   {
7267     Xalpha_9,                           TRUE,   FALSE,
7268     EL_CHAR('9'),                       -1, -1
7269   },
7270   {
7271     Xalpha_excla,                       TRUE,   FALSE,
7272     EL_CHAR('!'),                       -1, -1
7273   },
7274   {
7275     Xalpha_apost,                       TRUE,   FALSE,
7276     EL_CHAR('\''),                      -1, -1
7277   },
7278   {
7279     Xalpha_comma,                       TRUE,   FALSE,
7280     EL_CHAR(','),                       -1, -1
7281   },
7282   {
7283     Xalpha_minus,                       TRUE,   FALSE,
7284     EL_CHAR('-'),                       -1, -1
7285   },
7286   {
7287     Xalpha_perio,                       TRUE,   FALSE,
7288     EL_CHAR('.'),                       -1, -1
7289   },
7290   {
7291     Xalpha_colon,                       TRUE,   FALSE,
7292     EL_CHAR(':'),                       -1, -1
7293   },
7294   {
7295     Xalpha_quest,                       TRUE,   FALSE,
7296     EL_CHAR('?'),                       -1, -1
7297   },
7298   {
7299     Xalpha_a,                           TRUE,   FALSE,
7300     EL_CHAR('A'),                       -1, -1
7301   },
7302   {
7303     Xalpha_b,                           TRUE,   FALSE,
7304     EL_CHAR('B'),                       -1, -1
7305   },
7306   {
7307     Xalpha_c,                           TRUE,   FALSE,
7308     EL_CHAR('C'),                       -1, -1
7309   },
7310   {
7311     Xalpha_d,                           TRUE,   FALSE,
7312     EL_CHAR('D'),                       -1, -1
7313   },
7314   {
7315     Xalpha_e,                           TRUE,   FALSE,
7316     EL_CHAR('E'),                       -1, -1
7317   },
7318   {
7319     Xalpha_f,                           TRUE,   FALSE,
7320     EL_CHAR('F'),                       -1, -1
7321   },
7322   {
7323     Xalpha_g,                           TRUE,   FALSE,
7324     EL_CHAR('G'),                       -1, -1
7325   },
7326   {
7327     Xalpha_h,                           TRUE,   FALSE,
7328     EL_CHAR('H'),                       -1, -1
7329   },
7330   {
7331     Xalpha_i,                           TRUE,   FALSE,
7332     EL_CHAR('I'),                       -1, -1
7333   },
7334   {
7335     Xalpha_j,                           TRUE,   FALSE,
7336     EL_CHAR('J'),                       -1, -1
7337   },
7338   {
7339     Xalpha_k,                           TRUE,   FALSE,
7340     EL_CHAR('K'),                       -1, -1
7341   },
7342   {
7343     Xalpha_l,                           TRUE,   FALSE,
7344     EL_CHAR('L'),                       -1, -1
7345   },
7346   {
7347     Xalpha_m,                           TRUE,   FALSE,
7348     EL_CHAR('M'),                       -1, -1
7349   },
7350   {
7351     Xalpha_n,                           TRUE,   FALSE,
7352     EL_CHAR('N'),                       -1, -1
7353   },
7354   {
7355     Xalpha_o,                           TRUE,   FALSE,
7356     EL_CHAR('O'),                       -1, -1
7357   },
7358   {
7359     Xalpha_p,                           TRUE,   FALSE,
7360     EL_CHAR('P'),                       -1, -1
7361   },
7362   {
7363     Xalpha_q,                           TRUE,   FALSE,
7364     EL_CHAR('Q'),                       -1, -1
7365   },
7366   {
7367     Xalpha_r,                           TRUE,   FALSE,
7368     EL_CHAR('R'),                       -1, -1
7369   },
7370   {
7371     Xalpha_s,                           TRUE,   FALSE,
7372     EL_CHAR('S'),                       -1, -1
7373   },
7374   {
7375     Xalpha_t,                           TRUE,   FALSE,
7376     EL_CHAR('T'),                       -1, -1
7377   },
7378   {
7379     Xalpha_u,                           TRUE,   FALSE,
7380     EL_CHAR('U'),                       -1, -1
7381   },
7382   {
7383     Xalpha_v,                           TRUE,   FALSE,
7384     EL_CHAR('V'),                       -1, -1
7385   },
7386   {
7387     Xalpha_w,                           TRUE,   FALSE,
7388     EL_CHAR('W'),                       -1, -1
7389   },
7390   {
7391     Xalpha_x,                           TRUE,   FALSE,
7392     EL_CHAR('X'),                       -1, -1
7393   },
7394   {
7395     Xalpha_y,                           TRUE,   FALSE,
7396     EL_CHAR('Y'),                       -1, -1
7397   },
7398   {
7399     Xalpha_z,                           TRUE,   FALSE,
7400     EL_CHAR('Z'),                       -1, -1
7401   },
7402   {
7403     Xalpha_arrow_e,                     TRUE,   FALSE,
7404     EL_CHAR('>'),                       -1, -1
7405   },
7406   {
7407     Xalpha_arrow_w,                     TRUE,   FALSE,
7408     EL_CHAR('<'),                       -1, -1
7409   },
7410   {
7411     Xalpha_copyr,                       TRUE,   FALSE,
7412     EL_CHAR(CHAR_BYTE_COPYRIGHT),       -1, -1
7413   },
7414
7415   {
7416     Ykey_1_blank,                       FALSE,  FALSE,
7417     EL_EM_KEY_1,                        ACTION_COLLECTING, -1
7418   },
7419   {
7420     Ykey_2_blank,                       FALSE,  FALSE,
7421     EL_EM_KEY_2,                        ACTION_COLLECTING, -1
7422   },
7423   {
7424     Ykey_3_blank,                       FALSE,  FALSE,
7425     EL_EM_KEY_3,                        ACTION_COLLECTING, -1
7426   },
7427   {
7428     Ykey_4_blank,                       FALSE,  FALSE,
7429     EL_EM_KEY_4,                        ACTION_COLLECTING, -1
7430   },
7431   {
7432     Ykey_5_blank,                       FALSE,  FALSE,
7433     EL_EMC_KEY_5,                       ACTION_COLLECTING, -1
7434   },
7435   {
7436     Ykey_6_blank,                       FALSE,  FALSE,
7437     EL_EMC_KEY_6,                       ACTION_COLLECTING, -1
7438   },
7439   {
7440     Ykey_7_blank,                       FALSE,  FALSE,
7441     EL_EMC_KEY_7,                       ACTION_COLLECTING, -1
7442   },
7443   {
7444     Ykey_8_blank,                       FALSE,  FALSE,
7445     EL_EMC_KEY_8,                       ACTION_COLLECTING, -1
7446   },
7447   {
7448     Ylenses_blank,                      FALSE,  FALSE,
7449     EL_EMC_LENSES,                      ACTION_COLLECTING, -1
7450   },
7451   {
7452     Ymagnify_blank,                     FALSE,  FALSE,
7453     EL_EMC_MAGNIFIER,                   ACTION_COLLECTING, -1
7454   },
7455   {
7456     Ygrass_blank,                       FALSE,  FALSE,
7457     EL_EMC_GRASS,                       ACTION_SNAPPING, -1
7458   },
7459   {
7460     Ydirt_blank,                        FALSE,  FALSE,
7461     EL_SAND,                            ACTION_SNAPPING, -1
7462   },
7463
7464   {
7465     -1,                                 FALSE,  FALSE,
7466     -1,                                 -1, -1
7467   }
7468 };
7469
7470 static struct Mapping_EM_to_RND_player
7471 {
7472   int action_em;
7473   int player_nr;
7474
7475   int element_rnd;
7476   int action;
7477   int direction;
7478 }
7479 em_player_mapping_list[MAX_PLAYERS * PLY_MAX + 1] =
7480 {
7481   {
7482     PLY_walk_n,                         0,
7483     EL_PLAYER_1,                        ACTION_MOVING, MV_BIT_UP,
7484   },
7485   {
7486     PLY_walk_e,                         0,
7487     EL_PLAYER_1,                        ACTION_MOVING, MV_BIT_RIGHT,
7488   },
7489   {
7490     PLY_walk_s,                         0,
7491     EL_PLAYER_1,                        ACTION_MOVING, MV_BIT_DOWN,
7492   },
7493   {
7494     PLY_walk_w,                         0,
7495     EL_PLAYER_1,                        ACTION_MOVING, MV_BIT_LEFT,
7496   },
7497   {
7498     PLY_push_n,                         0,
7499     EL_PLAYER_1,                        ACTION_PUSHING, MV_BIT_UP,
7500   },
7501   {
7502     PLY_push_e,                         0,
7503     EL_PLAYER_1,                        ACTION_PUSHING, MV_BIT_RIGHT,
7504   },
7505   {
7506     PLY_push_s,                         0,
7507     EL_PLAYER_1,                        ACTION_PUSHING, MV_BIT_DOWN,
7508   },
7509   {
7510     PLY_push_w,                         0,
7511     EL_PLAYER_1,                        ACTION_PUSHING, MV_BIT_LEFT,
7512   },
7513   {
7514     PLY_shoot_n,                        0,
7515     EL_PLAYER_1,                        ACTION_SNAPPING, MV_BIT_UP,
7516   },
7517   {
7518     PLY_shoot_e,                        0,
7519     EL_PLAYER_1,                        ACTION_SNAPPING, MV_BIT_RIGHT,
7520   },
7521   {
7522     PLY_shoot_s,                        0,
7523     EL_PLAYER_1,                        ACTION_SNAPPING, MV_BIT_DOWN,
7524   },
7525   {
7526     PLY_shoot_w,                        0,
7527     EL_PLAYER_1,                        ACTION_SNAPPING, MV_BIT_LEFT,
7528   },
7529   {
7530     PLY_walk_n,                         1,
7531     EL_PLAYER_2,                        ACTION_MOVING, MV_BIT_UP,
7532   },
7533   {
7534     PLY_walk_e,                         1,
7535     EL_PLAYER_2,                        ACTION_MOVING, MV_BIT_RIGHT,
7536   },
7537   {
7538     PLY_walk_s,                         1,
7539     EL_PLAYER_2,                        ACTION_MOVING, MV_BIT_DOWN,
7540   },
7541   {
7542     PLY_walk_w,                         1,
7543     EL_PLAYER_2,                        ACTION_MOVING, MV_BIT_LEFT,
7544   },
7545   {
7546     PLY_push_n,                         1,
7547     EL_PLAYER_2,                        ACTION_PUSHING, MV_BIT_UP,
7548   },
7549   {
7550     PLY_push_e,                         1,
7551     EL_PLAYER_2,                        ACTION_PUSHING, MV_BIT_RIGHT,
7552   },
7553   {
7554     PLY_push_s,                         1,
7555     EL_PLAYER_2,                        ACTION_PUSHING, MV_BIT_DOWN,
7556   },
7557   {
7558     PLY_push_w,                         1,
7559     EL_PLAYER_2,                        ACTION_PUSHING, MV_BIT_LEFT,
7560   },
7561   {
7562     PLY_shoot_n,                        1,
7563     EL_PLAYER_2,                        ACTION_SNAPPING, MV_BIT_UP,
7564   },
7565   {
7566     PLY_shoot_e,                        1,
7567     EL_PLAYER_2,                        ACTION_SNAPPING, MV_BIT_RIGHT,
7568   },
7569   {
7570     PLY_shoot_s,                        1,
7571     EL_PLAYER_2,                        ACTION_SNAPPING, MV_BIT_DOWN,
7572   },
7573   {
7574     PLY_shoot_w,                        1,
7575     EL_PLAYER_2,                        ACTION_SNAPPING, MV_BIT_LEFT,
7576   },
7577   {
7578     PLY_still,                          0,
7579     EL_PLAYER_1,                        ACTION_DEFAULT, -1,
7580   },
7581   {
7582     PLY_still,                          1,
7583     EL_PLAYER_2,                        ACTION_DEFAULT, -1,
7584   },
7585   {
7586     PLY_walk_n,                         2,
7587     EL_PLAYER_3,                        ACTION_MOVING, MV_BIT_UP,
7588   },
7589   {
7590     PLY_walk_e,                         2,
7591     EL_PLAYER_3,                        ACTION_MOVING, MV_BIT_RIGHT,
7592   },
7593   {
7594     PLY_walk_s,                         2,
7595     EL_PLAYER_3,                        ACTION_MOVING, MV_BIT_DOWN,
7596   },
7597   {
7598     PLY_walk_w,                         2,
7599     EL_PLAYER_3,                        ACTION_MOVING, MV_BIT_LEFT,
7600   },
7601   {
7602     PLY_push_n,                         2,
7603     EL_PLAYER_3,                        ACTION_PUSHING, MV_BIT_UP,
7604   },
7605   {
7606     PLY_push_e,                         2,
7607     EL_PLAYER_3,                        ACTION_PUSHING, MV_BIT_RIGHT,
7608   },
7609   {
7610     PLY_push_s,                         2,
7611     EL_PLAYER_3,                        ACTION_PUSHING, MV_BIT_DOWN,
7612   },
7613   {
7614     PLY_push_w,                         2,
7615     EL_PLAYER_3,                        ACTION_PUSHING, MV_BIT_LEFT,
7616   },
7617   {
7618     PLY_shoot_n,                        2,
7619     EL_PLAYER_3,                        ACTION_SNAPPING, MV_BIT_UP,
7620   },
7621   {
7622     PLY_shoot_e,                        2,
7623     EL_PLAYER_3,                        ACTION_SNAPPING, MV_BIT_RIGHT,
7624   },
7625   {
7626     PLY_shoot_s,                        2,
7627     EL_PLAYER_3,                        ACTION_SNAPPING, MV_BIT_DOWN,
7628   },
7629   {
7630     PLY_shoot_w,                        2,
7631     EL_PLAYER_3,                        ACTION_SNAPPING, MV_BIT_LEFT,
7632   },
7633   {
7634     PLY_walk_n,                         3,
7635     EL_PLAYER_4,                        ACTION_MOVING, MV_BIT_UP,
7636   },
7637   {
7638     PLY_walk_e,                         3,
7639     EL_PLAYER_4,                        ACTION_MOVING, MV_BIT_RIGHT,
7640   },
7641   {
7642     PLY_walk_s,                         3,
7643     EL_PLAYER_4,                        ACTION_MOVING, MV_BIT_DOWN,
7644   },
7645   {
7646     PLY_walk_w,                         3,
7647     EL_PLAYER_4,                        ACTION_MOVING, MV_BIT_LEFT,
7648   },
7649   {
7650     PLY_push_n,                         3,
7651     EL_PLAYER_4,                        ACTION_PUSHING, MV_BIT_UP,
7652   },
7653   {
7654     PLY_push_e,                         3,
7655     EL_PLAYER_4,                        ACTION_PUSHING, MV_BIT_RIGHT,
7656   },
7657   {
7658     PLY_push_s,                         3,
7659     EL_PLAYER_4,                        ACTION_PUSHING, MV_BIT_DOWN,
7660   },
7661   {
7662     PLY_push_w,                         3,
7663     EL_PLAYER_4,                        ACTION_PUSHING, MV_BIT_LEFT,
7664   },
7665   {
7666     PLY_shoot_n,                        3,
7667     EL_PLAYER_4,                        ACTION_SNAPPING, MV_BIT_UP,
7668   },
7669   {
7670     PLY_shoot_e,                        3,
7671     EL_PLAYER_4,                        ACTION_SNAPPING, MV_BIT_RIGHT,
7672   },
7673   {
7674     PLY_shoot_s,                        3,
7675     EL_PLAYER_4,                        ACTION_SNAPPING, MV_BIT_DOWN,
7676   },
7677   {
7678     PLY_shoot_w,                        3,
7679     EL_PLAYER_4,                        ACTION_SNAPPING, MV_BIT_LEFT,
7680   },
7681   {
7682     PLY_still,                          2,
7683     EL_PLAYER_3,                        ACTION_DEFAULT, -1,
7684   },
7685   {
7686     PLY_still,                          3,
7687     EL_PLAYER_4,                        ACTION_DEFAULT, -1,
7688   },
7689
7690   {
7691     -1,                                 -1,
7692     -1,                                 -1, -1
7693   }
7694 };
7695
7696 int map_element_RND_to_EM_cave(int element_rnd)
7697 {
7698   static unsigned short mapping_RND_to_EM[NUM_FILE_ELEMENTS];
7699   static boolean mapping_initialized = FALSE;
7700
7701   if (!mapping_initialized)
7702   {
7703     int i;
7704
7705     // return "Xalpha_quest" for all undefined elements in mapping array
7706     for (i = 0; i < NUM_FILE_ELEMENTS; i++)
7707       mapping_RND_to_EM[i] = Xalpha_quest;
7708
7709     for (i = 0; em_object_mapping_list[i].element_em != -1; i++)
7710       if (em_object_mapping_list[i].is_rnd_to_em_mapping)
7711         mapping_RND_to_EM[em_object_mapping_list[i].element_rnd] =
7712           em_object_mapping_list[i].element_em;
7713
7714     mapping_initialized = TRUE;
7715   }
7716
7717   if (element_rnd < 0 || element_rnd >= NUM_FILE_ELEMENTS)
7718   {
7719     Warn("invalid RND level element %d", element_rnd);
7720
7721     return EL_UNKNOWN;
7722   }
7723
7724   return map_em_element_X_to_C(mapping_RND_to_EM[element_rnd]);
7725 }
7726
7727 int map_element_EM_to_RND_cave(int element_em_cave)
7728 {
7729   static unsigned short mapping_EM_to_RND[GAME_TILE_MAX];
7730   static boolean mapping_initialized = FALSE;
7731
7732   if (!mapping_initialized)
7733   {
7734     int i;
7735
7736     // return "EL_UNKNOWN" for all undefined elements in mapping array
7737     for (i = 0; i < GAME_TILE_MAX; i++)
7738       mapping_EM_to_RND[i] = EL_UNKNOWN;
7739
7740     for (i = 0; em_object_mapping_list[i].element_em != -1; i++)
7741       mapping_EM_to_RND[em_object_mapping_list[i].element_em] =
7742         em_object_mapping_list[i].element_rnd;
7743
7744     mapping_initialized = TRUE;
7745   }
7746
7747   if (element_em_cave < 0 || element_em_cave >= CAVE_TILE_MAX)
7748   {
7749     Warn("invalid EM cave element %d", element_em_cave);
7750
7751     return EL_UNKNOWN;
7752   }
7753
7754   return mapping_EM_to_RND[map_em_element_C_to_X(element_em_cave)];
7755 }
7756
7757 int map_element_EM_to_RND_game(int element_em_game)
7758 {
7759   static unsigned short mapping_EM_to_RND[GAME_TILE_MAX];
7760   static boolean mapping_initialized = FALSE;
7761
7762   if (!mapping_initialized)
7763   {
7764     int i;
7765
7766     // return "EL_UNKNOWN" for all undefined elements in mapping array
7767     for (i = 0; i < GAME_TILE_MAX; i++)
7768       mapping_EM_to_RND[i] = EL_UNKNOWN;
7769
7770     for (i = 0; em_object_mapping_list[i].element_em != -1; i++)
7771       mapping_EM_to_RND[em_object_mapping_list[i].element_em] =
7772         em_object_mapping_list[i].element_rnd;
7773
7774     mapping_initialized = TRUE;
7775   }
7776
7777   if (element_em_game < 0 || element_em_game >= GAME_TILE_MAX)
7778   {
7779     Warn("invalid EM game element %d", element_em_game);
7780
7781     return EL_UNKNOWN;
7782   }
7783
7784   return mapping_EM_to_RND[element_em_game];
7785 }
7786
7787 void map_android_clone_elements_RND_to_EM(struct LevelInfo *level)
7788 {
7789   struct LevelInfo_EM *level_em = level->native_em_level;
7790   struct CAVE *cav = level_em->cav;
7791   int i, j;
7792
7793   for (i = 0; i < GAME_TILE_MAX; i++)
7794     cav->android_array[i] = Cblank;
7795
7796   for (i = 0; i < level->num_android_clone_elements; i++)
7797   {
7798     int element_rnd = level->android_clone_element[i];
7799     int element_em_cave = map_element_RND_to_EM_cave(element_rnd);
7800
7801     for (j = 0; em_object_mapping_list[j].element_em != -1; j++)
7802       if (em_object_mapping_list[j].element_rnd == element_rnd)
7803         cav->android_array[em_object_mapping_list[j].element_em] =
7804           element_em_cave;
7805   }
7806 }
7807
7808 void map_android_clone_elements_EM_to_RND(struct LevelInfo *level)
7809 {
7810   struct LevelInfo_EM *level_em = level->native_em_level;
7811   struct CAVE *cav = level_em->cav;
7812   int i, j;
7813
7814   level->num_android_clone_elements = 0;
7815
7816   for (i = 0; i < GAME_TILE_MAX; i++)
7817   {
7818     int element_em_cave = cav->android_array[i];
7819     int element_rnd;
7820     boolean element_found = FALSE;
7821
7822     if (element_em_cave == Cblank)
7823       continue;
7824
7825     element_rnd = map_element_EM_to_RND_cave(element_em_cave);
7826
7827     for (j = 0; j < level->num_android_clone_elements; j++)
7828       if (level->android_clone_element[j] == element_rnd)
7829         element_found = TRUE;
7830
7831     if (!element_found)
7832     {
7833       level->android_clone_element[level->num_android_clone_elements++] =
7834         element_rnd;
7835
7836       if (level->num_android_clone_elements == MAX_ANDROID_ELEMENTS)
7837         break;
7838     }
7839   }
7840
7841   if (level->num_android_clone_elements == 0)
7842   {
7843     level->num_android_clone_elements = 1;
7844     level->android_clone_element[0] = EL_EMPTY;
7845   }
7846 }
7847
7848 int map_direction_RND_to_EM(int direction)
7849 {
7850   return (direction == MV_UP    ? 0 :
7851           direction == MV_RIGHT ? 1 :
7852           direction == MV_DOWN  ? 2 :
7853           direction == MV_LEFT  ? 3 :
7854           -1);
7855 }
7856
7857 int map_direction_EM_to_RND(int direction)
7858 {
7859   return (direction == 0 ? MV_UP    :
7860           direction == 1 ? MV_RIGHT :
7861           direction == 2 ? MV_DOWN  :
7862           direction == 3 ? MV_LEFT  :
7863           MV_NONE);
7864 }
7865
7866 int map_element_RND_to_SP(int element_rnd)
7867 {
7868   int element_sp = 0x20;        // map unknown elements to yellow "hardware"
7869
7870   if (element_rnd >= EL_SP_START &&
7871       element_rnd <= EL_SP_END)
7872     element_sp = element_rnd - EL_SP_START;
7873   else if (element_rnd == EL_EMPTY_SPACE)
7874     element_sp = 0x00;
7875   else if (element_rnd == EL_INVISIBLE_WALL)
7876     element_sp = 0x28;
7877
7878   return element_sp;
7879 }
7880
7881 int map_element_SP_to_RND(int element_sp)
7882 {
7883   int element_rnd = EL_UNKNOWN;
7884
7885   if (element_sp >= 0x00 &&
7886       element_sp <= 0x27)
7887     element_rnd = EL_SP_START + element_sp;
7888   else if (element_sp == 0x28)
7889     element_rnd = EL_INVISIBLE_WALL;
7890
7891   return element_rnd;
7892 }
7893
7894 int map_action_SP_to_RND(int action_sp)
7895 {
7896   switch (action_sp)
7897   {
7898     case actActive:             return ACTION_ACTIVE;
7899     case actImpact:             return ACTION_IMPACT;
7900     case actExploding:          return ACTION_EXPLODING;
7901     case actDigging:            return ACTION_DIGGING;
7902     case actSnapping:           return ACTION_SNAPPING;
7903     case actCollecting:         return ACTION_COLLECTING;
7904     case actPassing:            return ACTION_PASSING;
7905     case actPushing:            return ACTION_PUSHING;
7906     case actDropping:           return ACTION_DROPPING;
7907
7908     default:                    return ACTION_DEFAULT;
7909   }
7910 }
7911
7912 int map_element_RND_to_MM(int element_rnd)
7913 {
7914   return (element_rnd >= EL_MM_START_1 &&
7915           element_rnd <= EL_MM_END_1 ?
7916           EL_MM_START_1_NATIVE + element_rnd - EL_MM_START_1 :
7917
7918           element_rnd >= EL_MM_START_2 &&
7919           element_rnd <= EL_MM_END_2 ?
7920           EL_MM_START_2_NATIVE + element_rnd - EL_MM_START_2 :
7921
7922           element_rnd >= EL_CHAR_START &&
7923           element_rnd <= EL_CHAR_END ?
7924           EL_MM_CHAR_START_NATIVE + element_rnd - EL_CHAR_START :
7925
7926           element_rnd >= EL_MM_RUNTIME_START &&
7927           element_rnd <= EL_MM_RUNTIME_END ?
7928           EL_MM_RUNTIME_START_NATIVE + element_rnd - EL_MM_RUNTIME_START :
7929
7930           element_rnd >= EL_MM_DUMMY_START &&
7931           element_rnd <= EL_MM_DUMMY_END ?
7932           EL_MM_DUMMY_START_NATIVE + element_rnd - EL_MM_DUMMY_START :
7933
7934           EL_MM_EMPTY_NATIVE);
7935 }
7936
7937 int map_element_MM_to_RND(int element_mm)
7938 {
7939   return (element_mm == EL_MM_EMPTY_NATIVE ||
7940           element_mm == EL_DF_EMPTY_NATIVE ?
7941           EL_EMPTY :
7942
7943           element_mm >= EL_MM_START_1_NATIVE &&
7944           element_mm <= EL_MM_END_1_NATIVE ?
7945           EL_MM_START_1 + element_mm - EL_MM_START_1_NATIVE :
7946
7947           element_mm >= EL_MM_START_2_NATIVE &&
7948           element_mm <= EL_MM_END_2_NATIVE ?
7949           EL_MM_START_2 + element_mm - EL_MM_START_2_NATIVE :
7950
7951           element_mm >= EL_MM_CHAR_START_NATIVE &&
7952           element_mm <= EL_MM_CHAR_END_NATIVE ?
7953           EL_CHAR_START + element_mm - EL_MM_CHAR_START_NATIVE :
7954
7955           element_mm >= EL_MM_RUNTIME_START_NATIVE &&
7956           element_mm <= EL_MM_RUNTIME_END_NATIVE ?
7957           EL_MM_RUNTIME_START + element_mm - EL_MM_RUNTIME_START_NATIVE :
7958
7959           element_mm >= EL_MM_DUMMY_START_NATIVE &&
7960           element_mm <= EL_MM_DUMMY_END_NATIVE ?
7961           EL_MM_DUMMY_START + element_mm - EL_MM_DUMMY_START_NATIVE :
7962
7963           EL_EMPTY);
7964 }
7965
7966 int map_action_MM_to_RND(int action_mm)
7967 {
7968   // all MM actions are defined to exactly match their RND counterparts
7969   return action_mm;
7970 }
7971
7972 int map_sound_MM_to_RND(int sound_mm)
7973 {
7974   switch (sound_mm)
7975   {
7976     case SND_MM_GAME_LEVELTIME_CHARGING:
7977       return SND_GAME_LEVELTIME_CHARGING;
7978
7979     case SND_MM_GAME_HEALTH_CHARGING:
7980       return SND_GAME_HEALTH_CHARGING;
7981
7982     default:
7983       return SND_UNDEFINED;
7984   }
7985 }
7986
7987 int map_mm_wall_element(int element)
7988 {
7989   return (element >= EL_MM_STEEL_WALL_START &&
7990           element <= EL_MM_STEEL_WALL_END ?
7991           EL_MM_STEEL_WALL :
7992
7993           element >= EL_MM_WOODEN_WALL_START &&
7994           element <= EL_MM_WOODEN_WALL_END ?
7995           EL_MM_WOODEN_WALL :
7996
7997           element >= EL_MM_ICE_WALL_START &&
7998           element <= EL_MM_ICE_WALL_END ?
7999           EL_MM_ICE_WALL :
8000
8001           element >= EL_MM_AMOEBA_WALL_START &&
8002           element <= EL_MM_AMOEBA_WALL_END ?
8003           EL_MM_AMOEBA_WALL :
8004
8005           element >= EL_DF_STEEL_WALL_START &&
8006           element <= EL_DF_STEEL_WALL_END ?
8007           EL_DF_STEEL_WALL :
8008
8009           element >= EL_DF_WOODEN_WALL_START &&
8010           element <= EL_DF_WOODEN_WALL_END ?
8011           EL_DF_WOODEN_WALL :
8012
8013           element);
8014 }
8015
8016 int map_mm_wall_element_editor(int element)
8017 {
8018   switch (element)
8019   {
8020     case EL_MM_STEEL_WALL:      return EL_MM_STEEL_WALL_START;
8021     case EL_MM_WOODEN_WALL:     return EL_MM_WOODEN_WALL_START;
8022     case EL_MM_ICE_WALL:        return EL_MM_ICE_WALL_START;
8023     case EL_MM_AMOEBA_WALL:     return EL_MM_AMOEBA_WALL_START;
8024     case EL_DF_STEEL_WALL:      return EL_DF_STEEL_WALL_START;
8025     case EL_DF_WOODEN_WALL:     return EL_DF_WOODEN_WALL_START;
8026
8027     default:                    return element;
8028   }
8029 }
8030
8031 int get_next_element(int element)
8032 {
8033   switch (element)
8034   {
8035     case EL_QUICKSAND_FILLING:          return EL_QUICKSAND_FULL;
8036     case EL_QUICKSAND_EMPTYING:         return EL_QUICKSAND_EMPTY;
8037     case EL_QUICKSAND_FAST_FILLING:     return EL_QUICKSAND_FAST_FULL;
8038     case EL_QUICKSAND_FAST_EMPTYING:    return EL_QUICKSAND_FAST_EMPTY;
8039     case EL_MAGIC_WALL_FILLING:         return EL_MAGIC_WALL_FULL;
8040     case EL_MAGIC_WALL_EMPTYING:        return EL_MAGIC_WALL_ACTIVE;
8041     case EL_BD_MAGIC_WALL_FILLING:      return EL_BD_MAGIC_WALL_FULL;
8042     case EL_BD_MAGIC_WALL_EMPTYING:     return EL_BD_MAGIC_WALL_ACTIVE;
8043     case EL_DC_MAGIC_WALL_FILLING:      return EL_DC_MAGIC_WALL_FULL;
8044     case EL_DC_MAGIC_WALL_EMPTYING:     return EL_DC_MAGIC_WALL_ACTIVE;
8045     case EL_AMOEBA_DROPPING:            return EL_AMOEBA_WET;
8046
8047     default:                            return element;
8048   }
8049 }
8050
8051 int el2img_mm(int element_mm)
8052 {
8053   return el2img(map_element_MM_to_RND(element_mm));
8054 }
8055
8056 int el_act_dir2img(int element, int action, int direction)
8057 {
8058   element = GFX_ELEMENT(element);
8059   direction = MV_DIR_TO_BIT(direction); // default: MV_NONE => MV_DOWN
8060
8061   // direction_graphic[][] == graphic[] for undefined direction graphics
8062   return element_info[element].direction_graphic[action][direction];
8063 }
8064
8065 static int el_act_dir2crm(int element, int action, int direction)
8066 {
8067   element = GFX_ELEMENT(element);
8068   direction = MV_DIR_TO_BIT(direction); // default: MV_NONE => MV_DOWN
8069
8070   // direction_graphic[][] == graphic[] for undefined direction graphics
8071   return element_info[element].direction_crumbled[action][direction];
8072 }
8073
8074 int el_act2img(int element, int action)
8075 {
8076   element = GFX_ELEMENT(element);
8077
8078   return element_info[element].graphic[action];
8079 }
8080
8081 int el_act2crm(int element, int action)
8082 {
8083   element = GFX_ELEMENT(element);
8084
8085   return element_info[element].crumbled[action];
8086 }
8087
8088 int el_dir2img(int element, int direction)
8089 {
8090   element = GFX_ELEMENT(element);
8091
8092   return el_act_dir2img(element, ACTION_DEFAULT, direction);
8093 }
8094
8095 int el2baseimg(int element)
8096 {
8097   return element_info[element].graphic[ACTION_DEFAULT];
8098 }
8099
8100 int el2img(int element)
8101 {
8102   element = GFX_ELEMENT(element);
8103
8104   return element_info[element].graphic[ACTION_DEFAULT];
8105 }
8106
8107 int el2edimg(int element)
8108 {
8109   element = GFX_ELEMENT(element);
8110
8111   return element_info[element].special_graphic[GFX_SPECIAL_ARG_EDITOR];
8112 }
8113
8114 int el2preimg(int element)
8115 {
8116   element = GFX_ELEMENT(element);
8117
8118   return element_info[element].special_graphic[GFX_SPECIAL_ARG_PREVIEW];
8119 }
8120
8121 int el2panelimg(int element)
8122 {
8123   element = GFX_ELEMENT(element);
8124
8125   return element_info[element].special_graphic[GFX_SPECIAL_ARG_PANEL];
8126 }
8127
8128 int font2baseimg(int font_nr)
8129 {
8130   return font_info[font_nr].special_graphic[GFX_SPECIAL_ARG_DEFAULT];
8131 }
8132
8133 int getBeltNrFromBeltElement(int element)
8134 {
8135   return (element < EL_CONVEYOR_BELT_2_LEFT ? 0 :
8136           element < EL_CONVEYOR_BELT_3_LEFT ? 1 :
8137           element < EL_CONVEYOR_BELT_4_LEFT ? 2 : 3);
8138 }
8139
8140 int getBeltNrFromBeltActiveElement(int element)
8141 {
8142   return (element < EL_CONVEYOR_BELT_2_LEFT_ACTIVE ? 0 :
8143           element < EL_CONVEYOR_BELT_3_LEFT_ACTIVE ? 1 :
8144           element < EL_CONVEYOR_BELT_4_LEFT_ACTIVE ? 2 : 3);
8145 }
8146
8147 int getBeltNrFromBeltSwitchElement(int element)
8148 {
8149   return (element < EL_CONVEYOR_BELT_2_SWITCH_LEFT ? 0 :
8150           element < EL_CONVEYOR_BELT_3_SWITCH_LEFT ? 1 :
8151           element < EL_CONVEYOR_BELT_4_SWITCH_LEFT ? 2 : 3);
8152 }
8153
8154 int getBeltDirNrFromBeltElement(int element)
8155 {
8156   static int belt_base_element[4] =
8157   {
8158     EL_CONVEYOR_BELT_1_LEFT,
8159     EL_CONVEYOR_BELT_2_LEFT,
8160     EL_CONVEYOR_BELT_3_LEFT,
8161     EL_CONVEYOR_BELT_4_LEFT
8162   };
8163
8164   int belt_nr = getBeltNrFromBeltElement(element);
8165   int belt_dir_nr = element - belt_base_element[belt_nr];
8166
8167   return (belt_dir_nr % 3);
8168 }
8169
8170 int getBeltDirNrFromBeltSwitchElement(int element)
8171 {
8172   static int belt_base_element[4] =
8173   {
8174     EL_CONVEYOR_BELT_1_SWITCH_LEFT,
8175     EL_CONVEYOR_BELT_2_SWITCH_LEFT,
8176     EL_CONVEYOR_BELT_3_SWITCH_LEFT,
8177     EL_CONVEYOR_BELT_4_SWITCH_LEFT
8178   };
8179
8180   int belt_nr = getBeltNrFromBeltSwitchElement(element);
8181   int belt_dir_nr = element - belt_base_element[belt_nr];
8182
8183   return (belt_dir_nr % 3);
8184 }
8185
8186 int getBeltDirFromBeltElement(int element)
8187 {
8188   static int belt_move_dir[3] =
8189   {
8190     MV_LEFT,
8191     MV_NONE,
8192     MV_RIGHT
8193   };
8194
8195   int belt_dir_nr = getBeltDirNrFromBeltElement(element);
8196
8197   return belt_move_dir[belt_dir_nr];
8198 }
8199
8200 int getBeltDirFromBeltSwitchElement(int element)
8201 {
8202   static int belt_move_dir[3] =
8203   {
8204     MV_LEFT,
8205     MV_NONE,
8206     MV_RIGHT
8207   };
8208
8209   int belt_dir_nr = getBeltDirNrFromBeltSwitchElement(element);
8210
8211   return belt_move_dir[belt_dir_nr];
8212 }
8213
8214 int getBeltElementFromBeltNrAndBeltDirNr(int belt_nr, int belt_dir_nr)
8215 {
8216   static int belt_base_element[4] =
8217   {
8218     EL_CONVEYOR_BELT_1_LEFT,
8219     EL_CONVEYOR_BELT_2_LEFT,
8220     EL_CONVEYOR_BELT_3_LEFT,
8221     EL_CONVEYOR_BELT_4_LEFT
8222   };
8223
8224   return belt_base_element[belt_nr] + belt_dir_nr;
8225 }
8226
8227 int getBeltElementFromBeltNrAndBeltDir(int belt_nr, int belt_dir)
8228 {
8229   int belt_dir_nr = (belt_dir == MV_LEFT ? 0 : belt_dir == MV_RIGHT ? 2 : 1);
8230
8231   return getBeltElementFromBeltNrAndBeltDirNr(belt_nr, belt_dir_nr);
8232 }
8233
8234 int getBeltSwitchElementFromBeltNrAndBeltDirNr(int belt_nr, int belt_dir_nr)
8235 {
8236   static int belt_base_element[4] =
8237   {
8238     EL_CONVEYOR_BELT_1_SWITCH_LEFT,
8239     EL_CONVEYOR_BELT_2_SWITCH_LEFT,
8240     EL_CONVEYOR_BELT_3_SWITCH_LEFT,
8241     EL_CONVEYOR_BELT_4_SWITCH_LEFT
8242   };
8243
8244   return belt_base_element[belt_nr] + belt_dir_nr;
8245 }
8246
8247 int getBeltSwitchElementFromBeltNrAndBeltDir(int belt_nr, int belt_dir)
8248 {
8249   int belt_dir_nr = (belt_dir == MV_LEFT ? 0 : belt_dir == MV_RIGHT ? 2 : 1);
8250
8251   return getBeltSwitchElementFromBeltNrAndBeltDirNr(belt_nr, belt_dir_nr);
8252 }
8253
8254 boolean swapTiles_EM(boolean is_pre_emc_cave)
8255 {
8256   return is_pre_emc_cave && leveldir_current->use_emc_tiles;
8257 }
8258
8259 boolean getTeamMode_EM(void)
8260 {
8261   return game.team_mode || network_playing;
8262 }
8263
8264 boolean isActivePlayer_EM(int player_nr)
8265 {
8266   return stored_player[player_nr].active;
8267 }
8268
8269 unsigned int InitRND(int seed)
8270 {
8271   if (level.game_engine_type == GAME_ENGINE_TYPE_EM)
8272     return InitEngineRandom_EM(seed);
8273   else if (level.game_engine_type == GAME_ENGINE_TYPE_SP)
8274     return InitEngineRandom_SP(seed);
8275   else if (level.game_engine_type == GAME_ENGINE_TYPE_MM)
8276     return InitEngineRandom_MM(seed);
8277   else
8278     return InitEngineRandom_RND(seed);
8279 }
8280
8281 static struct Mapping_EM_to_RND_object object_mapping[GAME_TILE_MAX];
8282 static struct Mapping_EM_to_RND_player player_mapping[MAX_PLAYERS][PLY_MAX];
8283
8284 static int get_effective_element_EM(int tile, int frame_em)
8285 {
8286   int element             = object_mapping[tile].element_rnd;
8287   int action              = object_mapping[tile].action;
8288   boolean is_backside     = object_mapping[tile].is_backside;
8289   boolean action_removing = (action == ACTION_DIGGING ||
8290                              action == ACTION_SNAPPING ||
8291                              action == ACTION_COLLECTING);
8292
8293   if (frame_em < 7)
8294   {
8295     switch (tile)
8296     {
8297       case Xsplash_e:
8298       case Xsplash_w:
8299         return (frame_em > 5 ? EL_EMPTY : element);
8300
8301       default:
8302         return element;
8303     }
8304   }
8305   else  // frame_em == 7
8306   {
8307     switch (tile)
8308     {
8309       case Xsplash_e:
8310       case Xsplash_w:
8311         return EL_EMPTY;
8312
8313       case Ynut_stone:
8314         return EL_EMERALD;
8315
8316       case Ydiamond_stone:
8317         return EL_ROCK;
8318
8319       case Xdrip_stretch:
8320       case Xdrip_stretchB:
8321       case Ydrip_1_s:
8322       case Ydrip_1_sB:
8323       case Yball_1:
8324       case Xball_2:
8325       case Yball_2:
8326       case Yball_blank:
8327       case Ykey_1_blank:
8328       case Ykey_2_blank:
8329       case Ykey_3_blank:
8330       case Ykey_4_blank:
8331       case Ykey_5_blank:
8332       case Ykey_6_blank:
8333       case Ykey_7_blank:
8334       case Ykey_8_blank:
8335       case Ylenses_blank:
8336       case Ymagnify_blank:
8337       case Ygrass_blank:
8338       case Ydirt_blank:
8339       case Xsand_stonein_1:
8340       case Xsand_stonein_2:
8341       case Xsand_stonein_3:
8342       case Xsand_stonein_4:
8343         return element;
8344
8345       default:
8346         return (is_backside || action_removing ? EL_EMPTY : element);
8347     }
8348   }
8349 }
8350
8351 static boolean check_linear_animation_EM(int tile)
8352 {
8353   switch (tile)
8354   {
8355     case Xsand_stonesand_1:
8356     case Xsand_stonesand_quickout_1:
8357     case Xsand_sandstone_1:
8358     case Xsand_stonein_1:
8359     case Xsand_stoneout_1:
8360     case Xboom_1:
8361     case Xdynamite_1:
8362     case Ybug_w_n:
8363     case Ybug_n_e:
8364     case Ybug_e_s:
8365     case Ybug_s_w:
8366     case Ybug_e_n:
8367     case Ybug_s_e:
8368     case Ybug_w_s:
8369     case Ybug_n_w:
8370     case Ytank_w_n:
8371     case Ytank_n_e:
8372     case Ytank_e_s:
8373     case Ytank_s_w:
8374     case Ytank_e_n:
8375     case Ytank_s_e:
8376     case Ytank_w_s:
8377     case Ytank_n_w:
8378     case Xsplash_e:
8379     case Xsplash_w:
8380     case Ynut_stone:
8381       return TRUE;
8382   }
8383
8384   return FALSE;
8385 }
8386
8387 static void set_crumbled_graphics_EM(struct GraphicInfo_EM *g_em,
8388                                      boolean has_crumbled_graphics,
8389                                      int crumbled, int sync_frame)
8390 {
8391   // if element can be crumbled, but certain action graphics are just empty
8392   // space (like instantly snapping sand to empty space in 1 frame), do not
8393   // treat these empty space graphics as crumbled graphics in EMC engine
8394   if (crumbled == IMG_EMPTY_SPACE)
8395     has_crumbled_graphics = FALSE;
8396
8397   if (has_crumbled_graphics)
8398   {
8399     struct GraphicInfo *g_crumbled = &graphic_info[crumbled];
8400     int frame_crumbled = getAnimationFrame(g_crumbled->anim_frames,
8401                                            g_crumbled->anim_delay,
8402                                            g_crumbled->anim_mode,
8403                                            g_crumbled->anim_start_frame,
8404                                            sync_frame);
8405
8406     getGraphicSource(crumbled, frame_crumbled, &g_em->crumbled_bitmap,
8407                      &g_em->crumbled_src_x, &g_em->crumbled_src_y);
8408
8409     g_em->crumbled_border_size = graphic_info[crumbled].border_size;
8410     g_em->crumbled_tile_size = graphic_info[crumbled].tile_size;
8411
8412     g_em->has_crumbled_graphics = TRUE;
8413   }
8414   else
8415   {
8416     g_em->crumbled_bitmap = NULL;
8417     g_em->crumbled_src_x = 0;
8418     g_em->crumbled_src_y = 0;
8419     g_em->crumbled_border_size = 0;
8420     g_em->crumbled_tile_size = 0;
8421
8422     g_em->has_crumbled_graphics = FALSE;
8423   }
8424 }
8425
8426 #if 0
8427 void ResetGfxAnimation_EM(int x, int y, int tile)
8428 {
8429   GfxFrame[x][y] = 0;
8430 }
8431 #endif
8432
8433 void SetGfxAnimation_EM(struct GraphicInfo_EM *g_em,
8434                         int tile, int frame_em, int x, int y)
8435 {
8436   int action = object_mapping[tile].action;
8437   int direction = object_mapping[tile].direction;
8438   int effective_element = get_effective_element_EM(tile, frame_em);
8439   int graphic = (direction == MV_NONE ?
8440                  el_act2img(effective_element, action) :
8441                  el_act_dir2img(effective_element, action, direction));
8442   struct GraphicInfo *g = &graphic_info[graphic];
8443   int sync_frame;
8444   boolean action_removing = (action == ACTION_DIGGING ||
8445                              action == ACTION_SNAPPING ||
8446                              action == ACTION_COLLECTING);
8447   boolean action_moving   = (action == ACTION_FALLING ||
8448                              action == ACTION_MOVING ||
8449                              action == ACTION_PUSHING ||
8450                              action == ACTION_EATING ||
8451                              action == ACTION_FILLING ||
8452                              action == ACTION_EMPTYING);
8453   boolean action_falling  = (action == ACTION_FALLING ||
8454                              action == ACTION_FILLING ||
8455                              action == ACTION_EMPTYING);
8456
8457   // special case: graphic uses "2nd movement tile" and has defined
8458   // 7 frames for movement animation (or less) => use default graphic
8459   // for last (8th) frame which ends the movement animation
8460   if (g->double_movement && g->anim_frames < 8 && frame_em == 7)
8461   {
8462     action = ACTION_DEFAULT;    // (keep action_* unchanged for now)
8463     graphic = (direction == MV_NONE ?
8464                el_act2img(effective_element, action) :
8465                el_act_dir2img(effective_element, action, direction));
8466
8467     g = &graphic_info[graphic];
8468   }
8469
8470   if ((action_removing || check_linear_animation_EM(tile)) && frame_em == 0)
8471   {
8472     GfxFrame[x][y] = 0;
8473   }
8474   else if (action_moving)
8475   {
8476     boolean is_backside = object_mapping[tile].is_backside;
8477
8478     if (is_backside)
8479     {
8480       int direction = object_mapping[tile].direction;
8481       int move_dir = (action_falling ? MV_DOWN : direction);
8482
8483       GfxFrame[x][y]++;
8484
8485 #if 1
8486       // !!! TEST !!! NEW !!! DOES NOT WORK RIGHT YET !!!
8487       if (g->double_movement && frame_em == 0)
8488         GfxFrame[x][y] = 0;
8489 #endif
8490
8491       if (move_dir == MV_LEFT)
8492         GfxFrame[x - 1][y] = GfxFrame[x][y];
8493       else if (move_dir == MV_RIGHT)
8494         GfxFrame[x + 1][y] = GfxFrame[x][y];
8495       else if (move_dir == MV_UP)
8496         GfxFrame[x][y - 1] = GfxFrame[x][y];
8497       else if (move_dir == MV_DOWN)
8498         GfxFrame[x][y + 1] = GfxFrame[x][y];
8499     }
8500   }
8501   else
8502   {
8503     GfxFrame[x][y]++;
8504
8505     // special case: animation for Xsand_stonesand_quickout_1/2 twice as fast
8506     if (tile == Xsand_stonesand_quickout_1 ||
8507         tile == Xsand_stonesand_quickout_2)
8508       GfxFrame[x][y]++;
8509   }
8510
8511   if (graphic_info[graphic].anim_global_sync)
8512     sync_frame = FrameCounter;
8513   else if (IN_FIELD(x, y, MAX_LEV_FIELDX, MAX_LEV_FIELDY))
8514     sync_frame = GfxFrame[x][y];
8515   else
8516     sync_frame = 0;     // playfield border (pseudo steel)
8517
8518   SetRandomAnimationValue(x, y);
8519
8520   int frame = getAnimationFrame(g->anim_frames,
8521                                 g->anim_delay,
8522                                 g->anim_mode,
8523                                 g->anim_start_frame,
8524                                 sync_frame);
8525
8526   g_em->unique_identifier =
8527     (graphic << 16) | ((frame % 8) << 12) | (g_em->width << 6) | g_em->height;
8528 }
8529
8530 void getGraphicSourceObjectExt_EM(struct GraphicInfo_EM *g_em,
8531                                   int tile, int frame_em, int x, int y)
8532 {
8533   int action = object_mapping[tile].action;
8534   int direction = object_mapping[tile].direction;
8535   boolean is_backside = object_mapping[tile].is_backside;
8536   int effective_element = get_effective_element_EM(tile, frame_em);
8537   int effective_action = action;
8538   int graphic = (direction == MV_NONE ?
8539                  el_act2img(effective_element, effective_action) :
8540                  el_act_dir2img(effective_element, effective_action,
8541                                 direction));
8542   int crumbled = (direction == MV_NONE ?
8543                   el_act2crm(effective_element, effective_action) :
8544                   el_act_dir2crm(effective_element, effective_action,
8545                                  direction));
8546   int base_graphic = el_act2img(effective_element, ACTION_DEFAULT);
8547   int base_crumbled = el_act2crm(effective_element, ACTION_DEFAULT);
8548   boolean has_crumbled_graphics = (base_crumbled != base_graphic);
8549   struct GraphicInfo *g = &graphic_info[graphic];
8550   int sync_frame;
8551
8552   // special case: graphic uses "2nd movement tile" and has defined
8553   // 7 frames for movement animation (or less) => use default graphic
8554   // for last (8th) frame which ends the movement animation
8555   if (g->double_movement && g->anim_frames < 8 && frame_em == 7)
8556   {
8557     effective_action = ACTION_DEFAULT;
8558     graphic = (direction == MV_NONE ?
8559                el_act2img(effective_element, effective_action) :
8560                el_act_dir2img(effective_element, effective_action,
8561                               direction));
8562     crumbled = (direction == MV_NONE ?
8563                 el_act2crm(effective_element, effective_action) :
8564                 el_act_dir2crm(effective_element, effective_action,
8565                                direction));
8566
8567     g = &graphic_info[graphic];
8568   }
8569
8570   if (graphic_info[graphic].anim_global_sync)
8571     sync_frame = FrameCounter;
8572   else if (IN_FIELD(x, y, MAX_LEV_FIELDX, MAX_LEV_FIELDY))
8573     sync_frame = GfxFrame[x][y];
8574   else
8575     sync_frame = 0;     // playfield border (pseudo steel)
8576
8577   SetRandomAnimationValue(x, y);
8578
8579   int frame = getAnimationFrame(g->anim_frames,
8580                                 g->anim_delay,
8581                                 g->anim_mode,
8582                                 g->anim_start_frame,
8583                                 sync_frame);
8584
8585   getGraphicSourceExt(graphic, frame, &g_em->bitmap, &g_em->src_x, &g_em->src_y,
8586                       g->double_movement && is_backside);
8587
8588   // (updating the "crumbled" graphic definitions is probably not really needed,
8589   // as animations for crumbled graphics can't be longer than one EMC cycle)
8590   set_crumbled_graphics_EM(g_em, has_crumbled_graphics, crumbled,
8591                            sync_frame);
8592 }
8593
8594 void getGraphicSourcePlayerExt_EM(struct GraphicInfo_EM *g_em,
8595                                   int player_nr, int anim, int frame_em)
8596 {
8597   int element   = player_mapping[player_nr][anim].element_rnd;
8598   int action    = player_mapping[player_nr][anim].action;
8599   int direction = player_mapping[player_nr][anim].direction;
8600   int graphic = (direction == MV_NONE ?
8601                  el_act2img(element, action) :
8602                  el_act_dir2img(element, action, direction));
8603   struct GraphicInfo *g = &graphic_info[graphic];
8604   int sync_frame;
8605
8606   InitPlayerGfxAnimation(&stored_player[player_nr], action, direction);
8607
8608   stored_player[player_nr].StepFrame = frame_em;
8609
8610   sync_frame = stored_player[player_nr].Frame;
8611
8612   int frame = getAnimationFrame(g->anim_frames,
8613                                 g->anim_delay,
8614                                 g->anim_mode,
8615                                 g->anim_start_frame,
8616                                 sync_frame);
8617
8618   getGraphicSourceExt(graphic, frame, &g_em->bitmap,
8619                       &g_em->src_x, &g_em->src_y, FALSE);
8620 }
8621
8622 void InitGraphicInfo_EM(void)
8623 {
8624   int i, j, p;
8625
8626   // always start with reliable default values
8627   for (i = 0; i < GAME_TILE_MAX; i++)
8628   {
8629     object_mapping[i].element_rnd = EL_UNKNOWN;
8630     object_mapping[i].is_backside = FALSE;
8631     object_mapping[i].action = ACTION_DEFAULT;
8632     object_mapping[i].direction = MV_NONE;
8633   }
8634
8635   // always start with reliable default values
8636   for (p = 0; p < MAX_PLAYERS; p++)
8637   {
8638     for (i = 0; i < PLY_MAX; i++)
8639     {
8640       player_mapping[p][i].element_rnd = EL_UNKNOWN;
8641       player_mapping[p][i].action = ACTION_DEFAULT;
8642       player_mapping[p][i].direction = MV_NONE;
8643     }
8644   }
8645
8646   for (i = 0; em_object_mapping_list[i].element_em != -1; i++)
8647   {
8648     int e = em_object_mapping_list[i].element_em;
8649
8650     object_mapping[e].element_rnd = em_object_mapping_list[i].element_rnd;
8651     object_mapping[e].is_backside = em_object_mapping_list[i].is_backside;
8652
8653     if (em_object_mapping_list[i].action != -1)
8654       object_mapping[e].action = em_object_mapping_list[i].action;
8655
8656     if (em_object_mapping_list[i].direction != -1)
8657       object_mapping[e].direction =
8658         MV_DIR_FROM_BIT(em_object_mapping_list[i].direction);
8659   }
8660
8661   for (i = 0; em_player_mapping_list[i].action_em != -1; i++)
8662   {
8663     int a = em_player_mapping_list[i].action_em;
8664     int p = em_player_mapping_list[i].player_nr;
8665
8666     player_mapping[p][a].element_rnd = em_player_mapping_list[i].element_rnd;
8667
8668     if (em_player_mapping_list[i].action != -1)
8669       player_mapping[p][a].action = em_player_mapping_list[i].action;
8670
8671     if (em_player_mapping_list[i].direction != -1)
8672       player_mapping[p][a].direction =
8673         MV_DIR_FROM_BIT(em_player_mapping_list[i].direction);
8674   }
8675
8676   for (i = 0; i < GAME_TILE_MAX; i++)
8677   {
8678     int element = object_mapping[i].element_rnd;
8679     int action = object_mapping[i].action;
8680     int direction = object_mapping[i].direction;
8681     boolean is_backside = object_mapping[i].is_backside;
8682     boolean action_exploding = ((action == ACTION_EXPLODING ||
8683                                  action == ACTION_SMASHED_BY_ROCK ||
8684                                  action == ACTION_SMASHED_BY_SPRING) &&
8685                                 element != EL_DIAMOND);
8686     boolean action_active = (action == ACTION_ACTIVE);
8687     boolean action_other = (action == ACTION_OTHER);
8688
8689     for (j = 0; j < 8; j++)
8690     {
8691       int effective_element = get_effective_element_EM(i, j);
8692       int effective_action = (j < 7 ? action :
8693                               i == Xdrip_stretch ? action :
8694                               i == Xdrip_stretchB ? action :
8695                               i == Ydrip_1_s ? action :
8696                               i == Ydrip_1_sB ? action :
8697                               i == Yball_1 ? action :
8698                               i == Xball_2 ? action :
8699                               i == Yball_2 ? action :
8700                               i == Yball_blank ? action :
8701                               i == Ykey_1_blank ? action :
8702                               i == Ykey_2_blank ? action :
8703                               i == Ykey_3_blank ? action :
8704                               i == Ykey_4_blank ? action :
8705                               i == Ykey_5_blank ? action :
8706                               i == Ykey_6_blank ? action :
8707                               i == Ykey_7_blank ? action :
8708                               i == Ykey_8_blank ? action :
8709                               i == Ylenses_blank ? action :
8710                               i == Ymagnify_blank ? action :
8711                               i == Ygrass_blank ? action :
8712                               i == Ydirt_blank ? action :
8713                               i == Xsand_stonein_1 ? action :
8714                               i == Xsand_stonein_2 ? action :
8715                               i == Xsand_stonein_3 ? action :
8716                               i == Xsand_stonein_4 ? action :
8717                               i == Xsand_stoneout_1 ? action :
8718                               i == Xsand_stoneout_2 ? action :
8719                               i == Xboom_android ? ACTION_EXPLODING :
8720                               action_exploding ? ACTION_EXPLODING :
8721                               action_active ? action :
8722                               action_other ? action :
8723                               ACTION_DEFAULT);
8724       int graphic = (el_act_dir2img(effective_element, effective_action,
8725                                     direction));
8726       int crumbled = (el_act_dir2crm(effective_element, effective_action,
8727                                      direction));
8728       int base_graphic = el_act2img(effective_element, ACTION_DEFAULT);
8729       int base_crumbled = el_act2crm(effective_element, ACTION_DEFAULT);
8730       boolean has_action_graphics = (graphic != base_graphic);
8731       boolean has_crumbled_graphics = (base_crumbled != base_graphic);
8732       struct GraphicInfo *g = &graphic_info[graphic];
8733       struct GraphicInfo_EM *g_em = &graphic_info_em_object[i][j];
8734       Bitmap *src_bitmap;
8735       int src_x, src_y;
8736       // ensure to get symmetric 3-frame, 2-delay animations as used in EM
8737       boolean special_animation = (action != ACTION_DEFAULT &&
8738                                    g->anim_frames == 3 &&
8739                                    g->anim_delay == 2 &&
8740                                    g->anim_mode & ANIM_LINEAR);
8741       int sync_frame = (i == Xdrip_stretch ? 7 :
8742                         i == Xdrip_stretchB ? 7 :
8743                         i == Ydrip_2_s ? j + 8 :
8744                         i == Ydrip_2_sB ? j + 8 :
8745                         i == Xacid_1 ? 0 :
8746                         i == Xacid_2 ? 10 :
8747                         i == Xacid_3 ? 20 :
8748                         i == Xacid_4 ? 30 :
8749                         i == Xacid_5 ? 40 :
8750                         i == Xacid_6 ? 50 :
8751                         i == Xacid_7 ? 60 :
8752                         i == Xacid_8 ? 70 :
8753                         i == Xfake_acid_1 ? 0 :
8754                         i == Xfake_acid_2 ? 10 :
8755                         i == Xfake_acid_3 ? 20 :
8756                         i == Xfake_acid_4 ? 30 :
8757                         i == Xfake_acid_5 ? 40 :
8758                         i == Xfake_acid_6 ? 50 :
8759                         i == Xfake_acid_7 ? 60 :
8760                         i == Xfake_acid_8 ? 70 :
8761                         i == Xball_2 ? 7 :
8762                         i == Yball_2 ? j + 8 :
8763                         i == Yball_blank ? j + 1 :
8764                         i == Ykey_1_blank ? j + 1 :
8765                         i == Ykey_2_blank ? j + 1 :
8766                         i == Ykey_3_blank ? j + 1 :
8767                         i == Ykey_4_blank ? j + 1 :
8768                         i == Ykey_5_blank ? j + 1 :
8769                         i == Ykey_6_blank ? j + 1 :
8770                         i == Ykey_7_blank ? j + 1 :
8771                         i == Ykey_8_blank ? j + 1 :
8772                         i == Ylenses_blank ? j + 1 :
8773                         i == Ymagnify_blank ? j + 1 :
8774                         i == Ygrass_blank ? j + 1 :
8775                         i == Ydirt_blank ? j + 1 :
8776                         i == Xamoeba_1 ? 0 :
8777                         i == Xamoeba_2 ? 1 :
8778                         i == Xamoeba_3 ? 2 :
8779                         i == Xamoeba_4 ? 3 :
8780                         i == Xamoeba_5 ? 0 :
8781                         i == Xamoeba_6 ? 1 :
8782                         i == Xamoeba_7 ? 2 :
8783                         i == Xamoeba_8 ? 3 :
8784                         i == Xexit_2 ? j + 8 :
8785                         i == Xexit_3 ? j + 16 :
8786                         i == Xdynamite_1 ? 0 :
8787                         i == Xdynamite_2 ? 8 :
8788                         i == Xdynamite_3 ? 16 :
8789                         i == Xdynamite_4 ? 24 :
8790                         i == Xsand_stonein_1 ? j + 1 :
8791                         i == Xsand_stonein_2 ? j + 9 :
8792                         i == Xsand_stonein_3 ? j + 17 :
8793                         i == Xsand_stonein_4 ? j + 25 :
8794                         i == Xsand_stoneout_1 && j == 0 ? 0 :
8795                         i == Xsand_stoneout_1 && j == 1 ? 0 :
8796                         i == Xsand_stoneout_1 && j == 2 ? 1 :
8797                         i == Xsand_stoneout_1 && j == 3 ? 2 :
8798                         i == Xsand_stoneout_1 && j == 4 ? 2 :
8799                         i == Xsand_stoneout_1 && j == 5 ? 3 :
8800                         i == Xsand_stoneout_1 && j == 6 ? 4 :
8801                         i == Xsand_stoneout_1 && j == 7 ? 4 :
8802                         i == Xsand_stoneout_2 && j == 0 ? 5 :
8803                         i == Xsand_stoneout_2 && j == 1 ? 6 :
8804                         i == Xsand_stoneout_2 && j == 2 ? 7 :
8805                         i == Xsand_stoneout_2 && j == 3 ? 8 :
8806                         i == Xsand_stoneout_2 && j == 4 ? 9 :
8807                         i == Xsand_stoneout_2 && j == 5 ? 11 :
8808                         i == Xsand_stoneout_2 && j == 6 ? 13 :
8809                         i == Xsand_stoneout_2 && j == 7 ? 15 :
8810                         i == Xboom_bug && j == 1 ? 2 :
8811                         i == Xboom_bug && j == 2 ? 2 :
8812                         i == Xboom_bug && j == 3 ? 4 :
8813                         i == Xboom_bug && j == 4 ? 4 :
8814                         i == Xboom_bug && j == 5 ? 2 :
8815                         i == Xboom_bug && j == 6 ? 2 :
8816                         i == Xboom_bug && j == 7 ? 0 :
8817                         i == Xboom_tank && j == 1 ? 2 :
8818                         i == Xboom_tank && j == 2 ? 2 :
8819                         i == Xboom_tank && j == 3 ? 4 :
8820                         i == Xboom_tank && j == 4 ? 4 :
8821                         i == Xboom_tank && j == 5 ? 2 :
8822                         i == Xboom_tank && j == 6 ? 2 :
8823                         i == Xboom_tank && j == 7 ? 0 :
8824                         i == Xboom_android && j == 7 ? 6 :
8825                         i == Xboom_1 && j == 1 ? 2 :
8826                         i == Xboom_1 && j == 2 ? 2 :
8827                         i == Xboom_1 && j == 3 ? 4 :
8828                         i == Xboom_1 && j == 4 ? 4 :
8829                         i == Xboom_1 && j == 5 ? 6 :
8830                         i == Xboom_1 && j == 6 ? 6 :
8831                         i == Xboom_1 && j == 7 ? 8 :
8832                         i == Xboom_2 && j == 0 ? 8 :
8833                         i == Xboom_2 && j == 1 ? 8 :
8834                         i == Xboom_2 && j == 2 ? 10 :
8835                         i == Xboom_2 && j == 3 ? 10 :
8836                         i == Xboom_2 && j == 4 ? 10 :
8837                         i == Xboom_2 && j == 5 ? 12 :
8838                         i == Xboom_2 && j == 6 ? 12 :
8839                         i == Xboom_2 && j == 7 ? 12 :
8840                         special_animation && j == 4 ? 3 :
8841                         effective_action != action ? 0 :
8842                         j);
8843       int frame = getAnimationFrame(g->anim_frames,
8844                                     g->anim_delay,
8845                                     g->anim_mode,
8846                                     g->anim_start_frame,
8847                                     sync_frame);
8848
8849       getGraphicSourceExt(graphic, frame, &src_bitmap, &src_x, &src_y,
8850                           g->double_movement && is_backside);
8851
8852       g_em->bitmap = src_bitmap;
8853       g_em->src_x = src_x;
8854       g_em->src_y = src_y;
8855       g_em->src_offset_x = 0;
8856       g_em->src_offset_y = 0;
8857       g_em->dst_offset_x = 0;
8858       g_em->dst_offset_y = 0;
8859       g_em->width  = TILEX;
8860       g_em->height = TILEY;
8861
8862       g_em->preserve_background = FALSE;
8863
8864       set_crumbled_graphics_EM(g_em, has_crumbled_graphics, crumbled,
8865                                sync_frame);
8866
8867       if ((!g->double_movement && (effective_action == ACTION_FALLING ||
8868                                    effective_action == ACTION_MOVING  ||
8869                                    effective_action == ACTION_PUSHING ||
8870                                    effective_action == ACTION_EATING)) ||
8871           (!has_action_graphics && (effective_action == ACTION_FILLING ||
8872                                     effective_action == ACTION_EMPTYING)))
8873       {
8874         int move_dir =
8875           (effective_action == ACTION_FALLING ||
8876            effective_action == ACTION_FILLING ||
8877            effective_action == ACTION_EMPTYING ? MV_DOWN : direction);
8878         int dx = (move_dir == MV_LEFT ? -1 : move_dir == MV_RIGHT ? 1 : 0);
8879         int dy = (move_dir == MV_UP   ? -1 : move_dir == MV_DOWN  ? 1 : 0);
8880         int num_steps = (i == Ydrip_1_s  ? 16 :
8881                          i == Ydrip_1_sB ? 16 :
8882                          i == Ydrip_2_s  ? 16 :
8883                          i == Ydrip_2_sB ? 16 :
8884                          i == Xsand_stonein_1 ? 32 :
8885                          i == Xsand_stonein_2 ? 32 :
8886                          i == Xsand_stonein_3 ? 32 :
8887                          i == Xsand_stonein_4 ? 32 :
8888                          i == Xsand_stoneout_1 ? 16 :
8889                          i == Xsand_stoneout_2 ? 16 : 8);
8890         int cx = ABS(dx) * (TILEX / num_steps);
8891         int cy = ABS(dy) * (TILEY / num_steps);
8892         int step_frame = (i == Ydrip_2_s        ? j + 8 :
8893                           i == Ydrip_2_sB       ? j + 8 :
8894                           i == Xsand_stonein_2  ? j + 8 :
8895                           i == Xsand_stonein_3  ? j + 16 :
8896                           i == Xsand_stonein_4  ? j + 24 :
8897                           i == Xsand_stoneout_2 ? j + 8 : j) + 1;
8898         int step = (is_backside ? step_frame : num_steps - step_frame);
8899
8900         if (is_backside)        // tile where movement starts
8901         {
8902           if (dx < 0 || dy < 0)
8903           {
8904             g_em->src_offset_x = cx * step;
8905             g_em->src_offset_y = cy * step;
8906           }
8907           else
8908           {
8909             g_em->dst_offset_x = cx * step;
8910             g_em->dst_offset_y = cy * step;
8911           }
8912         }
8913         else                    // tile where movement ends
8914         {
8915           if (dx < 0 || dy < 0)
8916           {
8917             g_em->dst_offset_x = cx * step;
8918             g_em->dst_offset_y = cy * step;
8919           }
8920           else
8921           {
8922             g_em->src_offset_x = cx * step;
8923             g_em->src_offset_y = cy * step;
8924           }
8925         }
8926
8927         g_em->width  = TILEX - cx * step;
8928         g_em->height = TILEY - cy * step;
8929       }
8930
8931       // create unique graphic identifier to decide if tile must be redrawn
8932       /* bit 31 - 16 (16 bit): EM style graphic
8933          bit 15 - 12 ( 4 bit): EM style frame
8934          bit 11 -  6 ( 6 bit): graphic width
8935          bit  5 -  0 ( 6 bit): graphic height */
8936       g_em->unique_identifier =
8937         (graphic << 16) | (frame << 12) | (g_em->width << 6) | g_em->height;
8938     }
8939   }
8940
8941   for (i = 0; i < GAME_TILE_MAX; i++)
8942   {
8943     for (j = 0; j < 8; j++)
8944     {
8945       int element = object_mapping[i].element_rnd;
8946       int action = object_mapping[i].action;
8947       int direction = object_mapping[i].direction;
8948       boolean is_backside = object_mapping[i].is_backside;
8949       int graphic_action  = el_act_dir2img(element, action, direction);
8950       int graphic_default = el_act_dir2img(element, ACTION_DEFAULT, direction);
8951
8952       if ((action == ACTION_SMASHED_BY_ROCK ||
8953            action == ACTION_SMASHED_BY_SPRING ||
8954            action == ACTION_EATING) &&
8955           graphic_action == graphic_default)
8956       {
8957         int e = (action == ACTION_SMASHED_BY_ROCK   ? Ystone_s  :
8958                  action == ACTION_SMASHED_BY_SPRING ? Yspring_s :
8959                  direction == MV_LEFT  ? (is_backside? Yspring_wB: Yspring_w) :
8960                  direction == MV_RIGHT ? (is_backside? Yspring_eB: Yspring_e) :
8961                  Xspring);
8962
8963         // no separate animation for "smashed by rock" -- use rock instead
8964         struct GraphicInfo_EM *g_em = &graphic_info_em_object[i][j];
8965         struct GraphicInfo_EM *g_xx = &graphic_info_em_object[e][j];
8966
8967         g_em->bitmap            = g_xx->bitmap;
8968         g_em->src_x             = g_xx->src_x;
8969         g_em->src_y             = g_xx->src_y;
8970         g_em->src_offset_x      = g_xx->src_offset_x;
8971         g_em->src_offset_y      = g_xx->src_offset_y;
8972         g_em->dst_offset_x      = g_xx->dst_offset_x;
8973         g_em->dst_offset_y      = g_xx->dst_offset_y;
8974         g_em->width             = g_xx->width;
8975         g_em->height            = g_xx->height;
8976         g_em->unique_identifier = g_xx->unique_identifier;
8977
8978         if (!is_backside)
8979           g_em->preserve_background = TRUE;
8980       }
8981     }
8982   }
8983
8984   for (p = 0; p < MAX_PLAYERS; p++)
8985   {
8986     for (i = 0; i < PLY_MAX; i++)
8987     {
8988       int element = player_mapping[p][i].element_rnd;
8989       int action = player_mapping[p][i].action;
8990       int direction = player_mapping[p][i].direction;
8991
8992       for (j = 0; j < 8; j++)
8993       {
8994         int effective_element = element;
8995         int effective_action = action;
8996         int graphic = (direction == MV_NONE ?
8997                        el_act2img(effective_element, effective_action) :
8998                        el_act_dir2img(effective_element, effective_action,
8999                                       direction));
9000         struct GraphicInfo *g = &graphic_info[graphic];
9001         struct GraphicInfo_EM *g_em = &graphic_info_em_player[p][i][j];
9002         Bitmap *src_bitmap;
9003         int src_x, src_y;
9004         int sync_frame = j;
9005         int frame = getAnimationFrame(g->anim_frames,
9006                                       g->anim_delay,
9007                                       g->anim_mode,
9008                                       g->anim_start_frame,
9009                                       sync_frame);
9010
9011         getGraphicSourceExt(graphic, frame, &src_bitmap, &src_x, &src_y, FALSE);
9012
9013         g_em->bitmap = src_bitmap;
9014         g_em->src_x = src_x;
9015         g_em->src_y = src_y;
9016         g_em->src_offset_x = 0;
9017         g_em->src_offset_y = 0;
9018         g_em->dst_offset_x = 0;
9019         g_em->dst_offset_y = 0;
9020         g_em->width  = TILEX;
9021         g_em->height = TILEY;
9022       }
9023     }
9024   }
9025 }
9026
9027 static void CheckSaveEngineSnapshot_EM(byte action[MAX_PLAYERS], int frame,
9028                                        boolean any_player_moving,
9029                                        boolean any_player_snapping,
9030                                        boolean any_player_dropping)
9031 {
9032   if (frame == 7 && !any_player_dropping)
9033   {
9034     if (!local_player->was_waiting)
9035     {
9036       if (!CheckSaveEngineSnapshotToList())
9037         return;
9038
9039       local_player->was_waiting = TRUE;
9040     }
9041   }
9042   else if (any_player_moving || any_player_snapping || any_player_dropping)
9043   {
9044     local_player->was_waiting = FALSE;
9045   }
9046 }
9047
9048 static void CheckSaveEngineSnapshot_SP(boolean murphy_is_waiting,
9049                                        boolean murphy_is_dropping)
9050 {
9051   if (murphy_is_waiting)
9052   {
9053     if (!local_player->was_waiting)
9054     {
9055       if (!CheckSaveEngineSnapshotToList())
9056         return;
9057
9058       local_player->was_waiting = TRUE;
9059     }
9060   }
9061   else
9062   {
9063     local_player->was_waiting = FALSE;
9064   }
9065 }
9066
9067 static void CheckSaveEngineSnapshot_MM(boolean element_clicked,
9068                                        boolean button_released)
9069 {
9070   if (button_released)
9071   {
9072     if (game.snapshot.mode == SNAPSHOT_MODE_EVERY_MOVE)
9073       CheckSaveEngineSnapshotToList();
9074   }
9075   else if (element_clicked)
9076   {
9077     if (game.snapshot.mode != SNAPSHOT_MODE_EVERY_MOVE)
9078       CheckSaveEngineSnapshotToList();
9079
9080     game.snapshot.changed_action = TRUE;
9081   }
9082 }
9083
9084 boolean CheckSingleStepMode_EM(byte action[MAX_PLAYERS], int frame,
9085                                boolean any_player_moving,
9086                                boolean any_player_snapping,
9087                                boolean any_player_dropping)
9088 {
9089   if (tape.single_step && tape.recording && !tape.pausing)
9090     if (frame == 7 && !any_player_dropping)
9091       TapeTogglePause(TAPE_TOGGLE_AUTOMATIC);
9092
9093   CheckSaveEngineSnapshot_EM(action, frame, any_player_moving,
9094                              any_player_snapping, any_player_dropping);
9095
9096   return tape.pausing;
9097 }
9098
9099 void CheckSingleStepMode_SP(boolean murphy_is_waiting,
9100                             boolean murphy_is_dropping)
9101 {
9102   boolean murphy_starts_dropping = FALSE;
9103   int i;
9104
9105   for (i = 0; i < MAX_PLAYERS; i++)
9106     if (stored_player[i].force_dropping)
9107       murphy_starts_dropping = TRUE;
9108
9109   if (tape.single_step && tape.recording && !tape.pausing)
9110     if (murphy_is_waiting && !murphy_starts_dropping)
9111       TapeTogglePause(TAPE_TOGGLE_AUTOMATIC);
9112
9113   CheckSaveEngineSnapshot_SP(murphy_is_waiting, murphy_is_dropping);
9114 }
9115
9116 void CheckSingleStepMode_MM(boolean element_clicked,
9117                             boolean button_released)
9118 {
9119   if (tape.single_step && tape.recording && !tape.pausing)
9120     if (button_released)
9121       TapeTogglePause(TAPE_TOGGLE_AUTOMATIC);
9122
9123   CheckSaveEngineSnapshot_MM(element_clicked, button_released);
9124 }
9125
9126 void getGraphicSource_SP(struct GraphicInfo_SP *g_sp,
9127                          int graphic, int sync_frame, int x, int y)
9128 {
9129   int frame = getGraphicAnimationFrame(graphic, sync_frame);
9130
9131   getGraphicSource(graphic, frame, &g_sp->bitmap, &g_sp->src_x, &g_sp->src_y);
9132 }
9133
9134 boolean isNextAnimationFrame_SP(int graphic, int sync_frame)
9135 {
9136   return (IS_NEXT_FRAME(sync_frame, graphic));
9137 }
9138
9139 int getGraphicInfo_Delay(int graphic)
9140 {
9141   return graphic_info[graphic].anim_delay;
9142 }
9143
9144 void PlayMenuSoundExt(int sound)
9145 {
9146   if (sound == SND_UNDEFINED)
9147     return;
9148
9149   if ((!setup.sound_simple && !IS_LOOP_SOUND(sound)) ||
9150       (!setup.sound_loops && IS_LOOP_SOUND(sound)))
9151     return;
9152
9153   if (IS_LOOP_SOUND(sound))
9154     PlaySoundLoop(sound);
9155   else
9156     PlaySound(sound);
9157 }
9158
9159 void PlayMenuSound(void)
9160 {
9161   PlayMenuSoundExt(menu.sound[game_status]);
9162 }
9163
9164 void PlayMenuSoundStereo(int sound, int stereo_position)
9165 {
9166   if (sound == SND_UNDEFINED)
9167     return;
9168
9169   if ((!setup.sound_simple && !IS_LOOP_SOUND(sound)) ||
9170       (!setup.sound_loops && IS_LOOP_SOUND(sound)))
9171     return;
9172
9173   if (IS_LOOP_SOUND(sound))
9174     PlaySoundExt(sound, SOUND_MAX_VOLUME, stereo_position, SND_CTRL_PLAY_LOOP);
9175   else
9176     PlaySoundStereo(sound, stereo_position);
9177 }
9178
9179 void PlayMenuSoundIfLoopExt(int sound)
9180 {
9181   if (sound == SND_UNDEFINED)
9182     return;
9183
9184   if ((!setup.sound_simple && !IS_LOOP_SOUND(sound)) ||
9185       (!setup.sound_loops && IS_LOOP_SOUND(sound)))
9186     return;
9187
9188   if (IS_LOOP_SOUND(sound))
9189     PlaySoundLoop(sound);
9190 }
9191
9192 void PlayMenuSoundIfLoop(void)
9193 {
9194   PlayMenuSoundIfLoopExt(menu.sound[game_status]);
9195 }
9196
9197 void PlayMenuMusicExt(int music)
9198 {
9199   if (music == MUS_UNDEFINED)
9200     return;
9201
9202   if (!setup.sound_music)
9203     return;
9204
9205   if (IS_LOOP_MUSIC(music))
9206     PlayMusicLoop(music);
9207   else
9208     PlayMusic(music);
9209 }
9210
9211 void PlayMenuMusic(void)
9212 {
9213   char *curr_music = getCurrentlyPlayingMusicFilename();
9214   char *next_music = getMusicInfoEntryFilename(menu.music[game_status]);
9215
9216   if (!strEqual(curr_music, next_music))
9217     PlayMenuMusicExt(menu.music[game_status]);
9218 }
9219
9220 void PlayMenuSoundsAndMusic(void)
9221 {
9222   PlayMenuSound();
9223   PlayMenuMusic();
9224 }
9225
9226 static void FadeMenuSounds(void)
9227 {
9228   FadeSounds();
9229 }
9230
9231 static void FadeMenuMusic(void)
9232 {
9233   char *curr_music = getCurrentlyPlayingMusicFilename();
9234   char *next_music = getMusicInfoEntryFilename(menu.music[game_status]);
9235
9236   if (!strEqual(curr_music, next_music))
9237     FadeMusic();
9238 }
9239
9240 void FadeMenuSoundsAndMusic(void)
9241 {
9242   FadeMenuSounds();
9243   FadeMenuMusic();
9244 }
9245
9246 void PlaySoundActivating(void)
9247 {
9248 #if 0
9249   PlaySound(SND_MENU_ITEM_ACTIVATING);
9250 #endif
9251 }
9252
9253 void PlaySoundSelecting(void)
9254 {
9255 #if 0
9256   PlaySound(SND_MENU_ITEM_SELECTING);
9257 #endif
9258 }
9259
9260 void ToggleFullscreenIfNeeded(void)
9261 {
9262   // if setup and video fullscreen state are already matching, nothing do do
9263   if (setup.fullscreen == video.fullscreen_enabled ||
9264       !video.fullscreen_available)
9265     return;
9266
9267   SDLSetWindowFullscreen(setup.fullscreen);
9268
9269   // set setup value according to successfully changed fullscreen mode
9270   setup.fullscreen = video.fullscreen_enabled;
9271 }
9272
9273 void ChangeWindowScalingIfNeeded(void)
9274 {
9275   // if setup and video window scaling are already matching, nothing do do
9276   if (setup.window_scaling_percent == video.window_scaling_percent ||
9277       video.fullscreen_enabled)
9278     return;
9279
9280   SDLSetWindowScaling(setup.window_scaling_percent);
9281
9282   // set setup value according to successfully changed window scaling
9283   setup.window_scaling_percent = video.window_scaling_percent;
9284 }
9285
9286 void ChangeVsyncModeIfNeeded(void)
9287 {
9288   int setup_vsync_mode = VSYNC_MODE_STR_TO_INT(setup.vsync_mode);
9289   int video_vsync_mode = video.vsync_mode;
9290
9291   // if setup and video vsync mode are already matching, nothing do do
9292   if (setup_vsync_mode == video_vsync_mode)
9293     return;
9294
9295   // if renderer is using OpenGL, vsync mode can directly be changed
9296   SDLSetScreenVsyncMode(setup.vsync_mode);
9297
9298   // if vsync mode unchanged, try re-creating renderer to set vsync mode
9299   if (video.vsync_mode == video_vsync_mode)
9300   {
9301     Bitmap *tmp_backbuffer = CreateBitmap(WIN_XSIZE, WIN_YSIZE, DEFAULT_DEPTH);
9302
9303     // save backbuffer content which gets lost when re-creating screen
9304     BlitBitmap(backbuffer, tmp_backbuffer, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
9305
9306     // force re-creating screen and renderer to set new vsync mode
9307     video.fullscreen_enabled = !setup.fullscreen;
9308
9309     // when creating new renderer, destroy textures linked to old renderer
9310     FreeAllImageTextures();     // needs old renderer to free the textures
9311
9312     // re-create screen and renderer (including change of vsync mode)
9313     ChangeVideoModeIfNeeded(setup.fullscreen);
9314
9315     // set setup value according to successfully changed fullscreen mode
9316     setup.fullscreen = video.fullscreen_enabled;
9317
9318     // restore backbuffer content from temporary backbuffer backup bitmap
9319     BlitBitmap(tmp_backbuffer, backbuffer, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
9320     FreeBitmap(tmp_backbuffer);
9321
9322     // update visible window/screen
9323     BlitBitmap(backbuffer, window, 0, 0, WIN_XSIZE, WIN_YSIZE, 0, 0);
9324
9325     // when changing vsync mode, re-create textures for new renderer
9326     InitImageTextures();
9327   }
9328
9329   // set setup value according to successfully changed vsync mode
9330   setup.vsync_mode = VSYNC_MODE_INT_TO_STR(video.vsync_mode);
9331 }
9332
9333 static void JoinRectangles(int *x, int *y, int *width, int *height,
9334                            int x2, int y2, int width2, int height2)
9335 {
9336   // do not join with "off-screen" rectangle
9337   if (x2 == -1 || y2 == -1)
9338     return;
9339
9340   *x = MIN(*x, x2);
9341   *y = MIN(*y, y2);
9342   *width = MAX(*width, width2);
9343   *height = MAX(*height, height2);
9344 }
9345
9346 void SetAnimStatus(int anim_status_new)
9347 {
9348   if (anim_status_new == GAME_MODE_MAIN)
9349     anim_status_new = GAME_MODE_PSEUDO_MAINONLY;
9350   else if (anim_status_new == GAME_MODE_SCORES)
9351     anim_status_new = GAME_MODE_PSEUDO_SCORESOLD;
9352
9353   global.anim_status_next = anim_status_new;
9354
9355   // directly set screen modes that are entered without fading
9356   if ((global.anim_status      == GAME_MODE_PSEUDO_MAINONLY &&
9357        global.anim_status_next == GAME_MODE_PSEUDO_TYPENAME) ||
9358       (global.anim_status      == GAME_MODE_PSEUDO_TYPENAME &&
9359        global.anim_status_next == GAME_MODE_PSEUDO_MAINONLY))
9360     global.anim_status = global.anim_status_next;
9361 }
9362
9363 void SetGameStatus(int game_status_new)
9364 {
9365   if (game_status_new != game_status)
9366     game_status_last_screen = game_status;
9367
9368   game_status = game_status_new;
9369
9370   SetAnimStatus(game_status_new);
9371 }
9372
9373 void SetFontStatus(int game_status_new)
9374 {
9375   static int last_game_status = -1;
9376
9377   if (game_status_new != -1)
9378   {
9379     // set game status for font use after storing last game status
9380     last_game_status = game_status;
9381     game_status = game_status_new;
9382   }
9383   else
9384   {
9385     // reset game status after font use from last stored game status
9386     game_status = last_game_status;
9387   }
9388 }
9389
9390 void ResetFontStatus(void)
9391 {
9392   SetFontStatus(-1);
9393 }
9394
9395 void SetLevelSetInfo(char *identifier, int level_nr)
9396 {
9397   setString(&levelset.identifier, identifier);
9398
9399   levelset.level_nr = level_nr;
9400 }
9401
9402 boolean CheckIfAllViewportsHaveChanged(void)
9403 {
9404   // if game status has not changed, viewports have not changed either
9405   if (game_status == game_status_last)
9406     return FALSE;
9407
9408   // check if all viewports have changed with current game status
9409
9410   struct RectWithBorder *vp_playfield = &viewport.playfield[game_status];
9411   struct RectWithBorder *vp_door_1    = &viewport.door_1[game_status];
9412   struct RectWithBorder *vp_door_2    = &viewport.door_2[game_status];
9413   int new_real_sx       = vp_playfield->x;
9414   int new_real_sy       = vp_playfield->y;
9415   int new_full_sxsize   = vp_playfield->width;
9416   int new_full_sysize   = vp_playfield->height;
9417   int new_dx            = vp_door_1->x;
9418   int new_dy            = vp_door_1->y;
9419   int new_dxsize        = vp_door_1->width;
9420   int new_dysize        = vp_door_1->height;
9421   int new_vx            = vp_door_2->x;
9422   int new_vy            = vp_door_2->y;
9423   int new_vxsize        = vp_door_2->width;
9424   int new_vysize        = vp_door_2->height;
9425
9426   boolean playfield_viewport_has_changed =
9427     (new_real_sx != REAL_SX ||
9428      new_real_sy != REAL_SY ||
9429      new_full_sxsize != FULL_SXSIZE ||
9430      new_full_sysize != FULL_SYSIZE);
9431
9432   boolean door_1_viewport_has_changed =
9433     (new_dx != DX ||
9434      new_dy != DY ||
9435      new_dxsize != DXSIZE ||
9436      new_dysize != DYSIZE);
9437
9438   boolean door_2_viewport_has_changed =
9439     (new_vx != VX ||
9440      new_vy != VY ||
9441      new_vxsize != VXSIZE ||
9442      new_vysize != VYSIZE ||
9443      game_status_last == GAME_MODE_EDITOR);
9444
9445   return (playfield_viewport_has_changed &&
9446           door_1_viewport_has_changed &&
9447           door_2_viewport_has_changed);
9448 }
9449
9450 boolean CheckFadeAll(void)
9451 {
9452   return (CheckIfGlobalBorderHasChanged() ||
9453           CheckIfAllViewportsHaveChanged());
9454 }
9455
9456 void ChangeViewportPropertiesIfNeeded(void)
9457 {
9458   boolean use_mini_tilesize = (level.game_engine_type == GAME_ENGINE_TYPE_MM ?
9459                                FALSE : setup.small_game_graphics);
9460   int gfx_game_mode = game_status;
9461   int gfx_game_mode2 = (game_status == GAME_MODE_EDITOR ? GAME_MODE_DEFAULT :
9462                         game_status);
9463   struct RectWithBorder *vp_window    = &viewport.window[gfx_game_mode];
9464   struct RectWithBorder *vp_playfield = &viewport.playfield[gfx_game_mode];
9465   struct RectWithBorder *vp_door_1    = &viewport.door_1[gfx_game_mode];
9466   struct RectWithBorder *vp_door_2    = &viewport.door_2[gfx_game_mode2];
9467   struct RectWithBorder *vp_door_3    = &viewport.door_2[GAME_MODE_EDITOR];
9468   int new_win_xsize     = vp_window->width;
9469   int new_win_ysize     = vp_window->height;
9470   int border_left       = vp_playfield->border_left;
9471   int border_right      = vp_playfield->border_right;
9472   int border_top        = vp_playfield->border_top;
9473   int border_bottom     = vp_playfield->border_bottom;
9474   int new_sx            = vp_playfield->x      + border_left;
9475   int new_sy            = vp_playfield->y      + border_top;
9476   int new_sxsize        = vp_playfield->width  - border_left - border_right;
9477   int new_sysize        = vp_playfield->height - border_top  - border_bottom;
9478   int new_real_sx       = vp_playfield->x;
9479   int new_real_sy       = vp_playfield->y;
9480   int new_full_sxsize   = vp_playfield->width;
9481   int new_full_sysize   = vp_playfield->height;
9482   int new_dx            = vp_door_1->x;
9483   int new_dy            = vp_door_1->y;
9484   int new_dxsize        = vp_door_1->width;
9485   int new_dysize        = vp_door_1->height;
9486   int new_vx            = vp_door_2->x;
9487   int new_vy            = vp_door_2->y;
9488   int new_vxsize        = vp_door_2->width;
9489   int new_vysize        = vp_door_2->height;
9490   int new_ex            = vp_door_3->x;
9491   int new_ey            = vp_door_3->y;
9492   int new_exsize        = vp_door_3->width;
9493   int new_eysize        = vp_door_3->height;
9494   int new_tilesize_var = (use_mini_tilesize ? MINI_TILESIZE : game.tile_size);
9495   int tilesize = (gfx_game_mode == GAME_MODE_PLAYING ? new_tilesize_var :
9496                   gfx_game_mode == GAME_MODE_EDITOR ? MINI_TILESIZE : TILESIZE);
9497   int new_scr_fieldx = new_sxsize / tilesize;
9498   int new_scr_fieldy = new_sysize / tilesize;
9499   int new_scr_fieldx_buffers = new_sxsize / new_tilesize_var;
9500   int new_scr_fieldy_buffers = new_sysize / new_tilesize_var;
9501   boolean init_gfx_buffers = FALSE;
9502   boolean init_video_buffer = FALSE;
9503   boolean init_gadgets_and_anims = FALSE;
9504   boolean init_em_graphics = FALSE;
9505
9506   if (new_win_xsize != WIN_XSIZE ||
9507       new_win_ysize != WIN_YSIZE)
9508   {
9509     WIN_XSIZE = new_win_xsize;
9510     WIN_YSIZE = new_win_ysize;
9511
9512     init_video_buffer = TRUE;
9513     init_gfx_buffers = TRUE;
9514     init_gadgets_and_anims = TRUE;
9515
9516     // Debug("tools:viewport", "video: init_video_buffer, init_gfx_buffers");
9517   }
9518
9519   if (new_scr_fieldx != SCR_FIELDX ||
9520       new_scr_fieldy != SCR_FIELDY)
9521   {
9522     // this always toggles between MAIN and GAME when using small tile size
9523
9524     SCR_FIELDX = new_scr_fieldx;
9525     SCR_FIELDY = new_scr_fieldy;
9526
9527     // Debug("tools:viewport", "new_scr_fieldx != SCR_FIELDX ...");
9528   }
9529
9530   if (new_sx != SX ||
9531       new_sy != SY ||
9532       new_dx != DX ||
9533       new_dy != DY ||
9534       new_vx != VX ||
9535       new_vy != VY ||
9536       new_ex != EX ||
9537       new_ey != EY ||
9538       new_sxsize != SXSIZE ||
9539       new_sysize != SYSIZE ||
9540       new_dxsize != DXSIZE ||
9541       new_dysize != DYSIZE ||
9542       new_vxsize != VXSIZE ||
9543       new_vysize != VYSIZE ||
9544       new_exsize != EXSIZE ||
9545       new_eysize != EYSIZE ||
9546       new_real_sx != REAL_SX ||
9547       new_real_sy != REAL_SY ||
9548       new_full_sxsize != FULL_SXSIZE ||
9549       new_full_sysize != FULL_SYSIZE ||
9550       new_tilesize_var != TILESIZE_VAR
9551       )
9552   {
9553     // ------------------------------------------------------------------------
9554     // determine next fading area for changed viewport definitions
9555     // ------------------------------------------------------------------------
9556
9557     // start with current playfield area (default fading area)
9558     FADE_SX = REAL_SX;
9559     FADE_SY = REAL_SY;
9560     FADE_SXSIZE = FULL_SXSIZE;
9561     FADE_SYSIZE = FULL_SYSIZE;
9562
9563     // add new playfield area if position or size has changed
9564     if (new_real_sx != REAL_SX || new_real_sy != REAL_SY ||
9565         new_full_sxsize != FULL_SXSIZE || new_full_sysize != FULL_SYSIZE)
9566     {
9567       JoinRectangles(&FADE_SX, &FADE_SY, &FADE_SXSIZE, &FADE_SYSIZE,
9568                      new_real_sx, new_real_sy, new_full_sxsize,new_full_sysize);
9569     }
9570
9571     // add current and new door 1 area if position or size has changed
9572     if (new_dx != DX || new_dy != DY ||
9573         new_dxsize != DXSIZE || new_dysize != DYSIZE)
9574     {
9575       JoinRectangles(&FADE_SX, &FADE_SY, &FADE_SXSIZE, &FADE_SYSIZE,
9576                      DX, DY, DXSIZE, DYSIZE);
9577       JoinRectangles(&FADE_SX, &FADE_SY, &FADE_SXSIZE, &FADE_SYSIZE,
9578                      new_dx, new_dy, new_dxsize, new_dysize);
9579     }
9580
9581     // add current and new door 2 area if position or size has changed
9582     if (new_vx != VX || new_vy != VY ||
9583         new_vxsize != VXSIZE || new_vysize != VYSIZE)
9584     {
9585       JoinRectangles(&FADE_SX, &FADE_SY, &FADE_SXSIZE, &FADE_SYSIZE,
9586                      VX, VY, VXSIZE, VYSIZE);
9587       JoinRectangles(&FADE_SX, &FADE_SY, &FADE_SXSIZE, &FADE_SYSIZE,
9588                      new_vx, new_vy, new_vxsize, new_vysize);
9589     }
9590
9591     // ------------------------------------------------------------------------
9592     // handle changed tile size
9593     // ------------------------------------------------------------------------
9594
9595     if (new_tilesize_var != TILESIZE_VAR)
9596     {
9597       // Debug("tools:viewport", "new_tilesize_var != TILESIZE_VAR");
9598
9599       // changing tile size invalidates scroll values of engine snapshots
9600       FreeEngineSnapshotSingle();
9601
9602       // changing tile size requires update of graphic mapping for EM engine
9603       init_em_graphics = TRUE;
9604     }
9605
9606     SX = new_sx;
9607     SY = new_sy;
9608     DX = new_dx;
9609     DY = new_dy;
9610     VX = new_vx;
9611     VY = new_vy;
9612     EX = new_ex;
9613     EY = new_ey;
9614     SXSIZE = new_sxsize;
9615     SYSIZE = new_sysize;
9616     DXSIZE = new_dxsize;
9617     DYSIZE = new_dysize;
9618     VXSIZE = new_vxsize;
9619     VYSIZE = new_vysize;
9620     EXSIZE = new_exsize;
9621     EYSIZE = new_eysize;
9622     REAL_SX = new_real_sx;
9623     REAL_SY = new_real_sy;
9624     FULL_SXSIZE = new_full_sxsize;
9625     FULL_SYSIZE = new_full_sysize;
9626     TILESIZE_VAR = new_tilesize_var;
9627
9628     init_gfx_buffers = TRUE;
9629     init_gadgets_and_anims = TRUE;
9630
9631     // Debug("tools:viewport", "viewports: init_gfx_buffers");
9632     // Debug("tools:viewport", "viewports: init_gadgets_and_anims");
9633   }
9634
9635   if (init_gfx_buffers)
9636   {
9637     // Debug("tools:viewport", "init_gfx_buffers");
9638
9639     SCR_FIELDX = new_scr_fieldx_buffers;
9640     SCR_FIELDY = new_scr_fieldy_buffers;
9641
9642     InitGfxBuffers();
9643
9644     SCR_FIELDX = new_scr_fieldx;
9645     SCR_FIELDY = new_scr_fieldy;
9646
9647     SetDrawDeactivationMask(REDRAW_NONE);
9648     SetDrawBackgroundMask(REDRAW_FIELD);
9649   }
9650
9651   if (init_video_buffer)
9652   {
9653     // Debug("tools:viewport", "init_video_buffer");
9654
9655     FreeAllImageTextures();     // needs old renderer to free the textures
9656
9657     InitVideoBuffer(WIN_XSIZE, WIN_YSIZE, DEFAULT_DEPTH, setup.fullscreen);
9658     InitImageTextures();
9659   }
9660
9661   if (init_gadgets_and_anims)
9662   {
9663     // Debug("tools:viewport", "init_gadgets_and_anims");
9664
9665     InitGadgets();
9666     InitGlobalAnimations();
9667   }
9668
9669   if (init_em_graphics)
9670   {
9671     InitGraphicInfo_EM();
9672   }
9673 }