function isEven(n) {
return n % 2 === 0;
}
function radToDeg(radians) {
return radians * 180 / Math.PI;
}
function calculateAngle(xDiff, yDiff) {
yDiff = -yDiff;
let angle = Math.abs(Math.atan(yDiff / xDiff));
if (xDiff < 0 && yDiff > 0) {
angle = Math.PI - angle;
} else if (xDiff < 0 && yDiff < 0) {
angle = Math.PI + angle;
} else if (xDiff > 0 && yDiff < 0) {
angle = 2 * Math.PI - angle;
}
return angle;
}
function troopSelector(number, allegiance) {
return `[data-troop-number="${number}"][data-troop-allegiance="${allegiance}"]`;
}
function edgePoint(x1, y1, x2, y2, maxX, maxY) {
let pointCoords,
xDiff = x2 - x1,
yDiff = y2 - y1,
xIntercept = y => (y - y1) * xDiff / yDiff + x1,
yIntercept = x => (x - x1) * yDiff / xDiff + y1;
if (xDiff > 0 && yDiff > 0) {
let x = xIntercept(maxY);
pointCoords = x <= maxX ? [x, maxY] : [maxX, yIntercept(maxX)];
} else if (xDiff > 0 && yDiff < 0) {
let y = yIntercept(maxX);
pointCoords = y >= 0 ? [maxX, y] : [xIntercept(0), 0];
} else if (xDiff < 0 && yDiff < 0) {
let x = xIntercept(0);
pointCoords = x >= 0 ? [x, 0] : [0, yIntercept(0)];
} else {
let y = yIntercept(0);
pointCoords = y <= maxY ? [0, y] : [xIntercept(maxY), maxY];
}
return pointCoords;
}
let getPointCoords = (x, y) => {
let point = document.querySelector(`[data-x="${x}"][data-y="${y}"]`);
return [point.x.baseVal.value, point.y.baseVal.value]
};
const svgns = "http://www.w3.org/2000/svg",
svg = document.querySelector('svg'),
map = document.querySelector('rect#map'),
hex = document.getElementById('point'),
pointsGroup = document.getElementById('points'),
settingsPanel = document.getElementById('panel');
const { x: VIEWBOX_X, y: VIEWBOX_Y, width: VIEWBOX_WIDTH, height: VIEWBOX_HEIGHT } =
svg.viewBox.baseVal;
const COLUMN_COUNT = 33,
ROW_COUNT = 51,
HORZ_POINT_DISTANCE = 1.005,
VERT_POINT_DISTANCE = Math.sqrt(3) * HORZ_POINT_DISTANCE / 2,
ALTERNATING_OFFSET = HORZ_POINT_DISTANCE / 2,
CIRCUMRADIUS = Math.max(...[...new Set(Object.values(hex.points).flatMap(({x, y}) => [x, y]))]),
INRADIUS = CIRCUMRADIUS * Math.sqrt(3) / 2,
[COLUMNS, ROWS] = [COLUMN_COUNT, ROW_COUNT].map(n => [...Array(n).keys()]),
POINTS = ROWS.map(y => COLUMNS.map(x => [x, y]));
const FIRING_ARC_SIZE = {
'small': Math.atan(HORZ_POINT_DISTANCE / (6 * VERT_POINT_DISTANCE)),
'medium': Math.atan((HORZ_POINT_DISTANCE / 2) / VERT_POINT_DISTANCE),
'large': Math.atan((21 * HORZ_POINT_DISTANCE) / (6 * VERT_POINT_DISTANCE))
}
Object.values(settingsPanel.querySelectorAll('fieldset')).forEach(fieldset => {
const target = document.getElementById(fieldset.name);
const transform = window.getComputedStyle(target).transform.match(/-?\d+\.?\d*/g);
const inputs = fieldset.querySelectorAll('input');
if (transform) {
const [a, b, c, d, e, f] = transform.map(n => parseFloat(n));
// a c e
// b d f
const scaleX = Math.sqrt(a**2 + c**2);
const scaleY = Math.sqrt(b**2 + d**2);
let values = {
scale: Math.round(scaleX * 10) / 10,
translateX: e,
translateY: f,
rotate: Math.round(radToDeg((Math.acos(a / scaleX) + Math.asin(b / scaleY)) / 2) * 10) / 10
}
inputs.forEach(input => input.value = values[input.name]);
}
inputs.forEach(input => {
input.addEventListener('pointerenter', e => e.target.focus());
input.addEventListener('input', e => {
let { scale, translateX, translateY, rotate} = Object.values(inputs).reduce((acc, input) => {
acc[input.name] = input.value;
return acc;
}, {});
let transform = `translate(${translateX}px, ${translateY}px) rotate(${rotate}deg) scale(${scale}) `
target.style.transform = transform;
});
input.addEventListener('pointerleave', () => document.activeElement.blur());
});
});
POINTS.forEach((row, index) => row.forEach(([x, y]) => {
var cx = x * INRADIUS * 2 + (isEven(index) ? INRADIUS : 0),
cy = y * 3 / 2 * CIRCUMRADIUS,
point = document.createElementNS(svgns, 'use');
point.setAttributeNS(null, 'href', `#point`);
point.setAttributeNS(null, 'x', `${parseFloat(cx.toFixed(1))}`);
point.setAttributeNS(null, 'y', `${parseFloat(cy.toFixed(1))}`);
point.dataset.x = x;
point.dataset.y = y;
point.addEventListener('click', e => {
let selectedSoldier = document.querySelector('.soldier-record.selected');
if (selectedSoldier) {
let counter = document.createElementNS(svgns, 'circle'),
text = document.createElementNS(svgns, 'text'),
{troopNumber, troopAllegiance} = selectedSoldier.dataset,
selector = troopSelector(troopNumber, troopAllegiance);
let matrix = window.getComputedStyle(pointsGroup).transform.match(/-?\d+\.?\d*/g),
svgMatrix = new DOMMatrix(matrix || ''),
pt = new DOMPoint(point.x.baseVal.value, point.y.baseVal.value),
svgP = pt.matrixTransform(svgMatrix);
counter.setAttributeNS(null, 'cx', `${parseFloat(svgP.x.toFixed(1))}`);
counter.setAttributeNS(null, 'cy', `${parseFloat(svgP.y.toFixed(1))}`);
counter.setAttributeNS(null, 'r', '0.25in');
counter.dataset.troopNumber = troopNumber;
counter.dataset.troopAllegiance = troopAllegiance;
counter.classList.add('counter');
text.setAttributeNS(null, 'text-anchor', 'middle');
text.setAttributeNS(null, 'x', `${svgP.x}`);
text.setAttributeNS(null, 'y', `${svgP.y}`);
text.dataset.troopNumber = troopNumber;
text.dataset.troopAllegiance = troopAllegiance;
text.textContent = troopNumber;
text.classList.add('counter');
document.querySelectorAll(`.counter${selector}`).forEach(el => el.remove());
counter.addEventListener('click', e => {
let selectedSoldier = document.querySelector('.soldier-record.selected');
if (selectedSoldier) {
let {troopNumber, troopAllegiance} = selectedSoldier.dataset,
selector = troopSelector(troopNumber, troopAllegiance),
targetIsSelectedSoldier = [
e.target.dataset.troopNumber == troopNumber,
e.target.dataset.troopAllegiance == troopAllegiance
].every(el => el);
if (targetIsSelectedSoldier) {
document.querySelectorAll(`.counter${selector}`).forEach(el => el.remove());
document.querySelectorAll(`.firing-arc${selector}`).forEach(el => el.remove());
}
}
});
counter.addEventListener('mouseenter', e => {
let selectedSoldier = document.querySelector('.soldier-record.selected');
if (selectedSoldier) {
let {troopNumber, troopAllegiance} = selectedSoldier.dataset,
selector = troopSelector(troopNumber, troopAllegiance),
source = document.querySelector(`circle.counter${selector}`),
// TODO: use isEqualNode() method instead
sourceAndTargetAreNotTheSame = [
troopNumber != e.target.dataset.troopNumber,
troopAllegiance != e.target.dataset.troopAllegiance
].some(el => el);
if (source && sourceAndTargetAreNotTheSame) {
let sightLine = document.createElementNS(svgns, 'line');
sightLine.classList.add('sight-line');
sightLine.setAttributeNS(null, 'x1', source.getAttribute('cx'));
sightLine.setAttributeNS(null, 'y1', source.getAttribute('cy'));
sightLine.setAttributeNS(null, 'x2', e.target.getAttribute('cx'));
sightLine.setAttributeNS(null, 'y2', e.target.getAttribute('cy'));
svg.appendChild(sightLine);
}
}
});
counter.addEventListener('mouseleave', e => {
document.querySelectorAll('.sight-line').forEach(el => el.remove());
});
svg.appendChild(counter);
svg.appendChild(text);
}
});
point.addEventListener('mouseover', e => {
let selectedSoldier = document.querySelector('.soldier-record.selected');
if (selectedSoldier) {
e.target.classList.add('active');
}
});
point.addEventListener('mouseout', e => e.target.removeAttribute('class'));
pointsGroup.appendChild(point);
}));
map.addEventListener('mousemove', e => {
let boundingRect = e.target.getBoundingClientRect();
let pointerX = e.clientX - boundingRect.left;
let pointerY = e.clientY - boundingRect.top;
let [maxXpx, maxYpx] = [e.target.width, e.target.height].map(v => v.baseVal.value);
let activeFiringArc = document.querySelector('polygon.firing-arc.active');
// TODO: handle exactly horizontal and vertical lines
if (activeFiringArc) {
let {x: x1px, y: y1px} = activeFiringArc.points[0];
let [x2px, y2px] = [
pointerX / boundingRect.width * maxXpx,
pointerY / boundingRect.height * maxYpx
];
let xDiff = x2px - x1px;
let yDiff = y2px - y1px;
let angle = calculateAngle(xDiff, yDiff);
let arcAngle = FIRING_ARC_SIZE[activeFiringArc.dataset.size];
let distance = Math.sqrt((x2px - x1px)**2 + (y2px - y1px)**2);
let yDelta = distance * Math.cos(angle) * Math.tan(arcAngle);
let xDelta = distance * Math.sin(angle) * Math.tan(arcAngle);
let [newY1, newX1] = [y2px + yDelta, x2px + xDelta];
let [newY2, newX2] = [y2px - yDelta, x2px - xDelta];
[newX1, newY1] = edgePoint(x1px, y1px, newX1, newY1, maxXpx, maxYpx);
[newX2, newY2] = edgePoint(x1px, y1px, newX2, newY2, maxXpx, maxYpx);
let oppositeEdgeConditions = [
newX1 == 0 && newX2 == maxXpx,
newX2 == 0 && newX1 == maxXpx,
newY1 == 0 && newY2 == maxYpx,
newY2 == 0 && newY1 == maxYpx
]
let orthogonalEdgeConditions = [
(newX1 == 0 || newX1 == maxXpx) && (newY2 == 0 || newY2 == maxYpx),
(newX2 == 0 || newX2 == maxXpx) && (newY1 == 0 || newY1 == maxYpx),
]
let points;
if (oppositeEdgeConditions.some(e => e)) {
let cornerPoints;
if (xDiff > 0 && yDiff > 0) {
if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) {
cornerPoints = [[maxXpx, 0], [maxXpx, maxYpx]];
} else {
cornerPoints = [[maxXpx, maxYpx], [0, maxYpx]];
}
} else if (xDiff > 0 && yDiff < 0) {
if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) {
cornerPoints = [[maxXpx, 0], [maxXpx, maxYpx]];
} else {
cornerPoints = [[0, 0], [maxXpx, 0]];
}
} else if (xDiff < 0 && yDiff > 0) {
if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) {
cornerPoints = [[0, maxYpx], [0, 0]];
} else {
cornerPoints = [[maxXpx, maxYpx], [0, maxYpx]];
}
} else {
if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) {
cornerPoints = [[0, maxYpx], [0, 0]];
} else {
cornerPoints = [[0, 0], [maxXpx, 0]];
}
}
points = `${x1px},${y1px} ${newX1},${newY1} ${cornerPoints[1]} ${cornerPoints[0]} ${newX2},${newY2}`;
} else if (orthogonalEdgeConditions.some(e => e)) {
let cornerPoints = [];
let cp1, cp2;
if (newX1 == 0 || newX1 == maxXpx) {
cp1 = [newX1, yDiff > 0 ? maxYpx : 0];
} else {
cp1 = [xDiff > 0 ? maxXpx : 0, newY1];
}
if (newX2 == 0 || newX2 == maxXpx) {
cp2 = [newX2, yDiff > 0 ? maxYpx : 0];
} else {
cp2 = [xDiff > 0 ? maxXpx : 0, newY2];
}
if (cp1[0] == cp2[0] && cp1[1] == cp2[1]) {
cornerPoints.push(cp1);
} else {
cornerPoints.push(cp1);
cornerPoints.push([xDiff > 0 ? maxXpx : 0, yDiff > 0 ? maxYpx : 0])
cornerPoints.push(cp2);
}
points = `${x1px},${y1px} ${newX1},${newY1} ${cornerPoints.join(' ')} ${newX2},${newY2}`;
} else {
points = `${x1px},${y1px} ${newX1},${newY1} ${newX2},${newY2}`;
}
activeFiringArc.setAttributeNS(null, 'points', points);
}
});
document.querySelectorAll('.soldier-record').forEach(el =>
el.addEventListener('click', e => {
if (el.classList.contains('selected')) {
el.classList.remove('selected');
} else {
document.querySelectorAll('.soldier-record.selected').forEach(el =>
el.classList.remove('selected')
);
el.classList.add('selected');
}
})
);
document.querySelectorAll('.set-firing-arc').forEach(el => el.addEventListener('click', e => {
let selectedSoldier = document.querySelector('.soldier-record.selected');
if (selectedSoldier) {
let {troopNumber, troopAllegiance} = selectedSoldier.dataset;
let existingArcs = document.querySelectorAll(
`.firing-arc[data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]`
);
existingArcs.forEach(el => el.remove());
let counter = document.querySelector(
`circle.counter[data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]`
);
if (counter) {
let arcLayer = document.getElementById('firing-arcs');
let firingArcPlacementListener = e => {
document.querySelectorAll('.firing-arc.active').forEach(el => el.classList.remove('active'));
document.querySelector('#point').style.display = '';
map.removeEventListener('click', firingArcPlacementListener);
};
map.addEventListener('click', firingArcPlacementListener);
let pivotPoint = [counter.cx.baseVal.value, counter.cy.baseVal.value];
let firingArc = document.createElementNS(svgns, 'polygon');
firingArc.classList.add('firing-arc', 'active');
firingArc.dataset.troopNumber = troopNumber;
firingArc.dataset.troopAllegiance = troopAllegiance;
firingArc.dataset.size = e.target.dataset.size;
firingArc.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`);
arcLayer.prepend(firingArc);
document.querySelector('#point').style.display = 'none';
}
}
}));
document.querySelectorAll('.clear-firing-arcs').forEach(el =>
el.addEventListener('click', ({target: {dataset: {allegiance}}}) =>
document
.querySelectorAll(`.firing-arc[data-troop-allegiance="${allegiance}"]`)
.forEach(el => el.remove())
)
);
svg.addEventListener('wheel', e => {
e.preventDefault();
// const pt = svg.createSVGPoint();
const pt = new DOMPoint(e.clientX, e.clientY);
// pt.x = e.clientX;
// pt.y = e.clientY;
const svgP = pt.matrixTransform(svg.getScreenCTM().inverse());
let { x, y, width, height } = svg.viewBox.baseVal;
let widthDelta = width * 0.25;
let heightDelta = height * 0.25;
let xChange = (svgP.x - x) / width * widthDelta;
let yChange = (svgP.y - y) / height * heightDelta;
let widthChange = (1 - ((svgP.x - x) / width)) * widthDelta;
let heightChange = (1 - ((svgP.y - y) / height)) * heightDelta;
let newX = parseInt(e.deltaY < 0 ? x + xChange : x - xChange);
let newWidth = parseInt(e.deltaY < 0 ? width - xChange - widthChange : width + xChange + widthChange);
let newY = parseInt(e.deltaY < 0 ? y + yChange : y - yChange);
let newHeight = parseInt(e.deltaY < 0 ? height - yChange - heightChange : height + yChange + heightChange);
// console.log('VIEWBOX_X', 'VIEWBOX_Y', VIEWBOX_X, VIEWBOX_Y);
// console.log('VIEWBOX_WIDTH', 'VIEWBOX_HEIGHT', VIEWBOX_WIDTH, VIEWBOX_HEIGHT);
// if (newWidth + newX > VIEWBOX_WIDTH + VIEWBOX_X && newX < VIEWBOX_X) {
// newWidth = VIEWBOX_WIDTH;
// newX = VIEWBOX_X;
// } else if (newWidth + newX > VIEWBOX_WIDTH + VIEWBOX_X) {
// let diff = newWidth + newX - VIEWBOX_WIDTH - VIEWBOX_X;
// newX = newX - diff;
// }
// if (newHeight + newY > VIEWBOX_HEIGHT + VIEWBOX_Y && newY < VIEWBOX_Y) {
// newHeight = VIEWBOX_HEIGHT;
// newY = VIEWBOX_Y;
// } else if (newHeight + newY > VIEWBOX_HEIGHT + VIEWBOX_Y) {
// let diff = newHeight + newY - VIEWBOX_HEIGHT - VIEWBOX_Y;
// newY = newY - diff;
// }
// newX = newX < VIEWBOX_X ? VIEWBOX_X : newX;
// newY = newY < VIEWBOX_Y ? VIEWBOX_Y : newY;
svg.setAttributeNS(null, 'viewBox', `${newX} ${newY} ${newWidth} ${newHeight}`);
});
svg.addEventListener('pointerdown', e => {
const minPanDistanceThreshold = 5;
let dist, ctm,
pan = false,
{ x, y, width, height } = svg.viewBox.baseVal,
startPt = new DOMPoint(e.clientX, e.clientY),
movePt = new DOMPoint();
function pointerMove(e) {
movePt.x = e.clientX;
movePt.y = e.clientY;
dist = Math.sqrt((movePt.x - startPt.x)**2 + (movePt.y - startPt.y)**2);
if (!pan && dist >= minPanDistanceThreshold) {
pan = true;
startPt.x = e.clientX;
startPt.y = e.clientY;
}
if (pan) {
svg.setPointerCapture(e.pointerId);
ctm = svg.getScreenCTM().inverse();
const [svgStartPt, svgMovePt] = [startPt, movePt].map(p => p.matrixTransform(ctm)),
moveX = parseInt(svgStartPt.x - svgMovePt.x + x),
moveY = parseInt(svgStartPt.y - svgMovePt.y + y);
svg.setAttributeNS(null, 'viewBox', `${moveX} ${moveY} ${width} ${height}`);
}
}
function pointerUp(e) {
svg.releasePointerCapture(e.pointerId);
svg.removeEventListener('pointermove', pointerMove);
svg.removeEventListener('pointerup', pointerUp);
}
svg.addEventListener('pointermove', pointerMove);
svg.addEventListener('pointerup', pointerUp);
});