]> git.sesse.net Git - remoteglot/blob - www/js/remoteglot.js
4c79edfc20b43a4a8e6b32d85e26c35f4ce120de
[remoteglot] / www / js / remoteglot.js
1 (function() {
2
3 var board = null;
4 var hiddenboard = null;
5 var arrows = [];
6 var occupied_by_arrows = [];
7 var refutation_lines = [];
8 var move_num = 1;
9 var toplay = 'W';
10 var ims = 0;
11 var sort_refutation_lines_by_score = 0;
12 var highlight_from = undefined;
13 var highlight_to = undefined;
14 var unique = Math.random();
15
16 var fen = null;
17 var display_lines = [];
18 var current_display_line = null;
19 var current_display_move = null;
20
21 var request_update = function() {
22         $.ajax({
23                 url: "http://analysis.sesse.net/analysis.pl?ims=" + ims + "&unique=" + unique
24                 //url: "http://analysis.sesse.net:5000/analysis.pl?ims=" + ims + "&unique=" + unique
25         }).done(function(data, textstatus, xhr) {
26                 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
27                 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
28                 update_board(data, num_viewers);
29         }).fail(function() {
30                 // Wait ten seconds, then try again.
31                 setTimeout(function() { request_update(); }, 10000);
32         });
33 }
34
35 var clear_arrows = function() {
36         for (var i = 0; i < arrows.length; ++i) {
37                 if (arrows[i].svg) {
38                         arrows[i].svg.parentElement.removeChild(arrows[i].svg);
39                         delete arrows[i].svg;
40                 }
41         }
42         arrows = [];
43
44         occupied_by_arrows = [];
45         for (var y = 0; y < 8; ++y) {
46                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
47         }
48 }
49
50 var redraw_arrows = function() {
51         for (var i = 0; i < arrows.length; ++i) {
52                 position_arrow(arrows[i]);
53         }
54 }
55
56 var sign = function(x) {
57         if (x > 0) {
58                 return 1;
59         } else if (x < 0) {
60                 return -1;
61         } else {
62                 return 0;
63         }
64 }
65
66 // See if drawing this arrow on the board would cause unduly amount of confusion.
67 var interfering_arrow = function(from, to) {
68         var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
69         var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
70         var to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
71         var to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
72
73         occupied_by_arrows[from_row][from_col] = true;
74
75         // Knight move: Just check that we haven't been at the destination before.
76         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
77             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
78                 return occupied_by_arrows[to_row][to_col];
79         }
80
81         // Sliding piece: Check if anything except the from-square is seen before.
82         var dx = sign(to_col - from_col);
83         var dy = sign(to_row - from_row);
84         var x = from_col;
85         var y = from_row;
86         do {
87                 x += dx;
88                 y += dy;
89                 if (occupied_by_arrows[y][x]) {
90                         return true;
91                 }
92                 occupied_by_arrows[y][x] = true;
93         } while (x != to_col || y != to_row);
94
95         return false;
96 }
97
98 var point_from_start = function(x1, y1, x2, y2, t, u) {
99         var dx = x2 - x1;
100         var dy = y2 - y1;
101
102         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
103         dx *= norm;
104         dy *= norm;
105
106         var x = x1 + dx * t + dy * u;
107         var y = y1 + dy * t - dx * u;
108         return x + " " + y;
109 }
110
111 var point_from_end = function(x1, y1, x2, y2, t, u) {
112         var dx = x2 - x1;
113         var dy = y2 - y1;
114
115         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
116         dx *= norm;
117         dy *= norm;
118
119         var x = x2 + dx * t + dy * u;
120         var y = y2 + dy * t - dx * u;
121         return x + " " + y;
122 }
123
124 var position_arrow = function(arrow) {
125         if (arrow.svg) {
126                 arrow.svg.parentElement.removeChild(arrow.svg);
127                 delete arrow.svg;
128         }
129         if (current_display_line !== null) {
130                 return;
131         }
132
133         var pos = $(".square-a8").position();
134
135         var zoom_factor = $("#board").width() / 400.0;
136         var line_width = arrow.line_width * zoom_factor;
137         var arrow_size = arrow.arrow_size * zoom_factor;
138
139         var square_width = $(".square-a8").width();
140         var from_y = (7 - arrow.from_row + 0.5)*square_width;
141         var to_y = (7 - arrow.to_row + 0.5)*square_width;
142         var from_x = (arrow.from_col + 0.5)*square_width;
143         var to_x = (arrow.to_col + 0.5)*square_width;
144
145         var SVG_NS = "http://www.w3.org/2000/svg";
146         var XHTML_NS = "http://www.w3.org/1999/xhtml";
147         var svg = document.createElementNS(SVG_NS, "svg");
148         svg.setAttribute("width", $("#board").width());
149         svg.setAttribute("height", $("#board").height());
150         svg.setAttribute("style", "position: absolute");
151         svg.setAttribute("position", "absolute");
152         svg.setAttribute("version", "1.1");
153         svg.setAttribute("class", "c1");
154         svg.setAttribute("xmlns", XHTML_NS);
155
156         var x1 = from_x;
157         var y1 = from_y;
158         var x2 = to_x;
159         var y2 = to_y;
160
161         // Draw the line.
162         var outline = document.createElementNS(SVG_NS, "path");
163         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));
164         outline.setAttribute("xmlns", XHTML_NS);
165         outline.setAttribute("stroke", "#666");
166         outline.setAttribute("stroke-width", line_width + 2);
167         outline.setAttribute("fill", "none");
168         svg.appendChild(outline);
169
170         var path = document.createElementNS(SVG_NS, "path");
171         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));
172         path.setAttribute("xmlns", XHTML_NS);
173         path.setAttribute("stroke", arrow.fg_color);
174         path.setAttribute("stroke-width", line_width);
175         path.setAttribute("fill", "none");
176         svg.appendChild(path);
177
178         // Then the arrow head.
179         var head = document.createElementNS(SVG_NS, "path");
180         head.setAttribute("d",
181                 "M " +  point_from_end(x1, y1, x2, y2, 0, 0) +
182                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
183                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
184                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
185                 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
186         head.setAttribute("xmlns", XHTML_NS);
187         head.setAttribute("stroke", "#000");
188         head.setAttribute("stroke-width", "1");
189         head.setAttribute("fill", "#f66");
190         svg.appendChild(head);
191
192         $(svg).css({ top: pos.top, left: pos.left });
193         document.body.appendChild(svg);
194         arrow.svg = svg;
195 }
196
197 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
198         var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
199         var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
200         var to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
201         var to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
202
203         // Create arrow.
204         var arrow = {
205                 from_col: from_col,
206                 from_row: from_row,
207                 to_col: to_col,
208                 to_row: to_row,
209                 line_width: line_width,
210                 arrow_size: arrow_size,
211                 fg_color: fg_color
212         };
213
214         position_arrow(arrow);
215         arrows.push(arrow);
216 }
217
218 var compare_by_sort_key = function(refutation_lines, a, b) {
219         var ska = refutation_lines[a]['sort_key'];
220         var skb = refutation_lines[b]['sort_key'];
221         if (ska < skb) return -1;
222         if (ska > skb) return 1;
223         return 0;
224 };
225
226 var compare_by_score = function(refutation_lines, a, b) {
227         var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
228         var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
229         return sa - sb;
230 }
231
232 // Fake multi-PV using the refutation lines. Find all “relevant” moves,
233 // sorted by quality, descending.
234 var find_nonstupid_moves = function(data, margin) {
235         // First of all, if there are any moves that are more than 0.5 ahead of
236         // the primary move, the refutation lines are probably bunk, so just
237         // kill them all. 
238         var best_score = undefined;
239         var pv_score = undefined;
240         for (var move in data['refutation_lines']) {
241                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
242                 if (move == data['pv_uci'][0]) {
243                         pv_score = score;
244                 }
245                 if (best_score === undefined || score > best_score) {
246                         best_score = score;
247                 }
248                 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
249                         return [];
250                 }
251         }
252
253         if (best_score - pv_score > 50) {
254                 return [];
255         }
256
257         // Now find all moves that are within “margin” of the best score.
258         // The PV move will always be first.
259         var moves = [];
260         for (var move in data['refutation_lines']) {
261                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
262                 if (move != data['pv_uci'][0] && best_score - score <= margin) {
263                         moves.push(move);
264                 }
265         }
266         moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
267         moves.unshift(data['pv_uci'][0]);
268
269         return moves;
270 }
271
272 var thousands = function(x) {
273         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
274 }
275
276 var print_pv = function(fen, uci_pv, pretty_pv, move_num, toplay, opt_limit) {
277         display_lines.push({
278                 start_fen: fen,
279                 uci_pv: uci_pv,
280                 pretty_pv: pretty_pv 
281         });
282
283         var pv = '';
284         var i = 0;
285         if (toplay == 'B') {
286                 var move = "<a class=\"move\" href=\"javascript:show_line(" + (display_lines.length - 1) + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
287                 pv = move_num + '. … ' + move;
288                 toplay = 'W';
289                 ++i;
290                 ++move_num;
291         }
292         for ( ; i < pretty_pv.length; ++i) {
293                 var move = "<a class=\"move\" href=\"javascript:show_line(" + (display_lines.length - 1) + ", " + i + ");\">" + pretty_pv[i] + "</a>";
294
295                 if (toplay == 'W') {
296                         if (i > opt_limit) {
297                                 return pv + ' (…)';
298                         }
299                         if (pv != '') {
300                                 pv += ' ';
301                         }
302                         pv += move_num + '. ' + move;
303                         ++move_num;
304                         toplay = 'B';
305                 } else {
306                         pv += ' ' + move;
307                         toplay = 'W';
308                 }
309         }
310         return pv;
311 }
312
313 var update_highlight = function()  {
314         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
315         if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
316                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
317                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
318         }
319 }
320
321 var update_refutation_lines = function() {
322         if (display_lines.length > 1) {
323                 display_lines = [ display_lines[0] ];
324         }
325
326         var tbl = $("#refutationlines");
327         tbl.empty();
328
329         var moves = [];
330         for (var move in refutation_lines) {
331                 moves.push(move);
332         }
333         var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
334         moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
335         for (var i = 0; i < moves.length; ++i) {
336                 var line = refutation_lines[moves[i]];
337
338                 var tr = document.createElement("tr");
339
340                 var move_td = document.createElement("td");
341                 tr.appendChild(move_td);
342                 $(move_td).addClass("move");
343                 if (line['pv_uci'].length == 0) {
344                         $(move_td).text(line['pretty_move']);
345                 } else {
346                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
347                         $(move_td).html(move);
348                 }
349
350                 var score_td = document.createElement("td");
351                 tr.appendChild(score_td);
352                 $(score_td).addClass("score");
353                 $(score_td).text(line['pretty_score']);
354
355                 var depth_td = document.createElement("td");
356                 tr.appendChild(depth_td);
357                 $(depth_td).addClass("depth");
358                 $(depth_td).text("d" + line['depth']);
359
360                 var pv_td = document.createElement("td");
361                 tr.appendChild(pv_td);
362                 $(pv_td).addClass("pv");
363                 $(pv_td).html(print_pv(fen, line['pv_uci'], line['pv_pretty'], move_num, toplay, 10));
364
365                 tbl.append(tr);
366         }
367
368         // Make one of the links clickable and the other nonclickable.
369         if (sort_refutation_lines_by_score) {
370                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(0)\">Move</a>");
371                 $("#sortbyscore1").html("<strong>Score</strong>");
372         } else {
373                 $("#sortbyscore0").html("<strong>Move</strong>");
374                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(1)\">Score</a>");
375         }
376 }
377
378 var update_board = function(data, num_viewers) {
379         display_lines = [];
380
381         // The headline.
382         var headline = 'Analysis';
383         if (data['position']['last_move'] !== 'none') {
384                 headline += ' after '
385                 if (data['position']['toplay'] == 'W') {
386                         headline += (data['position']['move_num']-1) + '… ';
387                 } else {
388                         headline += data['position']['move_num'] + '. ';
389                 }
390                 headline += data['position']['last_move'];
391         }
392
393         $("#headline").text(headline);
394
395         if (num_viewers === null) {
396                 $("#numviewers").text("");
397         } else if (num_viewers == 1) {
398                 $("#numviewers").text("You are the only current viewer");
399         } else {
400                 $("#numviewers").text(num_viewers + " current viewers");
401         }
402
403         // The score.
404         if (data['score'] !== null) {
405                 $("#score").text(data['score']);
406         }
407
408         // The search stats.
409         if (data['nodes'] && data['nps'] && data['depth']) {
410                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
411                 if (data['seldepth']) {
412                         stats += ' (' + data['seldepth'] + ' selective)';
413                 }
414                 if (data['tbhits'] && data['tbhits'] > 0) {
415                         if (data['tbhits'] == 1) {
416                                 stats += ', one Nalimov hit';
417                         } else {
418                                 stats += ', ' + data['tbhits'] + ' Nalimov hits';
419                         }
420                 }
421
422                 $("#searchstats").text(stats);
423         }
424
425         // Update the board itself.
426         fen = data['position']['fen'];
427         update_displayed_line();
428
429         if (data['position']['last_move_uci']) {
430                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
431                 highlight_to = data['position']['last_move_uci'].substr(2, 4);
432         } else {
433                 highlight_from = highlight_to = undefined;
434         }
435         update_highlight();
436
437         // Print the PV.
438         $("#pv").html(print_pv(data['position']['fen'], data['pv_uci'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
439
440         // Update the PV arrow.
441         clear_arrows();
442         if (data['pv_uci'].length >= 1) {
443                 // draw a continuation arrow as long as it's the same piece
444                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
445                         var from = data['pv_uci'][i].substr(0, 2);
446                         var to = data['pv_uci'][i].substr(2,4);
447                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 4)) ||
448                              interfering_arrow(from, to)) {
449                                 break;
450                         }
451                         create_arrow(from, to, '#f66', 6, 20);
452                 }
453
454                 var alt_moves = find_nonstupid_moves(data, 30);
455                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
456                         create_arrow(alt_moves[i].substr(0, 2),
457                                      alt_moves[i].substr(2, 4), '#f66', 1, 10);
458                 }
459         }
460
461         // See if all semi-reasonable moves have only one possible response.
462         if (data['pv_uci'].length >= 2) {
463                 var nonstupid_moves = find_nonstupid_moves(data, 300);
464                 var response = data['pv_uci'][1];
465                 for (var i = 0; i < nonstupid_moves.length; ++i) {
466                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
467                                 // ignore the PV move for refutation lines.
468                                 continue;
469                         }
470                         if (!data['refutation_lines'] ||
471                             !data['refutation_lines'][nonstupid_moves[i]] ||
472                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
473                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
474                                 // Incomplete PV, abort.
475                                 response = undefined;
476                                 break;
477                         }
478                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
479                         if (response !== this_response) {
480                                 // Different response depending on lines, abort.
481                                 response = undefined;
482                                 break;
483                         }
484                 }
485
486                 if (nonstupid_moves.length > 0 && response !== undefined) {
487                         create_arrow(response.substr(0, 2),
488                                      response.substr(2, 4), '#66f', 6, 20);
489                 }
490         }
491
492         // Update the refutation lines.
493         fen = data['position']['fen'];
494         move_num = data['position']['move_num'];
495         toplay = data['position']['toplay'];
496         refutation_lines = data['refutation_lines'];
497         update_refutation_lines();
498
499         // Next update.
500         setTimeout(function() { request_update(); }, 100);
501 }
502
503 var resort_refutation_lines = function(sort_by_score) {
504         sort_refutation_lines_by_score = sort_by_score;
505         update_refutation_lines();
506 }
507 window['resort_refutation_lines'] = resort_refutation_lines;
508
509 var show_line = function(line_num, move_num) {
510         if (line_num == -1) {
511                 current_display_line = null;
512                 current_display_move = null;
513         } else {
514                 current_display_line = display_lines[line_num];
515                 current_display_move = move_num;
516         }
517         update_displayed_line();
518         update_highlight();
519         redraw_arrows();
520 }
521 window['show_line'] = show_line;
522
523 var prev_move = function() {
524         --current_display_move;
525         update_displayed_line();
526 }
527 window['prev_move'] = prev_move;
528
529 var next_move = function() {
530         ++current_display_move;
531         update_displayed_line();
532 }
533 window['next_move'] = prev_move;
534
535 var update_displayed_line = function() {
536         if (current_display_line === null) {
537                 $("#linenav").hide();
538                 $("#linemsg").show();
539                 board.position(fen);
540                 return;
541         }
542
543         $("#linenav").show();
544         $("#linemsg").hide();
545
546         if (current_display_move == 0) {
547                 $("#prevmove").html("Previous");
548         } else {
549                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
550         }
551         if (current_display_move == current_display_line.uci_pv.length - 1) {
552                 $("#nextmove").html("Next");
553         } else {
554                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
555         }
556
557         hiddenboard.position(current_display_line.start_fen, false);
558         for (var i = 0; i <= current_display_move; ++i) {
559                 var move = current_display_line.uci_pv[i];
560                 move = move.substr(0, 2) + "-" + move.substr(2, 4);
561                 hiddenboard.move(move, false);
562         }
563         board.position(hiddenboard.position());
564 }
565
566 var init = function() {
567         // Create board.
568         board = new window.ChessBoard('board', 'start');
569         hiddenboard = new window.ChessBoard('hiddenboard', 'start');
570
571         request_update();
572         $(window).resize(function() {
573                 board.resize();
574                 update_highlight();
575                 redraw_arrows();
576         });
577 };
578 $(document).ready(init);
579
580 })();