-
Notifications
You must be signed in to change notification settings - Fork 5
/
backend.c
19136 lines (17502 loc) · 658 KB
/
backend.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* backend.c -- Common back end for X and Windows NT versions of
*
* Copyright 1991 by Digital Equipment Corporation, Maynard,
* Massachusetts.
*
* Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
* 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Free
* Software Foundation, Inc.
*
* Enhancements Copyright 2005 Alessandro Scotti
*
* The following terms apply to Digital Equipment Corporation's copyright
* interest in XBoard:
* ------------------------------------------------------------------------
* All Rights Reserved
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of Digital not be
* used in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
*
* DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
* DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
* ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
* ------------------------------------------------------------------------
*
* The following terms apply to the enhanced version of XBoard
* distributed by the Free Software Foundation:
* ------------------------------------------------------------------------
*
* GNU XBoard is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* GNU XBoard is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/. *
*
*------------------------------------------------------------------------
** See the file ChangeLog for a revision history. */
/* [AS] Also useful here for debugging */
#ifdef WIN32
#include <windows.h>
int flock(int f, int code);
# define LOCK_EX 2
# define SLASH '\\'
# ifdef ARC_64BIT
# define EGBB_NAME "egbbdll64.dll"
# else
# define EGBB_NAME "egbbdll.dll"
# endif
#else
# include <sys/file.h>
# define SLASH '/'
# include <dlfcn.h>
# ifdef ARC_64BIT
# define EGBB_NAME "egbbso64.so"
# else
# define EGBB_NAME "egbbso.so"
# endif
// kludge to allow Windows code in back-end by converting it to corresponding Linux code
# define CDECL
# define HMODULE void *
# define LoadLibrary(x) dlopen(x, RTLD_LAZY)
# define GetProcAddress dlsym
#endif
#include "config.h"
#include <assert.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <math.h>
#include <ctype.h>
#if STDC_HEADERS
# include <stdlib.h>
# include <string.h>
# include <stdarg.h>
#else /* not STDC_HEADERS */
# if HAVE_STRING_H
# include <string.h>
# else /* not HAVE_STRING_H */
# include <strings.h>
# endif /* not HAVE_STRING_H */
#endif /* not STDC_HEADERS */
#if HAVE_SYS_FCNTL_H
# include <sys/fcntl.h>
#else /* not HAVE_SYS_FCNTL_H */
# if HAVE_FCNTL_H
# include <fcntl.h>
# endif /* HAVE_FCNTL_H */
#endif /* not HAVE_SYS_FCNTL_H */
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#if defined(_amigados) && !defined(__GNUC__)
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
extern int gettimeofday(struct timeval *, struct timezone *);
#endif
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#include "common.h"
#include "frontend.h"
#include "backend.h"
#include "parser.h"
#include "moves.h"
#if ZIPPY
# include "zippy.h"
#endif
#include "backendz.h"
#include "evalgraph.h"
#include "engineoutput.h"
#include "gettext.h"
#ifdef ENABLE_NLS
# define _(s) gettext (s)
# define N_(s) gettext_noop (s)
# define T_(s) gettext(s)
#else
# ifdef WIN32
# define _(s) T_(s)
# define N_(s) s
# else
# define _(s) (s)
# define N_(s) s
# define T_(s) s
# endif
#endif
int establish P((void));
void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
char *buf, int count, int error));
void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
char *buf, int count, int error));
void SendToICS P((char *s));
void SendToICSDelayed P((char *s, long msdelay));
void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
void HandleMachineMove P((char *message, ChessProgramState *cps));
int AutoPlayOneMove P((void));
int LoadGameOneMove P((ChessMove readAhead));
int LoadGameFromFile P((char *filename, int n, char *title, int useList));
int LoadPositionFromFile P((char *filename, int n, char *title));
int SavePositionToFile P((char *filename));
void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
void ShowMove P((int fromX, int fromY, int toX, int toY));
int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
/*char*/int promoChar));
void BackwardInner P((int target));
void ForwardInner P((int target));
int Adjudicate P((ChessProgramState *cps));
void GameEnds P((ChessMove result, char *resultDetails, int whosays));
void EditPositionDone P((Boolean fakeRights));
void PrintOpponents P((FILE *fp));
void PrintPosition P((FILE *fp, int move));
void SendToProgram P((char *message, ChessProgramState *cps));
void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
char *buf, int count, int error));
void SendTimeControl P((ChessProgramState *cps,
int mps, long tc, int inc, int sd, int st));
char *TimeControlTagValue P((void));
void Attention P((ChessProgramState *cps));
void FeedMovesToProgram P((ChessProgramState *cps, int upto));
int ResurrectChessProgram P((void));
void DisplayComment P((int moveNumber, char *text));
void DisplayMove P((int moveNumber));
void ParseGameHistory P((char *game));
void ParseBoard12 P((char *string));
void KeepAlive P((void));
void StartClocks P((void));
void SwitchClocks P((int nr));
void StopClocks P((void));
void ResetClocks P((void));
char *PGNDate P((void));
void SetGameInfo P((void));
int RegisterMove P((void));
void MakeRegisteredMove P((void));
void TruncateGame P((void));
int looking_at P((char *, int *, char *));
void CopyPlayerNameIntoFileName P((char **, char *));
char *SavePart P((char *));
int SaveGameOldStyle P((FILE *));
int SaveGamePGN P((FILE *));
int CheckFlags P((void));
long NextTickLength P((long));
void CheckTimeControl P((void));
void show_bytes P((FILE *, char *, int));
int string_to_rating P((char *str));
void ParseFeatures P((char* args, ChessProgramState *cps));
void InitBackEnd3 P((void));
void FeatureDone P((ChessProgramState* cps, int val));
void InitChessProgram P((ChessProgramState *cps, int setup));
void OutputKibitz(int window, char *text);
int PerpetualChase(int first, int last);
int EngineOutputIsUp();
void InitDrawingSizes(int x, int y);
void NextMatchGame P((void));
int NextTourneyGame P((int nr, int *swap));
int Pairing P((int nr, int nPlayers, int *w, int *b, int *sync));
FILE *WriteTourneyFile P((char *results, FILE *f));
void DisplayTwoMachinesTitle P(());
static void ExcludeClick P((int index));
void ToggleSecond P((void));
void PauseEngine P((ChessProgramState *cps));
static int NonStandardBoardSize P((VariantClass v, int w, int h, int s));
#ifdef WIN32
extern void ConsoleCreate();
#endif
ChessProgramState *WhitePlayer();
int VerifyDisplayMode P(());
char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
void ics_update_width P((int new_width));
extern char installDir[MSG_SIZ];
VariantClass startVariant; /* [HGM] nicks: initial variant */
Boolean abortMatch;
int deadRanks;
extern int tinyLayout, smallLayout;
ChessProgramStats programStats;
char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
int endPV = -1;
static int exiting = 0; /* [HGM] moved to top */
static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
int partnerHighlight[2];
Boolean partnerBoardValid = 0;
char partnerStatus[MSG_SIZ];
Boolean partnerUp;
Boolean originalFlip;
Boolean twoBoards = 0;
char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
int opponentKibitzes;
int lastSavedGame; /* [HGM] save: ID of game */
char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
extern int chatCount;
int chattingPartner;
char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
char legal[BOARD_RANKS][BOARD_FILES]; /* [HGM] legal target squares */
char lastMsg[MSG_SIZ];
char lastTalker[MSG_SIZ];
ChessSquare pieceSweep = EmptySquare;
ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
int promoDefaultAltered;
int keepInfo = 0; /* [HGM] to protect PGN tags in auto-step game analysis */
static int initPing = -1;
int border; /* [HGM] width of board rim, needed to size seek graph */
char bestMove[MSG_SIZ], avoidMove[MSG_SIZ];
int solvingTime, totalTime;
/* States for ics_getting_history */
#define H_FALSE 0
#define H_REQUESTED 1
#define H_GOT_REQ_HEADER 2
#define H_GOT_UNREQ_HEADER 3
#define H_GETTING_MOVES 4
#define H_GOT_UNWANTED_HEADER 5
/* whosays values for GameEnds */
#define GE_ICS 0
#define GE_ENGINE 1
#define GE_PLAYER 2
#define GE_FILE 3
#define GE_XBOARD 4
#define GE_ENGINE1 5
#define GE_ENGINE2 6
/* Maximum number of games in a cmail message */
#define CMAIL_MAX_GAMES 20
/* Different types of move when calling RegisterMove */
#define CMAIL_MOVE 0
#define CMAIL_RESIGN 1
#define CMAIL_DRAW 2
#define CMAIL_ACCEPT 3
/* Different types of result to remember for each game */
#define CMAIL_NOT_RESULT 0
#define CMAIL_OLD_RESULT 1
#define CMAIL_NEW_RESULT 2
/* Telnet protocol constants */
#define TN_WILL 0373
#define TN_WONT 0374
#define TN_DO 0375
#define TN_DONT 0376
#define TN_IAC 0377
#define TN_ECHO 0001
#define TN_SGA 0003
#define TN_PORT 23
char*
safeStrCpy (char *dst, const char *src, size_t count)
{ // [HGM] made safe
int i;
assert( dst != NULL );
assert( src != NULL );
assert( count > 0 );
for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
if( i == count && dst[count-1] != NULLCHAR)
{
dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
if(appData.debugMode)
fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
}
return dst;
}
/* Some compiler can't cast u64 to double
* This function do the job for us:
* We use the highest bit for cast, this only
* works if the highest bit is not
* in use (This should not happen)
*
* We used this for all compiler
*/
double
u64ToDouble (u64 value)
{
double r;
u64 tmp = value & u64Const(0x7fffffffffffffff);
r = (double)(s64)tmp;
if (value & u64Const(0x8000000000000000))
r += 9.2233720368547758080e18; /* 2^63 */
return r;
}
/* Fake up flags for now, as we aren't keeping track of castling
availability yet. [HGM] Change of logic: the flag now only
indicates the type of castlings allowed by the rule of the game.
The actual rights themselves are maintained in the array
castlingRights, as part of the game history, and are not probed
by this function.
*/
int
PosFlags (int index)
{
int flags = F_ALL_CASTLE_OK;
if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
switch (gameInfo.variant) {
case VariantSuicide:
flags &= ~F_ALL_CASTLE_OK;
case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
flags |= F_IGNORE_CHECK;
case VariantLosers:
flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
break;
case VariantAtomic:
flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
break;
case VariantKriegspiel:
flags |= F_KRIEGSPIEL_CAPTURE;
break;
case VariantCapaRandom:
case VariantFischeRandom:
flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
case VariantNoCastle:
case VariantShatranj:
case VariantCourier:
case VariantMakruk:
case VariantASEAN:
case VariantGrand:
flags &= ~F_ALL_CASTLE_OK;
break;
case VariantChu:
case VariantChuChess:
case VariantLion:
flags |= F_NULL_MOVE;
break;
default:
break;
}
if(appData.fischerCastling) flags |= F_FRC_TYPE_CASTLING, flags &= ~F_ALL_CASTLE_OK; // [HGM] fischer
return flags;
}
FILE *gameFileFP, *debugFP, *serverFP;
char *currentDebugFile; // [HGM] debug split: to remember name
/*
[AS] Note: sometimes, the sscanf() function is used to parse the input
into a fixed-size buffer. Because of this, we must be prepared to
receive strings as long as the size of the input buffer, which is currently
set to 4K for Windows and 8K for the rest.
So, we must either allocate sufficiently large buffers here, or
reduce the size of the input buffer in the input reading part.
*/
char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
char thinkOutput1[MSG_SIZ*10];
char promoRestrict[MSG_SIZ];
ChessProgramState first, second, pairing;
/* premove variables */
int premoveToX = 0;
int premoveToY = 0;
int premoveFromX = 0;
int premoveFromY = 0;
int premovePromoChar = 0;
int gotPremove = 0;
Boolean alarmSounded;
/* end premove variables */
char *ics_prefix = "$";
enum ICS_TYPE ics_type = ICS_GENERIC;
int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
int pauseExamForwardMostMove = 0;
int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
int whiteFlag = FALSE, blackFlag = FALSE;
int userOfferedDraw = FALSE;
int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
int cmailMoveType[CMAIL_MAX_GAMES];
long ics_clock_paused = 0;
ProcRef icsPR = NoProc, cmailPR = NoProc;
InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
GameMode gameMode = BeginningOfGame;
char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
int hiddenThinkOutputState = 0; /* [AS] */
int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
int adjudicateLossPlies = 6;
char white_holding[64], black_holding[64];
TimeMark lastNodeCountTime;
long lastNodeCount=0;
int shiftKey, controlKey; // [HGM] set by mouse handler
int have_sent_ICS_logon = 0;
int movesPerSession;
int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack, activePartnerTime;
Boolean adjustedClock;
long timeControl_2; /* [AS] Allow separate time controls */
char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC, activePartner; /* [HGM] secondary TC: merge of MPS, TC and inc */
long timeRemaining[2][MAX_MOVES];
int matchGame = 0, nextGame = 0, roundNr = 0;
Boolean waitingForGame = FALSE, startingEngine = FALSE;
TimeMark programStartTime, pauseStart;
char ics_handle[MSG_SIZ];
int have_set_title = 0;
/* animateTraining preserves the state of appData.animate
* when Training mode is activated. This allows the
* response to be animated when appData.animate == TRUE and
* appData.animateDragging == TRUE.
*/
Boolean animateTraining;
GameInfo gameInfo;
AppData appData;
Board boards[MAX_MOVES];
/* [HGM] Following 7 needed for accurate legality tests: */
signed char castlingRank[BOARD_FILES]; // and corresponding ranks
unsigned char initialRights[BOARD_FILES];
int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
int initialRulePlies, FENrulePlies;
FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
int loadFlag = 0;
Boolean shuffleOpenings;
int mute; // mute all sounds
// [HGM] vari: next 12 to save and restore variations
#define MAX_VARIATIONS 10
int framePtr = MAX_MOVES-1; // points to free stack entry
int storedGames = 0;
int savedFirst[MAX_VARIATIONS];
int savedLast[MAX_VARIATIONS];
int savedFramePtr[MAX_VARIATIONS];
char *savedDetails[MAX_VARIATIONS];
ChessMove savedResult[MAX_VARIATIONS];
void PushTail P((int firstMove, int lastMove));
Boolean PopTail P((Boolean annotate));
void PushInner P((int firstMove, int lastMove));
void PopInner P((Boolean annotate));
void CleanupTail P((void));
ChessSquare FIDEArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackBishop, BlackQueen,
BlackKing, BlackBishop, BlackKnight, BlackRook }
};
ChessSquare twoKingsArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackBishop, BlackQueen,
BlackKing, BlackKing, BlackKnight, BlackRook }
};
ChessSquare KnightmateArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
{ BlackRook, BlackMan, BlackBishop, BlackQueen,
BlackUnicorn, BlackBishop, BlackMan, BlackRook }
};
ChessSquare SpartanArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackAlfil, BlackDragon, BlackKing, BlackTower,
BlackTower, BlackKing, BlackAngel, BlackAlfil }
};
ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
};
ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
{ WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackAlfil, BlackKing,
BlackFerz, BlackAlfil, BlackKnight, BlackRook }
};
ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
{ WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackMan, BlackFerz,
BlackKing, BlackMan, BlackKnight, BlackRook }
};
ChessSquare aseanArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
{ WhiteRook, WhiteKnight, WhiteMan, WhiteFerz,
WhiteKing, WhiteMan, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackMan, BlackFerz,
BlackKing, BlackMan, BlackKnight, BlackRook }
};
ChessSquare lionArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteLion, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackRook, BlackLion, BlackBishop, BlackQueen,
BlackKing, BlackBishop, BlackKnight, BlackRook }
};
#if (BOARD_FILES>=10)
ChessSquare ShogiArray[2][BOARD_FILES] = {
{ WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
{ BlackQueen, BlackKnight, BlackFerz, BlackWazir,
BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
};
ChessSquare XiangqiArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackAlfil, BlackFerz,
BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
};
ChessSquare CapablancaArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
};
ChessSquare GreatArray[2][BOARD_FILES] = {
{ WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
{ BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
};
ChessSquare JanusArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
{ BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
};
ChessSquare GrandArray[2][BOARD_FILES] = {
{ EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
{ EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
};
ChessSquare ChuChessArray[2][BOARD_FILES] = {
{ WhiteMan, WhiteKnight, WhiteBishop, WhiteCardinal, WhiteLion,
WhiteQueen, WhiteDragon, WhiteBishop, WhiteKnight, WhiteMan },
{ BlackMan, BlackKnight, BlackBishop, BlackDragon, BlackQueen,
BlackLion, BlackCardinal, BlackBishop, BlackKnight, BlackMan }
};
#ifdef GOTHIC
ChessSquare GothicArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
};
#else // !GOTHIC
#define GothicArray CapablancaArray
#endif // !GOTHIC
#ifdef FALCON
ChessSquare FalconArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
};
#else // !FALCON
#define FalconArray CapablancaArray
#endif // !FALCON
#else // !(BOARD_FILES>=10)
#define XiangqiPosition FIDEArray
#define CapablancaArray FIDEArray
#define GothicArray FIDEArray
#define GreatArray FIDEArray
#endif // !(BOARD_FILES>=10)
#if (BOARD_FILES>=12)
ChessSquare CourierArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
};
ChessSquare ChuArray[6][BOARD_FILES] = {
{ WhiteLance, WhiteCat, WhiteCopper, WhiteFerz, WhiteWazir, WhiteKing,
WhiteAlfil, WhiteWazir, WhiteFerz, WhiteCopper, WhiteCat, WhiteLance },
{ BlackLance, BlackCat, BlackCopper, BlackFerz, BlackWazir, BlackAlfil,
BlackKing, BlackWazir, BlackFerz, BlackCopper, BlackCat, BlackLance },
{ WhiteAxe, EmptySquare, WhiteBishop, EmptySquare, WhiteClaw, WhiteMarshall,
WhiteAngel, WhiteClaw, EmptySquare, WhiteBishop, EmptySquare, WhiteAxe },
{ BlackAxe, EmptySquare, BlackBishop, EmptySquare, BlackClaw, BlackAngel,
BlackMarshall, BlackClaw, EmptySquare, BlackBishop, EmptySquare, BlackAxe },
{ WhiteDagger, WhiteSword, WhiteRook, WhiteCardinal, WhiteDragon, WhiteLion,
WhiteQueen, WhiteDragon, WhiteCardinal, WhiteRook, WhiteSword, WhiteDagger },
{ BlackDagger, BlackSword, BlackRook, BlackCardinal, BlackDragon, BlackQueen,
BlackLion, BlackDragon, BlackCardinal, BlackRook, BlackSword, BlackDagger }
};
#else // !(BOARD_FILES>=12)
#define CourierArray CapablancaArray
#define ChuArray CapablancaArray
#endif // !(BOARD_FILES>=12)
Board initialPosition;
/* Convert str to a rating. Checks for special cases of "----",
"++++", etc. Also strips ()'s */
int
string_to_rating (char *str)
{
while(*str && !isdigit(*str)) ++str;
if (!*str)
return 0; /* One of the special "no rating" cases */
else
return atoi(str);
}
void
ClearProgramStats ()
{
/* Init programStats */
programStats.movelist[0] = 0;
programStats.depth = 0;
programStats.nr_moves = 0;
programStats.moves_left = 0;
programStats.nodes = 0;
programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
programStats.score = 0;
programStats.got_only_move = 0;
programStats.got_fail = 0;
programStats.line_is_book = 0;
}
void
CommonEngineInit ()
{ // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
if (appData.firstPlaysBlack) {
first.twoMachinesColor = "black\n";
second.twoMachinesColor = "white\n";
} else {
first.twoMachinesColor = "white\n";
second.twoMachinesColor = "black\n";
}
first.other = &second;
second.other = &first;
{ float norm = 1;
if(appData.timeOddsMode) {
norm = appData.timeOdds[0];
if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
}
first.timeOdds = appData.timeOdds[0]/norm;
second.timeOdds = appData.timeOdds[1]/norm;
}
if(programVersion) free(programVersion);
if (appData.noChessProgram) {
programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
sprintf(programVersion, "%s", PACKAGE_STRING);
} else {
/* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
}
}
void
UnloadEngine (ChessProgramState *cps)
{
/* Kill off first chess program */
if (cps->isr != NULL)
RemoveInputSource(cps->isr);
cps->isr = NULL;
if (cps->pr != NoProc) {
ExitAnalyzeMode();
DoSleep( appData.delayBeforeQuit );
SendToProgram("quit\n", cps);
DestroyChildProcess(cps->pr, 4 + cps->useSigterm);
}
cps->pr = NoProc;
if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
}
void
ClearOptions (ChessProgramState *cps)
{
int i;
cps->nrOptions = cps->comboCnt = 0;
for(i=0; i<MAX_OPTIONS; i++) {
cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
cps->option[i].textValue = 0;
}
}
char *engineNames[] = {
/* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
N_("first"),
/* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
N_("second")
};
void
InitEngine (ChessProgramState *cps, int n)
{ // [HGM] all engine initialiation put in a function that does one engine
ClearOptions(cps);
cps->which = engineNames[n];
cps->maybeThinking = FALSE;
cps->pr = NoProc;
cps->isr = NULL;
cps->sendTime = 2;
cps->sendDrawOffers = 1;
cps->program = appData.chessProgram[n];
cps->host = appData.host[n];
cps->dir = appData.directory[n];
cps->initString = appData.engInitString[n];
cps->computerString = appData.computerString[n];
cps->useSigint = TRUE;
cps->useSigterm = TRUE;
cps->reuse = appData.reuse[n];
cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
cps->useSetboard = FALSE;
cps->useSAN = FALSE;
cps->usePing = FALSE;
cps->lastPing = 0;
cps->lastPong = 0;
cps->usePlayother = FALSE;
cps->useColors = TRUE;
cps->useUsermove = FALSE;
cps->sendICS = FALSE;
cps->sendName = appData.icsActive;
cps->sdKludge = FALSE;
cps->stKludge = FALSE;
if(cps->tidy == NULL) cps->tidy = (char*) malloc(MSG_SIZ);
TidyProgramName(cps->program, cps->host, cps->tidy);
cps->matchWins = 0;
ASSIGN(cps->variants, appData.noChessProgram ? "" : appData.variant);
cps->analysisSupport = 2; /* detect */
cps->analyzing = FALSE;
cps->initDone = FALSE;
cps->reload = FALSE;
cps->pseudo = appData.pseudo[n];
/* New features added by Tord: */
cps->useFEN960 = FALSE;
cps->useOOCastle = TRUE;
/* End of new features added by Tord. */
cps->fenOverride = appData.fenOverride[n];
/* [HGM] time odds: set factor for each machine */
cps->timeOdds = appData.timeOdds[n];
/* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
cps->accumulateTC = appData.accumulateTC[n];
cps->maxNrOfSessions = 1;
/* [HGM] debug */
cps->debug = FALSE;
cps->drawDepth = appData.drawDepth[n];
cps->supportsNPS = UNKNOWN;
cps->memSize = FALSE;
cps->maxCores = FALSE;
ASSIGN(cps->egtFormats, "");
/* [HGM] options */
cps->optionSettings = appData.engOptions[n];
cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
cps->isUCI = appData.isUCI[n]; /* [AS] */
cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
cps->highlight = 0;
if (appData.protocolVersion[n] > PROTOVER
|| appData.protocolVersion[n] < 1)
{
char buf[MSG_SIZ];
int len;
len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
appData.protocolVersion[n]);
if( (len >= MSG_SIZ) && appData.debugMode )
fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
DisplayFatalError(buf, 0, 2);
}
else
{
cps->protocolVersion = appData.protocolVersion[n];
}
InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
ParseFeatures(appData.featureDefaults, cps);
}
ChessProgramState *savCps;
GameMode oldMode;
void
LoadEngine ()
{
int i;
if(WaitForEngine(savCps, LoadEngine)) return;
CommonEngineInit(); // recalculate time odds
if(gameInfo.variant != StringToVariant(appData.variant)) {
// we changed variant when loading the engine; this forces us to reset
Reset(TRUE, savCps != &first);
oldMode = BeginningOfGame; // to prevent restoring old mode
}
InitChessProgram(savCps, FALSE);
if(gameMode == EditGame) SendToProgram("force\n", savCps); // in EditGame mode engine must be in force mode
DisplayMessage("", "");
if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
for (i = backwardMostMove; i < currentMove; i++) SendMoveToProgram(i, savCps);
ThawUI();
SetGNUMode();
if(oldMode == AnalyzeMode) AnalyzeModeEvent();
}
void
ReplaceEngine (ChessProgramState *cps, int n)
{
oldMode = gameMode; // remember mode, so it can be restored after loading sequence is complete
keepInfo = 1;
if(oldMode != BeginningOfGame) EditGameEvent();
keepInfo = 0;
UnloadEngine(cps);
appData.noChessProgram = FALSE;
appData.clockMode = TRUE;
InitEngine(cps, n);
UpdateLogos(TRUE);
if(n) return; // only startup first engine immediately; second can wait
savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
LoadEngine();
}
extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
static char resetOptions[] =
"-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
"-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
"-firstFeatures \"\" -firstLogo \"\" -firstAccumulateTC 1 -fd \".\" "
"-firstOptions \"\" -firstNPS -1 -fn \"\" -firstScoreAbs false";
void
FloatToFront(char **list, char *engineLine)
{
char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
int i=0;
if(appData.recentEngines <= 0) return;
TidyProgramName(engineLine, "localhost", tidy+1);
tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
strncpy(buf+1, *list, MSG_SIZ-50);
if(p = strstr(buf, tidy)) { // tidy name appears in list
q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
while(*p++ = *++q); // squeeze out
}
strcat(tidy, buf+1); // put list behind tidy name
p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
ASSIGN(*list, tidy+1);
}
char *insert, *wbOptions; // point in ChessProgramNames were we should insert new engine
void
Load (ChessProgramState *cps, int i)
{
char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ], buf3[MSG_SIZ], jar;
if(engineLine && engineLine[0]) { // an engine was selected from the combo box
snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
ParseArgsFromString(resetOptions); appData.pvSAN[0] = FALSE;
FREE(appData.fenOverride[0]); appData.fenOverride[0] = NULL;
appData.firstProtocolVersion = PROTOVER;
ParseArgsFromString(buf);
SwapEngines(i);
ReplaceEngine(cps, i);
FloatToFront(&appData.recentEngineList, engineLine);
if(gameMode == BeginningOfGame) Reset(TRUE, TRUE);