forked from foundryvtt/pf2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.ts
331 lines (285 loc) · 13.3 KB
/
helpers.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
import type { EffectAreaShape } from "@item/spell/types.ts";
import { TokenPF2e, type MeasuredTemplatePF2e } from "./index.ts";
/**
* Measure the minimum distance between two rectangles
* @param r0 The origin rectangle
* @param r1 The destination rectangle
* @param [reach] If this is a reach measurement, the origin actor's reach
*/
function measureDistanceCuboid(
r0: PIXI.Rectangle,
r1: PIXI.Rectangle,
{
reach = null,
token = null,
target = null,
}: {
reach?: number | null;
token?: TokenPF2e | null;
target?: TokenPF2e | null;
} = {},
): number {
if (!canvas.grid) return NaN;
if (canvas.grid.type !== CONST.GRID_TYPES.SQUARE) {
return canvas.grid.measurePath([r0, r1]).distance;
}
const gridWidth = canvas.grid.sizeX;
const distance = {
dx: 0,
dy: 0,
dz: 0,
};
// Return early if the rectangles overlap
const rectanglesOverlap = [
[r0, r1],
[r1, r0],
].some(([rA, rB]) => rB.right > rA.left && rB.left < rA.right && rB.bottom > rA.top && rB.top < rA.bottom);
if (rectanglesOverlap) {
distance.dx = 0;
distance.dy = 0;
} else {
// Snap the dimensions and position of the rectangle to grid square units
const snapBounds = (rectangle: PIXI.Rectangle, { toward }: { toward: PIXI.Rectangle }): PIXI.Rectangle => {
const roundLeft = rectangle.left < toward.left ? Math.ceil : Math.floor;
const roundTop = rectangle.top < toward.top ? Math.ceil : Math.floor;
const left = roundLeft(rectangle.left / gridWidth) * gridWidth;
const top = roundTop(rectangle.top / gridWidth) * gridWidth;
const width = Math.ceil(rectangle.width / gridWidth) * gridWidth;
const height = Math.ceil(rectangle.height / gridWidth) * gridWidth;
return new PIXI.Rectangle(left, top, width, height);
};
// Find the minimum distance between the rectangles for each dimension
const r0Snapped = snapBounds(r0, { toward: r1 });
const r1Snapped = snapBounds(r1, { toward: r0 });
distance.dx = Math.max(r0Snapped.left - r1Snapped.right, r1Snapped.left - r0Snapped.right, 0) + gridWidth;
distance.dy = Math.max(r0Snapped.top - r1Snapped.bottom, r1Snapped.top - r0Snapped.bottom, 0) + gridWidth;
}
if (token && target && token?.document?.elevation !== target?.document.elevation && token.actor && target.actor) {
const selfElevation = token.document.elevation;
const targetElevation = target.document.elevation;
const [selfDimensions, targetDimensions] = [token.actor.dimensions, target.actor.dimensions];
const gridSize = canvas.dimensions.size;
const gridDistance = canvas.dimensions.distance;
const elevation0 = Math.floor((selfElevation / gridDistance) * gridSize);
const height0 = Math.floor((selfDimensions.height / gridDistance) * gridSize);
const elevation1 = Math.floor((targetElevation / gridDistance) * gridSize);
const height1 = Math.floor((targetDimensions.height / gridDistance) * gridSize);
// simulate xz plane
const xzPlane = {
self: new PIXI.Rectangle(r0.x, elevation0, r0.width, height0),
target: new PIXI.Rectangle(r1.x, elevation1, r1.width, height1),
};
// check for overlappig
const elevationOverlap = [
[xzPlane.self, xzPlane.target],
[xzPlane.target, xzPlane.self],
].some(([rA, rB]) => rB.bottom > rA.top && rB.top < rA.bottom);
if (elevationOverlap) {
distance.dz = 0;
} else {
// Snap the dimensions and position of the rectangle to grid square units
const snapBounds = (rectangle: PIXI.Rectangle, { toward }: { toward: PIXI.Rectangle }): PIXI.Rectangle => {
const roundLeft = rectangle.left < toward.left ? Math.ceil : Math.floor;
const roundTop = rectangle.top < toward.top ? Math.ceil : Math.floor;
const left = roundLeft(rectangle.left / gridWidth) * gridWidth;
const top = roundTop(rectangle.top / gridWidth) * gridWidth;
const width = Math.ceil(rectangle.width / gridWidth) * gridWidth;
const height = Math.ceil(rectangle.height / gridWidth) * gridWidth;
return new PIXI.Rectangle(left, top, width, height);
};
// Find the minimum distance between the rectangles for each dimension
const r0Snapped = snapBounds(xzPlane.self, { toward: xzPlane.target });
const r1Snapped = snapBounds(xzPlane.target, { toward: xzPlane.self });
distance.dz = Math.max(r0Snapped.top - r1Snapped.bottom, r1Snapped.top - r0Snapped.bottom, 0) + gridWidth;
}
} else {
distance.dz = 0;
}
return measureDistanceOnGrid(distance, { reach });
}
/**
* Measure distance using Pathfinder 2e grid-counting rules
* @param p0 The origin point
* @param p1 The destination point
*/
function measureDistance(p0: Point, p1: Point): number {
if (canvas.grid.type !== CONST.GRID_TYPES.SQUARE) {
return canvas.grid.measurePath([p0, p1]).distance;
}
return measureDistanceOnGrid(new Ray(p0, p1));
}
/**
* Given the distance in each dimension, measure the distance in grid units
* @param segment A pair of x/y distances constituting the line segment between two points
* @param [reach] If this is a reach measurement, the origin actor's reach
*/
function measureDistanceOnGrid(
segment: { dx: number; dy: number; dz?: number | null },
{ reach = null }: { reach?: number | null } = {},
): number {
if (!canvas.dimensions) return NaN;
const gridSize = canvas.dimensions.size;
const gridDistance = canvas.dimensions.distance;
const nx = Math.ceil(Math.abs(segment.dx / gridSize));
const ny = Math.ceil(Math.abs(segment.dy / gridSize));
const nz = Math.ceil(Math.abs((segment.dz || 0) / gridSize));
// ingore the lowest difference
const sortedDistance = [nx, ny, nz].sort((a, b) => a - b);
// Get the number of straight and diagonal moves
const squares = {
doubleDiagonal: sortedDistance[0],
diagonal: sortedDistance[1] - sortedDistance[0],
straight: sortedDistance[2] - sortedDistance[1],
};
// "Unlike with measuring most distances, 10-foot reach can reach 2 squares diagonally." (CRB pg 455)
const reduction = squares.diagonal + squares.doubleDiagonal > 1 && reach === 10 ? 1 : 0;
// Diagonals in PF pretty much count as 1.5 times a straight
// for diagonals across the x, y, and z axis count it as 1.75 as a best guess
const distance = Math.floor(squares.doubleDiagonal * 1.75 + squares.diagonal * 1.5 + squares.straight) - reduction;
return distance * gridDistance;
}
/** Highlight grid according to Pathfinder 2e effect-area shapes */
function highlightGrid({
areaShape,
object,
colors,
document,
snappingMode = CONST.GRID_SNAPPING_MODES.CENTER,
collisionType = "move",
preview = false,
}: HighlightGridParams): void {
// Only highlight for objects that are non-previews (have IDs)
if (!object.id && !preview) return;
const dimensions = canvas.dimensions;
const grid = canvas.interface.grid;
if (!(grid && dimensions)) return;
// Set data defaults
const angle = document.angle ?? 0;
const direction = document.direction ?? 45;
// Clear existing highlight
const highlightLayer = grid.getHighlightLayer(object.highlightId)?.clear();
if (!highlightLayer) return;
const center = canvas.grid.getCenterPoint({ x: document.x, y: document.y });
const { i: col0, j: row0 } = canvas.grid.getOffset({ x: center.x, y: center.y });
const minAngle = (360 + ((direction - angle * 0.5) % 360)) % 360;
const maxAngle = (360 + ((direction + angle * 0.5) % 360)) % 360;
const snappedOrigin = canvas.grid.getSnappedPoint({ x: document.x, y: document.y }, { mode: snappingMode });
const withinAngle = (min: number, max: number, value: number) => {
min = (360 + (min % 360)) % 360;
max = (360 + (max % 360)) % 360;
value = (360 + (value % 360)) % 360;
if (min < max) return value >= min && value <= max;
return value >= min || value <= max;
};
// Offset measurement for cones to ensure that cones only start measuring from cell borders
const coneOriginOffset = ((): Point => {
if (areaShape !== "cone") return { x: 0, y: 0 };
// Degrees anticlockwise from pointing right. In 45-degree increments from 0 to 360
const dir = (direction >= 0 ? 360 - direction : -direction) % 360;
// If we're not on a border for X, offset by 0.5 or -0.5 to the border of the cell in the direction we're looking on X axis
const xOffset =
snappedOrigin.x % dimensions.size !== 0
? Math.sign((1 * Math.round(Math.cos(Math.toRadians(dir)) * 100)) / 100) / 2
: 0;
// Same for Y, but cos Y goes down on screens, we invert
const yOffset =
snappedOrigin.y % dimensions.size !== 0
? -Math.sign((1 * Math.round(Math.sin(Math.toRadians(dir)) * 100)) / 100) / 2
: 0;
return { x: xOffset * dimensions.size, y: yOffset * dimensions.size };
})();
// Point we are measuring distances from
const padding = Math.clamped(document.width ?? 0, 1.5, 2);
const docDistance = document.distance ?? 0;
const padded = (docDistance * padding) / dimensions.distance;
const rowCount = Math.ceil(padded / (dimensions.size / canvas.grid.sizeX));
const columnCount = Math.ceil(padded / (dimensions.size / canvas.grid.sizeY));
// If this is an emanation, measure from the outer squares of the token's space
const offsetEmanationOrigin = (destination: Point): Point => {
if (!(areaShape === "emanation" && object instanceof TokenPF2e)) {
return { x: 0, y: 0 };
}
// No offset is needed for medium and smaller creatures
if (object.w <= dimensions.size) return { x: 0, y: 0 };
const offset = (object.w - dimensions.size) / 2;
const getCoordinate = (centerCoord: number, destCoord: number): number =>
destCoord === centerCoord ? 0 : destCoord > centerCoord ? offset : -offset;
return {
x: getCoordinate(object.center.x, destination.x),
y: getCoordinate(object.center.y, destination.y),
};
};
for (let a = -columnCount; a < columnCount; a++) {
for (let b = -rowCount; b < rowCount; b++) {
// Position of cell's top-left corner, in pixels
const { x: gx, y: gy } = canvas.grid.getTopLeftPoint({ i: col0 + a, j: row0 + b });
// Position of cell's center in pixels
const destination = {
x: gx + dimensions.size * 0.5,
y: gy + dimensions.size * 0.5,
};
if (destination.x < 0 || destination.y < 0) continue;
// Determine point of origin
const emanationOriginOffset = offsetEmanationOrigin(destination);
const origin = {
x: snappedOrigin.x + coneOriginOffset.x + emanationOriginOffset.x,
y: snappedOrigin.y + coneOriginOffset.y + emanationOriginOffset.y,
};
if (areaShape === "cone") {
const ray = new Ray(origin, destination);
const rayAngle = (360 + ((ray.angle / (Math.PI / 180)) % 360)) % 360;
if (ray.distance > 0 && !withinAngle(minAngle, maxAngle, rayAngle)) {
continue;
}
}
// Determine grid-square point to which we're measuring the distance
const distance = measureDistance(destination, origin);
if (distance > docDistance) continue;
const hasCollision =
canvas.ready &&
CONFIG.Canvas.polygonBackends[collisionType].testCollision(origin, destination, {
type: collisionType,
mode: "any",
});
if (hasCollision) {
grid.highlightPosition(highlightLayer.name, {
x: gx,
y: gy,
border: 0x000001,
color: 0x000000,
});
highlightLayer
.beginFill(0x000000, 0.5)
.moveTo(gx, gy)
.lineTo(gx + dimensions.size, gy + dimensions.size)
.endFill();
} else {
grid.highlightPosition(highlightLayer.name, {
x: gx,
y: gy,
border: colors.border,
color: colors.fill,
});
}
}
}
}
interface HighlightGridParams {
areaShape: EffectAreaShape | null;
object: MeasuredTemplatePF2e | TokenPF2e;
/** Border and fill colors in hexadecimal */
colors: { border: number; fill: number };
/** Shape data for the effect area: satisfied by MeasuredTemplateData */
document: Readonly<{
x: number;
y: number;
distance: number | null;
angle?: number;
direction?: number;
width: number | null;
}>;
snappingMode?: number;
collisionType?: WallRestrictionType;
preview?: boolean;
}
export { highlightGrid, measureDistanceCuboid };