3 /** @type {window.ChessBoard} @private */
19 /** @type {Array.<Array.<boolean>>} */
20 var occupied_by_arrows = [];
22 var refutation_lines = [];
24 /** @type {!number} @private */
27 /** @type {!string} @private */
30 /** @type {number} @private */
33 /** @type {boolean} @private */
34 var sort_refutation_lines_by_score = true;
36 /** @type {boolean} @private */
37 var truncate_display_history = true;
39 /** @type {!string|undefined} @private */
40 var highlight_from = undefined;
42 /** @type {!string|undefined} @private */
43 var highlight_to = undefined;
45 /** @type {?jQuery} @private */
46 var highlighted_move = null;
48 /** @type {?number} @private */
51 /** The current position on the board, represented as a FEN string.
59 * uci_pv: Array.<string>,
60 * pretty_pv: Array.<string>,
65 /** @type {Array.<DisplayLine>}
68 var display_lines = [];
70 /** @type {?DisplayLine} @private */
71 var current_display_line = null;
73 /** @type {?number} @private */
74 var current_display_move = null;
76 var supports_html5_storage = function() {
78 return 'localStorage' in window && window['localStorage'] !== null;
84 // Make the unique token persistent so people refreshing the page won't count twice.
85 // Of course, you can never fully protect against people deliberately wanting to spam.
86 var get_unique = function() {
87 var use_local_storage = supports_html5_storage();
88 if (use_local_storage && localStorage['unique']) {
89 return localStorage['unique'];
91 var unique = Math.random();
92 if (use_local_storage) {
93 localStorage['unique'] = unique;
98 var request_update = function() {
100 url: "/analysis.pl?ims=" + ims + "&unique=" + unique
101 }).done(function(data, textstatus, xhr) {
102 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
103 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
104 update_board(data, num_viewers);
106 // Wait ten seconds, then try again.
107 setTimeout(function() { request_update(); }, 10000);
111 var clear_arrows = function() {
112 for (var i = 0; i < arrows.length; ++i) {
114 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
115 delete arrows[i].svg;
120 occupied_by_arrows = [];
121 for (var y = 0; y < 8; ++y) {
122 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
126 var redraw_arrows = function() {
127 for (var i = 0; i < arrows.length; ++i) {
128 position_arrow(arrows[i]);
132 /** @param {!number} x
135 var sign = function(x) {
145 /** See if drawing this arrow on the board would cause unduly amount of confusion.
146 * @param {!string} from The square the arrow is from (e.g. e4).
147 * @param {!string} to The square the arrow is to (e.g. e4).
150 var interfering_arrow = function(from, to) {
151 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
152 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
153 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
154 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
156 occupied_by_arrows[from_row][from_col] = true;
158 // Knight move: Just check that we haven't been at the destination before.
159 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
160 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
161 return occupied_by_arrows[to_row][to_col];
164 // Sliding piece: Check if anything except the from-square is seen before.
165 var dx = sign(to_col - from_col);
166 var dy = sign(to_row - from_row);
172 if (occupied_by_arrows[y][x]) {
175 occupied_by_arrows[y][x] = true;
176 } while (x != to_col || y != to_row);
181 /** Find a point along the coordinate system given by the given line,
182 * <t> units forward from the start of the line, <u> units to the right of it.
183 * @param {!number} x1
184 * @param {!number} x2
185 * @param {!number} y1
186 * @param {!number} y2
189 * @return {!string} The point in "x y" form, suitable for SVG paths.
191 var point_from_start = function(x1, y1, x2, y2, t, u) {
195 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
199 var x = x1 + dx * t + dy * u;
200 var y = y1 + dy * t - dx * u;
204 /** Find a point along the coordinate system given by the given line,
205 * <t> units forward from the end of the line, <u> units to the right of it.
206 * @param {!number} x1
207 * @param {!number} x2
208 * @param {!number} y1
209 * @param {!number} y2
212 * @return {!string} The point in "x y" form, suitable for SVG paths.
214 var point_from_end = function(x1, y1, x2, y2, t, u) {
218 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
222 var x = x2 + dx * t + dy * u;
223 var y = y2 + dy * t - dx * u;
227 var position_arrow = function(arrow) {
229 arrow.svg.parentElement.removeChild(arrow.svg);
232 if (current_display_line !== null) {
236 var pos = $(".square-a8").position();
238 var zoom_factor = $("#board").width() / 400.0;
239 var line_width = arrow.line_width * zoom_factor;
240 var arrow_size = arrow.arrow_size * zoom_factor;
242 var square_width = $(".square-a8").width();
243 var from_y = (7 - arrow.from_row + 0.5)*square_width;
244 var to_y = (7 - arrow.to_row + 0.5)*square_width;
245 var from_x = (arrow.from_col + 0.5)*square_width;
246 var to_x = (arrow.to_col + 0.5)*square_width;
248 var SVG_NS = "http://www.w3.org/2000/svg";
249 var XHTML_NS = "http://www.w3.org/1999/xhtml";
250 var svg = document.createElementNS(SVG_NS, "svg");
251 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
252 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
253 svg.setAttribute("style", "position: absolute");
254 svg.setAttribute("position", "absolute");
255 svg.setAttribute("version", "1.1");
256 svg.setAttribute("class", "c1");
257 svg.setAttribute("xmlns", XHTML_NS);
265 var outline = document.createElementNS(SVG_NS, "path");
266 outline.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
267 outline.setAttribute("xmlns", XHTML_NS);
268 outline.setAttribute("stroke", "#666");
269 outline.setAttribute("stroke-width", line_width + 2);
270 outline.setAttribute("fill", "none");
271 svg.appendChild(outline);
273 var path = document.createElementNS(SVG_NS, "path");
274 path.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
275 path.setAttribute("xmlns", XHTML_NS);
276 path.setAttribute("stroke", arrow.fg_color);
277 path.setAttribute("stroke-width", line_width);
278 path.setAttribute("fill", "none");
279 svg.appendChild(path);
281 // Then the arrow head.
282 var head = document.createElementNS(SVG_NS, "path");
283 head.setAttribute("d",
284 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
285 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
286 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
287 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
288 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
289 head.setAttribute("xmlns", XHTML_NS);
290 head.setAttribute("stroke", "#000");
291 head.setAttribute("stroke-width", "1");
292 head.setAttribute("fill", arrow.fg_color);
293 svg.appendChild(head);
295 $(svg).css({ top: pos.top, left: pos.left });
296 document.body.appendChild(svg);
301 * @param {!string} from_square
302 * @param {!string} to_square
303 * @param {!string} fg_color
304 * @param {number} line_width
305 * @param {number} arrow_size
307 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
308 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
309 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
310 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
311 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
319 line_width: line_width,
320 arrow_size: arrow_size,
324 position_arrow(arrow);
328 var compare_by_sort_key = function(refutation_lines, a, b) {
329 var ska = refutation_lines[a]['sort_key'];
330 var skb = refutation_lines[b]['sort_key'];
331 if (ska < skb) return -1;
332 if (ska > skb) return 1;
336 var compare_by_score = function(refutation_lines, a, b) {
337 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
338 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
343 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
344 * sorted by quality, descending.
346 * @param {!Object} data
347 * @param {number} margin The maximum number of centipawns worse than the
348 * best move can be and still be included.
349 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
350 * moves, in score order.
352 var find_nonstupid_moves = function(data, margin) {
353 // First of all, if there are any moves that are more than 0.5 ahead of
354 // the primary move, the refutation lines are probably bunk, so just
356 var best_score = undefined;
357 var pv_score = undefined;
358 for (var move in data['refutation_lines']) {
359 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
360 if (move == data['pv_uci'][0]) {
363 if (best_score === undefined || score > best_score) {
366 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
371 if (best_score - pv_score > 50) {
375 // Now find all moves that are within “margin” of the best score.
376 // The PV move will always be first.
378 for (var move in data['refutation_lines']) {
379 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
380 if (move != data['pv_uci'][0] && best_score - score <= margin) {
384 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
385 moves.unshift(data['pv_uci'][0]);
394 var thousands = function(x) {
395 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
399 * @param {!string} fen
400 * @param {Array.<string>} uci_pv
401 * @param {number} move_num
402 * @param {!string} toplay
403 * @param {number=} opt_limit
404 * @param {boolean=} opt_showlast
406 var add_pv = function(fen, uci_pv, move_num, toplay, opt_limit, opt_showlast) {
407 var hiddenboard = new Chess();
408 hiddenboard.load(fen);
409 for (var i = 0; i < uci_pv.length; ++i) {
410 hiddenboard.move(ucimove_to_chessjs_move(uci_pv[i]));
412 var pretty_pv = hiddenboard.history();
417 pretty_pv: pretty_pv,
418 line_number: display_lines.length
420 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
424 * @param {number} line_num
425 * @param {Array.<string>} pretty_pv
426 * @param {number} move_num
427 * @param {!string} toplay
428 * @param {number=} opt_limit
429 * @param {boolean=} opt_showlast
431 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
434 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
435 // Truncate the PV at the beginning (instead of at the end).
436 // We assume here that toplay is 'W'. We also assume that if
437 // opt_showlast is set, then it is the history, and thus,
438 // the UI should be to expand the history.
439 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
440 i = pretty_pv.length - opt_limit;
445 } else if (toplay == 'B' && pretty_pv.length > 0) {
446 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
447 pv = move_num + '. … ' + move;
452 for ( ; i < pretty_pv.length; ++i) {
453 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
456 if (i > opt_limit && !opt_showlast) {
462 pv += move_num + '. ' + move;
473 var update_highlight = function() {
474 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
475 if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
476 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
477 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
481 var update_history = function() {
482 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
483 $("#history").html("No history");
484 } else if (truncate_display_history) {
485 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
488 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
489 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
494 * @param {!boolean} truncate_history
496 var collapse_history = function(truncate_history) {
497 truncate_display_history = truncate_history;
500 window['collapse_history'] = collapse_history;
502 var update_refutation_lines = function() {
506 if (display_lines.length > 2) {
507 display_lines = [ display_lines[0], display_lines[1] ];
510 var tbl = $("#refutationlines");
514 for (var move in refutation_lines) {
517 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
518 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
519 for (var i = 0; i < moves.length; ++i) {
520 var line = refutation_lines[moves[i]];
522 var tr = document.createElement("tr");
524 var move_td = document.createElement("td");
525 tr.appendChild(move_td);
526 $(move_td).addClass("move");
527 if (line['pv_uci'].length == 0) {
528 $(move_td).text(line['pretty_move']);
530 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
531 $(move_td).html(move);
534 var score_td = document.createElement("td");
535 tr.appendChild(score_td);
536 $(score_td).addClass("score");
537 $(score_td).text(line['pretty_score']);
539 var depth_td = document.createElement("td");
540 tr.appendChild(depth_td);
541 $(depth_td).addClass("depth");
542 $(depth_td).text("d" + line['depth']);
544 var pv_td = document.createElement("td");
545 tr.appendChild(pv_td);
546 $(pv_td).addClass("pv");
547 $(pv_td).html(add_pv(fen, line['pv_uci'], move_num, toplay, 10));
552 // Make one of the links clickable and the other nonclickable.
553 if (sort_refutation_lines_by_score) {
554 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
555 $("#sortbyscore1").html("<strong>Score</strong>");
557 $("#sortbyscore0").html("<strong>Move</strong>");
558 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
563 * @param {Object} data
564 * @param {number} num_viewers
566 var update_board = function(data, num_viewers) {
571 if (data['position']['player_w'] && data['position']['player_b']) {
572 headline = data['position']['player_w'] + '–' +
573 data['position']['player_b'] + ', analysis';
575 headline = 'Analysis';
578 if (data['position']['last_move'] !== 'none') {
579 if (data['position']['toplay'] == 'W') {
580 last_move = (data['position']['move_num']-1) + '… ';
582 last_move = data['position']['move_num'] + '. ';
584 last_move += data['position']['last_move'];
586 headline += ' after ' + last_move;
591 $("#headline").text(headline);
593 if (num_viewers === null) {
594 $("#numviewers").text("");
595 } else if (num_viewers == 1) {
596 $("#numviewers").text("You are the only current viewer");
598 $("#numviewers").text(num_viewers + " current viewers");
602 if (data['id'] && data['id']['name'] !== null) {
603 $("#engineid").text(data['id']['name']);
607 if (data['score'] !== null) {
608 $("#score").text(data['score']);
611 var title_elems = [];
612 if (data['short_score'] !== undefined && data['short_score'] !== null) {
613 title_elems.push(data['short_score']);
615 if (last_move !== null) {
616 title_elems.push(last_move);
619 if (title_elems.length != 0) {
620 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
622 document.title = 'analysis.sesse.net';
626 if (data['tablebase'] == 1) {
627 $("#searchstats").text("Tablebase result");
628 } else if (data['nodes'] && data['nps'] && data['depth']) {
629 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
630 if (data['seldepth']) {
631 stats += ' (' + data['seldepth'] + ' selective)';
633 if (data['tbhits'] && data['tbhits'] > 0) {
634 if (data['tbhits'] == 1) {
635 stats += ', one Syzygy hit';
637 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
641 $("#searchstats").text(stats);
643 $("#searchstats").text("");
646 // Update the board itself.
647 fen = data['position']['fen'];
648 update_displayed_line();
650 if (data['position']['last_move_uci']) {
651 highlight_from = data['position']['last_move_uci'].substr(0, 2);
652 highlight_to = data['position']['last_move_uci'].substr(2, 2);
654 highlight_from = highlight_to = undefined;
658 // Print the history.
659 if (data['position']['history']) {
660 add_pv('start', data['position']['history'], 1, 'W', 8, true);
662 display_lines.push(null);
667 $("#pv").html(add_pv(data['position']['fen'], data['pv_uci'], data['position']['move_num'], data['position']['toplay']));
669 // Update the PV arrow.
671 if (data['pv_uci'].length >= 1) {
672 // draw a continuation arrow as long as it's the same piece
673 for (var i = 0; i < data['pv_uci'].length; i += 2) {
674 var from = data['pv_uci'][i].substr(0, 2);
675 var to = data['pv_uci'][i].substr(2,4);
676 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
677 interfering_arrow(from, to)) {
680 create_arrow(from, to, '#f66', 6, 20);
683 var alt_moves = find_nonstupid_moves(data, 30);
684 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
685 create_arrow(alt_moves[i].substr(0, 2),
686 alt_moves[i].substr(2, 2), '#f66', 1, 10);
690 // See if all semi-reasonable moves have only one possible response.
691 if (data['pv_uci'].length >= 2) {
692 var nonstupid_moves = find_nonstupid_moves(data, 300);
693 var response = data['pv_uci'][1];
694 for (var i = 0; i < nonstupid_moves.length; ++i) {
695 if (nonstupid_moves[i] == data['pv_uci'][0]) {
696 // ignore the PV move for refutation lines.
699 if (!data['refutation_lines'] ||
700 !data['refutation_lines'][nonstupid_moves[i]] ||
701 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
702 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
703 // Incomplete PV, abort.
704 response = undefined;
707 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
708 if (response !== this_response) {
709 // Different response depending on lines, abort.
710 response = undefined;
715 if (nonstupid_moves.length > 0 && response !== undefined) {
716 create_arrow(response.substr(0, 2),
717 response.substr(2, 2), '#66f', 6, 20);
721 // Update the refutation lines.
722 fen = data['position']['fen'];
723 move_num = data['position']['move_num'];
724 toplay = data['position']['toplay'];
725 refutation_lines = data['refutation_lines'];
726 update_refutation_lines();
729 setTimeout(function() { request_update(); }, 100);
733 * @param {boolean} sort_by_score
735 var resort_refutation_lines = function(sort_by_score) {
736 sort_refutation_lines_by_score = sort_by_score;
737 update_refutation_lines();
739 window['resort_refutation_lines'] = resort_refutation_lines;
742 * @param {boolean} truncate_history
744 var set_truncate_history = function(truncate_history) {
745 truncate_display_history = truncate_history;
746 update_refutation_lines();
748 window['set_truncate_history'] = set_truncate_history;
751 * @param {number} line_num
752 * @param {number} move_num
754 var show_line = function(line_num, move_num) {
755 if (line_num == -1) {
756 current_display_line = null;
757 current_display_move = null;
759 current_display_line = display_lines[line_num];
760 current_display_move = move_num;
762 update_displayed_line();
766 window['show_line'] = show_line;
768 var prev_move = function() {
769 if (current_display_move > -1) {
770 --current_display_move;
772 update_displayed_line();
774 window['prev_move'] = prev_move;
776 var next_move = function() {
777 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
778 ++current_display_move;
780 update_displayed_line();
782 window['next_move'] = next_move;
784 var update_displayed_line = function() {
785 if (highlighted_move !== null) {
786 highlighted_move.removeClass('highlight');
788 if (current_display_line === null) {
789 $("#linenav").hide();
790 $("#linemsg").show();
795 $("#linenav").show();
796 $("#linemsg").hide();
798 if (current_display_move <= 0) {
799 $("#prevmove").html("Previous");
801 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
803 if (current_display_move == current_display_line.uci_pv.length - 1) {
804 $("#nextmove").html("Next");
806 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
809 var hiddenboard = new Chess();
810 hiddenboard.load(current_display_line.start_fen);
811 for (var i = 0; i <= current_display_move; ++i) {
812 hiddenboard.move(ucimove_to_chessjs_move(current_display_line.uci_pv[i]));
815 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
816 highlighted_move.addClass('highlight');
818 board.position(hiddenboard.fen());
821 var ucimove_to_chessjs_move = function(move) {
822 var source = move.substr(0, 2);
823 var target = move.substr(2, 2);
824 var promo = move.substr(4, 1);
827 return { from: source, to: target };
829 return { from: source, to: target, promotion: promo };
833 var init = function() {
834 unique = get_unique();
837 board = new window.ChessBoard('board', 'start');
840 $(window).resize(function() {
845 $(window).keyup(function(event) {
846 if (event.which == 39) {
848 } else if (event.which == 37) {
853 $(document).ready(init);