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