Skip to content

Commit

Permalink
Merge pull request #24 from SebaSOFT/develop
Browse files Browse the repository at this point in the history
Debug mode
  • Loading branch information
SebaSOFT authored Apr 20, 2022
2 parents eeab26d + 1dde41c commit 19798f9
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 41 deletions.
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# CHANGELOG

## [1.0.1] 2022-04-20

### CHANGED

- Corrected some translations and improved code commenting

### ADDED

- Debug setting, so you can see the inner workings of the module and troubleshoot your scenes

## [1.0.0] 2022-02-28

### CHANGED
Expand Down
4 changes: 3 additions & 1 deletion languages/walls-have-ears.de.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
"WHE.settings.title": "Wände haben Ohren",
"WHE.save": "Speichern",
"WHE.settings_disable.title": "Geräuschdämpfung deaktivieren",
"WHE.settings_disable.hint": "Mit diesem Modul können Geräusche gedämpft werden, um das Eintauchen zu verbessern. Sie können diese Funktion jedoch aus Leistungsgründen deaktivieren."
"WHE.settings_disable.hint": "Mit diesem Modul können Geräusche gedämpft werden, um das Eintauchen zu verbessern. Sie können diese Funktion jedoch aus Leistungsgründen deaktivieren.",
"WHE.settings_debug.title": "Aktivieren Sie den Debug-Modus",
"WHE.settings_debug.hint": "Um Fehler in Ihren Szenen zu beheben, aktivieren Sie dies, um den Dämpfungsindex anzuzeigen, wenn Sie Ihre Token auswählen/verschieben."
}
4 changes: 3 additions & 1 deletion languages/walls-have-ears.en.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
"WHE.settings.title": "Walls Have Ears",
"WHE.save": "Save",
"WHE.settings_disable.title": "Disable sound muffling",
"WHE.settings_disable.hint": "This module allows for sounds to be muffled for improved inmersion. But you can disable this feature for performance reasons."
"WHE.settings_disable.hint": "This module allows for sounds to be muffled for improved inmersion. But you can disable this feature for performance reasons.",
"WHE.settings_debug.title": "Enable Debug mode",
"WHE.settings_debug.hint": "In order to troubleshoot your scenes, enable this to see the muffling index when selecting/moving your tokens."
}
6 changes: 4 additions & 2 deletions languages/walls-have-ears.es.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
"WHE.settings.title": "Las paredes escuchan",
"WHE.save": "Guardar",
"WHE.settings_disable.title": "Desactivar la amortiguación del sonido",
"WHE.settings_disable.hint": "Este módulo permite amortiguar los sonidos para mejorar la inmersión. Pero puede desactivar esta función por motivos de rendimiento."
}
"WHE.settings_disable.hint": "Este módulo permite amortiguar los sonidos para mejorar la inmersión. Pero puede desactivar esta función por motivos de rendimiento.",
"WHE.settings_debug.title": "Activar modo de depuración",
"WHE.settings_debug.hint": "Para resolver problemas en sus escenas, active esto para ver el índice amortiguación de sonidos cuando seleccione o mueva sus tokens."
}
14 changes: 8 additions & 6 deletions languages/walls-have-ears.fr.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"WHE.walls-have-ears": "Les murs ont des oreilles",
"WHE.settings.title": "Les murs ont des oreilles",
"WHE.save": "Enregistrer",
"WHE.settings_disable.title": "Désactiver le silencieux",
"WHE.settings_disable.hint": "Ce module permet d'étouffer les sons pour une meilleure intégration. Mais vous pouvez désactiver cette fonctionnalité pour des raisons de performances."
}
"WHE.walls-have-ears": "Les murs ont des oreilles",
"WHE.settings.title": "Les murs ont des oreilles",
"WHE.save": "Enregistrer",
"WHE.settings_disable.title": "Désactiver le silencieux",
"WHE.settings_disable.hint": "Ce module permet d'étouffer les sons pour une meilleure intégration. Mais vous pouvez désactiver cette fonctionnalité pour des raisons de performances.",
"WHE.settings_debug.title": "Activer le mode débogage",
"WHE.settings_debug.hint": "Afin de dépanner vos scènes, activez cette option pour voir l'indice d'étouffement lors de la sélection/déplacement de vos jetons."
}
14 changes: 8 additions & 6 deletions languages/walls-have-ears.pt-BR.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"WHE.walls-have-ears": "As paredes têm orelhas",
"WHE.settings.title": "As paredes têm orelhas",
"WHE.save": "Salvar",
"WHE.settings_disable.title": "Desativar abafamento de som",
"WHE.settings_disable.hint": "Este módulo permite que os sons sejam abafados para uma melhor imersão. Mas você pode desativar esse recurso por motivos de desempenho."
}
"WHE.walls-have-ears": "As paredes têm orelhas",
"WHE.settings.title": "As paredes têm orelhas",
"WHE.save": "Salvar",
"WHE.settings_disable.title": "Desativar abafamento de som",
"WHE.settings_disable.hint": "Este módulo permite que os sons sejam abafados para uma melhor imersão. Mas você pode desativar esse recurso por motivos de desempenho.",
"WHE.settings_debug.title": "Ativar o modo de depuração",
"WHE.settings_debug.hint": "Para solucionar problemas de suas cenas, ative isso para ver o índice de abafamento ao selecionar/mover seus tokens."
}
4 changes: 2 additions & 2 deletions module.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"authors": [],
"url": "https://github.com/SebaSOFT/walls-have-ears",
"flags": {},
"version": "1.0.0",
"version": "1.0.1",
"minimumCoreVersion": "9",
"compatibleCoreVersion": "9",
"scripts": [],
Expand Down Expand Up @@ -47,7 +47,7 @@
"dependencies": [],
"socket": false,
"manifest": "https://github.com/SebaSOFT/walls-have-ears/releases/latest/download/module.json",
"download": "https://github.com/SebaSOFT/walls-have-ears/releases/download/1.0.0/module.zip",
"download": "https://github.com/SebaSOFT/walls-have-ears/releases/download/1.0.1/module.zip",
"protected": false,
"coreTranslation": false
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "walls-have-ears",
"version": "0.0.4",
"version": "1.0.1",
"description": "A simple-as-possible module to muffle sounds that are behind a wall for a player.",
"main": "scripts/main.js",
"scripts": {
Expand Down
8 changes: 6 additions & 2 deletions scripts/WHE.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,23 @@ export default class WHE {
static MODULE = 'walls-have-ears';

static SETTING_DISABLE = 'client-disable';
static SETTING_DEBUG = 'client-debug';

static STR_SETTING_DISABLE_TITLE = 'WHE.settings_disable.title';
static STR_SETTING_DISABLE_HINT = 'WHE.settings_disable.hint';
static STR_SETTING_DEBUG_TITLE = 'WHE.settings_debug.title';
static STR_SETTING_DEBUG_HINT = 'WHE.settings_debug.hint';

static debug = false;

/**
* Gets a translated message text
* @param msgKey the key that will be translated, see constants
* @param paramMap (Optional) a map of variables that should be in the translated string
* @returns {string} the translated key or the key text
*/
static getMessageText(msgKey) {
return game.i18n.localize(msgKey);
static getMessageText(msgKey, paramMap = null) {
return (!paramMap) ? game.i18n.localize(msgKey) : game.i18n.format(msgKey, paramMap);
}

/**
Expand Down
75 changes: 55 additions & 20 deletions scripts/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import WHE from './WHE.js';

window.WHE = window.WHE || WHE;

let debugEnabled = false;
let wallsSoundsDisabled = true;
let listenerToken = null;

Expand All @@ -29,10 +30,26 @@ Hooks.once('setup', function () {

// Get User Options
wallsSoundsDisabled = game.settings.get(WHE.MODULE, WHE.SETTING_DISABLE);
debugEnabled = game.settings.get(WHE.MODULE, WHE.SETTING_DEBUG);
WHE.debug = debugEnabled;

WHE.logMessage('module setup finished');
});

/* ------------------------------------ */
// Settings changed
/* ------------------------------------ */
Hooks.on('closeSettingsConfig', function () {
WHE.logMessage('updateToken called');

// Get User Options
wallsSoundsDisabled = game.settings.get(WHE.MODULE, WHE.SETTING_DISABLE);
debugEnabled = game.settings.get(WHE.MODULE, WHE.SETTING_DEBUG);
WHE.debug = debugEnabled;

WHE.logMessage('settings reloaded');
});

/* ------------------------------------ */
// When ready
/* ------------------------------------ */
Expand Down Expand Up @@ -77,13 +94,18 @@ Hooks.on('updateWall', (_token, _updateData, _options, _userId) => {
/* ------------------------------------ */
Hooks.on('updateAmbientSound', (_ambientSound, _updateData, _options, _userId) => {
WHE.logMessage('updateAmbientSound called');

if (listenerToken) {
doTheMuffling();
}
});

// If its a gamemaster, lets get the controlled token
/* ------------------------------------ */
// When the user starts controlling a token
/* ------------------------------------ */
Hooks.on('controlToken', async (token, selected) => {
WHE.logMessage('controlToken called');

if (!selected) {
WHE.logMessage('No token selected but getting from user');
listenerToken = getActingToken({
Expand All @@ -106,7 +128,7 @@ Hooks.on('controlToken', async (token, selected) => {
/**
* This will create filter nodes and assign to global variables for reuse.
* This could be changes in the future as some sounds or sound listening
* events may need different parameters depending the occasion
* events may need different parameters depending on the occasion
*
* @param context : AudioContext
* @param muffling : int
Expand All @@ -129,6 +151,10 @@ function getAudioMuffler(context, muffling) {
return audioMuffler;
}

/**
* Loops through the sounds in the scene and estimate if its audible and the eventual
* muffling index, after estimate that, applies the audio filter correspondingly
*/
function doTheMuffling() {

if (wallsSoundsDisabled) return;
Expand All @@ -144,7 +170,7 @@ function doTheMuffling() {
* @type {AmbientSound[]}
*/
const ambientSounds = game.canvas.sounds.placeables;
WHE.logMessage('The SOUNDS: ', ambientSounds);
WHE.logMessage('The sounds: ', ambientSounds);
if (ambientSounds && ambientSounds.length > 0) {
for (let i = 0; i < ambientSounds.length; i++) {
const currentAmbientSound = ambientSounds[i];
Expand All @@ -155,7 +181,7 @@ function doTheMuffling() {

//Added in 0.8.x for Darkness range setting
if (!currentAmbientSound.isAudible) {
console.warn('WHE | Sound not Audible for some reason');
console.warn('WHE | Sound not Audible for (probably is just turned off)');
continue;
}
if (!soundMediaSource.context) {
Expand All @@ -170,15 +196,14 @@ function doTheMuffling() {
};

const distanceToSound = canvas.grid.measureDistance(tokenPosition, soundPosition);
WHE.logMessage('WHE | Sound ' + i, soundMediaSource, currentSoundRadius, distanceToSound);
WHE.logMessage('Sound ' + i, soundMediaSource, currentSoundRadius, distanceToSound);

if (currentSoundRadius < Math.floor(distanceToSound)) {
continue;
}

const muffleIndex = getMufflingIndex(soundPosition, tokenPosition);
if (muffleIndex < 0) {
// clearSound(soundMediaSource.container.gainNode);
WHE.logMessage('Sound ' + i, currentAmbientSound, soundMediaSource);
continue;
}
Expand All @@ -198,21 +223,18 @@ function doTheMuffling() {
clearSound(soundMediaSource.container.gainNode);
}
} else {
WHE.logMessage('Im FAR AWAY! and IS PLAYING');
// clearSound(soundMediaSource.container.gainNode);
// continue;
WHE.logMessage('Sound is too far away!');
}
} else {
// Schedule on start to take into consideration the moment
// the user hasn-t yet interacted with the browser so sound is unavailable
WHE.logMessage('WIll muffle on start');
// the user hasn't yet interacted with the browser so sound is unavailable
WHE.logMessage('WIll muffle on start if needed');
soundMediaSource.on('start', function (soundSource) {
// Muffle as needed
if (shouldBeMuffled) {
injectFilterIfPossible(soundSource.container.gainNode, audioMuffler);
} else {
WHE.logMessage('ON START Should not be muffled');
// clearSound(soundSource.container.gainNode);
WHE.logMessage('Sound is starting but should not be muffled');
}
});
}
Expand Down Expand Up @@ -254,7 +276,15 @@ function clearSound(sourceNode) {
sourceNode.connect(sourceNode.context.destination);
}

// Get if ywo points have a wall
/**
* Ray casts the sound and the token and estimate a muffling index
*
* @param number x1 x of the token
* @param number y1 y of the token
* @param number x2 x of the sound
* @param number y2 y of the sound
* @returns number returns the muffling index or -1 if the sound shouldn't be heard
*/
function getMufflingIndex({ x: x1, y: y1 }, { x: x2, y: y2 }) {
const ray = new Ray({ x: x1, y: y1 }, { x: x2, y: y2 });

Expand All @@ -263,18 +293,18 @@ function getMufflingIndex({ x: x1, y: y1 }, { x: x2, y: y2 }) {
mode: 'any',
});
if (hasSoundOccluded) {
WHE.logMessage('NO ABLE TO HEAR');
WHE.logMessage('This sound should not be heard (sound proof walls)');
return -1;
}

// If you dont see it, it's muffled
const sensesCollision = canvas.walls.checkCollision(ray, {
const sensesCollisions = canvas.walls.checkCollision(ray, {
type: 'sight',
mode: 'all',
});

// Then again if terrain collissions exist, you are in the same room
const noTerrainSightCollisions = sensesCollision.filter((impactVertex) => {
const noTerrainSenseCollisions = sensesCollisions.filter((impactVertex) => {
const wall = impactVertex?.edges?.first()?.isLimited;
return !wall;
});
Expand All @@ -285,13 +315,18 @@ function getMufflingIndex({ x: x1, y: y1 }, { x: x2, y: y2 }) {
mode: 'all',
});

// Present the results
WHE.logMessage('Collision walls (MOVE):', moveCollisions.length);
WHE.logMessage('Collision walls (SENSE):', sensesCollisions.length);
WHE.logMessage('Collision walls (SENSE excl. terrain ):', noTerrainSenseCollisions.length);

// Estimating how much to muffle
// See image:
const finalMuffling = Math.floor((noTerrainSightCollisions.length + moveCollisions.length) / 2);
const finalMuffling = Math.floor((noTerrainSenseCollisions.length + moveCollisions.length) / 2);

WHE.logMessage('MOVE SENSE Coll', moveCollisions, sensesCollision);
// Account for ethereal walls
if (sensesCollision.length >= 1 && moveCollisions.length === 0) {
if (sensesCollisions.length >= 1 && moveCollisions.length === 0) {
WHE.logMessage('There is at least an ethereal wall');
return 0;
}

Expand Down
10 changes: 10 additions & 0 deletions scripts/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ Hooks.once('init', async function () {
default: false
});

game.settings.register(WHE.MODULE, WHE.SETTING_DEBUG, {
name: WHE.getMessageText(WHE.STR_SETTING_DEBUG_TITLE),
hint: WHE.getMessageText(WHE.STR_SETTING_DEBUG_HINT),
scope: 'client',
config: true,
type: Boolean,
default: false
});


// Register custom sheets (if any)
// console.log('walls-have-ears | settings registration finished');
});

0 comments on commit 19798f9

Please sign in to comment.