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