All user data for FoundryVTT. Includes worlds, systems, modules, and any asset in the "foundryuserdata" directory. Does NOT include the FoundryVTT installation itself.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

427 lines
15 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. import { getWallBounds,getSceneSettings,migrateData,getLevelsBounds,getAdvancedLighting,migrateTokenHeight } from "./utils.js";
  2. const MODULE_ID = "wall-height";
  3. class WallHeightUtils{
  4. constructor(){
  5. this._advancedVision = null;
  6. this._currentTokenElevation = null;
  7. this.isLevels = game.modules.get("levels")?.active ?? false;
  8. this._isLevelsAutoCover = game.modules.get("levelsautocover")?.active ?? false;
  9. this._autoLosHeight = false;
  10. this._defaultTokenHeight = 6;
  11. }
  12. cacheSettings(){
  13. this._autoLosHeight = game.settings.get(MODULE_ID, 'autoLOSHeight');
  14. this._defaultTokenHeight = game.settings.get(MODULE_ID, 'defaultLosHeight');
  15. this._blockSightMovement = game.settings.get(MODULE_ID, "blockSightMovement");
  16. this._enableWallText = game.settings.get(MODULE_ID, "enableWallText");
  17. this.schedulePerceptionUpdate();
  18. }
  19. get tokenElevation(){
  20. return this._token?.document?.elevation ?? this.currentTokenElevation
  21. }
  22. set currentTokenElevation(elevation) {
  23. let update = false;
  24. const { advancedVision } = getSceneSettings(canvas.scene);
  25. if (this._currentTokenElevation !== elevation) {
  26. this._currentTokenElevation = elevation;
  27. if (advancedVision) {
  28. update = true;
  29. }
  30. }
  31. if (this._advancedVision !== !!advancedVision) {
  32. this._advancedVision = !!advancedVision;
  33. update = true;
  34. }
  35. if (update) {
  36. this.schedulePerceptionUpdate();
  37. }
  38. }
  39. get currentTokenElevation(){
  40. return this._currentTokenElevation;
  41. }
  42. schedulePerceptionUpdate(){
  43. if (!canvas.ready) return;
  44. canvas.perception.update({
  45. initializeLighting: true,
  46. initializeSounds: true,
  47. initializeVision: true,
  48. refreshLighting: true,
  49. refreshSounds: true,
  50. refreshTiles: true,
  51. refreshVision: true,
  52. }, true);
  53. }
  54. updateCurrentTokenElevation() {
  55. const token = canvas.tokens.controlled.find(t => t.document.sight.enabled) ?? canvas.tokens.controlled[0];
  56. if (!token && game.user.isGM) {
  57. this.currentTokenElevation = null;
  58. this._token = null;
  59. } else if (token) {
  60. this.currentTokenElevation = token.losHeight
  61. this._token = token;
  62. }
  63. }
  64. async setSourceElevationTop(document, value) {
  65. if (document instanceof TokenDocument) return;
  66. return await document.update({ "flags.levels.rangeTop": value });
  67. }
  68. getSourceElevationTop(document) {
  69. if (document instanceof TokenDocument) return document.object.losHeight
  70. return document.document.flags?.levels?.rangeTop ?? +Infinity;
  71. }
  72. async setSourceElevationBottom(document, value) {
  73. if (document instanceof TokenDocument) return await document.update({ "elevation": bottom });
  74. return await document.update({ "flags.levels.rangeBottom": value });
  75. }
  76. getSourceElevationBottom(document) {
  77. if (document instanceof TokenDocument) return document.document.elevation;
  78. return document.document.flags?.levels?.rangeBottom ?? -Infinity;
  79. }
  80. async setSourceElevationBounds(document, bottom, top) {
  81. if (document instanceof TokenDocument) return await document.update({ "elevation": bottom });
  82. return await document.update({ "flags.levels.rangeBottom": bottom, "flags.levels.rangeTop": top });
  83. }
  84. getSourceElevationBounds(document) {
  85. if (document instanceof TokenDocument) {
  86. const bottom = document.document.elevation;
  87. const top = document.object
  88. ? document.object.losHeight
  89. : bottom;
  90. return { bottom, top };
  91. }
  92. return getLevelsBounds(document);
  93. }
  94. async setSourceElevationBounds(document, bottom, top) {
  95. if (document instanceof TokenDocument) return await document.update({ "elevation": bottom });
  96. return await document.update({ "flags.levels.rangeBottom": bottom, "flags.levels.rangeTop": top });
  97. }
  98. getSourceElevationBounds(document) {
  99. if (document instanceof TokenDocument) {
  100. const bottom = document.elevation;
  101. const top = document.object
  102. ? document.object.losHeight
  103. : bottom;
  104. return { bottom, top };
  105. }
  106. return getLevelsBounds(document);
  107. }
  108. async removeOneToWalls(scene){
  109. if(!scene) scene = canvas.scene;
  110. const walls = Array.from(scene.walls);
  111. const updates = [];
  112. for(let wall of walls){
  113. const oldTop = wall.document.flags?.["wall-height"]?.top;
  114. if(oldTop != null && oldTop != undefined){
  115. const newTop = oldTop - 1;
  116. updates.push({_id: wall.id, "flags.wall-height.top": newTop});
  117. }
  118. }
  119. if(updates.length <= 0) return false;
  120. await scene.updateEmbeddedDocuments("Wall", updates);
  121. ui.notifications.notify("Wall Height - Added +1 to " + updates.length + " walls in scene " + scene.name);
  122. return true;
  123. }
  124. async migrateTokenHeight(){
  125. return await migrateTokenHeight();
  126. }
  127. async migrateData(scene){
  128. return await migrateData(scene);
  129. }
  130. async migrateCompendiums (){
  131. let migratedScenes = 0;
  132. const compendiums = Array.from(game.packs).filter(p => p.documentName === 'Scene');
  133. for (const compendium of compendiums) {
  134. const scenes = await compendium.getDocuments();
  135. for(const scene of scenes){
  136. const migrated = await migrateData(scene);
  137. if(migrated) migratedScenes++;
  138. }
  139. }
  140. if(migratedScenes > 0){
  141. ui.notifications.notify(`Wall Height - Migrated ${migratedScenes} scenes to new Wall Height data structure.`);
  142. console.log(`Wall Height - Migrated ${migratedScenes} scenes to new Wall Height data structure.`);
  143. }else{
  144. ui.notifications.notify(`Wall Height - No scenes to migrate.`);
  145. console.log(`Wall Height - No scenes to migrate.`);
  146. }
  147. return migratedScenes;
  148. }
  149. async migrateScenes (){
  150. const scenes = Array.from(game.scenes);
  151. let migratedScenes = 0;
  152. ui.notifications.warn("Wall Height - Migrating all scenes, do not refresh the page!");
  153. for(const scene of scenes){
  154. const migrated = await migrateData(scene);
  155. if(migrated) migratedScenes++;
  156. }
  157. if(migratedScenes > 0){
  158. ui.notifications.notify(`Wall Height - Migrated ${migratedScenes} scenes to new Wall Height data structure.`);
  159. console.log(`Wall Height - Migrated ${migratedScenes} scenes to new Wall Height data structure.`);
  160. }else{
  161. ui.notifications.notify(`Wall Height - No scenes to migrate.`);
  162. console.log(`Wall Height - No scenes to migrate.`);
  163. }
  164. return migratedScenes;
  165. }
  166. async migrateAll(){
  167. ui.notifications.error(`Wall Height - WARNING: The new data structure requires Better Roofs, Levels and 3D Canvas and Token Attacher to be updated!`);
  168. await WallHeight.migrateScenes();
  169. await WallHeight.migrateCompendiums();
  170. ui.notifications.notify(`Wall Height - Migration Complete.`);
  171. await game.settings.set(MODULE_ID, 'migrateOnStartup', false);
  172. }
  173. async setWallBounds(bottom, top, walls){
  174. if(!walls) walls = canvas.walls.controlled.length ? canvas.walls.controlled : canvas.walls.placeables;
  175. walls instanceof Array || (walls = [walls]);
  176. const updates = [];
  177. for(let wall of walls){
  178. updates.push({_id: wall.id, "flags.wall-height.top": top, "flags.wall-height.bottom": bottom});
  179. }
  180. return await canvas.scene.updateEmbeddedDocuments("Wall", updates);
  181. }
  182. getWallBounds(wall){
  183. return getWallBounds(wall);
  184. }
  185. addBoundsToRays(rays, token) {
  186. if (token) {
  187. const bottom = token.document.elevation;
  188. const top = WallHeight._blockSightMovement ? token.losHeight : token.document.elevation;
  189. for (const ray of rays) {
  190. ray.A.b = bottom;
  191. ray.A.t = top;
  192. }
  193. }
  194. return rays;
  195. }
  196. }
  197. export function registerWrappers() {
  198. globalThis.WallHeight = new WallHeightUtils();
  199. if(!globalThis.WallHeight.isLevels){
  200. Object.defineProperty(AmbientLightDocument.prototype, "elevation", {
  201. get: function () {
  202. return this.flags?.levels?.rangeBottom ?? canvas.primary.background.elevation;
  203. }
  204. });
  205. }
  206. function tokenOnUpdate(wrapped, ...args) {
  207. wrapped(...args);
  208. updateTokenSourceBounds(this);
  209. }
  210. function updateTokenSourceBounds(token) {
  211. const { advancedVision } = getSceneSettings(token.scene);
  212. const losHeight = token.losHeight;
  213. const sourceId = token.sourceId;
  214. if (!advancedVision) {
  215. if (canvas.effects.visionSources.has(sourceId)) {
  216. token.vision.los.origin.b = token.vision.los.origin.t = losHeight;
  217. }
  218. if (canvas.effects.lightSources.has(sourceId)) {
  219. token.light.los.origin.b = token.light.los.origin.t = losHeight;
  220. }
  221. } else if (canvas.effects.visionSources.has(sourceId) && (token.vision.los.origin.b !== losHeight || token.vision.los.origin.t !== losHeight)
  222. || canvas.effects.lightSources.has(sourceId) && (token.light.los.origin.b !== losHeight || token.light.los.origin.t !== losHeight)) {
  223. token.updateSource({ defer: true });
  224. canvas.perception.update({
  225. initializeLighting: true,
  226. initializeSounds: true,
  227. initializeVision: true,
  228. refreshLighting: true,
  229. refreshSounds: true,
  230. refreshTiles: true,
  231. refreshVision: true,
  232. }, true);
  233. }
  234. }
  235. function testWallInclusion(wrapped, ...args) {
  236. if (!wrapped(...args)) return false;
  237. const wall = args[0]
  238. const { advancedVision } = getSceneSettings(wall.scene);
  239. if (!advancedVision) return true;
  240. const { top, bottom } = getWallBounds(wall);
  241. const b = this.config?.source?.object?.b ?? this.origin?.object?.b ?? -Infinity;
  242. const t = this.config?.source?.object?.t ?? this.origin?.object?.t ?? +Infinity;
  243. return b >= bottom && t <= top;
  244. }
  245. function isDoorVisible(wrapped, ...args) {
  246. const wall = this.wall;
  247. const { advancedVision } = getSceneSettings(wall.scene);
  248. const isUI = CONFIG.Levels?.UI?.rangeEnabled && !canvas?.tokens?.controlled[0];
  249. const elevation = WallHeight.currentTokenElevation//isUI && !canvas.tokens.controlled[0] ? WallHeight.currentTokenElevation : WallHeight._token?.document?.elevation;
  250. if (elevation == null || !advancedVision) return wrapped(...args);
  251. const {top, bottom} = getWallBounds(wall);
  252. let inRange = elevation >= bottom && elevation <= top;
  253. if (isUI) inRange = elevation >= bottom && elevation < top;
  254. //if (elevation < bottom || elevation > top) return false;
  255. return wrapped(...args) && inRange;
  256. }
  257. function setSourceElevation(wrapped, origin, config = {}, ...args) {
  258. let bottom = -Infinity;
  259. let top = +Infinity;
  260. const object = config.source?.object ?? origin.object;
  261. if (origin.b == undefined && origin.t == undefined) {
  262. if (object instanceof Token) {
  263. if (config.type !== "move") {
  264. bottom = top = object.losHeight;
  265. } else {
  266. bottom = object.document.elevation;
  267. top = WallHeight._blockSightMovement ? object.losHeight : bottom;
  268. }
  269. } else if (object instanceof AmbientLight || object instanceof AmbientSound) {
  270. if (getAdvancedLighting(object.document)) {
  271. const bounds = getLevelsBounds(object.document)//WallHeight.getElevation(object.document);
  272. bottom = bounds.bottom;
  273. top = bounds.top;
  274. } else {
  275. bottom = WallHeight.currentTokenElevation;
  276. if (bottom == null) {
  277. bottom = -Infinity;
  278. top = +Infinity;
  279. } else {
  280. top = bottom;
  281. }
  282. }
  283. }
  284. }
  285. if(object){
  286. object.b = origin.b ?? config.b ?? bottom;
  287. object.t = origin.t ?? config.t ?? top;
  288. }
  289. return wrapped(origin, config, ...args);
  290. }
  291. function pointSourceInitialize(wrapped, ...args) {
  292. if(this.object) args[0].elevation = this.object.losHeight ?? this.object.document.elevation;
  293. return wrapped(...args);
  294. }
  295. function drawWallRange(wrapped, ...args) {
  296. const { advancedVision } = getSceneSettings(canvas.scene);
  297. const bounds = getWallBounds(this);
  298. if(!this.line && !WallHeight._enableWallText || !advancedVision || (bounds.top == Infinity && bounds.bottom == -Infinity)) {
  299. if(this.line) this.line.children = this.line.children.filter(c => c.name !== "wall-height-text");
  300. return wrapped(...args);
  301. }
  302. wrapped(...args);
  303. const style = CONFIG.canvasTextStyle.clone();
  304. style.fontSize /= 1.5;
  305. style.fill = this._getWallColor();
  306. if(bounds.top == Infinity) bounds.top = "Inf";
  307. if(bounds.bottom == -Infinity) bounds.bottom = "-Inf";
  308. const range = `${bounds.top} / ${bounds.bottom}`;
  309. const oldText = this.line.children.find(c => c.name === "wall-height-text");
  310. const text = oldText ?? new PreciseText(range, style);
  311. text.text = range;
  312. text.name = "wall-height-text";
  313. text.interactiveChildren = false;
  314. let angle = (Math.atan2( this.coords[3] - this.coords[1], this.coords[2] - this.coords[0] ) * ( 180 / Math.PI ));
  315. angle = (angle+90)%180 - 90;
  316. text.position.set(this.center.x, this.center.y);
  317. text.anchor.set(0.5, 0.5);
  318. text.angle = angle;
  319. if(!oldText) this.line.addChild(text)//this.addChild(text);
  320. }
  321. Hooks.on("updateToken", () => {
  322. WallHeight.updateCurrentTokenElevation();
  323. });
  324. Hooks.on("controlToken", () => {
  325. WallHeight.updateCurrentTokenElevation();
  326. });
  327. Hooks.on("updateScene", (doc, change) => {
  328. WallHeight.updateCurrentTokenElevation();
  329. });
  330. Hooks.on("canvasInit", () => {
  331. WallHeight._advancedVision = null;
  332. WallHeight._currentTokenElevation = null;
  333. WallHeight._token = null;
  334. });
  335. Hooks.on("canvasReady", () => {
  336. WallHeight.updateCurrentTokenElevation();
  337. });
  338. Hooks.on("updateWall", (wall, updates) => {
  339. if(updates.flags && updates.flags[MODULE_ID]) {
  340. WallHeight.schedulePerceptionUpdate();
  341. }
  342. if(canvas.walls.active) wall.object.refresh();
  343. })
  344. Hooks.on("activateWallsLayer", () => {
  345. canvas.walls.placeables.forEach(w => w.refresh());
  346. });
  347. libWrapper.register(MODULE_ID, "DoorControl.prototype.isVisible", isDoorVisible, "MIXED");
  348. libWrapper.register(MODULE_ID, "CONFIG.Token.objectClass.prototype._onUpdate", tokenOnUpdate, "WRAPPER");
  349. libWrapper.register(MODULE_ID, "ClockwiseSweepPolygon.prototype._testWallInclusion", testWallInclusion, "WRAPPER", { perf_mode: "FAST" });
  350. libWrapper.register(MODULE_ID, "ClockwiseSweepPolygon.prototype.initialize", setSourceElevation, "WRAPPER");
  351. libWrapper.register(MODULE_ID, "RenderedPointSource.prototype._initialize", pointSourceInitialize, "WRAPPER");
  352. libWrapper.register(MODULE_ID, "Wall.prototype.refresh", drawWallRange, "WRAPPER");
  353. libWrapper.register(
  354. MODULE_ID,
  355. "VisionSource.prototype.elevation",
  356. function () {
  357. return this.object?.losHeight ?? canvas.primary.background.elevation;
  358. },
  359. libWrapper.OVERRIDE,
  360. { perf_mode: libWrapper.PERF_FAST }
  361. );
  362. libWrapper.register(
  363. MODULE_ID,
  364. "LightSource.prototype.elevation",
  365. function () {
  366. return this.object instanceof Token
  367. ? this.object.losHeight
  368. : this.object?.document?.elevation ?? canvas.primary.background.elevation;
  369. },
  370. libWrapper.OVERRIDE,
  371. { perf_mode: libWrapper.PERF_FAST }
  372. );
  373. }