Initial import with skill sheet working

This commit is contained in:
2024-12-04 00:11:23 +01:00
commit 9050c80ab4
4488 changed files with 671048 additions and 0 deletions

View File

@ -0,0 +1,11 @@
export { default as CthulhuEternalProtagonistSheet } from "./sheets/protagonist-sheet.mjs";
export { default as CthulhuEternalWeaponSheet } from "./sheets/weapon-sheet.mjs"
export { default as CthulhuEternalSkillSheet } from "./sheets/skill-sheet.mjs"
export { default as CthulhuEternalBondSheet } from "./sheets/bond-sheet.mjs"
export { default as CthulhuEternalArcaneSheet } from "./sheets/arcane-sheet.mjs"
export { default as CthulhuEternalInjurySheet } from "./sheets/injury-sheet.mjs"
export { default as CthulhuEternalArmorSheet } from "./sheets/armor-sheet.mjs"
export { default as CthulhuEternalMentalDisorderSheet } from "./sheets/mentaldisorder-sheet.mjs"
export { default as CthulhuEternalGearSheet } from "./sheets/gear-sheet.mjs"
export { default as CthulhuEternalMotivationSheet } from "./sheets/motivation-sheet.mjs"
export { default as CthulhuEternalManager } from "./manager.mjs"

View File

@ -0,0 +1,142 @@
const { HandlebarsApplicationMixin, ApplicationV2 } = foundry.applications.api
import { SYSTEM } from "../config/system.mjs"
/**
* An application for configuring the permissions which are available to each User role.
* @extends ApplicationV2
* @mixes HandlebarsApplication
* @alias PermissionConfig
*/
export default class CthulhuEternalManager extends HandlebarsApplicationMixin(ApplicationV2) {
static DEFAULT_OPTIONS = {
id: "cthulhueternal-application-manager",
tag: "form",
window: {
contentClasses: ["cthulhueternal-manager"],
title: "CTHULHUETERNAL.Manager.title",
resizable: true,
},
position: {
width: "auto",
height: "auto",
top: 80,
left: 400,
},
form: {
closeOnSubmit: true,
},
actions: {
resourceAll: CthulhuEternalManager.#onResourceAll,
resourceOne: CthulhuEternalManager.#onResourceOne,
saveAll: CthulhuEternalManager.#onSaveAll,
saveOne: CthulhuEternalManager.#onSaveOne,
openSheet: CthulhuEternalManager.#onOpenSheet,
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/manager.hbs",
},
}
/* -------------------------------------------- */
/* Rendering */
/* -------------------------------------------- */
/** @override */
async _prepareContext(_options = {}) {
return {
players: game.users.filter((u) => u.hasPlayerOwner && u.active),
}
}
static async #onResourceAll(event, target) {
const value = event.target.dataset.resource
CthulhuEternalManager.askRollForAll("resource", value)
}
static async #onSaveAll(event, target) {
const value = event.target.dataset.save
CthulhuEternalManager.askRollForAll("save", value)
}
static #onResourceOne(event, target) {
const value = event.target.dataset.resource
const recipient = event.target.parentElement.dataset.userId
const name = event.target.parentElement.dataset.characterName
CthulhuEternalManager.askRollForOne("resource", value, recipient, name)
}
static async #onSaveOne(event, target) {
const value = event.target.dataset.save
const recipient = event.target.parentElement.dataset.userId
const name = event.target.parentElement.dataset.characterName
CthulhuEternalManager.askRollForOne("save", value, recipient, name)
}
static #onOpenSheet(event, target) {
const characterId = event.target.dataset.characterId
game.actors.get(characterId).sheet.render(true)
}
static async askRollForAll(type, value, title = null, avantage = null) {
let label = game.i18n.localize(`CTHULHUETERNAL.Manager.${value}`)
let text = game.i18n.format("CTHULHUETERNAL.Chat.askRollForAll", { value: label })
if (avantage) {
switch (avantage) {
case "++":
text += ` ${game.i18n.localize("CTHULHUETERNAL.Roll.doubleAvantage")}`
break
case "+":
text += ` ${game.i18n.localize("CTHULHUETERNAL.Roll.avantage")}`
break
case "-":
text += ` ${game.i18n.localize("CTHULHUETERNAL.Roll.desavantage")}`
break
case "--":
text += ` ${game.i18n.localize("CTHULHUETERNAL.Roll.doubleDesavantage")}`
break
default:
break
}
}
ChatMessage.create({
user: game.user.id,
content: await renderTemplate(`systems/fvtt-cthulhu-eternal/templates/chat-ask-roll.hbs`, {
title: title !== null ? title : "",
text: text,
rollType: type,
value: value,
avantage: avantage,
}),
flags: { tenebris: { typeMessage: "askRoll" } },
})
}
static async askRollForOne(type, value, recipient, name) {
let label = game.i18n.localize(`CTHULHUETERNAL.Manager.${value}`)
const text = game.i18n.format("CTHULHUETERNAL.Chat.askRollForOne", { value: label, name: name })
game.socket.emit(`system.${SYSTEM.id}`, {
action: "askRoll",
data: {
userId: recipient,
},
})
ChatMessage.create({
user: game.user.id,
content: await renderTemplate(`systems/fvtt-cthulhu-eternal/templates/chat-ask-roll.hbs`, {
text: text,
rollType: type,
value: value,
}),
whisper: [recipient],
flags: { tenebris: { typeMessage: "askRoll" } },
})
}
}

View File

@ -0,0 +1,28 @@
import CthulhuEternalItemSheet from "./base-item-sheet.mjs"
export default class CthulhuEternalArcaneSheet extends CthulhuEternalItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["arcane"],
position: {
width: 600,
},
window: {
contentClasses: ["arcane-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/arcane.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
context.enrichedDescription = await TextEditor.enrichHTML(this.document.system.description, { async: true })
return context
}
}

View File

@ -0,0 +1,27 @@
import CthulhuEternalItemSheet from "./base-item-sheet.mjs"
export default class CthulhuEternalArmorSheet extends CthulhuEternalItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["armor"],
position: {
width: 400,
},
window: {
contentClasses: ["armor-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/armor.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
return context
}
}

View File

