#include "pretty.h" #include #include #include #include #include "eval.h" #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #include #include #else #include #include #endif namespace rigby::pretty { namespace { // --------------------------------------------------------------------------- // Colours (24-bit ANSI) // --------------------------------------------------------------------------- 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 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) { char buf[32]; std::snprintf(buf, sizeof(buf), fmt, value); return buf; } // 999, 12.3k, 123k, 1.23M, 12.3M, 1.23G std::string count(u64 n) { if (n < 1000) return std::to_string(n); const char* units = "kMGT"; double v = double(n); int unit = -1; while (v >= 1000.0 && unit < 3) { v /= 1000.0; unit++; } const std::string digits = v < 10.0 ? format("%.2f", v) : v < 100.0 ? format("%.1f", v) : format("%.0f", v); return digits + units[unit]; } // 0.38s, 12.4s, 2m05s std::string duration(i64 ms) { if (ms < 10000) return format("%.2fs", double(ms) / 1000.0); if (ms < 60000) return format("%.1fs", double(ms) / 1000.0); const i64 s = ms / 1000; char buf[32]; std::snprintf(buf, sizeof(buf), "%lldm%02llds", static_cast(s / 60), static_cast(s % 60)); return buf; } std::string pawns(int cp) { return format("%+.2f", double(cp) / 100.0); } // 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 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)); 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++; } if (used < width) l.add(repeat("█", width - used), track); return l; } // --------------------------------------------------------------------------- // Terminal // --------------------------------------------------------------------------- bool stdin_is_terminal = false; struct TermSize { int cols = 100; int rows = 40; }; TermSize terminal_size() { #ifdef _WIN32 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 winsize w{}; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0 && w.ws_col) return {int(w.ws_col), int(w.ws_row)}; #endif return {}; } // --------------------------------------------------------------------------- // Box drawing // --------------------------------------------------------------------------- struct Box { int width; // total columns, borders included std::vector lines; 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); } 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::vector stats(const Dashboard& d, int width) { std::vector out; // 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 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); } 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; } // --------------------------------------------------------------------------- // Principal variation in SAN, wrapped // --------------------------------------------------------------------------- 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; } // --------------------------------------------------------------------------- // 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 + " (" + root.uci(move) + ")" + RESET + "\n"; } std::string san(const Position& pos, Move m) { if (!m) return "--"; std::string s; if (m.is_castle()) { s = m.flag() == Move::KING_CASTLE ? "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