Subversion Repositories Games.Chess Giants

Rev

Rev 1 | Rev 66 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 pmbaty 1
// pgnfile.cpp
2
 
3
#include "common.h"
4
 
5
 
6
// handy definitions
7
#define COPY_TIL_LAST_QUOTEMARK(dest,source) \
8
{ \
9
   mbstowcs_s (&converted_count, (dest), WCHAR_SIZEOF (dest), (source), WCHAR_SIZEOF (dest)); \
10
   for (char_index = wcslen (dest) - 1; char_index >= 0; char_index--) \
11
      if ((dest)[char_index] == L'"') \
12
      { \
13
         (dest)[char_index] = 0; \
14
         break; \
15
      } \
16
}
17
 
18
 
19
// prototypes of local functions
20
static void PGNFile_GameList_Init (int entry_count);
21
static void PGNFile_GameList_Shutdown (void);
22
static char *sgets (char *destination_line, int max_length, char *source_buffer);
23
 
24
 
25
bool PGNFile_Load (const wchar_t *pgnfile_pathname)
26
{
27
   // this function loads a PGN file and builds the game databases of the games described in this file
28
 
29
   char line_buffer[256]; // PGN files have 256 chars max per line by design
30
   char *file_data; // mallocated
31
   char *buffer;
32
   int file_size;
33
   int file_index;
34
   int char_index;
35
   int entry_count;
36
   FILE *fp;
37
   size_t converted_count; // used by the STRING_TO_CHAR macro
38
 
39
   // try to open file for reading in BINARY mode so as NOT to convert end of lines
40
   _wfopen_s (&fp, pgnfile_pathname, L"rb");
41
   if (fp == NULL)
42
      return (false); // on error, cancel
43
 
44
   // get file length
45
   fseek (fp, 0, SEEK_END);
46
   file_size = ftell (fp);
47
   fseek (fp, 0, SEEK_SET);
48
 
49
   // mallocate space for it and read it all at once
50
   file_data = (char *) SAFE_malloc (file_size, sizeof (char), false);
51
   fread (file_data, file_size, 1, fp);
52
   fclose (fp); // we no longer need the file, so close it
53
 
54
   // now the file is fully loaded in memory
55
 
56
   // read line per line and count the number of games
57
   buffer = file_data;
58
   entry_count = 0;
59
   while ((buffer = sgets (line_buffer, sizeof (line_buffer), buffer)) != NULL)
60
      if (strncmp (line_buffer, "[Event \"", 8) == 0)
61
         entry_count++; // we know now one game more
62
 
63
   // now prepare the games database for "entry_count" games
64
   PGNFile_GameList_Init (entry_count);
65
 
66
   // read line per line
67
   buffer = file_data;
68
   entry_count = 0;
69
   file_index = 0;
70
   while ((buffer = sgets (line_buffer, sizeof (line_buffer), buffer)) != NULL)
71
   {
72
      // is it a new game ?
73
      if (strncmp (line_buffer, "[Event \"", 8) == 0)
74
      {
75
         COPY_TIL_LAST_QUOTEMARK (games[entry_count].event_str, &line_buffer[8]); // copy event
76
 
77
         // assume a default "standard chess" start position unless told otherwise later
78
         wcscpy_s (games[entry_count].fen_str, WCHAR_SIZEOF (games[entry_count].fen_str), FENSTARTUP_STANDARDCHESS);
79
 
80
         games[entry_count].gamedata_start = 0; // reset gamedata so far
81
         entry_count++; // we know now one game more
82
      }
83
 
84
      // else have we found a game already ?
85
      else if (entry_count > 0)
86
      {
87
         // is it one of the known tags ?
88
         if (line_buffer[0] == '[')
89
         {
90
            if (strncmp (&line_buffer[1], "Site \"", 6) == 0)
91
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].site_str, &line_buffer[7]) // copy site
92
            else if (strncmp (&line_buffer[1], "Date \"", 6) == 0)
93
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].date_str, &line_buffer[7]) // copy date
94
            else if (strncmp (&line_buffer[1], "Round \"", 7) == 0)
95
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].round_str, &line_buffer[8]) // copy round
96
            else if (strncmp (&line_buffer[1], "White \"", 7) == 0)
97
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].white_str, &line_buffer[8]) // copy white
98
            else if (strncmp (&line_buffer[1], "Black \"", 7) == 0)
