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