@ -0,0 +1,292 @@
const { HandlebarsApplicationMixin } = foundry.applications.api
export default class CthulhuEternalActorSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ActorSheetV2) {
/**
* Different sheet modes.r
* @enum {number}
*/
static SHEET_MODES = { EDIT: 0, PLAY: 1 }
constructor(options = {}) {
super(options)
this.#dragDrop = this.#createDragDropHandlers()
}
#dragDrop
/** @override */
static DEFAULT_OPTIONS = {
classes: ["fvtt-cthulhu-eternal", "actor"],
position: {
width: 1400,
height: "auto",
},
form: {
submitOnChange: true,
},
window: {
resizable: true,
},
dragDrop: [{ dragSelector: '[data-drag="true"], .rollable', dropSelector: null }],
actions: {
editImage: CthulhuEternalActorSheet.#onEditImage,
toggleSheet: CthulhuEternalActorSheet.#onToggleSheet,
edit: CthulhuEternalActorSheet.#onItemEdit,
delete: CthulhuEternalActorSheet.#onItemDelete,
createSpell: CthulhuEternalActorSheet.#onCreateSpell,
},
}
/**
* The current sheet mode.
* @type {number}
*/
_sheetMode = this.constructor.SHEET_MODES.PLAY
/**
* Is the sheet currently in 'Play' mode?
* @type {boolean}
*/
get isPlayMode() {
return this._sheetMode === this.constructor.SHEET_MODES.PLAY
}
/**
* Is the sheet currently in 'Edit' mode?
* @type {boolean}
*/
get isEditMode() {
return this._sheetMode === this.constructor.SHEET_MODES.EDIT
}
/** @override */
async _prepareContext() {
const context = {
fields: this.document.schema.fields,
systemFields: this.document.system.schema.fields,
actor: this.document,
system: this.document.system,
source: this.document.toObject(),
enrichedDescription: await TextEditor.enrichHTML(this.document.system.description, { async: true }),
isEditMode: this.isEditMode,
isPlayMode: this.isPlayMode,
isEditable: this.isEditable,
}
return context
}
/** @override */
_onRender(context, options) {
this.#dragDrop.forEach((d) => d.bind(this.element))
// Add listeners to rollable elements
const rollables = this.element.querySelectorAll(".rollable")
rollables.forEach((d) => d.addEventListener("click", this._onRoll.bind(this)))
}
// #region Drag-and-Drop Workflow
/**
* Create drag-and-drop workflow handlers for this Application
* @returns {DragDrop[]} An array of DragDrop handlers
* @private
*/
#createDragDropHandlers() {
return this.options.dragDrop.map((d) => {
d.permissions = {
dragstart: this._canDragStart.bind(this),
drop: this._canDragDrop.bind(this),
}
d.callbacks = {
dragstart: this._onDragStart.bind(this),
dragover: this._onDragOver.bind(this),
drop: this._onDrop.bind(this),
}
return new DragDrop(d)
})
}
/**
* Callback actions which occur when a dragged element is dropped on a target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
async _onDrop(event) {}
/**
* Define whether a user is able to begin a dragstart workflow for a given drag selector
* @param {string} selector The candidate HTML selector for dragging
* @returns {boolean} Can the current user drag this selector?
* @protected
*/
_canDragStart(selector) {
return this.isEditable
}
/**
* Define whether a user is able to conclude a drag-and-drop workflow for a given drop selector
* @param {string} selector The candidate HTML selector for the drop target
* @returns {boolean} Can the current user drop on this selector?
* @protected
*/
_canDragDrop(selector) {
return this.isEditable && this.document.isOwner
}
/**
* Callback actions which occur at the beginning of a drag start workflow.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
_onDragStart(event) {
if ("link" in event.target.dataset) return
const el = event.currentTarget.closest('[data-drag="true"]')
const dragType = el.dataset.dragType
let dragData = {}
let target
switch (dragType) {
case "save":
target = event.currentTarget.querySelector("input")
dragData = {
actorId: this.document.id,
type: "roll",
rollType: target.dataset.rollType,
rollTarget: target.dataset.rollTarget,
value: target.value,
}
break
case "resource":
target = event.currentTarget.querySelector("select")
dragData = {
actorId: this.document.id,
type: "roll",
rollType: target.dataset.rollType,
rollTarget: target.dataset.rollTarget,
value: target.value,
}
break
case "damage":
dragData = {
actorId: this.document.id,
type: "rollDamage",
rollType: el.dataset.dragType,
rollTarget: el.dataset.itemId,
}
break
case "attack":
dragData = {
actorId: this.document.id,
type: "rollAttack",
rollValue: el.dataset.rollValue,
rollTarget: el.dataset.rollTarget,
}
break
default:
// Handle other cases or do nothing
break
}
// Extract the data you need
if (!dragData) return
// Set data transfer
event.dataTransfer.setData("text/plain", JSON.stringify(dragData))
}
/**
* Callback actions which occur when a dragged element is over a drop target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
_onDragOver(event) {}
async _onDropItem(item) {
let itemData = item.toObject()
await this.document.createEmbeddedDocuments("Item", [itemData], { renderSheet: false })
}
// #endregion
// #region Actions
/**
* Handle toggling between Edit and Play mode.
* @param {Event} event The initiating click event.
* @param {HTMLElement} target The current target of the event listener.
*/
static #onToggleSheet(event, target) {
const modes = this.constructor.SHEET_MODES
this._sheetMode = this.isEditMode ? modes.PLAY : modes.EDIT
this.render()
}
/**
* Handle changing a Document's image.
*
* @this CthulhuEternalCharacterSheet
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target The capturing HTML element which defined a [data-action]
* @returns {Promise}
* @private
*/
static async #onEditImage(event, target) {
const attr = target.dataset.edit
const current = foundry.utils.getProperty(this.document, attr)
const { img } = this.document.constructor.getDefaultArtwork?.(this.document.toObject()) ?? {}
const fp = new FilePicker({
current,
type: "image",
redirectToRoot: img ? [img] : [],
callback: (path) => {
this.document.update({ [attr]: path })
},
top: this.position.top + 40,
left: this.position.left + 10,
})
return fp.browse()
}
/**
* Edit an existing item within the Actor
* Start with the uuid, if it's not found, fallback to the id (as Embedded item in the actor)
* @this CthulhuEternalCharacterSheet
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target the capturing HTML element which defined a [data-action]
*/
static async #onItemEdit(event, target) {
const id = target.getAttribute("data-item-id")
const uuid = target.getAttribute("data-item-uuid")
let item
item = await fromUuid(uuid)
if (!item) item = this.document.items.get(id)
if (!item) return
item.sheet.render(true)
}
/**
* Delete an existing talent within the Actor
* Use the uuid to display the talent sheet
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target the capturing HTML element which defined a [data-action]
*/
static async #onItemDelete(event, target) {
const itemUuid = target.getAttribute("data-item-uuid")
const talent = await fromUuid(itemUuid)
await talent.deleteDialog()
}
/**
* Handles the creation of a new attack item.
*
* @param {Event} event The event that triggered the creation of the attack.
* @param {Object} target The target object where the attack will be created.
* @private
* @static
*/
static #onCreateSpell(event, target) {
const item = this.document.createEmbeddedDocuments("Item", [{ name: "Nouveau sortilège", type: "spell" }])
}
// #endregion
}

View File

@ -0,0 +1,193 @@
const { HandlebarsApplicationMixin } = foundry.applications.api
export default class CthulhuEternalItemSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {
/**
* Different sheet modes.
* @enum {number}
*/
static SHEET_MODES = { EDIT: 0, PLAY: 1 }
constructor(options = {}) {
super(options)
this.#dragDrop = this.#createDragDropHandlers()
}
#dragDrop
/** @override */
static DEFAULT_OPTIONS = {
classes: ["fvtt-cthulhu-eternal", "item"],
position: {
width: 600,
height: "auto",
},
form: {
submitOnChange: true,
},
window: {
resizable: true,
},
dragDrop: [{ dragSelector: "[data-drag]", dropSelector: null }],
actions: {
toggleSheet: CthulhuEternalItemSheet.#onToggleSheet,
editImage: CthulhuEternalItemSheet.#onEditImage,
},
}
/**
* The current sheet mode.
* @type {number}
*/
_sheetMode = this.constructor.SHEET_MODES.PLAY
/**
* Is the sheet currently in 'Play' mode?
* @type {boolean}
*/
get isPlayMode() {
return this._sheetMode === this.constructor.SHEET_MODES.PLAY
}
/**
* Is the sheet currently in 'Edit' mode?
* @type {boolean}
*/
get isEditMode() {
return this._sheetMode === this.constructor.SHEET_MODES.EDIT
}
/** @override */
async _prepareContext() {
const context = {
fields: this.document.schema.fields,
systemFields: this.document.system.schema.fields,
item: this.document,
system: this.document.system,
source: this.document.toObject(),
enrichedDescription: await TextEditor.enrichHTML(this.document.system.description, { async: true }),
isEditMode: this.isEditMode,
isPlayMode: this.isPlayMode,
isEditable: this.isEditable,
}
return context
}
/** @override */
_onRender(context, options) {
this.#dragDrop.forEach((d) => d.bind(this.element))
}
// #region Drag-and-Drop Workflow
/**
* Create drag-and-drop workflow handlers for this Application
* @returns {DragDrop[]} An array of DragDrop handlers
* @private
*/
#createDragDropHandlers() {
return this.options.dragDrop.map((d) => {
d.permissions = {
dragstart: this._canDragStart.bind(this),
drop: this._canDragDrop.bind(this),
}
d.callbacks = {
dragstart: this._onDragStart.bind(this),
dragover: this._onDragOver.bind(this),
drop: this._onDrop.bind(this),
}
return new DragDrop(d)
})
}
/**
* Define whether a user is able to begin a dragstart workflow for a given drag selector
* @param {string} selector The candidate HTML selector for dragging
* @returns {boolean} Can the current user drag this selector?
* @protected
*/
_canDragStart(selector) {
return this.isEditable
}
/**
* Define whether a user is able to conclude a drag-and-drop workflow for a given drop selector
* @param {string} selector The candidate HTML selector for the drop target
* @returns {boolean} Can the current user drop on this selector?
* @protected
*/
_canDragDrop(selector) {
return this.isEditable && this.document.isOwner
}
/**
* Callback actions which occur at the beginning of a drag start workflow.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
_onDragStart(event) {
const el = event.currentTarget
if ("link" in event.target.dataset) return
// Extract the data you need
let dragData = null
if (!dragData) return
// Set data transfer
event.dataTransfer.setData("text/plain", JSON.stringify(dragData))
}
/**
* Callback actions which occur when a dragged element is over a drop target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
_onDragOver(event) {}
/**
* Callback actions which occur when a dragged element is dropped on a target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
async _onDrop(event) {}
// #endregion
// #region Actions
/**
* Handle toggling between Edit and Play mode.
* @param {Event} event The initiating click event.
* @param {HTMLElement} target The current target of the event listener.
*/
static #onToggleSheet(event, target) {
const modes = this.constructor.SHEET_MODES
this._sheetMode = this.isEditMode ? modes.PLAY : modes.EDIT
this.render()
}
/**
* Handle changing a Document's image.
*
* @this CthulhuEternalCharacterSheet
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target The capturing HTML element which defined a [data-action]
* @returns {Promise}
* @private
*/
static async #onEditImage(event, target) {
const attr = target.dataset.edit
const current = foundry.utils.getProperty(this.document, attr)
const { img } = this.document.constructor.getDefaultArtwork?.(this.document.toObject()) ?? {}
const fp = new FilePicker({
current,
type: "image",
redirectToRoot: img ? [img] : [],
callback: (path) => {
this.document.update({ [attr]: path })
},
top: this.position.top + 40,
left: this.position.left + 10,
})
return fp.browse()
}
// #endregion
}

