2 * engineoutput.c - split-off backe-end from Engine output (PV) by HGM
4 * Author: Alessandro Scotti (Dec 2005)
6 * Copyright 2005 Alessandro Scotti
8 * Enhancements Copyright 1995, 2009, 2010, 2011, 2012, 2013, 2014,
9 * 2015, 2016 Free Software Foundation, Inc.
11 * ------------------------------------------------------------------------
13 * GNU XBoard is free software: you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation, either version 3 of the License, or (at
16 * your option) any later version.
18 * GNU XBoard is distributed in the hope that it will be useful, but
19 * WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see http://www.gnu.org/licenses/. *
26 *------------------------------------------------------------------------
27 ** See the file ChangeLog for a revision history. */
29 #define SHOW_PONDERING
39 #else /* not STDC_HEADERS */
42 # else /* not HAVE_STRING_H */
44 # endif /* not HAVE_STRING_H */
45 #endif /* not STDC_HEADERS */
51 #include "engineoutput.h"
55 # define _(s) gettext (s)
56 # define N_(s) gettext_noop (s)
61 # define ngettext(s,p,n) T_(p)
82 // called by other front-end
83 void EngineOutputUpdate( FrontEndProgramStats * stats );
84 void OutputKibitz(int window, char *text);
86 // module back-end routines
87 static void VerifyDisplayMode();
88 static void UpdateControls( EngineOutputData * ed );
90 static int lastDepth[2] = { -1, -1 };
91 static int lastForwardMostMove[2] = { -1, -1 };
92 static int engineState[2] = { -1, -1 };
93 static char lastLine[2][MSG_SIZ];
94 static char header[2][MSG_SIZ];
95 static char columnHeader[MSG_SIZ] = "dep\tscore\tnodes\ttime\t(not shown: tbhits\tknps\tseldep)\n";
96 static int columnMask = 0xF0;
99 static int scores[MAX_VAR], textEnd[MAX_VAR], keys[MAX_VAR], curDepth[2], nrVariations[2];
100 static char fail[MAX_VAR];
102 extern int initialRulePlies;
105 MakeEngineOutputTitle ()
107 static char buf[MSG_SIZ];
108 static char oldTitle[MSG_SIZ];
110 int count, rule = 2*appData.ruleMoves;
112 snprintf(title, MSG_SIZ, _("Engine Output") );
114 if(!EngineOutputIsUp()) return;
115 // figure out value of 50-move counter
117 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove ) count--;
118 if( count == backwardMostMove ) count -= initialRulePlies;
119 count = currentMove - count;
120 if(!rule) rule = 100;
121 if(count >= rule - 40 && (!appData.icsActive || gameMode == IcsObserving || appData.zippyPlay)) {
122 snprintf(buf, MSG_SIZ, ngettext("%s (%d reversible ply)", "%s (%d reversible plies)", count), title, count);
123 safeStrCpy(title, buf, MSG_SIZ);
125 if(!strcmp(oldTitle, title)) return;
126 safeStrCpy(oldTitle, title, MSG_SIZ);
127 SetEngineOutputTitle(title);
130 // back end, due to front-end wrapper for SetWindowText, and new SetIcon arguments
132 SetEngineState (int which, enum ENGINE_STATE state, char * state_data)
134 int x_which = 1 - which;
136 if( engineState[ which ] != state ) {
137 engineState[ which ] = state;
141 SetIcon( which, nStateIcon, nThinking );
142 if( engineState[ x_which ] == STATE_THINKING ) {
143 SetEngineState( x_which, STATE_IDLE, "" );
146 case STATE_PONDERING:
147 SetIcon( which, nStateIcon, nPondering );
149 case STATE_ANALYZING:
150 SetIcon( which, nStateIcon, nAnalyzing );
153 SetIcon( which, nStateIcon, nClear );
158 if( state_data != 0 ) {
159 DoSetWindowText( which, nStateData, state_data );
163 // back end, now the front-end wrapper ClearMemo is used, and ed no longer contains handles.
165 SetProgramStats (FrontEndProgramStats * stats) // now directly called by back-end
168 int clearMemo = FALSE;
169 int which, depth, multi;
175 SetEngineState( 0, STATE_IDLE, "" );
176 SetEngineState( 1, STATE_IDLE, "" );
180 if(gameMode == IcsObserving && !appData.icsEngineAnalyze)
181 return; // [HGM] kibitz: shut up engine if we are observing an ICS game
183 which = stats->which;
184 depth = stats->depth;
186 if( which < 0 || which > 1 || depth < 0 || stats->time < 0 || stats->pv == 0 ) {
190 if(appData.epd && which) return; // do not write second pane in -epd mode
192 if( !EngineOutputDialogExists() ) {
200 ed.nodes = stats->nodes;
201 ed.score = stats->score;
202 ed.time = stats->time;
204 ed.hint = stats->hint;
205 ed.an_move_index = stats->an_move_index;
206 ed.an_move_count = stats->an_move_count;
208 /* Get target control. [HGM] this is moved to front end, which get them from a table */
210 ed.name = first.tidy;
213 ed.name = second.tidy;
216 if( ed.pv != 0 && ed.pv[0] == ' ' ) {
217 if( strncmp( ed.pv, " no PV", 6 ) == 0 ) { /* Hack on hack! :-O */
222 /* Clear memo if needed */
223 if( lastDepth[which] > depth || (lastDepth[which] == depth && depth <= 1 && ed.pv[0]) ) { // no reason to clear if we won't add line
227 if( lastForwardMostMove[which] != forwardMostMove && endPV < 0) {
232 if(!appData.headers) columnHeader[0] = NULLCHAR;
233 DoClearMemo(which); nrVariations[which] = 0;
234 header[which][0] = NULLCHAR;
235 if(gameMode == AnalyzeMode) {
236 ChessProgramState *cps = (which ? &second : &first);
237 char *exclu = cps->excludeMoves ? exclusionHeader : "";
238 if((multi = MultiPV(cps, 3)) != -1) {
240 if(multi < -1) multi = -2 - multi, s = "margin";
241 snprintf(header[which], MSG_SIZ, "\t%s viewpoint\t\tfewer / Multi-PV %s = %d / more\n",
242 appData.whitePOV || appData.scoreWhite ? "white" : "mover", s, cps->option[multi].value);
244 if(!which) snprintf(header[which]+strlen(header[which]), MSG_SIZ-strlen(header[which]), "%s%s", exclu, columnHeader);
245 InsertIntoMemo( which, header[which], 0);
247 snprintf(header[which], MSG_SIZ, "%s", columnHeader);
248 if(appData.ponderNextMove && lastLine[which][0]) {
249 InsertIntoMemo( which, lastLine[which], 0 );
250 InsertIntoMemo( which, "\n", 0 );
252 InsertIntoMemo( which, header[which], 0);
256 if(ed.pv && ed.pv[0] && ParseOneMove(ed.pv, currentMove, &moveType, &ff, &rf, &ft, &rt, &pc))
257 ed.moveKey = (ff<<24 | rf << 16 | ft << 8 | rt) ^ pc*87161;
258 else ed.moveKey = ed.nodes; // kludge to get unique key unlikely to match any move
261 lastDepth[which] = depth == 1 && ed.nodes == 0 ? 0 : depth; // [HGM] info-line kudge
262 if(endPV < 0) lastForwardMostMove[which] = forwardMostMove; // not during PV walk!
264 UpdateControls( &ed );
267 #define ENGINE_COLOR_WHITE 'w'
268 #define ENGINE_COLOR_BLACK 'b'
269 #define ENGINE_COLOR_UNKNOWN ' '
273 GetEngineColor (int which)
275 char result = ENGINE_COLOR_UNKNOWN;
277 if( which == 0 || which == 1 ) {
278 ChessProgramState * cps;
281 case MachinePlaysBlack:
282 case IcsPlayingBlack:
283 result = ENGINE_COLOR_BLACK;
285 case MachinePlaysWhite:
286 case IcsPlayingWhite:
287 result = ENGINE_COLOR_WHITE;
291 result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
293 case TwoMachinesPlay:
294 cps = (which == 0) ? &first : &second;
295 result = cps->twoMachinesColor[0];
296 result = result == 'w' ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
298 default: ; // does not happen, but suppresses pedantic warnings
307 GetActiveEngineColor ()
309 char result = ENGINE_COLOR_UNKNOWN;
311 if( gameMode == TwoMachinesPlay ) {
312 result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
320 IsEnginePondering (int which)
325 case MachinePlaysBlack:
326 case IcsPlayingBlack:
327 if( WhiteOnMove(forwardMostMove) ) result = TRUE;
329 case MachinePlaysWhite:
330 case IcsPlayingWhite:
331 if( ! WhiteOnMove(forwardMostMove) ) result = TRUE;
333 case TwoMachinesPlay:
334 if( GetActiveEngineColor() != ENGINE_COLOR_UNKNOWN ) {
335 if( GetEngineColor( which ) != GetActiveEngineColor() ) result = TRUE;
338 default: ; // does not happen, but suppresses pedantic warnings
346 SetDisplayMode (int mode)
348 if( windowMode != mode ) {
351 ResizeWindowControls( mode );
361 /* Get proper mode for current game */
363 case IcsObserving: // [HGM] ICS analyze
364 if(!appData.icsEngineAnalyze) return;
366 case MachinePlaysWhite:
367 case MachinePlaysBlack:
371 mode = second.analyzing;
373 case IcsPlayingWhite:
374 case IcsPlayingBlack:
375 mode = appData.zippyPlay && opponentKibitzes; // [HGM] kibitz
377 case TwoMachinesPlay:
385 SetDisplayMode( mode );
388 // back end. Determine what icon to set in the color-icon field, and print it
390 SetEngineColorIcon (int which)
392 char color = GetEngineColor(which);
395 if( color == ENGINE_COLOR_BLACK )
397 else if( color == ENGINE_COLOR_WHITE )
400 nicon = nColorUnknown;
402 SetIcon( which, nColorIcon, nicon );
405 #define MAX_NAME_LENGTH 32
407 // [HGM] multivar: sort Thinking Output within one depth on score
411 { // map mate-score to monotonous scale, so sorting compares them correctly
412 if(n >= MATE_SCORE) return 2*MATE_SCORE - n;
413 if(n <= -MATE_SCORE) return -2*MATE_SCORE - n;
418 InsertionPoint (int len, EngineOutputData *ed)
420 int i, offs = 0, newScore = ed->score, n = ed->which;
423 if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
424 newScore = 1e6; // info lines inserted on top
425 if(ed->depth != curDepth[n]) { // depth has changed
426 curDepth[n] = ed->depth;
427 nrVariations[n] = 0; // throw away everything we had
429 i = strlen(ed->pv); if(i > 0) i--;
430 failType = ed->pv[i];
431 if(failType != '?' && failType != '!') failType = ' ';
432 // loop through all lines. Note even / odd used for different panes
433 for(i=nrVariations[n]-2; i>=0; i-=2) {
434 // put new item behind those we haven't looked at
436 textEnd[i+n+2] = offs + len;
437 scores[i+n+2] = newScore;
438 keys[i+n+2] = ed->moveKey;
439 fail[i+n+2] = failType;
440 if(ed->moveKey != keys[i+n] && // same move always tops previous one (as a higher score must be a fail low)
441 MateFlip(newScore) < MateFlip(scores[i+n]) && fail[i+n] == ' ') break;
442 // if it had higher score as previous, move previous in stead
443 scores[i+n+2] = ed->moveKey == keys[i+n] ? newScore : scores[i+n]; // correct scores of fail-low/high searches
444 textEnd[i+n+2] = textEnd[i+n] + len;
445 keys[i+n+2] = keys[i+n];
446 fail[i+n+2] = fail[i+n];
450 textEnd[n] = offs + len;
451 scores[n] = newScore;
452 keys[n] = ed->moveKey;
455 nrVariations[n] += 2;
456 return offs + strlen(header[ed->which]);
459 static char spaces[] = " "; // [HGM] align: spaces for padding
462 Format(char *buf, int val)
463 { // [HGM] tbhits: print a positive integer with trailing whitespace to give it fixed width
464 if( val < 1000000 ) {
466 while(h > 0) h /= 10, i++;
467 snprintf( buf, 24, "%d%s\t", val, spaces + 2*i);
471 if(val >= 1e9) val /= 1e3, unit = 'G';
472 snprintf( buf, 24, "%.*f%c%s\t", 1 + (val < 1e7), val/1e6, unit, spaces + 10 + 2*(val >= 1e8));
476 // pure back end, now SetWindowText is called via wrapper DoSetWindowText
478 UpdateControls (EngineOutputData *ed)
480 // int isPondering = FALSE;
482 char s_label[MAX_NAME_LENGTH + 32];
484 char * name = ed->name;
485 char *q, *pvStart = ed->pv;
488 if( name == 0 || *name == '\0' ) {
492 strncpy( s_label, name, MAX_NAME_LENGTH );
493 s_label[ MAX_NAME_LENGTH-1 ] = '\0';
495 if(pvStart) { // [HGM] tbhits: plit up old PV into extra infos and real PV
496 while(strchr(pvStart, '\t')) { // locate last tab before non-int (real PV starts after that)
497 for(q=pvStart; isdigit(*q) || *q == ' '; q++);
498 if(*q != '\t') break;
503 #ifdef SHOW_PONDERING
504 if( IsEnginePondering( ed->which ) ) {
509 if( ed->hint != 0 && *ed->hint != '\0' ) {
510 strncpy( buf, ed->hint, sizeof(buf) );
511 buf[sizeof(buf)-1] = '\0';
513 else if( pvStart != 0 && *pvStart != '\0' ) {
515 int buflen = sizeof(buf);
517 sep = strchr( pvStart, ' ' );
519 buflen = sep - pvStart + 1;
520 if( buflen > sizeof(buf) ) buflen = sizeof(buf);
523 strncpy( buf, pvStart, buflen );
524 buf[ buflen-1 ] = '\0';
527 SetEngineState( ed->which, STATE_PONDERING, buf );
529 else if( gameMode == TwoMachinesPlay ) {
530 SetEngineState( ed->which, STATE_THINKING, "" );
532 else if( gameMode == AnalyzeMode || gameMode == AnalyzeFile
533 || (gameMode == IcsObserving && appData.icsEngineAnalyze)) { // [HGM] ICS-analyze
535 int time_secs = ed->time / 100;
536 int time_mins = time_secs / 60;
540 if( ed->an_move_index != 0 && ed->an_move_count != 0 && *ed->hint != '\0' ) {
543 strncpy( mov, ed->hint, sizeof(mov) );
544 mov[ sizeof(mov)-1 ] = '\0';
546 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
547 ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
550 SetEngineState( ed->which, STATE_ANALYZING, buf );
553 SetEngineState( ed->which, STATE_IDLE, "" );
557 DoSetWindowText( ed->which, nLabel, s_label );
561 if( ed->time > 0 && ed->nodes > 0 ) {
562 unsigned long nps_100 = ed->nodes / ed->time;
564 if( nps_100 < 100000 ) {
565 snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %lu", _("NPS"), nps_100 * 100 );
568 snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %.1fk", _("NPS"), nps_100 / 10.0 );
572 DoSetWindowText( ed->which, nLabelNPS, s_label );
575 if( pvStart != 0 && *pvStart != '\0' ) {
583 int buflen, hits, i, params[5], extra;
584 int time_secs = ed->time / 100;
585 int time_cent = ed->time % 100;
588 if( ed->nodes < 1000000 ) {
589 int h = ed->nodes, i=0;
590 while(h > 0) h /= 10, i++; // [HGM] align: count digits; pad with 2 spaces for every missing digit
591 snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display "%s\t", ed->nodes, spaces + 2*i);
594 double x = u64ToDouble(ed->nodes);
596 if(x >= 1e9) x /= 1e3, unit = 'G';
597 snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.*f%c%s\t", 1 + (x < 1e7), x / 1e6,
598 unit, spaces + 10 + 2*(ed->nodes >= 1e8));
602 for(i=hits=0; i<5; i++) params[i] = 0;
603 //fprintf(stderr, "%s\n%s\n", ed->pv, pvStart);
604 if(pvStart != ed->pv) { // check if numbers before PV
605 strncpy(buf, ed->pv, 256); buf[pvStart - ed->pv] = NULLCHAR;
606 extra = sscanf(buf, "%d %d %d %d %d", params, params+1, params+2, params+3, params+4);
607 //fprintf(stderr, "extra=%d len=%d\n", extra, pvStart - ed->pv);
608 if(extra) hits = params[extra-1], params[extra-1] = 0; // last one is tbhits
610 Format(s_seld, params[0]); Format(s_knps, params[1]); Format(s_hits, hits);
612 if(*ed->pv) fail = ed->pv[strlen(ed->pv)-1]; else fail = ' ';
613 if(fail != '?' && fail != '!') fail = ' ';
616 h = ((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(currentMove) ? -1 : 1) * ed->score;
618 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), " 0.00%c\t", fail );
620 if( h >= MATE_SCORE) snprintf(s_score, 16, " %s#%d%c\t", ( h > MATE_SCORE+9 ? "" : " "), h - MATE_SCORE, fail ); else
621 if(-h >= MATE_SCORE) snprintf(s_score, 16, " %s#-%d%c\t", (-h > MATE_SCORE+9 ? "" : " "), -h - MATE_SCORE, fail ); else
623 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f%c\t", h / 100.0, fail );
626 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), " %.2f%c\t", h / 100.0, fail );
630 if(time_secs >= 3600)
631 snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d:%02d\t", time_secs / 3600, (time_secs / 60) % 60, time_secs % 60 );
633 snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d\t", time_secs / 60, time_secs % 60, time_cent );
635 if(columnMask & 2) s_score[0] = NULLCHAR; // [HGM] hide: erase columns the user has hidden
636 if(columnMask & 4) s_nodes[0] = NULLCHAR;
637 if(columnMask & 8) s_time[0] = NULLCHAR;
638 if(columnMask & 16) s_hits[0] = NULLCHAR;
639 if(columnMask & 32) s_knps[0] = NULLCHAR;
640 if(columnMask & 64) s_seld[0] = NULLCHAR;
642 /* Put all together... */
643 if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
644 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth );
646 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t%s%s%s%s%s%s", ed->depth, s_score, s_nodes, s_time, s_hits, s_knps, s_seld );
649 buflen = strlen(buf);
651 strncpy( buf + buflen, pvStart, sizeof(buf) - buflen );
653 buf[ sizeof(buf) - 3 ] = '\0';
655 strcat( buf + buflen, "\r\n" );
658 InsertIntoMemo( ed->which, buf, InsertionPoint(strlen(buf), ed) );
659 strncpy(lastLine[ed->which], buf, MSG_SIZ);
663 SetEngineColorIcon( ed->which );
666 static char *titles[] = { "score\t", "nodes\t", "time\t", "tbhits\t", "knps\t", "seldep\t" };
670 { // handle click on column headers, to hide / show them
671 int i, j, nr=0, m=~columnMask, Ncol=7;
672 for(i=0; columnHeader[i] && i<n; i++) nr += (columnHeader[i] == '\t');
673 if(!nr) return; // depth always shown, so clicks on it ignored
674 for(i=j=0; i<Ncol; i++) if(m & 1<<i) j++; // count hidden columns
675 if(nr < j) { // shown column clicked: hide it
676 for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
678 } else { // hidden column clicked: show it
680 for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
681 columnMask &= ~(1<<i);
683 // create new header line
684 strcpy(columnHeader, "dep\t");
686 for(i=j=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]), j++;
687 if(j != Ncol) { // list hidden columns, so user ca click them
688 m = ~m; strcat(columnHeader, "(not shown: ");
689 for(i=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]);
690 strcat(columnHeader, ")");
692 strcat(columnHeader, "\n");
695 // [HGM] kibitz: write kibitz line; split window for it if necessary
697 OutputKibitz (int window, char *text)
699 static int currentLineEnd[2];
701 if(!EngineOutputIsUp()) return;
702 if(!opponentKibitzes && !appData.epd) { // on first kibitz of game, clear memos
703 DoClearMemo(1); currentLineEnd[1] = 0;
704 if(gameMode == IcsObserving) { DoClearMemo(0); currentLineEnd[0] = 0; }
706 opponentKibitzes = TRUE; // this causes split window DisplayMode in ICS modes.
708 strncpy(text+strlen(text)-1, "\r\n", 4); // to not lose line breaks on copying
709 if(gameMode == IcsObserving) {
710 DoSetWindowText(0, nLabel, gameInfo.white);
711 SetIcon( 0, nColorIcon, nColorWhite);
712 SetIcon( 0, nStateIcon, nClear);
714 DoSetWindowText(1, nLabel, gameMode == IcsPlayingBlack ? gameInfo.white : gameInfo.black); // opponent name
715 SetIcon( 1, nColorIcon, gameMode == IcsPlayingBlack ? nColorWhite : nColorBlack);
716 SetIcon( 1, nStateIcon, nClear);
717 if(strstr(text, "\\ ") == text) where = currentLineEnd[window-1]; // continuation line
718 //if(appData.debugMode) fprintf(debugFP, "insert '%s' at %d (end = %d,%d)\n", text, where, currentLineEnd[0], currentLineEnd[1]);
719 InsertIntoMemo(window-1, text, where); // [HGM] multivar: always at top
720 currentLineEnd[window-1] = where + strlen(text);