Subversion Repositories Games.Chess Giants

Rev

Rev 66 | Rev 69 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

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