Merge branch 'maint' into HEAD
[gnushogi.git] / gnushogi / gnushogi.h
1 /*
2  * FILE: gnushogi.h
3  *
4  *     Main header file for GNU Shogi.
5  *
6  * ----------------------------------------------------------------------
7  * Copyright (c) 1993, 1994, 1995 Matthias Mutz
8  * Copyright (c) 1999 Michael Vanier and the Free Software Foundation
9  * Copyright (c) 2008, 2013, 2014 Yann Dirson and the Free Software Foundation
10  *
11  * GNU SHOGI is based on GNU CHESS
12  *
13  * Copyright (c) 1988, 1989, 1990 John Stanback
14  * Copyright (c) 1992 Free Software Foundation
15  *
16  * This file is part of GNU SHOGI.
17  *
18  * GNU Shogi is free software; you can redistribute it and/or modify it
19  * under the terms of the GNU General Public License as published by the
20  * Free Software Foundation; either version 3 of the License,
21  * or (at your option) any later version.
22  *
23  * GNU Shogi is distributed in the hope that it will be useful, but WITHOUT
24  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
25  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
26  * for more details.
27  *
28  * You should have received a copy of the GNU General Public License along
29  * with GNU Shogi; see the file COPYING. If not, see
30  * <http://www.gnu.org/licenses/>.
31  * ----------------------------------------------------------------------
32  *
33  */
34
35 /* Hack for anal-retentive ANSI-compliance if desired: */
36 #define inline
37
38 /* FIXME: this file needs to be reorganized in some rational manner. */
39
40 #ifndef _GNUSHOGI_H_
41 #define _GNUSHOGI_H_
42
43 #include "config.h"        /* Portability #defines. */
44 #include "debug.h"
45 #include "opts.h"          /* Various option-setting #defines.  */
46
47 #include <stdarg.h>
48
49 /*
50  * Display options.
51  */
52
53 typedef enum {
54   DISPLAY_RAW,
55 #ifdef HAVE_LIBCURSES
56   DISPLAY_CURSES,
57 #endif
58   DISPLAY_X
59 } display_t;
60 extern display_t display_type;
61
62 #define XSHOGI     (display_type == DISPLAY_X)
63
64
65 /* Miscellaneous globals. */
66
67 extern short hard_time_limit; /* If you exceed time limit, you lose.   */
68 extern short nolist;          /* Don't list game after exit.           */
69
70
71 /*
72  * Options for various compilers/OSs.
73  */
74
75 /*
76  * type small_short must cover -128 .. 127.  In case of trouble,
77  * try commenting out "signed".  If this doesn't help, use short.
78  */
79
80 #define small_short  signed char
81 #define small_ushort unsigned char
82
83
84 typedef small_ushort   UBYTE;
85 typedef short          SHORT;
86 typedef unsigned short USHORT;
87 typedef int            INT;
88 typedef unsigned int   UINT;
89 typedef long           LONG;
90 typedef unsigned long  ULONG;
91
92
93 #if !defined(HAVE_MEMCPY) && !defined(HAVE_BCOPY)
94 #  define array_copy(src, dst, len) \
95    { \
96        long i; \
97        char  *psrc = (char  *)src, *pdst = (char  *)dst; \
98        for (i = len; i; pdst[--i] = psrc[i]); \
99    }
100 #  define array_zero(dst, len) \
101   { \
102       long i; \
103       char  *pdst = (char  *)dst; \
104       for (i = len; i; pdst[--i] = 0); \
105   }
106 #elif !defined(HAVE_MEMCPY)   /* BSD and derivatives */
107 #  define array_copy(src, dst, len) bcopy(src, dst, len)
108 #  define array_zero(dst, len)      bzero(dst, len)
109 #else /* System V and derivatives */
110 #  define array_copy(src, dst, len) memcpy(dst, src, len)
111 #  define array_zero(dst, len)      memset(dst, 0, len)
112 #endif
113
114
115 #ifndef __GNUC__
116 #  define inline
117 #endif
118
119
120 /*
121  * Standard header files.
122  */
123
124 #include <stdio.h>
125 #include <ctype.h>
126 #include <stdlib.h>
127 #include <assert.h>
128 #include <string.h>
129
130 #include <sys/param.h>
131 #include <sys/types.h>
132 #ifdef WIN32
133 #  include <windows.h>
134 #else
135    typedef small_short    BYTE;
136 #  include <sys/times.h>
137 #  include <sys/ioctl.h>
138 #endif
139
140 #if TIME_WITH_SYS_TIME
141 #  include <sys/time.h>
142 #  include <time.h>
143 #else
144 #  if HAVE_SYS_TIME_H
145 #    include <sys/time.h>
146 #  else
147 #    include <time.h>
148 #  endif
149 #endif
150
151 #define RWA_ACC "r+"
152 #define WA_ACC "w+"
153 #ifdef BINBOOK
154 extern char *binbookfile;
155 #endif
156
157 extern char *bookfile;
158 extern short ahead;
159 extern char  *xwin;
160 extern char  *Lang;
161 extern void movealgbr(short m, char *s);
162
163
164 #define SEEK_SET 0
165 #define SEEK_END 2
166
167 #ifdef MINISHOGI
168 #define NO_PIECES       11
169 #define MAX_CAPTURED    19
170 #define NO_PTYPE_PIECES 11
171 #define NO_COLS          5
172 #define NO_ROWS          5
173 #define NO_CAMP_ROWS     1
174 #else
175 #define NO_PIECES       15
176 #define MAX_CAPTURED    19
177 #define NO_PTYPE_PIECES 15
178 #define NO_COLS          9
179 #define NO_ROWS          9
180 #define NO_CAMP_ROWS     3
181 #endif
182 #define NO_SQUARES      (NO_COLS*NO_ROWS)
183
184 #define ROW_NAME(n) ('a' + NO_ROWS - 1 - n)
185 #define COL_NAME(n) ('1' + NO_COLS - 1 - n)
186 #define ROW_NUM(c) ('a' + NO_ROWS - 1 - c)
187 #define COL_NUM(c) ('1' + NO_COLS - 1 - c)
188
189 #if defined HASHFILE || defined CACHE
190 #  define PTBLBDSIZE (NO_SQUARES + NO_PIECES)
191 #endif
192
193 #include "eval.h"
194
195 #define SCORE_LIMIT 12000
196
197 /* masks into upper 16 bits of attacks array */
198 /* observe order of relative piece values */
199 #define CNT_MASK 0x000000FF
200 #define ctlP  0x00200000
201 #define ctlPp 0x00100000
202 #define ctlL  0x00080000
203 #define ctlN  0x00040000
204 #define ctlLp 0x00020000
205 #define ctlNp 0x00010000
206 #define ctlS  0x00008000
207 #define ctlSp 0x00004000
208 #define ctlG  0x00002000
209 #define ctlB  0x00001000
210 #define ctlBp 0x00000800
211 #define ctlR  0x00000400
212 #define ctlRp 0x00000200
213 #define ctlK  0x00000100
214
215 /* attack functions */
216 #define Pattack(c, u)   (attack[c][u] > ctlP)
217 #define Anyattack(c, u) (attack[c][u] != 0)
218
219 /* hashtable flags */
220 #define truescore   0x0001
221 #define lowerbound  0x0002
222 #define upperbound  0x0004
223 #define kingcastle  0x0008
224 #define queencastle 0x0010
225 #define evalflag    0x0020
226
227 /* King positions */
228 #define BlackKing PieceList[black][0]
229 #define WhiteKing PieceList[white][0]
230 #define OwnKing   PieceList[c1][0]
231 #define EnemyKing PieceList[c2][0]
232
233
234 /* board properties */
235 #define InBlackCamp(sq) ((sq) < (NO_COLS * NO_CAMP_ROWS))
236 #define InWhiteCamp(sq) ((sq) >= (NO_COLS * (NO_ROWS - NO_CAMP_ROWS)))
237 #define InPromotionZone(side, sq) \
238 (((side) == black) ? InWhiteCamp(sq) : InBlackCamp(sq))
239
240 /* constants */
241 /* FIXME ? */
242 #define OPENING_HINT 0x141d /* P7g-7f (20->29) */
243
244 /* truth values */
245 #ifndef false
246 #define false 0
247 #endif
248
249 #ifndef true
250 #define true  1
251 #endif
252
253 /* colors */
254 #define black   0
255 #define white   1
256 #define neutral 2
257
258 /* piece code defines */
259 enum {
260     no_piece = 0,
261     pawn,
262 #ifndef MINISHOGI
263     lance,
264     knight,
265 #endif
266     /* start of pieces that can be dropped at any square */
267     silver,
268     gold,
269     bishop,
270     rook,
271     ppawn,
272 #ifndef MINISHOGI
273     plance,
274     pknight,
275 #endif
276     psilver,
277     pbishop,
278     prook,
279     king
280 };
281
282 /* move types */
283 enum {
284     ptype_no_piece = 0,
285     ptype_pawn = 0,
286 #ifndef MINISHOGI
287     ptype_lance,
288     ptype_knight,
289 #endif
290     ptype_silver,
291     ptype_gold,
292     ptype_bishop,
293     ptype_rook,
294     ptype_pbishop,
295     ptype_prook,
296     ptype_king,
297     ptype_wpawn,
298 #ifndef MINISHOGI
299     ptype_wlance,
300     ptype_wknight,
301 #endif
302     ptype_wsilver,
303     ptype_wgold
304 };
305
306 /* node flags */
307 #define pmask        0x000f /*    15 */
308 #define promote      0x0010 /*    16 */
309 #define dropmask     0x0020 /*    32 */
310 #define exact        0x0040 /*    64 */
311 #define tesuji       0x0080 /*   128 */
312 #define check        0x0100 /*   256 */
313 #define capture      0x0200 /*   512 */
314 #define draw         0x0400 /*  1024 */
315 #define stupid       0x0800 /*  2048 */
316 #define questionable 0x1000 /*  4096 */
317 #define kingattack   0x2000 /*  8192 */
318 #define book         0x4000 /* 16384 */
319
320 /* move quality flags */
321 #define goodmove     tesuji
322 #define badmove      stupid
323 #ifdef EASY_OPENINGS
324 #define difficult    questionable
325 #endif
326
327 /* move symbols */
328 #ifndef MINISHOGI
329 #define pxx (" PLNSGBRPLNSBRK ")
330 #define qxx (" plnsgbrplnsbrk ")
331 #else
332 #define pxx (" PSGBRPSBRK ")
333 #define qxx (" psgbrpsbrk ")
334 #endif
335
336 /***************** Table limits ********************************************/
337
338 /*
339  * ttblsz must be a power of 2. Setting ttblsz 0 removes the transposition
340  * tables.
341  */
342
343 #if defined NOTTABLE
344 #  define vttblsz 0
345 #elif defined SMALL_MEMORY
346 #  if defined SAVE_SSCORE
347 #    define vttblsz (1 << 12)
348 #  else
349 #    if defined EXTRA_2MB
350 #      define vttblsz (1 << 12)
351 #    else
352 #      define vttblsz (1 << 10)
353 #    endif
354 #  endif
355 #else
356 #  define vttblsz (100001)
357 #endif
358
359 #if defined SMALL_MEMORY
360 #  define MINTTABLE (0)
361 #else
362 #  define MINTTABLE (8000)    /* min ttable size -1 */
363 #endif
364
365 #define ttblsz vttblsz
366
367 #if defined SMALL_MEMORY
368 #  if !defined SAVE_SSCORE
369 #    define TREE 1500             /* max number of tree entries */
370 #  else
371 #    define TREE 2500             /* max number of tree entries */
372 #  endif
373 #else
374 #  define TREE 4000               /* max number of tree entries */
375 #endif
376
377 #define MAXDEPTH  40            /* max depth a search can be carried */
378 #define MINDEPTH   2            /* min search depth =1 (no hint), >1 hint */
379 #define MAXMOVES 300            /* max number of half moves in a game */
380 #define CPSIZE   241            /* size of lang file max */
381
382 #if defined SMALL_MEMORY
383 #  if defined SAVE_SSCORE
384 #    define ETABLE (1 << 10)      /* static eval cache */
385 #  else
386 #    if defined EXTRA_2MB
387 #      define ETABLE (1 << 10)    /* static eval cache */
388 #    else
389 #      define ETABLE (1 << 8)     /* static eval cache */
390 #    endif
391 #  endif
392 #else
393 #  define ETABLE (10001)          /* static eval cache */
394 #endif
395
396 /***************** tuning paramaters *******************/
397
398 #if defined VERY_SLOW_CPU
399 #  define MINRESPONSETIME 300
400 #elif defined SLOW_CPU
401 #  define MINRESPONSETIME 200
402 #else
403 #  define MINRESPONSETIME 100     /* 1 s */
404 #endif
405
406 #define MINGAMEIN  4
407 #define MINMOVES  15
408 #define CHKDEPTH   1   /* always look forward CHKDEPTH
409                         * half-moves if in check */
410
411 #if defined SLOW_CPU || defined VERY_SLOW_CPU
412 #  define DEPTHBEYOND 7     /* Max to go beyond Sdepth */
413 #else
414 #  define DEPTHBEYOND 11    /* Max to go beyond Sdepth */
415 #endif
416
417 #define HASHDEPTH      4  /* depth above which to use HashFile */
418 #define HASHMOVELIMIT 40  /* Use HashFile only for this many moves */
419 #define PTVALUE        0  /* material value below which pawn threats at
420                            * 5 & 3 are used */
421 #define ZDEPTH 3          /* depth beyond which to check
422                            * ZDELTA for extra time */
423 #define ZDELTA 10         /* score delta per ply to cause
424                            * extra time to be given */
425 #define BESTDELTA 90
426
427 /* about 1/2 second worth of nodes for your machine */
428 #if defined VERY_SLOW_CPU
429 /* check the time every ZNODES positions */
430 #  define ZNODES (flag.tsume ? 20 : 50)
431 #elif defined SLOW_CPU
432 #  define ZNODES (flag.tsume ? 40 : 100)
433 #else
434 #  define ZNODES (flag.tsume ? 400 : 1000)
435 #endif
436
437 #define MAXTCCOUNTX  10  /* max number of time clicks
438                           * per search to complete ply */
439 #define MAXTCCOUNTR   4  /* max number of time clicks
440                           * per search extensions*/
441 #define SCORESPLIM    8  /* Score space doesn't apply after this stage */
442 #define SDEPTHLIM    (Sdepth + 1)
443 #define HISTORYLIM 4096  /* Max value of history killer */
444
445 #ifdef EXACTHISTORY
446 #  if defined SMALL_MEMORY
447 #    define HISTORY_MASK 0x8000     /* mask to MSB of history index */
448 #    define HISTORY_SIZE 0x10000    /* size of history table */
449 #  else
450 #    define HISTORY_MASK (1 << 15)  /* mask to MSB of history index */
451 #    define HISTORY_SIZE (1 << 16)  /* size of history table */
452 #  endif
453 #else
454 /* smaller history table, but dangerous because of collisions */
455 #  define HISTORY_MASK 0x3fff     /* mask to significant bits
456                                    * of history index */
457 #  if defined SMALL_MEMORY
458 #    define HISTORY_SIZE 0x4000 /* size of history table */
459 #  else
460 #    define HISTORY_SIZE (1 << 14)  /* size of history table */
461 #  endif
462 #endif
463
464 #define sizeof_history (sizeof(unsigned short) * (size_t)HISTORY_SIZE)
465
466 #ifdef EXACTHISTORY
467 /* Map from.to (8bit.8bit) to from.to (0.7bit.8bit) */
468 #  define khmove(mv) (mv & 0x7fff)
469 #  define hmove(mv) ((mv & 0x7fff) ^ 0x5555)
470 #else
471 /* Map from.to (8bit.8bit) to from.to (00.7bit.7bit) */
472 /* Swap bits of ToSquare in case of promotions, hoping that
473    no catastrophic collision occurs. */
474 #  define khmove(mv) (((mv & 0x7f00) >> 1) | \
475            ((mv & 0x0080) ? ((mv & 0x007f) ^ 0x007f) : (mv & 0x007f)))
476 #  define hmove(mv) (khmove(mv) ^ 0x2aaa)
477 #endif
478
479 /* mask color to 15th bit */
480 #ifdef EXACTHISTORY
481 #  define hindex(c, mv) ((c ? HISTORY_MASK : 0) | hmove(mv))
482 #else
483 /* for white, swap bits, hoping that no catastrophic collision occurs. */
484 #  define hindex(c, mv) (c ? ((~hmove(mv)) & HISTORY_MASK) : hmove(mv))
485 #endif
486
487 #define EWNDW  10    /* Eval window to force position scoring at depth
488                       * greater than (Sdepth + 2)        */
489 #define WAWNDW 90    /* alpha window when computer black */
490 #define WBWNDW 90    /* beta window when computer black  */
491 #define BAWNDW 90    /* alpha window when computer white */
492 #define BBWNDW 90    /* beta window when computer white  */
493 #define BXWNDW 90    /* window to force position scoring at lower */
494 #define WXWNDW 90    /* window to force position scoring at lower */
495
496 #define DITHER  5    /* max amount random can alter a pos value */
497 #define LBONUS  1    /* points per stage value of L increases   */
498 #define BBONUS  2    /* points per stage value of B increases   */
499 #define RBONUS  2    /* points per stage value of R increases   */
500
501 #define QUESTIONABLE (valueK)   /* Penalty for questionable moves. */
502
503 #if defined STUPID
504 #  undef STUPID
505 #endif
506
507 #define STUPID (valueR << 1)    /* Penalty for stupid moves. */
508
509 #define KINGPOSLIMIT (-1)      /* King positional scoring limit */
510 #define KINGSAFETY  32
511 #define MAXrehash (7)
512
513 /******* parameters for Opening Book ****************/
514
515 #define BOOKSIZE   8000  /* Number of unique position/move
516                           * combinations allowed */
517 #define BOOKMAXPLY   40           /* Max plys to keep in book database */
518 #define BOOKFAIL (BOOKMAXPLY / 2) /* if no book move found for BOOKFAIL
519                                    * turns stop using book */
520 #define BOOKPOCKET          64
521 #define BOOKRAND          1000  /* used to select an opening move
522                                  * from a list */
523 #define BOOKENDPCT         950  /* 5 % chance a BOOKEND will stop the book */
524 #define DONTUSE         -32760  /* flag move as don't use */
525 #define ILLEGAL_TRAPPED -32761  /* flag move as illegal:
526                                  * no move from this square */
527 #define ILLEGAL_DOUBLED -32762  /* flag move as illegal:
528                                  * two pawns on one column */
529 #define ILLEGAL_MATE    -32763  /* flag move as illegal:
530                                  * pawn drop with mate */
531
532 /*****************************************************/
533
534 struct hashval
535 {
536     unsigned long key, bd;
537 };
538
539 struct hashentry
540 {
541     unsigned long hashbd;
542     unsigned short mv;
543     unsigned char depth; /* unsigned char saves some space */
544     unsigned char flags;
545 #ifdef notdef
546     unsigned short age;
547 #endif
548     short score;
549 #ifdef HASHTEST
550     unsigned char bd[PTBLBDSIZE];
551 #endif /* HASHTEST */
552 };
553
554 #if defined HASHFILE || defined CACHE
555 struct etable
556 {
557     unsigned long ehashbd;
558     short escore[2];
559 #if !defined SAVE_SSCORE
560     short sscore[NO_SQUARES];
561 #endif
562     short score;
563     small_short hung[2];
564 #ifdef CACHETEST
565     unsigned char bd[PTBLBDSIZE];
566 #endif /* CACHETEST */
567 };
568
569 #if defined CACHE
570 extern short use_etable;
571 typedef struct etable etable_field[ETABLE];
572 extern etable_field  *etab[2];
573 #endif
574
575 /*
576  * CHECKME! Is this valid?
577  *
578  * persistent transposition table. By default, the size is (1 << vfilesz).
579  * If you change the size, be sure to run gnushogi -c [vfilesz]
580  * before anything else.
581  */
582
583 #define frehash 6
584
585 #if defined SMALL_MEMORY
586 #  define vfilesz 10
587 #else
588 #  define vfilesz 14
589 #endif
590
591 struct fileentry
592 {
593     unsigned char bd[PTBLBDSIZE];
594     unsigned char f, t, flags, depth, sh, sl;
595 };
596
597 #endif /* HASHFILE */
598
599
600 struct leaf
601 {
602     small_ushort f, t;
603     short score, reply, width;
604     short INCscore;
605     unsigned short flags;
606 };
607
608
609 struct GameRec
610 {
611     unsigned short gmove;    /* this move */
612     short score;             /* score after this move */
613     short depth;             /* search depth this move */
614     long  time;               /* search time this move */
615     short fpiece;            /* moved or dropped piece */
616     short piece;             /* piece captured */
617     short color;             /* color */
618     short flags;             /* move flags capture, promote, castle */
619     short Game50;            /* flag for repetition */
620     long  nodes;              /* nodes searched for this move */
621     unsigned long hashkey, hashbd;   /* board key before this move */
622 };
623
624
625 struct TimeControlRec
626 {
627     short moves[2];
628     long  clock[2];
629 };
630
631
632 struct flags
633 {
634     short mate;              /* the game is over */
635     short post;              /* show principle variation */
636     short quit;              /* quit/exit */
637     short regularstart;      /* did the game start from standard
638                               * initial board ? */
639     short reverse;           /* reverse board display */
640     short bothsides;         /* computer plays both sides */
641     short hash;              /* enable/disable transposition table */
642     short force;             /* enter moves */
643     short easy;              /* disable thinking on opponents time */
644     short beep;              /* enable/disable beep */
645     short timeout;           /* time to make a move */
646     short musttimeout;       /* time to make a move */
647     short back;              /* time to make a move */
648     short rcptr;             /* enable/disable recapture heuristics */
649     short rv;                /* reverse video */
650     short stars;             /* add stars to uxdsp screen */
651     short coords;            /* add coords to visual screen */
652     short shade;
653     short material;          /* draw on lack of material */
654     short illegal;           /* illegal position */
655     short onemove;           /* timing is onemove */
656     short gamein;            /* timing is gamein */
657     short tsume;             /* first consider checks */
658 };
659
660 extern FILE *debugfile;
661
662 #ifndef EVALFILE
663 #define EVALFILE "/tmp/EVAL"
664 #endif
665
666 extern FILE *debug_eval_file;
667 extern short debug_moves;
668
669
670 #ifdef HISTORY
671 extern short use_history;
672 extern unsigned short  *history;
673 #endif
674
675 extern long znodes;
676
677 extern char ColorStr[2][10];
678
679 extern char mvstr[4][6];
680 extern int mycnt1, mycnt2;
681 extern short ahead;
682 extern struct leaf rootnode;
683 extern struct leaf  *Tree;
684 extern struct leaf  *root;
685 extern char savefile[], listfile[];
686 extern short TrPnt[];
687 extern small_short board[], color[];
688 extern const small_short sweep[NO_PIECES];
689 extern small_short PieceList[2][NO_SQUARES], PawnCnt[2][NO_COLS];
690 extern small_short Captured[2][NO_PIECES];
691
692 #ifndef HAVE_MEMSET
693 #  define ClearCaptured() \
694   { \
695       short piece, color; \
696       for (color = black; color <= white; color++) \
697           for (piece = 0; piece < NO_PIECES; piece++) \
698               Captured[color][piece] = 0; \
699   }
700 #else
701 #  define ClearCaptured() \
702   memset((char *)Captured, 0, (unsigned long)sizeof(Captured))
703 #endif /* HAVE_MEMSET */
704
705 extern small_short Mvboard[];
706
707 #if !defined SAVE_SVALUE
708 extern short svalue[NO_SQUARES];
709 #endif
710
711 extern short pscore[2]; /* eval.c */
712 extern int EADD; /* eval.c */
713 extern int EGET; /* eval.c */
714 extern struct flags flag;
715 extern short opponent, computer, INCscore;
716 extern short WAwindow, BAwindow, WBwindow, BBwindow;
717 extern short dither, player;
718 extern short xwndw, contempt;
719 extern long  ResponseTime, ExtraTime, TCleft,
720     MaxResponseTime, et, et0, time0, ft;
721 extern int   TCcount;
722
723 #ifdef INTERRUPT_TEST
724 extern long itime0, it;
725 #endif
726
727 extern long  reminus, replus;
728 extern long  GenCnt, NodeCnt, ETnodes, EvalNodes, HashAdd, HashCnt,
729     HashCol, THashCol, FHashCnt, FHashAdd;
730 extern short HashDepth, HashMoveLimit;
731 extern struct GameRec  *GameList;
732 extern short GameCnt, Game50;
733 extern short Sdepth, MaxSearchDepth;
734 extern int   Book;
735 extern struct TimeControlRec TimeControl;
736 extern int   TCadd;
737 extern short TCflag, TCmoves, TCminutes, TCseconds, OperatorTime;
738 extern int   timecomp[MINGAMEIN], timeopp[MINGAMEIN];
739 extern int   compptr, oppptr;
740 extern short XCmore, XCmoves[], XCminutes[], XCseconds[], XC;
741 extern const short otherside[];
742 extern const small_short Stboard[];
743 extern const small_short Stcolor[];
744 extern unsigned short hint;
745 extern short TOflag;
746 extern short stage, stage2;
747
748 #define in_opening_stage    (!flag.tsume && (stage < 33))
749 #define in_middlegame_stage (!flag.tsume && (stage >= 33) && (stage <= 66))
750 #define in_endgame_stage    (flag.tsume || (stage > 66))
751
752 extern short ahead, hash;
753 extern short balance[2];
754 extern small_short ChkFlag[], CptrFlag[], TesujiFlag[];
755 extern short Pscore[], Tscore[];
756 extern /*unsigned*/ short rehash;  /* -1 is used as a flag --tpm */
757 extern unsigned int ttbllimit;
758 extern unsigned int TTadd;
759 extern unsigned int ttblsize;
760 extern short mtl[], hung[];
761 extern small_short Pindex[];
762 extern small_short PieceCnt[];
763 extern short FROMsquare, TOsquare;
764 extern small_short HasPiece[2][NO_PIECES];
765 extern const short kingP[];
766 extern unsigned short killr0[], killr1[];
767 extern unsigned short killr2[], killr3[];
768 extern unsigned short PrVar[MAXDEPTH];
769 extern unsigned short PV, SwagHt, Swag0, Swag1, Swag2, Swag3, Swag4, sidebit;
770 extern short mtl[2], pmtl[2], hung[2];
771 extern const small_short relative_value[];
772 extern const long control[];
773 extern small_short diagonal(short delta);
774 extern const small_short promoted[NO_PIECES], unpromoted[NO_PIECES];
775 extern const small_short is_promoted[NO_PIECES];
776
777 typedef unsigned char next_array[NO_SQUARES][NO_SQUARES];
778 typedef small_short distdata_array[NO_SQUARES][NO_SQUARES];
779
780 extern const small_short inunmap[NO_SQUARES];
781 #ifndef MINISHOGI
782 extern const small_short nunmap[(NO_COLS + 2)*(NO_ROWS + 4)];
783 #else
784 extern const small_short nunmap[(NO_COLS + 2)*(NO_ROWS + 2)];
785 #endif
786
787 #if defined SAVE_NEXTPOS
788 extern const small_short direc[NO_PTYPE_PIECES][8];
789 extern short first_direction(short ptyp, short *d, short sq);
790 extern short next_direction(short ptyp, short *d, short sq);
791 extern short next_position(short ptyp, short *d, short sq, short u);
792 #else
793 extern short use_nextpos;
794 extern next_array  *nextpos[NO_PTYPE_PIECES];
795 extern next_array  *nextdir[NO_PTYPE_PIECES];
796 #endif
797
798 extern value_array   *value;
799 extern fscore_array  *fscore;
800
801 #ifndef SAVE_DISTDATA
802 extern short use_distdata;
803 extern distdata_array  *distdata;
804 #endif
805
806 #ifndef SAVE_PTYPE_DISTDATA
807 extern short use_ptype_distdata;
808 extern distdata_array  *ptype_distdata[NO_PTYPE_PIECES];
809 #endif
810
811 extern const small_short ptype[2][NO_PIECES];
812
813 extern long filesz, hashmask, hashbase;
814 extern FILE *hashfile;
815 extern unsigned int starttime;
816
817 /* eval.c */
818 typedef small_short Mpiece_array[2][NO_SQUARES];
819 extern Mpiece_array *Mpiece[NO_PIECES];
820 extern short ADVNCM[NO_PIECES];
821
822 #define computed_distance(a, b) \
823     ((abs(column(a) - column(b)) > abs(row(a) - row(b))) \
824     ? abs(column(a) - column(b)) : abs(row(a) - row(b)))
825
826 extern short distance(short a, short b);
827 extern short ptype_distance(short ptyp, short f, short t);
828 extern short piece_distance(short side, short piece, short f, short t);
829
830 #if defined UNKNOWN
831 #  undef UNKNOWN
832 #endif
833
834 #define UNKNOWN      'U'
835 #define STATIC_ROOK  'S'
836 #define RANGING_ROOK 'R'
837
838 extern char GameType[2];
839 void ShowGameType(void);
840
841 extern unsigned short bookmaxply;
842 extern unsigned int bookcount;
843 extern unsigned int booksize;
844 extern unsigned long hashkey, hashbd;
845
846 typedef struct hashval hashcode_array[2][NO_PIECES][NO_SQUARES];
847 typedef struct hashval drop_hashcode_array[2][NO_PIECES][NO_SQUARES];
848
849 extern hashcode_array  *hashcode;
850 extern drop_hashcode_array  *drop_hashcode;
851
852 #ifdef QUIETBACKGROUND
853 extern short background;
854 #endif /* QUIETBACKGROUND */
855
856 #if ttblsz
857 extern short use_ttable;
858 extern struct hashentry  *ttable[2];
859 #endif
860
861 /*
862  * hashbd contains a 32 bit "signature" of the board position. hashkey
863  * contains a 16 bit code used to address the hash table. When a move is
864  * made, XOR'ing the hashcode of moved piece on the from and to squares with
865  * the hashbd and hashkey values keeps things current.
866  */
867
868 #define UpdateHashbd(side, piece, f, t) \
869 { \
870   if ((f) >= 0) \
871     { \
872       hashbd  ^= (*hashcode)[side][piece][f].bd;  \
873       hashkey ^= (*hashcode)[side][piece][f].key; \
874     } \
875  \
876   if ((t) >= 0) \
877     { \
878       hashbd  ^= (*hashcode)[side][piece][t].bd;  \
879       hashkey ^= (*hashcode)[side][piece][t].key; \
880     } \
881 }
882
883 #define UpdateDropHashbd(side, piece, count) \
884 { \
885   hashbd  ^= (*drop_hashcode)[side][piece][count].bd;  \
886   hashkey ^= (*drop_hashcode)[side][piece][count].key; \
887 }
888
889
890 extern short rpthash[2][256];
891 extern char *DRAW;
892
893 extern char* DRAW_REPETITION;
894 extern char *DRAW_MAXMOVES;
895 extern char *DRAW_JUSTDRAW;
896
897 #define row(a)     ((a) / NO_COLS)
898 #define column(a)  ((a) % NO_COLS)
899 #define locn(a, b) (((a) * NO_COLS) + b)
900
901 /* init external functions */
902 extern void InitConst(char *lang); /* init.c */
903 extern int  Initialize_data(void); /* init.c */
904 extern void Free_data(void);       /* init.c */
905 extern int  Lock_data(void);       /* init.c */
906 extern void Unlock_data(void);     /* init.c */
907 extern void Initialize_dist(void); /* init.c */
908 extern void Initialize_eval(void); /* eval.c */
909 extern void NewGame(void);
910 extern void GetOpenings(void);
911 extern int  OpeningBook(unsigned short *hint);
912
913 typedef enum
914 {
915     REMOVE_PIECE = 1, ADD_PIECE
916 } UpdatePieceList_mode;
917
918 extern void
919 UpdatePieceList(short side, short sq, UpdatePieceList_mode iop);
920
921 typedef enum
922 {
923     FOREGROUND_MODE = 1, BACKGROUND_MODE
924 } SelectMove_mode;
925
926 extern void
927 SelectMove(short side, SelectMove_mode iop);
928
929 extern int
930 search(short side,
931        short ply,
932        short depth,
933        short alpha,
934        short beta,
935        unsigned short *bstline,
936        short *rpt);
937
938 #ifdef CACHE
939 void PutInEETable(short side, int score);
940 int  CheckEETable(short side);
941 int  ProbeEETable(short side, short *score);
942 #endif
943
944 #if ttblsz
945 extern int
946 ProbeTTable(short side,
947             short depth,
948             short ply,
949             short *alpha,
950             short *beta,
951             short *score);
952
953 extern int
954 PutInTTable(short side,
955             short score,
956             short depth,
957             short ply,
958             short beta,
959             unsigned short mv);
960
961 extern void ZeroTTable(void);
962 extern void ZeroRPT(void);
963 extern void Initialize_ttable(void);
964 extern unsigned int urand(void);
965
966 #  ifdef HASHFILE
967 extern void gsrand(unsigned int);
968
969 extern int
970 ProbeFTable(short side,
971             short depth,
972             short ply,
973             short *alpha,
974             short *beta,
975             short *score);
976
977 extern void
978 PutInFTable(short side,
979             short score,
980             short depth,
981             short ply,
982             short alpha,
983             short beta,
984             unsigned short f,
985             unsigned short t);
986
987 #  endif /* HASHFILE */
988 #endif /* ttblsz */
989
990 #if !defined SAVE_NEXTPOS
991 extern void Initialize_moves(void);
992 #endif
993
994 extern short generate_move_flags;
995
996 extern void MoveList(short side, short ply,
997                      short in_check, short blockable);
998 extern void CaptureList(short side, short ply,
999                         short in_check, short blockable);
1000
1001 /* from attacks.c */
1002 extern int
1003 SqAttacked(short square, short side, short *blockable);
1004
1005 extern void
1006 MakeMove(short side,
1007          struct leaf  *node,
1008          short *tempb,
1009          short *tempc,
1010          short *tempsf,
1011          short *tempst,
1012          short *INCscore);
1013
1014 extern void
1015 UnmakeMove(short side,
1016            struct leaf  *node,
1017            short *tempb,
1018            short *tempc,
1019            short *tempsf,
1020            short *tempst);
1021
1022 extern void
1023 InitializeStats(void);
1024
1025 extern int
1026 evaluate(short side,
1027          short ply,
1028          short alpha,
1029          short beta,
1030          short INCscore,
1031          short *InChk,
1032          short *blockable);
1033
1034 extern short ScorePosition(short side);
1035 extern void  ExaminePosition(short side);
1036 extern short ScorePatternDistance(short side);
1037 extern void  DetermineStage(short side);
1038 extern void  UpdateWeights(short side);
1039 extern int   InitMain(void);
1040 extern void  ExitMain(void);
1041 extern void  Initialize(void);
1042 extern void  InputCommand(char *command);
1043 extern void  ExitShogi(void);
1044 extern void  ClearScreen(void);
1045 extern void  SetTimeControl(void);
1046 extern void  SelectLevel(char *sx);
1047
1048 extern void
1049 UpdateDisplay(short f,
1050               short t,
1051               short flag,
1052               short iscastle);
1053
1054 typedef enum
1055 {
1056     COMPUTE_AND_INIT_MODE = 1, COMPUTE_MODE
1057 #ifdef INTERRUPT_TEST
1058     , INIT_INTERRUPT_MODE, COMPUTE_INTERRUPT_MODE
1059 #endif
1060 } ElapsedTime_mode;
1061
1062 extern void  SetResponseTime(short side);
1063 extern void  CheckForTimeout(int score, int globalscore,
1064                              int Jscore, int zwndw);
1065 extern void  ShowSidetoMove(void);
1066 extern void  ShowResponseTime(void);
1067 extern void  ShowPatternCount(short side, short n);
1068 extern void  SearchStartStuff(short side);
1069 extern void  ShowDepth(char ch);
1070 extern void  TerminateSearch(int);
1071 extern void  ShowResults(short score, unsigned short *bstline, char ch);
1072 extern void  SetupBoard(void);
1073 extern void  algbr(short f, short t, short flag);
1074 extern void  OutputMove(void);
1075 extern void  ShowCurrentMove(short pnt, short f, short t);
1076 extern void  ListGame(void);
1077 extern void  ShowMessage(char *s);
1078 extern void  ClearScreen(void);
1079 extern void  DoDebug(void);
1080 extern void  DoTable(short table[NO_SQUARES]);
1081 extern void  ShowPostnValues(void);
1082 extern void  ChangeXwindow(void);
1083 extern void  SetContempt(void);
1084 extern void  ChangeHashDepth(void);
1085 extern void  ChangeBetaWindow(void);
1086 extern void  GiveHint(void);
1087 extern void  ShowPrompt(void);
1088 extern void  EditBoard(void);
1089 extern void  help(void);
1090 extern void  ChangeSearchDepth(void);
1091 extern void  skip(void);
1092 extern void  skipb(void);
1093 extern void  EnPassant(short xside, short f, short t, short iop);
1094 extern void  ShowNodeCnt(long NodeCnt);
1095 extern void  ShowLine(unsigned short *bstline);
1096 extern int   pick(short p1, short p2);
1097 extern short repetition(void);
1098 extern void  TimeCalc(void);
1099 extern void  ElapsedTime(ElapsedTime_mode iop);
1100
1101 extern short
1102 DropPossible(short piece, short side, short sq); /* genmoves.c */
1103
1104 extern short
1105 IsCheckmate(short side, short in_check,
1106             short blockable); /* genmoves.c */
1107
1108
1109 typedef enum
1110 {
1111     VERIFY_AND_MAKE_MODE, VERIFY_AND_TRY_MODE, UNMAKE_MODE
1112 } VerifyMove_mode;
1113
1114 extern int VerifyMove(char *s, VerifyMove_mode iop, unsigned short *mv);
1115 extern unsigned short TTage;
1116
1117 /* display driver framework */
1118
1119 struct display
1120 {
1121     void (*ChangeAlphaWindow)(void);
1122     void (*ChangeBetaWindow)(void);
1123     void (*ChangeHashDepth)(void);
1124     void (*ChangeSearchDepth)(char *sx);
1125     void (*ChangeXwindow)(void);
1126     void (*ClearScreen)(void);
1127     void (*DoDebug)(void);
1128     void (*DoTable)(short table[NO_SQUARES]);
1129     void (*EditBoard)(void);
1130     void (*ExitShogi)(void);
1131     void (*GiveHint)(void);
1132     void (*Initialize)(void);
1133     void (*ShowNodeCnt)(long NodeCnt);
1134     void (*OutputMove)(void);
1135     void (*PollForInput)(void);
1136     void (*SetContempt)(void);
1137     void (*SearchStartStuff)(short side);
1138     void (*SelectLevel)(char *sx);
1139     void (*ShowCurrentMove)(short pnt, short f, short t);
1140     void (*ShowDepth)(char ch);
1141     void (*ShowGameType)(void);
1142     void (*ShowLine)(unsigned short *bstline);
1143     void (*ShowMessage)(char *s);
1144     void (*AlwaysShowMessage)(const char *format, ...);
1145     void (*Printf)(const char *format, ...);
1146     void (*doRequestInputString)(const char* fmt, char* buffer);
1147     int  (*GetString)(char* sx);
1148     void (*SetupBoard)(void);
1149     void (*ShowPatternCount)(short side, short n);
1150     void (*ShowPostnValue)(short sq);
1151     void (*ShowPostnValues)(void);
1152     void (*ShowPrompt)(void);
1153     void (*ShowResponseTime)(void);
1154     void (*ShowResults)(short score, unsigned short *bstline, char ch);
1155     void (*ShowSidetoMove)(void);
1156     void (*ShowStage)(void);
1157     void (*TerminateSearch)(int sig);
1158     void (*UpdateClocks)(void);
1159     void (*UpdateDisplay)(short f, short t, short redraw, short isspec);
1160     void (*help)(void);
1161 };
1162
1163 extern struct display *dsp;
1164
1165 extern struct display raw_display;
1166 extern struct display curses_display;
1167
1168 #endif /* _GNUSHOGI_H_ */