-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsvg.ts
443 lines (406 loc) · 13 KB
/
svg.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
import { State } from './state';
import { key2pos } from './util';
import { Drawable, DrawShape, DrawShapePiece, DrawBrush, DrawBrushes, DrawModifiers } from './draw';
import * as cg from './types';
import * as T from './transformations';
import { renderPiece as abaloneRenderPiece, renderShape as abaloneRenderShape } from './variants/abalone/svg';
export function createElement(tagName: string): SVGElement {
return document.createElementNS('http://www.w3.org/2000/svg', tagName);
}
export interface Shape {
shape: DrawShape;
current: boolean;
hash: Hash;
}
type CustomBrushes = Map<string, DrawBrush>; // by hash
export type ArrowDests = Map<cg.Key, number>; // how many arrows land on a square
type Hash = string;
export function renderSvg(state: State, svg: SVGElement, customSvg: SVGElement): void {
const d = state.drawable,
curD = d.current,
cur = curD && curD.mouseSq ? (curD as DrawShape) : undefined,
arrowDests: ArrowDests = new Map(),
bounds = state.dom.bounds();
for (const s of d.shapes.concat(d.autoShapes).concat(cur ? [cur] : [])) {
if (s.dest) arrowDests.set(s.dest, (arrowDests.get(s.dest) || 0) + 1);
}
const shapes: Shape[] = d.shapes.concat(d.autoShapes).map((s: DrawShape) => {
return {
shape: s,
current: false,
hash: shapeHash(s, arrowDests, false, bounds),
};
});
if (cur)
shapes.push({
shape: cur,
current: true,
hash: shapeHash(cur, arrowDests, true, bounds),
});
const fullHash = shapes.map(sc => sc.hash).join(';');
if (fullHash === state.drawable.prevSvgHash) return;
state.drawable.prevSvgHash = fullHash;
/*
-- DOM hierarchy --
<svg class="cg-shapes"> (<= svg)
<defs>
...(for brushes)...
</defs>
<g>
...(for arrows, circles, and pieces)...
</g>
</svg>
<svg class="cg-custom-svgs"> (<= customSvg)
<g>
...(for custom svgs)...
</g>
</svg>
*/
const defsEl = svg.querySelector('defs') as SVGElement;
const shapesEl = svg.querySelector('g') as SVGElement;
const customSvgsEl = customSvg.querySelector('g') as SVGElement;
syncDefs(d, shapes, defsEl);
syncShapes(
state,
shapes.filter(s => !s.shape.customSvg),
d.brushes,
arrowDests,
shapesEl,
);
syncShapes(
state,
shapes.filter(s => s.shape.customSvg),
d.brushes,
arrowDests,
customSvgsEl,
);
}
// append only. Don't try to update/remove.
function syncDefs(d: Drawable, shapes: Shape[], defsEl: SVGElement) {
const brushes: CustomBrushes = new Map();
let brush: DrawBrush;
for (const s of shapes) {
if (s.shape.dest) {
brush = d.brushes[s.shape.brush!];
if (s.shape.modifiers) brush = makeCustomBrush(brush, s.shape.modifiers);
brushes.set(brush.key, brush);
}
}
const keysInDom = new Set();
let el: SVGElement | undefined = defsEl.firstChild as SVGElement;
while (el) {
keysInDom.add(el.getAttribute('cgKey'));
el = el.nextSibling as SVGElement | undefined;
}
for (const [key, brush] of brushes.entries()) {
if (!keysInDom.has(key)) defsEl.appendChild(renderMarker(brush));
}
}
// append and remove only. No updates.
function syncShapes(
state: State,
shapes: Shape[],
brushes: DrawBrushes,
arrowDests: ArrowDests,
root: SVGElement,
): void {
const bounds = state.dom.bounds(),
hashesInDom = new Map(), // by hash
toRemove: SVGElement[] = [];
for (const sc of shapes) hashesInDom.set(sc.hash, false);
let el: SVGElement | undefined = root.firstChild as SVGElement,
elHash: Hash;
while (el) {
elHash = el.getAttribute('cgHash') as Hash;
// found a shape element that's here to stay
if (hashesInDom.has(elHash)) hashesInDom.set(elHash, true);
// or remove it
else toRemove.push(el);
el = el.nextSibling as SVGElement | undefined;
}
// remove old shapes
for (const el of toRemove) root.removeChild(el);
// insert shapes that are not yet in dom
for (const sc of shapes) {
if (!hashesInDom.get(sc.hash)) root.appendChild(renderShape(state, sc, brushes, arrowDests, bounds));
}
}
function shapeHash(
{ orig, dest, brush, piece, modifiers, customSvg }: DrawShape,
arrowDests: ArrowDests,
current: boolean,
bounds: ClientRect,
): Hash {
return [
bounds.width,
bounds.height,
current,
orig,
dest,
brush,
dest && (arrowDests.get(dest) || 0) > 1,
piece && pieceHash(piece),
modifiers && modifiersHash(modifiers),
customSvg && customSvgHash(customSvg),
]
.filter(x => x)
.join(',');
}
function pieceHash(piece: DrawShapePiece): Hash {
return [piece.playerIndex, piece.role, piece.scale].filter(x => x).join(',');
}
function modifiersHash(m: DrawModifiers): Hash {
return '' + (m.lineWidth || '');
}
function customSvgHash(s: string): Hash {
// Rolling hash with base 31 (cf. https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript)
let h = 0;
for (let i = 0; i < s.length; i++) {
h = ((h << 5) - h + s.charCodeAt(i)) >>> 0;
}
return 'custom-' + h.toString();
}
function renderShape(
state: State,
{ shape, current, hash }: Shape,
brushes: DrawBrushes,
arrowDests: ArrowDests,
bounds: ClientRect,
): SVGElement {
if (state.variant === 'abalone') {
return abaloneRenderShape(state, { shape, current, hash }, brushes, arrowDests, bounds);
}
let el: SVGElement;
if (shape.customSvg) {
const orig = orient(key2pos(shape.orig), state.orientation, state.dimensions);
el = renderCustomSvg(shape.customSvg, orig, bounds, state.dimensions);
} else if (shape.piece)
el = renderPiece(
state.drawable.pieces.baseUrl,
orient(key2pos(shape.orig), state.orientation, state.dimensions),
shape.piece,
bounds,
state.dimensions,
state.myPlayerIndex,
state.variant,
);
else {
const orig = orient(key2pos(shape.orig), state.orientation, state.dimensions);
if (shape.orig && shape.dest) {
let brush: DrawBrush = brushes[shape.brush!];
if (shape.modifiers) brush = makeCustomBrush(brush, shape.modifiers);
el = renderArrow(
brush,
orig,
orient(key2pos(shape.dest), state.orientation, state.dimensions),
current,
(arrowDests.get(shape.dest) || 0) > 1,
bounds,
state.dimensions,
);
} else el = renderCircle(brushes[shape.brush!], orig, current, bounds, state.dimensions);
}
el.setAttribute('cgHash', hash);
return el;
}
function renderCustomSvg(customSvg: string, pos: cg.Pos, bounds: ClientRect, bd: cg.BoardDimensions): SVGElement {
const { width, height } = bounds;
const w = width / bd.width;
const h = height / bd.height;
const x = (pos[0] - 1) * w;
const y = (bd.height - pos[1]) * h;
// Translate to top-left of `orig` square
const g = setAttributes(createElement('g'), { transform: `translate(${x},${y})` });
// Give 100x100 coordinate system to the user for `orig` square
const svg = setAttributes(createElement('svg'), { width: w, height: h, viewBox: '0 0 100 100' });
g.appendChild(svg);
svg.innerHTML = customSvg;
return g;
}
function renderCircle(
brush: DrawBrush,
pos: cg.Pos,
current: boolean,
bounds: ClientRect,
bd: cg.BoardDimensions,
): SVGElement {
const o = pos2px(pos, bounds, bd),
widths = circleWidth(bounds, bd),
radius = (bounds.width + bounds.height) / (2 * (bd.height + bd.width));
return setAttributes(createElement('circle'), {
stroke: brush.color,
'stroke-width': widths[current ? 0 : 1],
fill: 'none',
opacity: opacity(brush, current),
cx: o[0],
cy: o[1],
r: radius - widths[1] / 2,
});
}
function renderArrow(
brush: DrawBrush,
orig: cg.Pos,
dest: cg.Pos,
current: boolean,
shorten: boolean,
bounds: ClientRect,
bd: cg.BoardDimensions,
): SVGElement {
const m = arrowMargin(bounds, shorten && !current, bd),
a = pos2px(orig, bounds, bd),
b = pos2px(dest, bounds, bd),
dx = b[0] - a[0],
dy = b[1] - a[1],
angle = Math.atan2(dy, dx),
xo = Math.cos(angle) * m,
yo = Math.sin(angle) * m;
return setAttributes(createElement('line'), {
stroke: brush.color,
'stroke-width': lineWidth(brush, current, bounds, bd),
'stroke-linecap': 'round',
'marker-end': 'url(#arrowhead-' + brush.key + ')',
opacity: opacity(brush, current),
x1: a[0],
y1: a[1],
x2: b[0] - xo,
y2: b[1] - yo,
});
}
function renderPiece(
baseUrl: string,
pos: cg.Pos,
piece: DrawShapePiece,
bounds: ClientRect,
bd: cg.BoardDimensions,
myPlayerIndex: cg.PlayerIndex,
variant: cg.Variant,
): SVGElement {
if (variant === 'abalone') {
return abaloneRenderPiece(baseUrl, pos, piece, bounds, bd, myPlayerIndex);
}
const o = pos2px(pos, bounds, bd),
width = (bounds.width / bd.width) * (piece.scale || 1),
height = (bounds.height / bd.height) * (piece.scale || 1),
//name = piece.playerIndex[0] + piece.role[0].toUpperCase();
name = roleToSvgName(variant, piece);
// If baseUrl doesn't end with '/' use it as full href
// This is needed when drop piece suggestion .svg image file names are different than "name" produces
const href = baseUrl.endsWith('/') ? baseUrl.slice('https://playstrategy.org'.length) + name + '.svg' : baseUrl;
const side = piece.playerIndex === myPlayerIndex ? 'ally' : 'enemy';
return setAttributes(createElement('image'), {
className: `${piece.role} ${piece.playerIndex} ${side}`,
x: o[0] - width / 2,
y: o[1] - height / 2,
width: width,
height: height,
href: href,
});
}
function renderMarker(brush: DrawBrush): SVGElement {
const marker = setAttributes(createElement('marker'), {
id: 'arrowhead-' + brush.key,
orient: 'auto',
markerWidth: 4,
markerHeight: 8,
refX: 2.05,
refY: 2.01,
});
marker.appendChild(
setAttributes(createElement('path'), {
d: 'M0,0 V4 L3,2 Z',
fill: brush.color,
}),
);
marker.setAttribute('cgKey', brush.key);
return marker;
}
export function setAttributes(el: SVGElement, attrs: { [key: string]: any }): SVGElement {
for (const key in attrs) el.setAttribute(key, attrs[key]);
return el;
}
export function orient(pos: cg.Pos, orientation: cg.Orientation, bd: cg.BoardDimensions): cg.Pos {
return T.mapToP1Inverse[orientation](pos, bd);
}
export function makeCustomBrush(base: DrawBrush, modifiers: DrawModifiers): DrawBrush {
return {
color: base.color,
opacity: Math.round(base.opacity * 10) / 10,
lineWidth: Math.round(modifiers.lineWidth || base.lineWidth),
key: [base.key, modifiers.lineWidth].filter(x => x).join(''),
};
}
export function circleWidth(bounds: ClientRect, bd: cg.BoardDimensions): [number, number] {
const base = bounds.width / (bd.width * 64);
return [3 * base, 4 * base];
}
export function lineWidth(brush: DrawBrush, current: boolean, bounds: ClientRect, bd: cg.BoardDimensions): number {
return (((brush.lineWidth || 10) * (current ? 0.85 : 1)) / (bd.width * 64)) * bounds.width;
}
export function opacity(brush: DrawBrush, current: boolean): number {
return (brush.opacity || 1) * (current ? 0.9 : 1);
}
export function arrowMargin(bounds: ClientRect, shorten: boolean, bd: cg.BoardDimensions): number {
return ((shorten ? 20 : 10) / (bd.width * 64)) * bounds.width;
}
function pos2px(pos: cg.Pos, bounds: ClientRect, bd: cg.BoardDimensions): cg.NumberPair {
return [((pos[0] - 0.5) * bounds.width) / bd.width, ((bd.height + 0.5 - pos[1]) * bounds.height) / bd.height];
}
function roleToSvgName(variant: cg.Variant, piece: DrawShapePiece): string {
switch (variant) {
case 'shogi':
switch (piece.role) {
//promoted
case 'pp-piece':
return '0' + 'TO';
case 'pl-piece':
return '0' + 'NY';
case 'pn-piece':
return '0' + 'NK';
case 'ps-piece':
return '0' + 'NG';
case 'pr-piece':
return '0' + 'RY';
case 'pb-piece':
return '0' + 'UM';
//not promoted - only draw your own pieces therefore always 0 not 1?
case 'p-piece':
return '0FU';
case 'l-piece':
return '0KY';
case 'n-piece':
return '0KE';
case 's-piece':
return '0GI';
case 'r-piece':
return '0HI';
case 'b-piece':
return '0KA';
case 'g-piece':
return '0KI';
case 'k-piece':
return piece.playerIndex === 'p1' ? '0GY' : '0OU';
default:
return '';
}
case 'xiangqi':
return (piece.playerIndex === 'p1' ? 'R' : 'B') + piece.role[0].toUpperCase();
case 'flipello10':
case 'flipello':
case 'linesOfAction':
case 'go9x9':
case 'go13x13':
case 'go19x19':
case 'abalone':
return (piece.playerIndex === 'p1' ? 'b' : 'w') + piece.role[0].toUpperCase();
case 'oware':
case 'togyzkumalak':
case 'bestemshe':
return piece.role[0].split('-')[0].substring(1);
case 'nackgammon':
case 'backgammon':
return (piece.playerIndex === 'p1' ? 'w' : 'b') + piece.role[0].split('-')[0].substring(1);
default:
//chess types
return (piece.playerIndex === 'p1' ? 'w' : 'b') + piece.role[0].toUpperCase();
}
}