99
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].black_str, &line_buffer[8]) // copy black
100
            else if (strncmp (&line_buffer[1], "Result \"", 8) == 0)
101
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].result_str, &line_buffer[9]) // copy results
102
            else if (strncmp (&line_buffer[1], "ECO \"", 5) == 0)
103
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].eco_str, &line_buffer[6]) // copy ECO code
104
            else if (strncmp (&line_buffer[1], "FEN \"", 5) == 0)
105
               COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].fen_str, &line_buffer[6]) // copy FEN string
106
         }
107
 
108
         // else is it the beginning of a game ?
109
         else if (strncmp (line_buffer, "1.", 2) == 0)
110
            games[entry_count - 1].gamedata_start = file_index; // remember where this game starts
111
      }
112
 
113
      file_index = buffer - file_data; // save current file pointer index
114
   }
115
 
116
   // we no longer need the file data space, so free it
117
   SAFE_free ((void **) &file_data);
118
 
119
   return (true); // finished, return TRUE
120
}
121
 
122
 
123
bool PGNFile_LoadGame (board_t *board, const wchar_t *pgnfile_pathname, pgngame_t *game)
124
{
125
   // this function loads and parses a game data in a PGN file. If the selected game is NULL, it means that
126
   // the user didn't want to chose any game at all, so just free the games list and return a success value.
127
 
128
   static wchar_t pgn_comment[65536]; // declared static so as not to reallocate it
129
 
130
   char *file_data; // mallocated
131
   boardmove_t new_move;
132
   int file_size;
133
   int length;
134
   int char_index;
135
   int fieldstart;
136
   int fieldstop;
137
   char movenumber_string[8];
138
   FILE *fp;
139
 
140
   // did we chose NO game ?
141
   if (game == NULL)
142
   {
143
      PGNFile_GameList_Shutdown (); // free the games list
144
      return (true); // return success as there's nothing to load
145
   }
146
 
147
   // try to open file for reading in BINARY mode so as NOT to convert end of lines
148
   _wfopen_s (&fp, pgnfile_pathname, L"rb");
149
   if (fp == NULL)
150
   {
151
      PGNFile_GameList_Shutdown (); // free the games list
152
      return (false); // on error, cancel
153
   }
154
 
155
   // get file length
156
   fseek (fp, 0, SEEK_END);
157
   file_size = ftell (fp);
158
   fseek (fp, 0, SEEK_SET);
159
 
160
   // mallocate space for it and read it all at once
161
   file_data = (char *) SAFE_malloc (file_size, sizeof (char), false);
162
   fread (file_data, file_size, 1, fp);
163
   fclose (fp); // we no longer need the file, so close it
164
 
165
   // now the file is fully loaded in memory
166
 
167
   // reset the board (but NOT the players, just their view angles)
168
   Board_Reset (board, game->fen_str);
169
   animation_endtime = current_time + 2.0f; // HACK: this sorta prevents the "load file" dialog box trailing clicks to be misinterpreted
170
 
171
   // while we've not parsed til the end of game...
172
   char_index = game->gamedata_start;
173
   new_move.source[0] = -1;
174
   new_move.source[1] = -1;
175
   new_move.target[0] = -1;
176
   new_move.target[1] = -1;
177
   new_move.promotion_type = 0;
178
   pgn_comment[0] = 0;
179
   for (;;)
180
   {
181
      // build the move number string
182
      sprintf_s (movenumber_string, sizeof (movenumber_string), "%d.", 1 + board->move_count / 2);
183
 
184
      // is it a space ?
185
      if (isspace (file_data[char_index]))
186
      {
187
         char_index++; // if so, skip it
188
         continue; // and proceed to the next data
189
      }
190
 
191
      // else is what we're reading a move number ?
192
      else if (strncmp (&file_data[char_index], movenumber_string, strlen (movenumber_string)) == 0)
193
      {
194
         char_index += strlen (movenumber_string); // if so, skip it
195
         continue; // and proceed to the next data
196
      }
197
 
198
      // else is it a dot ?
199
      else if (file_data[char_index] == '.')
200
      {
201
         char_index++; // if so, skip it
202
         continue; // and proceed to the next data
203
      }
204
 
205
      // else is it an en passant notification ?
206
      else if (strncmp (&file_data[char_index], "e.p.", 4) == 0)
207
      {
208
         char_index += 4; // this notification is superfluous, skip it
209
         continue; // and proceed to the next data
210
      }
211
 
212
      // else is it a comment ?
213
      else if (file_data[char_index] == '{')
214
      {
215
         fieldstart = char_index + 1; // skip the leading brace
216
 
217
         while ((fieldstart < file_size) && isspace (file_data[fieldstart]))
218
            fieldstart++; // skip any leading spaces
219
 
65 pmbaty 220
         // move through all the other characters...
1 pmbaty 221
         for (fieldstop = fieldstart; fieldstop < file_size; fieldstop++)
222
            if (file_data[fieldstop] == '}')
223
               break; // and stop at the first closing brace we find
224
 
225
         char_index = fieldstop + 1; // remember where to continue reading (that is, after the closing brace)
226
 
227
         while ((fieldstop > 0) && isspace (file_data[fieldstop]))
228
            fieldstop--; // chop off any trailing spaces
229
 
230
         file_data[fieldstop] = 0; // break the string at this location
231
 
232
         // now copy out the commentary by appending it to the one we know already
233
         if (pgn_comment[0] != 0)
234
            wcscat_s (pgn_comment, WCHAR_SIZEOF (pgn_comment), L" ");
235
         length = wcslen (pgn_comment);
236
         ConvertToWideChar (&pgn_comment[length], WCHAR_SIZEOF (pgn_comment) - length, &file_data[fieldstart]);
237
         ConvertCRLFsToSingleSpaces (pgn_comment); // linearize string
238
 
239
         continue; // and proceed to the next data
240
      }
241
 
65 pmbaty 242
      // else is it a numeric annotation glyph ? if so, just ignore it (FIXME: better support this)
243
      else if (file_data[char_index] == '$')
244
      {
245
         while ((char_index < file_size) && !isspace (file_data[char_index]))
246
            char_index++; // figure out where it stops
247
         while ((char_index < file_size) && isspace (file_data[char_index]))
248
            char_index++; // figure out where the next word starts
249
 
250
         continue; // and proceed to the next data
251
      }
252
 
1 pmbaty 253
      // else is it a game result ?
254
      else if ((strncmp (&file_data[char_index], "1/2-1/2", 7) == 0)
255
               || (strncmp (&file_data[char_index], "1-0", 3) == 0)
256
               || (strncmp (&file_data[char_index], "0-1", 3) == 0)
257
               || (file_data[char_index] == '*'))
258
      {
259
         // if there's a move pending, validate it
260
         if ((new_move.source[0] != -1) && (new_move.source[1] != -1) && (new_move.target[0] != -1) && (new_move.target[1] != -1))
261
         {
262
            Board_AppendMove (board, new_move.source[0], new_move.source[1], new_move.target[0], new_move.target[1], new_move.promotion_type, pgn_comment); // save move
263
            board->has_playerchanged = true; // switch players
264
            new_move.part = PART_NONE;
265
            new_move.source[0] = -1;
266
            new_move.source[1] = -1;
267
            new_move.target[0] = -1;
268
            new_move.target[1] = -1;
269
            new_move.promotion_type = 0;
270
            pgn_comment[0] = 0; // reset comment
271
         }
272
 
273
         break; // we've finished reading the game
274
      }
275
 
276
      // else it must be a move data
277
      else
278
      {
279
         // if there's a move pending, validate it
280
         if ((new_move.source[0] != -1) && (new_move.source[1] != -1) && (new_move.target[0] != -1) && (new_move.target[1] != -1))
281
         {
282
            Board_AppendMove (board, new_move.source[0], new_move.source[1], new_move.target[0], new_move.target[1], new_move.promotion_type, pgn_comment); // save move
283
            board->has_playerchanged = true; // switch players
284
            new_move.part = PART_NONE;
285
            new_move.source[0] = -1;
286
            new_move.source[1] = -1;
287
            new_move.target[0] = -1;
288
            new_move.target[1] = -1;
289
            new_move.promotion_type = 0;
290
            pgn_comment[0] = 0; // reset comment
291
         }
292
 
293
         // convert the move string data to wide char
294
         ConvertToWideChar (new_move.pgntext, WCHAR_SIZEOF (new_move.pgntext), &file_data[char_index]);
295
 
296
         // evaluate the string in Standard Algebraic Notation and find the source, destination, part type and promotion
297
         if (!Move_SetupFromSAN (&board->moves[board->move_count - 1], &new_move, Board_ColorToMove (board)))
298
         {
299
            PGNFile_GameList_Shutdown (); // free the games list
300
            SAFE_free ((void **) &file_data); // free the file data space
301
            return (false); // on error, cancel
302
         }
303
 
304
         // find where it stops
305
         while ((char_index < file_size) && !isspace (file_data[char_index]))
306
            char_index++; // reach the next space
307
 
308
         char_index++; // remember where to continue reading (that is, after the next space)
309
         continue; // and proceed to the next data
310
      }
311
   }
312
 
313
   // save the players' names
314
   wcscpy_s (board->players[COLOR_WHITE].name, WCHAR_SIZEOF (board->players[COLOR_WHITE].name), game->white_str);
315
   wcscpy_s (board->players[COLOR_BLACK].name, WCHAR_SIZEOF (board->players[COLOR_BLACK].name), game->black_str);
316
 
317
   // we loaded the game we want, we no longer need the games array
318
   PGNFile_GameList_Shutdown ();
319
 
320
   // we no longer need the file data space, so free it
321
   SAFE_free ((void **) &file_data);
322
 
323
   return (true); // game loaded successfully, return TRUE
324
}
325
 
