fvtt-hero-system-6/modules/hero6-utility.js

587 lines
18 KiB
JavaScript
Raw Normal View History

2022-12-15 21:44:23 +01:00
/* -------------------------------------------- */
import { Hero6Combat } from "./hero6-combat.js";
import { Hero6Commands } from "./hero6-commands.js";
/* -------------------------------------------- */
const __locationNames = { head: "Head", chest: "Chest", abdomen: "Abdomen", leftarm: "Left Arm", rightarm: "Right Arm", leftleg: "Left Leg", rightleg: "Right Leg" }
/* -------------------------------------------- */
export class Hero6Utility {
/* -------------------------------------------- */
static async init() {
Hooks.on('renderChatLog', (log, html, data) => Hero6Utility.chatListeners(html));
/*Hooks.on("dropCanvasData", (canvas, data) => {
Hero6Utility.dropItemOnToken(canvas, data)
});*/
Handlebars.registerHelper('count', function (list) {
return list.length;
})
2023-03-24 10:17:20 +01:00
Handlebars.registerHelper('exists', function (val) {
return val != null && val != undefined;
2023-03-28 15:41:15 +02:00
});
2022-12-15 21:44:23 +01:00
Handlebars.registerHelper('includes', function (array, val) {
return array.includes(val);
})
Handlebars.registerHelper('upper', function (text) {
2023-03-28 15:41:15 +02:00
if (text) {
2023-02-01 12:16:04 +01:00
return text.toUpperCase();
}
return text
2022-12-15 21:44:23 +01:00
})
Handlebars.registerHelper('lower', function (text) {
return text.toLowerCase()
})
Handlebars.registerHelper('upperFirst', function (text) {
if (typeof text !== 'string') return text
return text.charAt(0).toUpperCase() + text.slice(1)
})
Handlebars.registerHelper('notEmpty', function (list) {
return list.length > 0;
})
Handlebars.registerHelper('mul', function (a, b) {
2023-06-30 13:14:40 +02:00
return Number(a) * Number(b);
2022-12-15 21:44:23 +01:00
})
Handlebars.registerHelper('locationLabel', function (key) {
2023-03-28 15:41:15 +02:00
return __locationNames[key]
2022-12-28 10:30:56 +01:00
})
Handlebars.registerHelper('isSkillCustom', function (key) {
2023-03-28 15:41:15 +02:00
if (key == "custom") {
2022-12-28 10:30:56 +01:00
return true;
}
return false
2023-03-28 15:41:15 +02:00
})
2023-08-24 20:32:00 +02:00
Handlebars.registerHelper('fixNum', function (value) {
return Number(value) || 0
})
2023-06-30 21:11:29 +02:00
Handlebars.registerHelper('checkInit', function (value) {
let myValue = Number(value) || 0
return myValue > 0
})
2022-12-15 21:44:23 +01:00
this.gameSettings()
}
/*-------------------------------------------- */
static gameSettings() {
/*game.settings.register("fvtt-hero-system-6", "dice-color-skill", {
name: "Dice color for skills",
hint: "Set the dice color for skills",
scope: "world",
config: true,
requiresReload: true ,
default: "#101010",
type: String
})
Hooks.on('renderSettingsConfig', (event) => {
const element = event.element[0].querySelector(`[name='fvtt-hero-system-6.dice-color-skill']`)
if (!element) return
// Replace placeholder element
console.log("Element Found !!!!")
}) */
}
2023-03-22 22:43:30 +01:00
/*-------------------------------------------- */
2023-03-24 10:17:20 +01:00
static getDerivatedDiceFormulas(value) {
2023-03-28 15:41:15 +02:00
let rollFormula = Math.floor(value / 5) + "d6"
let displayFormula = Math.floor(value / 5)
if (value % 5 > 2) {
2023-03-24 10:17:20 +01:00
rollFormula += "+round(1d6/2)"
displayFormula += " 1/2d6"
} else {
displayFormula += "d6"
2023-03-22 22:43:30 +01:00
}
2023-03-28 15:41:15 +02:00
return { rollFormula: rollFormula, displayFormula: displayFormula }
2023-03-22 22:43:30 +01:00
}
2022-12-15 21:44:23 +01:00
/*-------------------------------------------- */
static upperFirst(text) {
if (typeof text !== 'string') return text
return text.charAt(0).toUpperCase() + text.slice(1)
}
/*-------------------------------------------- */
static getSkills() {
return duplicate(this.skills)
}
/*-------------------------------------------- */
static getWeaponSkills() {
return duplicate(this.weaponSkills)
}
/*-------------------------------------------- */
static getShieldSkills() {
return duplicate(this.shieldSkills)
}
/* -------------------------------------------- */
static async ready() {
const skills = await Hero6Utility.loadCompendium("fvtt-hero-system-6.skills")
this.skills = skills.map(i => i.toObject())
this.weaponSkills = duplicate(this.skills.filter(item => item.system.isweaponskill))
this.shieldSkills = duplicate(this.skills.filter(item => item.system.isshieldskill))
const rollTables = await Hero6Utility.loadCompendium("fvtt-hero-system-6.rolltables")
this.rollTables = rollTables.map(i => i.toObject())
2023-08-07 23:28:04 +02:00
for (let actor of game.actors) {
actor.performMigration()
}
2022-12-15 21:44:23 +01:00
}
/* -------------------------------------------- */
static async loadCompendiumData(compendium) {
const pack = game.packs.get(compendium)
return await pack?.getDocuments() ?? []
}
/* -------------------------------------------- */
static async loadCompendium(compendium, filter = item => true) {
let compendiumData = await Hero6Utility.loadCompendiumData(compendium)
return compendiumData.filter(filter)
}
/* -------------------------------------------- */
static async chatListeners(html) {
html.on("click", '.view-item-from-chat', event => {
game.system.crucible.creator.openItemView(event)
})
}
/* -------------------------------------------- */
static async preloadHandlebarsTemplates() {
const templatePaths = [
'systems/fvtt-hero-system-6/templates/partials/editor-notes-gm.hbs',
'systems/fvtt-hero-system-6/templates/partials/partial-roll-select.hbs',
2023-02-01 12:16:04 +01:00
'systems/fvtt-hero-system-6/templates/partials/partial-actor-characteristic-block.hbs',
2023-02-14 15:34:37 +01:00
'systems/fvtt-hero-system-6/templates/partials/partial-actor-full-charac.hbs',
2022-12-15 21:44:23 +01:00
'systems/fvtt-hero-system-6/templates/partials/partial-actor-status.hbs',
'systems/fvtt-hero-system-6/templates/partials/partial-options-abilities.hbs',
'systems/fvtt-hero-system-6/templates/partials/partial-item-nav.hbs',
'systems/fvtt-hero-system-6/templates/partials/partial-item-description.hbs',
2023-08-15 22:12:02 +02:00
'systems/fvtt-hero-system-6/templates/partials/partial-item-notes.hbs',
2022-12-28 10:30:56 +01:00
'systems/fvtt-hero-system-6/templates/partials/partial-actor-equipment.hbs',
'systems/fvtt-hero-system-6/templates/partials/partial-item-cost.hbs',
'systems/fvtt-hero-system-6/templates/partials/partial-power-equipment-cost.hbs',
2023-01-04 22:43:01 +01:00
'systems/fvtt-hero-system-6/templates/partials/partial-item-hasroll.hbs',
2023-02-21 20:22:08 +01:00
'systems/fvtt-hero-system-6/templates/partials/partial-actor-equipment.hbs',
2023-04-06 16:57:19 +02:00
'systems/fvtt-hero-system-6/templates/partials/partial-actor-equipment-section.hbs',
'systems/fvtt-hero-system-6/templates/partials/partial-power-maneuver-effect.hbs'
2022-12-15 21:44:23 +01:00
]
return loadTemplates(templatePaths);
}
/* -------------------------------------------- */
static removeChatMessageId(messageId) {
if (messageId) {
game.messages.get(messageId)?.delete();
}
}
static findChatMessageId(current) {
return Hero6Utility.getChatMessageId(Hero6Utility.findChatMessage(current));
}
static getChatMessageId(node) {
return node?.attributes.getNamedItem('data-message-id')?.value;
}
static findChatMessage(current) {
return Hero6Utility.findNodeMatching(current, it => it.classList.contains('chat-message') && it.attributes.getNamedItem('data-message-id'));
}
static findNodeMatching(current, predicate) {
if (current) {
if (predicate(current)) {
return current;
}
return Hero6Utility.findNodeMatching(current.parentElement, predicate);
}
return undefined;
}
/* -------------------------------------------- */
static createDirectOptionList(min, max) {
let options = {};
for (let i = min; i <= max; i++) {
options[`${i}`] = `${i}`;
}
return options;
}
/* -------------------------------------------- */
static buildListOptions(min, max) {
let options = ""
for (let i = min; i <= max; i++) {
options += `<option value="${i}">${i}</option>`
}
return options;
}
/* -------------------------------------------- */
static getTarget() {
if (game.user.targets) {
for (let target of game.user.targets) {
return target
}
}
return undefined
}
/* -------------------------------------------- */
static async onSocketMesssage(msg) {
2023-08-07 23:28:04 +02:00
console.log("SOCKET MESSAGE", msg.name, msg)
2022-12-15 21:44:23 +01:00
if (msg.name == "msg_update_roll") {
this.updateRollData(msg.data)
}
2023-08-07 23:28:04 +02:00
if (msg.name == "msg_force_hold") {
if (game.user.isGM) {
let actor = game.actors.get(msg.data.actorId)
game.combat.forceHold(actor, msg.data.isHold)
}
}
if (msg.name == "msg_force_abort") {
if (game.user.isGM) {
let actor = game.actors.get(msg.data.actorId)
game.combat.forceAbort(actor, msg.data.isAbort)
}
2022-12-15 21:44:23 +01:00
}
if (msg.name == "msg_gm_item_drop" && game.user.isGM) {
let actor = game.actors.get(msg.data.actorId)
let item
if (msg.data.isPack) {
item = await fromUuid("Compendium." + msg.data.isPack + "." + msg.data.itemId)
} else {
item = game.items.get(msg.data.itemId)
}
this.addItemDropToActor(actor, item)
}
}
/* -------------------------------------------- */
static chatDataSetup(content, modeOverride, isRoll = false, forceWhisper) {
let chatData = {
user: game.user.id,
rollMode: modeOverride || game.settings.get("core", "rollMode"),
content: content
};
if (["gmroll", "blindroll"].includes(chatData.rollMode)) chatData["whisper"] = ChatMessage.getWhisperRecipients("GM").map(u => u.id);
if (chatData.rollMode === "blindroll") chatData["blind"] = true;
else if (chatData.rollMode === "selfroll") chatData["whisper"] = [game.user];
if (forceWhisper) { // Final force !
chatData["speaker"] = ChatMessage.getSpeaker();
chatData["whisper"] = ChatMessage.getWhisperRecipients(forceWhisper);
}
return chatData;
}
/* -------------------------------------------- */
static async showDiceSoNice(roll, rollMode) {
if (game.modules.get("dice-so-nice")?.active) {
if (game.dice3d) {
let whisper = null;
let blind = false;
rollMode = rollMode ?? game.settings.get("core", "rollMode");
switch (rollMode) {
case "blindroll": //GM only
blind = true;
case "gmroll": //GM + rolling player
whisper = this.getUsers(user => user.isGM);
break;
case "roll": //everybody
whisper = this.getUsers(user => user.active);
break;
case "selfroll":
whisper = [game.user.id];
break;
}
await game.dice3d.showForRoll(roll, game.user, true, whisper, blind);
}
}
}
2023-03-28 15:41:15 +02:00
/* -------------- ----------------------------- */
static computeBodyValue(roll) {
let bodyValue = 0
for (let term of roll.terms) {
if (term.constructor.name == "Die") {
for (let value of term.values) {
if (value > 1) {
bodyValue += 1
}
if (value == 6) {
bodyValue += 1
}
}
}
if (term.constructor.name == "NumericTerm") {
if (term.total > 1) {
bodyValue += 1
}
if (term.total == 6) {
bodyValue += 1
}
}
}
return bodyValue
}
2022-12-15 21:44:23 +01:00
/* -------------------------------------------- */
static async rollHero6(rollData) {
let actor = game.actors.get(rollData.actorId)
// ability/save/size => 0
2023-03-28 15:41:15 +02:00
let diceFormula = "3d6"
2023-02-01 12:16:04 +01:00
let target = 10
2023-08-25 23:00:21 +02:00
if(rollData.weapon) {
target = rollData.weaponRoll
}
if(rollData.maneuver) {
target = rollData.maneuverRoll
}
2023-08-26 05:14:08 +02:00
if(rollData.power) {
target = rollData.powerRoll
}
2023-02-01 12:16:04 +01:00
if (rollData.charac) {
target = rollData.charac.roll
2022-12-15 21:44:23 +01:00
}
2023-02-14 15:34:37 +01:00
if (rollData.item) {
2023-03-14 19:23:19 +01:00
target = rollData.item.roll || rollData.item.system.roll
2023-02-14 15:34:37 +01:00
}
2023-03-21 14:01:27 +01:00
target += rollData.bonusMalus
2023-03-28 15:41:15 +02:00
2022-12-15 21:44:23 +01:00
// Performs roll
console.log("Roll formula", diceFormula)
let myRoll = rollData.roll
if (!myRoll) { // New rolls only of no rerolls
myRoll = new Roll(diceFormula).roll({ async: false })
2023-08-09 18:05:16 +02:00
//await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
2022-12-15 21:44:23 +01:00
}
2023-03-28 15:41:15 +02:00
2022-12-15 21:44:23 +01:00
rollData.roll = myRoll
2023-02-01 12:16:04 +01:00
rollData.target = target
rollData.diceFormula = diceFormula
rollData.result = myRoll.total
rollData.isSuccess = false
if (rollData.result <= target) {
rollData.isSuccess = true
2022-12-15 21:44:23 +01:00
}
2023-03-28 15:41:15 +02:00
if (myRoll.terms[0].total == 3) { // Always a success
2023-02-01 12:16:04 +01:00
rollData.isSuccess = true
2022-12-15 21:44:23 +01:00
}
2023-03-28 15:41:15 +02:00
if (myRoll.terms[0].total == 18) { // Always a failure
2023-02-01 12:16:04 +01:00
rollData.isSuccess = false
2022-12-15 21:44:23 +01:00
}
2023-03-14 19:23:19 +01:00
rollData.margin = target - rollData.result
2022-12-15 21:44:23 +01:00
2023-03-24 10:17:20 +01:00
this.outputRollMessage(rollData)
}
/* -------------- ----------------------------- */
2023-03-28 15:41:15 +02:00
static processDirectRoll(rollData) {
let roll = new Roll(rollData.rollFormula).roll({ async: false })
2023-03-24 10:17:20 +01:00
rollData.roll = roll
rollData.result = roll.total
2023-05-07 14:03:14 +02:00
rollData.bodyValue = this.computeBodyValue(rollData.roll)
2023-03-24 10:17:20 +01:00
this.outputRollMessage(rollData).catch(function() { ui.notifications.warn("Error during message output.") })
2023-03-24 10:17:20 +01:00
}
/* -------------- ----------------------------- */
static async outputRollMessage(rollData) {
let msgFlavor = await renderTemplate(`systems/fvtt-hero-system-6/templates/chat/chat-generic-result.hbs`, rollData)
let msg = await rollData.roll.toMessage({
user: game.user.id,
rollMode: game.settings.get("core", "rollMode"),
flavor: msgFlavor
2022-12-15 21:44:23 +01:00
})
rollData.roll = duplicate(rollData.roll) // Convert to object
2023-02-01 12:16:04 +01:00
msg.setFlag("world", "rolldata", rollData)
2022-12-15 21:44:23 +01:00
console.log("Rolldata result", rollData)
}
2023-05-07 14:03:14 +02:00
/* -------------- ----------------------------- */
static convertRollHeroSyntax(hero6Formula) {
2023-05-07 14:03:14 +02:00
// Ensure we have no space at all
//hero6Formula = hero6Formula.replace(/\s/g, '')
let hasHalfDice = ""
2023-06-30 17:21:11 +02:00
let newFormula = hero6Formula
let form1 = hero6Formula.match(/\s*(\d*)\s*1\/2d6/)
if ( form1 ) {
let nbDice = form1[1] || 0
newFormula = nbDice+"d6+round(1d6/2)"
2023-06-30 13:14:40 +02:00
}
2023-06-30 17:21:11 +02:00
let form3 = hero6Formula.match(/\s*(\d*)\.5d6/)
if ( form3 ) {
let nbDice = form3[1] || 0
newFormula = nbDice+"d6+round(1d6/2)"
2023-05-07 14:03:14 +02:00
}
2023-06-30 17:21:11 +02:00
console.log("Parsed formula : ", hero6Formula, newFormula)
return newFormula
2023-05-07 14:03:14 +02:00
}
2023-03-24 10:17:20 +01:00
/* -------------- ----------------------------- */
2022-12-15 21:44:23 +01:00
static sortArrayObjectsByName(myArray) {
myArray.sort((a, b) => {
let fa = a.name.toLowerCase();
let fb = b.name.toLowerCase();
if (fa < fb) {
return -1;
}
if (fa > fb) {
return 1;
}
return 0;
})
}
/* -------------------------------------------- */
static getUsers(filter) {
return game.users.filter(filter).map(user => user.id);
}
/* -------------------------------------------- */
static getWhisperRecipients(rollMode, name) {
switch (rollMode) {
case "blindroll": return this.getUsers(user => user.isGM);
case "gmroll": return this.getWhisperRecipientsAndGMs(name);
case "selfroll": return [game.user.id];
}
return undefined;
}
/* -------------------------------------------- */
static getWhisperRecipientsAndGMs(name) {
let recep1 = ChatMessage.getWhisperRecipients(name) || [];
return recep1.concat(ChatMessage.getWhisperRecipients('GM'));
}
/* -------------------------------------------- */
static blindMessageToGM(chatOptions) {
let chatGM = duplicate(chatOptions);
chatGM.whisper = this.getUsers(user => user.isGM);
chatGM.content = "Blind message of " + game.user.name + "<br>" + chatOptions.content;
2022-12-15 21:44:23 +01:00
console.log("blindMessageToGM", chatGM);
game.socket.emit("system.fvtt-hero-system-6", { msg: "msg_gm_chat_message", data: chatGM });
}
/* -------------------------------------------- */
static async searchItem(dataItem) {
let item
if (dataItem.pack) {
item = await fromUuid("Compendium." + dataItem.pack + "." + dataItem.id)
} else {
item = game.items.get(dataItem.id)
}
return item
}
/* -------------------------------------------- */
static split3Columns(data) {
let array = [[], [], []];
if (data == undefined) return array;
let col = 0;
for (let key in data) {
let keyword = data[key];
keyword.key = key; // Self-reference
array[col].push(keyword);
col++;
if (col == 3) col = 0;
}
return array;
}
/* -------------------------------------------- */
2023-02-01 12:16:04 +01:00
static async createChatMessage(name, rollMode, chatOptions) {
2022-12-15 21:44:23 +01:00
switch (rollMode) {
case "blindroll": // GM only
if (!game.user.isGM) {
this.blindMessageToGM(chatOptions);
chatOptions.whisper = [game.user.id];
chatOptions.content = "Message only to the GM";
}
else {
chatOptions.whisper = this.getUsers(user => user.isGM);
}
break;
default:
chatOptions.whisper = this.getWhisperRecipients(rollMode, name);
break;
}
chatOptions.alias = chatOptions.alias || name;
2023-02-01 12:16:04 +01:00
return await ChatMessage.create(chatOptions);
2022-12-15 21:44:23 +01:00
}
/* -------------------------------------------- */
static getBasicRollData() {
let rollData = {
rollId: randomID(16),
rollMode: game.settings.get("core", "rollMode"),
2023-02-01 12:16:04 +01:00
bonusMalus: 0
2022-12-15 21:44:23 +01:00
}
Hero6Utility.updateWithTarget(rollData)
return rollData
}
/* -------------------------------------------- */
static updateWithTarget(rollData) {
let target = Hero6Utility.getTarget()
if (target) {
rollData.defenderTokenId = target.id
}
}
/* -------------------------------------------- */
2023-02-01 12:16:04 +01:00
static async createChatWithRollMode(name, chatOptions) {
return await this.createChatMessage(name, game.settings.get("core", "rollMode"), chatOptions)
2022-12-15 21:44:23 +01:00
}
/* -------------------------------------------- */
static async confirmDelete(actorSheet, li) {
let itemId = li.data("item-id");
let msgTxt = "<p>Are you sure to remove this Item ?";
let buttons = {
delete: {
icon: '<i class="fas fa-check"></i>',
label: "Yes, remove it",
callback: () => {
actorSheet.actor.deleteEmbeddedDocuments("Item", [itemId]);
li.slideUp(200, () => actorSheet.render(false));
}
},
cancel: {
icon: '<i class="fas fa-times"></i>',
label: "Cancel"
}
}
msgTxt += "</p>";
let d = new Dialog({
title: "Confirm removal",
content: msgTxt,
buttons: buttons,
default: "cancel"
});
d.render(true);
}
}