Compare commits

..

5 Commits

Author SHA1 Message Date
Manuel Vögele a5de9bbf0a Make the pathfinding demonstration loop 2022-10-14 21:26:30 +02:00
Manuel Vögele 15cda2cdbe Demonstration of pathfinding 2022-10-13 10:21:56 +02:00
Manuel Vögele 709774b25f New assets for 1.7.0 documentation update 2021-05-19 20:56:03 +02:00
Manuel Vögele bb8ac5d1ac Demonstration of TerrainLayer support 2021-03-09 10:06:27 +01:00
Manuel Vögele 5177746fbb Usage graphics for Drag Ruler 2021-02-01 15:36:01 +01:00
16 changed files with 12 additions and 261 deletions
-20
View File
@@ -1,20 +0,0 @@
## v1.1.1
### Bugfixes
- Fixed a bug where tokens wouldn't be moved to the corect end position on gridless maps
- Ruler now appears immediately when the token is being dragged
- On gridless maps the ruler will always start measuring at the center of the token
- This change has no impact on the distance that is being measured
- In addition to the cosmetical aspect this also fixes a bug that allowed players to glitch through walls
## v1.1.0
### New features
- The drag ruler will now be colored for other players than the dragging player as well (only if they have at least observer permissions for that token)
- The drag ruler won't be shown to other players if they cannot see the dragged token
### Bugfixes
- Fixed a bug where Drag Ruler wouldn't work at all on some windows installations (specificially where the `foundry.js` has `CRLF` line endings)
## v1.0.1
### Bugfixes
- The GM can now move tokens through walls
- It is now possible to move multiple tokens with Drag Ruler enabled
-80
View File
@@ -1,80 +0,0 @@
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/staebchenfisch)
# Drag Ruler
This module shows a ruler when you drag a token to infrom you how far you've dragged the token from it's start point. Additionally, if you're using a grid, the spaces the token will travel though will be colored depending on your tokens speed.
## Path color
![Drag Ruler demonstration](https://raw.githubusercontent.com/manuelVo/foundryvtt-drag-ruler/5177746fbb4edb28b6ba09137247d142af575c47/media/drag_ruler.webp)
The token has a speed of 30ft. All squares on the path within that range are colored in the players color. If the token is running it can cover double that range (this can be changed in the settings). All Squares on the path that can only be reached while running are colored in yellow. Squares on the path that the token cannot possibly reached at regular speeds are colored red. This coloring behavior can be tweaked in the settings and can be overridden by modules and game systems to provide more granular, game system specific control. For more information on how to do this see the [API](#api) section of this document.
## Waypoints
You can add waypoints to the path by pressing spacebar while you drag the token. To remove a placed waypoint press the right mouse button.
![Demonstration of Waypoints](https://raw.githubusercontent.com/manuelVo/foundryvtt-drag-ruler/5177746fbb4edb28b6ba09137247d142af575c47/media/waypoints.webp)
## Why would I want to use this instead of ShowDragDistance?
ShowDragDistance isn't maintained anymore. This means that it is at risk to stop working with every foundry update. In fact this process has already begun. As of Foundry Version 0.7.9 ShowDragDistance doesn't work anymore on gridless maps. Drag Ruler on the other hand is fully compatible with the current Foundry release and I'll continue updating it for future foundry releases for the forseeable future.
In addition Drag Ruler provides more flexibility for game systems and modules via it's api to provide an experience that fits the rules of the game system that you are playing best.
## API
*Audience: This paragraph is intended for module and system devleopers that want to add more complex behavior to Drag Ruler. If you just want to use this plugins features skip this paragraph.*
The path coloring behavior of Drag Ruler can be altered by modules and systems to allow for for more complex coloring than provided by default. This allows specifying custom colors, using more different colors than offered by default and performing more calculations for determining the colors (for example a token may only be allowd to run if it isn't waring armor). Doing so is simple. This paragraph gives a short introduction on how to accomplish this, followed by a full example of how a call to the api might look like.
### Registering your Module/System
*This section is written from the perspective of a module developer. If you're writing a game system the process is exactly the same, except that you need to invoke `registerSystem` instead of `registerModule` and need to use the id of your system instead of a module id.*
The first thing you'll have to do is to make your module known to Drag Ruler. To do this, you have to call the `dragRuler.registerModule` function after the `dragRuler.ready` hook has fired. This might look like this:
```javascript
Hooks.once("dragRuler.ready", () => {
dragRuler.registerModule("id-of-your-module", mySpeedProvider)
})
```
The function `registerModule` takes two parameters: The first parameter must be the ID of your module as specified in your manifest. The second parameter is a reference to the Speed Provider of your module. What that Speed Provider looks like will be detailed in the paragraph [Writing the Speed Provider](#writing-the-speed-provider)
### Writing the Speed Provider
The Speed Provider is a function that calculates the speeds that a token can reach and assigns a color to each of the speeds. That function receives two arguments. The first argument is the token for which the speed should be calculated. The second argument is the color of the player that is dragging the token.
The function should contain an array of objects in the format `{range: Integer, color: Integer}`. The range indicates a distance that the token can cover with a certain speed and the color indicates which color should be used for that range. Spaces that cannot be reached with any of the speeds provided by this function will be colored in red (`0xFF0000`). The returned array doesn't need to be sorted in any particular order. However the array is not allowe to contain two objects with an identical range, as that results in undefined behavior.
The Speed Provider will be called once for each square that will be colored. For this reason it is advisable to not perform any expensive calculations in the Speed Provider.
Here is an example of how a Speed Provider might look like:
```javascript
function mySpeedProvider(token, playerColor) {
const baseSpeed = token.actor.data.speed
const ranges = [{range: baseSpeed, color: playerColor}, {range: baseSpeed * 2, color: 0xFFFF00}]
if (!token.actor.data.isWearingArmor) {
ranges.push({range: baseSpeed * 3, color: 0xFF8000})
}
return ranges
}
```
With this speed provider, the fields reachable with the token's base speed will be colored in the color of the player that is dragging the token. Each token is able to dash, which allows it to run twice it's base speed. Spaces that are reachable by dashing will be colored yellow (`0xFFFF00`). If the token isn't wearing any armor it is also allowed to sprint, allowing it to cover a distance of 3 times it's base speed. Those squares will be colored in orange (`0xFF8000`). All spaces further away from the token will be colored in red. Tokens wearing armor aren't allowed to sprint and for them all spaces that exceed 2 times their base speed will be colored red.
### Full example
This is a full example of how using the api might look like. It's built from the examples above. For a explanation to what is going on refer to the previous chapters.
```javascript
Hooks.once("dragRuler.ready", () => {
dragRuler.registerModule("id-of-your-module", mySpeedProvider)
})
function mySpeedProvider(token, playerColor) {
const baseSpeed = token.actor.data.speed
const ranges = [{range: baseSpeed, color: playerColor}, {range: baseSpeed * 2, color: 0xFFFF00}]
if (!token.actor.data.isWearingArmor) {
ranges.push({range: baseSpeed * 3, color: 0xFF8000})
}
return ranges
}
```
-4
View File
@@ -1,10 +1,6 @@
{ {
"drag-ruler": { "drag-ruler": {
"settings": { "settings": {
"alwaysShowSpeedForPCs": {
"name": "Show PC speed to everyone",
"hint": "If enabled the coloring based on actor speed for player characters will shown to everyone, even if they don't have observer permission for the character sheet."
},
"dashMultiplier": { "dashMultiplier": {
"name": "Dash Multiplier", "name": "Dash Multiplier",
"hint": "This can be used to give tokens a secondary speed during coloring of the measured path. Set it to 0 to disable the secondary speed." "hint": "This can be used to give tokens a secondary speed during coloring of the measured path. Set it to 0 to disable the secondary speed."
Binary file not shown.

After

Width:  |  Height:  |  Size: 689 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 775 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 603 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 503 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

+2 -3
View File
@@ -2,7 +2,7 @@
"name": "drag-ruler", "name": "drag-ruler",
"title": "Drag Ruler", "title": "Drag Ruler",
"description": "When dragging a token displays a ruler showing how far you've moved that token.", "description": "When dragging a token displays a ruler showing how far you've moved that token.",
"version": "1.1.1", "version": "0.0.1",
"minimumCoreVersion" : "0.7.9", "minimumCoreVersion" : "0.7.9",
"compatibleCoreVersion" : "0.7.9", "compatibleCoreVersion" : "0.7.9",
"authors": [ "authors": [
@@ -23,9 +23,8 @@
} }
], ],
"url": "https://github.com/manuelVo/foundryvtt-drag-ruler", "url": "https://github.com/manuelVo/foundryvtt-drag-ruler",
"download": "https://github.com/manuelVo/foundryvtt-drag-ruler/archive/v1.1.1.zip", "download": "https://github.com/manuelVo/foundryvtt-drag-ruler/archive/master.zip",
"manifest": "https://raw.githubusercontent.com/manuelVo/foundryvtt-drag-ruler/master/module.json", "manifest": "https://raw.githubusercontent.com/manuelVo/foundryvtt-drag-ruler/master/module.json",
"readme": "https://github.com/manuelVo/foundryvtt-drag-ruler/blob/master/README.md", "readme": "https://github.com/manuelVo/foundryvtt-drag-ruler/blob/master/README.md",
"changelog": "https://github.com/manuelVo/foundryvtt-drag-ruler/blob/master/CHANGELOG.md",
"bugs": "https://github.com/manuelVo/foundryvtt-drag-ruler/issues" "bugs": "https://github.com/manuelVo/foundryvtt-drag-ruler/issues"
} }
-97
View File
@@ -1,97 +0,0 @@
// This is a modified version of Ruler.moveToken from foundry 0.7.9
export async function moveTokens(selectedTokens) {
let wasPaused = game.paused;
if (wasPaused && !game.user.isGM) {
ui.notifications.warn(game.i18n.localize("GAME.PausedWarning"));
return false;
}
if (!this.visible || !this.destination) return false;
const draggedToken = this._getMovementToken();
if (!draggedToken) return;
// Get the movement rays and check collision along each Ray
// These rays are center-to-center for the purposes of collision checking
const rays = this._getRaysFromWaypoints(this.waypoints, this.destination);
if (!game.user.isGM) {
const hasCollision = selectedTokens.some(token => {
const offset = calculateTokenOffset(token, draggedToken)
const offsetRays = rays.map(ray => applyOffsetToRay(ray, offset))
return offsetRays.some(r => canvas.walls.checkCollision(r));
})
if (hasCollision) {
ui.notifications.error(game.i18n.localize("ERROR.TokenCollide"));
this._endMeasurement();
return true;
}
}
// Execute the movement path.
// Transform each center-to-center ray into a top-left to top-left ray using the prior token offsets.
this._state = Ruler.STATES.MOVING;
await Promise.all(selectedTokens.map(token => {
// Return the promise so we can wait for it outside the loop
const offset = calculateTokenOffset(token, draggedToken)
return animateToken.call(this, token, rays, offset, wasPaused)
}))
// Once all animations are complete we can clear the ruler
this._endMeasurement();
}
// This is a modified version code extracted from Ruler.moveToken from foundry 0.7.9
async function animateToken(token, rays, tokenOffset, wasPaused) {
const offsetRays = rays.map(ray => applyOffsetToRay(ray, tokenOffset))
// Determine offset relative to the Token top-left.
// This is important so we can position the token relative to the ruler origin for non-1x1 tokens.
origin = canvas.grid.getTopLeft(this.waypoints[0].x + tokenOffset.x, this.waypoints[0].y + tokenOffset.y);
let dx, dy
if (canvas.grid.type === CONST.GRID_TYPES.GRIDLESS) {
dx = token.data.x - origin[0]
dy = token.data.y - origin[1]
}
else {
const s2 = canvas.dimensions.size / 2;
dx = Math.round((token.data.x - origin[0]) / s2) * s2;
dy = Math.round((token.data.y - origin[1]) / s2) * s2;
}
token._noAnimate = true;
for (let r of offsetRays) {
if (!wasPaused && game.paused) break;
const dest = canvas.grid.getTopLeft(r.B.x, r.B.y);
const path = new Ray({ x: token.x, y: token.y }, { x: dest[0] + dx, y: dest[1] + dy });
await token.update(path.B);
await token.animateMovement(path);
}
token._noAnimate = false;
}
function calculateTokenOffset(tokenA, tokenB) {
return {x: tokenA.data.x - tokenB.data.x, y: tokenA.data.y - tokenB.data.y}
}
function applyOffsetToRay(ray, offset) {
return new Ray({x: ray.A.x + offset.x, y: ray.A.y + offset.y}, {x: ray.B.x + offset.x, y: ray.B.y + offset.y})
}
// This is a modified version of Ruler._onMouseMove from foundry 0.7.9
export function onMouseMove(event) {
if (this._state === Ruler.STATES.MOVING) return;
// Extract event data
const mt = event._measureTime || 0;
const originalEvent = event.data.originalEvent;
const destination = {x: event.data.destination.x + this.rulerOffset.x, y: event.data.destination.y + this.rulerOffset.y}
// Hide any existing Token HUD
canvas.hud.token.clear();
delete event.data.hudState;
// Draw measurement updates
if (Date.now() - mt > 50) {
this.measure(destination, { gridSpaces: !originalEvent.shiftKey });
event._measureTime = Date.now();
this._state = Ruler.STATES.MEASURING;
}
}
+10 -48
View File
@@ -1,13 +1,12 @@
"use strict" "use strict"
import {availableSpeedProviders, currentSpeedProvider, registerModule, registerSystem, setCurrentSpeedProvider} from "./api.js" import {availableSpeedProviders, currentSpeedProvider, registerModule, registerSystem, setCurrentSpeedProvider} from "./api.js"
import {moveTokens, onMouseMove} from "./foundry_imports.js"
import {registerSettings, settingsKey} from "./settings.js" import {registerSettings, settingsKey} from "./settings.js"
Hooks.once("init", () => { Hooks.once("init", () => {
registerSettings() registerSettings()
hookTokenDragHandlers() hookTokenDragHandlers()
hookRulerFunctions() hookRulerHandlers()
patchRulerMeasure() patchRulerMeasure()
patchRulerHighlightMeasurement() patchRulerHighlightMeasurement()
@@ -27,13 +26,11 @@ Hooks.once("ready", () => {
}) })
Hooks.on("canvasReady", () => { Hooks.on("canvasReady", () => {
canvas.controls.rulers.children.forEach(ruler => { canvas.controls.ruler.draggedToken = null
ruler.draggedToken = null Object.defineProperty(canvas.controls.ruler, "isDragRuler", {
Object.defineProperty(ruler, "isDragRuler", { get: function isDragRuler() {
get: function isDragRuler() { return Boolean(this.draggedToken) // If draggedToken is set this is a drag ruler
return Boolean(this.draggedToken) // If draggedToken is set this is a drag ruler }
}
})
}) })
}) })
@@ -65,7 +62,7 @@ function hookTokenDragHandlers() {
} }
} }
function hookRulerFunctions() { function hookRulerHandlers() {
const originalMoveTokenHandler = Ruler.prototype.moveToken const originalMoveTokenHandler = Ruler.prototype.moveToken
Ruler.prototype.moveToken = function (event) { Ruler.prototype.moveToken = function (event) {
const eventHandled = onRulerMoveToken.call(this, event) const eventHandled = onRulerMoveToken.call(this, event)
@@ -73,44 +70,23 @@ function hookRulerFunctions() {
return originalMoveTokenHandler.call(this, event) return originalMoveTokenHandler.call(this, event)
return true return true
} }
const originalToJSON = Ruler.prototype.toJSON
Ruler.prototype.toJSON = function () {
const json = originalToJSON.call(this)
if (this.draggedToken)
json["draggedToken"] = this.draggedToken.data._id
return json
}
const originalUpdate = Ruler.prototype.update
Ruler.prototype.update = function (data) {
if (data.draggedToken) {
this.draggedToken = canvas.tokens.get(data.draggedToken)
}
originalUpdate.call(this, data)
}
} }
function onTokenLeftDragStart(event) { function onTokenLeftDragStart(event) {
canvas.controls.ruler._onDragStart(event)
canvas.controls.ruler.draggedToken = this canvas.controls.ruler.draggedToken = this
const tokenCenter = {x: this.x + canvas.grid.size / 2, y: this.y + canvas.grid.size / 2}
canvas.controls.ruler.clear();
canvas.controls.ruler._state = Ruler.STATES.STARTING;
canvas.controls.ruler.rulerOffset = {x: tokenCenter.x - event.data.origin.x, y: tokenCenter.y - event.data.origin.y}
canvas.controls.ruler._addWaypoint(tokenCenter);
} }
function onTokenLeftDragMove(event) { function onTokenLeftDragMove(event) {
if (canvas.controls.ruler.isDragRuler) if (canvas.controls.ruler.isDragRuler)
onMouseMove.call(canvas.controls.ruler, event) canvas.controls.ruler._onMouseMove(event)
} }
function onTokenDragLeftDrop(event) { function onTokenDragLeftDrop(event) {
if (!canvas.controls.ruler.isDragRuler) if (!canvas.controls.ruler.isDragRuler)
return false return false
canvas.controls.ruler.draggedToken = null canvas.controls.ruler.draggedToken = null
const selectedTokens = canvas.tokens.placeables.filter(token => token._controlled) canvas.controls.ruler.moveToken(event)
moveTokens.call(canvas.controls.ruler, selectedTokens)
return true return true
} }
@@ -147,16 +123,10 @@ function strInsertAfter(haystack, needle, strToInsert) {
// These patches were written with foundry-0.7.9.js as reference // These patches were written with foundry-0.7.9.js as reference
function patchRulerMeasure() { function patchRulerMeasure() {
let code = Ruler.prototype.measure.toString() let code = Ruler.prototype.measure.toString()
// Replace CRLF with LF in case foundry.js has CRLF for some reason
code = code.replace(/\r\n/g, "\n")
// Remove function signature and closing curly bracket (those are on the first and last line) // Remove function signature and closing curly bracket (those are on the first and last line)
code = code.slice(code.indexOf("\n"), code.lastIndexOf("\n")) code = code.slice(code.indexOf("\n"), code.lastIndexOf("\n"))
code = strInsertAfter(code, "for ( let [i, d] of distances.entries() ) {\n", "segments[i].startDistance = totalDistance\n") code = strInsertAfter(code, "for ( let [i, d] of distances.entries() ) {\n", "segments[i].startDistance = totalDistance\n")
code = strInsertAfter(code, "this._highlightMeasurement(ray", ", s.startDistance") code = strInsertAfter(code, "this._highlightMeasurement(ray", ", s.startDistance")
// Don't show ruler if the measured token is invisible
code = "if (this.isDragRuler && !this.draggedToken.isVisible) return [];" + code
Ruler.prototype.measure = new Function("destination", "{gridSpaces=true}={}", code) Ruler.prototype.measure = new Function("destination", "{gridSpaces=true}={}", code)
} }
@@ -178,12 +148,6 @@ function nativeSpeedProvider(token, playercolor) {
function getColorForDistance(startDistance, subDistance) { function getColorForDistance(startDistance, subDistance) {
if (!this.isDragRuler) if (!this.isDragRuler)
return this.color return this.color
// Don't apply colors if the current user doesn't have at least observer permissions
if (this.draggedToken.actor.permission < 2) {
// If this is a pc and alwaysShowSpeedForPCs is enabled we show the color anyway
if (!(this.draggedToken.actor.data.type === "character" && game.settings.get(settingsKey, "alwaysShowSpeedForPCs")))
return this.color
}
const distance = startDistance + subDistance const distance = startDistance + subDistance
const ranges = currentSpeedProvider(this.draggedToken, this.color) const ranges = currentSpeedProvider(this.draggedToken, this.color)
if (ranges.length === 0) if (ranges.length === 0)
@@ -199,8 +163,6 @@ function getColorForDistance(startDistance, subDistance) {
// These patches were written with foundry-0.7.9.js as reference // These patches were written with foundry-0.7.9.js as reference
function patchRulerHighlightMeasurement() { function patchRulerHighlightMeasurement() {
let code = Ruler.prototype._highlightMeasurement.toString() let code = Ruler.prototype._highlightMeasurement.toString()
// Replace CRLF with LF in case foundry.js has CRLF for some reason
code = code.replace(/\r\n/g, "\n")
// Remove function signature and closing curly bracket (those are on the first and last line) // Remove function signature and closing curly bracket (those are on the first and last line)
code = code.slice(code.indexOf("\n"), code.lastIndexOf("\n")) code = code.slice(code.indexOf("\n"), code.lastIndexOf("\n"))
-9
View File
@@ -4,15 +4,6 @@ import {getDefaultDashMultiplier, getDefaultSpeedAttribute} from "./systems.js"
export const settingsKey = "drag-ruler"; export const settingsKey = "drag-ruler";
export function registerSettings() { export function registerSettings() {
game.settings.register(settingsKey, "alwaysShowSpeedForPCs", {
name: "drag-ruler.settings.alwaysShowSpeedForPCs.name",
hint: "drag-ruler.settings.alwaysShowSpeedForPCs.hint",
scope: "world",
config: true,
type: Boolean,
default: true,
})
// This setting will be modified by the api if modules register to it // This setting will be modified by the api if modules register to it
game.settings.register(settingsKey, "speedProvider", { game.settings.register(settingsKey, "speedProvider", {
name: "drag-ruler.settings.speedProvider.name", name: "drag-ruler.settings.speedProvider.name",