View File

@ -0,0 +1,28 @@
import CthulhuEternalItemSheet from "./base-item-sheet.mjs"
export default class CthulhuEternalGiftSheet extends CthulhuEternalItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["bond"],
position: {
width: 600,
},
window: {
contentClasses: ["bond-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/bond.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
context.enrichedDescription = await TextEditor.enrichHTML(this.document.system.description, { async: true })
return context
}
}

View File

@ -0,0 +1,27 @@
import CthulhuEternalItemSheet from "./base-item-sheet.mjs"
export default class CthulhuEternalGearSheet extends CthulhuEternalItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["gear"],
position: {
width: 600,
},
window: {
contentClasses: ["gear-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/gear.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
return context
}
}

View File

@ -0,0 +1,28 @@
import CthulhuEternalItemSheet from "./base-item-sheet.mjs"
export default class CthulhuEternalInjurySheet extends CthulhuEternalItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["injury"],
position: {
width: 600,
},
window: {
contentClasses: ["injury-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/injury.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
context.enrichedDescription = await TextEditor.enrichHTML(this.document.system.description, { async: true })
return context
}
}

View File

@ -0,0 +1,21 @@
import CthulhuEternalItemSheet from "./base-item-sheet.mjs"
export default class CthulhuEternalMentalDisorderSheet extends CthulhuEternalItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["mentaldisorder"],
position: {
width: 450,
},
window: {
contentClasses: ["mentaldisorder-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/mentaldisorder.hbs",
},
}
}

View File

@ -0,0 +1,27 @@
import CthulhuEternalItemSheet from "./base-item-sheet.mjs"
export default class CthulhuEternalMotivationSheet extends CthulhuEternalItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["motivation"],
position: {
width: 620,
},
window: {
contentClasses: ["motivation-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/motivation.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
return context
}
}

View File

@ -0,0 +1,173 @@
import CthulhuEternalActorSheet from "./base-actor-sheet.mjs"
export default class CthulhuEternalProtagonistSheet extends CthulhuEternalActorSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["protagonist"],
position: {
width: 1150,
height: 780,
},
window: {
contentClasses: ["protagonist-content"],
},
actions: {
createEquipment: CthulhuEternalProtagonistSheet.#onCreateEquipment,
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/character-main.hbs",
},
tabs: {
template: "systems/fvtt-cthulhu-eternal/templates/generic/tab-navigation.hbs",
},
items: {
template: "systems/fvtt-cthulhu-eternal/templates/character-items.hbs",
},
biography: {
template: "systems/fvtt-cthulhu-eternal/templates/character-biography.hbs",
},
}
/** @override */
tabGroups = {
sheet: "items",
}
/**
* Prepare an array of form header tabs.
* @returns {Record<string, Partial<ApplicationTab>>}
*/
#getTabs() {
const tabs = {
items: { id: "items", group: "sheet", icon: "fa-solid fa-shapes", label: "CTHULHUETERNAL.Character.Label.details" },
biography: { id: "biography", group: "sheet", icon: "fa-solid fa-book", label: "CTHULHUETERNAL.Character.Label.biography" },
}
for (const v of Object.values(tabs)) {
v.active = this.tabGroups[v.group] === v.id
v.cssClass = v.active ? "active" : ""
}
return tabs
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
context.tabs = this.#getTabs()
context.tooltipsCaracteristiques = {
}
context.tooltipsRessources = {
}
context.rollType = {
}
return context
}
_generateTooltip(type, target) {
}
/** @override */
async _preparePartContext(partId, context) {
const doc = this.document
switch (partId) {
case "main":
context.enrichedBiens = await TextEditor.enrichHTML(doc.system.biens, { async: true })
break
case "items":
context.tab = context.tabs.items
context.weapons = doc.itemTypes.weapon
context.armors = doc.itemTypes.armor
context.spells = doc.itemTypes.spell
context.hasSpells = context.spells.length > 0
break
case "biography":
context.tab = context.tabs.biography
context.enrichedDescription = await TextEditor.enrichHTML(doc.system.description, { async: true })
context.enrichedNotes = await TextEditor.enrichHTML(doc.system.notes, { async: true })
break
}
return context
}
// #region Drag-and-Drop Workflow
/**
* Callback actions which occur when a dragged element is dropped on a target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
async _onDrop(event) {
if (!this.isEditable || !this.isEditMode) return
const data = TextEditor.getDragEventData(event)
// Handle different data types
switch (data.type) {
case "Item":
const item = await fromUuid(data.uuid)
if (!["path", "weapon", "armor", "spell"].includes(item.type)) return
if (item.type === "path") return this.#onDropPathItem(item)
if (item.type === "weapon") return super._onDropItem(item)
if (item.type === "armor") return this._onDropItem(item)
if (item.type === "spell") return this._onDropItem(item)
}
}
async #onDropPathItem(item) {
await this.document.addPath(item)
}
/**
* Creates a new attack item directly from the sheet and embeds it into the document.
* @param {Event} event The initiating click event.
* @param {HTMLElement} target The current target of the event listener.
*/
static #onCreateEquipment(event, target) {
// Création d'une armure
if (event.shiftKey) {
this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newArmor"), type: "armor" }])
}
// Création d'une arme
else {
this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newWeapon"), type: "weapon" }])
}
}
/**
* Handles the roll action triggered by user interaction.
*
* @param {PointerEvent} event The event object representing the user interaction.
* @param {HTMLElement} target The target element that triggered the roll.
*
* @returns {Promise<void>} A promise that resolves when the roll action is complete.
*
* @throws {Error} Throws an error if the roll type is not recognized.
*
* @description This method checks the current mode (edit or not) and determines the type of roll
* (save, resource, or damage) based on the target element's data attributes. It retrieves the
* corresponding value from the document's system and performs the roll.
*/
async _onRoll(event, target) {
if (this.isEditMode) return
// Jet de sauvegarde
let elt = event.currentTarget.querySelector("input")
// Jet de ressource
if (!elt) elt = event.currentTarget.querySelector("select")
// Jet de dégâts
if (!elt) elt = event.currentTarget
const rollType = elt.dataset.rollType
let rollTarget
switch (rollType) {
default:
break
}
await this.document.system.roll(rollType, rollTarget)
}
// #endregion
}

View File

@ -0,0 +1,28 @@
import CthulhuEternalItemSheet from "./base-item-sheet.mjs"
export default class CthulhuEternalSkillSheet extends CthulhuEternalItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["skill"],
position: {
width: 600,
},
window: {
contentClasses: ["skill-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/skill.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
context.enrichedDescription = await TextEditor.enrichHTML(this.document.system.description, { async: true })
return context
}
}

View File

@ -0,0 +1,21 @@
import LethalFantasyItemSheet from "./base-item-sheet.mjs"
export default class LethalFantasyWeaponSheet extends LethalFantasyItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["weapon"],
position: {
width: 620,
},
window: {
contentClasses: ["weapon-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-cthulhu-eternal/templates/weapon.hbs",
},
}
}

5
module/config/bond.mjs Normal file
View File

@ -0,0 +1,5 @@
export const BOND_TYPE = {
"individual": "CTHULHUETERNAL.Weapon.WeaponType.melee",
"community": "CTHULHUETERNAL.Weapon.WeaponType.ranged"
}

View File

