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