chiark / gitweb /
e28b4dd5413f3f8fcac8a3003d903f0329ef4de6
[otter.git] / templates / script.ts
1 // -*- JavaScript -*-
2
3 // Copyright 2020-2021 Ian Jackson and contributors to Otter
4 // SPDX-License-Identifier: AGPL-3.0-or-later
5 // There is NO WARRANTY.
6
7 // elemnts for a piece
8 //
9 // In svg toplevel
10 //
11 //   uelem
12 //      #use{}
13 //      <use id="use{}", href="#piece{}" x= y= >
14 //         .piece   piece id (static)
15 //      container to allow quick movement and hang stuff off
16 //
17 //   delem
18 //      #defs{}
19 //      <def id="defs{}">
20 //
21 // And in each delem
22 //
23 //   pelem
24 //   #piece{}
25 //         .dragraise   dragged more than this ?  raise to top!
26 //         .special     enum RenderSpecial
27 //      <g id="piece{}" >
28 //      currently-displayed version of the piece
29 //      to allow addition/removal of selected indication
30 //      contains 1 or 3 subelements:
31 //      one is straight from server and not modified
32 //      one is possible <use href="#select{}" >
33 //      one is possible <use href="#halo{}" >
34 //
35 //   #select{}
36 //      generated by server, referenced by JS in pelem for selection
37 //
38 //   #def.{}.stuff
39 //      generated by server, reserved for Piece trait impl
40
41 type PieceId = string;
42 type PlayerId = string;
43 type Pos = [number, number];
44 type Rect = [Pos, Pos];
45 type ClientSeq = number;
46 type Generation = number;
47 type UoKind = 'Client' | "Global"| "Piece" | "ClientExtra" | "GlobalExtra";
48 type WhatResponseToClientOp = "Predictable" | "Unpredictable" | "UpdateSvg";
49 type HeldUsRaising = "NotYet" | "Lowered" | "Raised"
50 type Timestamp = number; // unix time_t, will break in 285My
51 type Layout = 'Portrait' | 'Landscape';
52 type PieceMoveable = "No" | "IfWresting" | "Yes";
53 type CompassAngle = number;
54 type FaceId = number;
55
56 type UoDescription = {
57   kind: UoKind;
58   wrc: WhatResponseToClientOp,
59   def_key: string,
60   opname: string,
61   desc: string,
62 }
63
64 type UoRecord = UoDescription & {
65   targets: PieceId[] | null,
66 }
67
68 type ZCoord = string;
69
70 // On load, starts from SessionPieceLoadJson (Rust-only)
71 // On update, updated field-by-field from PreparedPieceState (Rust&JS)
72 type PieceInfo = {
73   held : PlayerId | null,
74   cseq_main : number | null,
75   cseq_loose: number | null,
76   cseq_updatesvg : number | null,
77   z : ZCoord,
78   zg : Generation,
79   angle: CompassAngle,
80   pinned: boolean,
81   moveable: PieceMoveable,
82   rotateable: boolean,
83   multigrab: boolean,
84   desc: string,
85   uos : UoDescription[],
86   uelem : SVGGraphicsElement,
87   delem : SVGGraphicsElement,
88   pelem : SVGGraphicsElement,
89   queued_moves : number,
90   last_seen_moved : DOMHighResTimeStamp | null, // non-0 means halo'd
91   held_us_inoccult: boolean,
92   held_us_raising: HeldUsRaising,
93   bbox: Rect,
94   drag_delta: number,
95   special: SpecialRendering | null,
96 }
97
98 type SpecialRendering = {
99   kind: string,
100   stop: SpecialRenderingCallback,
101 }
102
103 let wasm : InitOutput;
104
105 var pieces : { [piece: string]: PieceInfo } = Object.create(null);
106
107 type MessageHandler = (op: Object) => void;
108 type PieceHandler = (piece: PieceId, p: PieceInfo, info: Object) => void;
109 type PieceErrorHandler = (piece: PieceId, p: PieceInfo, m: PieceOpError)
110   => boolean;
111 type SpecialRenderingCallback =
112   (piece: PieceId, p: PieceInfo, s: SpecialRendering) => void;
113 interface DispatchTable<H> { [key: string]: H };
114
115 var otter_debug: boolean;
116
117 // from header
118 var movehist_len_i: number;
119 var movehist_len_max: number;
120 var movehist_lens: number[];
121
122 // todo turn all var into let
123 // todo any exceptions should have otter in them or something
124 var globalinfo_elem : HTMLElement;
125 var layout: Layout;
126 var held_surround_colour: string;
127 var general_timeout : number = 10000;
128 var messages : DispatchTable<MessageHandler> = Object();
129 var special_renderings : DispatchTable<SpecialRenderingCallback> = Object();
130 var pieceops : DispatchTable<PieceHandler> = Object();
131 var update_error_handlers : DispatchTable<MessageHandler> = Object();
132 var piece_error_handlers : DispatchTable<PieceErrorHandler> = Object();
133 var our_dnd_type = "text/puvnex-game-server-dummy";
134 var api_queue : [string, Object][] = [];
135 var api_posting = false;
136 var us : PlayerId;
137 var gen : Generation = 0;
138 var cseq : ClientSeq = 0;
139 var ctoken : string;
140 var uo_map : { [k: string]: UoRecord | null } = Object.create(null);
141 var keyops_local : { [opname: string]: (uo: UoRecord) => void } = Object();
142 var last_log_ts: wasm_bindgen.TimestampAbbreviator;
143 var last_zoom_factor : number = 1.0;
144 var firefox_bug_zoom_factor_compensation : number = 1.0;
145 var test_update_hook : () => void;
146
147 var svg_ns : string;
148 var space : SVGGraphicsElement;
149 var pieces_marker : SVGGraphicsElement;
150 var defs_marker : SVGGraphicsElement;
151 var movehist_start: SVGGraphicsElement;
152 var movehist_end: SVGGraphicsElement;
153 var rectsel_path: SVGGraphicsElement;
154 var log_elem : HTMLElement;
155 var logscroll_elem : HTMLElement;
156 var status_node : HTMLElement;
157 var uos_node : HTMLElement;
158 var zoom_val : HTMLInputElement;
159 var zoom_btn : HTMLInputElement;
160 var links_elem : HTMLElement;
161 var wresting: boolean;
162 var occregions: wasm_bindgen.RegionList;
163 let special_count: number | null;
164
165 var movehist_gen: number = 0;
166 const MOVEHIST_ENDS = 2.5;
167 const SPECIAL_MULTI_DELTA_EACH = 3;
168 const SPECIAL_MULTI_DELTA_MAX = 18;
169
170 type PaneName = string;
171 const pane_keys : { [key: string]: PaneName } = {
172   "H" : "help",
173   "U" : "players",
174   "B" : "bundles",
175 };
176
177 const uo_kind_prec : { [kind: string]: number } = {
178   'GlobalExtra' :  50,
179   'Client'      :  70,
180   'Global'      : 100,
181   'Piece'       : 200,
182   'ClientExtra' : 500,
183 }
184
185 type PlayerInfo = {
186   dasharray : string,
187   nick: string,
188 }
189 var players : { [player: string]: PlayerInfo };
190
191 type MovementRecord = { // for yellow halo, unrelasted to movehist
192   piece: PieceId,
193   p: PieceInfo,
194   this_motion: DOMHighResTimeStamp,
195 }
196 var movements : MovementRecord[] = [];
197
198 function xhr_post_then(url : string, data: string,
199                        good : (xhr: XMLHttpRequest) => void) {
200   var xhr : XMLHttpRequest = new XMLHttpRequest();
201   xhr.onreadystatechange = function(){
202     if (xhr.readyState != XMLHttpRequest.DONE) { return; }
203     if (xhr.status != 200) { xhr_report_error(xhr); }
204     else { good(xhr); }
205   };
206   xhr.timeout = general_timeout;
207   xhr.open('POST',url);
208   xhr.setRequestHeader('Content-Type','application/json');
209   xhr.send(data);
210 }
211
212 function xhr_report_error(xhr: XMLHttpRequest) {
213   json_report_error({
214     statusText : xhr.statusText,
215     responseText : xhr.responseText,
216   });
217 }
218
219 function json_report_error(error_for_json: Object) {
220   let error_message = JSON.stringify(error_for_json);
221   string_report_error(error_message);
222 }
223
224 function string_report_error(error_message: String) {
225   string_report_error_raw('Error (reloading may help?): ' + error_message)
226 }
227 function string_report_error_raw(error_message: String) {
228   let errornode = document.getElementById('error')!;
229   errornode.textContent += '\n' + error_message;
230   console.error("ERROR reported via log", error_message);
231   // todo want to fix this for at least basic game reconfigs, auto-reload?
232 }
233
234 function api_immediate(meth: string, data: Object) {
235   api_queue.push([meth, data]);
236   api_check();
237 }
238 function api_delay(meth: string, data: Object) {
239   if (api_queue.length==0) window.setTimeout(api_check, 10);
240   api_queue.push([meth, data]);
241 }
242 function api_check() {
243   if (api_posting) { return; }
244   if (!api_queue.length) { test_update_hook(); return; }
245   do {
246     var [meth, data] = api_queue.shift()!;
247     if (meth != 'm') break;
248     let piece = (data as any).piece;
249     let p = pieces[piece];
250     if (p == null) break;
251     p.queued_moves--;
252     if (p.queued_moves == 0) break;
253   } while (api_queue.length);
254   api_posting = true;
255   xhr_post_then('/_/api/'+meth, JSON.stringify(data), api_posted);
256 }
257 function api_posted() {
258   api_posting = false;
259   api_check();
260 }
261
262 function api_piece_x(f: (meth: string, payload: Object) => void,
263                      loose: boolean,
264                      meth: string,
265                      piece: PieceId, p: PieceInfo,
266                      op: Object) {
267   clear_halo(piece,p);
268   cseq += 1;
269   if (loose) {
270     p.cseq_loose = cseq;
271   } else {
272     p.cseq_main = cseq;
273     p.cseq_loose = null;
274   }
275   f(meth, {
276     ctoken : ctoken,
277     piece : piece,
278     gen : gen,
279     cseq : cseq,
280     op : op,
281     loose: loose,
282   })
283 }
284 function api_piece(meth: string,
285                    piece: PieceId, p: PieceInfo,
286                    op: Object) {
287   api_piece_x(api_immediate, false,meth, piece, p, op);
288 }
289
290 function svg_element(id: string): SVGGraphicsElement | null {
291   let elem = document.getElementById(id);
292   return elem as unknown as (SVGGraphicsElement | null);
293 }
294 function piece_element(base: string, piece: PieceId): SVGGraphicsElement | null
295 {
296   return svg_element(base+piece);
297 }
298
299 function piece_moveable(p: PieceInfo) {
300   return p.moveable == 'Yes' || p.moveable == 'IfWresting' && wresting;
301 }
302
303 // ----- key handling -----
304
305 function recompute_keybindings() {
306   uo_map = Object.create(null);
307   let all_targets = [];
308   for (let piece of Object.keys(pieces)) {
309     let p = pieces[piece];
310     if (p.held != us) continue;
311     all_targets.push(piece);
312     for (var uo of p.uos) {
313       let currently = uo_map[uo.def_key];
314       if (currently === null) continue;
315       if (currently !== undefined) {
316         if (currently.opname != uo.opname) {
317           uo_map[uo.def_key] = null;
318           continue;
319         }
320       } else {
321         currently = {
322           targets: [],
323           ...uo
324         };
325         uo_map[uo.def_key] = currently;
326       }
327       currently.desc = currently.desc < uo.desc ? currently.desc : uo.desc;
328       currently.targets!.push(piece);
329     }
330   }
331   all_targets.sort(pieceid_z_cmp);
332   let add_uo = function(targets: PieceId[] | null, uo: UoDescription) {
333     uo_map[uo.def_key] = {
334       targets: targets,
335       ...uo
336     };
337   };
338   if (all_targets.length) {
339     let got_rotateable = false;
340     for (let t of all_targets) {
341       if (pieces[t]!.rotateable)
342         got_rotateable = true;
343     }
344     if (got_rotateable) {
345       add_uo(all_targets, {
346         def_key: 'l',
347         kind: 'Client',
348         wrc: 'Predictable',
349         opname: "left",
350         desc: "rotate left",
351       });
352       add_uo(all_targets, {
353         def_key: 'r',
354         kind: 'Client',
355         wrc: 'Predictable',
356         opname: "right",
357         desc: "rotate right",
358       });
359     }
360     add_uo(all_targets, {
361       def_key: 'b',
362       kind: 'Client',
363       wrc: 'Predictable',
364       opname: "lower",
365       desc: "send to bottom (below other pieces)",
366     });
367     add_uo(all_targets, {
368       def_key: 't',
369       kind: 'Client',
370       wrc: 'Predictable',
371       opname: "raise",
372       desc: "raise to top",
373     });
374   }
375   if (all_targets.length) {
376     let got = 0;
377     for (let t of all_targets) {
378       got |= 1 << Number(pieces[t]!.pinned);
379     }
380     if (got == 1) {
381       add_uo(all_targets, {
382         def_key: 'P',
383         kind: 'ClientExtra',
384         opname: 'pin',
385         desc: 'Pin to table',
386         wrc: 'Predictable',
387       });
388     } else if (got == 2) {
389       add_uo(all_targets, {
390         def_key: 'P',
391         kind: 'ClientExtra',
392         opname: 'unpin',
393         desc: 'Unpin from table',
394         wrc: 'Predictable',
395       });
396     }
397   }
398   add_uo(null, {
399     def_key: 'W',
400     kind: 'ClientExtra',
401     opname: 'wrest',
402     desc: wresting ? 'Exit wresting mode' : 'Enter wresting mode',
403     wrc: 'Predictable',
404   });
405   if (special_count != null) {
406     let desc;
407     if (special_count == 0) {
408       desc = 'select bottommost';
409     } else {
410       desc = `select ${special_count}`;
411     }
412     desc = `cancel <strong style="color:purple">${desc}</strong>`;
413     add_uo(null, {
414       def_key: 'SPC', // won't match key event; we handle this ad-hoc
415       kind: 'ClientExtra',
416       opname: 'cancel-special',
417       desc: desc,
418       wrc: 'Predictable',
419     });
420   }
421   add_uo(null, {
422     def_key: 'h',
423     kind: 'ClientExtra',
424     opname: 'motion-hint-history',
425     desc: 'Recent history display',
426     wrc: 'Predictable',
427   });
428   var uo_keys = Object.keys(uo_map);
429   uo_keys.sort(function (ak,bk) {
430     let a = uo_map[ak];
431     let b = uo_map[bk];
432     if (a==null || b==null) return (
433       ( (!!a) as any ) -
434       ( (!!b) as any )
435     );
436     return uo_kind_prec[a.kind] - uo_kind_prec[b.kind]
437       || ak.localeCompare(bk);
438   });
439   let mid_elem = null;
440   for (let celem = uos_node.firstElementChild;
441        celem != null;
442        celem = nextelem) {
443     var nextelem = celem.nextElementSibling;
444     let cid = celem.getAttribute("id");
445     if (cid == "uos-mid") mid_elem = celem;
446     else if (celem.getAttribute("class") == 'uos-mid') { }
447     else celem.remove();
448   }
449   for (var kk of uo_keys) {
450     let uo = uo_map[kk];
451     if (!uo) continue;
452     let prec = uo_kind_prec[uo.kind];
453     let ent = document.createElement('div');
454     ent.innerHTML = '<b>' + kk + '</b> ' + uo.desc;
455     if (prec < 400) {
456       ent.setAttribute('class','uokey-l');
457       uos_node.insertBefore(ent, mid_elem);
458     } else {
459       ent.setAttribute('class','uokey-r');
460       uos_node.appendChild(ent);
461     }
462   }
463 }
464
465 function some_keydown(e: KeyboardEvent) {
466   // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event
467   // says to do this, something to do with CJK composition.
468   // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
469   // says that keyCode is deprecated
470   // my tsc says this isComposing thing doesn't exist.  wat.
471   if ((e as any).isComposing /* || e.keyCode === 229 */) return;
472   if (e.ctrlKey || e.altKey || e.metaKey) return;
473   if (e.target) {
474     // someone else is dealing with it ?
475     let tag = (e.target as HTMLElement).tagName;
476     if (tag == 'INPUT') return;
477   }
478
479   let y = function() { e.preventDefault(); e.stopPropagation(); }
480
481   let pane = pane_keys[e.key];
482   if (pane) {
483     y();
484     return pane_switch(pane);
485   }
486
487   let special_count_key = parseInt(e.key);
488   if (isFinite(special_count_key)) {
489     y();
490     if (special_count == null) special_count = 0;
491     special_count *= 10;
492     special_count += special_count_key;
493     special_count %= 100000;
494     mousecursor_etc_reupdate();
495     return;
496   }
497   if (e.key == ' ') {
498     y();
499     special_count = null;
500     mousecursor_etc_reupdate();
501     return;
502   }
503
504   let uo = uo_map[e.key];
505   if (uo === undefined || uo === null) return;
506
507   y();
508   console.log('KEY UO', e, uo);
509   if (uo.kind == 'Client' || uo.kind == 'ClientExtra') {
510     let f = keyops_local[uo.opname];
511     f(uo);
512     return;
513   }
514   if (!(uo.kind == 'Global' || uo.kind == 'GlobalExtra' || uo.kind == 'Piece'))
515     throw 'bad kind '+uo.kind;
516
517   for (var piece of uo.targets!) {
518     let p = pieces[piece]!;
519     api_piece('k', piece, p, { opname: uo.opname, wrc: uo.wrc });
520     if (uo.wrc == 'UpdateSvg') {
521       // No UpdateSvg is loose, so no need to check p.cseq_loose
522       p.cseq_updatesvg = p.cseq_main;
523       redisplay_ancillaries(piece,p);
524     }
525   }
526 }
527
528 function pane_switch(newpane: PaneName) {
529   let new_e;
530   for (;;) {
531     new_e = document.getElementById('pane_' + newpane)!;
532     let style = new_e.getAttribute('style');
533     if (style || newpane == 'help') break;
534     newpane = 'help';
535   }
536   for (let old_e = new_e.parentElement!.firstElementChild;
537        old_e;
538        old_e = old_e.nextElementSibling) {
539     old_e.setAttribute('style','display: none;');
540   }
541   new_e.removeAttribute('style');
542 }
543
544 function mousecursor_etc_reupdate() {
545   let style_elem = document.getElementById("space-cursor-style")!;
546   let style_text;
547   let svg;
548   let xy;
549   let path = 'stroke-linecap="square" d="M -10 -10 10 10 M 10 -10 -10 10"';
550   
551   if (wresting) {
552     let text;
553     if (special_count == null) {
554       text = "WREST";
555     } else if (special_count == 0) {
556       text = "W v";
557     } else {
558       text = "W " + special_count;
559     }
560     xy = '60 15';
561     svg =
562 `<svg xmlns="http://www.w3.org/2000/svg"
563      viewBox="-60 -15 120 60" width="120" height="60">
564   <g transform="translate(0 0)">
565     <path stroke-width="8" stroke="black" ${path}/>
566     <path stroke-width="4" stroke="#cc0" ${path}/>
567  <text x="0" y="40" fill="black" stroke="#cc0" stroke-width="1.7" text-align="center" text-anchor="middle"
568  font-family="sans-serif" font-size="30">${text}</text>
569   </g></svg>`;
570   } else if (special_count == null) {
571   } else {
572     if (special_count != 0) {
573       let text_len = special_count.toString().length;
574       let text_x = text_len <= 3 ? 0 : -15;
575       let text_size = text_len <= 3 ? 50 : 45 * (4/text_len);
576       xy = '15 50';
577       svg = 
578 `<svg xmlns="http://www.w3.org/2000/svg"
579      viewBox="-15 0 120 65" width="120" height="65">
580   <g transform="translate(0 50)">
581     <path stroke-width="8" stroke="#fcf" ${path}/>
582     <path stroke-width="4" stroke="purple" ${path}/>
583     <text x="${text_x}" y="0" fill="purple" stroke="#fcf" stroke-width="2"
584        font-family="sans-serif" font-size="${text_size}">${special_count}</text>
585   </g></svg>`;
586     } else {
587       let path = 'stroke-linecap="square" d="M -10 -10 0 0 10 -10 M 0 0 0 -20"';
588       xy = '15 30';
589       svg =
590 `<svg xmlns="http://www.w3.org/2000/svg"
591      viewBox="-15 -25 30 30" width="30" height="30">
592   <g transform="translate(0 0)">
593     <path stroke-width="8" stroke="#fcf" ${path}/>
594     <path stroke-width="4" stroke="purple" ${path}/>
595   </g></svg>`;
596     }
597   }
598   if (svg !== undefined) {
599     let svg_data = btoa(svg);
600     style_text =
601 `svg[id=space] {
602   cursor: url(data:image/svg+xml;base64,${svg_data}) ${xy}, auto;
603 }`;
604   } else {
605     style_text = '';
606   }
607   style_elem.innerHTML = style_text;
608   recompute_keybindings();
609 }
610
611 keyops_local['left' ] = function (uo: UoRecord) { rotate_targets(uo, +1); }
612 keyops_local['right'] = function (uo: UoRecord) { rotate_targets(uo, -1); }
613
614 function rotate_targets(uo: UoRecord, dangle: number): boolean {
615   for (let piece of uo.targets!) {
616     let p = pieces[piece]!;
617     if (!p.rotateable) continue;
618     p.angle += dangle + 8;
619     p.angle %= 8;
620     let transform = wasm_bindgen.angle_transform(p.angle);
621     p.pelem.setAttributeNS(null,'transform',transform);
622     api_piece('rotate', piece,p, p.angle);
623   }
624   recompute_keybindings();
625   return true;
626 }
627
628 // ----- lower -----
629
630 type LowerTodoItem = {
631   piece: PieceId,
632   p: PieceInfo,
633   heavy: boolean,
634 };
635
636 type LowerTodoList = { [piece: string]: LowerTodoItem };
637
638 keyops_local['lower'] = function (uo: UoRecord) { lower_targets(uo); }
639
640 function lower_heavy(p: PieceInfo): boolean {
641   return wresting || p.pinned || p.moveable == "No";
642 }
643
644 function lower_targets(uo: UoRecord): boolean {
645   let targets_todo : LowerTodoList = Object.create(null);
646
647   for (let piece of uo.targets!) {
648     let p = pieces[piece]!;
649     let heavy = lower_heavy(p);
650     targets_todo[piece] = { p, piece, heavy, };
651   }
652   let problem = lower_pieces(targets_todo);
653   if (problem !== null) {
654     add_log_message('Cannot lower: ' + problem);
655     return false;
656   }
657   return true;
658 }
659
660 function lower_pieces(targets_todo: LowerTodoList):
661  string | null
662 {
663   // This is a bit subtle.  We don't want to lower below heavy pieces
664   // (unless we are heavy too, or the user is wresting).  But maybe
665   // the heavy pieces aren't already at the bottom.  For now we will
666   // declare that all heavy pieces "should" be below all light
667   // ones.  Not as an invariant, but as a thing we will do here to try
668   // to make a sensible result.  We implement this as follows: if we
669   // find heavy pieces above light pieces, we move those heavy
670   // pieces to the bottom too, just below us, preserving their
671   // relative order.
672   //
673   // Disregarding heavy targets:
674   //
675   // Z     <some stuff not including any light targets>
676   // Z
677   //       topmost light target           *
678   // B (
679   // B     light non-target
680   // B |   light target                   *
681   // B |   heavy non-target, mis-stacked  *
682   // B )*
683   // B
684   //       bottommost light non-target
685   //        if that is below topmost light target
686   //            <- tomove_light: insert targets from * here           Q ->
687   //            <- tomove_misstacked: insert non-targets from * here  Q ->
688   //            <- heavy non-targets with clashing Z Coords           X ->
689   // A
690   // A     heavy non-targets (nomove_heavy)
691   //            <- tomove_heavy: insert all heavy targets here        P ->
692   //
693   // When wresting, treat all targets as heavy.
694
695   type Entry = {
696     piece: PieceId,
697     p: PieceInfo,
698   };
699   // bottom of the stack order first
700   let tomove_light       : Entry[] = [];
701   let tomove_misstacked  : Entry[] = [];
702   let nomove_heavy       : Entry[] = [];
703   let tomove_heavy       : Entry[] = [];
704
705                                                     //  A      B      Z
706   let q_z_top : ZCoord | null = null;               //  null   some   some
707   let n_targets_todo_light = 0;                     //                0
708
709   let any_targets = false;
710   for (const piece of Object.keys(targets_todo)) {
711     any_targets = true;
712     let p = targets_todo[piece];
713     if (!p.heavy) n_targets_todo_light++;
714   }
715   if (!any_targets) return 'Nothing to lower!';
716
717   let walk = pieces_marker;
718   for (;;) { // starting at the bottom of the stack order
719     if (Object.keys(targets_todo).length == 0 &&
720        q_z_top !== null) {
721       // no targets left, state Z, we can stop now
722       console.log('LOWER STATE Z FINISHED');
723       break;
724     }
725
726     let new_walk = walk.nextElementSibling;
727     if (new_walk == null) {
728       console.log('LOWER WALK NO SIBLING!');
729       break;
730     }
731     walk = new_walk as SVGGraphicsElement;
732     let piece = walk.dataset.piece;
733     if (piece == null) {
734       console.log('LOWER WALK REACHED TOP');
735       break;
736     }
737
738     let p = pieces[piece]!;
739     let todo = targets_todo[piece];
740     if (todo) {
741       let xst = '';
742       if (q_z_top === null && !todo.heavy) {
743         q_z_top = p.z;
744         xst = 'STATE -> B';
745       }
746       console.log('LOWER WALK', piece, 'TODO', todo.heavy ? "H" : "_", xst);
747       delete targets_todo[piece];
748       if (!todo.heavy) n_targets_todo_light--;
749       (todo.heavy ? tomove_heavy : tomove_light).push(todo);
750       continue;
751     }
752
753     let p_heavy = lower_heavy(p);
754     if (q_z_top === null) { // state A
755       if (!p_heavy) {
756         console.log('LOWER WALK', piece, 'STATE A -> Z');
757         q_z_top = p.z;
758       } else {
759         console.log('LOWER WALK', piece, 'STATE A');
760         nomove_heavy.push({ p, piece });
761       }
762       continue;
763     }
764
765     // state B
766     if (p_heavy) {
767       console.log('LOWER WALK', piece, 'STATE B MIS-STACKED');
768       tomove_misstacked.push({ p, piece });
769     } else {
770       console.log('LOWER WALK', piece, 'STATE B');
771     }
772   }
773
774   if (q_z_top === null) {
775     // Somehow we didn't find the top of Q, so we didn't meet any
776     // targets.  (In the walk loop, we always set q_z_top if todo.)
777     q_z_top =
778       tomove_misstacked.length ? tomove_misstacked[0].p.z :
779       tomove_light     .length ? tomove_light     [0].p.z :
780                                  tomove_heavy     [0].p.z;
781   }
782
783   while (nomove_heavy.length &&
784          (tomove_light.length || tomove_misstacked.length) &&
785          nomove_heavy[nomove_heavy.length-1].p.z == q_z_top) {
786     // Yowzer.  We have to reset the Z coordinates on these heavy
787     // pieces, whose Z coordinate is the same as the stuff we are not
788     // touching, because otherwise there is no gap.
789     //
790     // Treating them as misstacked instead is sufficient, provided
791     // we put them at the front (bottom end) of the misstacked list.
792     //
793     // This is X in the chart.
794     //
795     let restack = nomove_heavy.pop()!;
796     console.log('LOWER CLASHING Z - RESTACKING', restack);
797     tomove_misstacked.unshift(restack);
798   }
799
800   type PlanEntry = {
801     content: Entry[], // bottom to top
802     z_top: ZCoord,
803     z_bot: ZCoord | null,
804   };
805
806   let plan : PlanEntry[] = [];
807
808   console.log('LOWER PARTQ X', tomove_misstacked);
809   console.log('LOWER PARTQ L', tomove_light);
810   console.log('LOWER PARTP H', tomove_heavy);
811   let partQ = tomove_misstacked.concat(tomove_light);
812   let partP = tomove_heavy;
813
814   if (nomove_heavy.length == 0) {
815     plan.push({
816       content: partP.concat(partQ),
817       z_top: q_z_top,
818       z_bot : null,
819     });
820   } else {
821     plan.push({
822       content: partQ,
823       z_top: q_z_top,
824       z_bot: nomove_heavy[nomove_heavy.length-1].p.z,
825     }, {
826       content: partP,
827       z_top: nomove_heavy[0].p.z,
828       z_bot: null,
829     });
830   }
831
832   console.log('LOWER PLAN', plan);
833
834   for (const pe of plan) {
835     for (const e of pe.content) {
836       if (e.p.held != null && e.p.held != us) {
837         return "lowering would disturb a piece held by another player";
838       }
839     }
840   }
841
842   for (const pe of plan) {
843     let z_top = pe.z_top;
844     let z_bot = pe.z_bot;
845     if (! pe.content.length) continue;
846     if (z_bot == null) {
847       let first_z = pe.content[0].p.z;
848       if (z_top >= first_z)
849         z_top = first_z;
850     }
851     let zrange = wasm_bindgen.range(z_bot, z_top, pe.content.length);
852     console.log('LOQER PLAN PE',
853                 pe, z_bot, z_top, pe.content.length, zrange.debug());
854     for (const e of pe.content) {
855       let p = e.p;
856       p.held_us_raising = "Lowered";
857       piece_set_zlevel(e.piece, p, (oldtop_piece) => {
858         let z = zrange.next();
859         p.z = z;
860         api_piece("setz", e.piece, e.p, { z });
861       });
862     }
863   }
864   return null;
865 }
866
867 keyops_local['wrest'] = function (uo: UoRecord) {
868   wresting = !wresting;
869   document.getElementById('wresting-warning')!.innerHTML = !wresting ? "" :
870     " <strong>(wresting mode!)</strong>";
871   ungrab_all();
872   mousecursor_etc_reupdate();
873 }
874
875 keyops_local['motion-hint-history'] = function (uo: UoRecord) {
876   movehist_len_i ++;
877   movehist_len_i %= movehist_lens.length;
878   movehist_revisible();
879 }
880
881 keyops_local['pin'  ] = function (uo) {
882   if (!lower_targets(uo)) return;
883   pin_unpin(uo, true);
884 }
885 keyops_local['unpin'] = function (uo) {
886   pin_unpin(uo, false);
887 }
888
889 function pin_unpin(uo: UoRecord, newpin: boolean) {
890   for (let piece of uo.targets!) {
891     let p = pieces[piece]!;
892     p.pinned = newpin;
893     api_piece('pin', piece,p, newpin);
894     redisplay_ancillaries(piece,p);
895   }
896   recompute_keybindings();
897 }
898
899 // ----- raising -----
900
901 keyops_local['raise'] = function (uo: UoRecord) { raise_targets(uo); }
902
903 function raise_targets(uo: UoRecord) {
904   let any = false;
905   for (let piece of uo.targets!) {
906     let p = pieces[piece]!;
907     if (p.pinned || !piece_moveable(p)) continue;
908     any = true;
909     piece_raise(piece, p, "NotYet");
910   }
911   if (!any) { 
912     add_log_message('No pieces could be raised.');
913   }
914 }
915
916 function piece_raise(piece: PieceId, p: PieceInfo,
917                      new_held_us_raising: HeldUsRaising,
918   implement: (piece: PieceId, p: PieceInfo, z: ZCoord) => void
919   = function(piece: PieceId, p: PieceInfo, z: ZCoord) {
920     api_piece("setz", piece,p, { z: z });
921   })
922 {
923   p.held_us_raising = new_held_us_raising;
924   piece_set_zlevel(piece,p, (oldtop_piece) => {
925     let oldtop_p = pieces[oldtop_piece]!;
926     let z = wasm_bindgen.increment(oldtop_p.z);
927     p.z = z;
928     implement(piece,p,z);
929   });
930 }
931
932 // ----- clicking/dragging pieces -----
933
934 type DragInfo = {
935   piece : PieceId,
936   dox : number,
937   doy : number,
938 }
939
940 enum DRAGGING { // bitmask
941   NO           = 0x00,
942   MAYBE_GRAB   = 0x01,
943   MAYBE_UNGRAB = 0x02,
944   YES          = 0x04,
945   RAISED       = 0x08,
946 };
947
948 var drag_pieces : DragInfo[] = [];
949 var dragging = DRAGGING.NO;
950 var dcx : number | null;
951 var dcy : number | null;
952
953 const DRAGTHRESH = 5;
954
955 let rectsel_start: Pos | null;
956 let rectsel_shifted: boolean | null;
957 const RECTSELTHRESH = 5;
958
959 function piece_xy(p: PieceInfo): Pos {
960   return [ parseFloat(p.uelem.getAttributeNS(null,"x")!),
961            parseFloat(p.uelem.getAttributeNS(null,"y")!) ];
962 }
963
964 function drag_start_prepare(new_dragging: DRAGGING) {
965   dragging = new_dragging;
966
967   let spos_map = Object.create(null);
968   for (let piece of Object.keys(pieces)) {
969     let p = pieces[piece]!;
970     if (p.held != us) continue;
971     let spos = piece_xy(p);
972     let sposk = `${spos[0]} ${spos[1]}`;
973     if (spos_map[sposk] === undefined) spos_map[sposk] = [spos, []];
974     spos_map[sposk][1].push([spos, piece,p]);
975   }
976
977   for (let sposk of Object.keys(spos_map)) {
978     let [[dox, doy], ents] = spos_map[sposk];
979     for (let i=0; i<ents.length; i++) {
980       let [p, piece] = ents[i];
981       let delta = (-(ents.length-1)/2 + i) * SPECIAL_MULTI_DELTA_EACH;
982       p.drag_delta = Math.min(Math.max(delta, -SPECIAL_MULTI_DELTA_MAX),
983                                               +SPECIAL_MULTI_DELTA_MAX);
984       drag_pieces.push({
985         piece: piece,
986         dox: dox + p.drag_delta,
987         doy: doy,
988       });
989     }
990   }
991 }
992
993 function some_mousedown(e : MouseEvent) {
994   console.log('mousedown', e, e.clientX, e.clientY, e.target);
995
996   if (e.button != 0) { return }
997   if (e.altKey) { return }
998   if (e.metaKey) { return }
999   if (e.ctrlKey) {
1000     return;
1001   } else {
1002     drag_mousedown(e, e.shiftKey);
1003   }
1004 }
1005
1006 type MouseFindClicked = null | {
1007   clicked: PieceId[],
1008   held: PlayerId | null,
1009   pinned: boolean,
1010   multigrab?: number,
1011 };
1012
1013 type PieceSet = { [piece: string]: true };
1014
1015 function grab_clicked(clicked: PieceId[], loose: boolean,
1016                       multigrab: number | undefined) {
1017   for (let piece of clicked) {
1018     let p = pieces[piece]!;
1019     set_grab_us(piece,p);
1020     if (multigrab === undefined) {
1021       api_piece_x(api_immediate, loose,
1022                   wresting ? 'wrest' : 'grab', piece,p, { });
1023     } else {
1024       piece_raise(piece,p, 'Raised', function(piece,p,z) {
1025         api_piece_x(api_immediate, loose, 'multigrab',
1026                     piece,p, { n: multigrab, z: z });
1027       })
1028     }
1029   }
1030 }
1031 function ungrab_clicked(clicked: PieceId[]) {
1032   let todo: [PieceId, PieceInfo][] = [];
1033   for (let tpiece of clicked) {
1034     let tp = pieces[tpiece]!;
1035     todo.push([tpiece, tp]);
1036   }
1037   do_ungrab_n(todo);
1038 }
1039
1040 function mouse_clicked_one(piece: PieceId, p: PieceInfo): MouseFindClicked {
1041   let held = p.held;
1042   let pinned = p.pinned;
1043   return { clicked: [piece], held, pinned };
1044 }
1045
1046 function mouse_find_predicate(
1047   wanted: number | null,
1048   allow_for_deselect: boolean,
1049   note_already: PieceSet | null,
1050   predicate: (p: PieceInfo) => boolean
1051 ): MouseFindClicked {
1052   let clicked: PieceId[];
1053   let held: string | null;
1054   let pinned = false;
1055   let already_count = 0;
1056
1057   clicked = [];
1058   let uelem = defs_marker;
1059   while (wanted == null || (clicked.length + already_count) < wanted) {
1060     let i = clicked.length;
1061     uelem = uelem.previousElementSibling as any;
1062     if (uelem == pieces_marker) {
1063       if (wanted != null) {
1064         add_log_message(`Not enough pieces!  Stopped after ${i}.`);
1065         return null;
1066       }
1067       break;
1068     }
1069     let piece = uelem.dataset.piece!;
1070
1071     function is_already() {
1072       if (note_already != null) {
1073         already_count++;
1074         note_already[piece] = true;
1075       }
1076     }
1077
1078     let p = pieces[piece];
1079     if (p.pinned && !wresting) continue;
1080     if (p.held && p.held != us && !wresting) continue;
1081     if (i > 0 && !piece_moveable(p))
1082       continue;
1083     if (!predicate(p)) {
1084       continue;
1085     }
1086     if (p.pinned) pinned = true;
1087
1088     if (i == 0) {
1089       held = p.held;
1090       if (held == us && !allow_for_deselect) held = null;
1091     }
1092     if (held! == us) {
1093       // user is going to be deselecting
1094       if (p.held != us) {
1095         // skip ones we don't have
1096         is_already();
1097         continue;
1098       }
1099     } else { // user is going to be selecting
1100       if (p.held == us) {
1101         is_already();
1102         continue; // skip ones we have already
1103       } else if (p.held == null) {
1104       } else {
1105         held = p.held; // wrestish
1106       }
1107     }
1108     clicked.push(piece);
1109   }
1110   if (clicked.length == 0) return null;
1111   else return { clicked, held: held!, pinned: pinned! };
1112 }
1113
1114 function mouse_find_lowest(e: MouseEvent) {
1115   let clickpos = mouseevent_pos(e);
1116   let uelem = pieces_marker;
1117   for (;;) {
1118     uelem = uelem.nextElementSibling as any;
1119     if (uelem == defs_marker) break;
1120     let piece = uelem.dataset.piece!;
1121     let p = pieces[piece]!;
1122     if (p_bbox_contains(p, clickpos)) {
1123       return mouse_clicked_one(piece, p);
1124     }
1125   }
1126   return null;
1127 }
1128
1129 function mouse_find_clicked(e: MouseEvent,
1130                             target: SVGGraphicsElement, piece: PieceId,
1131                             count_allow_for_deselect: boolean,
1132                             note_already: PieceSet | null,
1133                             ): MouseFindClicked
1134 {
1135   let p = pieces[piece]!;
1136   if (special_count == null) {
1137     return mouse_clicked_one(piece, p);
1138   } else if (special_count == 0) {
1139     return mouse_find_lowest(e);
1140   } else { // special_count > 0
1141     if (p.multigrab && !wresting) {
1142       let clicked = mouse_clicked_one(piece, p);
1143       if (clicked) clicked.multigrab = special_count;
1144       return clicked;
1145     } else {
1146       if (special_count > 99) {
1147         add_log_message(
1148           `Refusing to try to select ${special_count} pieces (max is 99)`);
1149         return null;
1150       }
1151       let clickpos = mouseevent_pos(e);
1152       return mouse_find_predicate(
1153         special_count, count_allow_for_deselect, note_already,
1154         function(p) { return p_bbox_contains(p, clickpos); }
1155       )
1156     }
1157   }
1158 }
1159
1160 function drag_mousedown(e : MouseEvent, shifted: boolean) {
1161   let target = e.target as SVGGraphicsElement; // we check this just now!
1162   let piece: PieceId | undefined = target.dataset.piece;
1163
1164   if (!piece) {
1165     rectsel_start = mouseevent_pos(e);
1166     rectsel_shifted = shifted;
1167     window.addEventListener('mousemove', rectsel_mousemove, true);
1168     window.addEventListener('mouseup',   rectsel_mouseup,   true);
1169     return;
1170   }
1171
1172   let note_already = shifted ? null : Object.create(null);
1173
1174   let c = mouse_find_clicked(e, target, piece, false, note_already);
1175   if (c == null) return;
1176   let clicked = c.clicked;
1177   let held = c.held;
1178   let pinned = c.pinned;
1179   let multigrab = c.multigrab;
1180
1181   special_count = null;
1182   mousecursor_etc_reupdate();
1183   drag_cancel();
1184
1185   drag_pieces = [];
1186   if (held == us) {
1187     if (shifted) {
1188       ungrab_clicked(clicked);
1189       return;
1190     }
1191     drag_start_prepare(DRAGGING.MAYBE_UNGRAB);
1192   } else if (held == null || wresting) {
1193     if (!shifted) {
1194       ungrab_all_except(note_already);
1195     }
1196     if (pinned && !wresting) {
1197       let p = pieces[c.clicked[0]!]!;
1198       add_log_message('That piece ('+p.desc+') is pinned to the table.');
1199       return;
1200     }
1201     grab_clicked(clicked, !wresting, multigrab);
1202     drag_start_prepare(DRAGGING.MAYBE_GRAB);
1203   } else {
1204     add_log_message('That piece is held by another player.');
1205     return;
1206   }
1207   dcx = e.clientX;
1208   dcy = e.clientY;
1209
1210   window.addEventListener('mousemove', drag_mousemove, true);
1211   window.addEventListener('mouseup',   drag_mouseup,   true);
1212 }
1213
1214 function mouseevent_pos(e: MouseEvent): Pos {
1215   let ctm = space.getScreenCTM()!;
1216   let px = (e.clientX - ctm.e)/(ctm.a * firefox_bug_zoom_factor_compensation);
1217   let py = (e.clientY - ctm.f)/(ctm.d * firefox_bug_zoom_factor_compensation);
1218   let pos: Pos = [px, py];
1219   console.log('mouseevent_pos', pos);
1220   return pos;
1221 }
1222
1223 function p_bbox_contains(p: PieceInfo, test: Pos) {
1224   let ctr = piece_xy(p);
1225   for (let i of [0,1]) {
1226     let offset = test[i] - ctr[i];
1227     if (offset < p.bbox[0][i] || offset > p.bbox[1][i])
1228       return false;
1229   }
1230   return true;
1231 }
1232
1233 function do_ungrab_n(todo: [PieceId, PieceInfo][]) {
1234   function sort_with(a: [PieceId, PieceInfo],
1235                      b: [PieceId, PieceInfo]): number {
1236     return piece_z_cmp(a[1], b[1]);
1237   }
1238   todo.sort(sort_with);
1239   for (let [tpiece, tp] of todo) {
1240     do_ungrab_1(tpiece, tp);
1241   }
1242 }
1243 function ungrab_all_except(dont: PieceSet | null) {
1244   let todo: [PieceId, PieceInfo][] =  [];
1245   for (let tpiece of Object.keys(pieces)) {
1246     if (dont && dont[tpiece]) continue;
1247     let tp = pieces[tpiece]!;
1248     if (tp.held == us) {
1249       todo.push([tpiece, tp]);
1250     }
1251   }
1252   do_ungrab_n(todo);
1253 }
1254 function ungrab_all() {
1255   ungrab_all_except(null);
1256 }
1257
1258 function set_grab_us(piece: PieceId, p: PieceInfo) {
1259   p.held = us;
1260   p.held_us_raising = "NotYet";
1261   p.drag_delta = 0;
1262   redisplay_ancillaries(piece,p);
1263   recompute_keybindings();
1264 }
1265 function do_ungrab_1(piece: PieceId, p: PieceInfo) {
1266   let autoraise = p.held_us_raising == "Raised";
1267   p.held = null;
1268   p.held_us_raising = "NotYet";
1269   p.drag_delta = 0;
1270   redisplay_ancillaries(piece,p);
1271   recompute_keybindings();
1272   api_piece('ungrab', piece,p, { autoraise });
1273 }
1274
1275 function clear_halo(piece: PieceId, p: PieceInfo) {
1276   let was = p.last_seen_moved;
1277   p.last_seen_moved = null;
1278   if (was) redisplay_ancillaries(piece,p);
1279 }
1280
1281 function ancillary_node(piece: PieceId, stroke: string): SVGGraphicsElement {
1282   var nelem = document.createElementNS(svg_ns,'use');
1283   nelem.setAttributeNS(null,'href','#surround'+piece);
1284   nelem.setAttributeNS(null,'stroke',stroke);
1285   nelem.setAttributeNS(null,'fill','none');
1286   return nelem as any;
1287 }
1288
1289 function redisplay_ancillaries(piece: PieceId, p: PieceInfo) {
1290   let href = '#surround'+piece;
1291   console.log('REDISPLAY ANCILLARIES',href);
1292
1293   for (let celem = p.pelem.firstElementChild;
1294        celem != null;
1295        celem = nextelem) {
1296     var nextelem = celem.nextElementSibling
1297     let thref = celem.getAttributeNS(null,"href");
1298     if (thref == href) {
1299       celem.remove();
1300     }
1301   }
1302
1303   let halo_colour = null;
1304   if (p.cseq_updatesvg != null) {
1305     halo_colour = 'purple';
1306   } else if (p.last_seen_moved != null) {
1307     halo_colour = 'yellow';
1308   } else if (p.held != null && p.pinned) {
1309     halo_colour = '#8cf';
1310   }
1311   if (halo_colour != null) {
1312     let nelem = ancillary_node(piece, halo_colour);
1313     if (p.held != null) {
1314       // value 2ps is also in src/pieces.rs SELECT_STROKE_WIDTH
1315       nelem.setAttributeNS(null,'stroke-width','2px');
1316     }
1317     p.pelem.prepend(nelem);
1318   } 
1319   if (p.held != null) {
1320     let da = null;
1321     if (p.held != us) {
1322       da = players[p.held!]!.dasharray;
1323     } else {
1324       let [px, py] = piece_xy(p);
1325       let inoccult = occregions.contains_pos(px, py);
1326       p.held_us_inoccult = inoccult;
1327       if (inoccult) {
1328         da = "0.9 0.6"; // dotted dasharray
1329       }
1330     }
1331     let nelem = ancillary_node(piece, held_surround_colour);
1332     if (da !== null) {
1333       nelem.setAttributeNS(null,'stroke-dasharray',da);
1334     }
1335     p.pelem.appendChild(nelem);
1336   }
1337 }
1338
1339 function drag_mousemove(e: MouseEvent) {
1340   var ctm = space.getScreenCTM()!;
1341   var ddx = (e.clientX - dcx!)/(ctm.a * firefox_bug_zoom_factor_compensation);
1342   var ddy = (e.clientY - dcy!)/(ctm.d * firefox_bug_zoom_factor_compensation);
1343   var ddr2 = ddx*ddx + ddy*ddy;
1344   if (!(dragging & DRAGGING.YES)) {
1345     if (ddr2 > DRAGTHRESH) {
1346       for (let dp of drag_pieces) {
1347         let tpiece = dp.piece;
1348         let tp = pieces[tpiece]!;
1349         if (tp.moveable == "Yes") {
1350           continue;
1351         } else if (tp.moveable == "IfWresting") {
1352           if (wresting) continue;
1353           add_log_message('That piece can only be moved when Wresting.');
1354         } else {
1355           add_log_message('That piece cannot be moved at the moment.');
1356         }
1357         return ddr2;
1358       }
1359       dragging |= DRAGGING.YES;
1360     }
1361   }
1362   //console.log('mousemove', ddx, ddy, dragging);
1363   if (dragging & DRAGGING.YES) {
1364     console.log('DRAG PIECES',drag_pieces);
1365     for (let dp of drag_pieces) {
1366       console.log('DRAG PIECES PIECE',dp);
1367       let tpiece = dp.piece;
1368       let tp = pieces[tpiece]!;
1369       var x = Math.round(dp.dox + ddx);
1370       var y = Math.round(dp.doy + ddy);
1371       let need_redisplay_ancillaries = (
1372         tp.held == us &&
1373         occregions.contains_pos(x,y) != tp.held_us_inoccult
1374       );
1375       piece_set_pos_core(tp, x, y);
1376       tp.queued_moves++;
1377       api_piece_x(api_delay, false, 'm', tpiece,tp, [x, y] );
1378       if (need_redisplay_ancillaries) redisplay_ancillaries(tpiece, tp);
1379     }
1380     if (!(dragging & DRAGGING.RAISED)) {
1381       sort_drag_pieces();
1382       for (let dp of drag_pieces) {
1383         let piece = dp.piece;
1384         let p = pieces[piece]!;
1385         if (p.held_us_raising == "Lowered") continue;
1386         let dragraise = +p.pelem.dataset.dragraise!;
1387         if (dragraise > 0 && ddr2 >= dragraise*dragraise) {
1388           dragging |= DRAGGING.RAISED;
1389           console.log('CHECK RAISE ', dragraise, dragraise*dragraise, ddr2);
1390           piece_raise(piece,p,"Raised");
1391         }
1392       }
1393     }
1394   }
1395   return ddr2;
1396 }
1397 function sort_drag_pieces() {
1398   function sort_with(a: DragInfo, b: DragInfo): number {
1399     return pieceid_z_cmp(a.piece,
1400                          b.piece);
1401   }
1402   drag_pieces.sort(sort_with);
1403 }
1404
1405 function drag_mouseup(e: MouseEvent) {
1406   console.log('mouseup', dragging);
1407   let ddr2 : number = drag_mousemove(e);
1408   drag_end();
1409 }
1410
1411 function drag_end() {
1412   if (dragging == DRAGGING.MAYBE_UNGRAB ||
1413       (dragging & ~DRAGGING.RAISED) == (DRAGGING.MAYBE_GRAB | DRAGGING.YES)) {
1414     sort_drag_pieces();
1415     for (let dp of drag_pieces) {
1416       let piece = dp.piece;
1417       let p = pieces[piece]!;
1418       do_ungrab_1(piece,p);
1419     }
1420   }
1421   drag_cancel();
1422 }
1423
1424 function drag_cancel() {
1425   window.removeEventListener('mousemove', drag_mousemove, true);
1426   window.removeEventListener('mouseup',   drag_mouseup,   true);
1427   dragging = DRAGGING.NO;
1428   drag_pieces = [];
1429 }
1430
1431 function rectsel_nontrivial_pos2(e: MouseEvent): Pos | null {
1432   let pos2 = mouseevent_pos(e);
1433   let d2 = 0;
1434   for (let i of [0,1]) {
1435     let d = pos2[i] - rectsel_start![i];
1436     d2 += d*d;
1437   }
1438   return d2 > RECTSELTHRESH*RECTSELTHRESH ? pos2 : null;
1439 }
1440
1441 function rectsel_mousemove(e: MouseEvent) {
1442   let pos2 = rectsel_nontrivial_pos2(e);
1443   let path;
1444   if (pos2 == null) {
1445     path = "";
1446   } else {
1447     let pos1 = rectsel_start!;
1448     path = `M ${ pos1 [0]} ${ pos1 [1] }
1449               ${ pos2 [0]} ${ pos1 [1] }
1450             M ${ pos1 [0]} ${ pos2 [1] }
1451               ${ pos2 [0]} ${ pos2 [1] }
1452             M ${ pos1 [0]} ${ pos1 [1] }
1453               ${ pos1 [0]} ${ pos2 [1] }
1454             M ${ pos2 [0]} ${ pos1 [1] }
1455               ${ pos2 [0]} ${ pos2 [1] }`;
1456   }
1457   rectsel_path.firstElementChild!.setAttributeNS(null,'d',path);
1458 }
1459
1460 function rectsel_mouseup(e: MouseEvent) {
1461   console.log('rectsel mouseup');
1462   window.removeEventListener('mousemove', rectsel_mousemove, true);
1463   window.removeEventListener('mouseup',   rectsel_mouseup,   true);
1464   rectsel_path.firstElementChild!.setAttributeNS(null,'d','');
1465   let pos2 = rectsel_nontrivial_pos2(e);
1466
1467   if (pos2 == null) {
1468     // clicked not on a piece, and didn't drag
1469     special_count = null;
1470     mousecursor_etc_reupdate();
1471     // we'll bail in a moment, after possibly unselecting things
1472   }
1473
1474   let note_already = Object.create(null);
1475   let c = null;
1476
1477   if (pos2 != null) {
1478     if (special_count != null && special_count == 0) {
1479       add_log_message(`Cannot drag-select lowest.`);
1480       return;
1481     }
1482     let tl = [0,0];
1483     let br = [0,0];
1484     for (let i of [0,1]) {
1485       tl[i] = Math.min(rectsel_start![i], pos2[i]);
1486       br[i] = Math.max(rectsel_start![i], pos2[i]);
1487     }
1488     c = mouse_find_predicate(
1489       special_count, rectsel_shifted!, note_already,
1490       function(p: PieceInfo) {
1491         let pp = piece_xy(p);
1492         for (let i of [0,1]) {
1493           if (pp[i] < tl[i] || pp[i] > br[i]) return false;
1494         }
1495         return true;
1496       }
1497     );
1498   }
1499
1500   if (!c) {
1501     // clicked not on a piece, didn't end up selecting anything
1502     // either because drag region had nothing in it, or special
1503     // failed, or some such.
1504     if (!rectsel_shifted) {
1505       let mr;
1506       while (mr = movements.pop()) {
1507         mr.p.last_seen_moved = null;
1508         redisplay_ancillaries(mr.piece, mr.p);
1509       }
1510       ungrab_all();
1511     }
1512     return;
1513   }
1514
1515   // did the special
1516   special_count = null;
1517   mousecursor_etc_reupdate();
1518
1519   if (rectsel_shifted && c.held == us) {
1520     ungrab_clicked(c.clicked);
1521     return;
1522   } else {
1523     if (!rectsel_shifted) {
1524       ungrab_all_except(note_already);
1525     }
1526     grab_clicked(c.clicked, false, undefined);
1527   }
1528 }
1529
1530 // ----- general -----
1531
1532 type PlayersUpdate = { new_info_pane: string };
1533
1534 messages.SetPlayer = <MessageHandler>function
1535 (j: { player: string, data: PlayerInfo } & PlayersUpdate) {
1536   players[j.player] = j.data;
1537   player_info_pane_set(j);
1538 }
1539
1540 messages.RemovePlayer = <MessageHandler>function
1541 (j: { player: string } & PlayersUpdate ) {
1542   delete players[j.player];
1543   player_info_pane_set(j);
1544 }
1545
1546 function player_info_pane_set(j: PlayersUpdate) {
1547   document.getElementById('player_list')!
1548     .innerHTML = j.new_info_pane;
1549 }
1550
1551 messages.UpdateBundles = <MessageHandler>function
1552 (j: { new_info_pane: string }) {
1553   document.getElementById('bundle_list')!
1554     .innerHTML = j.new_info_pane;
1555 }
1556
1557 messages.SetTableSize = <MessageHandler>function
1558 ([x, y]: [number, number]) {
1559   function set_attrs(elem: Element, l: [string,string][]) {
1560     for (let a of l) {
1561       elem.setAttributeNS(null,a[0],a[1]);
1562     }
1563   }
1564   let rect = document.getElementById('table_rect')!;
1565   set_attrs(space, wasm_bindgen.space_table_attrs(x, y));
1566   set_attrs(rect,  wasm_bindgen.space_table_attrs(x, y));
1567 }
1568
1569 messages.SetTableColour = <MessageHandler>function
1570 (c: string) {
1571   let rect = document.getElementById('table_rect')!;
1572   rect.setAttributeNS(null, 'fill', c);
1573 }
1574
1575 messages.SetLinks = <MessageHandler>function
1576 (msg: string) {
1577   if (msg.length != 0 && layout == 'Portrait') {
1578     msg += " |";
1579   }
1580   links_elem.innerHTML = msg
1581 }
1582
1583 // ---------- movehist ----------
1584
1585 type MoveHistEnt = {
1586   held: PlayerId,
1587   posx: [MoveHistPosx, MoveHistPosx],
1588   diff: { 'Moved': { d: number } },
1589 }
1590 type MoveHistPosx = {
1591   pos: Pos,
1592   angle: CompassAngle,
1593   facehint: FaceId | null,
1594 }
1595
1596 messages.MoveHistEnt = <MessageHandler>movehist_record;
1597 messages.MoveHistClear = <MessageHandler>function() {
1598   movehist_revisible_custmax(0);
1599 }
1600
1601 function movehist_record(ent: MoveHistEnt) {
1602   let old_pos = ent.posx[0].pos;
1603   let new_pos = ent.posx[1].pos;
1604
1605   movehist_gen++;
1606   movehist_gen %= (movehist_len_max * 2);
1607   let meid = 'motionhint-marker-' + movehist_gen;
1608
1609   let moved = ent.diff['Moved'];
1610   if (moved) {
1611     let d = moved.d;
1612     let ends = [];
1613     for (let end of [0,1]) {
1614       let s = (!end ? MOVEHIST_ENDS : d - MOVEHIST_ENDS) / d;
1615       ends.push([ (1-s) * old_pos[0] + s * new_pos[0],
1616                   (1-s) * old_pos[1] + s * new_pos[1] ]);
1617     }
1618     let g = document.createElementNS(svg_ns,'g');
1619     let sz = 4;
1620     let pi = players[ent.held];
1621     let nick = pi ? pi.nick : '';
1622     // todo: would be nice to place text variously along arrow, rotated
1623     let svg = `
1624       <marker id="${meid}" viewBox="2 0 ${sz} ${sz}" 
1625         refX="${sz}" refY="${sz/2}"
1626         markerWidth="${sz + 2}" markerHeight="${sz}"
1627         stroke="yellow" fill="none"
1628         orient="auto-start-reverse" stroke-linejoin="miter">
1629         <path d="M 0 0 L ${sz} ${sz/2} L 0 ${sz}" />
1630       </marker>
1631       <line x1="${ends[0][0].toString()}"
1632             y1="${ends[0][1].toString()}"
1633             x2="${ends[1][0].toString()}"
1634             y2="${ends[1][1].toString()}"
1635             stroke="yellow"
1636             stroke-width="1" pointer-events="none"
1637             marker-end="url(#${meid})" />
1638       <text x="${((ends[0][0] + ends[1][0]) / 2).toString()}"
1639             y="${((ends[0][1] + ends[1][1]) / 2).toString()}"
1640             font-size="5" pointer-events="none"
1641             stroke-width="0.1">${nick}</text>
1642     `;
1643     g.innerHTML = svg;
1644     space.insertBefore(g, movehist_end);
1645     movehist_revisible();
1646   }
1647 }
1648
1649 function movehist_revisible() { 
1650   movehist_revisible_custmax(movehist_len_max);
1651 }
1652
1653 function movehist_revisible_custmax(len_max: number) {
1654   let n = movehist_lens[movehist_len_i];
1655   let i = 0;
1656   let node = movehist_end;
1657   while (i < len_max) {
1658     i++; // i now eg 1..10
1659     node = node.previousElementSibling! as SVGGraphicsElement;
1660     if (node == movehist_start)
1661       return;
1662     let prop = i > n ? 0 : (n-i+1)/n;
1663     let stroke = (prop * 1.0).toString();
1664     let marker = node.firstElementChild!;
1665     marker.setAttributeNS(null,'stroke-width',stroke);
1666     let line = marker.nextElementSibling!;
1667     line.setAttributeNS(null,'stroke-width',stroke);
1668     let text = line.nextElementSibling!;
1669     if (!prop) {
1670       text.setAttributeNS(null,'stroke','none');
1671       text.setAttributeNS(null,'fill','none');
1672     } else {
1673       text.setAttributeNS(null,'fill','yellow');
1674       text.setAttributeNS(null,'stroke','orange');
1675     }
1676   }
1677   for (;;) {
1678     let del = node.previousElementSibling!;
1679     if (del == movehist_start)
1680       return;
1681     del.remove();
1682   }
1683 }  
1684
1685 // ----- logs -----
1686
1687 messages.Log = <MessageHandler>function
1688 (j: { when: string, logent: { html: string } }) {
1689   add_timestamped_log_message(j.when, j.logent.html);
1690 }
1691
1692 function add_log_message(msg_html: string) {
1693   add_timestamped_log_message('', msg_html);
1694 }
1695
1696 function add_timestamped_log_message(ts_html: string, msg_html: string) {
1697   var lastent = log_elem.lastElementChild;
1698   var in_scrollback =
1699     lastent == null ||
1700     // inspired by
1701     //   https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling/21627295#21627295
1702     // rejected
1703       //   https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
1704       (() => {
1705         let le_top = lastent.getBoundingClientRect()!.top;
1706         let le_bot = lastent.getBoundingClientRect()!.bottom;
1707         let ld_bot = logscroll_elem.getBoundingClientRect()!.bottom;
1708         console.log("ADD_LOG_MESSAGE bboxes: le t b, bb",
1709                     le_top, le_bot, ld_bot);
1710         return 0.5 * (le_bot + le_top) > ld_bot;
1711       })();
1712
1713   console.log('ADD LOG MESSAGE ',in_scrollback, layout, msg_html);
1714
1715   var ne : HTMLElement;
1716
1717   function add_thing(elemname: string, cl: string, html: string) {
1718     var ie = document.createElement(elemname);
1719     ie.innerHTML = html;
1720     ie.setAttribute("class", cl);
1721     ne.appendChild(ie);
1722   }
1723
1724   if (layout == 'Portrait') {
1725     ne = document.createElement('tr');
1726     add_thing('td', 'logmsg', msg_html);
1727     add_thing('td', 'logts',  ts_html);
1728   } else if (layout == 'Landscape') {
1729     ts_html = last_log_ts.update(ts_html);
1730     ne = document.createElement('div');
1731     add_thing('span', 'logts',  ts_html);
1732     ne.appendChild(document.createElement('br'));
1733     add_thing('span', 'logmsg', msg_html);
1734     ne.appendChild(document.createElement('br'));
1735   } else {
1736     throw 'bad layout ' + layout;
1737   }
1738   log_elem.appendChild(ne);
1739
1740   if (!in_scrollback) {
1741     logscroll_elem.scrollTop = logscroll_elem.scrollHeight;
1742   }
1743 }
1744
1745 // ----- zoom -----
1746
1747 function zoom_pct (): number | undefined {
1748   let str = zoom_val.value;
1749   let val = parseFloat(str);
1750   if (isNaN(val)) {
1751     return undefined;
1752   } else {
1753     return val;
1754   }
1755 }
1756
1757 function zoom_enable() {
1758   zoom_btn.disabled = (zoom_pct() === undefined);
1759 }
1760
1761 function zoom_activate() {
1762   let pct = zoom_pct();
1763   if (pct !== undefined) {
1764     let fact = pct * 0.01;
1765     let last_ctm_a = space.getScreenCTM()!.a;
1766     (document.getElementsByTagName('body')[0] as HTMLElement)
1767       .style.transform = 'scale('+fact+','+fact+')';
1768     if (fact != last_zoom_factor) {
1769       if (last_ctm_a == space.getScreenCTM()!.a) {
1770         console.log('FIREFOX GETSCREENCTM BUG');
1771         firefox_bug_zoom_factor_compensation = fact;
1772       } else {
1773         console.log('No firefox getscreenctm bug');
1774         firefox_bug_zoom_factor_compensation = 1.0;
1775       }
1776       last_zoom_factor = fact;
1777     }
1778   }
1779   zoom_btn.disabled = true;
1780 }
1781
1782 // ----- test counter, startup -----
1783
1784 type TransmitUpdateEntry_Piece = {
1785   piece: PieceId,
1786   op: Object,
1787 };
1788 type ErrorTransmitUpdateEntry_Piece = TransmitUpdateEntry_Piece & {
1789   cseq: ClientSeq | null,
1790 };
1791
1792 function handle_piece_update(j: TransmitUpdateEntry_Piece) {
1793   console.log('PIECE UPDATE ',j)
1794   var piece = j.piece;
1795   var m = j.op as { [k: string]: Object };
1796   var k = Object.keys(m)[0];
1797   let p = pieces[piece];
1798   pieceops[k](piece,p, m[k]);
1799 };
1800
1801 messages.Piece = <MessageHandler>handle_piece_update;
1802
1803 type PreparedPieceState = {
1804   pos: Pos,
1805   svg: string,
1806   desc: string,
1807   held: PlayerId | null,
1808   z: ZCoord,
1809   zg: Generation,
1810   pinned: boolean,
1811   angle: number,
1812   uos: UoDescription[],
1813   moveable: PieceMoveable,
1814   rotateable: boolean,
1815   multigrab: boolean,
1816   occregion: string | null,
1817   bbox: Rect,
1818 }
1819
1820 pieceops.ModifyQuiet = <PieceHandler>function
1821 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1822   console.log('PIECE UPDATE MODIFY QUIET ',piece,info)
1823   piece_modify(piece, p, info);
1824 }
1825
1826 pieceops.Modify = <PieceHandler>function
1827 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1828   console.log('PIECE UPDATE MODIFY LOuD ',piece,info)
1829   piece_note_moved(piece,p);
1830   piece_modify(piece, p, info);
1831 }
1832
1833 pieceops.InsertQuiet = <PieceHandler>(insert_piece as any);
1834 pieceops.Insert = <PieceHandler>function
1835 (piece: PieceId, xp: any, info: PreparedPieceState) {
1836   let p = insert_piece(piece,xp,info);
1837   piece_note_moved(piece,p);
1838 }
1839
1840 function insert_piece(piece: PieceId, xp: any,
1841                       info: PreparedPieceState): PieceInfo
1842 {
1843   console.log('PIECE UPDATE INSERT ',piece,info)
1844   let delem = document.createElementNS(svg_ns,'defs');
1845   delem.setAttributeNS(null,'id','defs'+piece);
1846   delem.innerHTML = info.svg;
1847   defs_marker.insertAdjacentElement('afterend', delem);
1848   let pelem = piece_element('piece',piece);
1849   let uelem = document.createElementNS(svg_ns,'use');
1850   uelem.setAttributeNS(null,'id',"use"+piece);
1851   uelem.setAttributeNS(null,'href',"#piece"+piece);
1852   uelem.setAttributeNS(null,'data-piece',piece);
1853   let p = {
1854     uelem: uelem,
1855     pelem: pelem,
1856     delem: delem,
1857   } as any as PieceInfo; // fudge this, piece_modify_core will fix it
1858   pieces[piece] = p;
1859   p.uos = info.uos;
1860   p.queued_moves = 0;
1861   piece_resolve_special(piece, p);
1862   piece_modify_core(piece, p, info);
1863   return p;
1864 }
1865
1866 pieceops.Delete = <PieceHandler>function
1867 (piece: PieceId, p: PieceInfo, info: {}) {
1868   console.log('PIECE UPDATE DELETE ', piece)
1869   piece_stop_special(piece, p);
1870   p.uelem.remove();
1871   p.delem.remove();
1872   delete pieces[piece];
1873   if (p.held == us) {
1874     recompute_keybindings();
1875   }
1876 }
1877
1878 piece_error_handlers.PosOffTable = <PieceErrorHandler>function()
1879 { return true ; }
1880 piece_error_handlers.Conflict = <PieceErrorHandler>function()
1881 { return true ; }
1882
1883 function piece_modify_image(piece: PieceId, p: PieceInfo,
1884                             info: PreparedPieceImage) {
1885   p.delem.innerHTML = info.svg;
1886   p.pelem= piece_element('piece',piece)!;
1887   p.uos = info.uos;
1888   p.bbox = info.bbox;
1889   p.desc = info.desc;
1890   piece_resolve_special(piece, p);
1891 }
1892
1893 function piece_resolve_special(piece: PieceId, p: PieceInfo) {
1894   let new_special =
1895       p.pelem.dataset.special ?
1896       JSON.parse(p.pelem.dataset.special) : null;
1897   let new_special_kind = new_special ? new_special.kind : '';
1898   let old_special_kind = p  .special ? p  .special.kind : '';
1899
1900   if (new_special_kind != old_special_kind) {
1901     piece_stop_special(piece, p);
1902   }
1903   if (new_special) {
1904     console.log('SPECIAL START', new_special);
1905     new_special.stop = function() { };
1906     p.special = new_special;
1907     special_renderings[new_special_kind](piece, p, new_special);
1908   }
1909 }
1910
1911 function piece_stop_special(piece: PieceId, p: PieceInfo) {
1912   let s = p.special;
1913   p.special = null;
1914   if (s) {
1915     console.log('SPECIAL STOP', s);
1916     s.stop(piece, p, s);
1917   }
1918 }
1919
1920 function piece_modify(piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1921   piece_modify_image(piece, p, info);
1922   piece_modify_core(piece, p, info);
1923 }
1924                        
1925 function piece_set_pos_core(p: PieceInfo, x: number, y: number) {
1926   p.uelem.setAttributeNS(null, "x", x+"");
1927   p.uelem.setAttributeNS(null, "y", y+"");
1928 }
1929
1930 function piece_modify_core(piece: PieceId, p: PieceInfo,
1931                            info: PreparedPieceState) {
1932   p.uelem.setAttributeNS(null, "x", info.pos[0]+"");
1933   p.uelem.setAttributeNS(null, "y", info.pos[1]+"");
1934   p.held = info.held;
1935   p.held_us_raising = "NotYet";
1936   p.pinned = info.pinned;
1937   p.moveable = info.moveable;
1938   p.rotateable = info.rotateable;
1939   p.multigrab = info.multigrab;
1940   p.angle = info.angle;
1941   p.bbox = info.bbox;
1942   piece_set_zlevel_from(piece,p,info);
1943   let occregions_changed = occregion_update(piece, p, info);
1944   piece_checkconflict_nrda(piece,p);
1945   redisplay_ancillaries(piece,p);
1946   if (occregions_changed) redisplay_held_ancillaries();
1947   recompute_keybindings();
1948   console.log('MODIFY DONE');
1949 }
1950 function occregion_update(piece: PieceId, p: PieceInfo,
1951                           info: PreparedPieceState) {
1952   let occregions_changed = (
1953     info.occregion != null
1954       ? occregions.insert(piece, info.occregion)
1955       : occregions.remove(piece)
1956   );
1957   return occregions_changed;
1958 }
1959 function redisplay_held_ancillaries() {
1960   for (let piece of Object.keys(pieces)) {
1961     let p = pieces[piece];
1962     if (p.held != us) continue;
1963     redisplay_ancillaries(piece,p);
1964   }
1965 }
1966
1967 type PreparedPieceImage = {
1968   svg: string,
1969   desc: string,
1970   uos: UoDescription[],
1971   bbox: Rect,
1972 }
1973
1974 type TransmitUpdateEntry_Image = {
1975   piece: PieceId,
1976   im: PreparedPieceImage,
1977 };
1978
1979 messages.Image = <MessageHandler>function(j: TransmitUpdateEntry_Image) {
1980   console.log('IMAGE UPDATE ',j)
1981   var piece = j.piece;
1982   let p = pieces[piece]!;
1983   piece_modify_image(piece, p, j.im);
1984   redisplay_ancillaries(piece,p);
1985   recompute_keybindings();
1986   console.log('IMAGE DONE');
1987 }
1988
1989 function piece_set_zlevel(piece: PieceId, p: PieceInfo,
1990                           modify : (oldtop_piece: PieceId) => void) {
1991   // Calls modify, which should set .z and/or .gz, and/or
1992   // make any necessary API call.
1993   //
1994   // Then moves uelem to the right place in the DOM.  This is done
1995   // by assuming that uelem ought to go at the end, so this is
1996   // O(new depth), which is right (since the UI for inserting
1997   // an object is itself O(new depth) UI operations to prepare.
1998
1999   let oldtop_elem = (defs_marker.previousElementSibling! as
2000                      unknown as SVGGraphicsElement);
2001   let oldtop_piece = oldtop_elem.dataset.piece!;
2002   modify(oldtop_piece);
2003
2004   let ins_before = defs_marker
2005   let earlier_elem;
2006   for (; ; ins_before = earlier_elem) {
2007     earlier_elem = (ins_before.previousElementSibling! as
2008                    unknown as SVGGraphicsElement);
2009     if (earlier_elem == pieces_marker) break;
2010     if (earlier_elem == p.uelem) continue;
2011     let earlier_p = pieces[earlier_elem.dataset.piece!]!;
2012     if (!piece_z_before(p, earlier_p)) break;
2013   }
2014   if (ins_before != p.uelem)
2015     space.insertBefore(p.uelem, ins_before);
2016
2017   check_z_order();
2018 }
2019
2020 function check_z_order() {
2021   if (!otter_debug) return;
2022   let s = pieces_marker;
2023   let last_z = "";
2024   for (;;) {
2025     s = s.nextElementSibling as SVGGraphicsElement;
2026     if (s == defs_marker) break;
2027     let piece = s.dataset.piece!;
2028     let z = pieces[piece].z;
2029     if (z < last_z) {
2030       json_report_error(['Z ORDER INCONSISTENCY!', piece, z, last_z]);
2031     }
2032     last_z = z;
2033   }
2034 }
2035
2036 function piece_note_moved(piece: PieceId, p: PieceInfo) {
2037   let now = performance.now();
2038
2039   let need_redisplay = p.last_seen_moved == null;
2040   p.last_seen_moved = now;
2041   if (need_redisplay) redisplay_ancillaries(piece,p);
2042
2043   let cutoff = now-1000.;
2044   while (movements.length > 0 && movements[0].this_motion < cutoff) {
2045     let mr = movements.shift()!;
2046     if (mr.p.last_seen_moved != null &&
2047         mr.p.last_seen_moved < cutoff) {
2048       mr.p.last_seen_moved = null;
2049       redisplay_ancillaries(mr.piece,mr.p);
2050     }
2051   }
2052
2053   movements.push({ piece: piece, p: p, this_motion: now });
2054 }
2055
2056 function piece_z_cmp(a: PieceInfo, b: PieceInfo) {
2057   if (a.z  < b.z ) return -1;
2058   if (a.z  > b.z ) return +1;
2059   if (a.zg < b.zg) return -1;
2060   if (a.zg > b.zg) return +1;
2061   return 0;
2062 }
2063
2064 function piece_z_before(a: PieceInfo, b: PieceInfo) {
2065   return piece_z_cmp(a,
2066                      b) < 0;
2067 }
2068
2069 function pieceid_z_cmp(a: PieceId, b: PieceId) {
2070   return piece_z_cmp(pieces[a]!,
2071                      pieces[b]!);
2072 }
2073
2074 pieceops.Move = <PieceHandler>function
2075 (piece,p, info: Pos ) {
2076   piece_checkconflict_nrda(piece,p);
2077   piece_note_moved(piece, p);
2078   piece_set_pos_core(p, info[0], info[1]);
2079 }
2080
2081 pieceops.MoveQuiet = <PieceHandler>function
2082 (piece,p, info: Pos ) {
2083   piece_checkconflict_nrda(piece,p);
2084   piece_set_pos_core(p, info[0], info[1]);
2085 }
2086
2087 pieceops.SetZLevel = <PieceHandler>function
2088 (piece,p, info: { z: ZCoord, zg: Generation }) {
2089   piece_note_moved(piece,p);
2090   piece_set_zlevel_from(piece,p,info);
2091 }
2092
2093 pieceops.SetZLevelQuiet = <PieceHandler>function
2094 (piece,p, info: { z: ZCoord, zg: Generation }) {
2095   piece_set_zlevel_from(piece,p,info);
2096 }
2097
2098 function piece_set_zlevel_from(piece: PieceId, p: PieceInfo,
2099                                info: { z: ZCoord, zg: Generation }) {
2100   piece_set_zlevel(piece,p, (oldtop_piece)=>{
2101     p.z  = info.z;
2102     p.zg = info.zg;
2103   });
2104 }
2105
2106 messages.Recorded = <MessageHandler>function
2107 (j: { piece: PieceId, cseq: ClientSeq,
2108       zg: Generation|null, svg: string | null, desc: string | null } ) {
2109   let piece = j.piece;
2110   let p = pieces[piece]!;
2111   piece_recorded_cseq(p, j);
2112   if (p.cseq_updatesvg != null && j.cseq >= p.cseq_updatesvg) {
2113     p.cseq_updatesvg = null;
2114     redisplay_ancillaries(piece,p);
2115   }
2116   if (j.svg != null) {
2117     p.delem.innerHTML = j.svg;
2118     p.pelem= piece_element('piece',piece)!;
2119     piece_resolve_special(piece, p);
2120     redisplay_ancillaries(piece,p);
2121   }
2122   if (j.zg != null) {
2123     var zg_new = j.zg; // type narrowing doesn't propagate :-/
2124     piece_set_zlevel(piece,p, (oldtop_piece: PieceId)=>{
2125       p.zg = zg_new;
2126     });
2127   }
2128   if (j.desc != null) {
2129     p.desc = j.desc;
2130   }
2131 }
2132
2133 function piece_recorded_cseq(p: PieceInfo, j: { cseq: ClientSeq }) {
2134   if (p.cseq_main  != null && j.cseq >= p.cseq_main ) { p.cseq_main  = null; }
2135   if (p.cseq_loose != null && j.cseq >= p.cseq_loose) { p.cseq_loose = null; }
2136 }
2137
2138 messages.RecordedUnpredictable = <MessageHandler>function
2139 (j: { piece: PieceId, cseq: ClientSeq, ns: PreparedPieceState } ) {
2140   let piece = j.piece;
2141   let p = pieces[piece]!;
2142   piece_recorded_cseq(p, j);
2143   piece_modify(piece, p, j.ns);
2144 }
2145
2146 messages.Error = <MessageHandler>function
2147 (m: any) {
2148   console.log('ERROR UPDATE ', m);
2149   var k = Object.keys(m)[0];
2150   update_error_handlers[k](m[k]);
2151 }
2152
2153 type PieceOpError = {
2154   error: string,
2155   error_msg: string,
2156   state: ErrorTransmitUpdateEntry_Piece,
2157 };
2158
2159 update_error_handlers.PieceOpError = <MessageHandler>function
2160 (m: PieceOpError) {
2161   let piece = m.state.piece;
2162   let cseq = m.state.cseq;
2163   let p = pieces[piece];
2164   console.log('ERROR UPDATE PIECE ', piece, cseq, m, m.error_msg, p);
2165   if (p == null) return; // who can say!
2166   if (m.error != 'Conflict') {
2167     // Our gen was high enough we we sent this, that it ought to have
2168     // worked.  Report it as a problem, then.
2169     add_log_message('Problem manipulating piece: ' + m.error_msg);
2170     // Mark aus as having no outstanding requests, and cancel any drag.
2171     piece_checkconflict_nrda(piece, p, true);
2172   }
2173   handle_piece_update(m.state);
2174 }
2175
2176 function piece_checkconflict_nrda(piece: PieceId, p: PieceInfo,
2177                                   already_logged: boolean = false) {
2178   // Our state machine for cseq:
2179   //
2180   // When we send an update (api_piece_x) we always set cseq.  If the
2181   // update is loose we also set cseq_beforeloose.  Whenever we
2182   // clear cseq we clear cseq_beforeloose too.
2183   //
2184   // The result is that if cseq_beforeloose is non-null precisely if
2185   // the last op we sent was loose.
2186   //
2187   // We track separately the last loose, and the last non-loose,
2188   // outstanding API request.  (We discard our idea of the last
2189   // loose request if we follow it with a non-loose one.)
2190   //
2191   // So
2192   //     cseq_main > cseq_loose         one loose request then some non-loose
2193   //     cseq_main, no cseq_loose       just non-loose requests
2194   //     no cseq_main, but cseq_loose   just one loose request
2195   //     neither                        no outstanding requests
2196   //
2197   // If our only outstanding update is loose, we ignore a detected
2198   // conflict.  We expect the server to send us a proper
2199   // (non-Conflict) error later.
2200   if (p.cseq_main != null || p.cseq_loose != null) {
2201     if (drag_pieces.some(function(dp) { return dp.piece == piece; })) {
2202       console.log('drag end due to conflict');
2203       drag_end();
2204     }
2205   }
2206   if (p.cseq_main != null) {
2207     if (!already_logged)
2208       add_log_message('Conflict! - simultaneous update');
2209   }
2210   p.cseq_main = null;
2211   p.cseq_loose = null;
2212 }
2213
2214 function test_swap_stack() {
2215   let old_bot = pieces_marker.nextElementSibling!;
2216   let container = old_bot.parentElement!;
2217   container.insertBefore(old_bot, defs_marker);
2218   window.setTimeout(test_swap_stack, 1000);
2219 }
2220
2221 function startup() {
2222   console.log('STARTUP');
2223   console.log(wasm_bindgen.setup("OK"));
2224
2225   var body = document.getElementById("main-body")!;
2226   zoom_btn = document.getElementById("zoom-btn") as any;
2227   zoom_val = document.getElementById("zoom-val") as any;
2228   links_elem = document.getElementById("links") as any;
2229   ctoken = body.dataset.ctoken!;
2230   us = body.dataset.us!;
2231   gen = +body.dataset.gen!;
2232   let sse_url_prefix = body.dataset.sseUrlPrefix!;
2233   status_node = document.getElementById('status')!;
2234   status_node.innerHTML = 'js-done';
2235   log_elem = document.getElementById("log")!;
2236   logscroll_elem = document.getElementById("logscroll") || log_elem;
2237   let dataload = JSON.parse(body.dataset.load!);
2238   held_surround_colour = dataload.held_surround_colour!;
2239   players = dataload.players!;
2240   delete body.dataset.load;
2241   uos_node = document.getElementById("uos")!;
2242   occregions = wasm_bindgen.empty_region_list();
2243
2244   space = svg_element('space')!;
2245   pieces_marker = svg_element("pieces_marker")!;
2246   defs_marker = svg_element("defs_marker")!;
2247   movehist_start = svg_element('movehist_marker')!;
2248   movehist_end = svg_element('movehist_end')!;
2249   rectsel_path = svg_element('rectsel_path')!;
2250   svg_ns = space.getAttribute('xmlns')!;
2251
2252   for (let uelem = pieces_marker.nextElementSibling! as SVGGraphicsElement;
2253        uelem != defs_marker;
2254        uelem = uelem.nextElementSibling! as SVGGraphicsElement) {
2255     let piece = uelem.dataset.piece!;
2256     let p = JSON.parse(uelem.dataset.info!);
2257     p.uelem = uelem;
2258     p.delem = piece_element('defs',piece);
2259     p.pelem = piece_element('piece',piece);
2260     p.queued_moves = 0;
2261     occregion_update(piece, p, p); delete p.occregion;
2262     delete uelem.dataset.info;
2263     pieces[piece] = p;
2264     piece_resolve_special(piece,p);
2265     redisplay_ancillaries(piece,p);
2266   }
2267
2268   if (test_update_hook == null) test_update_hook = function() { };
2269   test_update_hook();
2270
2271   last_log_ts = wasm_bindgen.timestamp_abbreviator(dataload.last_log_ts);
2272
2273   for (let ent of dataload.movehist.hist) {
2274     movehist_record(ent);
2275   }
2276
2277   var es = new EventSource(
2278     sse_url_prefix + "/_/updates?ctoken="+ctoken+'&gen='+gen
2279   );
2280   es.onmessage = function(event) {
2281     console.log('GOTEVE', event.data);
2282     var k;
2283     var m;
2284     try {
2285       var [tgen, ms] = JSON.parse(event.data);
2286       for (m of ms) {
2287         k = Object.keys(m)[0];
2288         messages[k](m[k]);
2289       }
2290       gen = tgen;
2291       test_update_hook();
2292     } catch (exc) {
2293       var s = exc.toString();
2294       string_report_error('exception handling update '
2295                           + k + ': ' + JSON.stringify(m) + ': ' + s);
2296     }
2297   }
2298   es.addEventListener('commsworking', function(event) {
2299     console.log('GOTDATA', (event as any).data);
2300     status_node.innerHTML = (event as any).data;
2301   });
2302   es.addEventListener('player-gone', function(event) {
2303     console.log('PLAYER-GONE', event);
2304     status_node.innerHTML = (event as any).data;
2305     add_log_message('<strong>You are no longer in the game</strong>');
2306     space.removeEventListener('mousedown', some_mousedown);
2307     document.removeEventListener('keydown', some_keydown);
2308     es.close();
2309   });
2310   es.addEventListener('updates-expired', function(event) {
2311     console.log('UPDATES-EXPIRED', event);
2312     string_report_error('connection to server interrupted too long');
2313   });
2314   es.onerror = function(e) {
2315     let info = {
2316       updates_error : e,
2317       updates_event_source : es,
2318       updates_event_source_ready : es.readyState,
2319       update_oe : (e as any).className,
2320     };
2321     if (es.readyState == 2) {
2322       json_report_error({
2323         reason: "TOTAL SSE FAILURE",
2324         info: info,
2325       })
2326     } else {
2327       console.log('SSE error event', info);
2328     }
2329   }
2330   recompute_keybindings();
2331   space.addEventListener('mousedown', some_mousedown);
2332   space.addEventListener('dragstart', function (e) {
2333     e.preventDefault();
2334     e.stopPropagation();
2335   }, true);
2336   document.addEventListener('keydown',   some_keydown);
2337   check_z_order();
2338 }
2339
2340 type DieSpecialRendering = SpecialRendering & {
2341   cd_path: SVGPathElement,
2342   loaded_ts: DOMHighResTimeStamp,
2343   loaded_remprop: number,
2344   total_ms: number,
2345   radius: number,
2346   anim_id: number | null,
2347 };
2348 special_renderings['Die'] = function(piece: PieceId, p: PieceInfo,
2349                                      s: DieSpecialRendering) {
2350   let cd_path = document.getElementById('def.'+piece+'.die.cd');
2351   if (!cd_path) return;
2352
2353   s.cd_path = cd_path as any as SVGPathElement;
2354   s.loaded_ts = performance.now();
2355   s.loaded_remprop = parseFloat(cd_path.dataset.remprop!)!;
2356   s.total_ms       = parseFloat(cd_path.dataset.total_ms!)!;
2357   s.radius         = parseFloat(cd_path.dataset.radius!)!;
2358
2359   s.stop = die_rendering_stop as any;
2360   die_request_animation(piece, p, s);
2361 } as any;
2362 function die_request_animation(piece: PieceId, p: PieceInfo,
2363                                s: DieSpecialRendering) {
2364   s.anim_id = window.requestAnimationFrame(
2365     function(ts) { die_render_frame(piece, p, s, ts) }
2366   );
2367 }
2368 function die_render_frame(piece: PieceId, p: PieceInfo,
2369                           s: DieSpecialRendering, ts: DOMHighResTimeStamp) {
2370   s.anim_id = null;
2371   let remprop = s.loaded_remprop - (ts - s.loaded_ts) / s.total_ms;
2372   //console.log('DIE RENDER', piece, s, remprop);
2373   if (remprop <= 0) {
2374     console.log('DIE COMPLETE', piece, s, remprop);
2375     let to_remove: Element = s.cd_path;
2376     for (;;) {
2377       let previous = to_remove.previousElementSibling!;
2378       // see dice/overlya-template-extractor
2379       if (to_remove.tagName == 'text') break;
2380       to_remove.remove();
2381       to_remove = previous;
2382     }
2383   } else {
2384     let path_d = wasm_bindgen.die_cooldown_path(s.radius, remprop);
2385     s.cd_path.setAttributeNS(null, "d", path_d);
2386     die_request_animation(piece, p, s);
2387   }
2388 }
2389 function die_rendering_stop(piece: PieceId, p: PieceInfo,
2390                             s: DieSpecialRendering) {
2391   let anim_id = s.anim_id;
2392   if (anim_id == null) return;
2393   s.anim_id = null;
2394   window.cancelAnimationFrame(anim_id);
2395 }    
2396
2397 declare var wasm_input : any;
2398 var wasm_promise : Promise<any>;;
2399
2400 function doload(){
2401   console.log('DOLOAD');
2402   globalinfo_elem = document.getElementById('global-info')!;
2403   layout = globalinfo_elem!.dataset!.layout! as any;
2404   var elem = document.getElementById('loading_token')!;
2405   var ptoken = elem.dataset.ptoken;
2406   xhr_post_then('/_/session/' + layout, 
2407                 JSON.stringify({ ptoken : ptoken }),
2408                 loaded);
2409
2410   wasm_promise = wasm_input
2411     .then(wasm_bindgen);
2412 }
2413
2414 function loaded(xhr: XMLHttpRequest){
2415   console.log('LOADED');
2416   var body = document.getElementById('loading_body')!;
2417   wasm_promise.then((got_wasm) => {
2418     wasm = got_wasm;
2419     body.outerHTML = xhr.response;
2420     try {
2421       startup();
2422     } catch (exc) {
2423       let s = exc.toString();
2424       string_report_error_raw('Exception on load, unrecoverable: ' + s);
2425     }
2426   });
2427 }
2428
2429 // todo scroll of log messages to bottom did not always work somehow
2430 //    think I have fixed this with approximation
2431
2432 //@@notest
2433 doload();