@ -0,0 +1,57 @@
export const CHARACTERISTICS = Object.freeze({
str: {
id: "str",
label: "CTHULHUETERNAL.Character.str.label"
},
int: {
id: "int",
label: "CTHULHUETERNAL.Character.int.label"
},
wis: {
id: "wis",
label: "CTHULHUETERNAL.Character.wis.label"
},
dex: {
id: "dex",
label: "CTHULHUETERNAL.Character.dex.label"
},
con: {
id: "con",
label: "CTHULHUETERNAL.Character.con.label"
},
cha: {
id: "cha",
label: "CTHULHUETERNAL.Character.cha.label"
},
app: {
id: "app",
label: "CTHULHUETERNAL.Character.app.label"
},
})
export const SAVES = Object.freeze({
str: {
id: "str",
label: "CTHULHUETERNAL.Character.str.label"
},
agility: {
id: "agility",
label: "CTHULHUETERNAL.Character.agility.label"
},
dying: {
id: "dying",
label: "CTHULHUETERNAL.Character.dying.label"
},
will: {
id: "will",
label: "CTHULHUETERNAL.Character.will.label"
},
dodge: {
id: "dodge",
label: "CTHULHUETERNAL.Character.dodge.label"
},
toughness: {
id: "toughness",
label: "CTHULHUETERNAL.Character.toughness.label"
}
})

45
module/config/system.mjs Normal file
View File

@ -0,0 +1,45 @@
import * as PROTAGONIST from "./protagonist.mjs"
import * as WEAPON from "./weapon.mjs"
import * as BOND from "./bond.mjs"
export const SYSTEM_ID = "fvtt-cthulhu-eternal"
export const AVAILABLE_SETTINGS = {
common: "CTHULHUETERNAL.Settings.Common",
modern: "CTHULHUETERNAL.Settings.Modern",
jazz: "CTHULHUETERNAL.Settings.Jazz",
future: "CTHULHUETERNAL.Settings.Future",
coldwar: "CTHULHUETERNAL.Settings.ColdWar",
ww2: "CTHULHUETERNAL.Settings.WW2",
ww1: "CTHULHUETERNAL.Settings.WW1",
victorian: "CTHULHUETERNAL.Settings.Victorian",
revolution: "CTHULHUETERNAL.Settings.Revolution",
medieval: "CTHULHUETERNAL.Settings.Medieval",
classical: "CTHULHUETERNAL.Settings.Classical"
}
export const ASCII = `
······················································································································
: :
:@@@ @@@@@@@@ @@@@@@@ @@@ @@@ @@@@@@ @@@ @@@@@@@@ @@@@@@ @@@ @@@ @@@@@@@ @@@@@@ @@@@@@ @@@ @@@ :
:@@! @@! @!! @@! @@@ @@! @@@ @@! @@! @@! @@@ @@!@!@@@ @!! @@! @@@ !@@ @@! !@@ :
:@!! @!!!:! @!! @!@!@!@! @!@!@!@! @!! @!!!:! @!@!@!@! @!@@!!@! @!! @!@!@!@! !@@!! !@!@! :
:!!: !!: !!: !!: !!! !!: !!! !!: !!: !!: !!! !!: !!! !!: !!: !!! !:! !!: :
:: ::.: : : :: :: : : : : : : : : ::.: : : : : : :: : : : : : ::.: : .: :
: :
······················································································································
`
/**
* Include all constant definitions within the SYSTEM global export
* @type {Object}
*/
export const SYSTEM = {
id: SYSTEM_ID,
CHARACTERISTICS: PROTAGONIST.CHARACTERISTICS,
WEAPON_TYPE: WEAPON.WEAPON_TYPE,
BOND_TYPE: BOND.BOND_TYPE,
AVAILABLE_SETTINGS,
ASCII
}

9
module/config/weapon.mjs Normal file
View File

@ -0,0 +1,9 @@
export const WEAPON_TYPE = {
"melee": "CTHULHUETERNAL.Weapon.WeaponType.melee",
"ranged": "CTHULHUETERNAL.Weapon.WeaponType.ranged"
}
export const WEAPON_RANGE_UNIT = {
"yard": "CTHULHUETERNAL.Weapon.RangeUnit.yard",
"meter": "CTHULHUETERNAL.Weapon.RangeUnit.meter"
}

View File

@ -0,0 +1,44 @@
/**
* Menu spécifique au système
*/
export function initControlButtons() {
CONFIG.Canvas.layers.tenebris = { layerClass: ControlsLayer, group: "primary" }
Hooks.on("getSceneControlButtons", (btns) => {
let menu = []
menu.push({
name: "fortune",
title: game.i18n.localize("TENEBRIS.Fortune.title"),
icon: "fa-solid fa-clover",
button: true,
onClick: () => {
if (!foundry.applications.instances.has("tenebris-application-fortune")) {
game.system.applicationFortune.render(true)
} else game.system.applicationFortune.close()
},
})
if (game.user.isGM) {
menu.push({
name: "gm-manager",
title: game.i18n.localize("TENEBRIS.Manager.title"),
icon: "fa-solid fa-users",
button: true,
onClick: () => {
if (!foundry.applications.instances.has("tenebris-application-manager")) {
game.system.applicationManager.render(true)
} else game.system.applicationManager.close()
},
})
}
btns.push({
name: "tenebris",
title: "Cthulhu CthulhuEternal",
icon: "tenebris",
layer: "tenebris",
tools: menu,
})
})
}

View File

@ -0,0 +1,4 @@
export { default as CthulhuEternalActor } from "./actor.mjs"
export { default as CthulhuEternalItem } from "./item.mjs"
export { default as CthulhuEternalRoll } from "./roll.mjs"
export { default as CthulhuEternalChatMessage } from "./chat-message.mjs"

View File

@ -0,0 +1,17 @@
export default class CthulhuEternalActor extends Actor {
async _preCreate(data, options, user) {
await super._preCreate(data, options, user)
// Configure prototype token settings
const prototypeToken = {}
if (this.type === "protagonist") {
Object.assign(prototypeToken, {
sight: { enabled: true },
actorLink: true,
disposition: CONST.TOKEN_DISPOSITIONS.FRIENDLY,
})
this.updateSource({ prototypeToken })
}
}
}

View File

@ -0,0 +1,21 @@
import CthulhuEternalRoll from "./roll.mjs"
export default class CthulhuEternalChatMessage extends ChatMessage {
async _renderRollContent(messageData) {
const data = messageData.message
if (this.rolls[0] instanceof CthulhuEternalRoll) {
const isPrivate = !this.isContentVisible
// _renderRollHTML va appeler render sur tous les rolls
const rollHTML = await this._renderRollHTML(isPrivate)
if (isPrivate) {
data.flavor = game.i18n.format("CHAT.PrivateRollContent", { user: this.user.name })
messageData.isWhisper = false
messageData.alias = this.user.name
}
data.content = `<section class="dice-rolls">${rollHTML}</section>`
return
}
return super._renderRollContent(messageData)
}
}

View File

@ -0,0 +1 @@
export default class CthulhuEternalItem extends Item {}

583
module/documents/roll.mjs Normal file
View File

