fixed bug with not updating game panel when leaving invisible warp mode
[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 = (value / 100) % 100;
316       int month = month_index + 1;
317       int day = value % 100;
318
319       strcpy(s, (type & DATETIME_DATE_YYYY ? int2str(year4, 4) :
320                  type & DATETIME_DATE_YY   ? int2str(year2, 2) :
321                  type & DATETIME_DATE_MON  ? month_shortnames[month_index] :
322                  type & DATETIME_DATE_MM   ? int2str(month, 2) :
323                  type & DATETIME_DATE_DD   ? int2str(day, 2) : ""));
324
325       DrawText(xpos, ypos, s, pos->font);
326     }
327     else if ((type & DATETIME_TIME) && (state & VIDEO_STATE_TIME_ON))
328     {
329       char s[MAX_DATETIME_STRING_SIZE];
330       int hh = (value / 3600) % 100;
331       int min = value / 60;
332       int mm = (value / 60) % 60;
333       int ss = value % 60;
334
335       strcpy(s, (type & DATETIME_TIME_HH  ? int2str(hh, 2) :
336                  type & DATETIME_TIME_MIN ? int2str(min, 2) :
337                  type & DATETIME_TIME_MM  ? int2str(mm, 2) :
338                  type & DATETIME_TIME_SS  ? int2str(ss, 2) : ""));
339
340       DrawText(xpos, ypos, s, pos->font);
341     }
342     else if ((type & DATETIME_FRAME) && (state & VIDEO_STATE_FRAME_ON))
343     {
344       DrawText(xpos, ypos, int2str(value, pos->size), pos->font);
345     }
346   }
347 }
348
349 void DrawVideoDisplay(unsigned int state, unsigned int value)
350 {
351   DrawVideoDisplay_Graphics(state, value);
352   DrawVideoDisplay_DateTime(state, value);
353 }
354
355 static void DrawVideoDisplayLabel(unsigned int state)
356 {
357   DrawVideoDisplay(state, VIDEO_DISPLAY_LABEL_ONLY);
358 }
359
360 static void DrawVideoDisplaySymbol(unsigned int state)
361 {
362   DrawVideoDisplay(state, VIDEO_DISPLAY_SYMBOL_ONLY);
363 }
364
365 static void DrawVideoDisplayCurrentState(void)
366 {
367   int state = 0;
368
369   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
370
371   if (tape.pausing)
372     state |= VIDEO_STATE_PAUSE_ON;
373
374   if (tape.recording)
375   {
376     state |= VIDEO_STATE_REC_ON;
377
378     if (tape.single_step)
379       state |= VIDEO_STATE_1STEP_ON;
380   }
381   else if (tape.playing)
382   {
383     state |= VIDEO_STATE_PLAY_ON;
384
385     if (!tape.pausing)
386     {
387       if (tape.deactivate_display)
388         state |= VIDEO_STATE_WARP2_ON;
389       else if (tape.warp_forward)
390         state |= VIDEO_STATE_WARP_ON;
391       else if (tape.fast_forward)
392         state |= VIDEO_STATE_FFWD_ON;
393
394       if (tape.pause_before_end)
395         state |= VIDEO_STATE_PBEND_ON;
396     }
397   }
398
399   // draw labels and symbols separately to prevent labels overlapping symbols
400   DrawVideoDisplayLabel(state);
401   DrawVideoDisplaySymbol(state);
402 }
403
404 void DrawCompleteVideoDisplay(void)
405 {
406   struct GraphicInfo *g_tape = &graphic_info[IMG_BACKGROUND_TAPE];
407
408   // draw tape background
409   BlitBitmap(g_tape->bitmap, drawto, g_tape->src_x, g_tape->src_y,
410              gfx.vxsize, gfx.vysize, gfx.vx, gfx.vy);
411
412   // draw tape buttons (forced)
413   RedrawOrRemapTapeButtons();
414
415   DrawVideoDisplay(VIDEO_ALL_OFF, 0);
416
417   if (tape.recording)
418   {
419     DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
420     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
421     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
422     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
423
424     if (tape.pausing)
425       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
426   }
427   else if (tape.playing)
428   {
429     DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
430     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
431     DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
432     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
433
434     if (tape.pausing)
435       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
436   }
437   else if (tape.date && tape.length)
438   {
439     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
440     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
441     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
442   }
443
444   BlitBitmap(drawto, bitmap_db_door_2, gfx.vx, gfx.vy, gfx.vxsize, gfx.vysize,
445              0, 0);
446 }
447
448 void TapeDeactivateDisplayOn(void)
449 {
450   SetDrawDeactivationMask(REDRAW_FIELD);
451   audio.sound_deactivated = TRUE;
452 }
453
454 void TapeDeactivateDisplayOff(boolean redraw_display)
455 {
456   SetDrawDeactivationMask(REDRAW_NONE);
457   audio.sound_deactivated = FALSE;
458
459   if (redraw_display)
460   {
461     RedrawPlayfield();
462
463     UpdateGameDoorValues();
464     DrawGameDoorValues();
465   }
466 }
467
468
469 // ============================================================================
470 // tape logging functions
471 // ============================================================================
472
473 static char tape_patch_info[MAX_OUTPUT_LINESIZE];
474
475 static void PrintTapeReplayProgress(boolean replay_finished)
476 {
477   static unsigned int counter_last = -1;
478   unsigned int counter = Counter();
479   unsigned int counter_seconds  = counter / 1000;
480
481   if (!replay_finished)
482   {
483     unsigned int counter_delay = 50;
484
485     if (counter > counter_last + counter_delay)
486     {
487       PrintNoLog("\r");
488       PrintNoLog("Tape %03d %s[%02d:%02d]: [%02d:%02d] - playing tape ... ",
489                  level_nr,  tape_patch_info,
490                  tape.length_seconds / 60, tape.length_seconds % 60,
491                  TapeTime / 60, TapeTime % 60);
492
493       counter_last = counter;
494     }
495   }
496   else
497   {
498     float tape_length_seconds = GetTapeLengthSecondsFloat();
499
500     PrintNoLog("\r");
501     Print("Tape %03d %s[%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
502           level_nr, tape_patch_info,
503           tape.length_seconds / 60, tape.length_seconds % 60,
504           counter_seconds / 60, counter_seconds % 60, counter % 1000,
505           (float)counter / tape_length_seconds / 10,
506           tape.auto_play_level_fixed ? "solved and fixed" :
507           tape.auto_play_level_solved ? "solved" :
508           tape.auto_play_level_not_fixable ? "NOT SOLVED, NOT FIXED" :
509           "NOT SOLVED");
510
511     counter_last = -1;
512   }
513 }
514
515
516 // ============================================================================
517 // tape control functions
518 // ============================================================================
519
520 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
521 {
522   struct tm *lt = localtime(&epoch_seconds);
523
524   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
525 }
526
527 void TapeSetDateFromNow(void)
528 {
529   TapeSetDateFromEpochSeconds(time(NULL));
530 }
531
532 void TapeErase(void)
533 {
534   int i;
535
536   CopyTapeToUndoBuffer();
537
538   tape.counter = 0;
539   tape.length = 0;
540   tape.length_frames = 0;
541   tape.length_seconds = 0;
542
543   if (leveldir_current)
544     setString(&tape.level_identifier, leveldir_current->identifier);
545
546   tape.level_nr = level_nr;
547   tape.pos[tape.counter].delay = 0;
548   tape.changed = TRUE;
549
550   tape.random_seed = InitRND(level.random_seed);
551
552   tape.file_version = FILE_VERSION_ACTUAL;
553   tape.game_version = GAME_VERSION_ACTUAL;
554   tape.engine_version = level.game_version;
555
556   TapeSetDateFromNow();
557
558   for (i = 0; i < MAX_PLAYERS; i++)
559     tape.player_participates[i] = FALSE;
560
561   tape.centered_player_nr_next = -1;
562   tape.set_centered_player = FALSE;
563
564   // set flags for game actions to default values (may be overwritten later)
565   tape.use_key_actions = TRUE;
566   tape.use_mouse_actions = FALSE;
567 }
568
569 static void TapeRewind(void)
570 {
571   tape.counter = 0;
572   tape.delay_played = 0;
573   tape.pause_before_end = FALSE;
574   tape.recording = FALSE;
575   tape.playing = FALSE;
576   tape.fast_forward = FALSE;
577   tape.warp_forward = FALSE;
578   tape.deactivate_display = FALSE;
579   tape.auto_play = (global.autoplay_leveldir != NULL);
580   tape.auto_play_level_solved = FALSE;
581   tape.auto_play_level_fixed = FALSE;
582   tape.auto_play_level_not_fixable = FALSE;
583   tape.quick_resume = FALSE;
584   tape.single_step = FALSE;
585
586   tape.centered_player_nr_next = -1;
587   tape.set_centered_player = FALSE;
588
589   InitRND(tape.random_seed);
590 }
591
592 static void TapeSetRandomSeed(int random_seed)
593 {
594   tape.random_seed = InitRND(random_seed);
595 }
596
597 void TapeStartRecording(int random_seed)
598 {
599   if (!TAPE_IS_STOPPED(tape))
600     TapeStop();
601
602   TapeErase();
603   TapeRewind();
604   TapeSetRandomSeed(random_seed);
605
606   tape.recording = TRUE;
607
608   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
609   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
610   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
611   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
612
613   MapTapeWarpButton();
614
615   SetDrawDeactivationMask(REDRAW_NONE);
616   audio.sound_deactivated = FALSE;
617
618   // required here to update video display if tape door is closed
619   if (GetDoorState() & DOOR_CLOSE_2)
620     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
621 }
622
623 static void TapeStartGameRecording(void)
624 {
625   StartGameActions(network.enabled, TRUE, level.random_seed);
626 }
627
628 static void TapeAppendRecording(void)
629 {
630   if (!tape.playing || !tape.pausing)
631     return;
632
633   // stop playing
634   tape.playing = FALSE;
635   tape.fast_forward = FALSE;
636   tape.warp_forward = FALSE;
637   tape.pause_before_end = FALSE;
638   tape.deactivate_display = FALSE;
639
640   // start recording
641   tape.recording = TRUE;
642   tape.changed = TRUE;
643
644   // set current delay (for last played move)
645   tape.pos[tape.counter].delay = tape.delay_played;
646
647   // set current date
648   TapeSetDateFromNow();
649
650   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
651   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
652
653   UpdateAndDisplayGameControlValues();
654 }
655
656 void TapeHaltRecording(void)
657 {
658   tape.counter++;
659
660   // initialize delay for next tape entry (to be able to continue recording)
661   if (tape.counter < MAX_TAPE_LEN)
662     tape.pos[tape.counter].delay = 0;
663
664   tape.length = tape.counter;
665   tape.length_frames = GetTapeLengthFrames();
666   tape.length_seconds = GetTapeLengthSeconds();
667 }
668
669 void TapeStopRecording(void)
670 {
671   if (tape.recording)
672     TapeHaltRecording();
673
674   tape.recording = FALSE;
675   tape.pausing = FALSE;
676
677   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
678   MapTapeEjectButton();
679 }
680
681 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
682 {
683   int i;
684
685   if (tape.pos[tape.counter].delay > 0)         // already stored action
686   {
687     boolean changed_events = FALSE;
688
689     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
690       if (tape.pos[tape.counter].action[i] != action[i])
691         changed_events = TRUE;
692
693     if (changed_events || tape.pos[tape.counter].delay >= 255)
694     {
695       if (tape.counter >= MAX_TAPE_LEN - 1)
696         return FALSE;
697
698       tape.counter++;
699       tape.pos[tape.counter].delay = 0;
700     }
701     else
702       tape.pos[tape.counter].delay++;
703   }
704
705   if (tape.pos[tape.counter].delay == 0)        // store new action
706   {
707     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
708       tape.pos[tape.counter].action[i] = action[i];
709
710     tape.pos[tape.counter].delay++;
711   }
712
713   return TRUE;
714 }
715
716 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
717 {
718   byte action[MAX_TAPE_ACTIONS];
719   int i;
720
721   if (!tape.recording)          // (record action even when tape is paused)
722     return;
723
724   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
725     action[i] = action_raw[i];
726
727   if (tape.use_key_actions && tape.set_centered_player)
728   {
729     for (i = 0; i < MAX_PLAYERS; i++)
730       if (tape.centered_player_nr_next == i ||
731           tape.centered_player_nr_next == -1)
732         action[i] |= KEY_SET_FOCUS;
733
734     tape.set_centered_player = FALSE;
735   }
736
737   if (!TapeAddAction(action))
738     TapeStopRecording();
739 }
740
741 void TapeTogglePause(boolean toggle_mode)
742 {
743   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
744   {
745     // continue playing in normal mode
746     tape.fast_forward = FALSE;
747     tape.warp_forward = FALSE;
748     tape.deactivate_display = FALSE;
749
750     tape.pause_before_end = FALSE;
751   }
752
753   tape.pausing = !tape.pausing;
754
755   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
756     tape.single_step = FALSE;
757
758   DrawVideoDisplayCurrentState();
759
760   if (tape.deactivate_display)
761   {
762     if (tape.pausing)
763       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
764     else
765       TapeDeactivateDisplayOn();
766   }
767
768   if (tape.quick_resume)
769   {
770     tape.quick_resume = FALSE;
771
772     TapeStopWarpForward();
773     TapeAppendRecording();
774
775     if (!CheckEngineSnapshotSingle())
776       SaveEngineSnapshotSingle();
777
778     // restart step/move snapshots after quick loading tape
779     SaveEngineSnapshotToListInitial();
780
781     // do not map undo/redo buttons after quick loading tape
782     return;
783   }
784
785   if (game_status == GAME_MODE_PLAYING)
786   {
787     if (setup.show_snapshot_buttons && CheckEngineSnapshotList())
788     {
789       if (tape.pausing)
790         MapUndoRedoButtons();
791       else if (!tape.single_step)
792         UnmapUndoRedoButtons();
793     }
794
795     ModifyPauseButtons();
796   }
797 }
798
799 void TapeStartPlaying(void)
800 {
801   if (TAPE_IS_EMPTY(tape))
802     return;
803
804   if (!TAPE_IS_STOPPED(tape))
805     TapeStop();
806
807   TapeRewind();
808
809   tape.playing = TRUE;
810
811   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
812   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
813   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
814   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
815
816   MapTapeWarpButton();
817
818   SetDrawDeactivationMask(REDRAW_NONE);
819   audio.sound_deactivated = FALSE;
820 }
821
822 static void TapeStartGamePlaying(void)
823 {
824   TapeStartPlaying();
825
826   InitGame();
827 }
828
829 void TapeStopPlaying(void)
830 {
831   tape.playing = FALSE;
832   tape.pausing = FALSE;
833
834   if (tape.warp_forward)
835     TapeStopWarpForward();
836
837   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
838   MapTapeEjectButton();
839 }
840
841 byte *TapePlayAction(void)
842 {
843   int update_delay = FRAMES_PER_SECOND / 2;
844   boolean update_video_display = (FrameCounter % update_delay == 0);
845   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
846   static byte action[MAX_TAPE_ACTIONS];
847   int i;
848
849   if (!tape.playing || tape.pausing)
850     return NULL;
851
852   if (tape.pause_before_end)  // stop some seconds before end of tape
853   {
854     if (TapeTime > tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
855     {
856       TapeStopWarpForward();
857       TapeTogglePause(TAPE_TOGGLE_MANUAL);
858
859       return NULL;
860     }
861   }
862
863   if (tape.counter >= tape.length)      // end of tape reached
864   {
865     if (tape.warp_forward && !tape.auto_play)
866     {
867       TapeStopWarpForward();
868       TapeTogglePause(TAPE_TOGGLE_MANUAL);
869     }
870     else
871     {
872       TapeStop();
873     }
874
875     return NULL;
876   }
877
878   if (update_video_display && !tape.deactivate_display)
879   {
880     int state = 0;
881
882     if (tape.warp_forward)
883       state |= VIDEO_STATE_WARP(update_draw_label_on);
884     else if (tape.fast_forward)
885       state |= VIDEO_STATE_FFWD(update_draw_label_on);
886
887     if (tape.pause_before_end)
888       state |= VIDEO_STATE_PBEND(update_draw_label_on);
889
890     // draw labels and symbols separately to prevent labels overlapping symbols
891     DrawVideoDisplayLabel(state);
892     DrawVideoDisplaySymbol(state);
893   }
894
895   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
896     action[i] = tape.pos[tape.counter].action[i];
897
898 #if DEBUG_TAPE_WHEN_PLAYING
899   DebugContinued("", "%05d", FrameCounter);
900   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
901     DebugContinued("", "   %08x", action[i]);
902   DebugContinued("tape:play", "\n");
903 #endif
904
905   tape.set_centered_player = FALSE;
906   tape.centered_player_nr_next = -999;
907
908   if (tape.use_key_actions)
909   {
910     for (i = 0; i < MAX_PLAYERS; i++)
911     {
912       if (action[i] & KEY_SET_FOCUS)
913       {
914         tape.set_centered_player = TRUE;
915         tape.centered_player_nr_next =
916           (tape.centered_player_nr_next == -999 ? i : -1);
917       }
918
919       action[i] &= ~KEY_SET_FOCUS;
920     }
921   }
922
923   tape.delay_played++;
924   if (tape.delay_played >= tape.pos[tape.counter].delay)
925   {
926     tape.counter++;
927     tape.delay_played = 0;
928   }
929
930   if (tape.auto_play)
931     PrintTapeReplayProgress(FALSE);
932
933   return action;
934 }
935
936 void TapeStop(void)
937 {
938   if (tape.pausing)
939     TapeTogglePause(TAPE_TOGGLE_MANUAL);
940
941   TapeStopRecording();
942   TapeStopPlaying();
943
944   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
945
946   if (tape.date && tape.length)
947   {
948     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
949     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
950     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
951   }
952 }
953
954 unsigned int GetTapeLengthFrames(void)
955 {
956   unsigned int tape_length_frames = 0;
957   int i;
958
959   if (TAPE_IS_EMPTY(tape))
960     return 0;
961
962   for (i = 0; i < tape.length; i++)
963     tape_length_frames += tape.pos[i].delay;
964
965   return tape_length_frames;
966 }
967
968 unsigned int GetTapeLengthSeconds(void)
969 {
970   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
971 }
972
973 static float GetTapeLengthSecondsFloat(void)
974 {
975   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
976 }
977
978 static void TapeStartWarpForward(int mode)
979 {
980   tape.fast_forward = (mode & AUTOPLAY_FFWD);
981   tape.warp_forward = (mode & AUTOPLAY_WARP);
982   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
983
984   tape.pausing = FALSE;
985
986   if (tape.deactivate_display)
987     TapeDeactivateDisplayOn();
988
989   DrawVideoDisplayCurrentState();
990 }
991
992 static void TapeStopWarpForward(void)
993 {
994   tape.fast_forward = FALSE;
995   tape.warp_forward = FALSE;
996   tape.deactivate_display = FALSE;
997
998   tape.pause_before_end = FALSE;
999
1000   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1001
1002   DrawVideoDisplayCurrentState();
1003 }
1004
1005 static void TapeSingleStep(void)
1006 {
1007   if (network.enabled)
1008     return;
1009
1010   if (!tape.pausing)
1011     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1012
1013   tape.single_step = !tape.single_step;
1014
1015   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1016 }
1017
1018 void TapeQuickSave(void)
1019 {
1020   if (game_status == GAME_MODE_MAIN)
1021   {
1022     Request("No game that can be saved!", REQ_CONFIRM);
1023
1024     return;
1025   }
1026
1027   if (game_status != GAME_MODE_PLAYING)
1028     return;
1029
1030   if (tape.recording)
1031     TapeHaltRecording();        // prepare tape for saving on-the-fly
1032
1033   if (TAPE_IS_EMPTY(tape))
1034   {
1035     Request("No tape that can be saved!", REQ_CONFIRM);
1036
1037     return;
1038   }
1039
1040   if (SaveTapeChecked(tape.level_nr))
1041     SaveEngineSnapshotSingle();
1042 }
1043
1044 void TapeQuickLoad(void)
1045 {
1046   char *filename = getTapeFilename(level_nr);
1047
1048   if (!fileExists(filename))
1049   {
1050     Request("No tape for this level!", REQ_CONFIRM);
1051
1052     return;
1053   }
1054
1055   if (tape.recording && !Request("Stop recording and load tape?",
1056                                  REQ_ASK | REQ_STAY_CLOSED))
1057   {
1058     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1059
1060     return;
1061   }
1062
1063   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1064     return;
1065
1066   if (CheckEngineSnapshotSingle())
1067   {
1068     TapeStartGamePlaying();
1069
1070     LoadEngineSnapshotSingle();
1071
1072     DrawCompleteVideoDisplay();
1073
1074     tape.playing = TRUE;
1075     tape.pausing = TRUE;
1076
1077     TapeStopWarpForward();
1078     TapeAppendRecording();
1079
1080     // restart step/move snapshots after quick loading tape
1081     SaveEngineSnapshotToListInitial();
1082
1083     if (FrameCounter > 0)
1084       return;
1085   }
1086
1087   TapeStop();
1088   TapeErase();
1089
1090   LoadTape(level_nr);
1091
1092   if (!TAPE_IS_EMPTY(tape))
1093   {
1094     TapeStartGamePlaying();
1095     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1096
1097     tape.quick_resume = TRUE;
1098   }
1099   else  // this should not happen (basically checked above)
1100   {
1101     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1102
1103     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1104   }
1105 }
1106
1107 boolean hasSolutionTape(void)
1108 {
1109   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1110   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1111                             level.native_sp_level->demo.is_available);
1112
1113   return (tape_file_exists || level_has_tape);
1114 }
1115
1116 boolean InsertSolutionTape(void)
1117 {
1118   if (!hasSolutionTape())
1119   {
1120     Request("No solution tape for this level!", REQ_CONFIRM);
1121
1122     return FALSE;
1123   }
1124
1125   if (!TAPE_IS_STOPPED(tape))
1126     TapeStop();
1127
1128   // if tape recorder already contains a tape, remove it without asking
1129   TapeErase();
1130
1131   LoadSolutionTape(level_nr);
1132
1133   DrawCompleteVideoDisplay();
1134
1135   if (TAPE_IS_EMPTY(tape))
1136   {
1137     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1138
1139     return FALSE;
1140   }
1141
1142   return TRUE;
1143 }
1144
1145 boolean PlaySolutionTape(void)
1146 {
1147   if (!InsertSolutionTape())
1148     return FALSE;
1149
1150   TapeStartGamePlaying();
1151
1152   return TRUE;
1153 }
1154
1155 static boolean checkTapesFromSameLevel(struct TapeInfo *t1, struct TapeInfo *t2)
1156 {
1157   return (strEqual(t1->level_identifier, t2->level_identifier) &&
1158           t1->level_nr == t2->level_nr);
1159 }
1160
1161 static void CopyTape(struct TapeInfo *tape_from, struct TapeInfo *tape_to)
1162 {
1163   if (tape_to->level_identifier != NULL)
1164     checked_free(tape_to->level_identifier);
1165
1166   *tape_to = *tape_from;
1167
1168   tape_to->level_identifier = getStringCopy(tape_from->level_identifier);
1169 }
1170
1171 static void SwapTapes(struct TapeInfo *t1, struct TapeInfo *t2)
1172 {
1173   struct TapeInfo tmp = *t1;
1174
1175   *t1 = *t2;
1176   *t2 = tmp;
1177 }
1178
1179 static void CopyTapeToUndoBuffer(void)
1180 {
1181   // copy tapes to undo buffer if large enough (or larger than last undo tape)
1182   // or if the last undo tape is from a different level set or level number
1183   if (tape.length_seconds >= TAPE_MIN_SECONDS_FOR_UNDO_BUFFER ||
1184       tape.length_seconds >= tape_undo_buffer.length_seconds ||
1185       !checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1186   {
1187     CopyTape(&tape, &tape_undo_buffer);
1188   }
1189 }
1190
1191 void UndoTape(void)
1192 {
1193   // only undo tapes from same level set and with same level number
1194   if (!checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1195     return;
1196
1197   if (!TAPE_IS_STOPPED(tape))
1198     TapeStop();
1199
1200   // swap last recorded tape with undo buffer, so undo can be reversed
1201   SwapTapes(&tape, &tape_undo_buffer);
1202
1203   DrawCompleteVideoDisplay();
1204 }
1205
1206 void FixTape_ForceSinglePlayer(void)
1207 {
1208   int i;
1209
1210   /* fix single-player tapes that contain player input for more than one
1211      player (due to a bug in 3.3.1.2 and earlier versions), which results
1212      in playing levels with more than one player in multi-player mode,
1213      even though the tape was originally recorded in single-player mode */
1214
1215   // remove player input actions for all players but the first one
1216   for (i = 1; i < MAX_PLAYERS; i++)
1217     tape.player_participates[i] = FALSE;
1218
1219   tape.changed = TRUE;
1220 }
1221
1222
1223 // ----------------------------------------------------------------------------
1224 // tape autoplay functions
1225 // ----------------------------------------------------------------------------
1226
1227 void AutoPlayTapes(void)
1228 {
1229   static LevelDirTree *autoplay_leveldir = NULL;
1230   static boolean autoplay_initialized = FALSE;
1231   static int autoplay_level_nr = -1;
1232   static int num_levels_played = 0;
1233   static int num_levels_solved = 0;
1234   static int num_tapes_patched = 0;
1235   static int num_tape_missing = 0;
1236   static boolean level_failed[MAX_TAPES_PER_SET];
1237   static int patch_nr = 0;
1238   static char *patch_name[] =
1239   {
1240     "original tape",
1241     "em_random_bug",
1242     "screen_34x34",
1243
1244     NULL
1245   };
1246   static int patch_version_first[] =
1247   {
1248     VERSION_IDENT(0,0,0,0),
1249     VERSION_IDENT(3,3,1,0),
1250     VERSION_IDENT(0,0,0,0),
1251
1252     -1
1253   };
1254   static int patch_version_last[] =
1255   {
1256     VERSION_IDENT(9,9,9,9),
1257     VERSION_IDENT(4,0,1,1),
1258     VERSION_IDENT(4,2,2,0),
1259
1260     -1
1261   };
1262   static byte patch_property_bit[] =
1263   {
1264     TAPE_PROPERTY_NONE,
1265     TAPE_PROPERTY_EM_RANDOM_BUG,
1266     TAPE_PROPERTY_NONE,
1267
1268     -1
1269   };
1270   int i;
1271
1272   if (autoplay_initialized)
1273   {
1274     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1275     {
1276       if (tape.auto_play_level_solved)
1277       {
1278         if (patch_nr > 0)
1279         {
1280           // level solved by patched tape -- save fixed tape
1281           char *filename = getTapeFilename(level_nr);
1282           char *filename_orig = getStringCat2(filename, ".orig");
1283
1284           // create backup from old tape, if not yet existing
1285           if (!fileExists(filename_orig))
1286             rename(filename, filename_orig);
1287
1288           SaveTapeToFilename(filename);
1289
1290           tape.auto_play_level_fixed = TRUE;
1291           num_tapes_patched++;
1292         }
1293
1294         // continue with next tape
1295         patch_nr = 0;
1296       }
1297       else if (patch_name[patch_nr + 1] != NULL)
1298       {
1299         // level not solved by patched tape -- continue with next patch
1300         patch_nr++;
1301       }
1302       else
1303       {
1304         // level not solved by any patched tape -- continue with next tape
1305         tape.auto_play_level_not_fixable = TRUE;
1306         patch_nr = 0;
1307       }
1308     }
1309
1310     // just finished auto-playing tape
1311     PrintTapeReplayProgress(TRUE);
1312
1313     if (patch_nr == 0)
1314       num_levels_played++;
1315
1316     if (tape.auto_play_level_solved)
1317       num_levels_solved++;
1318
1319     if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1320       level_failed[level_nr] = !tape.auto_play_level_solved;
1321   }
1322   else
1323   {
1324     DrawCompleteVideoDisplay();
1325
1326     audio.sound_enabled = FALSE;
1327     setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1328
1329     autoplay_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1330                                                   global.autoplay_leveldir);
1331
1332     if (autoplay_leveldir == NULL)
1333       Fail("no such level identifier: '%s'", global.autoplay_leveldir);
1334
1335     leveldir_current = autoplay_leveldir;
1336
1337     if (autoplay_leveldir->first_level < 0)
1338       autoplay_leveldir->first_level = 0;
1339     if (autoplay_leveldir->last_level >= MAX_TAPES_PER_SET)
1340       autoplay_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1341
1342     autoplay_level_nr = autoplay_leveldir->first_level;
1343
1344     PrintLine("=", 79);
1345     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1346       Print("Automatically fixing level tapes\n");
1347     else
1348       Print("Automatically playing level tapes\n");
1349     PrintLine("-", 79);
1350     Print("Level series identifier: '%s'\n", autoplay_leveldir->identifier);
1351     Print("Level series name:       '%s'\n", autoplay_leveldir->name);
1352     Print("Level series author:     '%s'\n", autoplay_leveldir->author);
1353     Print("Number of levels:        %d\n",   autoplay_leveldir->levels);
1354     PrintLine("=", 79);
1355     Print("\n");
1356
1357     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1358       level_failed[i] = FALSE;
1359
1360     // only private tapes may be modified
1361     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1362       options.mytapes = TRUE;
1363
1364     autoplay_initialized = TRUE;
1365   }
1366
1367   while (1)
1368   {
1369     if (global.autoplay_mode != AUTOPLAY_MODE_FIX || patch_nr == 0)
1370       level_nr = autoplay_level_nr++;
1371
1372     if (level_nr > autoplay_leveldir->last_level)
1373       break;
1374
1375     // set patch info (required for progress output)
1376     strcpy(tape_patch_info, "");
1377     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1378       snprintf(tape_patch_info, MAX_OUTPUT_LINESIZE, "[%-13s] ",
1379                patch_name[patch_nr]);
1380
1381     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1382       continue;
1383
1384     TapeErase();
1385
1386     LoadLevel(level_nr);
1387
1388     if (level.no_level_file || level.no_valid_file)
1389     {
1390       Print("Tape %03d: (no level found)\n", level_nr);
1391
1392       continue;
1393     }
1394
1395 #if 0
1396     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
1397     Print("Tape %03d: (only testing level)\n", level_nr);
1398     continue;
1399 #endif
1400
1401     if (options.mytapes)
1402       LoadTape(level_nr);
1403     else
1404       LoadSolutionTape(level_nr);
1405
1406     if (tape.no_valid_file)
1407     {
1408       num_tape_missing++;
1409
1410       Print("Tape %03d: (no tape found)\n", level_nr);
1411
1412       continue;
1413     }
1414
1415     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1416     {
1417       boolean skip_patch = FALSE;
1418
1419       if (tape.engine_version < patch_version_first[patch_nr] ||
1420           tape.engine_version > patch_version_last[patch_nr])
1421       {
1422         Print("Tape %03d %s[%02d:%02d]: (%s %d.%d.%d.%d) - skipped.\n",
1423               level_nr,  tape_patch_info,
1424               tape.length_seconds / 60, tape.length_seconds % 60,
1425               "not suitable for version",
1426               (tape.engine_version / 1000000) % 100,
1427               (tape.engine_version / 10000  ) % 100,
1428               (tape.engine_version / 100    ) % 100,
1429               (tape.engine_version          ) % 100);
1430
1431         skip_patch = TRUE;
1432       }
1433
1434       if (strEqual(patch_name[patch_nr], "screen_34x34") &&
1435           tape.num_participating_players == 1)
1436       {
1437         Print("Tape %03d %s[%02d:%02d]: (%s) - skipped.\n",
1438               level_nr,  tape_patch_info,
1439               tape.length_seconds / 60, tape.length_seconds % 60,
1440               "not suitable for single player tapes");
1441
1442         skip_patch = TRUE;
1443       }
1444
1445       if (skip_patch)
1446       {
1447         if (patch_name[patch_nr + 1] != NULL)
1448         {
1449           // continue with next patch
1450           patch_nr++;
1451         }
1452         else
1453         {
1454           // continue with next tape
1455           patch_nr = 0;
1456         }
1457
1458         continue;
1459       }
1460
1461       if (strEqual(patch_name[patch_nr], "screen_34x34"))
1462       {
1463         tape.scr_fieldx = SCR_FIELDX_DEFAULT * 2;
1464         tape.scr_fieldy = SCR_FIELDY_DEFAULT * 2;
1465       }
1466       else
1467       {
1468         tape.property_bits |= patch_property_bit[patch_nr];
1469       }
1470     }
1471
1472     InitCounter();
1473
1474     TapeStartGamePlaying();
1475     TapeStartWarpForward(global.autoplay_mode);
1476
1477     return;
1478   }
1479
1480   Print("\n");
1481   PrintLine("=", 79);
1482   Print("Number of levels played: %d\n", num_levels_played);
1483   Print("Number of levels solved: %d (%d%%)\n", num_levels_solved,
1484         (num_levels_played ? num_levels_solved * 100 / num_levels_played : 0));
1485   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1486     Print("Number of tapes fixed: %d\n", num_tapes_patched);
1487   PrintLine("-", 79);
1488   Print("Summary (for automatic parsing by scripts):\n");
1489   Print("LEVELDIR [%s] '%s', SOLVED %d/%d (%d%%)",
1490         (num_levels_played == num_levels_solved ? " OK " : "WARN"),
1491         autoplay_leveldir->identifier, num_levels_solved, num_levels_played,
1492         (num_levels_played ? num_levels_solved * 100 / num_levels_played : 0));
1493
1494   if (num_levels_played != num_levels_solved)
1495   {
1496     Print(", FAILED:");
1497     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1498       if (level_failed[i])
1499         Print(" %03d", i);
1500   }
1501
1502   Print("\n");
1503   PrintLine("=", 79);
1504
1505   CloseAllAndExit(0);
1506 }
1507
1508
1509 // ----------------------------------------------------------------------------
1510 // tape patch functions
1511 // ----------------------------------------------------------------------------
1512
1513 static boolean PatchTape(struct TapeInfo *tape, char *mode)
1514 {
1515   Print("[%d.%d.%d.%d]: ",
1516         (tape->engine_version / 1000000) % 100,
1517         (tape->engine_version / 10000  ) % 100,
1518         (tape->engine_version / 100    ) % 100,
1519         (tape->engine_version          ) % 100);
1520
1521   if (strEqual(mode, "info"))
1522   {
1523     Print("property bits == 0x%02x\n", tape->property_bits);
1524
1525     return FALSE;
1526   }
1527
1528   boolean unpatch_tape = FALSE;
1529   boolean use_property_bit = FALSE;
1530   byte property_bitmask = 0;
1531
1532   if (strSuffix(mode, ":0") ||
1533       strSuffix(mode, ":off") ||
1534       strSuffix(mode, ":clear"))
1535     unpatch_tape = TRUE;
1536
1537   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
1538   {
1539     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
1540     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
1541         tape->engine_version >= VERSION_IDENT(4,0,1,2))
1542     {
1543       Print("This tape version cannot be patched against EM random bug!\n");
1544
1545       return FALSE;
1546     }
1547
1548     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
1549
1550     use_property_bit = TRUE;
1551   }
1552   else if (strEqual(mode, "screen_34x34") || strPrefix(mode, "screen_34x34:"))
1553   {
1554     // this bug only affects team mode tapes
1555     if (tape->num_participating_players == 1)
1556     {
1557       Print("Only team mode tapes can be patched against screen size bug!\n");
1558
1559       return FALSE;
1560     }
1561
1562     // this bug (that always existed before) was fixed in version 4.2.2.1
1563     if (tape->engine_version >= VERSION_IDENT(4,2,2,1))
1564     {
1565       Print("This tape version cannot be patched against screen size bug!\n");
1566
1567       return FALSE;
1568     }
1569
1570     int factor = (unpatch_tape ? 1 : 2);
1571     int scr_fieldx_new = SCR_FIELDX_DEFAULT * factor;
1572     int scr_fieldy_new = SCR_FIELDY_DEFAULT * factor;
1573
1574     if (scr_fieldx_new == tape->scr_fieldx &&
1575         scr_fieldy_new == tape->scr_fieldy)
1576     {
1577       Print("Tape already patched for '%s'!\n", mode);
1578
1579       return FALSE;
1580     }
1581
1582     tape->scr_fieldx = scr_fieldx_new;
1583     tape->scr_fieldy = scr_fieldy_new;
1584   }
1585   else
1586   {
1587     Print("Unknown patch mode '%s'!\n", mode);
1588
1589     return FALSE;
1590   }
1591
1592   // patching tapes using property bits may be used for several patch modes
1593   if (use_property_bit)
1594   {
1595     byte property_bits = tape->property_bits;
1596     boolean set_property_bit = (unpatch_tape ? FALSE : TRUE);
1597
1598     if (set_property_bit)
1599       property_bits |= property_bitmask;
1600     else
1601       property_bits &= ~property_bitmask;
1602
1603     if (property_bits == tape->property_bits)
1604     {
1605       Print("Tape already patched for '%s'!\n", mode);
1606
1607       return FALSE;
1608     }
1609
1610     tape->property_bits = property_bits;
1611   }
1612
1613   Print("Patching for '%s' ... ", mode);
1614
1615   return TRUE;
1616 }
1617
1618 void PatchTapes(void)
1619 {
1620   static LevelDirTree *patchtapes_leveldir = NULL;
1621   static int num_tapes_found = 0;
1622   static int num_tapes_patched = 0;
1623   char *mode = global.patchtapes_mode;
1624   int i;
1625
1626   if (strEqual(mode, "help"))
1627   {
1628     PrintLine("=", 79);
1629     Print("Supported patch modes:\n");
1630     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
1631     Print("- \"screen_34x34\"    - force visible playfield size of 34 x 34\n");
1632     PrintLine("-", 79);
1633     Print("Supported modifiers:\n");
1634     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
1635     PrintLine("=", 79);
1636
1637     CloseAllAndExit(0);
1638   }
1639
1640   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1641                                                   global.patchtapes_leveldir);
1642
1643   if (patchtapes_leveldir == NULL)
1644     Fail("no such level identifier: '%s'", global.patchtapes_leveldir);
1645
1646   leveldir_current = patchtapes_leveldir;
1647
1648   if (patchtapes_leveldir->first_level < 0)
1649     patchtapes_leveldir->first_level = 0;
1650   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
1651     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1652
1653   PrintLine("=", 79);
1654   Print("Patching level tapes for patch mode '%s'\n", mode);
1655   PrintLine("-", 79);
1656   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
1657   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
1658   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
1659   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
1660   PrintLine("=", 79);
1661   Print("\n");
1662
1663   int first_level = patchtapes_leveldir->first_level;
1664   int last_level = patchtapes_leveldir->last_level;
1665
1666   for (i = first_level; i <= last_level; i++)
1667   {
1668     if (!global.patchtapes_all && !global.patchtapes_level[i])
1669       continue;
1670
1671     Print("Tape %03d: ", i);
1672
1673     TapeErase();
1674     LoadTape(i);
1675
1676     if (tape.no_valid_file)
1677     {
1678       Print("(no tape found)\n");
1679
1680       continue;
1681     }
1682
1683     num_tapes_found++;
1684
1685     if (PatchTape(&tape, mode))
1686     {
1687       char *filename = getTapeFilename(i);
1688       char *filename_orig = getStringCat2(filename, ".orig");
1689
1690       if (!fileExists(filename_orig))
1691         rename(filename, filename_orig);
1692
1693       SaveTapeToFilename(filename);
1694
1695       Print("patched tape saved.\n");
1696
1697       num_tapes_patched++;
1698     }
1699   }
1700
1701   Print("\n");
1702   PrintLine("=", 79);
1703   Print("Number of tapes found: %d\n", num_tapes_found);
1704   Print("Number of tapes patched: %d\n", num_tapes_patched);
1705   PrintLine("=", 79);
1706
1707   CloseAllAndExit(0);
1708 }
1709
1710
1711 // ---------- new tape button stuff -------------------------------------------
1712
1713 static struct
1714 {
1715   int graphic;
1716   struct XY *pos;
1717   int gadget_id;
1718   char *infotext;
1719 } tapebutton_info[NUM_TAPE_BUTTONS] =
1720 {
1721   {
1722     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
1723     TAPE_CTRL_ID_EJECT,                 "eject tape"
1724   },
1725   {
1726     // (same position as "eject" button)
1727     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
1728     TAPE_CTRL_ID_EXTRA,                 "extra functions"
1729   },
1730   {
1731     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
1732     TAPE_CTRL_ID_STOP,                  "stop tape"
1733   },
1734   {
1735     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
1736     TAPE_CTRL_ID_PAUSE,                 "pause tape"
1737   },
1738   {
1739     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
1740     TAPE_CTRL_ID_RECORD,                "record tape"
1741   },
1742   {
1743     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
1744     TAPE_CTRL_ID_PLAY,                  "play tape"
1745   },
1746   {
1747     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
1748     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
1749   },
1750   {
1751     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
1752     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
1753   }
1754 };
1755
1756 void CreateTapeButtons(void)
1757 {
1758   int i;
1759
1760   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1761   {
1762     int graphic = tapebutton_info[i].graphic;
1763     struct GraphicInfo *gfx = &graphic_info[graphic];
1764     struct XY *pos = tapebutton_info[i].pos;
1765     struct GadgetInfo *gi;
1766     int gd_x = gfx->src_x;
1767     int gd_y = gfx->src_y;
1768     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
1769     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
1770     int id = i;
1771
1772     gi = CreateGadget(GDI_CUSTOM_ID, id,
1773                       GDI_IMAGE_ID, graphic,
1774                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
1775                       GDI_X, VX + pos->x,
1776                       GDI_Y, VY + pos->y,
1777                       GDI_WIDTH, gfx->width,
1778                       GDI_HEIGHT, gfx->height,
1779                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
1780                       GDI_STATE, GD_BUTTON_UNPRESSED,
1781                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
1782                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
1783                       GDI_DIRECT_DRAW, FALSE,
1784                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
1785                       GDI_CALLBACK_ACTION, HandleTapeButtons,
1786                       GDI_END);
1787
1788     if (gi == NULL)
1789       Fail("cannot create gadget");
1790
1791     tape_gadget[id] = gi;
1792   }
1793 }
1794
1795 void FreeTapeButtons(void)
1796 {
1797   int i;
1798
1799   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1800     FreeGadget(tape_gadget[i]);
1801 }
1802
1803 void MapTapeEjectButton(void)
1804 {
1805   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1806   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1807 }
1808
1809 void MapTapeWarpButton(void)
1810 {
1811   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1812   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1813 }
1814
1815 void MapTapeButtons(void)
1816 {
1817   int i;
1818
1819   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1820     if (i != TAPE_CTRL_ID_EXTRA)
1821       MapGadget(tape_gadget[i]);
1822
1823   if (tape.recording || tape.playing)
1824     MapTapeWarpButton();
1825
1826   if (tape.show_game_buttons)
1827     MapGameButtonsOnTape();
1828 }
1829
1830 void UnmapTapeButtons(void)
1831 {
1832   int i;
1833
1834   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1835     UnmapGadget(tape_gadget[i]);
1836
1837   if (tape.show_game_buttons)
1838     UnmapGameButtonsOnTape();
1839 }
1840
1841 void RedrawTapeButtons(void)
1842 {
1843   int i;
1844
1845   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1846     RedrawGadget(tape_gadget[i]);
1847
1848   if (tape.show_game_buttons)
1849     RedrawGameButtonsOnTape();
1850 }
1851
1852 void RedrawOrRemapTapeButtons(void)
1853 {
1854   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
1855   {
1856     // tape buttons already mapped
1857     RedrawTapeButtons();
1858   }
1859   else
1860   {
1861     UnmapTapeButtons();
1862     MapTapeButtons();
1863   }
1864 }
1865
1866 static void HandleTapeButtonsExt(int id)
1867 {
1868   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
1869     return;
1870
1871   switch (id)
1872   {
1873     case TAPE_CTRL_ID_EJECT:
1874       TapeStop();
1875
1876       if (TAPE_IS_EMPTY(tape))
1877       {
1878         LoadTape(level_nr);
1879
1880         if (TAPE_IS_EMPTY(tape))
1881           Request("No tape for this level!", REQ_CONFIRM);
1882       }
1883       else
1884       {
1885         if (tape.changed)
1886           SaveTapeChecked(level_nr);
1887
1888         TapeErase();
1889       }
1890
1891       DrawCompleteVideoDisplay();
1892       break;
1893
1894     case TAPE_CTRL_ID_EXTRA:
1895       if (tape.playing)
1896       {
1897         tape.pause_before_end = !tape.pause_before_end;
1898
1899         DrawVideoDisplayCurrentState();
1900       }
1901       else if (tape.recording)
1902       {
1903         TapeSingleStep();
1904       }
1905
1906       break;
1907
1908     case TAPE_CTRL_ID_STOP:
1909       TapeStop();
1910
1911       break;
1912
1913     case TAPE_CTRL_ID_PAUSE:
1914       TapeTogglePause(TAPE_TOGGLE_MANUAL);
1915
1916       break;
1917
1918     case TAPE_CTRL_ID_RECORD:
1919       if (TAPE_IS_STOPPED(tape))
1920       {
1921         TapeStartGameRecording();
1922       }
1923       else if (tape.pausing)
1924       {
1925         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
1926           TapeAppendRecording();
1927         else
1928           TapeTogglePause(TAPE_TOGGLE_MANUAL);
1929       }
1930
1931       break;
1932
1933     case TAPE_CTRL_ID_PLAY:
1934       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
1935       {
1936         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
1937
1938         TapeTogglePause(TAPE_TOGGLE_MANUAL);
1939       }
1940
1941       if (TAPE_IS_EMPTY(tape))
1942         break;
1943
1944       if (TAPE_IS_STOPPED(tape))
1945       {
1946         TapeStartGamePlaying();
1947       }
1948       else if (tape.playing)
1949       {
1950         if (tape.pausing)                       // PAUSE -> PLAY
1951         {
1952           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
1953         }
1954         else if (!tape.fast_forward)            // PLAY -> FFWD
1955         {
1956           tape.fast_forward = TRUE;
1957         }
1958         else if (!tape.warp_forward)            // FFWD -> WARP
1959         {
1960           tape.warp_forward = TRUE;
1961         }
1962         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
1963         {
1964           tape.deactivate_display = TRUE;
1965
1966           TapeDeactivateDisplayOn();
1967         }
1968         else                                    // WARP BLIND -> PLAY
1969         {
1970           tape.fast_forward = FALSE;
1971           tape.warp_forward = FALSE;
1972           tape.deactivate_display = FALSE;
1973
1974           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1975         }
1976
1977         DrawVideoDisplayCurrentState();
1978       }
1979
1980       break;
1981
1982     case TAPE_CTRL_ID_INSERT_SOLUTION:
1983       InsertSolutionTape();
1984
1985       break;
1986
1987     case TAPE_CTRL_ID_PLAY_SOLUTION:
1988       PlaySolutionTape();
1989
1990       break;
1991
1992     default:
1993       break;
1994   }
1995 }
1996
1997 static void HandleTapeButtons(struct GadgetInfo *gi)
1998 {
1999   HandleTapeButtonsExt(gi->custom_id);
2000 }
2001
2002 void HandleTapeButtonKeys(Key key)
2003 {
2004   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
2005   boolean extra_button_is_active = !eject_button_is_active;
2006
2007   if (key == setup.shortcut.tape_eject && eject_button_is_active)
2008     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
2009   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
2010     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
2011   else if (key == setup.shortcut.tape_stop)
2012     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
2013   else if (key == setup.shortcut.tape_pause)
2014     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
2015   else if (key == setup.shortcut.tape_record)
2016     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
2017   else if (key == setup.shortcut.tape_play)
2018     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
2019 }