-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
view.ts
494 lines (463 loc) · 15.2 KB
/
view.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import * as winningChances from './winningChances';
import * as licon from 'common/licon';
import { stepwiseScroll } from 'common/scroll';
import { bind } from 'common/snabbdom';
import { defined, notNull } from 'common';
import { Eval, ParentCtrl, NodeEvals } from './types';
import { h, VNode } from 'snabbdom';
import { Position } from 'chessops/chess';
import { lichessRules } from 'chessops/compat';
import { makeSanAndPlay } from 'chessops/san';
import { opposite, parseUci } from 'chessops/util';
import { parseFen, makeBoardFen } from 'chessops/fen';
import { renderEval } from './util';
import { setupPosition } from 'chessops/variant';
import { uciToMove } from 'chessground/util';
import { CevalState } from './worker';
import CevalCtrl from './ctrl';
let gaugeLast = 0;
const gaugeTicks: VNode[] = [...Array(8).keys()].map(i =>
h(i === 3 ? 'tick.zero' : 'tick', { attrs: { style: `height: ${(i + 1) * 12.5}%` } }),
);
function localEvalInfo(ctrl: ParentCtrl, evs: NodeEvals): Array<VNode | string> {
const ceval = ctrl.getCeval(),
state = ceval.getState(),
trans = ctrl.trans;
if (!evs.client) {
if (!ceval.analysable) return ['Engine cannot analyze this position'];
if (state == CevalState.Failed) return [trans.noarg('engineFailed')];
const mb = ceval.downloadProgress() / 1024 / 1024;
const localEvalText =
state == CevalState.Loading
? trans.noarg('loadingEngine') + (mb >= 1 ? ` (${mb.toFixed(1)} MiB)` : '')
: trans.noarg('calculatingMoves');
return [evs.server && ctrl.nextNodeBest() ? trans.noarg('usingServerAnalysis') : localEvalText];
}
const depth = evs.client.depth || 0;
const t: Array<VNode | string> = evs.client.cloud
? [trans('depthX', depth), h('span.cloud', { attrs: { title: trans.noarg('cloudAnalysis') } }, 'Cloud')]
: [trans('depthX', depth + '/' + Math.max(depth, evs.client.maxDepth))];
if (ceval.infinite()) t.push(h('span.infinite', { attrs: { title: trans('infiniteAnalysis') } }, '∞'));
if (ceval.canGoDeeper())
t.push(
h('a.deeper', {
attrs: {
title: trans.noarg('goDeeper'),
'data-icon': licon.PlusButton,
},
hook: bind('click', ceval.goDeeper),
}),
);
else if (!evs.client.cloud && evs.client.knps) t.push(', ' + Math.round(evs.client.knps) + 'k nodes/s');
return t;
}
function threatInfo(ctrl: ParentCtrl, threat?: Tree.LocalEval | false): string {
if (!threat) return ctrl.trans.noarg('calculatingMoves');
let t = ctrl.trans('depthX', (threat.depth || 0) + '/' + threat.maxDepth);
if (threat.knps) t += ', ' + Math.round(threat.knps) + 'k nodes/s';
return t;
}
function threatButton(ctrl: ParentCtrl): VNode | null {
if (ctrl.disableThreatMode && ctrl.disableThreatMode()) return null;
return h('a.show-threat', {
class: {
active: ctrl.threatMode(),
hidden: !!ctrl.getNode().check,
},
attrs: {
'data-icon': licon.Target,
title: ctrl.trans.noarg('showThreat') + ' (x)',
},
hook: bind('click', ctrl.toggleThreatMode),
});
}
function engineName(ctrl: CevalCtrl): VNode[] {
return [
h('span', { attrs: { title: ctrl.longEngineName() || '' } }, ctrl.shortEngineName()),
ctrl.technology == 'external'
? h(
'span.technology.good',
{
attrs: {
title: 'Engine running outside of the browser',
},
},
'EXTERNAL',
)
: ctrl.technology == 'nnue'
? h(
'span.technology.good',
{
attrs: {
title:
'Multi-threaded WebAssembly with SIMD (efficiently updatable neural network, using 4x smaller net by Sopel97)',
},
},
'NNUE',
)
: ctrl.technology == 'hce'
? h(
'span.technology.good',
{ attrs: { title: 'Multi-threaded WebAssembly (classical hand crafted evaluation)' } },
'HCE',
)
: ctrl.technology == 'wasm'
? h('span.technology', { attrs: { title: 'Single-threaded WebAssembly fallback (slow)' } }, 'WASM')
: h(
'span.technology',
{ attrs: { title: 'Single-threaded JavaScript fallback (very slow)' } },
'ASMJS',
),
];
}
const serverNodes = 4e6;
export function getBestEval(evs: NodeEvals): Eval | undefined {
const serverEv = evs.server,
localEv = evs.client;
if (!serverEv) return localEv;
if (!localEv) return serverEv;
// Prefer localEv if it exceeds fishnet node limit or finds a better mate.
if (
localEv.nodes > serverNodes ||
(typeof localEv.mate !== 'undefined' &&
(typeof serverEv.mate === 'undefined' || Math.abs(localEv.mate) < Math.abs(serverEv.mate)))
)
return localEv;
return serverEv;
}
export function renderGauge(ctrl: ParentCtrl): VNode | undefined {
if (ctrl.ongoing || !ctrl.showEvalGauge()) return;
const bestEv = getBestEval(ctrl.currentEvals());
let ev;
if (bestEv) {
ev = winningChances.povChances('white', bestEv);
gaugeLast = ev;
} else ev = gaugeLast;
return h(
'div.eval-gauge',
{
class: {
empty: ev === null,
reverse: ctrl.getOrientation() === 'black',
},
},
[h('div.black', { attrs: { style: `height: ${100 - (ev + 1) * 50}%` } }), ...gaugeTicks],
);
}
export function renderCeval(ctrl: ParentCtrl): VNode | undefined {
const instance = ctrl.getCeval(),
trans = ctrl.trans;
if (!instance.allowed() || !instance.possible || !ctrl.showComputer()) return;
const enabled = instance.enabled(),
evs = ctrl.currentEvals(),
threatMode = ctrl.threatMode(),
threat = threatMode && ctrl.getNode().threat,
bestEv = threat || getBestEval(evs);
let pearl: VNode | string, percent: number;
if (bestEv && typeof bestEv.cp !== 'undefined') {
pearl = renderEval(bestEv.cp);
percent = evs.client
? evs.client.cloud
? 100
: Math.min(100, Math.round((100 * evs.client.depth) / evs.client.maxDepth))
: 0;
} else if (bestEv && defined(bestEv.mate)) {
pearl = '#' + bestEv.mate;
percent = 100;
} else {
if (!enabled) pearl = h('i');
else if (ctrl.outcome() || ctrl.getNode().threefold) pearl = '-';
else if (instance.getState() === CevalState.Failed)
pearl = h('i.is-red', { attrs: { 'data-icon': licon.CautionCircle } });
else pearl = h('i.ddloader');
percent = 0;
}
if (threatMode) {
if (threat) percent = Math.min(100, Math.round((100 * threat.depth) / threat.maxDepth));
else percent = 0;
}
const progressBar: VNode | null = enabled
? h(
'div.bar',
h('span', {
class: { threat: threatMode },
attrs: { style: `width: ${percent}%` },
hook: {
postpatch: (old, vnode) => {
if (old.data!.percent > percent || !!old.data!.threatMode != threatMode) {
const el = vnode.elm as HTMLElement;
const p = el.parentNode as HTMLElement;
p.removeChild(el);
p.appendChild(el);
}
vnode.data!.percent = percent;
vnode.data!.threatMode = threatMode;
},
},
}),
)
: null;
const body: Array<VNode | null> = enabled
? [
h('pearl', [pearl]),
h('div.engine', [
...(threatMode ? [trans.noarg('showThreat')] : engineName(instance)),
h(
'span.info',
ctrl.outcome()
? [trans.noarg('gameOver')]
: ctrl.getNode().threefold
? [trans.noarg('threefoldRepetition')]
: threatMode
? [threatInfo(ctrl, threat)]
: localEvalInfo(ctrl, evs),
),
]),
]
: [
pearl ? h('pearl', [pearl]) : null,
h('help', [
...engineName(instance),
h('br'),
instance.analysable ? trans.noarg('inLocalBrowser') : 'Engine cannot analyse this game',
]),
];
const switchButton: VNode | null =
ctrl.mandatoryCeval && ctrl.mandatoryCeval()
? null
: h(
'div.switch',
{
attrs: { title: trans.noarg('toggleLocalEvaluation') + ' (L)' },
},
[
h('input#analyse-toggle-ceval.cmn-toggle.cmn-toggle--subtle', {
attrs: {
type: 'checkbox',
checked: enabled,
disabled: !instance.analysable,
},
hook: bind('change', ctrl.toggleCeval),
}),
h('label', { attrs: { for: 'analyse-toggle-ceval' } }),
],
);
return h(
'div.ceval' + (enabled ? '.enabled' : ''),
{
class: {
computing: percent < 100 && instance.getState() === CevalState.Computing,
},
},
[progressBar, ...body, threatButton(ctrl), switchButton],
);
}
function getElFen(el: HTMLElement): string {
return el.getAttribute('data-fen')!;
}
function getElUci(e: TouchEvent | MouseEvent): string | undefined {
return (
$(e.target as HTMLElement)
.closest('div.pv')
.attr('data-uci') || undefined
);
}
function getElUciList(e: TouchEvent | MouseEvent): string[] {
return getElPvMoves(e)
.filter(notNull)
.map(move => move.split('|')[1]);
}
function getElPvMoves(e: TouchEvent | MouseEvent): (string | null)[] {
const pvMoves: (string | null)[] = [];
$(e.target as HTMLElement)
.closest('div.pv')
.children()
.filter('span.pv-san')
.each(function () {
pvMoves.push($(this).attr('data-board'));
});
return pvMoves;
}
function checkHover(el: HTMLElement, instance: CevalCtrl): void {
lichess.requestIdleCallback(
() => instance.setHovering(getElFen(el), $(el).find('div.pv:hover').attr('data-uci') || undefined),
500,
);
}
export function renderPvs(ctrl: ParentCtrl): VNode | undefined {
const instance = ctrl.getCeval();
if (!instance.allowed() || !instance.possible || !instance.enabled()) return;
const multiPv = instance.multiPv(),
node = ctrl.getNode(),
setup = parseFen(node.fen).unwrap();
let pvs: Tree.PvData[],
threat = false,
pvMoves: (string | null)[],
pvIndex: number | null;
if (ctrl.threatMode() && node.threat) {
pvs = node.threat.pvs;
threat = true;
} else if (node.ceval) pvs = node.ceval.pvs;
else pvs = [];
if (threat) {
setup.turn = opposite(setup.turn);
if (setup.turn == 'white') setup.fullmoves += 1;
}
const pos = setupPosition(lichessRules(instance.opts.variant.key), setup);
return h(
'div.pv_box',
{
attrs: { 'data-fen': node.fen },
hook: {
insert: vnode => {
const el = vnode.elm as HTMLElement;
el.addEventListener('mouseover', (e: MouseEvent) => {
const instance = ctrl.getCeval();
instance.setHovering(getElFen(el), getElUci(e));
const pvBoard = (e.target as HTMLElement).dataset.board;
if (pvBoard) {
pvIndex = Number((e.target as HTMLElement).dataset.moveIndex);
pvMoves = getElPvMoves(e);
const [fen, uci] = pvBoard.split('|');
instance.setPvBoard({ fen, uci });
}
});
el.addEventListener(
'wheel',
stepwiseScroll((e: WheelEvent, scroll: boolean) => {
e.preventDefault();
if (pvIndex != null && pvMoves != null) {
if (e.deltaY < 0 && pvIndex > 0 && scroll) pvIndex -= 1;
else if (e.deltaY > 0 && pvIndex < pvMoves.length - 1 && scroll) pvIndex += 1;
const pvBoard = pvMoves[pvIndex];
if (pvBoard) {
const [fen, uci] = pvBoard.split('|');
ctrl.getCeval().setPvBoard({ fen, uci });
}
}
}),
);
el.addEventListener('mouseout', () => ctrl.getCeval().setHovering(getElFen(el)));
for (const event of ['touchstart', 'mousedown']) {
el.addEventListener(event, (e: TouchEvent | MouseEvent) => {
const uciList = getElUciList(e);
if (uciList.length > (pvIndex ?? 0) && !ctrl.threatMode()) {
ctrl.playUciList(uciList.slice(0, (pvIndex ?? 0) + 1));
e.preventDefault();
}
});
}
el.addEventListener('mouseleave', () => {
ctrl.getCeval().setPvBoard(null);
pvIndex = null;
});
checkHover(el, instance);
},
postpatch: (_, vnode) => checkHover(vnode.elm as HTMLElement, instance),
},
},
[
...[...Array(multiPv).keys()].map(i =>
renderPv(threat, multiPv, pvs[i], pos.isOk ? pos.value : undefined),
),
renderPvBoard(ctrl),
],
);
}
const MAX_NUM_MOVES = 16;
function renderPv(threat: boolean, multiPv: number, pv?: Tree.PvData, pos?: Position): VNode {
const data: any = {};
const children: VNode[] = [renderPvWrapToggle()];
if (pv) {
if (!threat) {
data.attrs = { 'data-uci': pv.moves[0] };
}
if (multiPv > 1) {
children.push(h('strong', defined(pv.mate) ? '#' + pv.mate : renderEval(pv.cp!)));
}
if (pos) {
children.push(...renderPvMoves(pos.clone(), pv.moves.slice(0, MAX_NUM_MOVES)));
}
}
return h('div.pv.pv--nowrap', data, children);
}
function renderPvWrapToggle(): VNode {
return h('span.pv-wrap-toggle', {
hook: {
insert: (vnode: VNode) => {
const el = vnode.elm as HTMLElement;
for (const event of ['touchstart', 'mousedown']) {
el.addEventListener(event, (e: Event) => {
e.stopPropagation();
e.preventDefault();
$(el).closest('.pv').toggleClass('pv--nowrap');
});
}
},
},
});
}
function renderPvMoves(pos: Position, pv: Uci[]): VNode[] {
const vnodes: VNode[] = [];
let key = makeBoardFen(pos.board);
for (let i = 0; i < pv.length; i++) {
let text;
if (pos.turn === 'white') {
text = `${pos.fullmoves}.`;
} else if (i === 0) {
text = `${pos.fullmoves}...`;
}
if (text) {
vnodes.push(h('span', { key: text }, text));
}
const uci = pv[i];
const san = makeSanAndPlay(pos, parseUci(uci)!);
const fen = makeBoardFen(pos.board); // Chessground uses only board fen
if (san === '--') {
break;
}
key += '|' + uci;
vnodes.push(
h(
'span.pv-san',
{
key,
attrs: {
'data-move-index': i,
'data-board': `${fen}|${uci}`,
},
},
san,
),
);
}
return vnodes;
}
function renderPvBoard(ctrl: ParentCtrl): VNode | undefined {
const instance = ctrl.getCeval();
const pvBoard = instance.pvBoard();
if (!pvBoard) {
return;
}
const { fen, uci } = pvBoard;
const orientation = ctrl.getOrientation();
const cgConfig = {
fen,
lastMove: uciToMove(uci),
orientation,
coordinates: false,
viewOnly: true,
drawable: {
enabled: false,
visible: false,
},
};
const cgVNode = h('div.cg-wrap.is2d', {
hook: {
insert: (vnode: any) => (vnode.elm._cg = lichess.makeChessground(vnode.elm, cgConfig)),
update: (vnode: any) => vnode.elm._cg?.set(cgConfig),
destroy: (vnode: any) => vnode.elm._cg?.destroy(),
},
});
return h('div.pv-board', h('div.pv-board-square', cgVNode));
}