@ -0,0 +1,583 @@
import CthulhuEternalUtils from "../utils.mjs"
export default class CthulhuEternalRoll extends Roll {
/**
* The HTML template path used to render dice checks of this type
* @type {string}
*/
static CHAT_TEMPLATE = "systems/fvtt-cthulhu-eternal/templates/chat-message.hbs"
get type() {
return this.options.type
}
get isDamage() {
return this.type === ROLL_TYPE.DAMAGE
}
get target() {
return this.options.target
}
get value() {
return this.options.value
}
get treshold() {
return this.options.treshold
}
get actorId() {
return this.options.actorId
}
get actorName() {
return this.options.actorName
}
get actorImage() {
return this.options.actorImage
}
get introText() {
return this.options.introText
}
get introTextTooltip() {
return this.options.introTextTooltip
}
get aide() {
return this.options.aide
}
get gene() {
return this.options.gene
}
get modificateur() {
return this.options.modificateur
}
get avantages() {
return this.options.avantages
}
get resultType() {
return this.options.resultType
}
get isFailure() {
return this.resultType === "failure"
}
get hasTarget() {
return this.options.hasTarget
}
get targetName() {
return this.options.targetName
}
get targetArmor() {
return this.options.targetArmor
}
get targetMalus() {
return this.options.targetMalus
}
get realDamage() {
return this.options.realDamage
}
get rollAdvantage() {
return this.options.rollAdvantage
}
/**
* Generates introductory text based on the roll type.
*
* @returns {string} The formatted introductory text for the roll.
*/
_createIntroText() {
let text
switch (this.type) {
case ROLL_TYPE.SAVE:
const saveLabel = game.i18n.localize(`TENEBRIS.Character.FIELDS.caracteristiques.${this.target}.valeur.label`)
text = game.i18n.format("TENEBRIS.Roll.save", { save: saveLabel })
text = text.concat("<br>").concat(`Seuil : ${this.treshold}`)
break
case ROLL_TYPE.RESOURCE:
const resourceLabel = game.i18n.localize(`TENEBRIS.Character.FIELDS.ressources.${this.target}.valeur.label`)
text = game.i18n.format("TENEBRIS.Roll.resource", { resource: resourceLabel })
break
case ROLL_TYPE.DAMAGE:
const damageLabel = this.target
text = game.i18n.format("TENEBRIS.Roll.damage", { item: damageLabel })
break
case ROLL_TYPE.ATTACK:
const attackLabel = this.target
text = game.i18n.format("TENEBRIS.Roll.attack", { item: attackLabel })
break
}
return text
}
/**
* Generates an introductory text tooltip with characteristics and modifiers.
*
* @returns {string} A formatted string containing the value, help, hindrance, and modifier.
*/
_createIntroTextTooltip() {
let tooltip = game.i18n.format("TENEBRIS.Tooltip.saveIntroTextTooltip", { value: this.value, aide: this.aide, gene: this.gene, modificateur: this.modificateur })
if (this.hasTarget) {
tooltip = tooltip.concat(`<br>Cible : ${this.targetName}`)
}
return tooltip
}
/**
* Prompt the user with a dialog to configure and execute a roll.
*
* @param {Object} options Configuration options for the roll.
* @param {string} options.rollType The type of roll being performed (e.g., RESOURCE, DAMAGE, ATTACK, SAVE).
* @param {string} options.rollValue The initial value or formula for the roll.
* @param {string} options.rollTarget The target of the roll.
* @param {"="|"+"|"++"|"-"|"--"} options.rollAdvantage If there is an avantage (+), a disadvantage (-), a double advantage (++), a double disadvantage (--) or a normal roll (=).
* @param {string} options.actorId The ID of the actor performing the roll.
* @param {string} options.actorName The name of the actor performing the roll.
* @param {string} options.actorImage The image of the actor performing the roll.
* @param {boolean} options.hasTarget Whether the roll has a target.
* @param {Object} options.target The target of the roll, if any.
* @param {Object} options.data Additional data for the roll.
*
* @returns {Promise<Object|null>} The roll result or null if the dialog was cancelled.
*/
static async prompt(options = {}) {
let formula = options.rollValue
// Formula for a resource roll
if (options.rollType === ROLL_TYPE.RESOURCE) {
let ressource = game.i18n.localize(`TENEBRIS.Character.FIELDS.ressources.${options.rollTarget}.valeur.label`)
if (formula === "0" || formula === "") {
ui.notifications.warn(game.i18n.format("TENEBRIS.Warning.plusDeRessource", { ressource: ressource }))
return null
}
}
const rollModes = Object.fromEntries(Object.entries(CONFIG.Dice.rollModes).map(([key, value]) => [key, game.i18n.localize(value)]))
const fieldRollMode = new foundry.data.fields.StringField({
choices: rollModes,
blank: false,
default: "public",
})
const choiceAide = foundry.utils.mergeObject({ 0: "0" }, options.rollValue <= 10 ? { 1: "1" } : { 1: "1", 2: "2" })
const choiceGene = {
0: "0",
"-1": "-1",
"-2": "-2",
"-3": "-3",
"-4": "-4",
"-5": "-5",
"-6": "-6",
"-7": "-7",
"-8": "-8",
"-9": "-9",
"-10": "-10",
}
const choiceAvantage = { normal: "Normal", avantage: "Avantage", desavantage: "Désavantage", doubleAvantage: "Double avantage", doubleDesavantage: "Double désavantage" }
const choiceModificateur = {
0: "0",
"-1": "-1",
"-2": "-2",
"-3": "-3",
"-4": "-4",
"-5": "-5",
"-6": "-6",
"-7": "-7",
"-8": "-8",
"-9": "-9",
"-10": "-10",
}
let damageDice
let damageDiceMax
let damageDiceFinal
let damageDiceLowered
// Damage roll : check the roll is not above the maximum damage
if (options.rollType === ROLL_TYPE.DAMAGE) {
damageDice = options.rollValue
damageDiceMax = game.actors.get(options.actorId).system.dmax.valeur
damageDiceFinal = CthulhuEternalUtils.maxDamage(damageDice, damageDiceMax)
damageDiceLowered = damageDiceFinal !== damageDice
// Récupération du nom de l'objet si c'est un jet depuis la fiche de l'acteur
// Si c'est via une macro le nom est connu
options.rollTarget = game.actors.get(options.actorId).items.get(options.rollTarget).name
}
if (options.rollType === ROLL_TYPE.ATTACK) {
damageDice = options.rollValue
}
let malus = "0"
let targetMalus = "0"
let targetName
let targetArmor
const displayOpponentMalus = game.settings.get("tenebris", "displayOpponentMalus")
if (options.rollType === ROLL_TYPE.SAVE && options.hasTarget && options.target.document.actor.type === "opponent") {
targetName = options.target.document.actor.name
if (displayOpponentMalus) malus = options.target.document.actor.system.malus.toString()
else targetMalus = options.target.document.actor.system.malus.toString()
}
if (options.rollType === ROLL_TYPE.DAMAGE && options.hasTarget && options.target.document.actor.type === "opponent") {
targetName = options.target.document.actor.name
targetArmor = options.target.document.actor.system.armure.toString()
}
let dialogContext = {
isSave: options.rollType === ROLL_TYPE.SAVE,
isResource: options.rollType === ROLL_TYPE.RESOURCE,
isDamage: options.rollType === ROLL_TYPE.DAMAGE,
isAttack: options.rollType === ROLL_TYPE.ATTACK,
rollModes,
fieldRollMode,
choiceAide,
choiceGene,
choiceAvantage,
choiceModificateur,
damageDice,
damageDiceMax,
damageDiceFinal,
damageDiceLowered,
formula,
hasTarget: options.hasTarget,
malus,
targetName,
targetArmor,
rollAdvantage: this._convertAvantages(options.rollAdvantage),
rangeAdvantage: this._convertRollAdvantageToRange(options.rollAdvantage),
}
const content = await renderTemplate("systems/fvtt-cthulhu-eternal/templates/roll-dialog.hbs", dialogContext)
const title = CthulhuEternalRoll.createTitle(options.rollType, options.rollTarget)
const label = game.i18n.localize("TENEBRIS.Roll.roll")
const rollContext = await foundry.applications.api.DialogV2.wait({
window: { title: title },
classes: ["lethalfantasy"],
content,
buttons: [
{
label: label,
callback: (event, button, dialog) => {
const output = Array.from(button.form.elements).reduce((obj, input) => {
if (input.name) obj[input.name] = input.value
return obj
}, {})
// Avantages
switch (output.avantages) {
case "1":
output.avantages = "doubleDesavantage"
break
case "2":
output.avantages = "desavantage"
break
case "3":
output.avantages = "normal"
break
case "4":
output.avantages = "avantage"
break
case "5":
output.avantages = "doubleAvantage"
break
}
return output
},
},
],
rejectClose: false, // Click on Close button will not launch an error
render: (event, dialog) => {
const rangeInput = dialog.querySelector('input[name="avantages"]')
if (rangeInput) {
rangeInput.addEventListener("change", (event) => {
event.preventDefault()
event.stopPropagation()
const readOnly = dialog.querySelector('input[name="selectAvantages"]')
readOnly.value = this._convertAvantages(event.target.value)
})
}
},
})
// If the user cancels the dialog, exit
if (rollContext === null) return
let treshold
if (options.rollType === ROLL_TYPE.SAVE) {
const aide = rollContext.aide === "" ? 0 : parseInt(rollContext.aide, 10)
const gene = rollContext.gene === "" ? 0 : parseInt(rollContext.gene, 10)
const modificateur = rollContext.modificateur === "" ? 0 : parseInt(rollContext.modificateur, 10)
if (options.rollType === ROLL_TYPE.SAVE) {
let dice = "1d20"
switch (rollContext.avantages) {
case "avantage":
dice = "2d20kl"
break
case "desavantage":
dice = "2d20kh"
break
case "doubleAvantage":
dice = "3d20kl"
break
case "doubleDesavantage":
dice = "3d20kh"
break
}
formula = `${dice}`
}
treshold = options.rollValue + aide + gene + modificateur
}
// Formula for a damage roll
if (options.rollType === ROLL_TYPE.DAMAGE) {
formula = damageDiceFinal
}
// Formula for an attack roll
if (options.rollType === ROLL_TYPE.ATTACK) {
formula = damageDice
}
const rollData = {
type: options.rollType,
target: options.rollTarget,
value: options.rollValue,
treshold: treshold,
actorId: options.actorId,
actorName: options.actorName,
actorImage: options.actorImage,
rollMode: rollContext.visibility,
hasTarget: options.hasTarget,
targetName,
targetArmor,
targetMalus,
...rollContext,
}
/**
* A hook event that fires before the roll is made.
* @function tenebris.preRoll
* @memberof hookEvents
* @param {Object} options Options for the roll.
* @param {Object} rollData All data related to the roll.
* @returns {boolean} Explicitly return `false` to prevent roll to be made.
*/
if (Hooks.call("tenebris.preRoll", options, rollData) === false) return
const roll = new this(formula, options.data, rollData)
await roll.evaluate()
let resultType
if (options.rollType === ROLL_TYPE.SAVE) {
resultType = roll.total <= treshold ? "success" : "failure"
} else if (options.rollType === ROLL_TYPE.RESOURCE) {
resultType = roll.total === 1 || roll.total === 2 ? "failure" : "success"
}
let realDamage
if (options.rollType === ROLL_TYPE.DAMAGE) {
realDamage = Math.max(0, roll.total - parseInt(targetArmor, 10))
}
roll.options.resultType = resultType
roll.options.treshold = treshold
roll.options.introText = roll._createIntroText()
roll.options.introTextTooltip = roll._createIntroTextTooltip()
roll.options.realDamage = realDamage
/**
* A hook event that fires after the roll has been made.
* @function tenebris.Roll
* @memberof hookEvents
* @param {Object} options Options for the roll.
* @param {Object} rollData All data related to the roll.
@param {CthulhuEternalRoll} roll The resulting roll.
* @returns {boolean} Explicitly return `false` to prevent roll to be made.
*/
if (Hooks.call("tenebris.Roll", options, rollData, roll) === false) return
return roll
}
/**
* Creates a title based on the given type.
*
* @param {string} type The type of the roll.
* @param {string} target The target of the roll.
* @returns {string} The generated title.
*/
static createTitle(type, target) {
switch (type) {
case ROLL_TYPE.SAVE:
return `${game.i18n.localize("TENEBRIS.Dialog.titleSave")} : ${game.i18n.localize(`TENEBRIS.Manager.${target}`)}`
case ROLL_TYPE.RESOURCE:
return `${game.i18n.localize("TENEBRIS.Dialog.titleResource")} : ${game.i18n.localize(`TENEBRIS.Manager.${target}`)}`
case ROLL_TYPE.DAMAGE:
return `${game.i18n.localize("TENEBRIS.Dialog.titleDamage")} : ${target}`
case ROLL_TYPE.ATTACK:
return `${game.i18n.localize("TENEBRIS.Dialog.titleAttack")} : ${target}`
default:
return game.i18n.localize("TENEBRIS.Dialog.titleStandard")
}
}
/** @override */
async render(chatOptions = {}) {
let chatData = await this._getChatCardData(chatOptions.isPrivate)
return await renderTemplate(this.constructor.CHAT_TEMPLATE, chatData)
}
/**
* Generates the data required for rendering a roll chat card.
*
* @param {boolean} isPrivate Indicates if the chat card is private.
* @returns {Promise<Object>} A promise that resolves to an object containing the chat card data.
* @property {Array<string>} css - CSS classes for the chat card.
* @property {Object} data - The data associated with the roll.
* @property {number} diceTotal - The total value of the dice rolled.
* @property {boolean} isGM - Indicates if the user is a Game Master.
* @property {string} formula - The formula used for the roll.
* @property {number} total - The total result of the roll.
* @property {boolean} isSave - Indicates if the roll is a saving throw.
* @property {boolean} isResource - Indicates if the roll is related to a resource.
* @property {boolean} isDamage - Indicates if the roll is for damage.
* @property {boolean} isFailure - Indicates if the roll is a failure.
* @property {Array} avantages - Advantages associated with the roll.
* @property {string} actorId - The ID of the actor performing the roll.
* @property {string} actingCharName - The name of the character performing the roll.
* @property {string} actingCharImg - The image of the character performing the roll.
* @property {string} introText - Introductory text for the roll.
* @property {string} introTextTooltip - Tooltip for the introductory text.
* @property {string} resultType - The type of result (e.g., success, failure).
* @property {boolean} hasTarget - Indicates if the roll has a target.
* @property {string} targetName - The name of the target.
* @property {number} targetArmor - The armor value of the target.
* @property {number} realDamage - The real damage dealt.
* @property {boolean} isPrivate - Indicates if the chat card is private.
* @property {string} cssClass - The combined CSS classes as a single string.
* @property {string} tooltip - The tooltip text for the chat card.
*/
async _getChatCardData(isPrivate) {
const cardData = {
css: [SYSTEM.id, "dice-roll"],
data: this.data,
diceTotal: this.dice.reduce((t, d) => t + d.total, 0),
isGM: game.user.isGM,
formula: this.formula,
total: this.total,
isSave: this.isSave,
isResource: this.isResource,
isDamage: this.isDamage,
isFailure: this.isFailure,
avantages: this.avantages,
actorId: this.actorId,
actingCharName: this.actorName,
actingCharImg: this.actorImage,
introText: this.introText,
introTextTooltip: this.introTextTooltip,
resultType: this.resultType,
hasTarget: this.hasTarget,
targetName: this.targetName,
targetArmor: this.targetArmor,
realDamage: this.realDamage,
isPrivate: isPrivate,
}
cardData.cssClass = cardData.css.join(" ")
cardData.tooltip = isPrivate ? "" : await this.getTooltip()
return cardData
}
/**
* Converts the roll result to a chat message.
*
* @param {Object} [messageData={}] Additional data to include in the message.
* @param {Object} options Options for message creation.
* @param {string} options.rollMode The mode of the roll (e.g., public, private).
* @param {boolean} [options.create=true] Whether to create the message.
* @returns {Promise} - A promise that resolves when the message is created.
*/
async toMessage(messageData = {}, { rollMode, create = true } = {}) {
super.toMessage(
{
isSave: this.isSave,
isResource: this.isResource,
isDamage: this.isDamage,
isFailure: this.resultType === "failure",
avantages: this.avantages,
introText: this.introText,
introTextTooltip: this.introTextTooltip,
actingCharName: this.actorName,
actingCharImg: this.actorImage,
hasTarget: this.hasTarget,
targetName: this.targetName,
targetArmor: this.targetArmor,
targetMalus: this.targetMalus,
realDamage: this.realDamage,
...messageData,
},
{ rollMode: rollMode },
)
}
// Used in the avantages select and with the rollAdvantage parameter: convert the selected value to the corresponding string
static _convertAvantages(value) {
switch (value) {
case "1":
return game.i18n.localize("TENEBRIS.Roll.doubleDesavantage")
case "2":
return game.i18n.localize("TENEBRIS.Roll.desavantage")
case "3":
return game.i18n.localize("TENEBRIS.Roll.normal")
case "4":
return game.i18n.localize("TENEBRIS.Roll.avantage")
case "5":
return game.i18n.localize("TENEBRIS.Roll.doubleAvantage")
case "--":
return game.i18n.localize("TENEBRIS.Roll.doubleDesavantage")
case "-":
return game.i18n.localize("TENEBRIS.Roll.desavantage")
case "=":
return game.i18n.localize("TENEBRIS.Roll.normal")
case "+":
return game.i18n.localize("TENEBRIS.Roll.avantage")
case "++":
return game.i18n.localize("TENEBRIS.Roll.doubleAvantage")
}
}
// Used in the rollAdvantage parameter: convert the selected value to the corresponding range value
static _convertRollAdvantageToRange(value) {
switch (value) {
case "--":
return 1
case "-":
return 2
case "=":
return 3
case "+":
return 4
case "++":
return 5
}
}
}