326
 
327
bool PGNFile_Save (board_t *board, const wchar_t *pgnfile_pathname)
328
{
329
   // this function writes a PGN file in the standard, international Chess format
330
 
331
   FILE *fp;
332
   wchar_t machine_name[256];
333
   unsigned long buffer_size;
334
   wchar_t result_string[16];
335
   time_t rawtime;
336
   struct tm timeinfo;
337
   boardmove_t *move;
338
   int move_index;
339
   int char_index;
340
   int length;
341
   int count;
342
   int consecutive_count;
343
   bool needs_newline;
344
 
345
   // try to open file for writing
346
   _wfopen_s (&fp, pgnfile_pathname, L"w");
347
   if (fp == NULL)
348
      return (false); // on error, cancel
349
 
350
   // get the machine name as an ASCII string
351
   buffer_size = WCHAR_SIZEOF (machine_name);
352
   GetComputerName (machine_name, &buffer_size);
353
 
354
   // get the current date and time
355
   time (&rawtime);
356
   localtime_s (&timeinfo, &rawtime);
357
 
358
   // build the result string
359
   if ((board->game_state == STATE_WHITEWIN_CHECKMATE) || (board->game_state == STATE_WHITEWIN_RESIGNORFORFEIT))
360
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"1-0"); // white won
361
   else if ((board->game_state == STATE_BLACKWIN_CHECKMATE) || (board->game_state == STATE_BLACKWIN_RESIGNORFORFEIT))
