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