diff --git a/README.md b/README.md index 197ce76..c242861 100644 --- a/README.md +++ b/README.md @@ -60,12 +60,16 @@ Extra commands: `go depth N` limits the mean playout depth. `nodes` in `info` lines are playouts. -Started from a terminal, Rigby prints its search for a human instead: coloured -progress lines (depth, playouts, speed, tree fill, score, PV) and, at the end, the -most visited root moves with their share of the visits, score and prior. The first -`uci` command switches to plain UCI output for good; GUIs and match runners send it -first and read stdout through a pipe, so they never see the coloured output. -`NO_COLOR` turns it off. +Started from a terminal, Rigby shows its search for a human instead: a framed +dashboard, redrawn in place ten times a second, with the score and an evaluation +bar, depth, playouts, speed, a time bar, tree fill, the principal variation in SAN +and the most visited root moves with their share of the visits, score and prior. +It adapts to the terminal's size. The +first `uci` command switches to plain UCI output for good; GUIs and match runners +send it first and read stdout through a pipe, so they never see it. `NO_COLOR` +turns it off, `RIGBY_PRETTY=1` forces it into a pipe (e.g. `less -R`). It needs a +terminal with 24-bit colour and UTF-8 (Windows Terminal, any modern Linux/macOS +terminal). ### Options diff --git a/src/mcts.cpp b/src/mcts.cpp index a374df4..d0bb7d0 100644 --- a/src/mcts.cpp +++ b/src/mcts.cpp @@ -413,43 +413,57 @@ void Searcher::print_info() const { const i64 ms = elapsed_ms(); const u32 best = best_child(Tree::root()); - pretty::Progress p; - p.depth = int(iterations_ ? std::max(1, depth_sum_ / iterations_) : 0); - p.seldepth = seldepth_; - p.cp = eval::q_to_cp(best && tree_[best].visits ? tree_[best].q : -root.q); - p.playouts = iterations_; - p.nps = ms ? iterations_ * 1000 / u64(ms) : iterations_; - p.ms = ms; - p.hashfull = int(tree_.used() * 1000 / tree_.capacity()); + std::ostringstream out; + out << "info depth " << (iterations_ ? std::max(1, depth_sum_ / iterations_) : 0) << " seldepth " + << seldepth_; + const float q = best && tree_[best].visits ? tree_[best].q : -root.q; + out << " score cp " << eval::q_to_cp(q); + out << " nodes " << iterations_ << " nps " << (ms ? iterations_ * 1000 / u64(ms) : iterations_) << " time " << ms; + out << " hashfull " << (tree_.used() * 1000 / tree_.capacity()); + + out << " pv"; + for (const Move m : principal_variation()) out << ' ' << m.to_uci(); + uci_io::send(out.str()); +} + +std::vector Searcher::principal_variation() const { + std::vector pv; u32 idx = Tree::root(); for (int ply = 0; ply < 64; ply++) { const u32 c = best_child(idx); if (!c || !tree_[c].visits) break; - p.pv.push_back(Move::from_raw(tree_[c].move).to_uci()); + pv.push_back(Move::from_raw(tree_[c].move)); idx = c; } - - if (pretty) { - uci_io::send(pretty::progress(p)); - return; - } - - std::ostringstream out; - out << "info depth " << p.depth << " seldepth " << p.seldepth << " score cp " << p.cp << " nodes " << p.playouts - << " nps " << p.nps << " time " << p.ms << " hashfull " << p.hashfull << " pv"; - for (const std::string& m : p.pv) out << ' ' << m; - uci_io::send(out.str()); + return pv; } -void Searcher::print_root_moves() const { +void Searcher::draw_dashboard(bool done) { const Node& root = tree_[Tree::root()]; - std::vector moves; + const u32 best = best_child(Tree::root()); + const i64 ms = elapsed_ms(); + + pretty::Dashboard d; + d.root = root_pos_; + d.depth = int(iterations_ ? std::max(1, depth_sum_ / iterations_) : 0); + d.seldepth = seldepth_; + d.playouts = iterations_; + d.nps = ms ? iterations_ * 1000 / u64(ms) : iterations_; + d.ms = ms; + d.time_limit_ms = time_limit_ms_; + d.node_limit = node_limit_; + d.hashfull = int(tree_.used() * 1000 / tree_.capacity()); + d.cp = eval::q_to_cp(best && tree_[best].visits ? tree_[best].q : -root.q); + d.pv = principal_variation(); for (u32 i = 0; i < root.num_children; i++) { const Node& child = tree_[root.first_child + i]; - moves.push_back({Move::from_raw(child.move).to_uci(), child.visits, eval::q_to_cp(child.q), child.prior()}); + d.moves.push_back({Move::from_raw(child.move), child.visits, eval::q_to_cp(child.q), child.prior()}); } - uci_io::send(pretty::root_table(std::move(moves), 8)); + d.reused = reused_; + d.collections = gc_runs_; + d.done = done; + uci_io::send(live_.draw(d)); } SearchResult Searcher::search(const Position& root, const std::vector& history, const SearchLimits& limits, @@ -479,6 +493,8 @@ SearchResult Searcher::search(const Position& root, const std::vector& hist seldepth_ = 0; gc_pending_ = false; gc_runs_ = 0; + reused_ = reused; + node_limit_ = limits.nodes; compute_time_limit(limits); SearchResult result; @@ -488,16 +504,13 @@ SearchResult Searcher::search(const Position& root, const std::vector& hist if (root_moves.empty()) { tree_valid_ = false; if (print && pretty) - uci_io::send(pretty::note(root.in_check() ? "\n checkmate, no legal moves" : "\n stalemate, no legal moves")); + uci_io::send(pretty::note(root.in_check() ? "checkmate, no legal moves" : "stalemate, no legal moves")); else if (print) uci_io::send("info depth 0 score " + std::string(root.in_check() ? "mate 0" : "cp 0")); return result; } - if (print && pretty) { - if (reused) uci_io::send(pretty::reused(reused)); - uci_io::send(pretty::header()); - } + if (print && pretty) live_.begin(); // The root needs its children before the first playout, so that even a // single playout leaves a move to play. @@ -507,9 +520,11 @@ SearchResult Searcher::search(const Position& root, const std::vector& hist expand(Tree::root(), root); } - // UCI reports once a second. A human gets lines at 125, 250, 500 ms and so - // on, so short searches still show how the search developed. - i64 next_info = pretty ? 125 : 1000; + // UCI reports once a second; the dashboard for a human is redrawn in place + // ten times a second. + const i64 info_interval = pretty ? 100 : 1000; + const u64 info_mask = pretty ? 255 : 1023; + i64 next_info = pretty ? 0 : 1000; do { playout(); if (gc_pending_) { @@ -520,24 +535,21 @@ SearchResult Searcher::search(const Position& root, const std::vector& hist verify_tree(); #endif } - if (print && (iterations_ & 1023) == 0) { + if (print && (iterations_ & info_mask) == 0) { const i64 ms = elapsed_ms(); if (ms >= next_info) { - next_info = pretty && next_info < 1000 ? next_info * 2 : ms + 1000; - print_info(); + next_info = ms + info_interval; + if (pretty) draw_dashboard(false); + else print_info(); } } } while (!should_stop(limits)); - if (print) { + if (print && pretty) { + draw_dashboard(true); + } else if (print) { print_info(); - if (pretty) { - print_root_moves(); - if (gc_runs_) uci_io::send(pretty::note("\n tree memory was full " + std::to_string(gc_runs_) + - "x: the least visited branches were collected")); - } else if (gc_runs_) { - uci_io::send("info string tree collected " + std::to_string(gc_runs_) + " times"); - } + if (gc_runs_) uci_io::send("info string tree collected " + std::to_string(gc_runs_) + " times"); } const u32 best = best_child(Tree::root()); diff --git a/src/mcts.h b/src/mcts.h index 495a890..1ba83a2 100644 --- a/src/mcts.h +++ b/src/mcts.h @@ -5,6 +5,7 @@ #include #include "position.h" +#include "pretty.h" namespace rigby { @@ -126,6 +127,9 @@ private: int seldepth_ = 0; bool gc_pending_ = false; int gc_runs_ = 0; + size_t reused_ = 0; + u64 node_limit_ = 0; + pretty::LiveView live_; // Share of the arena kept after a collection. static constexpr double GC_KEEP_FRACTION = 0.5; @@ -150,7 +154,8 @@ private: u32 best_child(u32 idx) const; void print_info() const; - void print_root_moves() const; + std::vector principal_variation() const; + void draw_dashboard(bool done); }; } // namespace rigby diff --git a/src/pretty.cpp b/src/pretty.cpp index 328cf33..bafaf38 100644 --- a/src/pretty.cpp +++ b/src/pretty.cpp @@ -5,6 +5,8 @@ #include #include +#include "eval.h" + #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN @@ -15,6 +17,7 @@ #include #include #else +#include #include #endif @@ -22,28 +25,58 @@ namespace rigby::pretty { namespace { -// ANSI SGR sequences. -constexpr const char* RESET = "\x1b[0m"; -constexpr const char* BOLD = "\x1b[1m"; -constexpr const char* DIM = "\x1b[90m"; -constexpr const char* WHITE_ = "\x1b[97m"; -constexpr const char* CYAN = "\x1b[36m"; -constexpr const char* BLUE = "\x1b[94m"; -constexpr const char* MAGENTA = "\x1b[95m"; -constexpr const char* GREEN = "\x1b[32m"; -constexpr const char* BRIGHT_GREEN = "\x1b[92m"; -constexpr const char* YELLOW = "\x1b[93m"; -constexpr const char* RED = "\x1b[31m"; -constexpr const char* BRIGHT_RED = "\x1b[91m"; +// --------------------------------------------------------------------------- +// Colours (24-bit ANSI) +// --------------------------------------------------------------------------- -std::string paint(const char* colour, const std::string& text) { return colour + text + RESET; } - -// Right- or left-aligns `text` (plain ASCII) to `width` columns. -std::string pad_left(const std::string& text, size_t width) { - return text.size() >= width ? text : std::string(width - text.size(), ' ') + text; +std::string fg(int r, int g, int b) { + return "\x1b[38;2;" + std::to_string(r) + ";" + std::to_string(g) + ";" + std::to_string(b) + "m"; } -std::string pad_right(const std::string& text, size_t width) { - return text.size() >= width ? text : text + std::string(width - text.size(), ' '); +std::string bg(int r, int g, int b) { + return "\x1b[48;2;" + std::to_string(r) + ";" + std::to_string(g) + ";" + std::to_string(b) + "m"; +} + +const std::string RESET = "\x1b[0m"; +const std::string BOLD = "\x1b[1m"; + +const std::string BORDER = fg(98, 104, 150); +const std::string TITLE = BOLD + fg(205, 145, 255); +const std::string LABEL = fg(125, 128, 150); +const std::string FAINT = fg(85, 88, 105); +const std::string VALUE = fg(235, 236, 245); +const std::string CYAN = fg(110, 205, 235); +const std::string BLUE = fg(125, 155, 255); +const std::string VIOLET = fg(185, 130, 255); +const std::string GREEN = fg(120, 215, 120); +const std::string BRIGHT_GREEN = fg(80, 245, 125); +const std::string YELLOW = fg(245, 200, 90); +const std::string RED = fg(235, 110, 110); +const std::string BRIGHT_RED = fg(255, 75, 85); + +const std::string& score_colour(int cp) { + if (cp >= 150) return BRIGHT_GREEN; + if (cp >= 25) return GREEN; + if (cp > -25) return VALUE; + if (cp > -150) return RED; + return BRIGHT_RED; +} + +// --------------------------------------------------------------------------- +// Text helpers +// --------------------------------------------------------------------------- + +// Visible columns of plain UTF-8 text (every code point counts as one column). +int columns(const std::string& text) { + int n = 0; + for (unsigned char c : text) + if ((c & 0xC0) != 0x80) n++; + return n; +} + +std::string repeat(const std::string& s, int n) { + std::string out; + for (int i = 0; i < n; i++) out += s; + return out; } std::string format(const char* fmt, double value) { @@ -76,125 +109,415 @@ std::string duration(i64 ms) { return buf; } -// Pawns with a sign: +0.42, -1.30 -std::string score_text(int cp) { return format("%+.2f", double(cp) / 100.0); } +std::string pawns(int cp) { return format("%+.2f", double(cp) / 100.0); } -const char* score_colour(int cp) { - if (cp >= 150) return BRIGHT_GREEN; - if (cp >= 25) return GREEN; - if (cp > -25) return WHITE_; - if (cp > -150) return RED; - return BRIGHT_RED; +// A line of coloured text that knows how many columns it takes. +struct Line { + std::string text; + int width = 0; + + Line& add(const std::string& plain, const std::string& colour = "") { + text += colour.empty() ? plain : colour + plain + RESET; + width += columns(plain); + return *this; + } + Line& pad_to(int target) { + if (width < target) add(std::string(size_t(target - width), ' ')); + return *this; + } + Line& append(const Line& other) { + text += other.text; + width += other.width; + return *this; + } +}; + +std::string pad_left(const std::string& plain, int width) { + const int n = columns(plain); + return n >= width ? plain : std::string(size_t(width - n), ' ') + plain; +} +std::string pad_right(const std::string& plain, int width) { + const int n = columns(plain); + return n >= width ? plain : plain + std::string(size_t(width - n), ' '); } -// A bar `width` cells wide; eighth blocks make it smooth. -std::string bar(double fraction, int width) { +// A smooth bar: `fraction` of `width` cells filled in `fill`, the rest in `track` +// (both foreground colours); the cell at the edge uses eighth blocks. +Line bar(double fraction, int width, const std::string& fill, const std::string& track, const std::string& track_bg) { static constexpr const char* EIGHTHS[] = {"", "▏", "▎", "▍", "▌", "▋", "▊", "▉"}; const int eighths = int(std::lround(std::clamp(fraction, 0.0, 1.0) * width * 8)); - std::string out; - for (int i = 0; i < eighths / 8; i++) out += "█"; - int cells = eighths / 8; - if (eighths % 8) { - out += EIGHTHS[eighths % 8]; - cells++; + const int full = eighths / 8; + Line l; + if (full) l.add(repeat("█", full), fill); + int used = full; + if (eighths % 8 && used < width) { + l.text += track_bg + fill + EIGHTHS[eighths % 8] + RESET; + l.width++; + used++; } - return out + std::string(size_t(width - cells), ' '); + if (used < width) l.add(repeat("█", width - used), track); + return l; } -// The tree's fill level as a bar of `width` cells, filled ones coloured by how full it is. -std::string tree_bar(int permille, int width) { - const int filled = std::clamp((permille * width + 500) / 1000, 0, width); - const char* colour = permille < 500 ? GREEN : permille < 900 ? YELLOW : RED; - std::string full, empty; - for (int i = 0; i < filled; i++) full += "■"; - for (int i = filled; i < width; i++) empty += "■"; - return paint(colour, full) + paint(DIM, empty); -} +// --------------------------------------------------------------------------- +// Terminal +// --------------------------------------------------------------------------- -constexpr int TREE_WIDTH = 8; +bool stdin_is_terminal = false; -} // namespace +struct TermSize { + int cols = 100; + int rows = 40; +}; -bool init_terminal() { - if (std::getenv("NO_COLOR")) return false; +TermSize terminal_size() { #ifdef _WIN32 - if (!_isatty(_fileno(stdout))) return false; - const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); - DWORD mode = 0; - if (!GetConsoleMode(out, &mode) || !SetConsoleMode(out, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) return false; - SetConsoleOutputCP(CP_UTF8); - return true; + CONSOLE_SCREEN_BUFFER_INFO info; + if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info)) + return {info.srWindow.Right - info.srWindow.Left + 1, info.srWindow.Bottom - info.srWindow.Top + 1}; #else - return isatty(STDOUT_FILENO); + winsize w{}; + if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0 && w.ws_col) return {int(w.ws_col), int(w.ws_row)}; #endif + return {}; } -std::string banner(const std::string& name, const std::string& version, const std::string& author) { - return std::string("\n ") + BOLD + MAGENTA + name + RESET + " " + WHITE_ + version + RESET + DIM + " by " + - author + RESET + "\n " + DIM + "MCTS chess engine · type " + RESET + CYAN + "uci" + RESET + DIM + - " for UCI mode, or e.g. " + RESET + CYAN + "go movetime 5000" + RESET + "\n"; -} +// --------------------------------------------------------------------------- +// Box drawing +// --------------------------------------------------------------------------- -std::string header() { - const std::string cols = " " + pad_left("depth", 7) + " " + pad_left("playouts", 8) + " " + pad_left("speed", 9) + - " " + pad_left("time", 6) + " " + pad_right("tree", TREE_WIDTH + 5) + " " + - pad_left("score", 6) + " pv"; - return std::string("\n") + DIM + cols + RESET; -} +struct Box { + int width; // total columns, borders included + std::vector lines; -std::string progress(const Progress& p) { - std::string line = " "; - line += paint(WHITE_, pad_left(std::to_string(p.depth), 3)) + paint(DIM, pad_right("/" + std::to_string(p.seldepth), 4)); - line += " " + paint(CYAN, pad_left(count(p.playouts), 8)); - line += " " + paint(BLUE, pad_left(count(p.nps), 7)) + paint(DIM, "/s"); - line += " " + paint(WHITE_, pad_left(duration(p.ms), 6)); - line += " " + tree_bar(p.hashfull, TREE_WIDTH) + paint(DIM, pad_left(std::to_string((p.hashfull + 5) / 10) + "%", 5)); - line += " " + paint(score_colour(p.cp), std::string(BOLD) + pad_left(score_text(p.cp), 6)); - line += " "; - for (size_t i = 0; i < p.pv.size(); i++) { - // The move to play stands out; the rest of the line fades with depth. - line += " " + (i == 0 ? paint(WHITE_, std::string(BOLD) + p.pv[i]) : paint(i < 4 ? WHITE_ : DIM, p.pv[i])); + int inner() const { return width - 4; } + + void top(const Line& left, const Line& right) { + // ╭─ left ───── right ─╮ + const int fill = width - 8 - left.width - right.width; + lines.push_back(BORDER + "╭─ " + RESET + left.text + BORDER + " " + repeat("─", std::max(fill, 1)) + " " + + RESET + right.text + BORDER + " ─╮" + RESET); } - return line; + void section(const Line& title) { + // ├─ title ─────┤ + const int fill = width - 5 - title.width; + lines.push_back(BORDER + "├─ " + RESET + title.text + BORDER + " " + repeat("─", std::max(fill, 0)) + "┤" + + RESET); + } + void row(Line content) { + content.pad_to(inner()); + lines.push_back(BORDER + "│ " + RESET + content.text + BORDER + " │" + RESET); + } + void bottom() { lines.push_back(BORDER + "╰" + repeat("─", width - 2) + "╯" + RESET); } +}; + +// --------------------------------------------------------------------------- +// Statistics, nine lines +// --------------------------------------------------------------------------- + +constexpr int LABEL_WIDTH = 10; + +Line label(const std::string& text) { + Line l; + l.add(pad_right(text, LABEL_WIDTH), LABEL); + return l; } -std::string root_table(std::vector moves, size_t max_rows) { - u64 total = 0; - for (const RootMove& m : moves) total += m.visits; - std::stable_sort(moves.begin(), moves.end(), - [](const RootMove& a, const RootMove& b) { return a.visits > b.visits; }); +std::vector stats(const Dashboard& d, int width) { + std::vector out; - constexpr int SHARE_WIDTH = 24; - std::string out = std::string("\n") + DIM + " " + pad_right("move", 7) + pad_left("visits", 8) + " " + - pad_right("share", SHARE_WIDTH + 8) + pad_left("score", 6) + " " + pad_left("prior", 6) + RESET; + // Score, and white's expected score as a bar. + Line score = label("score"); + score.add(pawns(d.cp), BOLD + score_colour(d.cp)); + score.add(d.root.stm == WHITE ? " white to move" : " black to move", FAINT); + out.push_back(score); - const size_t rows = std::min(moves.size(), max_rows); - for (size_t i = 0; i < rows; i++) { - const RootMove& m = moves[i]; - const double share = total ? double(m.visits) / double(total) : 0.0; - const bool best = i == 0; - out += "\n "; - out += best ? paint(WHITE_, std::string(BOLD) + pad_right(m.move, 7)) : paint(WHITE_, pad_right(m.move, 7)); - out += paint(CYAN, pad_left(count(m.visits), 8)) + " "; - out += paint(best ? MAGENTA : BLUE, bar(share, SHARE_WIDTH)); - out += paint(DIM, pad_left(format("%.1f%%", share * 100.0), 7)) + " "; - out += m.visits ? paint(score_colour(m.cp), pad_left(score_text(m.cp), 6)) : paint(DIM, pad_left("-", 6)); - out += " " + paint(DIM, pad_left(format("%.1f%%", double(m.prior) * 100.0), 6)); + const double q = eval::cp_to_q(d.cp); + const double white = d.root.stm == WHITE ? (q + 1.0) / 2.0 : (1.0 - q) / 2.0; + Line eval_bar = label("white"); + const int bar_width = std::clamp(width - LABEL_WIDTH - 5, 4, 48); + eval_bar.append(bar(white, bar_width, fg(240, 240, 245), fg(55, 55, 68), bg(55, 55, 68))); + eval_bar.add(pad_left(format("%.0f%%", white * 100.0), 5), VALUE); + out.push_back(eval_bar); + + out.push_back(Line{}); + + Line depth = label("depth"); + depth.add(std::to_string(d.depth), VALUE).add(" avg ", FAINT).add(std::to_string(d.seldepth), VALUE).add(" max", FAINT); + out.push_back(depth); + + Line playouts = label("playouts"); + playouts.add(pad_right(count(d.playouts), 8), CYAN).add("speed ", LABEL).add(count(d.nps), BLUE).add("/s", FAINT); + out.push_back(playouts); + + Line time = label("time"); + time.add(duration(d.ms), VALUE); + double progress = -1.0; + if (d.time_limit_ms) { + time.add(" / " + duration(d.time_limit_ms), FAINT); + progress = double(d.ms) / double(d.time_limit_ms); + } else if (d.node_limit) { + time.add(" " + count(d.playouts) + "/" + count(d.node_limit), FAINT); + progress = double(d.playouts) / double(d.node_limit); + } else { + time.add(d.done ? " stopped" : " infinite", FAINT); } - if (moves.size() > rows) - out += "\n " + paint(DIM, "... " + std::to_string(moves.size() - rows) + " more moves"); + out.push_back(time); + + Line progress_bar = label(""); + if (progress >= 0.0) + progress_bar.append(bar(d.done ? 1.0 : progress, bar_width + 5, CYAN, fg(45, 50, 66), bg(45, 50, 66))); + out.push_back(progress_bar); + + // Tree memory: one square per tenth. + Line tree = label("tree"); + const int filled = std::clamp((d.hashfull + 50) / 100, 0, 10); + const std::string& colour = d.hashfull < 500 ? GREEN : d.hashfull < 900 ? YELLOW : RED; + tree.add(repeat("■", filled), colour).add(repeat("■", 10 - filled), fg(55, 58, 72)); + tree.add(pad_left(std::to_string((d.hashfull + 5) / 10) + "%", 5), VALUE); + out.push_back(tree); + + Line notes = label(""); + std::string text; + if (d.reused) text += "reused " + count(d.reused); + if (d.collections) text += std::string(text.empty() ? "" : " · ") + "collected " + std::to_string(d.collections) + "×"; + notes.add(text, FAINT); + out.push_back(notes); + return out; } -std::string note(const std::string& text) { return std::string(" ") + DIM + text + RESET; } +// --------------------------------------------------------------------------- +// Principal variation in SAN, wrapped +// --------------------------------------------------------------------------- -std::string reused(u64 nodes) { - return std::string("\n ") + DIM + "reused " + RESET + CYAN + count(nodes) + RESET + DIM + - " tree nodes from the last search" + RESET; +std::vector pv_lines(const Dashboard& d, int width, int max_lines) { + struct Token { + std::string text; + std::string colour; + }; + std::vector tokens; + Position pos = d.root; + for (size_t i = 0; i < d.pv.size(); i++) { + if (pos.stm == WHITE) tokens.push_back({std::to_string(pos.fullmove) + ".", FAINT}); + else if (i == 0) tokens.push_back({std::to_string(pos.fullmove) + "...", FAINT}); + const std::string colour = i == 0 ? BOLD + fg(255, 255, 255) : i < 5 ? VALUE : i < 10 ? LABEL : FAINT; + tokens.push_back({san(pos, d.pv[i]), colour}); + pos.make_move(d.pv[i]); + } + + std::vector lines(1); + for (const Token& t : tokens) { + const int need = (lines.back().width ? 1 : 0) + columns(t.text); + if (lines.back().width + need > width) { + if (int(lines.size()) == max_lines) { + lines.back().add(" …", FAINT); + break; + } + lines.emplace_back(); + } + if (lines.back().width) lines.back().add(" "); + lines.back().add(t.text, t.colour); + } + if (d.pv.empty()) lines.back().add("…", FAINT); + return lines; } -std::string bestmove(const std::string& move) { - return std::string("\n ") + DIM + "bestmove " + RESET + BOLD + BRIGHT_GREEN + move + RESET + "\n"; +// --------------------------------------------------------------------------- +// Root moves table +// --------------------------------------------------------------------------- + +void root_moves(Box& box, const Dashboard& d, size_t rows) { + std::vector moves = d.moves; + std::stable_sort(moves.begin(), moves.end(), [](const RootMove& a, const RootMove& b) { return a.visits > b.visits; }); + u64 total = 0; + for (const RootMove& m : moves) total += m.visits; + + const int bar_width = std::max(box.inner() - 8 - 8 - 2 - 7 - 8 - 8, 6); + Line header; + header.add(pad_right("move", 8) + pad_left("visits", 8) + " " + pad_right("share", bar_width) + pad_left("%", 7) + + pad_left("score", 8) + pad_left("prior", 8), + FAINT); + box.row(header); + + for (size_t i = 0; i < std::min(rows, moves.size()); i++) { + const RootMove& m = moves[i]; + const double share = total ? double(m.visits) / double(total) : 0.0; + Line l; + l.add(pad_right(san(d.root, m.move), 8), i == 0 ? BOLD + fg(255, 255, 255) : VALUE); + l.add(pad_left(count(m.visits), 8), CYAN).add(" "); + l.append(bar(share, bar_width, i == 0 ? VIOLET : BLUE, fg(40, 44, 58), bg(40, 44, 58))); + l.add(pad_left(format("%.1f%%", share * 100.0), 7), VALUE); + if (m.visits) l.add(pad_left(pawns(m.cp), 8), score_colour(m.cp)); + else l.add(pad_left("-", 8), FAINT); + l.add(pad_left(format("%.1f%%", double(m.prior) * 100.0), 8), LABEL); + box.row(l); + } +} + +std::vector render(const Dashboard& d, int frame) { + static constexpr const char* SPINNER[] = {"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}; + const TermSize term = terminal_size(); + + Box box{std::clamp(term.cols - 1, 52, 104), {}}; + const int inner = box.inner(); + + // Fit the height: fewer root moves first, then no blank lines. + const int pv_max = 2; + const int available = term.rows - 1; + int fixed = 1 + 1 + 9 + 1 + 1 + pv_max + 1 + 1 + 1; + bool blanks = true; + int rows = std::clamp(available - fixed, 0, 8); + if (rows < 3) { + blanks = false; + fixed -= 2; + rows = std::clamp(available - fixed, 0, 8); + } + const bool show_moves = rows >= 1; + + Line title; + title.add("Rigby", TITLE); + Line status; + if (d.done) status.add("✓ done", BOLD + BRIGHT_GREEN); + else status.add(std::string(SPINNER[frame % 10]) + " searching", YELLOW); + box.top(title, status); + if (blanks) box.row(Line{}); + + for (const Line& l : stats(d, inner)) box.row(l); + if (blanks) box.row(Line{}); + + Line pv_title; + pv_title.add("principal variation", LABEL); + box.section(pv_title); + for (const Line& l : pv_lines(d, inner, pv_max)) box.row(l); + + if (show_moves) { + Line moves_title; + moves_title.add("root moves", LABEL).add(" · " + std::to_string(d.moves.size()) + " legal", FAINT); + box.section(moves_title); + root_moves(box, d, size_t(rows)); + } + box.bottom(); + return box.lines; +} + +} // namespace + +// --------------------------------------------------------------------------- +// Public interface +// --------------------------------------------------------------------------- + +bool init_terminal() { + if (std::getenv("NO_COLOR")) return false; + // RIGBY_PRETTY forces the dashboard even into a pipe, e.g. for `less -R`. + const bool forced = std::getenv("RIGBY_PRETTY") != nullptr; +#ifdef _WIN32 + if (!forced && !_isatty(_fileno(stdout))) return false; + const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); + DWORD mode = 0; + const bool vt = GetConsoleMode(out, &mode) && SetConsoleMode(out, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING); + if (!forced && !vt) return false; + SetConsoleOutputCP(CP_UTF8); + stdin_is_terminal = _isatty(_fileno(stdin)); + return true; +#else + if (!forced && !isatty(STDOUT_FILENO)) return false; + stdin_is_terminal = isatty(STDIN_FILENO); + return true; +#endif +} + +std::atomic& typed_lines() { + static std::atomic lines{0}; + return lines; +} + +std::string banner(const std::string& name, const std::string& version, const std::string& author) { + Box box{58, {}}; + Line title; + title.add(name, TITLE).add(" " + version, VALUE); + Line right; + right.add("MCTS chess engine", LABEL); + box.top(title, right); + box.row(Line{}); + Line by; + by.add("by ", FAINT).add(author, VALUE); + box.row(by); + Line help; + help.add("try ", FAINT).add("go movetime 5000", CYAN).add(" or ", FAINT).add("go infinite", CYAN).add(" + ", FAINT) + .add("stop", CYAN); + box.row(help); + Line uci; + uci.add("type ", FAINT).add("uci", CYAN).add(" for plain UCI output", FAINT); + box.row(uci); + box.bottom(); + std::string out = "\n"; + for (const std::string& l : box.lines) out += " " + l + "\n"; + return out; +} + +std::string LiveView::draw(const Dashboard& d) { + const std::vector lines = render(d, frame_++); + std::string out; + if (lines_) { + // Back to the first line of the previous dashboard (and over any line + // the user typed below it), then clear everything from there down. + const int typed = stdin_is_terminal ? typed_lines().exchange(0) : 0; + out += "\x1b[" + std::to_string(lines_ + typed) + "F\x1b[J"; + } + for (size_t i = 0; i < lines.size(); i++) out += (i ? "\n" : "") + lines[i]; + lines_ = int(lines.size()); + return out; +} + +std::string note(const std::string& text) { return " " + LABEL + text + RESET; } + +std::string bestmove(const Position& root, Move move) { + return " " + LABEL + "bestmove " + RESET + BOLD + BRIGHT_GREEN + san(root, move) + RESET + FAINT + " (" + + move.to_uci() + ")" + RESET + "\n"; +} + +std::string san(const Position& pos, Move m) { + if (!m) return "--"; + std::string s; + if (m.is_castle()) { + s = file_of(m.to()) > file_of(m.from()) ? "O-O" : "O-O-O"; + } else { + const int type = piece_type(pos.piece_on(m.from())); + if (type == PAWN) { + if (m.is_capture()) s += char('a' + file_of(m.from())); + } else { + s += "PNBRQK"[type]; + // Disambiguate between pieces of the same type that reach the same square. + MoveList legal; + generate_legal(pos, legal); + bool clash = false, same_file = false, same_rank = false; + for (Move o : legal) { + if (o == m || o.to() != m.to() || o.from() == m.from()) continue; + if (piece_type(pos.piece_on(o.from())) != type) continue; + clash = true; + same_file |= file_of(o.from()) == file_of(m.from()); + same_rank |= rank_of(o.from()) == rank_of(m.from()); + } + if (clash) { + if (!same_file) s += char('a' + file_of(m.from())); + else if (!same_rank) s += char('1' + rank_of(m.from())); + else s += square_name(m.from()); + } + } + if (m.is_capture()) s += 'x'; + s += square_name(m.to()); + if (m.is_promotion()) s += std::string("=") + "NBRQ"[m.promo_type() - KNIGHT]; + } + + Position next = pos; + next.make_move(m); + if (next.in_check()) { + MoveList replies; + generate_legal(next, replies); + s += replies.empty() ? '#' : '+'; + } + return s; } } // namespace rigby::pretty diff --git a/src/pretty.h b/src/pretty.h index 479ea9f..e210d7f 100644 --- a/src/pretty.h +++ b/src/pretty.h @@ -1,15 +1,19 @@ #pragma once +#include #include #include +#include "position.h" #include "types.h" namespace rigby::pretty { -// Human-readable, coloured search output for a terminal. The engine uses it -// until the first "uci" command; GUIs and match runners always send "uci" -// (and read stdout through a pipe), so they only ever see plain UCI. +// Human-readable search display for a terminal: a framed dashboard with the +// board, the score, search statistics, the principal variation and the root +// moves, redrawn in place while the search runs. The engine uses it until the +// first "uci" command; GUIs and match runners always send "uci" (and read +// stdout through a pipe), so they only ever see plain UCI. // True when stdout is a terminal (and NO_COLOR is not set). Turns on ANSI // colours and UTF-8 output on the Windows console. @@ -17,31 +21,56 @@ bool init_terminal(); std::string banner(const std::string& name, const std::string& version, const std::string& author); -// One snapshot of a running search. -struct Progress { - int depth = 0; - int seldepth = 0; - u64 playouts = 0; - u64 nps = 0; - i64 ms = 0; - int hashfull = 0; // per mille - int cp = 0; // side to move's view - std::vector pv; -}; +// Lines the user typed (and the terminal echoed) since the dashboard was last +// drawn; each one pushed the cursor a line further down. +std::atomic& typed_lines(); struct RootMove { - std::string move; + Move move; u32 visits = 0; int cp = 0; // from Q, side to move's view float prior = 0.0f; }; -std::string header(); -std::string progress(const Progress& p); -// The most visited root moves, with their share of the visits. -std::string root_table(std::vector moves, size_t max_rows); +// One snapshot of a running search. +struct Dashboard { + Position root; + int depth = 0; + int seldepth = 0; + u64 playouts = 0; + u64 nps = 0; + i64 ms = 0; + i64 time_limit_ms = 0; // 0: no time limit + u64 node_limit = 0; // 0: no playout limit + int hashfull = 0; // per mille + int cp = 0; // side to move's view + std::vector pv; + std::vector moves; + u64 reused = 0; + int collections = 0; + bool done = false; +}; + +// Draws dashboards in place: each call returns the text that replaces the +// previous dashboard of the same search. +class LiveView { +public: + void begin() { + lines_ = 0; + frame_ = 0; + typed_lines() = 0; + } + std::string draw(const Dashboard& d); + +private: + int lines_ = 0; + int frame_ = 0; +}; + std::string note(const std::string& text); -std::string reused(u64 nodes); -std::string bestmove(const std::string& move); +std::string bestmove(const Position& root, Move move); + +// Standard algebraic notation of a legal move, with + and #. +std::string san(const Position& pos, Move m); } // namespace rigby::pretty diff --git a/src/uci.cpp b/src/uci.cpp index 05e57c5..1b36d08 100644 --- a/src/uci.cpp +++ b/src/uci.cpp @@ -145,7 +145,7 @@ void go(Engine& e, std::istringstream& is) { e.searcher.stop_flag = false; e.worker = std::thread([&e, pos = e.pos, history = e.history, limits] { const SearchResult result = e.searcher.search(pos, history, limits, true); - send(e.searcher.pretty ? pretty::bestmove(result.best.to_uci()) : "bestmove " + result.best.to_uci()); + send(e.searcher.pretty ? pretty::bestmove(pos, result.best) : "bestmove " + result.best.to_uci()); }); } @@ -205,6 +205,8 @@ void uci_loop() { std::string line; while (std::getline(std::cin, line)) { + // The terminal echoed the line under a live dashboard; it redraws over it. + if (e.searcher.pretty) pretty::typed_lines()++; std::istringstream is(line); std::string cmd; is >> cmd;