2024-04-24 10:41:01 +02:00
|
|
|
# Copyright 2024 Mattia Giambirtone & All Contributors
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
|
|
## Implementation of a UCI compatible server
|
|
|
|
import std/strutils
|
|
|
|
import std/strformat
|
2024-04-25 15:20:55 +02:00
|
|
|
import std/atomics
|
2024-04-24 10:41:01 +02:00
|
|
|
|
|
|
|
|
|
|
|
import board
|
|
|
|
import movegen
|
2024-04-24 19:38:54 +02:00
|
|
|
import search
|
2024-04-24 10:41:01 +02:00
|
|
|
|
|
|
|
|
|
|
|
type
|
|
|
|
UCISession = ref object
|
|
|
|
debug: bool
|
|
|
|
board: Chessboard
|
2024-04-24 19:38:54 +02:00
|
|
|
searching: bool
|
|
|
|
currentSearch: SearchManager
|
2024-04-25 23:41:25 +02:00
|
|
|
hashTableSize: uint64
|
2024-04-24 10:41:01 +02:00
|
|
|
|
|
|
|
UCICommandType = enum
|
2024-04-24 19:38:54 +02:00
|
|
|
Unknown,
|
|
|
|
IsReady,
|
|
|
|
NewGame,
|
2024-04-24 10:41:01 +02:00
|
|
|
Quit,
|
|
|
|
Debug,
|
2024-04-24 12:38:03 +02:00
|
|
|
Position,
|
2024-04-25 18:53:51 +02:00
|
|
|
SetOption,
|
2024-04-24 19:38:54 +02:00
|
|
|
Go,
|
|
|
|
Stop
|
2024-04-24 10:41:01 +02:00
|
|
|
|
|
|
|
UCICommand = object
|
|
|
|
case kind: UCICommandType
|
|
|
|
of Debug:
|
2024-04-25 23:41:25 +02:00
|
|
|
on: bool
|
2024-04-24 10:41:01 +02:00
|
|
|
of Position:
|
|
|
|
fen: string
|
|
|
|
moves: seq[string]
|
2024-04-25 23:41:25 +02:00
|
|
|
of SetOption:
|
|
|
|
name: string
|
|
|
|
value: string
|
2024-04-24 10:41:01 +02:00
|
|
|
of Unknown:
|
|
|
|
reason: string
|
2024-04-24 12:38:03 +02:00
|
|
|
of Go:
|
|
|
|
wtime: int
|
|
|
|
btime: int
|
|
|
|
winc: int
|
|
|
|
binc: int
|
|
|
|
movesToGo: int
|
|
|
|
depth: int
|
|
|
|
moveTime: int
|
2024-04-25 15:20:55 +02:00
|
|
|
nodes: uint64
|
|
|
|
searchmoves: seq[Move]
|
2024-04-24 10:41:01 +02:00
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
|
|
|
|
2024-04-25 15:20:55 +02:00
|
|
|
proc parseUCIMove(session: UCISession, move: string): tuple[move: Move, command: UCICommand] =
|
2024-04-24 10:41:01 +02:00
|
|
|
var
|
|
|
|
startSquare: Square
|
|
|
|
targetSquare: Square
|
|
|
|
flags: seq[MoveFlag]
|
|
|
|
if len(move) notin 4..5:
|
2024-04-24 12:38:03 +02:00
|
|
|
return (nullMove(), UCICommand(kind: Unknown, reason: "invalid move syntax"))
|
2024-04-24 10:41:01 +02:00
|
|
|
try:
|
|
|
|
startSquare = move[0..1].toSquare()
|
|
|
|
except ValueError:
|
|
|
|
return (nullMove(), UCICommand(kind: Unknown, reason: &"invalid start square {move[0..1]}"))
|
|
|
|
try:
|
|
|
|
targetSquare = move[2..3].toSquare()
|
|
|
|
except ValueError:
|
|
|
|
return (nullMove(), UCICommand(kind: Unknown, reason: &"invalid target square {move[2..3]}"))
|
|
|
|
|
|
|
|
# Since the client tells us just the source and target square of the move,
|
|
|
|
# we have to figure out all the flags by ourselves (whether it's a double
|
|
|
|
# push, a capture, a promotion, etc.)
|
|
|
|
if session.board.getPiece(targetSquare).kind != Empty:
|
|
|
|
flags.add(Capture)
|
|
|
|
|
|
|
|
if session.board.getPiece(startSquare).kind == Pawn and abs(rankFromSquare(startSquare) - rankFromSquare(targetSquare)) == 2:
|
|
|
|
flags.add(DoublePush)
|
|
|
|
|
|
|
|
if len(move) == 5:
|
|
|
|
# Promotion
|
|
|
|
case move[4]:
|
|
|
|
of 'b':
|
|
|
|
flags.add(PromoteToBishop)
|
|
|
|
of 'n':
|
|
|
|
flags.add(PromoteToKnight)
|
|
|
|
of 'q':
|
|
|
|
flags.add(PromoteToQueen)
|
|
|
|
of 'r':
|
|
|
|
flags.add(PromoteToRook)
|
|
|
|
else:
|
|
|
|
return
|
|
|
|
let piece = session.board.getPiece(startSquare)
|
|
|
|
if piece.kind == King and startSquare == session.board.position.sideToMove.getKingStartingSquare():
|
|
|
|
if targetSquare in [piece.kingSideCastling(), piece.queenSideCastling()]:
|
|
|
|
flags.add(Castle)
|
2024-04-25 23:41:25 +02:00
|
|
|
elif piece.kind == Pawn and targetSquare == session.board.position.enPassantSquare:
|
|
|
|
# I hate en passant I hate en passant I hate en passant I hate en passant I hate en passant I hate en passant
|
2024-04-24 10:41:01 +02:00
|
|
|
flags.add(EnPassant)
|
2024-04-25 15:20:55 +02:00
|
|
|
result.move = createMove(startSquare, targetSquare, flags)
|
|
|
|
|
|
|
|
|
|
|
|
proc handleUCIMove(session: UCISession, move: string): tuple[move: Move, cmd: UCICommand] {.discardable.} =
|
2024-04-24 10:41:01 +02:00
|
|
|
if session.debug:
|
|
|
|
echo &"info string making move {move}"
|
2024-04-25 15:20:55 +02:00
|
|
|
let
|
|
|
|
r = session.parseUCIMove(move)
|
|
|
|
move = r.move
|
|
|
|
command = r.command
|
|
|
|
if move == nullMove():
|
|
|
|
return (move, command)
|
|
|
|
else:
|
|
|
|
result.move = session.board.makeMove(move)
|
|
|
|
|
|
|
|
|
|
|
|
proc handleUCIGoCommand(session: UCISession, command: seq[string]): UCICommand =
|
|
|
|
result = UCICommand(kind: Go)
|
|
|
|
result.wtime = 0
|
|
|
|
result.btime = 0
|
|
|
|
result.winc = 0
|
|
|
|
result.binc = 0
|
|
|
|
result.movesToGo = 0
|
|
|
|
result.depth = -1
|
|
|
|
result.moveTime = -1
|
|
|
|
result.nodes = 0
|
|
|
|
var
|
|
|
|
current = 1 # Skip the "go"
|
|
|
|
while current < command.len():
|
|
|
|
let flag = command[current]
|
|
|
|
inc(current)
|
|
|
|
case flag:
|
|
|
|
of "infinite":
|
|
|
|
result.wtime = int32.high()
|
|
|
|
result.btime = int32.high()
|
|
|
|
of "wtime":
|
|
|
|
result.wtime = command[current].parseInt()
|
|
|
|
of "btime":
|
|
|
|
result.btime = command[current].parseInt()
|
|
|
|
of "winc":
|
|
|
|
result.winc = command[current].parseInt()
|
|
|
|
of "binc":
|
|
|
|
result.binc = command[current].parseInt()
|
|
|
|
of "movestogo":
|
|
|
|
result.movesToGo = command[current].parseInt()
|
|
|
|
of "depth":
|
|
|
|
result.depth = command[current].parseInt()
|
|
|
|
of "movetime":
|
|
|
|
result.moveTime = command[current].parseInt()
|
|
|
|
of "nodes":
|
|
|
|
result.nodes = command[current].parseBiggestUInt()
|
|
|
|
of "searchmoves":
|
|
|
|
while current < command.len():
|
|
|
|
inc(current)
|
|
|
|
if command[current] == "":
|
|
|
|
break
|
|
|
|
let move = session.parseUCIMove(command[current]).move
|
|
|
|
if move == nullMove():
|
|
|
|
return UCICommand(kind: Unknown, reason: &"invalid move '{command[current]}' for searchmoves")
|
|
|
|
result.searchmoves.add(move)
|
|
|
|
else:
|
|
|
|
discard
|
2024-04-24 10:41:01 +02:00
|
|
|
|
|
|
|
|
|
|
|
proc handleUCIPositionCommand(session: UCISession, command: seq[string]): UCICommand =
|
|
|
|
# Makes sure we don't leave the board in an invalid state if
|
|
|
|
# some error occurs
|
|
|
|
result = UCICommand(kind: Position)
|
|
|
|
case command[1]:
|
|
|
|
of "startpos":
|
|
|
|
result.fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
|
|
|
|
session.board = newDefaultChessboard()
|
|
|
|
if command.len() > 2:
|
|
|
|
let args = command[2..^1]
|
|
|
|
if args.len() > 0:
|
|
|
|
var i = 0
|
|
|
|
while i < args.len():
|
|
|
|
case args[i]:
|
|
|
|
of "moves":
|
|
|
|
var j = i + 1
|
|
|
|
while j < args.len():
|
|
|
|
let r = handleUCIMove(session, args[j])
|
|
|
|
if r.move == nullMove():
|
|
|
|
if r.cmd.reason.len() > 0:
|
|
|
|
return UCICommand(kind: Unknown, reason: &"move {args[j]} is illegal or invalid ({r.cmd.reason})")
|
|
|
|
else:
|
|
|
|
return UCICommand(kind: Unknown, reason: &"move {args[j]} is illegal or invalid")
|
|
|
|
result.moves.add(args[j])
|
|
|
|
inc(j)
|
|
|
|
inc(i)
|
|
|
|
of "fen":
|
|
|
|
var
|
|
|
|
args = command[2..^1]
|
|
|
|
fenString = ""
|
|
|
|
stop = 0
|
|
|
|
for i, arg in args:
|
|
|
|
if arg in ["moves", ]:
|
|
|
|
break
|
|
|
|
if i > 0:
|
|
|
|
fenString &= " "
|
|
|
|
fenString &= arg
|
|
|
|
inc(stop)
|
|
|
|
result.fen = fenString
|
|
|
|
args = args[stop..^1]
|
|
|
|
session.board = newChessboardFromFEN(fenString)
|
|
|
|
if args.len() > 0:
|
|
|
|
var i = 0
|
|
|
|
while i < args.len():
|
|
|
|
case args[i]:
|
|
|
|
of "moves":
|
|
|
|
var j = i + 1
|
|
|
|
while j < args.len():
|
2024-04-25 23:41:25 +02:00
|
|
|
let r = handleUCIMove(session, args[j])
|
|
|
|
if r.move == nullMove():
|
|
|
|
if r.cmd.reason.len() > 0:
|
|
|
|
return UCICommand(kind: Unknown, reason: &"move {args[j]} is illegal or invalid ({r.cmd.reason})")
|
|
|
|
else:
|
|
|
|
return UCICommand(kind: Unknown, reason: &"move {args[j]} is illegal or invalid")
|
|
|
|
result.moves.add(args[j])
|
|
|
|
inc(j)
|
2024-04-24 10:41:01 +02:00
|
|
|
inc(i)
|
|
|
|
else:
|
|
|
|
return UCICommand(kind: Unknown, reason: &"unknown subcomponent '{command[1]}'")
|
|
|
|
|
|
|
|
|
|
|
|
proc parseUCICommand(session: UCISession, command: string): UCICommand =
|
|
|
|
## Attempts to parse the given UCI command
|
|
|
|
var cmd = command.replace("\t", "").splitWhitespace()
|
|
|
|
result = UCICommand(kind: Unknown)
|
|
|
|
var current = 0
|
|
|
|
while current < cmd.len():
|
|
|
|
case cmd[current]:
|
|
|
|
of "isready":
|
|
|
|
return UCICommand(kind: IsReady)
|
2024-04-24 19:38:54 +02:00
|
|
|
of "stop":
|
|
|
|
return UCICommand(kind: Stop)
|
2024-04-24 10:41:01 +02:00
|
|
|
of "ucinewgame":
|
|
|
|
return UCICommand(kind: NewGame)
|
|
|
|
of "quit":
|
|
|
|
return UCICommand(kind: Quit)
|
|
|
|
of "debug":
|
|
|
|
if current == cmd.high():
|
|
|
|
return
|
|
|
|
case cmd[current + 1]:
|
|
|
|
of "on":
|
2024-04-25 23:41:25 +02:00
|
|
|
return UCICommand(kind: Debug, on: true)
|
2024-04-24 10:41:01 +02:00
|
|
|
of "off":
|
2024-04-25 23:41:25 +02:00
|
|
|
return UCICommand(kind: Debug, on: false)
|
2024-04-24 10:41:01 +02:00
|
|
|
else:
|
|
|
|
return
|
|
|
|
of "position":
|
|
|
|
return session.handleUCIPositionCommand(cmd)
|
2024-04-24 12:38:03 +02:00
|
|
|
of "go":
|
|
|
|
return session.handleUCIGoCommand(cmd)
|
2024-04-25 23:41:25 +02:00
|
|
|
of "setoption":
|
|
|
|
result = UCICommand(kind: SetOption)
|
|
|
|
while current < cmd.len():
|
|
|
|
inc(current)
|
|
|
|
case cmd[current]:
|
|
|
|
of "name":
|
|
|
|
inc(current)
|
|
|
|
result.name = cmd[current]
|
|
|
|
of "value":
|
|
|
|
inc(current)
|
|
|
|
result.value = cmd[current]
|
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
2024-04-24 10:41:01 +02:00
|
|
|
else:
|
|
|
|
# Unknown UCI commands should be ignored. Attempt
|
|
|
|
# to make sense of the input regardless
|
|
|
|
inc(current)
|
|
|
|
|
|
|
|
|
2024-04-25 15:20:55 +02:00
|
|
|
proc bestMove(args: tuple[session: UCISession, command: UCICommand]) {.thread.} =
|
2024-04-24 19:38:54 +02:00
|
|
|
## Finds the best move in the current position
|
2024-04-25 15:20:55 +02:00
|
|
|
{.cast(gcsafe).}:
|
|
|
|
setControlCHook(proc () {.noconv.} = quit(0))
|
|
|
|
# Yes yes nim sure this isn't gcsafe. Now stfu and spawn a thread
|
|
|
|
var session = args.session
|
|
|
|
var command = args.command
|
|
|
|
session.searching = true
|
|
|
|
session.currentSearch = newSearchManager(session.board)
|
|
|
|
session.currentSearch.stopFlag.store(false)
|
|
|
|
var
|
|
|
|
timeRemaining = (if session.board.position.sideToMove == White: command.wtime else: command.btime)
|
|
|
|
increment = (if session.board.position.sideToMove == White: command.winc else: command.binc)
|
|
|
|
maxTime = (timeRemaining div 20) + (increment div 2)
|
|
|
|
# Buffer to avoid loosing on time
|
|
|
|
if maxTime == 0:
|
|
|
|
maxTime = int32.high()
|
|
|
|
else:
|
|
|
|
maxTime -= 100
|
|
|
|
if command.moveTime != -1:
|
|
|
|
maxTime = command.moveTime
|
|
|
|
if session.debug:
|
|
|
|
echo &"info string starting search to depth {command.depth} for at most {maxTime} ms and {command.nodes} nodes"
|
|
|
|
if session.debug and command.searchmoves.len() > 0:
|
|
|
|
echo &"""info string restricting search to: {command.searchmoves.join(" ")}"""
|
|
|
|
var move = session.currentSearch.findBestMove(maxTime, command.depth, command.nodes, command.searchmoves)
|
|
|
|
session.searching = false
|
|
|
|
echo &"bestmove {move.toAlgebraic()}"
|
|
|
|
|
|
|
|
|
2024-04-24 19:38:54 +02:00
|
|
|
|
2024-04-24 10:41:01 +02:00
|
|
|
proc startUCISession* =
|
|
|
|
## Begins listening for UCI commands
|
|
|
|
echo "id name Nimfish 0.1"
|
|
|
|
echo "id author Nocturn9x & Contributors (see LICENSE)"
|
2024-04-25 23:41:25 +02:00
|
|
|
echo "option name Hash type spin default 64 min 1 max 33554432"
|
2024-04-24 10:41:01 +02:00
|
|
|
echo "uciok"
|
|
|
|
var
|
|
|
|
cmd: UCICommand
|
|
|
|
cmdStr: string
|
|
|
|
session = UCISession()
|
|
|
|
while true:
|
|
|
|
try:
|
|
|
|
cmdStr = readLine(stdin).strip(leading=true, trailing=true, chars={'\t', ' '})
|
|
|
|
if cmdStr.len() == 0:
|
|
|
|
if session.debug:
|
|
|
|
echo "info string received empty input, ignoring it"
|
|
|
|
continue
|
|
|
|
cmd = session.parseUCICommand(cmdStr)
|
|
|
|
if cmd.kind == Unknown:
|
|
|
|
if session.debug:
|
|
|
|
echo &"info string received unknown or invalid command '{cmdStr}' -> {cmd.reason}"
|
|
|
|
continue
|
|
|
|
if session.debug:
|
|
|
|
echo &"info string received command '{cmdStr}' -> {cmd}"
|
|
|
|
case cmd.kind:
|
|
|
|
of Quit:
|
|
|
|
quit(0)
|
|
|
|
of IsReady:
|
|
|
|
echo "readyok"
|
|
|
|
of Debug:
|
2024-04-25 23:41:25 +02:00
|
|
|
session.debug = cmd.on
|
2024-04-24 10:41:01 +02:00
|
|
|
of NewGame:
|
|
|
|
session.board = newDefaultChessboard()
|
2024-04-24 12:38:03 +02:00
|
|
|
of Go:
|
2024-04-25 15:20:55 +02:00
|
|
|
var thread: Thread[tuple[session: UCISession, command: UCICommand]]
|
|
|
|
createThread(thread, bestMove, (session, cmd))
|
|
|
|
of Stop:
|
|
|
|
if session.searching:
|
2024-04-25 23:41:25 +02:00
|
|
|
session.currentSearch.stopFlag.store(true)
|
|
|
|
of SetOption:
|
|
|
|
case cmd.name:
|
|
|
|
of "Hash":
|
|
|
|
session.hashTableSize = cmd.value.parseBiggestUInt()
|
|
|
|
if session.debug:
|
|
|
|
echo &"info string set TT hash table size to {session.hashTableSize} MiB"
|
|
|
|
else:
|
|
|
|
discard
|
2024-04-24 10:41:01 +02:00
|
|
|
of Position:
|
|
|
|
discard
|
|
|
|
else:
|
|
|
|
discard
|
|
|
|
except IOError:
|
|
|
|
if session.debug:
|
|
|
|
echo "info string I/O error while reading from stdin, exiting"
|
|
|
|
echo ""
|
|
|
|
quit(0)
|
|
|
|
except EOFError:
|
|
|
|
if session.debug:
|
|
|
|
echo "info string EOF received while reading from stdin, exiting"
|
|
|
|
echo ""
|
|
|
|
quit(0)
|