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