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