362
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"0-1"); // black won
363
   else if ((board->game_state == STATE_DRAW_STALEMATE) || (board->game_state == STATE_DRAW_AGREEMENT) || (board->game_state == STATE_DRAW_OTHER))
364
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"1/2-1/2"); // game is a draw
365
   else
366
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"*"); // game still in progress
367
 
368
   // write the mandatory header parts
369
   fwprintf (fp, L"[Event \"Chess Giants game\"]\n");
370
   fwprintf (fp, L"[Site \"%s\"]\n", machine_name);
371
   fwprintf (fp, L"[Date \"%d.%02d.%02d\"]\n", 1900 + timeinfo.tm_year, 1 + timeinfo.tm_mon, timeinfo.tm_mday);
372
   fwprintf (fp, L"[Round \"1\"]\n");
373
   fwprintf (fp, L"[White \"%s\"]\n", board->players[COLOR_WHITE].name);
374
   fwprintf (fp, L"[Black \"%s\"]\n", board->players[COLOR_BLACK].name);
375
   fwprintf (fp, L"[Result \"%s\"]\n", result_string);
376
   fwprintf (fp, L"[FEN \"%s\"]\n", board->moves[0].fen_string);
377
   fwprintf (fp, L"\n");
378
 
379
   // now write the game
380
   consecutive_count = 0;
381
   for (move_index = 1; move_index < board->move_count; move_index++)