80
module/enrichers.mjs Normal file
View File

@ -0,0 +1,80 @@
/**
* Enricher qui permet de transformer un texte en un lien de lancer de dés
* Pour une syntaxe de type @jet[x]{y}(z) avec x la caractéristique, y le titre et z l'avantage
* x de type rob, dex, int, per, vol pour les caractéristiques
* et de type oeil, verbe, san, bourse, magie pour les ressources
* y est le titre du jet et permet de décrire l'action
* z est l'avantage du jet, avec pour valeurs possibles : --, -, +, ++
*/
export function setupTextEnrichers() {
CONFIG.TextEditor.enrichers = CONFIG.TextEditor.enrichers.concat([
{
// eslint-disable-next-line no-useless-escape
pattern: /\@jet\[(.+?)\]{(.*?)}\((.*?)\)/gm,
enricher: async (match, options) => {
const a = document.createElement("a")
a.classList.add("ask-roll-journal")
const target = match[1]
const title = match[2]
const avantage = match[3]
let type = "resource"
if (["rob", "dex", "int", "per", "vol"].includes(target)) {
type = "save"
}
let rollAvantage = "normal"
if (avantage) {
switch (avantage) {
case "++":
rollAvantage = "++"
break
case "+":
rollAvantage = "+"
break
case "-":
rollAvantage = "-"
break
case "--":
rollAvantage = "--"
break
default:
break
}
}
a.dataset.rollType = type
a.dataset.rollTarget = target
a.dataset.rollTitle = title
a.dataset.rollAvantage = rollAvantage
a.innerHTML = `
<i class="fas fa-dice-d20"></i> ${getLibelle(target)}${rollAvantage !== "normal" ? rollAvantage : ""}
`
return a
},
},
])
}
const mapLibelles = {
rob: "ROB",
dex: "DEX",
int: "INT",
per: "PER",
vol: "VOL",
oeil: "OEIL",
verbe: "VERBE",
san: "SANTE MENTALE",
bourse: "BOURSE",
magie: "MAGIE",
}
/**
* Retourne le libellé associé à la valeur qui sera affiché dans le journal
* @param {string} value
*/
function getLibelle(value) {
if (mapLibelles[value]) {
return mapLibelles[value]
}
return null
}

