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