382
   {
383
      // every seven move pairs, drop a carriage return
384
      if (consecutive_count == 14)
385
      {
386
         fwprintf (fp, L"\n"); // one blank line
387
         consecutive_count = 0;
388
      }
389
 
390
      move = &board->moves[move_index]; // quick access to move
391
 
392
      // white to move ?
393
      if (move->color == COLOR_WHITE)
394
         fwprintf (fp, L"%d.", (move_index + 1) / 2); // if so, display double-move number
395
 
396
      // dump move data
397
      fwprintf (fp, L"%s ", move->pgntext);
398
      consecutive_count++;
399
 
400
      // is there a comment for this move ?
401
      if ((move->comment != NULL) && (move->comment[0] != 0))
402
      {
403
         fwprintf (fp, L"\n{\n"); // dump an open brace
404
         length = wcslen (move->comment); // get comment length
405
 
406
         // for each character in comment text...
407
         needs_newline = false;
408
         count = 0;
409
         for (char_index = 0; char_index < length; char_index++)
410
         {
411
            // is it a space and do we need a newline ?
412
            if (iswspace (move->comment[char_index]) && needs_newline)
413
            {
414
               fputwc (L'\n', fp); // dump a newline
415
               needs_newline = false; // we no longer need a newline
416
               count = 0; // reset the number of characters written
417
            }
418
 
419
            // else it's a character
420
            else
421
            {
422
               fputwc (move->comment[char_index], fp); // dump it
423
               count++; // we dumped one character more on this line
424
               if (count > 80)
425
                  needs_newline = true; // if we need a newline, remember it
426
            }
427
         }
428
 
429
         fwprintf (fp, L"\n}\n"); // dump an open brace
430
         consecutive_count = 0;
431
      }
432
 
433
      // if it's the last move, dump the game results
434
      if (move_index == board->move_count - 1)
435
         fwprintf (fp, result_string);
436
   }
437
 
438
   fclose (fp); // finished, close the file
439
 
440
   return (true); // file saved successfully, return TRUE
441
}
442
 
443
 
444
static void PGNFile_GameList_Init (int entry_count)
445
{
446
   // helper function to initialize the game lists array pointer and the games count
447
 
448
   // allocate space for all the games in a row (it's faster than reallocating)
449
   games = (pgngame_t *) SAFE_malloc (entry_count, sizeof (pgngame_t), true);
450
   game_count = entry_count;
451
 
452
   return; // finished
453
}
454
 
455
 
456
static void PGNFile_GameList_Shutdown (void)
457
{
458
   // helper function to free the game lists array and reset the games count
459
 
460
   SAFE_free ((void **) &games); // free the PGN games array
461
   game_count = 0;
462
 
463
   return; // finished
464
}
465
 
466
 
467
static char *sgets (char *destination_line, int max_length, char *source_buffer)
468
{
469
   // copy a line from a given string. Kinda like fgets() when you're reading from a string.
470
   // use it like:
471
   // while (blah = sgets (dest, sizeof (dest), blah)) != NULL)
472
 
473
   char *pointer;
474
   int char_index;
475
 
476
   if (source_buffer[0] == 0)
477
   {
478
      destination_line[0] = 0;
479
      return (NULL); // if EOS return a NULL pointer
480
   }
481
 
482
   pointer = strchr (source_buffer, '\n'); // get to the first carriage return we can find
483
 
484
   // found none ?
485
   if (pointer == NULL)
486
   {
487
      // if so, copy the line we found
488
      for (char_index = 0; char_index < max_length; char_index++)
489
      {
490
         destination_line[char_index] = source_buffer[char_index]; // copy the line we found
491
         if (source_buffer[char_index] == 0)
492
            break; // don't copy beyond the end of source
493
      }
494
 
495
      if (char_index == max_length)
496
         destination_line[max_length - 1] = 0; // ensure string is terminated
497
 
498
      return (&source_buffer[strlen (source_buffer)]); // and return a pointer to the end of the string
499
   }
500
 
501
   *pointer = 0; // temporarily turn the carriage return to an end of string
502
 
503
   for (char_index = 0; char_index < max_length; char_index++)
504
   {
505
      destination_line[char_index] = source_buffer[char_index]; // copy the line we found
506
      if (source_buffer[char_index] == 0)
507
         break; // don't copy beyond the end of source
508
   }
509
 
510
   destination_line[max_length - 1] = 0; // terminate string
511
   *pointer = '\n'; // put the carriage return back
512
 
513
   return (&pointer[1]); // and return next line's source buffer pointer
514
}