82
module/macros.mjs Normal file
View File

@ -0,0 +1,82 @@
export class Macros {
/**
* Creates a macro based on the type of data dropped onto the hotbar.
*
* @param {Object} dropData The data object representing the item dropped.
* @param {string} dropData.type The type of the dropped item (e.g., "Actor", "JournalEntry", "roll").
* @param {string} dropData.uuid The UUID of the dropped item.
* @param {string} [dropData.actorId] The ID of the actor (required if type is "roll").
* @param {string} [dropData.rollType] The type of roll (required if type is "roll").
* @param {string} [dropData.rollTarget] The target of the roll (required if type is "roll").
* @param {string} [dropData.value] The value of the roll (required if type is "roll").
* @param {number} slot The hotbar slot where the macro will be created.
*
* @returns {Promise<void>} A promise that resolves when the macro is created.
*/
static createCthulhuEternalMacro = async function (dropData, slot) {
switch (dropData.type) {
case "Actor":
const actor = await fromUuid(dropData.uuid)
const actorCommand = `game.actors.get("${actor.id}").sheet.render(true)`
this.createMacro(slot, actor.name, actorCommand, actor.img)
break
case "JournalEntry":
const journal = await fromUuid(dropData.uuid)
const journalCommand = `game.journal.get("${journal.id}").sheet.render(true)`
this.createMacro(slot, journal.name, journalCommand, journal.img ? journal.img : "icons/svg/book.svg")
break
case "roll":
const rollCommand =
dropData.rollType === "save"
? `game.actors.get('${dropData.actorId}').system.roll('${dropData.rollType}', '${dropData.rollTarget}', '=');`
: `game.actors.get('${dropData.actorId}').system.roll('${dropData.rollType}', '${dropData.rollTarget}');`
const rollName = `${game.i18n.localize("TENEBRIS.Label.jet")} ${game.i18n.localize(`TENEBRIS.Manager.${dropData.rollTarget}`)}`
this.createMacro(slot, rollName, rollCommand, "icons/svg/d20-grey.svg")
break
case "rollDamage":
const weapon = game.actors.get(dropData.actorId).items.get(dropData.rollTarget)
const rollDamageCommand = `game.actors.get('${dropData.actorId}').system.roll('${dropData.rollType}', '${dropData.rollTarget}');`
const rollDamageName = `${game.i18n.localize("TENEBRIS.Label.jet")} ${weapon.name}`
this.createMacro(slot, rollDamageName, rollDamageCommand, weapon.img)
break
case "rollAttack":
const rollAttackCommand = `game.actors.get('${dropData.actorId}').system.roll('${dropData.rollValue}', '${dropData.rollTarget}');`
const rollAttackName = `${game.i18n.localize("TENEBRIS.Label.jet")} ${dropData.rollTarget}`
this.createMacro(slot, rollAttackName, rollAttackCommand, "icons/svg/d20-grey.svg")
break
default:
// Handle other cases or do nothing
break
}
}
/**
* Create a macro
* All macros are flaged with a tenebris.macro flag at true
* @param {*} slot
* @param {*} name
* @param {*} command
* @param {*} img
*/
static createMacro = async function (slot, name, command, img) {
let macro = game.macros.contents.find((m) => m.name === name && m.command === command)
if (!macro) {
macro = await Macro.create(
{
name: name,
type: "script",
img: img,
command: command,
flags: { "tenebris.macro": true },
},
{ displaySheet: false },
)
game.user.assignHotbarMacro(macro, slot)
}
}
}

10
module/models/_module.mjs Normal file
View File

@ -0,0 +1,10 @@
export { default as CthulhuEternalProtagonist } from "./protagonist.mjs"
export { default as CthulhuEternalWeapon } from "./weapon.mjs"
export { default as CthulhuEternalArcane } from "./arcane.mjs"
export { default as CthulhuEternalSkill } from "./skill.mjs"
export { default as CthulhuEternalArmor } from "./armor.mjs"
export { default as CthulhuEternalInjury } from "./injury.mjs"
export { default as CthulhuEternalMentalDisorder } from "./mentaldisorder.mjs"
export { default as CthulhuEternalBond } from "./bond.mjs"
export { default as CthulhuEternalGear } from "./gear.mjs"
export { default as CthulhuEternalMotivation } from "./motivation.mjs"

20
module/models/arcane.mjs Normal file
View File

@ -0,0 +1,20 @@
import { SYSTEM } from "../config/system.mjs"
export default class CthulhuEternalArcane extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.description = new fields.HTMLField({
required: false,
blank: true,
initial: "",
textSearch: true,
})
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.Arcane"]
}

18
module/models/armor.mjs Normal file
View File

@ -0,0 +1,18 @@
import { SYSTEM } from "../config/system.mjs"
export default class CthulhuEternalArmor extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const schema = {}
const requiredInteger = { required: true, nullable: false, integer: true }
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.settings = new fields.StringField({ required: true, initial: "common", choices: SYSTEM.AVAILABLE_SETTINGS })
schema.protection = new fields.NumberField({ ...requiredInteger, required: true, initial: 0, min: 0 })
schema.resourceLevel = new fields.NumberField({ required: true, initial: 0, min: 0 })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.Armor"]
}

17
module/models/bond.mjs Normal file
View File

@ -0,0 +1,17 @@
export default class CthulhuEternalBond extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.bondType = new fields.StringField({ required: true, initial: "individual", choices: SYSTEM.BOND_TYPE })
schema.value = new fields.NumberField({ ...requiredInteger, required: true, initial: 0, min: 0 })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.Bond"]
}

19
module/models/gear.mjs Normal file
View File

@ -0,0 +1,19 @@
import { SYSTEM } from "../config/system.mjs"
export default class CthulhuEternalEquipment extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const schema = {}
const requiredInteger = { required: true, nullable: false, integer: true }
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.settings = new fields.StringField({ required: true, initial: "common", choices: SYSTEM.AVAILABLE_SETTINGS })
schema.resourceLevel = new fields.NumberField({ required: true, initial: 0, min: 0 })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.Equipment"]
}

15
module/models/injury.mjs Normal file
View File

@ -0,0 +1,15 @@
export default class CthulhuEternalInjury extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.description = new fields.HTMLField({ required: true, textSearch: true })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.Gift"]
}

View File

@ -0,0 +1,15 @@
export default class CthulhuEternalMentalDisorder extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.description = new fields.HTMLField({ required: true, textSearch: true })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.MentalDisorder"]
}

View File

@ -0,0 +1,16 @@
import { SYSTEM } from "../config/system.mjs"
export default class CthulhuEternalMotivation extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const schema = {}
const requiredInteger = { required: true, nullable: false, integer: true }
schema.description = new fields.HTMLField({ required: true, textSearch: true })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.Shield"]
}

