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