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