BlueGit

timfa questward

Files

questward / shared / lighting / combatLight.js

combatLight.js

combatLight.js 2.5 KiB Download Raw
1import { CHUNK_SIZE } from "../protocol/constants.js";
2import { lightIntensity, falloffAtDistance } from "./raycast.js";
3import { equippedLightRadiusTiles } from "../definitions/items.js";
4import { statusExtraLightRadius } from "../statusEffects/rules.js";
5
6/** Night ambient darkness 0–1 (matches client `nightFactor`). */
7export function nightFactor (hour, nightDarkness = 0.72)
8{
9 const peak = Math.min(1, Math.max(0, nightDarkness));
10 if (hour >= 8 && hour <= 16)
11 { return 0; }
12 if (hour >= 22 || hour <= 5)
13 { return peak; }
14 if (hour < 8)
15 { return lerp(peak, 0, (hour - 5) / 3); }
16 return lerp(0, peak, (hour - 16) / 6);
17}
18
19function lerp (a, b, t)
20{
21 return a + (b - a) * Math.min(1, Math.max(0, t));
22}
23
24function chebyshev (ax, ay, bx, by)
25{
26 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
27}
28
29/** Baked static light 0–1 at a tile (0 when unlit / unbaked). */
30export function bakedTileLight01 (lightArray, index)
31{
32 if (!lightArray || index < 0 || index >= lightArray.length)
33 { return 0; }
34 return lightIntensity(lightArray[index] ?? 0);
35}
36
37/** Combined target-tile lighting 0–1 for combat (static + entity lights + time of day). */
38export function tileCombatLight01 ({
39 bakedLight01 = 0,
40 entityLight01 = 0,
41 worldHour = 12,
42 nightDarkness = 0.72
43} = {})
44{
45 const localLit = Math.min(1, Math.max(bakedLight01, entityLight01));
46 const ambientDark = nightFactor(worldHour, nightDarkness);
47 return 1 - ambientDark * (1 - localLit);
48}
49
50/** Best dynamic entity light reaching a tile (0–1). */
51export function entityLightAtTile (ecs, Component, tileX, tileY, now = Date.now())
52{
53 let best = 0;
54 for (const entity of ecs.query(Component.position))
55 {
56 const radius = entityLightRadiusTiles(ecs, entity.handle, Component, now);
57 if (radius <= 0)
58 { continue; }
59 const dist = chebyshev(entity.position.tileX, entity.position.tileY, tileX, tileY);
60 if (dist > radius)
61 { continue; }
62 best = Math.max(best, falloffAtDistance(dist, radius));
63 }
64 return best;
65}
66
67function entityLightRadiusTiles (ecs, handle, Component, now)
68{
69 const equipment = ecs.get(handle, Component.equipment);
70 const gear = equippedLightRadiusTiles(equipment);
71 const status = statusExtraLightRadius(ecs.get(handle, Component.statusEffects), now);
72 return Math.max(gear, status);
73}
74
75export function tileIndexLocal (tileX, tileY, chunkSize = CHUNK_SIZE)
76{
77 const localX = ((tileX % chunkSize) + chunkSize) % chunkSize;
78 const localY = ((tileY % chunkSize) + chunkSize) % chunkSize;
79 return localY * chunkSize + localX;
80}