View File

@ -0,0 +1,120 @@
import { SYSTEM } from "../config/system.mjs"
import CthulhuEternalRoll from "../documents/roll.mjs"
export default class CthulhuEternalProtagonist extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.notes = new fields.HTMLField({ required: true, textSearch: true })
// Carac
const characteristicField = (label) => {
const schema = {
value: new fields.NumberField({ ...requiredInteger, initial: 3, min: 0 }),
percent: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0, max: 100 }),
attackMod: new fields.NumberField({ ...requiredInteger, initial: 0 }),
defenseMod: new fields.NumberField({ ...requiredInteger, initial: 0 })
}
return new fields.SchemaField(schema, { label })
}
schema.characteristics = new fields.SchemaField(
Object.values(SYSTEM.CHARACTERISTICS).reduce((obj, characteristic) => {
obj[characteristic.id] = characteristicField(characteristic.label)
return obj
}, {}),
)
schema.hp = new fields.SchemaField({
value: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
max: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
})
schema.perception = new fields.SchemaField({
value: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
bonus: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
})
schema.grit = new fields.SchemaField({
earned: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
current: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
})
schema.luck = new fields.SchemaField({
earned: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
current: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
})
schema.movement = new fields.SchemaField({
walk: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
jog: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
sprint: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
run: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
armorAdjust: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
})
schema.biodata = new fields.SchemaField({
class: new fields.StringField({ required: true, nullable: false, initial: "" }),
level: new fields.NumberField({ ...requiredInteger, initial: 1, min: 1 }),
mortal: new fields.StringField({ required: true, nullable: false, initial: "" }),
alignment: new fields.StringField({ required: true, nullable: false, initial: "" }),
age: new fields.NumberField({ ...requiredInteger, initial: 15, min: 6 }),
height: new fields.NumberField({ ...requiredInteger, initial: 170, min: 50 }),
eyes: new fields.StringField({ required: true, nullable: false, initial: "" }),
hair: new fields.StringField({ required: true, nullable: false, initial: "" })
})
schema.developmentPoints = new fields.SchemaField({
total: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
remaining: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
})
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.Protagonist"]
/**
* Rolls a dice for a character.
* @param {("save"|"resource|damage")} rollType The type of the roll.
* @param {number} rollTarget The target value for the roll. Which caracteristic or resource. If the roll is a damage roll, this is the id of the item.
* @param {"="|"+"|"++"|"-"|"--"} rollAdvantage If there is an avantage (+), a disadvantage (-), a double advantage (++), a double disadvantage (--) or a normal roll (=).
* @returns {Promise<null>} - A promise that resolves to null if the roll is cancelled.
*/
async roll(rollType, rollTarget, rollAdvantage = "=") {
let rollValue
let opponentTarget
switch (rollType) {
default:
// Handle other cases or do nothing
break
}
await this._roll(rollType, rollTarget, rollValue, opponentTarget, rollAdvantage)
}
/**
* Rolls a dice for a character.
* @param {("save"|"resource|damage")} rollType The type of the roll.
* @param {number} rollTarget The target value for the roll. Which caracteristic or resource. If the roll is a damage roll, this is the id of the item.
* @param {number} rollValue The value of the roll. If the roll is a damage roll, this is the dice to roll.
* @param {Token} opponentTarget The target of the roll : used for save rolls to get the oppponent's malus.
* @param {"="|"+"|"++"|"-"|"--"} rollAdvantage If there is an avantage (+), a disadvantage (-), a double advantage (++), a double disadvantage (--) or a normal roll (=).
* @returns {Promise<null>} - A promise that resolves to null if the roll is cancelled.
*/
async _roll(rollType, rollTarget, rollValue, opponentTarget = undefined, rollAdvantage = "=") {
const hasTarget = opponentTarget !== undefined
let roll = await CthulhuEternalRoll.prompt({
rollType,
rollTarget,
rollValue,
actorId: this.parent.id,
actorName: this.parent.name,
actorImage: this.parent.img,
hasTarget,
target: opponentTarget,
rollAdvantage,
})
if (!roll) return null
await roll.toMessage({}, { rollMode: roll.options.rollMode })
}
}

65
module/models/skill.mjs Normal file
View File

@ -0,0 +1,65 @@
import { SYSTEM } from "../config/system.mjs"
export default class LethalFantasySkill extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const schema = {}
const requiredInteger = { required: true, nullable: false, integer: true }
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.settings = new fields.StringField({ required: true, initial: "common", choices: SYSTEM.AVAILABLE_SETTINGS })
schema.base = new fields.StringField({ required: true, initial: "WIS" })
schema.bonus = new fields.NumberField({ ...requiredInteger, required: true, initial: 0, min: 0 })
schema.diceEvolved = new fields.BooleanField({ required: true, initial: true })
schema.rollFailed = new fields.BooleanField({ required: true, initial: false })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.Skill"]
prepareDerivedData() {
super.prepareDerivedData();
this.skillTotal = this.computeBase();
}
computeBase() {
let actor = this.parent?.actor;
if (!actor) {
return `${this.base } + ${ String(this.bonus)}`;
}
// Split the base value per stat : WIS,DEX,STR,INT,CHA (example)
const base = this.base;
let baseSplit = base.split(",");
let baseSplitLength = baseSplit.length;
if ( baseSplitLength > 0) {
// Select the max stat value from the parent actor
let maxStat = 0;
for (let i = 0; i < baseSplitLength; i++) {
const stat = baseSplit[i];
const statValue = actor.system.characteristics[stat.toLowerCase()]?.value || 0;
if (statValue > maxStat) {
maxStat = statValue;
}
}
return maxStat;
} else {
// Split with + calculate the total
baseSplit = base.split("+");
baseSplitLength = baseSplit.length;
if ( baseSplitLength > 0) {
let total = 0;
for (let i = 0; i < baseSplitLength; i++) {
const stat = baseSplit[i];
const statValue = actor.system.characteristics[stat.toLowerCase()]?.value || 0;
total += statValue;
}
return total
}
}
return `${this.base } + ${ String(this.bonus)}`;
}
}

30
module/models/weapon.mjs Normal file
View File

@ -0,0 +1,30 @@
import { SYSTEM } from "../config/system.mjs"
export default class LethalFantasySkill extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const schema = {}
const requiredInteger = { required: true, nullable: false, integer: true }
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.settings = new fields.StringField({ required: true, initial: "common", choices: SYSTEM.AVAILABLE_SETTINGS })
schema.weaponType = new fields.StringField({ required: true, initial: "melee", choices: SYSTEM.WEAPON_TYPE })
schema.damage = new fields.StringField({required: true, initial: "1d6"})
schema.baseRange = new fields.StringField({required: true, initial: ""})
schema.rangeDistance = new fields.StringField({ required: true, initial: "yard", choices: SYSTEM.WEAPON_RANGE_UNIT })
schema.lethality = new fields.NumberField({ required: true, initial: 0, min: 0 })
schema.killRadius = new fields.NumberField({ required: true, initial: 0, min: 0 })
schema.resourceLevel = new fields.NumberField({ required: true, initial: 0, min: 0 })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["CTHULHUETERNAL.Weapon"]
get weaponCategory() {
return game.i18n.localize(CATEGORY[this.category].label)
}
}

32
module/socket.mjs Normal file
View File

@ -0,0 +1,32 @@
/**
* Handles socket events based on the provided action.
*
* @param {Object} [params={}] The parameters for the socket event.
* @param {string|null} [params.action=null] The action to be performed.
* @param {Object} [params.data={}] The data associated with the action.
* @returns {*} The result of the action handler, if applicable.
*/
export function handleSocketEvent({ action = null, data = {} } = {}) {
console.debug("handleSocketEvent", action, data)
switch (action) {
case "fortune":
return CthulhuEternalFortune.handleSocketEvent(data)
case "askRoll":
return _askRoll(data)
}
}
/**
* Handles the socket event to ask for a roll.
*
* @param {Object} [options={}] The options object.
* @param {string} [options.userId] The ID of the user who initiated the roll.
*/
export function _askRoll({ userId } = {}) {
console.debug(`handleSocketEvent _askRoll from ${userId} !`)
const currentUser = game.user._id
if (userId === currentUser) {
foundry.audio.AudioHelper.play({ src: "/systems/fvtt-cthulhu-eternal/sounds/drums.wav", volume: 0.8, autoplay: true, loop: false }, false)
}
}

4
module/utils.mjs Normal file
View File

@ -0,0 +1,4 @@
export default class CthulhuEternalUtils {
}