// https://www.redblobgames.com/grids/hexagons/
// Horizontal distance between hex centers is sqrt(3) * size. The vertical
// distance is 3 / 2 * size. When we calculate horzDist / vertDist, the size
// cancels out, leaving us with a unitless ratio of sqrt(3) / (3 / 2), or
// 2 * sqrt(3) / 3.
const svgns = "http://www.w3.org/2000/svg",
horzToVertDistRatio = 2 * Math.sqrt(3) / 3,
arcSize = {
'small': Math.atan(horzToVertDistRatio / 6),
'medium': Math.atan(horzToVertDistRatio / 2),
'large': Math.atan(7 * horzToVertDistRatio / 2)
},
firingArcVisibility = {
davion: false,
liao: false
},
clippedFiringArcRadius = 100;
let svg;
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 edgePoint([x1, y1], [x2, y2], { minX = 0, minY = 0, maxX, maxY } = {}) {
const xDiff = x2 - x1,
yDiff = y2 - y1,
xIntercept = y => (y - y1) * xDiff / yDiff + x1,
yIntercept = x => (x - x1) * yDiff / xDiff + y1;
let pointCoords;
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 >= minY ? [maxX, y] : [xIntercept(minY), minY];
} else if (xDiff < 0 && yDiff < 0) {
let x = xIntercept(minY);
pointCoords = x >= minX ? [x, minY] : [minX, yIntercept(minX)];
} else {
let y = yIntercept(minX);
pointCoords = y <= maxY ? [minX, y] : [xIntercept(maxY), maxY];
}
return pointCoords;
}
function position(activeFiringArc, activeFiringArcOutline, aim, grid, e) {
// TODO: handle exactly horizontal and vertical lines?
let pt = new DOMPoint(e.clientX, e.clientY);
let { x: pointerX, y: pointerY } = pt.matrixTransform(grid.getScreenCTM().inverse());
let pivotPt = [x1, y1] = [aim.getAttribute('x1'), aim.getAttribute('y1')].map(n => parseFloat(n));
let { x, y, width, height } = grid.getBBox();
let [minX, minY, maxX, maxY] = [x, y, x + width, y + height];
let bounds = { minX, minY, maxX, maxY };
let cornerPoints = [[x, y], [x + width, y], [x + width, y + height], [x, y + height]];
let aimPt = [x2, y2] = edgePoint(pivotPt, [pointerX, pointerY], bounds);
aim.setAttributeNS(null, 'x2', x2);
aim.setAttributeNS(null, 'y2', y2);
let angle = calculateAngle(x2 - x1, y2 - y1);
let arcAngle = arcSize[activeFiringArc.dataset.size];
let distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
let yDelta = distance * Math.cos(angle) * Math.tan(arcAngle);
let xDelta = distance * Math.sin(angle) * Math.tan(arcAngle);
let [newY1, newX1] = [y2 - yDelta, x2 - xDelta];
let [newY2, newX2] = [y2 + yDelta, x2 + xDelta];
let arcPt1 = [newX1, newY1] = edgePoint(pivotPt, [newX1, newY1], bounds);
let arcPt2 = [newX2, newY2] = edgePoint(pivotPt, [newX2, newY2], bounds);
activeFiringArcOutline.setAttributeNS(null, 'points', `${newX1},${newY1} ${x1},${y1} ${newX2},${newY2}`);
function touchSameEdge([x1, y1], [x2, y2]) {
return x1 === x2 || y1 === y2;
}
function touchOrthogonalEdges([x1, y1], [x2, y2]) {
let xLimit = [minX, maxX], yLimit = [minY, maxY];
return (xLimit.includes(x1) && yLimit.includes(y2)) || (yLimit.includes(y1) && xLimit.includes(x2));
}
function shareValue([x1, y1], [x2, y2]) {
return x1 === x2 || y1 === y2;
}
// which arcpt does aimpt share a value with?
// if they share an x value, we will look for corner y value
// if they share a y value, we will look for corner x value
// is aim pt non-shared value greater or less than arcpt non-shared value?
function findSharedValue(pt, ...pts) {
const sharedValPt = pts.find(([ptX, ptY]) => pt.includes(ptX) || pt.includes(ptY));
if (!sharedValPt) {
return;
}
const limits = [[minX, maxX], [minY, maxY]],
nonSharedValIndex = pt[0] === sharedValPt[0] ? 1 : 0;
let cornerVal;
if (pt[nonSharedValIndex] < sharedValPt[nonSharedValIndex]) {
cornerVal = Math.min(...limits[nonSharedValIndex])
} else {
cornerVal = Math.max(...limits[nonSharedValIndex]);
}
return cornerPoints.filter(cp => cp[nonSharedValIndex] === cornerVal);
}
let points;
if (touchSameEdge(arcPt1, arcPt2)) {
// 0-corner case
points = [arcPt2, pivotPt, arcPt1];
} else if (touchOrthogonalEdges(arcPt1, arcPt2)) {
if (touchSameEdge(aimPt, arcPt1) || touchSameEdge(aimPt, arcPt2)) {
// 1-corner case
let cp = cornerPoints.find(cp => shareValue(cp, arcPt1) && shareValue(cp, arcPt2));
points = [arcPt2, pivotPt, arcPt1, cp];
} else {
// 3-corner case
points = cornerPoints.filter(cp => !shareValue(cp, arcPt1) || !shareValue(cp, arcPt2));
let index = points.findIndex(cp => shareValue(cp, arcPt2));
points.splice(index + 1, 0, arcPt2, pivotPt, arcPt1);
}
} else {
if (touchSameEdge(aimPt, arcPt1) || touchSameEdge(aimPt, arcPt2)) {
// 2-corner case, aim and an arc point touch the same edge
points = findSharedValue(aimPt, arcPt1, arcPt2);
let index = points.findIndex(cp => shareValue(cp, arcPt2));
points.splice(index + 1, 0, arcPt2, pivotPt, arcPt1);
} else {
// 2-corner case, aim and both arc points all touch different edges
points = cornerPoints.filter(cp => shareValue(cp, aimPt) || shareValue(cp, aimPt));
let index = points.findIndex(cp => shareValue(cp, arcPt2));
points.splice(index + 1, 0, arcPt2, pivotPt, arcPt1);
}
}
activeFiringArc.setAttributeNS(null, 'points', points.join(' '));
}
function setDataAttrs({ dataset: { allegiance, number }}, el) {
el.dataset.allegiance = allegiance;
el.dataset.number = number;
}
function getClipPathId({ dataset: { allegiance, number }}) {
return `clip-path-${allegiance}-${number}`;
}
function getUnclipped() {
return svg.querySelectorAll('#firing-arcs polygon:not([clip-path])');
};
export default function (el) {
svg = el;
this.set = function (size, counter, { x, y }) {
this.get(counter).forEach(fa => fa.remove());
let arcLayer = svg.querySelector('#shapes');
let outlineLayer = svg.querySelector('#lines');
let arcContainer = svg.querySelector('#firing-arcs');
let grid = svg.querySelector('.grid');
let points = `${x},${y} ${x},${y} ${x},${y}`;
let aim = document.createElementNS(svgns, 'line');
aim.setAttributeNS(null, 'x1', x);
aim.setAttributeNS(null, 'y1', y);
aim.setAttributeNS(null, 'x2', x);
aim.setAttributeNS(null, 'y2', y);
outlineLayer.appendChild(aim);
let firingArc = document.createElementNS(svgns, 'polygon');
let firingArcOutline = document.createElementNS(svgns, 'polyline');
setDataAttrs(counter, firingArc);
firingArc.dataset.size = size;
firingArc.classList.add('firing-arc', 'active');
firingArc.setAttributeNS(null, 'points', points);
setDataAttrs(counter, firingArcOutline);
firingArcOutline.setAttributeNS(null, 'points', points);
let clipShape = document.createElementNS(svgns, 'circle');
clipShape.setAttributeNS(null, 'cx', x);
clipShape.setAttributeNS(null, 'cy', y);
clipShape.setAttributeNS(null, 'r', clippedFiringArcRadius);
let clipPath = document.createElementNS(svgns, 'clipPath');
setDataAttrs(counter, clipPath);
clipPath.setAttributeNS(null, 'id', getClipPathId(counter));
clipPath.appendChild(clipShape);
arcContainer.appendChild(clipPath);
arcLayer.appendChild(firingArc);
outlineLayer.appendChild(firingArcOutline);
const positionListener = position.bind(svg, firingArc, firingArcOutline, aim, grid);
let firingArcPlacementListener = e => {
svg.querySelectorAll('.firing-arc.active').forEach(el => el.classList.remove('active'));
grid.removeAttribute('style');
svg.removeEventListener('mousemove', positionListener);
firingArc.removeEventListener('click', firingArcPlacementListener);
firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement);
};
let cancelFiringArcPlacement = e => {
e.preventDefault();
firingArc.removeEventListener('click', firingArcPlacementListener);
firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement);
this.get(counter).forEach(fa => fa.remove());
grid.removeAttribute('style');
svg.removeEventListener('mousemove', positionListener);
};
grid.style.pointerEvents = 'none';
firingArc.addEventListener('click', firingArcPlacementListener);
firingArc.addEventListener('contextmenu', cancelFiringArcPlacement);
svg.addEventListener('mousemove', positionListener);
};
this.clear = function (allegiance) {
const selector = `#firing-arcs [data-allegiance="${allegiance}"]`;
svg.querySelectorAll(selector).forEach(el => el.remove());
};
this.get = function ({ dataset: { allegiance, number }}) {
return svg.querySelectorAll(`#firing-arcs [data-number="${number}"][data-allegiance="${allegiance}"], #firing-arcs line`);
};
this.toggleVisibility = function (allegiance) {
const vis = firingArcVisibility[allegiance],
clipPaths = svg.querySelectorAll(`clipPath[data-allegiance="${allegiance}"]`);
clipPaths.forEach(cp => cp.style.display = !vis ? 'none' : '');
firingArcVisibility[allegiance] = !vis;
};
this.toggleCounterVisibility = function ({ dataset: { number, allegiance }}, vis) {
const cp = svg.querySelector(`#clip-path-${allegiance}-${number}`),
display = vis ? 'none' : '';
if (cp) {
cp.style.display = firingArcVisibility[allegiance] ? 'none' : display;
}
};
this.clipAll = function () {
console.log('clipall')
let unclipped = getUnclipped();
unclipped.forEach(el => {
const { number, allegiance } = el.dataset,
clipPathId = `clip-path-${allegiance}-${number}`,
isVisible = firingArcVisibility[allegiance];
if (isVisible) {
svg.querySelector(`#${clipPathId}`).style.display = 'none';
}
el.setAttributeNS(null, 'clip-path', `url(#${clipPathId})`);
});
};
}