e9e2c26403de4f3587e9134286424a35698fc143
[rocksndiamonds.git] / src / tape.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 // tape.c
10 // ============================================================================
11
12 #include "libgame/libgame.h"
13
14 #include "tape.h"
15 #include "init.h"
16 #include "game.h"
17 #include "tools.h"
18 #include "files.h"
19 #include "network.h"
20 #include "anim.h"
21
22 #define DEBUG_TAPE_WHEN_PLAYING                 FALSE
23
24 // tape button identifiers
25 #define TAPE_CTRL_ID_EJECT                      0
26 #define TAPE_CTRL_ID_EXTRA                      1
27 #define TAPE_CTRL_ID_STOP                       2
28 #define TAPE_CTRL_ID_PAUSE                      3
29 #define TAPE_CTRL_ID_RECORD                     4
30 #define TAPE_CTRL_ID_PLAY                       5
31 #define TAPE_CTRL_ID_INSERT_SOLUTION            6
32 #define TAPE_CTRL_ID_PLAY_SOLUTION              7
33
34 #define NUM_TAPE_BUTTONS                        8
35
36 // values for tape handling
37 #define TAPE_PAUSE_SECONDS_BEFORE_DEATH         5
38 #define TAPE_MIN_SECONDS_FOR_UNDO_BUFFER        20
39
40 // forward declaration for internal use
41 static void HandleTapeButtons(struct GadgetInfo *);
42 static void TapeStopWarpForward(void);
43 static float GetTapeLengthSecondsFloat(void);
44 static void CopyTapeToUndoBuffer(void);
45
46 static struct GadgetInfo *tape_gadget[NUM_TAPE_BUTTONS];
47 static struct TapeInfo tape_undo_buffer;
48
49
50 // ============================================================================
51 // video tape definitions
52 // ============================================================================
53
54 #define VIDEO_INFO_OFF                  (VIDEO_STATE_DATE_OFF   |       \
55                                          VIDEO_STATE_TIME_OFF   |       \
56                                          VIDEO_STATE_FRAME_OFF)
57 #define VIDEO_STATE_OFF                 (VIDEO_STATE_PLAY_OFF   |       \
58                                          VIDEO_STATE_REC_OFF    |       \
59                                          VIDEO_STATE_PAUSE_OFF  |       \
60                                          VIDEO_STATE_FFWD_OFF   |       \
61                                          VIDEO_STATE_WARP_OFF   |       \
62                                          VIDEO_STATE_WARP2_OFF  |       \
63                                          VIDEO_STATE_PBEND_OFF  |       \
64                                          VIDEO_STATE_1STEP_OFF)
65 #define VIDEO_PRESS_OFF                 (VIDEO_PRESS_PLAY_OFF   |       \
66                                          VIDEO_PRESS_REC_OFF    |       \
67                                          VIDEO_PRESS_PAUSE_OFF  |       \
68                                          VIDEO_PRESS_STOP_OFF   |       \
69                                          VIDEO_PRESS_EJECT_OFF)
70 #define VIDEO_ALL_OFF                   (VIDEO_INFO_OFF         |       \
71                                          VIDEO_STATE_OFF        |       \
72                                          VIDEO_PRESS_OFF)
73
74 #define VIDEO_INFO_ON                   (VIDEO_STATE_DATE_ON    |       \
75                                          VIDEO_STATE_TIME_ON    |       \
76                                          VIDEO_STATE_FRAME_ON)
77 #define VIDEO_STATE_ON                  (VIDEO_STATE_PLAY_ON    |       \
78                                          VIDEO_STATE_REC_ON     |       \
79                                          VIDEO_STATE_PAUSE_ON   |       \
80                                          VIDEO_STATE_FFWD_ON    |       \
81                                          VIDEO_STATE_WARP_ON    |       \
82                                          VIDEO_STATE_WARP2_ON   |       \
83                                          VIDEO_STATE_PBEND_ON   |       \
84                                          VIDEO_STATE_1STEP_ON)
85 #define VIDEO_PRESS_ON                  (VIDEO_PRESS_PLAY_ON    |       \
86                                          VIDEO_PRESS_REC_ON     |       \
87                                          VIDEO_PRESS_PAUSE_ON   |       \
88                                          VIDEO_PRESS_STOP_ON    |       \
89                                          VIDEO_PRESS_EJECT_ON)
90 #define VIDEO_ALL_ON                    (VIDEO_INFO_ON          |       \
91                                          VIDEO_STATE_ON         |       \
92                                          VIDEO_PRESS_ON)
93
94 #define VIDEO_INFO                      (VIDEO_INFO_ON | VIDEO_INFO_OFF)
95 #define VIDEO_STATE                     (VIDEO_STATE_ON | VIDEO_STATE_OFF)
96 #define VIDEO_PRESS                     (VIDEO_PRESS_ON | VIDEO_PRESS_OFF)
97 #define VIDEO_ALL                       (VIDEO_ALL_ON | VIDEO_ALL_OFF)
98
99 #define NUM_TAPE_FUNCTIONS              11
100 #define NUM_TAPE_FUNCTION_PARTS         2
101 #define NUM_TAPE_FUNCTION_STATES        2
102
103
104 // ============================================================================
105 // video display functions
106 // ============================================================================
107
108 static void DrawVideoDisplay_Graphics(unsigned int state, unsigned int value)
109 {
110   int i, j, k;
111
112   static struct
113   {
114     int graphic;
115     struct XY *pos;
116   }
117   video_pos[NUM_TAPE_FUNCTIONS][NUM_TAPE_FUNCTION_PARTS] =
118   {
119     {
120       { IMG_GFX_TAPE_LABEL_PLAY,                &tape.label.play        },
121       { IMG_GFX_TAPE_SYMBOL_PLAY,               &tape.symbol.play       },
122     },
123     {
124       { IMG_GFX_TAPE_LABEL_RECORD,              &tape.label.record      },
125       { IMG_GFX_TAPE_SYMBOL_RECORD,             &tape.symbol.record     },
126     },
127     {
128       { IMG_GFX_TAPE_LABEL_PAUSE,               &tape.label.pause       },
129       { IMG_GFX_TAPE_SYMBOL_PAUSE,              &tape.symbol.pause      },
130     },
131     {
132       { IMG_GFX_TAPE_LABEL_DATE,                &tape.label.date        },
133       { -1,                                     NULL                    },
134     },
135     {
136       { IMG_GFX_TAPE_LABEL_TIME,                &tape.label.time        },
137       { -1,                                     NULL                    },
138     },
139     {
140       // (no label for displaying optional frame)
141       { -1,                                     NULL                    },
142       { -1,                                     NULL                    },
143     },
144     {
145       { IMG_GFX_TAPE_LABEL_FAST_FORWARD,        &tape.label.fast_forward  },
146       { IMG_GFX_TAPE_SYMBOL_FAST_FORWARD,       &tape.symbol.fast_forward },
147     },
148     {
149       { IMG_GFX_TAPE_LABEL_WARP_FORWARD,        &tape.label.warp_forward  },
150       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD,       &tape.symbol.warp_forward },
151     },
152     {
153       { IMG_GFX_TAPE_LABEL_WARP_FORWARD_BLIND,  &tape.label.warp_forward_blind},
154       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD_BLIND, &tape.symbol.warp_forward_blind},
155     },
156     {
157       { IMG_GFX_TAPE_LABEL_PAUSE_BEFORE_END,    &tape.label.pause_before_end  },
158       { IMG_GFX_TAPE_SYMBOL_PAUSE_BEFORE_END,   &tape.symbol.pause_before_end },
159     },
160     {
161       { IMG_GFX_TAPE_LABEL_SINGLE_STEP,         &tape.label.single_step  },
162       { IMG_GFX_TAPE_SYMBOL_SINGLE_STEP,        &tape.symbol.single_step },
163     },
164   };
165
166   for (k = 0; k < NUM_TAPE_FUNCTION_STATES; k++)        // on or off states
167   {
168     for (i = 0; i < NUM_TAPE_FUNCTIONS; i++)            // record, play, ...
169     {
170       for (j = 0; j < NUM_TAPE_FUNCTION_PARTS; j++)     // label or symbol
171       {
172         int graphic = video_pos[i][j].graphic;
173         struct XY *pos = video_pos[i][j].pos;
174
175         if (graphic == -1 ||
176             pos->x == -1 ||
177             pos->y == -1)
178           continue;
179
180         if (state & (1 << (i * 2 + k)))
181         {
182           struct GraphicInfo *gfx_bg = &graphic_info[IMG_BACKGROUND_TAPE];
183           struct GraphicInfo *gfx = &graphic_info[graphic];
184           Bitmap *gd_bitmap;
185           int gd_x, gd_y;
186           int skip_value =
187             (j == 0 ? VIDEO_DISPLAY_SYMBOL_ONLY : VIDEO_DISPLAY_LABEL_ONLY);
188
189           if (value == skip_value)
190             continue;
191
192           if (k == 1)           // on
193           {
194             gd_bitmap = gfx->bitmap;
195             gd_x = gfx->src_x;
196             gd_y = gfx->src_y;
197           }
198           else                  // off
199           {
200             gd_bitmap = gfx_bg->bitmap;
201             gd_x = gfx_bg->src_x + pos->x;
202             gd_y = gfx_bg->src_y + pos->y;
203           }
204
205           // some tape graphics may be undefined -- only draw if defined
206           if (gd_bitmap != NULL)
207             BlitBitmap(gd_bitmap, drawto, gd_x, gd_y, gfx->width, gfx->height,
208                        VX + pos->x, VY + pos->y);
209
210           redraw_mask |= REDRAW_DOOR_2;
211         }
212       }
213     }
214   }
215 }
216
217
218 #define DATETIME_NONE                   (0)
219
220 #define DATETIME_DATE_YYYY              (1 << 0)
221 #define DATETIME_DATE_YY                (1 << 1)
222 #define DATETIME_DATE_MON               (1 << 2)
223 #define DATETIME_DATE_MM                (1 << 3)
224 #define DATETIME_DATE_DD                (1 << 4)
225
226 #define DATETIME_TIME_HH                (1 << 5)
227 #define DATETIME_TIME_MIN               (1 << 6)
228 #define DATETIME_TIME_MM                (1 << 7)
229 #define DATETIME_TIME_SS                (1 << 8)
230
231 #define DATETIME_FRAME                  (1 << 9)
232
233 #define DATETIME_XOFFSET_1              (1 << 10)
234 #define DATETIME_XOFFSET_2              (1 << 11)
235
236 #define DATETIME_DATE                   (DATETIME_DATE_YYYY     |       \
237                                          DATETIME_DATE_YY       |       \
238                                          DATETIME_DATE_MON      |       \
239                                          DATETIME_DATE_MM       |       \
240                                          DATETIME_DATE_DD)
241
242 #define DATETIME_TIME                   (DATETIME_TIME_HH       |       \
243                                          DATETIME_TIME_MIN      |       \
244                                          DATETIME_TIME_MM       |       \
245                                          DATETIME_TIME_SS)
246
247 #define MAX_DATETIME_STRING_SIZE        32
248
249 static void DrawVideoDisplay_DateTime(unsigned int state, unsigned int value)
250 {
251   int i;
252
253   static char *month_shortnames[] =
254   {
255     "JAN",
256     "FEB",
257     "MAR",
258     "APR",
259     "MAY",
260     "JUN",
261     "JUL",
262     "AUG",
263     "SEP",
264     "OCT",
265     "NOV",
266     "DEC"
267   };
268
269   static struct
270   {
271     struct TextPosInfo *pos;
272     int type;
273   }
274   datetime_info[] =
275   {
276     { &tape.text.date,          DATETIME_DATE_DD                        },
277     { &tape.text.date,          DATETIME_DATE_MON | DATETIME_XOFFSET_1  },
278     { &tape.text.date,          DATETIME_DATE_YY  | DATETIME_XOFFSET_2  },
279     { &tape.text.date_yyyy,     DATETIME_DATE_YYYY                      },
280     { &tape.text.date_yy,       DATETIME_DATE_YY                        },
281     { &tape.text.date_mon,      DATETIME_DATE_MON                       },
282     { &tape.text.date_mm,       DATETIME_DATE_MM                        },
283     { &tape.text.date_dd,       DATETIME_DATE_DD                        },
284
285     { &tape.text.time,          DATETIME_TIME_MIN                       },
286     { &tape.text.time,          DATETIME_TIME_SS  | DATETIME_XOFFSET_1  },
287     { &tape.text.time_hh,       DATETIME_TIME_HH                        },
288     { &tape.text.time_mm,       DATETIME_TIME_MM                        },
289     { &tape.text.time_ss,       DATETIME_TIME_SS                        },
290
291     { &tape.text.frame,         DATETIME_FRAME                          },
292
293     { NULL,                     DATETIME_NONE                           },
294   };
295
296   for (i = 0; datetime_info[i].pos != NULL; i++)
297   {
298     struct TextPosInfo *pos = datetime_info[i].pos;
299     int type = datetime_info[i].type;
300     int xpos, ypos;
301
302     if (pos->x == -1 &&
303         pos->y == -1)
304       continue;
305
306     xpos = VX + pos->x + (type & DATETIME_XOFFSET_1 ? pos->xoffset  :
307                           type & DATETIME_XOFFSET_2 ? pos->xoffset2 : 0);
308     ypos = VY + pos->y;
309
310     if ((type & DATETIME_DATE) && (state & VIDEO_STATE_DATE_ON))
311     {
312       char s[MAX_DATETIME_STRING_SIZE];
313       int year2 = value / 10000;
314       int year4 = (year2 < 70 ? 2000 + year2 : 1900 + year2);
315       int month_index_raw = (value / 100) % 100;
316       int month_index = month_index_raw % 12;   // prevent invalid index
317       int month = month_index + 1;
318       int day = value % 100;
319
320       strcpy(s, (type & DATETIME_DATE_YYYY ? int2str(year4, 4) :
321                  type & DATETIME_DATE_YY   ? int2str(year2, 2) :
322                  type & DATETIME_DATE_MON  ? month_shortnames[month_index] :
323                  type & DATETIME_DATE_MM   ? int2str(month, 2) :
324                  type & DATETIME_DATE_DD   ? int2str(day, 2) : ""));
325
326       DrawText(xpos, ypos, s, pos->font);
327     }
328     else if ((type & DATETIME_TIME) && (state & VIDEO_STATE_TIME_ON))
329     {
330       char s[MAX_DATETIME_STRING_SIZE];
331       int hh = (value / 3600) % 100;
332       int min = value / 60;
333       int mm = (value / 60) % 60;
334       int ss = value % 60;
335
336       strcpy(s, (type & DATETIME_TIME_HH  ? int2str(hh, 2) :
337                  type & DATETIME_TIME_MIN ? int2str(min, 2) :
338                  type & DATETIME_TIME_MM  ? int2str(mm, 2) :
339                  type & DATETIME_TIME_SS  ? int2str(ss, 2) : ""));
340
341       DrawText(xpos, ypos, s, pos->font);
342     }
343     else if ((type & DATETIME_FRAME) && (state & VIDEO_STATE_FRAME_ON))
344     {
345       DrawText(xpos, ypos, int2str(value, pos->size), pos->font);
346     }
347   }
348 }
349
350 void DrawVideoDisplay(unsigned int state, unsigned int value)
351 {
352   DrawVideoDisplay_Graphics(state, value);
353   DrawVideoDisplay_DateTime(state, value);
354 }
355
356 static void DrawVideoDisplayLabel(unsigned int state)
357 {
358   DrawVideoDisplay(state, VIDEO_DISPLAY_LABEL_ONLY);
359 }
360
361 static void DrawVideoDisplaySymbol(unsigned int state)
362 {
363   DrawVideoDisplay(state, VIDEO_DISPLAY_SYMBOL_ONLY);
364 }
365
366 static void DrawVideoDisplayCurrentState(void)
367 {
368   int state = 0;
369
370   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
371
372   if (tape.pausing)
373     state |= VIDEO_STATE_PAUSE_ON;
374
375   if (tape.recording)
376   {
377     state |= VIDEO_STATE_REC_ON;
378
379     if (tape.single_step)
380       state |= VIDEO_STATE_1STEP_ON;
381   }
382   else if (tape.playing)
383   {
384     state |= VIDEO_STATE_PLAY_ON;
385
386     if (!tape.pausing)
387     {
388       if (tape.deactivate_display)
389         state |= VIDEO_STATE_WARP2_ON;
390       else if (tape.warp_forward)
391         state |= VIDEO_STATE_WARP_ON;
392       else if (tape.fast_forward)
393         state |= VIDEO_STATE_FFWD_ON;
394
395       if (tape.pause_before_end)
396         state |= VIDEO_STATE_PBEND_ON;
397     }
398   }
399
400   // draw labels and symbols separately to prevent labels overlapping symbols
401   DrawVideoDisplayLabel(state);
402   DrawVideoDisplaySymbol(state);
403 }
404
405 void DrawCompleteVideoDisplay(void)
406 {
407   struct GraphicInfo *g_tape = &graphic_info[IMG_BACKGROUND_TAPE];
408
409   // draw tape background
410   BlitBitmap(g_tape->bitmap, drawto, g_tape->src_x, g_tape->src_y,
411              gfx.vxsize, gfx.vysize, gfx.vx, gfx.vy);
412
413   // draw tape buttons (forced)
414   RedrawOrRemapTapeButtons();
415
416   DrawVideoDisplay(VIDEO_ALL_OFF, 0);
417
418   if (tape.recording)
419   {
420     DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
421     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
422     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
423     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
424
425     if (tape.pausing)
426       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
427   }
428   else if (tape.playing)
429   {
430     DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
431     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
432     DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
433     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
434
435     if (tape.pausing)
436       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
437   }
438   else if (tape.date && tape.length)
439   {
440     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
441     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
442     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
443   }
444
445   BlitBitmap(drawto, bitmap_db_door_2, gfx.vx, gfx.vy, gfx.vxsize, gfx.vysize,
446              0, 0);
447 }
448
449 void TapeDeactivateDisplayOn(void)
450 {
451   SetDrawDeactivationMask(REDRAW_FIELD);
452   audio.sound_deactivated = TRUE;
453 }
454
455 void TapeDeactivateDisplayOff(boolean redraw_display)
456 {
457   SetDrawDeactivationMask(REDRAW_NONE);
458   audio.sound_deactivated = FALSE;
459
460   if (redraw_display)
461   {
462     RedrawPlayfield();
463
464     UpdateGameDoorValues();
465     DrawGameDoorValues();
466   }
467 }
468
469
470 // ============================================================================
471 // tape logging functions
472 // ============================================================================
473
474 struct AutoPlayInfo
475 {
476   LevelDirTree *leveldir;
477   boolean initialized;
478   int last_level_nr;
479   int level_nr;
480   int num_levels_played;
481   int num_levels_solved;
482   int num_tapes_patched;
483   int num_tape_missing;
484   boolean level_failed[MAX_TAPES_PER_SET];
485   char *tape_filename;
486 };
487
488 static char tape_patch_info[MAX_OUTPUT_LINESIZE];
489
490 static void PrintTapeReplayHeader(struct AutoPlayInfo *autoplay)
491 {
492   PrintLine("=", 79);
493
494   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
495     Print("Automatically fixing level tapes\n");
496   else if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
497     Print("Automatically uploading level tapes\n");
498   else
499     Print("Automatically playing level tapes\n");
500
501   PrintLine("-", 79);
502   Print("Level series identifier: '%s'\n", autoplay->leveldir->identifier);
503   Print("Level series name:       '%s'\n", autoplay->leveldir->name);
504   Print("Level series author:     '%s'\n", autoplay->leveldir->author);
505   Print("Number of levels:        %d\n",   autoplay->leveldir->levels);
506   PrintLine("=", 79);
507   Print("\n");
508 }
509
510 static void PrintTapeReplayProgress(boolean replay_finished)
511 {
512   static unsigned int counter_last = -1;
513   unsigned int counter = Counter();
514   unsigned int counter_seconds  = counter / 1000;
515
516   if (!replay_finished)
517   {
518     unsigned int counter_delay = 50;
519
520     if (counter > counter_last + counter_delay)
521     {
522       PrintNoLog("\r");
523       PrintNoLog("Tape %03d %s[%02d:%02d]: [%02d:%02d] - playing tape ... ",
524                  level_nr,  tape_patch_info,
525                  tape.length_seconds / 60, tape.length_seconds % 60,
526                  TapeTime / 60, TapeTime % 60);
527
528       counter_last = counter;
529     }
530   }
531   else
532   {
533     float tape_length_seconds = GetTapeLengthSecondsFloat();
534
535     PrintNoLog("\r");
536     Print("Tape %03d %s[%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
537           level_nr, tape_patch_info,
538           tape.length_seconds / 60, tape.length_seconds % 60,
539           counter_seconds / 60, counter_seconds % 60, counter % 1000,
540           (float)counter / tape_length_seconds / 10,
541           tape.auto_play_level_fixed ? "solved and fixed" :
542           tape.auto_play_level_solved ? "solved" :
543           tape.auto_play_level_not_fixable ? "NOT SOLVED, NOT FIXED" :
544           "NOT SOLVED");
545
546     counter_last = -1;
547   }
548 }
549
550 static void PrintTapeReplaySummary(struct AutoPlayInfo *autoplay)
551 {
552   char *autoplay_status =
553     (autoplay->num_levels_played == autoplay->num_levels_solved &&
554      autoplay->num_levels_played > 0 ? " OK " : "WARN");
555   int autoplay_percent =
556     (autoplay->num_levels_played ?
557      autoplay->num_levels_solved * 100 / autoplay->num_levels_played : 0);
558   int i;
559
560   Print("\n");
561   PrintLine("=", 79);
562   Print("Number of levels played: %d\n", autoplay->num_levels_played);
563   Print("Number of levels solved: %d (%d%%)\n", autoplay->num_levels_solved,
564         (autoplay->num_levels_played ?
565          autoplay->num_levels_solved * 100 / autoplay->num_levels_played : 0));
566   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
567     Print("Number of tapes fixed: %d\n", autoplay->num_tapes_patched);
568   PrintLine("-", 79);
569   Print("Summary (for automatic parsing by scripts):\n");
570
571   if (autoplay->tape_filename)
572   {
573     Print("TAPEFILE [%s] '%s', %d, %d, %d",
574           autoplay_status,
575           autoplay->leveldir->identifier,
576           autoplay->last_level_nr,
577           game.score_final,
578           game.score_time_final);
579   }
580   else
581   {
582     Print("LEVELDIR [%s] '%s', SOLVED %d/%d (%d%%)",
583           autoplay_status,
584           autoplay->leveldir->identifier,
585           autoplay->num_levels_solved,
586           autoplay->num_levels_played,
587           autoplay_percent);
588
589     if (autoplay->num_levels_played != autoplay->num_levels_solved)
590     {
591       Print(", FAILED:");
592       for (i = 0; i < MAX_TAPES_PER_SET; i++)
593         if (autoplay->level_failed[i])
594           Print(" %03d", i);
595     }
596   }
597
598   Print("\n");
599   PrintLine("=", 79);
600 }
601
602 static FILE *tape_log_file;
603
604 static void OpenTapeLogfile(void)
605 {
606   if (!(tape_log_file = fopen(options.tape_log_filename, MODE_WRITE)))
607     Warn("cannot write tape logfile '%s'", options.tape_log_filename);
608 }
609
610 static void WriteTapeLogfile(byte action[MAX_TAPE_ACTIONS])
611 {
612   int i;
613
614   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
615     putFile8Bit(tape_log_file, action[i]);
616 }
617
618 static void CloseTapeLogfile(void)
619 {
620   fclose(tape_log_file);
621 }
622
623
624 // ============================================================================
625 // tape control functions
626 // ============================================================================
627
628 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
629 {
630   struct tm *lt = localtime(&epoch_seconds);
631
632   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
633 }
634
635 void TapeSetDateFromNow(void)
636 {
637   TapeSetDateFromEpochSeconds(time(NULL));
638 }
639
640 void TapeErase(void)
641 {
642   int i;
643
644   CopyTapeToUndoBuffer();
645
646   tape.counter = 0;
647   tape.length = 0;
648   tape.length_frames = 0;
649   tape.length_seconds = 0;
650
651   tape.score_tape_basename[0] = '\0';
652
653   if (leveldir_current)
654   {
655     strncpy(tape.level_identifier, leveldir_current->identifier,
656             MAX_FILENAME_LEN);
657     tape.level_identifier[MAX_FILENAME_LEN] = '\0';
658   }
659
660   tape.level_nr = level_nr;
661   tape.pos[tape.counter].delay = 0;
662   tape.changed = TRUE;
663
664   tape.random_seed = InitRND(level.random_seed);
665
666   tape.file_version = FILE_VERSION_ACTUAL;
667   tape.game_version = GAME_VERSION_ACTUAL;
668   tape.engine_version = level.game_version;
669
670   tape.property_bits = TAPE_PROPERTY_NONE;
671
672   TapeSetDateFromNow();
673
674   for (i = 0; i < MAX_PLAYERS; i++)
675     tape.player_participates[i] = FALSE;
676
677   tape.centered_player_nr_next = -1;
678   tape.set_centered_player = FALSE;
679
680   // set flags for game actions to default values (may be overwritten later)
681   tape.use_key_actions = TRUE;
682   tape.use_mouse_actions = FALSE;
683 }
684
685 static void TapeRewind(void)
686 {
687   tape.counter = 0;
688   tape.delay_played = 0;
689   tape.pause_before_end = FALSE;
690   tape.recording = FALSE;
691   tape.playing = FALSE;
692   tape.fast_forward = FALSE;
693   tape.warp_forward = FALSE;
694   tape.deactivate_display = FALSE;
695   tape.auto_play = (global.autoplay_leveldir != NULL);
696   tape.auto_play_level_solved = FALSE;
697   tape.auto_play_level_fixed = FALSE;
698   tape.auto_play_level_not_fixable = FALSE;
699   tape.quick_resume = FALSE;
700   tape.single_step = FALSE;
701
702   tape.centered_player_nr_next = -1;
703   tape.set_centered_player = FALSE;
704
705   InitRND(tape.random_seed);
706 }
707
708 static void TapeSetRandomSeed(int random_seed)
709 {
710   tape.random_seed = InitRND(random_seed);
711 }
712
713 void TapeStartRecording(int random_seed)
714 {
715   if (!TAPE_IS_STOPPED(tape))
716     TapeStop();
717
718   TapeErase();
719   TapeRewind();
720   TapeSetRandomSeed(random_seed);
721
722   tape.recording = TRUE;
723
724   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
725   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
726   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
727   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
728
729   MapTapeWarpButton();
730
731   SetDrawDeactivationMask(REDRAW_NONE);
732   audio.sound_deactivated = FALSE;
733
734   // required here to update video display if tape door is closed
735   if (GetDoorState() & DOOR_CLOSE_2)
736     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
737 }
738
739 static void TapeStartGameRecording(void)
740 {
741   StartGameActions(network.enabled, TRUE, level.random_seed);
742 }
743
744 static void TapeAppendRecording(void)
745 {
746   if (!tape.playing || !tape.pausing)
747     return;
748
749   // stop playing
750   tape.playing = FALSE;
751   tape.fast_forward = FALSE;
752   tape.warp_forward = FALSE;
753   tape.pause_before_end = FALSE;
754   tape.deactivate_display = FALSE;
755
756   // start recording
757   tape.recording = TRUE;
758   tape.changed = TRUE;
759
760   // set current delay (for last played move)
761   tape.pos[tape.counter].delay = tape.delay_played;
762
763   tape.property_bits |= TAPE_PROPERTY_REPLAYED;
764
765   // set current date
766   TapeSetDateFromNow();
767
768   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
769   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
770
771   UpdateAndDisplayGameControlValues();
772 }
773
774 void TapeHaltRecording(void)
775 {
776   tape.counter++;
777
778   // initialize delay for next tape entry (to be able to continue recording)
779   if (tape.counter < MAX_TAPE_LEN)
780     tape.pos[tape.counter].delay = 0;
781
782   tape.length = tape.counter;
783   tape.length_frames = GetTapeLengthFrames();
784   tape.length_seconds = GetTapeLengthSeconds();
785 }
786
787 void TapeStopRecording(void)
788 {
789   if (tape.recording)
790     TapeHaltRecording();
791
792   tape.recording = FALSE;
793   tape.pausing = FALSE;
794
795   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
796   MapTapeEjectButton();
797 }
798
799 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
800 {
801   int i;
802
803   if (tape.pos[tape.counter].delay > 0)         // already stored action
804   {
805     boolean changed_events = FALSE;
806
807     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
808       if (tape.pos[tape.counter].action[i] != action[i])
809         changed_events = TRUE;
810
811     if (changed_events || tape.pos[tape.counter].delay >= 255)
812     {
813       if (tape.counter >= MAX_TAPE_LEN - 1)
814         return FALSE;
815
816       tape.counter++;
817       tape.pos[tape.counter].delay = 0;
818     }
819     else
820       tape.pos[tape.counter].delay++;
821   }
822
823   if (tape.pos[tape.counter].delay == 0)        // store new action
824   {
825     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
826       tape.pos[tape.counter].action[i] = action[i];
827
828     tape.pos[tape.counter].delay++;
829   }
830
831   return TRUE;
832 }
833
834 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
835 {
836   byte action[MAX_TAPE_ACTIONS];
837   int i;
838
839   if (!tape.recording)          // (record action even when tape is paused)
840     return;
841
842   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
843     action[i] = action_raw[i];
844
845   if (tape.use_key_actions && tape.set_centered_player)
846   {
847     for (i = 0; i < MAX_PLAYERS; i++)
848       if (tape.centered_player_nr_next == i ||
849           tape.centered_player_nr_next == -1)
850         action[i] |= KEY_SET_FOCUS;
851
852     tape.set_centered_player = FALSE;
853   }
854
855   if (GameFrameDelay != GAME_FRAME_DELAY)
856     tape.property_bits |= TAPE_PROPERTY_GAME_SPEED;
857
858   if (setup.small_game_graphics || SCR_FIELDX >= 2 * SCR_FIELDX_DEFAULT)
859     tape.property_bits |= TAPE_PROPERTY_SMALL_GRAPHICS;
860
861   if (!TapeAddAction(action))
862     TapeStopRecording();
863 }
864
865 void TapeTogglePause(boolean toggle_mode)
866 {
867   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
868   {
869     // continue playing in normal mode
870     tape.fast_forward = FALSE;
871     tape.warp_forward = FALSE;
872     tape.deactivate_display = FALSE;
873
874     tape.pause_before_end = FALSE;
875   }
876
877   tape.pausing = !tape.pausing;
878
879   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
880     tape.single_step = FALSE;
881
882   if (tape.single_step)
883     tape.property_bits |= TAPE_PROPERTY_SINGLE_STEP;
884
885   if (tape.pausing)
886     tape.property_bits |= TAPE_PROPERTY_PAUSE_MODE;
887
888   DrawVideoDisplayCurrentState();
889
890   if (tape.deactivate_display)
891   {
892     if (tape.pausing)
893       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
894     else
895       TapeDeactivateDisplayOn();
896   }
897
898   if (tape.quick_resume)
899   {
900     tape.quick_resume = FALSE;
901
902     TapeStopWarpForward();
903     TapeAppendRecording();
904
905     if (!CheckEngineSnapshotSingle())
906       SaveEngineSnapshotSingle();
907
908     // restart step/move snapshots after quick loading tape
909     SaveEngineSnapshotToListInitial();
910
911     // do not map undo/redo buttons after quick loading tape
912     return;
913   }
914
915   if (game_status == GAME_MODE_PLAYING)
916   {
917     if (setup.show_load_save_buttons &&
918         setup.show_undo_redo_buttons &&
919         CheckEngineSnapshotList())
920     {
921       if (tape.pausing)
922         MapUndoRedoButtons();
923       else if (!tape.single_step)
924         MapLoadSaveButtons();
925     }
926
927     ModifyPauseButtons();
928   }
929 }
930
931 void TapeStartPlaying(void)
932 {
933   if (TAPE_IS_EMPTY(tape))
934     return;
935
936   if (!TAPE_IS_STOPPED(tape))
937     TapeStop();
938
939   TapeRewind();
940
941   tape.playing = TRUE;
942
943   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
944   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
945   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
946   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
947
948   MapTapeWarpButton();
949
950   SetDrawDeactivationMask(REDRAW_NONE);
951   audio.sound_deactivated = FALSE;
952 }
953
954 static void TapeStartGamePlaying(void)
955 {
956   TapeStartPlaying();
957
958   InitGame();
959 }
960
961 void TapeStopPlaying(void)
962 {
963   tape.playing = FALSE;
964   tape.pausing = FALSE;
965
966   if (tape.warp_forward)
967     TapeStopWarpForward();
968
969   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
970   MapTapeEjectButton();
971 }
972
973 byte *TapePlayAction(void)
974 {
975   int update_delay = FRAMES_PER_SECOND / 2;
976   boolean update_video_display = (FrameCounter % update_delay == 0);
977   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
978   static byte action[MAX_TAPE_ACTIONS];
979   int i;
980
981   if (!tape.playing || tape.pausing)
982     return NULL;
983
984   if (tape.pause_before_end)  // stop some seconds before end of tape
985   {
986     if (TapeTime > tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
987     {
988       TapeStopWarpForward();
989       TapeTogglePause(TAPE_TOGGLE_MANUAL);
990
991       return NULL;
992     }
993   }
994
995   if (tape.counter >= tape.length)      // end of tape reached
996   {
997     if (tape.warp_forward && !tape.auto_play)
998     {
999       TapeStopWarpForward();
1000       TapeTogglePause(TAPE_TOGGLE_MANUAL);
1001     }
1002     else
1003     {
1004       TapeStop();
1005     }
1006
1007     return NULL;
1008   }
1009
1010   if (update_video_display && !tape.deactivate_display)
1011   {
1012     int state = 0;
1013
1014     if (tape.warp_forward)
1015       state |= VIDEO_STATE_WARP(update_draw_label_on);
1016     else if (tape.fast_forward)
1017       state |= VIDEO_STATE_FFWD(update_draw_label_on);
1018
1019     if (tape.pause_before_end)
1020       state |= VIDEO_STATE_PBEND(update_draw_label_on);
1021
1022     // draw labels and symbols separately to prevent labels overlapping symbols
1023     DrawVideoDisplayLabel(state);
1024     DrawVideoDisplaySymbol(state);
1025   }
1026
1027   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
1028     action[i] = tape.pos[tape.counter].action[i];
1029
1030 #if DEBUG_TAPE_WHEN_PLAYING
1031   DebugContinued("", "%05d", FrameCounter);
1032   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
1033     DebugContinued("", "   %08x", action[i]);
1034   DebugContinued("tape:play", "\n");
1035 #endif
1036
1037   tape.set_centered_player = FALSE;
1038   tape.centered_player_nr_next = -999;
1039
1040   if (tape.use_key_actions)
1041   {
1042     for (i = 0; i < MAX_PLAYERS; i++)
1043     {
1044       if (action[i] & KEY_SET_FOCUS)
1045       {
1046         tape.set_centered_player = TRUE;
1047         tape.centered_player_nr_next =
1048           (tape.centered_player_nr_next == -999 ? i : -1);
1049       }
1050
1051       action[i] &= ~KEY_SET_FOCUS;
1052     }
1053   }
1054
1055   tape.delay_played++;
1056   if (tape.delay_played >= tape.pos[tape.counter].delay)
1057   {
1058     tape.counter++;
1059     tape.delay_played = 0;
1060   }
1061
1062   if (tape.auto_play)
1063     PrintTapeReplayProgress(FALSE);
1064
1065   if (options.tape_log_filename != NULL)
1066     WriteTapeLogfile(action);
1067
1068   return action;
1069 }
1070
1071 void TapeStop(void)
1072 {
1073   if (tape.pausing)
1074     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1075
1076   TapeStopRecording();
1077   TapeStopPlaying();
1078
1079   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
1080
1081   if (tape.date && tape.length)
1082   {
1083     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
1084     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
1085     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
1086   }
1087 }
1088
1089 unsigned int GetTapeLengthFrames(void)
1090 {
1091   unsigned int tape_length_frames = 0;
1092   int i;
1093
1094   if (TAPE_IS_EMPTY(tape))
1095     return 0;
1096
1097   for (i = 0; i < tape.length; i++)
1098     tape_length_frames += tape.pos[i].delay;
1099
1100   return tape_length_frames;
1101 }
1102
1103 unsigned int GetTapeLengthSeconds(void)
1104 {
1105   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1106 }
1107
1108 static float GetTapeLengthSecondsFloat(void)
1109 {
1110   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1111 }
1112
1113 static void TapeStartWarpForward(int mode)
1114 {
1115   tape.fast_forward = (mode & AUTOPLAY_FFWD);
1116   tape.warp_forward = (mode & AUTOPLAY_WARP);
1117   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
1118
1119   tape.pausing = FALSE;
1120
1121   if (tape.deactivate_display)
1122     TapeDeactivateDisplayOn();
1123
1124   DrawVideoDisplayCurrentState();
1125 }
1126
1127 static void TapeStopWarpForward(void)
1128 {
1129   tape.fast_forward = FALSE;
1130   tape.warp_forward = FALSE;
1131   tape.deactivate_display = FALSE;
1132
1133   tape.pause_before_end = FALSE;
1134
1135   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1136
1137   DrawVideoDisplayCurrentState();
1138 }
1139
1140 static void TapeSingleStep(void)
1141 {
1142   if (network.enabled)
1143     return;
1144
1145   if (!tape.pausing)
1146     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1147
1148   tape.single_step = !tape.single_step;
1149
1150   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1151 }
1152
1153 void TapeQuickSave(void)
1154 {
1155   if (game_status == GAME_MODE_MAIN)
1156   {
1157     Request("No game that can be saved!", REQ_CONFIRM);
1158
1159     return;
1160   }
1161
1162   if (game_status != GAME_MODE_PLAYING)
1163     return;
1164
1165   if (tape.recording)
1166     TapeHaltRecording();        // prepare tape for saving on-the-fly
1167
1168   if (TAPE_IS_EMPTY(tape))
1169   {
1170     Request("No tape that can be saved!", REQ_CONFIRM);
1171
1172     return;
1173   }
1174
1175   tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1176
1177   if (SaveTapeChecked(tape.level_nr))
1178     SaveEngineSnapshotSingle();
1179 }
1180
1181 void TapeQuickLoad(void)
1182 {
1183   char *filename = getTapeFilename(level_nr);
1184
1185   if (!fileExists(filename))
1186   {
1187     Request("No tape for this level!", REQ_CONFIRM);
1188
1189     return;
1190   }
1191
1192   if (tape.recording && !Request("Stop recording and load tape?",
1193                                  REQ_ASK | REQ_STAY_CLOSED))
1194   {
1195     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1196
1197     return;
1198   }
1199
1200   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1201     return;
1202
1203   if (CheckEngineSnapshotSingle())
1204   {
1205     TapeStartGamePlaying();
1206
1207     LoadEngineSnapshotSingle();
1208
1209     DrawCompleteVideoDisplay();
1210
1211     tape.playing = TRUE;
1212     tape.pausing = TRUE;
1213
1214     TapeStopWarpForward();
1215     TapeAppendRecording();
1216
1217     // restart step/move snapshots after quick loading tape
1218     SaveEngineSnapshotToListInitial();
1219
1220     if (FrameCounter > 0)
1221       return;
1222   }
1223
1224   TapeStop();
1225   TapeErase();
1226
1227   LoadTape(level_nr);
1228
1229   if (!TAPE_IS_EMPTY(tape))
1230   {
1231     TapeStartGamePlaying();
1232     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1233
1234     tape.quick_resume = TRUE;
1235     tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1236   }
1237   else  // this should not happen (basically checked above)
1238   {
1239     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1240
1241     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1242   }
1243 }
1244
1245 boolean hasSolutionTape(void)
1246 {
1247   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1248   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1249                             level.native_sp_level->demo.is_available);
1250
1251   return (tape_file_exists || level_has_tape);
1252 }
1253
1254 boolean InsertSolutionTape(void)
1255 {
1256   if (!hasSolutionTape())
1257   {
1258     Request("No solution tape for this level!", REQ_CONFIRM);
1259
1260     return FALSE;
1261   }
1262
1263   if (!TAPE_IS_STOPPED(tape))
1264     TapeStop();
1265
1266   // if tape recorder already contains a tape, remove it without asking
1267   TapeErase();
1268
1269   LoadSolutionTape(level_nr);
1270
1271   DrawCompleteVideoDisplay();
1272
1273   if (TAPE_IS_EMPTY(tape))
1274   {
1275     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1276
1277     return FALSE;
1278   }
1279
1280   return TRUE;
1281 }
1282
1283 boolean PlaySolutionTape(void)
1284 {
1285   if (!InsertSolutionTape())
1286     return FALSE;
1287
1288   TapeStartGamePlaying();
1289
1290   return TRUE;
1291 }
1292
1293 static boolean checkTapesFromSameLevel(struct TapeInfo *t1, struct TapeInfo *t2)
1294 {
1295   return (strEqual(t1->level_identifier, t2->level_identifier) &&
1296           t1->level_nr == t2->level_nr);
1297 }
1298
1299 static void CopyTape(struct TapeInfo *tape_from, struct TapeInfo *tape_to)
1300 {
1301   *tape_to = *tape_from;
1302 }
1303
1304 static void SwapTapes(struct TapeInfo *t1, struct TapeInfo *t2)
1305 {
1306   struct TapeInfo tmp = *t1;
1307
1308   *t1 = *t2;
1309   *t2 = tmp;
1310 }
1311
1312 static void CopyTapeToUndoBuffer(void)
1313 {
1314   // copy tapes to undo buffer if large enough (or larger than last undo tape)
1315   // or if the last undo tape is from a different level set or level number
1316   if (tape.length_seconds >= TAPE_MIN_SECONDS_FOR_UNDO_BUFFER ||
1317       tape.length_seconds >= tape_undo_buffer.length_seconds ||
1318       !checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1319   {
1320     CopyTape(&tape, &tape_undo_buffer);
1321   }
1322 }
1323
1324 void UndoTape(void)
1325 {
1326   // only undo tapes from same level set and with same level number
1327   if (!checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1328     return;
1329
1330   if (!TAPE_IS_STOPPED(tape))
1331     TapeStop();
1332
1333   // swap last recorded tape with undo buffer, so undo can be reversed
1334   SwapTapes(&tape, &tape_undo_buffer);
1335
1336   DrawCompleteVideoDisplay();
1337 }
1338
1339 void FixTape_ForceSinglePlayer(void)
1340 {
1341   int i;
1342
1343   /* fix single-player tapes that contain player input for more than one
1344      player (due to a bug in 3.3.1.2 and earlier versions), which results
1345      in playing levels with more than one player in multi-player mode,
1346      even though the tape was originally recorded in single-player mode */
1347
1348   // remove player input actions for all players but the first one
1349   for (i = 1; i < MAX_PLAYERS; i++)
1350     tape.player_participates[i] = FALSE;
1351
1352   tape.changed = TRUE;
1353 }
1354
1355
1356 // ----------------------------------------------------------------------------
1357 // tape autoplay functions
1358 // ----------------------------------------------------------------------------
1359
1360 static void AutoPlayTapes_SetScoreEntry(int score, int time)
1361 {
1362   // set unique basename for score tape (for uploading to score server)
1363   strcpy(tape.score_tape_basename, getScoreTapeBasename(setup.player_name));
1364
1365   // store score in first score entry
1366   scores.last_added = 0;
1367
1368   struct ScoreEntry *entry = &scores.entry[scores.last_added];
1369
1370   strncpy(entry->tape_basename, tape.score_tape_basename, MAX_FILENAME_LEN);
1371   strncpy(entry->name, setup.player_name, MAX_PLAYER_NAME_LEN);
1372
1373   entry->score = score;
1374   entry->time = time;
1375
1376   PrintNoLog("- uploading score tape to score server ... ");
1377
1378   server_scores.uploaded = FALSE;
1379 }
1380
1381 static void AutoPlayTapes_WaitForUpload(void)
1382 {
1383   unsigned int upload_delay = 0;
1384   unsigned int upload_delay_value = 10000;
1385
1386   ResetDelayCounter(&upload_delay);
1387
1388   // wait for score tape to be successfully uploaded (and fail on timeout)
1389   while (!server_scores.uploaded)
1390   {
1391     if (DelayReached(&upload_delay, upload_delay_value))
1392     {
1393       PrintNoLog("\r");
1394       Print("- uploading score tape to score server - TIMEOUT.\n");
1395
1396       Fail("cannot upload score tape to score server");
1397     }
1398
1399     Delay(20);
1400   }
1401
1402   PrintNoLog("\r");
1403   Print("- uploading score tape to score server - uploaded.\n");
1404 }
1405
1406 void AutoPlayTapes(void)
1407 {
1408   static struct AutoPlayInfo autoplay;
1409   static int patch_nr = 0;
1410   static char *patch_name[] =
1411   {
1412     "original tape",
1413     "em_random_bug",
1414     "screen_34x34",
1415
1416     NULL
1417   };
1418   static int patch_version_first[] =
1419   {
1420     VERSION_IDENT(0,0,0,0),
1421     VERSION_IDENT(3,3,1,0),
1422     VERSION_IDENT(0,0,0,0),
1423
1424     -1
1425   };
1426   static int patch_version_last[] =
1427   {
1428     VERSION_IDENT(9,9,9,9),
1429     VERSION_IDENT(4,0,1,1),
1430     VERSION_IDENT(4,2,2,0),
1431
1432     -1
1433   };
1434   static byte patch_property_bit[] =
1435   {
1436     TAPE_PROPERTY_NONE,
1437     TAPE_PROPERTY_EM_RANDOM_BUG,
1438     TAPE_PROPERTY_NONE,
1439
1440     -1
1441   };
1442   boolean init_level_set = FALSE;
1443   int i;
1444
1445   if (autoplay.initialized)
1446   {
1447     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1448     {
1449       if (tape.auto_play_level_solved)
1450       {
1451         if (patch_nr > 0)
1452         {
1453           // level solved by patched tape -- save fixed tape
1454           char *filename = getTapeFilename(level_nr);
1455           char *filename_orig = getStringCat2(filename, ".orig");
1456
1457           // create backup from old tape, if not yet existing
1458           if (!fileExists(filename_orig))
1459             rename(filename, filename_orig);
1460
1461           SaveTapeToFilename(filename);
1462
1463           tape.auto_play_level_fixed = TRUE;
1464           autoplay.num_tapes_patched++;
1465         }
1466
1467         // continue with next tape
1468         patch_nr = 0;
1469       }
1470       else if (patch_name[patch_nr + 1] != NULL)
1471       {
1472         // level not solved by patched tape -- continue with next patch
1473         patch_nr++;
1474       }
1475       else
1476       {
1477         // level not solved by any patched tape -- continue with next tape
1478         tape.auto_play_level_not_fixable = TRUE;
1479         patch_nr = 0;
1480       }
1481     }
1482
1483     // just finished auto-playing tape
1484     PrintTapeReplayProgress(TRUE);
1485
1486     if (options.tape_log_filename != NULL)
1487       CloseTapeLogfile();
1488
1489     if (global.autoplay_mode == AUTOPLAY_MODE_SAVE &&
1490         tape.auto_play_level_solved)
1491     {
1492       AutoPlayTapes_SetScoreEntry(game.score_final, game.score_time_final);
1493
1494       if (leveldir_current)
1495       {
1496         // the tape's level set identifier may differ from current level set
1497         strncpy(tape.level_identifier, leveldir_current->identifier,
1498                 MAX_FILENAME_LEN);
1499         tape.level_identifier[MAX_FILENAME_LEN] = '\0';
1500
1501         // the tape's level number may differ from current level number
1502         tape.level_nr = level_nr;
1503       }
1504
1505       // save score tape to upload to server; may be required for some reasons:
1506       // * level set identifier in solution tapes may differ from level set
1507       // * solution tape may have native format (like Supaplex solution files)
1508
1509       SaveScoreTape(level_nr);
1510       SaveServerScore(level_nr);
1511
1512       AutoPlayTapes_WaitForUpload();
1513     }
1514
1515     if (patch_nr == 0)
1516       autoplay.num_levels_played++;
1517
1518     if (tape.auto_play_level_solved)
1519       autoplay.num_levels_solved++;
1520
1521     if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1522       autoplay.level_failed[level_nr] = !tape.auto_play_level_solved;
1523   }
1524   else
1525   {
1526     if ((global.autoplay_mode == AUTOPLAY_MODE_SAVE ||
1527          global.autoplay_mode == AUTOPLAY_MODE_UPLOAD) &&
1528         !options.mytapes &&
1529         options.player_name == NULL)
1530     {
1531       Fail("specify player name when uploading solution tapes");
1532     }
1533
1534     DrawCompleteVideoDisplay();
1535
1536     audio.sound_enabled = FALSE;
1537     setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1538
1539     if (strSuffix(global.autoplay_leveldir, ".tape"))
1540     {
1541       autoplay.tape_filename = global.autoplay_leveldir;
1542
1543       LoadTapeFromFilename(autoplay.tape_filename);
1544
1545       if (tape.no_valid_file)
1546       {
1547         if (!fileExists(autoplay.tape_filename))
1548           Fail("tape file '%s' does not exist", autoplay.tape_filename);
1549         else
1550           Fail("cannot load tape file '%s'", autoplay.tape_filename);
1551       }
1552
1553       global.autoplay_leveldir = tape.level_identifier;
1554
1555       if (tape.level_nr >= 0 && tape.level_nr < MAX_TAPES_PER_SET)
1556         global.autoplay_level[tape.level_nr] = TRUE;
1557
1558       global.autoplay_all = FALSE;
1559     }
1560
1561     autoplay.leveldir = getTreeInfoFromIdentifier(leveldir_first,
1562                                                   global.autoplay_leveldir);
1563
1564     if (autoplay.leveldir == NULL)
1565       Fail("no such level identifier: '%s'", global.autoplay_leveldir);
1566
1567     // only private tapes may be modified
1568     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1569       options.mytapes = TRUE;
1570
1571     init_level_set = TRUE;
1572
1573     autoplay.initialized = TRUE;
1574   }
1575
1576   while (1)
1577   {
1578     if (init_level_set)
1579     {
1580       leveldir_current = autoplay.leveldir;
1581
1582       if (autoplay.leveldir->first_level < 0)
1583         autoplay.leveldir->first_level = 0;
1584       if (autoplay.leveldir->last_level >= MAX_TAPES_PER_SET)
1585         autoplay.leveldir->last_level = MAX_TAPES_PER_SET - 1;
1586
1587       autoplay.level_nr = autoplay.leveldir->first_level;
1588
1589       for (i = 0; i < MAX_TAPES_PER_SET; i++)
1590         autoplay.level_failed[i] = FALSE;
1591
1592       PrintTapeReplayHeader(&autoplay);
1593
1594       init_level_set = FALSE;
1595     }
1596
1597     if (global.autoplay_mode != AUTOPLAY_MODE_FIX || patch_nr == 0)
1598       level_nr = autoplay.level_nr++;
1599
1600     if (level_nr > autoplay.leveldir->last_level)
1601     {
1602       PrintTapeReplaySummary(&autoplay);
1603
1604       break;
1605     }
1606
1607     // set patch info (required for progress output)
1608     strcpy(tape_patch_info, "");
1609     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1610       snprintf(tape_patch_info, MAX_OUTPUT_LINESIZE, "[%-13s] ",
1611                patch_name[patch_nr]);
1612
1613     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1614       continue;
1615
1616     TapeErase();
1617
1618     LoadLevel(level_nr);
1619
1620     if (level.no_level_file || level.no_valid_file)
1621     {
1622       Print("Tape %03d: (no level found)\n", level_nr);
1623
1624       continue;
1625     }
1626
1627 #if 0
1628     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
1629     Print("Tape %03d: (only testing level)\n", level_nr);
1630     continue;
1631 #endif
1632
1633     if (autoplay.tape_filename)
1634       LoadTapeFromFilename(autoplay.tape_filename);
1635     else if (options.mytapes)
1636       LoadTape(level_nr);
1637     else
1638       LoadSolutionTape(level_nr);
1639
1640     if (tape.no_valid_file)
1641     {
1642       autoplay.num_tape_missing++;
1643
1644       Print("Tape %03d: (no tape found)\n", level_nr);
1645
1646       continue;
1647     }
1648
1649     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1650     {
1651       boolean skip_patch = FALSE;
1652
1653       if (tape.engine_version < patch_version_first[patch_nr] ||
1654           tape.engine_version > patch_version_last[patch_nr])
1655       {
1656         Print("Tape %03d %s[%02d:%02d]: (%s %d.%d.%d.%d) - skipped.\n",
1657               level_nr,  tape_patch_info,
1658               tape.length_seconds / 60, tape.length_seconds % 60,
1659               "not suitable for version",
1660               (tape.engine_version / 1000000) % 100,
1661               (tape.engine_version / 10000  ) % 100,
1662               (tape.engine_version / 100    ) % 100,
1663               (tape.engine_version          ) % 100);
1664
1665         skip_patch = TRUE;
1666       }
1667
1668       if (strEqual(patch_name[patch_nr], "screen_34x34") &&
1669           tape.num_participating_players == 1)
1670       {
1671         Print("Tape %03d %s[%02d:%02d]: (%s) - skipped.\n",
1672               level_nr,  tape_patch_info,
1673               tape.length_seconds / 60, tape.length_seconds % 60,
1674               "not suitable for single player tapes");
1675
1676         skip_patch = TRUE;
1677       }
1678
1679       if (skip_patch)
1680       {
1681         if (patch_name[patch_nr + 1] != NULL)
1682         {
1683           // continue with next patch
1684           patch_nr++;
1685         }
1686         else
1687         {
1688           // continue with next tape
1689           patch_nr = 0;
1690         }
1691
1692         continue;
1693       }
1694
1695       if (strEqual(patch_name[patch_nr], "screen_34x34"))
1696       {
1697         tape.scr_fieldx = SCR_FIELDX_DEFAULT * 2;
1698         tape.scr_fieldy = SCR_FIELDY_DEFAULT * 2;
1699       }
1700       else
1701       {
1702         tape.property_bits |= patch_property_bit[patch_nr];
1703       }
1704     }
1705
1706     if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1707     {
1708       boolean use_temporary_tape_file = FALSE;
1709
1710       Print("Tape %03d:\n", level_nr);
1711
1712       AutoPlayTapes_SetScoreEntry(0, 0);
1713
1714       if (autoplay.tape_filename == NULL)
1715       {
1716         autoplay.tape_filename = (options.mytapes ? getTapeFilename(level_nr) :
1717                                   getDefaultSolutionTapeFilename(level_nr));
1718
1719         if (!fileExists(autoplay.tape_filename))
1720         {
1721           // non-standard solution tape -- save to temporary file
1722           autoplay.tape_filename = getTemporaryTapeFilename();
1723
1724           SaveTapeToFilename(autoplay.tape_filename);
1725
1726           use_temporary_tape_file = TRUE;
1727         }
1728       }
1729
1730       SaveServerScoreFromFile(level_nr, autoplay.tape_filename);
1731
1732       AutoPlayTapes_WaitForUpload();
1733
1734       if (use_temporary_tape_file)
1735         unlink(autoplay.tape_filename);
1736
1737       // required for uploading multiple tapes
1738       autoplay.tape_filename = NULL;
1739
1740       continue;
1741     }
1742
1743     InitCounter();
1744
1745     if (options.tape_log_filename != NULL)
1746       OpenTapeLogfile();
1747
1748     TapeStartGamePlaying();
1749     TapeStartWarpForward(global.autoplay_mode);
1750
1751     autoplay.last_level_nr = level_nr;
1752
1753     return;
1754   }
1755
1756   CloseAllAndExit(0);
1757 }
1758
1759
1760 // ----------------------------------------------------------------------------
1761 // tape patch functions
1762 // ----------------------------------------------------------------------------
1763
1764 static boolean PatchTape(struct TapeInfo *tape, char *mode)
1765 {
1766   Print("[%d.%d.%d.%d]: ",
1767         (tape->engine_version / 1000000) % 100,
1768         (tape->engine_version / 10000  ) % 100,
1769         (tape->engine_version / 100    ) % 100,
1770         (tape->engine_version          ) % 100);
1771
1772   if (strEqual(mode, "info"))
1773   {
1774     Print("property bits == 0x%02x\n", tape->property_bits);
1775
1776     return FALSE;
1777   }
1778
1779   boolean unpatch_tape = FALSE;
1780   boolean use_property_bit = FALSE;
1781   byte property_bitmask = 0;
1782
1783   if (strSuffix(mode, ":0") ||
1784       strSuffix(mode, ":off") ||
1785       strSuffix(mode, ":clear"))
1786     unpatch_tape = TRUE;
1787
1788   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
1789   {
1790     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
1791     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
1792         tape->engine_version >= VERSION_IDENT(4,0,1,2))
1793     {
1794       Print("This tape version cannot be patched against EM random bug!\n");
1795
1796       return FALSE;
1797     }
1798
1799     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
1800
1801     use_property_bit = TRUE;
1802   }
1803   else if (strEqual(mode, "screen_34x34") || strPrefix(mode, "screen_34x34:"))
1804   {
1805     // this bug only affects team mode tapes
1806     if (tape->num_participating_players == 1)
1807     {
1808       Print("Only team mode tapes can be patched against screen size bug!\n");
1809
1810       return FALSE;
1811     }
1812
1813     // this bug (that always existed before) was fixed in version 4.2.2.1
1814     if (tape->engine_version >= VERSION_IDENT(4,2,2,1))
1815     {
1816       Print("This tape version cannot be patched against screen size bug!\n");
1817
1818       return FALSE;
1819     }
1820
1821     int factor = (unpatch_tape ? 1 : 2);
1822     int scr_fieldx_new = SCR_FIELDX_DEFAULT * factor;
1823     int scr_fieldy_new = SCR_FIELDY_DEFAULT * factor;
1824
1825     if (scr_fieldx_new == tape->scr_fieldx &&
1826         scr_fieldy_new == tape->scr_fieldy)
1827     {
1828       Print("Tape already patched for '%s'!\n", mode);
1829
1830       return FALSE;
1831     }
1832
1833     tape->scr_fieldx = scr_fieldx_new;
1834     tape->scr_fieldy = scr_fieldy_new;
1835   }
1836   else
1837   {
1838     Print("Unknown patch mode '%s'!\n", mode);
1839
1840     return FALSE;
1841   }
1842
1843   // patching tapes using property bits may be used for several patch modes
1844   if (use_property_bit)
1845   {
1846     byte property_bits = tape->property_bits;
1847     boolean set_property_bit = (unpatch_tape ? FALSE : TRUE);
1848
1849     if (set_property_bit)
1850       property_bits |= property_bitmask;
1851     else
1852       property_bits &= ~property_bitmask;
1853
1854     if (property_bits == tape->property_bits)
1855     {
1856       Print("Tape already patched for '%s'!\n", mode);
1857
1858       return FALSE;
1859     }
1860
1861     tape->property_bits = property_bits;
1862   }
1863
1864   Print("Patching for '%s' ... ", mode);
1865
1866   return TRUE;
1867 }
1868
1869 void PatchTapes(void)
1870 {
1871   static LevelDirTree *patchtapes_leveldir = NULL;
1872   static int num_tapes_found = 0;
1873   static int num_tapes_patched = 0;
1874   char *mode = global.patchtapes_mode;
1875   int i;
1876
1877   if (strEqual(mode, "help"))
1878   {
1879     PrintLine("=", 79);
1880     Print("Supported patch modes:\n");
1881     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
1882     Print("- \"screen_34x34\"    - force visible playfield size of 34 x 34\n");
1883     PrintLine("-", 79);
1884     Print("Supported modifiers:\n");
1885     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
1886     PrintLine("=", 79);
1887
1888     CloseAllAndExit(0);
1889   }
1890
1891   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1892                                                   global.patchtapes_leveldir);
1893
1894   if (patchtapes_leveldir == NULL)
1895     Fail("no such level identifier: '%s'", global.patchtapes_leveldir);
1896
1897   leveldir_current = patchtapes_leveldir;
1898
1899   if (patchtapes_leveldir->first_level < 0)
1900     patchtapes_leveldir->first_level = 0;
1901   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
1902     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1903
1904   PrintLine("=", 79);
1905   Print("Patching level tapes for patch mode '%s'\n", mode);
1906   PrintLine("-", 79);
1907   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
1908   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
1909   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
1910   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
1911   PrintLine("=", 79);
1912   Print("\n");
1913
1914   int first_level = patchtapes_leveldir->first_level;
1915   int last_level = patchtapes_leveldir->last_level;
1916
1917   for (i = first_level; i <= last_level; i++)
1918   {
1919     if (!global.patchtapes_all && !global.patchtapes_level[i])
1920       continue;
1921
1922     Print("Tape %03d: ", i);
1923
1924     TapeErase();
1925     LoadTape(i);
1926
1927     if (tape.no_valid_file)
1928     {
1929       Print("(no tape found)\n");
1930
1931       continue;
1932     }
1933
1934     num_tapes_found++;
1935
1936     if (PatchTape(&tape, mode))
1937     {
1938       char *filename = getTapeFilename(i);
1939       char *filename_orig = getStringCat2(filename, ".orig");
1940
1941       if (!fileExists(filename_orig))
1942         rename(filename, filename_orig);
1943
1944       SaveTapeToFilename(filename);
1945
1946       Print("patched tape saved.\n");
1947
1948       num_tapes_patched++;
1949     }
1950   }
1951
1952   Print("\n");
1953   PrintLine("=", 79);
1954   Print("Number of tapes found: %d\n", num_tapes_found);
1955   Print("Number of tapes patched: %d\n", num_tapes_patched);
1956   PrintLine("=", 79);
1957
1958   CloseAllAndExit(0);
1959 }
1960
1961
1962 // ---------- new tape button stuff -------------------------------------------
1963
1964 static struct
1965 {
1966   int graphic;
1967   struct XY *pos;
1968   int gadget_id;
1969   char *infotext;
1970 } tapebutton_info[NUM_TAPE_BUTTONS] =
1971 {
1972   {
1973     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
1974     TAPE_CTRL_ID_EJECT,                 "eject tape"
1975   },
1976   {
1977     // (same position as "eject" button)
1978     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
1979     TAPE_CTRL_ID_EXTRA,                 "extra functions"
1980   },
1981   {
1982     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
1983     TAPE_CTRL_ID_STOP,                  "stop tape"
1984   },
1985   {
1986     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
1987     TAPE_CTRL_ID_PAUSE,                 "pause tape"
1988   },
1989   {
1990     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
1991     TAPE_CTRL_ID_RECORD,                "record tape"
1992   },
1993   {
1994     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
1995     TAPE_CTRL_ID_PLAY,                  "play tape"
1996   },
1997   {
1998     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
1999     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
2000   },
2001   {
2002     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
2003     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
2004   }
2005 };
2006
2007 void CreateTapeButtons(void)
2008 {
2009   int i;
2010
2011   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2012   {
2013     int graphic = tapebutton_info[i].graphic;
2014     struct GraphicInfo *gfx = &graphic_info[graphic];
2015     struct XY *pos = tapebutton_info[i].pos;
2016     struct GadgetInfo *gi;
2017     int gd_x = gfx->src_x;
2018     int gd_y = gfx->src_y;
2019     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
2020     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
2021     int id = i;
2022
2023     gi = CreateGadget(GDI_CUSTOM_ID, id,
2024                       GDI_IMAGE_ID, graphic,
2025                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
2026                       GDI_X, VX + pos->x,
2027                       GDI_Y, VY + pos->y,
2028                       GDI_WIDTH, gfx->width,
2029                       GDI_HEIGHT, gfx->height,
2030                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
2031                       GDI_STATE, GD_BUTTON_UNPRESSED,
2032                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
2033                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
2034                       GDI_DIRECT_DRAW, FALSE,
2035                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
2036                       GDI_CALLBACK_ACTION, HandleTapeButtons,
2037                       GDI_END);
2038
2039     if (gi == NULL)
2040       Fail("cannot create gadget");
2041
2042     tape_gadget[id] = gi;
2043   }
2044 }
2045
2046 void FreeTapeButtons(void)
2047 {
2048   int i;
2049
2050   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2051     FreeGadget(tape_gadget[i]);
2052 }
2053
2054 void MapTapeEjectButton(void)
2055 {
2056   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2057   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2058 }
2059
2060 void MapTapeWarpButton(void)
2061 {
2062   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2063   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2064 }
2065
2066 void MapTapeButtons(void)
2067 {
2068   int i;
2069
2070   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2071     if (i != TAPE_CTRL_ID_EXTRA)
2072       MapGadget(tape_gadget[i]);
2073
2074   if (tape.recording || tape.playing)
2075     MapTapeWarpButton();
2076
2077   if (tape.show_game_buttons)
2078     MapGameButtonsOnTape();
2079 }
2080
2081 void UnmapTapeButtons(void)
2082 {
2083   int i;
2084
2085   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2086     UnmapGadget(tape_gadget[i]);
2087
2088   if (tape.show_game_buttons)
2089     UnmapGameButtonsOnTape();
2090 }
2091
2092 void RedrawTapeButtons(void)
2093 {
2094   int i;
2095
2096   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2097     RedrawGadget(tape_gadget[i]);
2098
2099   if (tape.show_game_buttons)
2100     RedrawGameButtonsOnTape();
2101 }
2102
2103 void RedrawOrRemapTapeButtons(void)
2104 {
2105   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
2106   {
2107     // tape buttons already mapped
2108     RedrawTapeButtons();
2109   }
2110   else
2111   {
2112     UnmapTapeButtons();
2113     MapTapeButtons();
2114   }
2115 }
2116
2117 static void HandleTapeButtonsExt(int id)
2118 {
2119   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
2120     return;
2121
2122   switch (id)
2123   {
2124     case TAPE_CTRL_ID_EJECT:
2125       TapeStop();
2126
2127       if (TAPE_IS_EMPTY(tape))
2128       {
2129         LoadTape(level_nr);
2130
2131         if (TAPE_IS_EMPTY(tape))
2132           Request("No tape for this level!", REQ_CONFIRM);
2133       }
2134       else
2135       {
2136         if (tape.changed)
2137           SaveTapeChecked(level_nr);
2138
2139         TapeErase();
2140       }
2141
2142       DrawCompleteVideoDisplay();
2143       break;
2144
2145     case TAPE_CTRL_ID_EXTRA:
2146       if (tape.playing)
2147       {
2148         tape.pause_before_end = !tape.pause_before_end;
2149
2150         DrawVideoDisplayCurrentState();
2151       }
2152       else if (tape.recording)
2153       {
2154         TapeSingleStep();
2155       }
2156
2157       break;
2158
2159     case TAPE_CTRL_ID_STOP:
2160       TapeStop();
2161
2162       break;
2163
2164     case TAPE_CTRL_ID_PAUSE:
2165       TapeTogglePause(TAPE_TOGGLE_MANUAL);
2166
2167       break;
2168
2169     case TAPE_CTRL_ID_RECORD:
2170       if (TAPE_IS_STOPPED(tape))
2171       {
2172         TapeStartGameRecording();
2173       }
2174       else if (tape.pausing)
2175       {
2176         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
2177           TapeAppendRecording();
2178         else
2179           TapeTogglePause(TAPE_TOGGLE_MANUAL);
2180       }
2181
2182       break;
2183
2184     case TAPE_CTRL_ID_PLAY:
2185       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
2186       {
2187         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
2188
2189         TapeTogglePause(TAPE_TOGGLE_MANUAL);
2190       }
2191
2192       if (TAPE_IS_EMPTY(tape))
2193         break;
2194
2195       if (TAPE_IS_STOPPED(tape))
2196       {
2197         TapeStartGamePlaying();
2198       }
2199       else if (tape.playing)
2200       {
2201         if (tape.pausing)                       // PAUSE -> PLAY
2202         {
2203           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
2204         }
2205         else if (!tape.fast_forward)            // PLAY -> FFWD
2206         {
2207           tape.fast_forward = TRUE;
2208         }
2209         else if (!tape.warp_forward)            // FFWD -> WARP
2210         {
2211           tape.warp_forward = TRUE;
2212         }
2213         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
2214         {
2215           tape.deactivate_display = TRUE;
2216
2217           TapeDeactivateDisplayOn();
2218         }
2219         else                                    // WARP BLIND -> PLAY
2220         {
2221           tape.fast_forward = FALSE;
2222           tape.warp_forward = FALSE;
2223           tape.deactivate_display = FALSE;
2224
2225           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
2226         }
2227
2228         DrawVideoDisplayCurrentState();
2229       }
2230
2231       break;
2232
2233     case TAPE_CTRL_ID_INSERT_SOLUTION:
2234       InsertSolutionTape();
2235
2236       break;
2237
2238     case TAPE_CTRL_ID_PLAY_SOLUTION:
2239       PlaySolutionTape();
2240
2241       break;
2242
2243     default:
2244       break;
2245   }
2246 }
2247
2248 static void HandleTapeButtons(struct GadgetInfo *gi)
2249 {
2250   HandleTapeButtonsExt(gi->custom_id);
2251 }
2252
2253 void HandleTapeButtonKeys(Key key)
2254 {
2255   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
2256   boolean extra_button_is_active = !eject_button_is_active;
2257
2258   if (key == setup.shortcut.tape_eject && eject_button_is_active)
2259     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
2260   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
2261     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
2262   else if (key == setup.shortcut.tape_stop)
2263     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
2264   else if (key == setup.shortcut.tape_pause)
2265     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
2266   else if (key == setup.shortcut.tape_record)
2267     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
2268   else if (key == setup.shortcut.tape_play)
2269     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
2270 }