magics
@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#c03010"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">BL</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#c03010"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">BL</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#2a2040"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">DK</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#2a2040"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">DK</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#4a3060"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">DR</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#4a3060"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">DR</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#d04020"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FA</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#d04020"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FA</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#e06030"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FB</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#e06030"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FB</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#801010"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">HF</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#801010"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">HF</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#a02010"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">IN</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#a02010"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">IN</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#3a8040"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">PO</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#3a8040"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">PO</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#4080c0"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">RV</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#4080c0"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">RV</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#303040"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SH</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#303040"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SH</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2
<rect width="32" height="32" rx="6" fill="#c08030"/>
3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">TI</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">2
<rect width="32" height="32" rx="6" fill="#c08030"/>3
<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">TI</text>4
</svg>@@ -1588,6 +1588,13 @@ async function main ()
1588
1588
case MessageType.spellLightRemove:
1589
1589
view?.removeSpellLight(message);
1590
1590
break;
1591
case MessageType.spellDarkAppear:
1592
case MessageType.spellDarkUpdate:
1593
view?.setSpellDark(message);
1594
break;
1595
case MessageType.spellDarkRemove:
1596
view?.removeSpellDark(message);
1597
break;
1591
1598
case MessageType.stamina:
1592
1599
staminaUi?.apply(message);
1593
1600
if (message.gait)
@@ -1588,6 +1588,13 @@ async function main ()1588
case MessageType.spellLightRemove:1588
case MessageType.spellLightRemove:1589
view?.removeSpellLight(message);1589
view?.removeSpellLight(message);1590
break;1590
break;1591
case MessageType.spellDarkAppear:1592
case MessageType.spellDarkUpdate:1593
view?.setSpellDark(message);1594
break;1595
case MessageType.spellDarkRemove:1596
view?.removeSpellDark(message);1597
break;1591
case MessageType.stamina:1598
case MessageType.stamina:1592
staminaUi?.apply(message);1599
staminaUi?.apply(message);1593
if (message.gait)1600
if (message.gait)@@ -1,5 +1,5 @@
1
1
import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2
import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
2
import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3
3
import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4
4
import { bakeChunkOcclusion } from "/shared/lighting/chunkOcclusion.js";
5
5
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
@@ -48,6 +48,8 @@ const GATHER_TOOL_HOLD_MS = 1100;
48
48
const DAMAGE_FLASH_MS = 180;
49
49
const DAMAGE_FLOAT_MS = 900;
50
50
const SKILL_LEVEL_FLOAT_MS = 2800;
51
/** Projectiles spawn this many sprite-pixels below the caster sprite top. */
52
const PROJECTILE_LAUNCH_FROM_TOP_PX = 4;
51
53
52
54
const SPRITE_LIGHTING_FRAG = [
53
55
"precision mediump float;",
@@ -422,6 +424,8 @@ export class WorldView
422
424
this.dynamicLights = [];
423
425
/** Persistent Light-spell tile lights (server-driven). */
424
426
this.spellLights = new Map();
427
/** Persistent Dark-spell tile darkness (server-driven). */
428
this.spellDarks = new Map();
425
429
this.swipes = [];
426
430
this.damageFloats = [];
427
431
this.damageNumbersEl = document.getElementById("damage-numbers");
@@ -1443,8 +1447,16 @@ export class WorldView
1443
1447
if (!image)
1444
1448
{ return; }
1445
1449
const dualTint = this.#dualTintFromPayload(payload);
1446
const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
1447
const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1450
const fromPivot = this.#projectileLaunchPoint(
1451
payload.attackerId ?? null,
1452
payload.fromTileX,
1453
payload.fromTileY
1454
);
1455
const toPivot = this.#projectileAimPoint(
1456
payload.targetId ?? null,
1457
payload.tileX,
1458
payload.tileY
1459
);
1448
1460
const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1449
1461
const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1450
1462
const object = new GameObject(0, 0, image, SORT_FX);
@@ -1481,15 +1493,23 @@ export class WorldView
1481
1493
});
1482
1494
}
1483
1495
1484
/** Bloom-layer spell projectiles — unlit, animated, 2s travel. */
1496
/** Bloom-layer spell projectiles — unlit, animated travel. */
1485
1497
spawnSpellProjectileFx (payload)
1486
1498
{
1487
1499
const baseSprite = payload.sprite ?? "fx:projectile:spell-light";
1488
1500
const image = this.#spellProjectileImage(baseSprite, 0);
1489
1501
if (!image)
1490
1502
{ return; }
1491
const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
1492
const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1503
const fromPivot = this.#projectileLaunchPoint(
1504
payload.casterId ?? null,
1505
payload.fromTileX,
1506
payload.fromTileY
1507
);
1508
const toPivot = this.#projectileAimPoint(
1509
payload.targetId ?? null,
1510
payload.tileX,
1511
payload.tileY
1512
);
1493
1513
const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1494
1514
const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1495
1515
const object = new GameObject(0, 0, image, SORT_FX);
@@ -1546,6 +1566,23 @@ export class WorldView
1546
1566
this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
1547
1567
}
1548
1568
1569
setSpellDark (payload)
1570
{
1571
const key = `${payload.tileX},${payload.tileY}`;
1572
this.spellDarks.set(key, {
1573
tileX: payload.tileX,
1574
tileY: payload.tileY,
1575
until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1576
range: payload.rangeTiles ?? 6,
1577
intensity: payload.intensity ?? 0.88
1578
});
1579
}
1580
1581
removeSpellDark (payload)
1582
{
1583
this.spellDarks.delete(`${payload.tileX},${payload.tileY}`);
1584
}
1585
1549
1586
#spellProjectileImage (baseSprite, frameIndex)
1550
1587
{
1551
1588
const frame = Math.max(0, Math.min(2, frameIndex | 0));
@@ -3318,6 +3355,24 @@ export class WorldView
3318
3355
if (this.spellLights.get(key).until <= now)
3319
3356
{ this.spellLights.delete(key); }
3320
3357
}
3358
const activeDarks = [];
3359
for (const dark of this.spellDarks.values())
3360
{
3361
if (dark.until <= now)
3362
{ continue; }
3363
activeDarks.push({
3364
tileX: dark.tileX,
3365
tileY: dark.tileY,
3366
range: dark.range,
3367
intensity: dark.intensity
3368
});
3369
}
3370
for (const key of [...this.spellDarks.keys()])
3371
{
3372
if (this.spellDarks.get(key).until <= now)
3373
{ this.spellDarks.delete(key); }
3374
}
3375
this._activeSpellDarks = activeDarks;
3321
3376
const tileSize = this.tileSize();
3322
3377
const blindLight = this.#blindVisionLight();
3323
3378
if (blindLight)
@@ -3393,7 +3448,13 @@ export class WorldView
3393
3448
activeLights,
3394
3449
lightOcclusion
3395
3450
);
3396
return Math.max(baked, dynamic);
3451
const dark = dynamicDarknessAtTile(
3452
objects.tileX,
3453
objects.tileY,
3454
this._activeSpellDarks ?? [],
3455
lightOcclusion
3456
);
3457
return Math.max(0, Math.max(baked, dynamic) - dark);
3397
3458
}
3398
3459
3399
3460
/** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
@@ -3412,7 +3473,8 @@ export class WorldView
3412
3473
const index = localY * CHUNK_SIZE + localX;
3413
3474
const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
3414
3475
const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
3415
return Math.max(bakedLit, dynamic);
3476
const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
3477
return Math.max(0, Math.max(bakedLit, dynamic) - dark);
3416
3478
}
3417
3479
3418
3480
/** True when ground or block on this tile occludes light rays (same rules as bake). */
@@ -3664,7 +3726,11 @@ export class WorldView
3664
3726
{
3665
3727
const durationMs = swipe.durationMs ?? 400;
3666
3728
const t = Math.min(1, (now - swipe.started) / durationMs);
3667
const fromPivot = tilePivot(swipe.fromTileX, swipe.fromTileY, this.tileSize());
3729
const fromPivot = this.#projectileLaunchPoint(
3730
swipe.attackerId ?? null,
3731
swipe.fromTileX,
3732
swipe.fromTileY
3733
);
3668
3734
const toPivot = this.#projectileEndPivot(swipe);
3669
3735
const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
3670
3736
const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
@@ -3726,14 +3792,46 @@ export class WorldView
3726
3792
#projectileEndPivot (swipe)
3727
3793
{
3728
3794
if (swipe.trackTarget && swipe.targetId != null)
3795
{ return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); }
3796
return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY);
3797
}
3798
3799
/**
3800
* Launch point: 4px below the top of the caster sprite (falls back to tile centre).
3801
*/
3802
#projectileLaunchPoint (entityId, tileX, tileY)
3803
{
3804
const entity = entityId != null ? this.entities.get(entityId) : null;
3805
if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
3729
3806
{
3730
const target = this.entities.get(swipe.targetId);
3731
if (target && Number.isFinite(target.visualX) && Number.isFinite(target.visualY))
3732
{
3733
return { x: target.visualX, y: target.visualY };
3734
}
3807
const zoom = this.zoom;
3808
const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
3809
const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
3810
const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
3811
const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom;
3812
return {
3813
x: pivotX,
3814
y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom
3815
};
3816
}
3817
return tilePivot(tileX, tileY, this.tileSize());
3818
}
3819
3820
/**
3821
* Aim point: sprite centre for creatures, tile centre for tile targets.
3822
*/
3823
#projectileAimPoint (entityId, tileX, tileY)
3824
{
3825
const entity = entityId != null ? this.entities.get(entityId) : null;
3826
if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
3827
{
3828
const zoom = this.zoom;
3829
const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
3830
const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
3831
const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
3832
return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom);
3735
3833
}
3736
return tilePivot(swipe.tileX, swipe.tileY, this.tileSize());
3834
return tilePivot(tileX, tileY, this.tileSize());
3737
3835
}
3738
3836
3739
3837
#updateDamageNumbers (now)
@@ -1,5 +1,5 @@1
import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";1
import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";2
import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";2
import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";3
import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";3
import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";4
import { bakeChunkOcclusion } from "/shared/lighting/chunkOcclusion.js";4
import { bakeChunkOcclusion } from "/shared/lighting/chunkOcclusion.js";5
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";5
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";@@ -48,6 +48,8 @@ const GATHER_TOOL_HOLD_MS = 1100;48
const DAMAGE_FLASH_MS = 180;48
const DAMAGE_FLASH_MS = 180;49
const DAMAGE_FLOAT_MS = 900;49
const DAMAGE_FLOAT_MS = 900;50
const SKILL_LEVEL_FLOAT_MS = 2800;50
const SKILL_LEVEL_FLOAT_MS = 2800;51
/** Projectiles spawn this many sprite-pixels below the caster sprite top. */52
const PROJECTILE_LAUNCH_FROM_TOP_PX = 4;51
53
52
const SPRITE_LIGHTING_FRAG = [54
const SPRITE_LIGHTING_FRAG = [53
"precision mediump float;",55
"precision mediump float;",@@ -422,6 +424,8 @@ export class WorldView422
this.dynamicLights = [];424
this.dynamicLights = [];423
/** Persistent Light-spell tile lights (server-driven). */425
/** Persistent Light-spell tile lights (server-driven). */424
this.spellLights = new Map();426
this.spellLights = new Map();427
/** Persistent Dark-spell tile darkness (server-driven). */428
this.spellDarks = new Map();425
this.swipes = [];429
this.swipes = [];426
this.damageFloats = [];430
this.damageFloats = [];427
this.damageNumbersEl = document.getElementById("damage-numbers");431
this.damageNumbersEl = document.getElementById("damage-numbers");@@ -1443,8 +1447,16 @@ export class WorldView1443
if (!image)1447
if (!image)1444
{ return; }1448
{ return; }1445
const dualTint = this.#dualTintFromPayload(payload);1449
const dualTint = this.#dualTintFromPayload(payload);1446
const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());1450
const fromPivot = this.#projectileLaunchPoint(1447
const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());1451
payload.attackerId ?? null,1452
payload.fromTileX,1453
payload.fromTileY1454
);1455
const toPivot = this.#projectileAimPoint(1456
payload.targetId ?? null,1457
payload.tileX,1458
payload.tileY1459
);1448
const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;1460
const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;1449
const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);1461
const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);1450
const object = new GameObject(0, 0, image, SORT_FX);1462
const object = new GameObject(0, 0, image, SORT_FX);@@ -1481,15 +1493,23 @@ export class WorldView1481
});1493
});1482
}1494
}1483
1495
1484
/** Bloom-layer spell projectiles — unlit, animated, 2s travel. */1496
/** Bloom-layer spell projectiles — unlit, animated travel. */1485
spawnSpellProjectileFx (payload)1497
spawnSpellProjectileFx (payload)1486
{1498
{1487
const baseSprite = payload.sprite ?? "fx:projectile:spell-light";1499
const baseSprite = payload.sprite ?? "fx:projectile:spell-light";1488
const image = this.#spellProjectileImage(baseSprite, 0);1500
const image = this.#spellProjectileImage(baseSprite, 0);1489
if (!image)1501
if (!image)1490
{ return; }1502
{ return; }1491
const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());1503
const fromPivot = this.#projectileLaunchPoint(1492
const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());1504
payload.casterId ?? null,1505
payload.fromTileX,1506
payload.fromTileY1507
);1508
const toPivot = this.#projectileAimPoint(1509
payload.targetId ?? null,1510
payload.tileX,1511
payload.tileY1512
);1493
const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;1513
const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;1494
const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);1514
const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);1495
const object = new GameObject(0, 0, image, SORT_FX);1515
const object = new GameObject(0, 0, image, SORT_FX);@@ -1546,6 +1566,23 @@ export class WorldView1546
this.spellLights.delete(`${payload.tileX},${payload.tileY}`);1566
this.spellLights.delete(`${payload.tileX},${payload.tileY}`);1547
}1567
}1548
1568
1569
setSpellDark (payload)1570
{1571
const key = `${payload.tileX},${payload.tileY}`;1572
this.spellDarks.set(key, {1573
tileX: payload.tileX,1574
tileY: payload.tileY,1575
until: performance.now() + Math.max(0, payload.remainingMs ?? 0),1576
range: payload.rangeTiles ?? 6,1577
intensity: payload.intensity ?? 0.881578
});1579
}1580
1581
removeSpellDark (payload)1582
{1583
this.spellDarks.delete(`${payload.tileX},${payload.tileY}`);1584
}1585
1549
#spellProjectileImage (baseSprite, frameIndex)1586
#spellProjectileImage (baseSprite, frameIndex)1550
{1587
{1551
const frame = Math.max(0, Math.min(2, frameIndex | 0));1588
const frame = Math.max(0, Math.min(2, frameIndex | 0));@@ -3318,6 +3355,24 @@ export class WorldView3318
if (this.spellLights.get(key).until <= now)3355
if (this.spellLights.get(key).until <= now)3319
{ this.spellLights.delete(key); }3356
{ this.spellLights.delete(key); }3320
}3357
}3358
const activeDarks = [];3359
for (const dark of this.spellDarks.values())3360
{3361
if (dark.until <= now)3362
{ continue; }3363
activeDarks.push({3364
tileX: dark.tileX,3365
tileY: dark.tileY,3366
range: dark.range,3367
intensity: dark.intensity3368
});3369
}3370
for (const key of [...this.spellDarks.keys()])3371
{3372
if (this.spellDarks.get(key).until <= now)3373
{ this.spellDarks.delete(key); }3374
}3375
this._activeSpellDarks = activeDarks;3321
const tileSize = this.tileSize();3376
const tileSize = this.tileSize();3322
const blindLight = this.#blindVisionLight();3377
const blindLight = this.#blindVisionLight();3323
if (blindLight)3378
if (blindLight)@@ -3393,7 +3448,13 @@ export class WorldView3393
activeLights,3448
activeLights,3394
lightOcclusion3449
lightOcclusion3395
);3450
);3396
return Math.max(baked, dynamic);3451
const dark = dynamicDarknessAtTile(3452
objects.tileX,3453
objects.tileY,3454
this._activeSpellDarks ?? [],3455
lightOcclusion3456
);3457
return Math.max(0, Math.max(baked, dynamic) - dark);3397
}3458
}3398
3459
3399
/** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */3460
/** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */@@ -3412,7 +3473,8 @@ export class WorldView3412
const index = localY * CHUNK_SIZE + localX;3473
const index = localY * CHUNK_SIZE + localX;3413
const bakedLit = lightIntensity(snapshot.light[index] ?? 0);3474
const bakedLit = lightIntensity(snapshot.light[index] ?? 0);3414
const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);3475
const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);3415
return Math.max(bakedLit, dynamic);3476
const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);3477
return Math.max(0, Math.max(bakedLit, dynamic) - dark);3416
}3478
}3417
3479
3418
/** True when ground or block on this tile occludes light rays (same rules as bake). */3480
/** True when ground or block on this tile occludes light rays (same rules as bake). */@@ -3664,7 +3726,11 @@ export class WorldView3664
{3726
{3665
const durationMs = swipe.durationMs ?? 400;3727
const durationMs = swipe.durationMs ?? 400;3666
const t = Math.min(1, (now - swipe.started) / durationMs);3728
const t = Math.min(1, (now - swipe.started) / durationMs);3667
const fromPivot = tilePivot(swipe.fromTileX, swipe.fromTileY, this.tileSize());3729
const fromPivot = this.#projectileLaunchPoint(3730
swipe.attackerId ?? null,3731
swipe.fromTileX,3732
swipe.fromTileY3733
);3668
const toPivot = this.#projectileEndPivot(swipe);3734
const toPivot = this.#projectileEndPivot(swipe);3669
const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;3735
const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;3670
const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;3736
const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;@@ -3726,14 +3792,46 @@ export class WorldView3726
#projectileEndPivot (swipe)3792
#projectileEndPivot (swipe)3727
{3793
{3728
if (swipe.trackTarget && swipe.targetId != null)3794
if (swipe.trackTarget && swipe.targetId != null)3795
{ return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); }3796
return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY);3797
}3798
3799
/**3800
* Launch point: 4px below the top of the caster sprite (falls back to tile centre).3801
*/3802
#projectileLaunchPoint (entityId, tileX, tileY)3803
{3804
const entity = entityId != null ? this.entities.get(entityId) : null;3805
if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))3729
{3806
{3730
const target = this.entities.get(swipe.targetId);3807
const zoom = this.zoom;3731
if (target && Number.isFinite(target.visualX) && Number.isFinite(target.visualY))3808
const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;3732
{3809
const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);3733
return { x: target.visualX, y: target.visualY };3810
const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);3734
}3811
const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom;3812
return {3813
x: pivotX,3814
y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom3815
};3816
}3817
return tilePivot(tileX, tileY, this.tileSize());3818
}3819
3820
/**3821
* Aim point: sprite centre for creatures, tile centre for tile targets.3822
*/3823
#projectileAimPoint (entityId, tileX, tileY)3824
{3825
const entity = entityId != null ? this.entities.get(entityId) : null;3826
if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))3827
{3828
const zoom = this.zoom;3829
const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;3830
const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);3831
const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);3832
return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom);3735
}3833
}3736
return tilePivot(swipe.tileX, swipe.tileY, this.tileSize());3834
return tilePivot(tileX, tileY, this.tileSize());3737
}3835
}3738
3836
3739
#updateDamageNumbers (now)3837
#updateDamageNumbers (now)@@ -25,7 +25,9 @@ export const Component = Object.freeze({
25
25
shop: "shop",
26
26
statusEffects: "statusEffects",
27
27
spells: "spells",
28
spellcasting: "spellcasting"
28
spellcasting: "spellcasting",
29
/** Temporary summoned companion (Shade). */
30
summon: "summon"
29
31
});
30
32
31
33
/** Default position component fields (tile coords + dimension). */
@@ -25,7 +25,9 @@ export const Component = Object.freeze({25
shop: "shop",25
shop: "shop",26
statusEffects: "statusEffects",26
statusEffects: "statusEffects",27
spells: "spells",27
spells: "spells",28
spellcasting: "spellcasting"28
spellcasting: "spellcasting",29
/** Temporary summoned companion (Shade). */30
summon: "summon"29
});31
});30
32
31
/** Default position component fields (tile coords + dimension). */33
/** Default position component fields (tile coords + dimension). */@@ -1820,7 +1820,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1820
1820
}
1821
1821
continue;
1822
1822
}
1823
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1823
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1824
1824
{ publishEntity(event); }
1825
1825
}
1826
1826
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1991,30 +1991,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1991
1991
});
1992
1992
continue;
1993
1993
}
1994
if (event.type === "spell-light-appear" || event.type === "spell-light-update")
1994
if (event.type === "spell-light-appear" || event.type === "spell-light-update"
1995
|| event.type === "spell-dark-appear" || event.type === "spell-dark-update")
1995
1996
{
1996
1997
if (!seesTo)
1997
1998
{ continue; }
1999
const isDark = event.type.startsWith("spell-dark");
2000
const appear = event.type.endsWith("appear");
1998
2001
send(session, {
1999
type: event.type === "spell-light-appear"
2000
? MessageType.spellLightAppear
2001
: MessageType.spellLightUpdate,
2002
type: appear
2003
? (isDark ? MessageType.spellDarkAppear : MessageType.spellLightAppear)
2004
: (isDark ? MessageType.spellDarkUpdate : MessageType.spellLightUpdate),
2002
2005
tileX: event.tileX,
2003
2006
tileY: event.tileY,
2004
2007
ownerEntityId: event.ownerEntityId,
2005
2008
remainingMs: event.remainingMs ?? 0,
2006
2009
rangeTiles: event.rangeTiles ?? 0,
2007
2010
intensity: event.intensity ?? 0,
2008
expiresAt: event.expiresAt ?? 0
2011
expiresAt: event.expiresAt ?? 0,
2012
kind: isDark ? "dark" : "light"
2009
2013
});
2010
2014
continue;
2011
2015
}
2012
if (event.type === "spell-light-remove")
2016
if (event.type === "spell-light-remove" || event.type === "spell-dark-remove")
2013
2017
{
2014
2018
if (!seesTo)
2015
2019
{ continue; }
2016
2020
send(session, {
2017
type: MessageType.spellLightRemove,
2021
type: event.type === "spell-dark-remove"
2022
? MessageType.spellDarkRemove
2023
: MessageType.spellLightRemove,
2018
2024
tileX: event.tileX,
2019
2025
tileY: event.tileY
2020
2026
});
@@ -1820,7 +1820,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1820
}1820
}1821
continue;1821
continue;1822
}1822
}1823
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")1823
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")1824
{ publishEntity(event); }1824
{ publishEntity(event); }1825
}1825
}1826
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)1826
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)@@ -1991,30 +1991,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1991
});1991
});1992
continue;1992
continue;1993
}1993
}1994
if (event.type === "spell-light-appear" || event.type === "spell-light-update")1994
if (event.type === "spell-light-appear" || event.type === "spell-light-update"1995
|| event.type === "spell-dark-appear" || event.type === "spell-dark-update")1995
{1996
{1996
if (!seesTo)1997
if (!seesTo)1997
{ continue; }1998
{ continue; }1999
const isDark = event.type.startsWith("spell-dark");2000
const appear = event.type.endsWith("appear");1998
send(session, {2001
send(session, {1999
type: event.type === "spell-light-appear"2002
type: appear2000
? MessageType.spellLightAppear2003
? (isDark ? MessageType.spellDarkAppear : MessageType.spellLightAppear)2001
: MessageType.spellLightUpdate,2004
: (isDark ? MessageType.spellDarkUpdate : MessageType.spellLightUpdate),2002
tileX: event.tileX,2005
tileX: event.tileX,2003
tileY: event.tileY,2006
tileY: event.tileY,2004
ownerEntityId: event.ownerEntityId,2007
ownerEntityId: event.ownerEntityId,2005
remainingMs: event.remainingMs ?? 0,2008
remainingMs: event.remainingMs ?? 0,2006
rangeTiles: event.rangeTiles ?? 0,2009
rangeTiles: event.rangeTiles ?? 0,2007
intensity: event.intensity ?? 0,2010
intensity: event.intensity ?? 0,2008
expiresAt: event.expiresAt ?? 02011
expiresAt: event.expiresAt ?? 0,2012
kind: isDark ? "dark" : "light"2009
});2013
});2010
continue;2014
continue;2011
}2015
}2012
if (event.type === "spell-light-remove")2016
if (event.type === "spell-light-remove" || event.type === "spell-dark-remove")2013
{2017
{2014
if (!seesTo)2018
if (!seesTo)2015
{ continue; }2019
{ continue; }2016
send(session, {2020
send(session, {2017
type: MessageType.spellLightRemove,2021
type: event.type === "spell-dark-remove"2022
? MessageType.spellDarkRemove2023
: MessageType.spellLightRemove,2018
tileX: event.tileX,2024
tileX: event.tileX,2019
tileY: event.tileY2025
tileY: event.tileY2020
});2026
});@@ -34,6 +34,7 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../
34
34
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
35
35
import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
36
36
import { mobComponents } from "./spawners.js";
37
import { shadeSummonComponents } from "../spells/summons.js";
37
38
import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
38
39
import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
39
40
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
@@ -237,6 +238,11 @@ export class Simulation
237
238
remoteRanged.push(event);
238
239
continue;
239
240
}
241
if (event.type === "summon-entity")
242
{
243
events.push(...this.#applySummonEntity(event));
244
continue;
245
}
240
246
if (event.type === "entity-move")
241
247
{ this.#applyMoveToDirectory(event); }
242
248
if (event.type === "entity-despawn")
@@ -2551,6 +2557,29 @@ export class Simulation
2551
2557
});
2552
2558
}
2553
2559
2560
#applySummonEntity (event)
2561
{
2562
const components = shadeSummonComponents({
2563
tileX: event.tileX | 0,
2564
tileY: event.tileY | 0,
2565
level: event.level | 0 || 1,
2566
ownerEntityId: event.ownerEntityId,
2567
expiresAt: event.expiresAt,
2568
dimensionId: event.dimensionId
2569
});
2570
try
2571
{
2572
const entityId = this.spawnEntity(components, { requireResident: true });
2573
if (entityId == null)
2574
{ return []; }
2575
return [];
2576
}
2577
catch
2578
{
2579
return [];
2580
}
2581
}
2582
2554
2583
#skillLevelUpEvents (event)
2555
2584
{
2556
2585
const levelUps = event?.levelUps ?? [];
@@ -34,6 +34,7 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../34
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";34
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";35
import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";35
import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";36
import { mobComponents } from "./spawners.js";36
import { mobComponents } from "./spawners.js";37
import { shadeSummonComponents } from "../spells/summons.js";37
import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";38
import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";38
import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";39
import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";39
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";40
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";@@ -237,6 +238,11 @@ export class Simulation237
remoteRanged.push(event);238
remoteRanged.push(event);238
continue;239
continue;239
}240
}241
if (event.type === "summon-entity")242
{243
events.push(...this.#applySummonEntity(event));244
continue;245
}240
if (event.type === "entity-move")246
if (event.type === "entity-move")241
{ this.#applyMoveToDirectory(event); }247
{ this.#applyMoveToDirectory(event); }242
if (event.type === "entity-despawn")248
if (event.type === "entity-despawn")@@ -2551,6 +2557,29 @@ export class Simulation2551
});2557
});2552
}2558
}2553
2559
2560
#applySummonEntity (event)2561
{2562
const components = shadeSummonComponents({2563
tileX: event.tileX | 0,2564
tileY: event.tileY | 0,2565
level: event.level | 0 || 1,2566
ownerEntityId: event.ownerEntityId,2567
expiresAt: event.expiresAt,2568
dimensionId: event.dimensionId2569
});2570
try2571
{2572
const entityId = this.spawnEntity(components, { requireResident: true });2573
if (entityId == null)2574
{ return []; }2575
return [];2576
}2577
catch2578
{2579
return [];2580
}2581
}2582
2554
#skillLevelUpEvents (event)2583
#skillLevelUpEvents (event)2555
{2584
{2556
const levelUps = event?.levelUps ?? [];2585
const levelUps = event?.levelUps ?? [];@@ -33,6 +33,7 @@ import {
33
33
stripCarriedCoinsForDeath
34
34
} from "../items/bags.js";
35
35
import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js";
36
import { stepSummons } from "../spells/summons.js";
36
37
import { publicSpellsView } from "../../../shared/spells/state.js";
37
38
import {
38
39
handleGatherCommand,
@@ -74,6 +75,7 @@ import {
74
75
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
75
76
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
76
77
import { stepStatusEffects } from "../statusEffects/service.js";
78
import { hasStatusEffect, StatusEffectType } from "../../../shared/statusEffects/rules.js";
77
79
78
80
export class WorkerWorld
79
81
{
@@ -1202,6 +1204,9 @@ export class WorkerWorld
1202
1204
const { handle, character, stamina, movement } = entity;
1203
1205
if (this.ecs.has(handle, Component.dead))
1204
1206
{ continue; }
1207
const status = this.ecs.get(handle, Component.statusEffects);
1208
if (hasStatusEffect(status, StatusEffectType.staminaBlock, Date.now()))
1209
{ continue; }
1205
1210
// Run gait only blocks regen while actually stepping along a path.
1206
1211
const path = this.ecs.get(handle, Component.path);
1207
1212
if (movement.gait === GAIT.run && path?.tiles?.length)
@@ -1277,6 +1282,14 @@ export class WorkerWorld
1277
1282
events.push(...processSpellImpacts(this, now));
1278
1283
events.push(...stepSpellAutoCast(this, now));
1279
1284
events.push(...tickSpellLights(this, now));
1285
const summons = stepSummons(this, now);
1286
events.push(...(summons.events ?? []));
1287
for (const entityId of summons.despawnIds ?? [])
1288
{
1289
const dropped = this.#destroyEntity(entityId);
1290
if (dropped)
1291
{ events.push({ type: "entity-despawn", entityId }); }
1292
}
1280
1293
stepFollow(this);
1281
1294
const gather = stepGather(this, now);
1282
1295
events.push(...gather.events);
@@ -33,6 +33,7 @@ import {33
stripCarriedCoinsForDeath33
stripCarriedCoinsForDeath34
} from "../items/bags.js";34
} from "../items/bags.js";35
import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js";35
import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js";36
import { stepSummons } from "../spells/summons.js";36
import { publicSpellsView } from "../../../shared/spells/state.js";37
import { publicSpellsView } from "../../../shared/spells/state.js";37
import {38
import {38
handleGatherCommand,39
handleGatherCommand,@@ -74,6 +75,7 @@ import {74
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";75
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";75
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";76
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";76
import { stepStatusEffects } from "../statusEffects/service.js";77
import { stepStatusEffects } from "../statusEffects/service.js";78
import { hasStatusEffect, StatusEffectType } from "../../../shared/statusEffects/rules.js";77
79
78
export class WorkerWorld80
export class WorkerWorld79
{81
{@@ -1202,6 +1204,9 @@ export class WorkerWorld1202
const { handle, character, stamina, movement } = entity;1204
const { handle, character, stamina, movement } = entity;1203
if (this.ecs.has(handle, Component.dead))1205
if (this.ecs.has(handle, Component.dead))1204
{ continue; }1206
{ continue; }1207
const status = this.ecs.get(handle, Component.statusEffects);1208
if (hasStatusEffect(status, StatusEffectType.staminaBlock, Date.now()))1209
{ continue; }1205
// Run gait only blocks regen while actually stepping along a path.1210
// Run gait only blocks regen while actually stepping along a path.1206
const path = this.ecs.get(handle, Component.path);1211
const path = this.ecs.get(handle, Component.path);1207
if (movement.gait === GAIT.run && path?.tiles?.length)1212
if (movement.gait === GAIT.run && path?.tiles?.length)@@ -1277,6 +1282,14 @@ export class WorkerWorld1277
events.push(...processSpellImpacts(this, now));1282
events.push(...processSpellImpacts(this, now));1278
events.push(...stepSpellAutoCast(this, now));1283
events.push(...stepSpellAutoCast(this, now));1279
events.push(...tickSpellLights(this, now));1284
events.push(...tickSpellLights(this, now));1285
const summons = stepSummons(this, now);1286
events.push(...(summons.events ?? []));1287
for (const entityId of summons.despawnIds ?? [])1288
{1289
const dropped = this.#destroyEntity(entityId);1290
if (dropped)1291
{ events.push({ type: "entity-despawn", entityId }); }1292
}1280
stepFollow(this);1293
stepFollow(this);1281
const gather = stepGather(this, now);1294
const gather = stepGather(this, now);1282
events.push(...gather.events);1295
events.push(...gather.events);@@ -5,13 +5,14 @@ import
5
5
LIGHT_FADE_MS,
6
6
LIGHT_MAX_DURATION_MS,
7
7
LIGHT_OWNER_DISTANCE_CAP_MS,
8
SPELL_DARK_INTENSITY,
8
9
SPELL_LIGHT_INTENSITY,
9
10
SPELL_LIGHT_RANGE_TILES,
10
11
COMBAT_RANGE_TILES
11
12
} from "../../../shared/spells/constants.js";
12
13
13
14
/**
14
* Authoritative temporary spell lights keyed by tile.
15
* Authoritative temporary spell lights / darkness keyed by tile.
15
16
* @typedef {object} SpellLight
16
17
* @property {number} tileX
17
18
* @property {number} tileY
@@ -20,6 +21,7 @@ import
20
21
* @property {number} maxDurationMs
21
22
* @property {number} baseRange
22
23
* @property {number} baseIntensity
24
* @property {"light"|"dark"} kind
23
25
*/
24
26
25
27
export class SpellLightRegistry
@@ -43,14 +45,18 @@ export class SpellLightRegistry
43
45
ownerEntityId,
44
46
durationMs,
45
47
baseRange = SPELL_LIGHT_RANGE_TILES,
48
baseIntensity = SPELL_LIGHT_INTENSITY,
49
kind = "light",
46
50
now = Date.now()
47
51
})
48
52
{
49
53
const key = tileKey(tileX, tileY);
50
54
const addMs = Math.max(0, Math.min(LIGHT_MAX_DURATION_MS, durationMs | 0));
51
55
const range = Math.max(0, Number(baseRange) || SPELL_LIGHT_RANGE_TILES);
56
const intensity = Math.max(0, Number(baseIntensity)
57
|| (kind === "dark" ? SPELL_DARK_INTENSITY : SPELL_LIGHT_INTENSITY));
52
58
const existing = this.byTile.get(key);
53
if (existing)
59
if (existing && existing.kind === kind)
54
60
{
55
61
const remaining = Math.max(0, existing.expiresAt - now);
56
62
const next = Math.min(LIGHT_MAX_DURATION_MS, remaining + addMs);
@@ -58,6 +64,7 @@ export class SpellLightRegistry
58
64
existing.maxDurationMs = Math.max(existing.maxDurationMs, next);
59
65
existing.ownerEntityId = ownerEntityId;
60
66
existing.baseRange = Math.max(existing.baseRange ?? 0, range);
67
existing.baseIntensity = Math.max(existing.baseIntensity ?? 0, intensity);
61
68
return { light: existing, extended: true };
62
69
}
63
70
const light = {
@@ -68,7 +75,8 @@ export class SpellLightRegistry
68
75
expiresAt: now + addMs,
69
76
maxDurationMs: addMs,
70
77
baseRange: range,
71
baseIntensity: SPELL_LIGHT_INTENSITY
78
baseIntensity: intensity,
79
kind: kind === "dark" ? "dark" : "light"
72
80
};
73
81
this.byTile.set(key, light);
74
82
return { light, extended: false };
@@ -93,7 +101,11 @@ export class SpellLightRegistry
93
101
if (now >= light.expiresAt)
94
102
{
95
103
this.byTile.delete(tileKey(light.tileX, light.tileY));
96
events.push({ type: "spell-light-remove", tileX: light.tileX, tileY: light.tileY });
104
events.push({
105
type: light.kind === "dark" ? "spell-dark-remove" : "spell-light-remove",
106
tileX: light.tileX,
107
tileY: light.tileY
108
});
97
109
continue;
98
110
}
99
111
const ownerHandle = world.ecs.handleOf(light.ownerEntityId);
@@ -111,7 +123,8 @@ export class SpellLightRegistry
111
123
if (capped !== remaining)
112
124
{
113
125
light.expiresAt = now + capped;
114
events.push({ type: "spell-light-update", ...publicSpellLight(light, now) });
126
const eventType = light.kind === "dark" ? "spell-dark-update" : "spell-light-update";
127
events.push({ type: eventType, ...publicSpellLight(light, now) });
115
128
}
116
129
}
117
130
}
@@ -147,13 +160,17 @@ export function publicSpellLight (light, now = Date.now())
147
160
remainingMs,
148
161
rangeTiles: range,
149
162
intensity,
150
expiresAt: light.expiresAt
163
expiresAt: light.expiresAt,
164
kind: light.kind === "dark" ? "dark" : "light"
151
165
};
152
166
}
153
167
154
168
export function spellLightsForDynamicLighting (registry, now = Date.now())
155
169
{
156
const out = [];
170
const lights = [];
171
const darks = [];
172
if (!registry)
173
{ return { lights, darks }; }
157
174
for (const light of registry.byTile.values())
158
175
{
159
176
if (now >= light.expiresAt)
@@ -161,12 +178,16 @@ export function spellLightsForDynamicLighting (registry, now = Date.now())
161
178
const pub = publicSpellLight(light, now);
162
179
if (pub.intensity <= 0 || pub.rangeTiles <= 0)
163
180
{ continue; }
164
out.push({
181
const entry = {
165
182
tileX: light.tileX,
166
183
tileY: light.tileY,
167
184
range: pub.rangeTiles,
168
185
intensity: pub.intensity
169
});
186
};
187
if (light.kind === "dark")
188
{ darks.push(entry); }
189
else
190
{ lights.push(entry); }
170
191
}
171
return out;
192
return { lights, darks };
172
193
}
@@ -5,13 +5,14 @@ import5
LIGHT_FADE_MS,5
LIGHT_FADE_MS,6
LIGHT_MAX_DURATION_MS,6
LIGHT_MAX_DURATION_MS,7
LIGHT_OWNER_DISTANCE_CAP_MS,7
LIGHT_OWNER_DISTANCE_CAP_MS,8
SPELL_DARK_INTENSITY,8
SPELL_LIGHT_INTENSITY,9
SPELL_LIGHT_INTENSITY,9
SPELL_LIGHT_RANGE_TILES,10
SPELL_LIGHT_RANGE_TILES,10
COMBAT_RANGE_TILES11
COMBAT_RANGE_TILES11
} from "../../../shared/spells/constants.js";12
} from "../../../shared/spells/constants.js";12
13
13
/**14
/**14
* Authoritative temporary spell lights keyed by tile.15
* Authoritative temporary spell lights / darkness keyed by tile.15
* @typedef {object} SpellLight16
* @typedef {object} SpellLight16
* @property {number} tileX17
* @property {number} tileX17
* @property {number} tileY18
* @property {number} tileY@@ -20,6 +21,7 @@ import20
* @property {number} maxDurationMs21
* @property {number} maxDurationMs21
* @property {number} baseRange22
* @property {number} baseRange22
* @property {number} baseIntensity23
* @property {number} baseIntensity24
* @property {"light"|"dark"} kind23
*/25
*/24
26
25
export class SpellLightRegistry27
export class SpellLightRegistry@@ -43,14 +45,18 @@ export class SpellLightRegistry43
ownerEntityId,45
ownerEntityId,44
durationMs,46
durationMs,45
baseRange = SPELL_LIGHT_RANGE_TILES,47
baseRange = SPELL_LIGHT_RANGE_TILES,48
baseIntensity = SPELL_LIGHT_INTENSITY,49
kind = "light",46
now = Date.now()50
now = Date.now()47
})51
})48
{52
{49
const key = tileKey(tileX, tileY);53
const key = tileKey(tileX, tileY);50
const addMs = Math.max(0, Math.min(LIGHT_MAX_DURATION_MS, durationMs | 0));54
const addMs = Math.max(0, Math.min(LIGHT_MAX_DURATION_MS, durationMs | 0));51
const range = Math.max(0, Number(baseRange) || SPELL_LIGHT_RANGE_TILES);55
const range = Math.max(0, Number(baseRange) || SPELL_LIGHT_RANGE_TILES);56
const intensity = Math.max(0, Number(baseIntensity)57
|| (kind === "dark" ? SPELL_DARK_INTENSITY : SPELL_LIGHT_INTENSITY));52
const existing = this.byTile.get(key);58
const existing = this.byTile.get(key);53
if (existing)59
if (existing && existing.kind === kind)54
{60
{55
const remaining = Math.max(0, existing.expiresAt - now);61
const remaining = Math.max(0, existing.expiresAt - now);56
const next = Math.min(LIGHT_MAX_DURATION_MS, remaining + addMs);62
const next = Math.min(LIGHT_MAX_DURATION_MS, remaining + addMs);@@ -58,6 +64,7 @@ export class SpellLightRegistry58
existing.maxDurationMs = Math.max(existing.maxDurationMs, next);64
existing.maxDurationMs = Math.max(existing.maxDurationMs, next);59
existing.ownerEntityId = ownerEntityId;65
existing.ownerEntityId = ownerEntityId;60
existing.baseRange = Math.max(existing.baseRange ?? 0, range);66
existing.baseRange = Math.max(existing.baseRange ?? 0, range);67
existing.baseIntensity = Math.max(existing.baseIntensity ?? 0, intensity);61
return { light: existing, extended: true };68
return { light: existing, extended: true };62
}69
}63
const light = {70
const light = {@@ -68,7 +75,8 @@ export class SpellLightRegistry68
expiresAt: now + addMs,75
expiresAt: now + addMs,69
maxDurationMs: addMs,76
maxDurationMs: addMs,70
baseRange: range,77
baseRange: range,71
baseIntensity: SPELL_LIGHT_INTENSITY78
baseIntensity: intensity,79
kind: kind === "dark" ? "dark" : "light"72
};80
};73
this.byTile.set(key, light);81
this.byTile.set(key, light);74
return { light, extended: false };82
return { light, extended: false };@@ -93,7 +101,11 @@ export class SpellLightRegistry93
if (now >= light.expiresAt)101
if (now >= light.expiresAt)94
{102
{95
this.byTile.delete(tileKey(light.tileX, light.tileY));103
this.byTile.delete(tileKey(light.tileX, light.tileY));96
events.push({ type: "spell-light-remove", tileX: light.tileX, tileY: light.tileY });104
events.push({105
type: light.kind === "dark" ? "spell-dark-remove" : "spell-light-remove",106
tileX: light.tileX,107
tileY: light.tileY108
});97
continue;109
continue;98
}110
}99
const ownerHandle = world.ecs.handleOf(light.ownerEntityId);111
const ownerHandle = world.ecs.handleOf(light.ownerEntityId);@@ -111,7 +123,8 @@ export class SpellLightRegistry111
if (capped !== remaining)123
if (capped !== remaining)112
{124
{113
light.expiresAt = now + capped;125
light.expiresAt = now + capped;114
events.push({ type: "spell-light-update", ...publicSpellLight(light, now) });126
const eventType = light.kind === "dark" ? "spell-dark-update" : "spell-light-update";127
events.push({ type: eventType, ...publicSpellLight(light, now) });115
}128
}116
}129
}117
}130
}@@ -147,13 +160,17 @@ export function publicSpellLight (light, now = Date.now())147
remainingMs,160
remainingMs,148
rangeTiles: range,161
rangeTiles: range,149
intensity,162
intensity,150
expiresAt: light.expiresAt163
expiresAt: light.expiresAt,164
kind: light.kind === "dark" ? "dark" : "light"151
};165
};152
}166
}153
167
154
export function spellLightsForDynamicLighting (registry, now = Date.now())168
export function spellLightsForDynamicLighting (registry, now = Date.now())155
{169
{156
const out = [];170
const lights = [];171
const darks = [];172
if (!registry)173
{ return { lights, darks }; }157
for (const light of registry.byTile.values())174
for (const light of registry.byTile.values())158
{175
{159
if (now >= light.expiresAt)176
if (now >= light.expiresAt)@@ -161,12 +178,16 @@ export function spellLightsForDynamicLighting (registry, now = Date.now())161
const pub = publicSpellLight(light, now);178
const pub = publicSpellLight(light, now);162
if (pub.intensity <= 0 || pub.rangeTiles <= 0)179
if (pub.intensity <= 0 || pub.rangeTiles <= 0)163
{ continue; }180
{ continue; }164
out.push({181
const entry = {165
tileX: light.tileX,182
tileX: light.tileX,166
tileY: light.tileY,183
tileY: light.tileY,167
range: pub.rangeTiles,184
range: pub.rangeTiles,168
intensity: pub.intensity185
intensity: pub.intensity169
});186
};187
if (light.kind === "dark")188
{ darks.push(entry); }189
else190
{ lights.push(entry); }170
}191
}171
return out;192
return { lights, darks };172
}193
}@@ -32,7 +32,7 @@ import
32
32
import { mobDefinition } from "../../../shared/definitions/mobs.js";
33
33
import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
34
34
import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js";
35
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
35
import { statusSkillBonuses, applyStatusEffect, emptyStatusEffects, StatusEffectType, publicStatusEffectsView, hasStatusEffect } from "../../../shared/statusEffects/rules.js";
36
36
import
37
37
{
38
38
chebyshev,
@@ -44,8 +44,9 @@ import
44
44
import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
45
45
import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
46
46
import { publicSpellLight, SpellLightRegistry } from "./lights.js";
47
import { SpellbookItemId, spellbookInstance } from "../../../shared/definitions/spellItems.js";
47
import { spellbookInstance, spellbookItemIdForSpell } from "../../../shared/definitions/spellItems.js";
48
48
import { bagView } from "../items/bags.js";
49
import { applyTindersAtTile } from "./tinders.js";
49
50
50
51
const MAGIC_ATTACK_PROFILE = Object.freeze({
51
52
hitSkillId: SkillId.magic,
@@ -318,6 +319,7 @@ function castSpellAtEntity (world, sessionId, command, now)
318
319
error.userFacing = true;
319
320
throw error;
320
321
}
322
const { entityId: casterEntityId } = requirePlayer(world, sessionId, command.characterId);
321
323
const target = resolveCombatTarget(world, command.targetEntityId);
322
324
if (!target)
323
325
{
@@ -325,11 +327,12 @@ function castSpellAtEntity (world, sessionId, command, now)
325
327
error.userFacing = true;
326
328
throw error;
327
329
}
330
const selfTarget = command.targetEntityId === casterEntityId;
328
331
return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
329
332
tileX: target.pos.tileX,
330
333
tileY: target.pos.tileY,
331
334
targetEntityId: command.targetEntityId
332
}, now, 1);
335
}, now, selfTarget ? 0 : 1);
333
336
}
334
337
335
338
function executeCast (world, sessionId, characterId, spellId, target, now)
@@ -469,26 +472,6 @@ function targetAffinitiesForEntity (world, entityId)
469
472
return mobElementAffinities(mobDefinition(creature.mobTypeId));
470
473
}
471
474
472
export function processSpellImpacts (world, now = Date.now())
473
{
474
const queue = world.pendingSpellImpacts ?? [];
475
if (!queue.length)
476
{ return []; }
477
const events = [];
478
const keep = [];
479
for (const impact of queue)
480
{
481
if (impact.executeAt > now)
482
{
483
keep.push(impact);
484
continue;
485
}
486
events.push(...applySpellImpact(world, impact, now));
487
}
488
world.pendingSpellImpacts = keep;
489
return events;
490
}
491
492
475
function applySpellImpact (world, impact, now)
493
476
{
494
477
const def = spellDefinition(impact.spellId);
@@ -505,65 +488,288 @@ function applySpellImpact (world, impact, now)
505
488
tier: def.tier
506
489
});
507
490
508
if (impact.spellId === SpellId.light)
509
{
510
world.spellLights = world.spellLights ?? new SpellLightRegistry();
511
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
512
// Mind 0: still a brief light, but at half range. Mind 1+ → roll × 5s at full range.
513
const durationMs = Math.max(1, mindRoll) * LIGHT_DURATION_MS_PER_MIND;
514
const baseRange = mindRoll === 0
515
? SPELL_LIGHT_RANGE_TILES * 0.5
516
: SPELL_LIGHT_RANGE_TILES;
517
const { light, extended } = world.spellLights.placeOrExtend({
518
tileX: impact.targetTileX,
519
tileY: impact.targetTileY,
520
ownerEntityId: impact.casterEntityId,
521
durationMs,
522
baseRange,
523
now
491
const effect = def.effect ?? impact.spellId;
492
if (effect === "light" || effect === "dark")
493
{
494
events.push(...applyLightOrDarkImpact(world, impact, def, effect, now));
495
return events;
496
}
497
if (effect === "damage")
498
{
499
events.push(...applyDamageSpellImpact(world, impact, def, now));
500
return events;
501
}
502
if (effect === "poison")
503
{
504
events.push(...applyPoisonImpact(world, impact, def, now));
505
return events;
506
}
507
if (effect === "drain")
508
{
509
events.push(...applyDrainImpact(world, impact, now));
510
return events;
511
}
512
if (effect === "revitalize")
513
{
514
events.push(...applyRevitalizeImpact(world, impact, now));
515
return events;
516
}
517
if (effect === "tinders")
518
{
519
events.push(...applyTindersImpact(world, impact, now));
520
return events;
521
}
522
if (effect === "shade")
523
{
524
events.push(...applyShadeImpact(world, impact, now));
525
return events;
526
}
527
return events;
528
}
529
530
function mindRollOf (impact)
531
{
532
return resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
533
}
534
535
function applyLightOrDarkImpact (world, impact, def, effect, now)
536
{
537
const events = [];
538
world.spellLights = world.spellLights ?? new SpellLightRegistry();
539
const mindRoll = mindRollOf(impact);
540
const durationMs = Math.max(1, mindRoll) * LIGHT_DURATION_MS_PER_MIND;
541
const baseRange = mindRoll === 0
542
? SPELL_LIGHT_RANGE_TILES * 0.5
543
: SPELL_LIGHT_RANGE_TILES;
544
const kind = effect === "dark" ? "dark" : "light";
545
const { light, extended } = world.spellLights.placeOrExtend({
546
tileX: impact.targetTileX,
547
tileY: impact.targetTileY,
548
ownerEntityId: impact.casterEntityId,
549
durationMs,
550
baseRange,
551
kind,
552
now
553
});
554
const appear = kind === "dark"
555
? (extended ? "spell-dark-update" : "spell-dark-appear")
556
: (extended ? "spell-light-update" : "spell-light-appear");
557
events.push({ type: appear, ...publicSpellLight(light, now) });
558
return events;
559
}
560
561
function elementalDamageMultiplier (def, affinities)
562
{
563
let multiplier = ElementMultiplier.neutral;
564
const affinity = affinities[def.element ?? "none"];
565
if (affinity === "weak")
566
{ multiplier = ElementMultiplier.weak; }
567
else if (affinity === "resistant")
568
{ multiplier = ElementMultiplier.resistant; }
569
return multiplier;
570
}
571
572
function applyDamageSpellImpact (world, impact, def, now)
573
{
574
if (impact.targetEntityId == null)
575
{ return []; }
576
const events = [];
577
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
578
const mindRoll = mindRollOf(impact);
579
const multiplier = elementalDamageMultiplier(def, affinities);
580
const damage = Math.max(1, Math.floor(mindRoll * multiplier));
581
events.push(...applyDamageAndKill(
582
world,
583
impact.casterEntityId,
584
impact.targetEntityId,
585
damage,
586
now
587
));
588
events.push(...awardMagicHitXp(world, impact, damage));
589
return events;
590
}
591
592
function awardMagicHitXp (world, impact, damage)
593
{
594
const events = [];
595
const casterHandle = world.ecs.handleOf(impact.casterEntityId);
596
if (casterHandle == null || !impact.casterCharacterId)
597
{ return events; }
598
const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
599
if (xp)
600
{
601
events.push({
602
type: "skills-updated",
603
entityId: impact.casterEntityId,
604
characterId: impact.casterCharacterId,
605
skills: xp.view,
606
stored: xp.stored,
607
levelUps: xp.levelUps ?? []
524
608
});
609
}
610
return events;
611
}
612
613
function ensureEntityStatusEffects (ecs, handle)
614
{
615
let component = ecs.get(handle, Component.statusEffects);
616
if (!component)
617
{ component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
618
return component;
619
}
620
621
function applyPoisonImpact (world, impact, def, now)
622
{
623
if (impact.targetEntityId == null)
624
{ return []; }
625
const target = resolveCombatTarget(world, impact.targetEntityId);
626
if (!target?.local || target.handle == null)
627
{ return []; }
628
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
629
const mindRoll = mindRollOf(impact);
630
const multiplier = elementalDamageMultiplier(def, affinities);
631
const total = Math.max(1, Math.floor(mindRoll * multiplier * 2));
632
const durationMs = total * 1000;
633
const status = ensureEntityStatusEffects(world.ecs, target.handle);
634
applyStatusEffect(status, {
635
type: StatusEffectType.healthDrain,
636
durationMs,
637
amountPerSecond: 1
638
}, now);
639
return [{
640
type: "status-effects-entity",
641
entityId: impact.targetEntityId,
642
effects: publicStatusEffectsView(status, now)
643
}];
644
}
645
646
function applyDrainImpact (world, impact, now)
647
{
648
if (impact.targetEntityId == null)
649
{ return []; }
650
const target = resolveCombatTarget(world, impact.targetEntityId);
651
if (!target?.local || target.handle == null)
652
{ return []; }
653
if (!world.ecs.get(target.handle, Component.stamina))
654
{ return []; }
655
const mindRoll = mindRollOf(impact);
656
const durationMs = Math.max(1000, mindRoll * 3 * 1000);
657
const status = ensureEntityStatusEffects(world.ecs, target.handle);
658
applyStatusEffect(status, {
659
type: StatusEffectType.staminaDrain,
660
durationMs,
661
amountPerSecond: 1
662
}, now);
663
applyStatusEffect(status, {
664
type: StatusEffectType.staminaBlock,
665
durationMs,
666
amountPerSecond: 0
667
}, now);
668
const character = world.ecs.get(target.handle, Component.character);
669
const events = [{
670
type: "status-effects-entity",
671
entityId: impact.targetEntityId,
672
effects: publicStatusEffectsView(status, now)
673
}];
674
if (character?.characterId)
675
{
525
676
events.push({
526
type: extended ? "spell-light-update" : "spell-light-appear",
527
...publicSpellLight(light, now)
677
type: "status-effects",
678
characterId: character.characterId,
679
effects: publicStatusEffectsView(status, now),
680
blind: hasStatusEffect(status, StatusEffectType.blind, now)
528
681
});
529
return events;
530
682
}
683
return events;
684
}
531
685
532
if (impact.spellId === SpellId.spark && impact.targetEntityId != null)
686
function applyRevitalizeImpact (world, impact, now)
687
{
688
if (impact.targetEntityId == null)
689
{ return []; }
690
const target = resolveCombatTarget(world, impact.targetEntityId);
691
if (!target?.local || target.handle == null)
692
{ return []; }
693
if (!world.ecs.get(target.handle, Component.health))
694
{ return []; }
695
const mindRoll = mindRollOf(impact);
696
const healTotal = Math.max(1, mindRoll);
697
const durationMs = healTotal * 1000;
698
const status = ensureEntityStatusEffects(world.ecs, target.handle);
699
applyStatusEffect(status, {
700
type: StatusEffectType.healthRegen,
701
durationMs,
702
amountPerSecond: 1
703
}, now);
704
const character = world.ecs.get(target.handle, Component.character);
705
const events = [{
706
type: "status-effects-entity",
707
entityId: impact.targetEntityId,
708
effects: publicStatusEffectsView(status, now)
709
}];
710
if (character?.characterId)
533
711
{
534
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
535
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
536
let multiplier = ElementMultiplier.neutral;
537
const affinity = affinities[def.element ?? "fire"];
538
if (affinity === "weak")
539
{ multiplier = ElementMultiplier.weak; }
540
else if (affinity === "resistant")
541
{ multiplier = ElementMultiplier.resistant; }
542
const damage = Math.max(1, Math.floor(mindRoll * multiplier));
543
events.push(...applyDamageAndKill(
544
world,
545
impact.casterEntityId,
546
impact.targetEntityId,
547
damage,
548
now
549
));
550
const casterHandle = world.ecs.handleOf(impact.casterEntityId);
551
if (casterHandle != null && impact.casterCharacterId)
712
events.push({
713
type: "status-effects",
714
characterId: character.characterId,
715
effects: publicStatusEffectsView(status, now),
716
blind: hasStatusEffect(status, StatusEffectType.blind, now)
717
});
718
}
719
return events;
720
}
721
722
function applyTindersImpact (world, impact, now)
723
{
724
const events = applyTindersAtTile(world, impact, now);
725
const casterHandle = world.ecs.handleOf(impact.casterEntityId);
726
const sessionId = casterHandle != null
727
? world.ecs.get(casterHandle, Component.networkIdentity)?.sessionId
728
: null;
729
for (const event of events)
730
{
731
if (event.type === "command-error" && sessionId != null)
732
{ event.sessionId = sessionId; }
733
}
734
return events;
735
}
736
737
function applyShadeImpact (world, impact, now)
738
{
739
const mindRoll = mindRollOf(impact);
740
const durationMs = Math.max(1000, mindRoll * 3 * 1000);
741
const casterHandle = world.ecs.handleOf(impact.casterEntityId);
742
const mindLevel = impact.levels?.mind | 0 || 1;
743
const level = Math.max(1, Math.min(99, Math.floor(mindLevel * 0.75)));
744
return [{
745
type: "summon-entity",
746
ownerEntityId: impact.casterEntityId,
747
ownerCharacterId: impact.casterCharacterId ?? null,
748
tileX: impact.targetTileX,
749
tileY: impact.targetTileY,
750
level,
751
expiresAt: now + durationMs,
752
mobTypeId: "shade"
753
}];
754
}
755
756
export function processSpellImpacts (world, now = Date.now())
757
{
758
const queue = world.pendingSpellImpacts ?? [];
759
if (!queue.length)
760
{ return []; }
761
const events = [];
762
const keep = [];
763
for (const impact of queue)
764
{
765
if (impact.executeAt > now)
552
766
{
553
const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
554
if (xp)
555
{
556
events.push({
557
type: "skills-updated",
558
entityId: impact.casterEntityId,
559
characterId: impact.casterCharacterId,
560
skills: xp.view,
561
stored: xp.stored,
562
levelUps: xp.levelUps ?? []
563
});
564
}
767
keep.push(impact);
768
continue;
565
769
}
770
events.push(...applySpellImpact(world, impact, now));
566
771
}
772
world.pendingSpellImpacts = keep;
567
773
return events;
568
774
}
569
775
@@ -691,12 +897,8 @@ function readSpellbook (world, sessionId, command, now)
691
897
export function createSpellbookStack (spellId)
692
898
{
693
899
const instance = spellbookInstance(spellId);
694
if (!instance)
695
{ return null; }
696
const itemId = spellId === SpellId.spark
697
? SpellbookItemId.sparkSpellbook
698
: null;
699
if (itemId == null)
900
const itemId = spellbookItemIdForSpell(spellId);
901
if (!instance || itemId == null)
700
902
{ return null; }
701
903
return { itemId, quantity: 1, instance };
702
904
}
@@ -32,7 +32,7 @@ import32
import { mobDefinition } from "../../../shared/definitions/mobs.js";32
import { mobDefinition } from "../../../shared/definitions/mobs.js";33
import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";33
import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";34
import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js";34
import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js";35
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";35
import { statusSkillBonuses, applyStatusEffect, emptyStatusEffects, StatusEffectType, publicStatusEffectsView, hasStatusEffect } from "../../../shared/statusEffects/rules.js";36
import36
import37
{37
{38
chebyshev,38
chebyshev,@@ -44,8 +44,9 @@ import44
import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";44
import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";45
import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";45
import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";46
import { publicSpellLight, SpellLightRegistry } from "./lights.js";46
import { publicSpellLight, SpellLightRegistry } from "./lights.js";47
import { SpellbookItemId, spellbookInstance } from "../../../shared/definitions/spellItems.js";47
import { spellbookInstance, spellbookItemIdForSpell } from "../../../shared/definitions/spellItems.js";48
import { bagView } from "../items/bags.js";48
import { bagView } from "../items/bags.js";49
import { applyTindersAtTile } from "./tinders.js";49
50
50
const MAGIC_ATTACK_PROFILE = Object.freeze({51
const MAGIC_ATTACK_PROFILE = Object.freeze({51
hitSkillId: SkillId.magic,52
hitSkillId: SkillId.magic,@@ -318,6 +319,7 @@ function castSpellAtEntity (world, sessionId, command, now)318
error.userFacing = true;319
error.userFacing = true;319
throw error;320
throw error;320
}321
}322
const { entityId: casterEntityId } = requirePlayer(world, sessionId, command.characterId);321
const target = resolveCombatTarget(world, command.targetEntityId);323
const target = resolveCombatTarget(world, command.targetEntityId);322
if (!target)324
if (!target)323
{325
{@@ -325,11 +327,12 @@ function castSpellAtEntity (world, sessionId, command, now)325
error.userFacing = true;327
error.userFacing = true;326
throw error;328
throw error;327
}329
}330
const selfTarget = command.targetEntityId === casterEntityId;328
return beginCastOrApproach(world, sessionId, command.characterId, spellId, {331
return beginCastOrApproach(world, sessionId, command.characterId, spellId, {329
tileX: target.pos.tileX,332
tileX: target.pos.tileX,330
tileY: target.pos.tileY,333
tileY: target.pos.tileY,331
targetEntityId: command.targetEntityId334
targetEntityId: command.targetEntityId332
}, now, 1);335
}, now, selfTarget ? 0 : 1);333
}336
}334
337
335
function executeCast (world, sessionId, characterId, spellId, target, now)338
function executeCast (world, sessionId, characterId, spellId, target, now)@@ -469,26 +472,6 @@ function targetAffinitiesForEntity (world, entityId)469
return mobElementAffinities(mobDefinition(creature.mobTypeId));472
return mobElementAffinities(mobDefinition(creature.mobTypeId));470
}473
}471
474
472
export function processSpellImpacts (world, now = Date.now())473
{474
const queue = world.pendingSpellImpacts ?? [];475
if (!queue.length)476
{ return []; }477
const events = [];478
const keep = [];479
for (const impact of queue)480
{481
if (impact.executeAt > now)482
{483
keep.push(impact);484
continue;485
}486
events.push(...applySpellImpact(world, impact, now));487
}488
world.pendingSpellImpacts = keep;489
return events;490
}491
492
function applySpellImpact (world, impact, now)475
function applySpellImpact (world, impact, now)493
{476
{494
const def = spellDefinition(impact.spellId);477
const def = spellDefinition(impact.spellId);@@ -505,65 +488,288 @@ function applySpellImpact (world, impact, now)505
tier: def.tier488
tier: def.tier506
});489
});507
490
508
if (impact.spellId === SpellId.light)491
const effect = def.effect ?? impact.spellId;509
{492
if (effect === "light" || effect === "dark")510
world.spellLights = world.spellLights ?? new SpellLightRegistry();493
{511
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;494
events.push(...applyLightOrDarkImpact(world, impact, def, effect, now));512
// Mind 0: still a brief light, but at half range. Mind 1+ → roll × 5s at full range.495
return events;513
const durationMs = Math.max(1, mindRoll) * LIGHT_DURATION_MS_PER_MIND;496
}514
const baseRange = mindRoll === 0497
if (effect === "damage")515
? SPELL_LIGHT_RANGE_TILES * 0.5498
{516
: SPELL_LIGHT_RANGE_TILES;499
events.push(...applyDamageSpellImpact(world, impact, def, now));517
const { light, extended } = world.spellLights.placeOrExtend({500
return events;518
tileX: impact.targetTileX,501
}519
tileY: impact.targetTileY,502
if (effect === "poison")520
ownerEntityId: impact.casterEntityId,503
{521
durationMs,504
events.push(...applyPoisonImpact(world, impact, def, now));522
baseRange,505
return events;523
now506
}507
if (effect === "drain")508
{509
events.push(...applyDrainImpact(world, impact, now));510
return events;511
}512
if (effect === "revitalize")513
{514
events.push(...applyRevitalizeImpact(world, impact, now));515
return events;516
}517
if (effect === "tinders")518
{519
events.push(...applyTindersImpact(world, impact, now));520
return events;521
}522
if (effect === "shade")523
{524
events.push(...applyShadeImpact(world, impact, now));525
return events;526
}527
return events;528
}529
530
function mindRollOf (impact)531
{532
return resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;533
}534
535
function applyLightOrDarkImpact (world, impact, def, effect, now)536
{537
const events = [];538
world.spellLights = world.spellLights ?? new SpellLightRegistry();539
const mindRoll = mindRollOf(impact);540
const durationMs = Math.max(1, mindRoll) * LIGHT_DURATION_MS_PER_MIND;541
const baseRange = mindRoll === 0542
? SPELL_LIGHT_RANGE_TILES * 0.5543
: SPELL_LIGHT_RANGE_TILES;544
const kind = effect === "dark" ? "dark" : "light";545
const { light, extended } = world.spellLights.placeOrExtend({546
tileX: impact.targetTileX,547
tileY: impact.targetTileY,548
ownerEntityId: impact.casterEntityId,549
durationMs,550
baseRange,551
kind,552
now553
});554
const appear = kind === "dark"555
? (extended ? "spell-dark-update" : "spell-dark-appear")556
: (extended ? "spell-light-update" : "spell-light-appear");557
events.push({ type: appear, ...publicSpellLight(light, now) });558
return events;559
}560
561
function elementalDamageMultiplier (def, affinities)562
{563
let multiplier = ElementMultiplier.neutral;564
const affinity = affinities[def.element ?? "none"];565
if (affinity === "weak")566
{ multiplier = ElementMultiplier.weak; }567
else if (affinity === "resistant")568
{ multiplier = ElementMultiplier.resistant; }569
return multiplier;570
}571
572
function applyDamageSpellImpact (world, impact, def, now)573
{574
if (impact.targetEntityId == null)575
{ return []; }576
const events = [];577
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);578
const mindRoll = mindRollOf(impact);579
const multiplier = elementalDamageMultiplier(def, affinities);580
const damage = Math.max(1, Math.floor(mindRoll * multiplier));581
events.push(...applyDamageAndKill(582
world,583
impact.casterEntityId,584
impact.targetEntityId,585
damage,586
now587
));588
events.push(...awardMagicHitXp(world, impact, damage));589
return events;590
}591
592
function awardMagicHitXp (world, impact, damage)593
{594
const events = [];595
const casterHandle = world.ecs.handleOf(impact.casterEntityId);596
if (casterHandle == null || !impact.casterCharacterId)597
{ return events; }598
const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);599
if (xp)600
{601
events.push({602
type: "skills-updated",603
entityId: impact.casterEntityId,604
characterId: impact.casterCharacterId,605
skills: xp.view,606
stored: xp.stored,607
levelUps: xp.levelUps ?? []524
});608
});609
}610
return events;611
}612
613
function ensureEntityStatusEffects (ecs, handle)614
{615
let component = ecs.get(handle, Component.statusEffects);616
if (!component)617
{ component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }618
return component;619
}620
621
function applyPoisonImpact (world, impact, def, now)622
{623
if (impact.targetEntityId == null)624
{ return []; }625
const target = resolveCombatTarget(world, impact.targetEntityId);626
if (!target?.local || target.handle == null)627
{ return []; }628
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);629
const mindRoll = mindRollOf(impact);630
const multiplier = elementalDamageMultiplier(def, affinities);631
const total = Math.max(1, Math.floor(mindRoll * multiplier * 2));632
const durationMs = total * 1000;633
const status = ensureEntityStatusEffects(world.ecs, target.handle);634
applyStatusEffect(status, {635
type: StatusEffectType.healthDrain,636
durationMs,637
amountPerSecond: 1638
}, now);639
return [{640
type: "status-effects-entity",641
entityId: impact.targetEntityId,642
effects: publicStatusEffectsView(status, now)643
}];644
}645
646
function applyDrainImpact (world, impact, now)647
{648
if (impact.targetEntityId == null)649
{ return []; }650
const target = resolveCombatTarget(world, impact.targetEntityId);651
if (!target?.local || target.handle == null)652
{ return []; }653
if (!world.ecs.get(target.handle, Component.stamina))654
{ return []; }655
const mindRoll = mindRollOf(impact);656
const durationMs = Math.max(1000, mindRoll * 3 * 1000);657
const status = ensureEntityStatusEffects(world.ecs, target.handle);658
applyStatusEffect(status, {659
type: StatusEffectType.staminaDrain,660
durationMs,661
amountPerSecond: 1662
}, now);663
applyStatusEffect(status, {664
type: StatusEffectType.staminaBlock,665
durationMs,666
amountPerSecond: 0667
}, now);668
const character = world.ecs.get(target.handle, Component.character);669
const events = [{670
type: "status-effects-entity",671
entityId: impact.targetEntityId,672
effects: publicStatusEffectsView(status, now)673
}];674
if (character?.characterId)675
{525
events.push({676
events.push({526
type: extended ? "spell-light-update" : "spell-light-appear",677
type: "status-effects",527
...publicSpellLight(light, now)678
characterId: character.characterId,679
effects: publicStatusEffectsView(status, now),680
blind: hasStatusEffect(status, StatusEffectType.blind, now)528
});681
});529
return events;530
}682
}683
return events;684
}531
685
532
if (impact.spellId === SpellId.spark && impact.targetEntityId != null)686
function applyRevitalizeImpact (world, impact, now)687
{688
if (impact.targetEntityId == null)689
{ return []; }690
const target = resolveCombatTarget(world, impact.targetEntityId);691
if (!target?.local || target.handle == null)692
{ return []; }693
if (!world.ecs.get(target.handle, Component.health))694
{ return []; }695
const mindRoll = mindRollOf(impact);696
const healTotal = Math.max(1, mindRoll);697
const durationMs = healTotal * 1000;698
const status = ensureEntityStatusEffects(world.ecs, target.handle);699
applyStatusEffect(status, {700
type: StatusEffectType.healthRegen,701
durationMs,702
amountPerSecond: 1703
}, now);704
const character = world.ecs.get(target.handle, Component.character);705
const events = [{706
type: "status-effects-entity",707
entityId: impact.targetEntityId,708
effects: publicStatusEffectsView(status, now)709
}];710
if (character?.characterId)533
{711
{534
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);712
events.push({535
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;713
type: "status-effects",536
let multiplier = ElementMultiplier.neutral;714
characterId: character.characterId,537
const affinity = affinities[def.element ?? "fire"];715
effects: publicStatusEffectsView(status, now),538
if (affinity === "weak")716
blind: hasStatusEffect(status, StatusEffectType.blind, now)539
{ multiplier = ElementMultiplier.weak; }717
});540
else if (affinity === "resistant")718
}541
{ multiplier = ElementMultiplier.resistant; }719
return events;542
const damage = Math.max(1, Math.floor(mindRoll * multiplier));720
}543
events.push(...applyDamageAndKill(721
544
world,722
function applyTindersImpact (world, impact, now)545
impact.casterEntityId,723
{546
impact.targetEntityId,724
const events = applyTindersAtTile(world, impact, now);547
damage,725
const casterHandle = world.ecs.handleOf(impact.casterEntityId);548
now726
const sessionId = casterHandle != null549
));727
? world.ecs.get(casterHandle, Component.networkIdentity)?.sessionId550
const casterHandle = world.ecs.handleOf(impact.casterEntityId);728
: null;551
if (casterHandle != null && impact.casterCharacterId)729
for (const event of events)730
{731
if (event.type === "command-error" && sessionId != null)732
{ event.sessionId = sessionId; }733
}734
return events;735
}736
737
function applyShadeImpact (world, impact, now)738
{739
const mindRoll = mindRollOf(impact);740
const durationMs = Math.max(1000, mindRoll * 3 * 1000);741
const casterHandle = world.ecs.handleOf(impact.casterEntityId);742
const mindLevel = impact.levels?.mind | 0 || 1;743
const level = Math.max(1, Math.min(99, Math.floor(mindLevel * 0.75)));744
return [{745
type: "summon-entity",746
ownerEntityId: impact.casterEntityId,747
ownerCharacterId: impact.casterCharacterId ?? null,748
tileX: impact.targetTileX,749
tileY: impact.targetTileY,750
level,751
expiresAt: now + durationMs,752
mobTypeId: "shade"753
}];754
}755
756
export function processSpellImpacts (world, now = Date.now())757
{758
const queue = world.pendingSpellImpacts ?? [];759
if (!queue.length)760
{ return []; }761
const events = [];762
const keep = [];763
for (const impact of queue)764
{765
if (impact.executeAt > now)552
{766
{553
const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);767
keep.push(impact);554
if (xp)768
continue;555
{556
events.push({557
type: "skills-updated",558
entityId: impact.casterEntityId,559
characterId: impact.casterCharacterId,560
skills: xp.view,561
stored: xp.stored,562
levelUps: xp.levelUps ?? []563
});564
}565
}769
}770
events.push(...applySpellImpact(world, impact, now));566
}771
}772
world.pendingSpellImpacts = keep;567
return events;773
return events;568
}774
}569
775
@@ -691,12 +897,8 @@ function readSpellbook (world, sessionId, command, now)691
export function createSpellbookStack (spellId)897
export function createSpellbookStack (spellId)692
{898
{693
const instance = spellbookInstance(spellId);899
const instance = spellbookInstance(spellId);694
if (!instance)900
const itemId = spellbookItemIdForSpell(spellId);695
{ return null; }901
if (!instance || itemId == null)696
const itemId = spellId === SpellId.spark697
? SpellbookItemId.sparkSpellbook698
: null;699
if (itemId == null)700
{ return null; }902
{ return null; }701
return { itemId, quantity: 1, instance };903
return { itemId, quantity: 1, instance };702
}904
}@@ -0,0 +1,155 @@
1
import { Component } from "../ecs/components.js";
2
import { MobId, mobDefinition } from "../../../shared/definitions/mobs.js";
3
import { mobCanFight, mobIsAggressive } from "../../../shared/definitions/mobCombat.js";
4
import
5
{
6
chebyshev,
7
engageTarget,
8
ensureMobCombat,
9
hasCombatLineOfSight
10
} from "../combat/service.js";
11
import { mobComponents } from "../simulation/spawners.js";
12
13
const SHADE_AGGRO_RANGE = 12;
14
15
/**
16
* Expire summons and pick combat targets for Shade companions.
17
* @returns {{ events: object[], despawnIds: number[] }}
18
*/
19
export function stepSummons (world, now = Date.now())
20
{
21
const events = [];
22
const despawnIds = [];
23
for (const entity of world.ecs.query(Component.summon, Component.creature, Component.position))
24
{
25
const { handle, entityId, summon, position } = entity;
26
if (now >= (summon.expiresAt | 0))
27
{
28
despawnIds.push(entityId);
29
continue;
30
}
31
if (world.ecs.has(handle, Component.dead))
32
{ continue; }
33
const combat = world.ecs.get(handle, Component.combat);
34
if (combat?.targetEntityId != null)
35
{
36
const stillValid = resolveSummonTarget(world, combat.targetEntityId, summon.ownerEntityId);
37
if (stillValid)
38
{ continue; }
39
combat.targetEntityId = null;
40
}
41
42
const targetId = pickShadeTarget(world, entityId, handle, position, summon.ownerEntityId);
43
if (targetId == null)
44
{ continue; }
45
if (!ensureMobCombat(world.ecs, entityId))
46
{ continue; }
47
engageTarget(world.ecs, entityId, targetId, now);
48
}
49
return { events, despawnIds };
50
}
51
52
function resolveSummonTarget (world, targetId, ownerEntityId)
53
{
54
if (targetId == null || targetId === ownerEntityId)
55
{ return false; }
56
const handle = world.ecs.handleOf(targetId);
57
if (handle == null)
58
{ return false; }
59
if (world.ecs.has(handle, Component.dead))
60
{ return false; }
61
const health = world.ecs.get(handle, Component.health);
62
if (health && health.current <= 0)
63
{ return false; }
64
return true;
65
}
66
67
function pickShadeTarget (world, shadeId, shadeHandle, shadePos, ownerEntityId)
68
{
69
const ownerHandle = world.ecs.handleOf(ownerEntityId);
70
if (ownerHandle == null || world.ecs.has(ownerHandle, Component.dead))
71
{ return null; }
72
73
const ownerCombat = world.ecs.get(ownerHandle, Component.combat);
74
if (ownerCombat?.targetEntityId != null
75
&& ownerCombat.targetEntityId !== shadeId
76
&& resolveSummonTarget(world, ownerCombat.targetEntityId, ownerEntityId))
77
{ return ownerCombat.targetEntityId; }
78
79
// Anything attacking the owner.
80
for (const entity of world.ecs.query(Component.combat, Component.creature, Component.position))
81
{
82
if (entity.entityId === shadeId || entity.entityId === ownerEntityId)
83
{ continue; }
84
if (entity.combat.targetEntityId !== ownerEntityId)
85
{ continue; }
86
if (world.ecs.has(entity.handle, Component.dead))
87
{ continue; }
88
if (!inRangeLos(world, shadePos, entity.position))
89
{ continue; }
90
return entity.entityId;
91
}
92
93
// Aggressive mobs nearby.
94
let bestId = null;
95
let bestDist = Infinity;
96
for (const entity of world.ecs.query(Component.creature, Component.position))
97
{
98
if (entity.entityId === shadeId || entity.entityId === ownerEntityId)
99
{ continue; }
100
if (world.ecs.has(entity.handle, Component.dead))
101
{ continue; }
102
if (world.ecs.get(entity.handle, Component.summon))
103
{ continue; }
104
const def = mobDefinition(entity.creature.mobTypeId);
105
const origin = world.ecs.get(entity.handle, Component.spawnOrigin);
106
const aggressive = origin ? !!origin.aggressive : mobIsAggressive(def);
107
if (!aggressive || !mobCanFight(def))
108
{ continue; }
109
const dist = chebyshev(
110
shadePos.tileX,
111
shadePos.tileY,
112
entity.position.tileX,
113
entity.position.tileY
114
);
115
if (dist < 1 || dist > SHADE_AGGRO_RANGE || dist >= bestDist)
116
{ continue; }
117
if (!inRangeLos(world, shadePos, entity.position))
118
{ continue; }
119
bestDist = dist;
120
bestId = entity.entityId;
121
}
122
return bestId;
123
}
124
125
function inRangeLos (world, fromPos, toPos)
126
{
127
const dist = chebyshev(fromPos.tileX, fromPos.tileY, toPos.tileX, toPos.tileY);
128
if (dist < 1 || dist > SHADE_AGGRO_RANGE)
129
{ return false; }
130
return hasCombatLineOfSight(world, fromPos.tileX, fromPos.tileY, toPos.tileX, toPos.tileY);
131
}
132
133
/** Build ECS components for a Shade summon spawn. */
134
export function shadeSummonComponents ({ tileX, tileY, level, ownerEntityId, expiresAt, dimensionId })
135
{
136
const components = mobComponents({
137
mobTypeId: MobId.shade,
138
tileX,
139
tileY,
140
level,
141
dimensionId,
142
displayName: "Shade",
143
aggressive: false
144
});
145
components.summon = {
146
ownerEntityId,
147
expiresAt
148
};
149
return components;
150
}
151
152
export function publicSummonDespawn (entityId)
153
{
154
return { type: "entity-despawn", entityId };
155
}
@@ -0,0 +1,155 @@1
import { Component } from "../ecs/components.js";2
import { MobId, mobDefinition } from "../../../shared/definitions/mobs.js";3
import { mobCanFight, mobIsAggressive } from "../../../shared/definitions/mobCombat.js";4
import5
{6
chebyshev,7
engageTarget,8
ensureMobCombat,9
hasCombatLineOfSight10
} from "../combat/service.js";11
import { mobComponents } from "../simulation/spawners.js";12
13
const SHADE_AGGRO_RANGE = 12;14
15
/**16
* Expire summons and pick combat targets for Shade companions.17
* @returns {{ events: object[], despawnIds: number[] }}18
*/19
export function stepSummons (world, now = Date.now())20
{21
const events = [];22
const despawnIds = [];23
for (const entity of world.ecs.query(Component.summon, Component.creature, Component.position))24
{25
const { handle, entityId, summon, position } = entity;26
if (now >= (summon.expiresAt | 0))27
{28
despawnIds.push(entityId);29
continue;30
}31
if (world.ecs.has(handle, Component.dead))32
{ continue; }33
const combat = world.ecs.get(handle, Component.combat);34
if (combat?.targetEntityId != null)35
{36
const stillValid = resolveSummonTarget(world, combat.targetEntityId, summon.ownerEntityId);37
if (stillValid)38
{ continue; }39
combat.targetEntityId = null;40
}41
42
const targetId = pickShadeTarget(world, entityId, handle, position, summon.ownerEntityId);43
if (targetId == null)44
{ continue; }45
if (!ensureMobCombat(world.ecs, entityId))46
{ continue; }47
engageTarget(world.ecs, entityId, targetId, now);48
}49
return { events, despawnIds };50
}51
52
function resolveSummonTarget (world, targetId, ownerEntityId)53
{54
if (targetId == null || targetId === ownerEntityId)55
{ return false; }56
const handle = world.ecs.handleOf(targetId);57
if (handle == null)58
{ return false; }59
if (world.ecs.has(handle, Component.dead))60
{ return false; }61
const health = world.ecs.get(handle, Component.health);62
if (health && health.current <= 0)63
{ return false; }64
return true;65
}66
67
function pickShadeTarget (world, shadeId, shadeHandle, shadePos, ownerEntityId)68
{69
const ownerHandle = world.ecs.handleOf(ownerEntityId);70
if (ownerHandle == null || world.ecs.has(ownerHandle, Component.dead))71
{ return null; }72
73
const ownerCombat = world.ecs.get(ownerHandle, Component.combat);74
if (ownerCombat?.targetEntityId != null75
&& ownerCombat.targetEntityId !== shadeId76
&& resolveSummonTarget(world, ownerCombat.targetEntityId, ownerEntityId))77
{ return ownerCombat.targetEntityId; }78
79
// Anything attacking the owner.80
for (const entity of world.ecs.query(Component.combat, Component.creature, Component.position))81
{82
if (entity.entityId === shadeId || entity.entityId === ownerEntityId)83
{ continue; }84
if (entity.combat.targetEntityId !== ownerEntityId)85
{ continue; }86
if (world.ecs.has(entity.handle, Component.dead))87
{ continue; }88
if (!inRangeLos(world, shadePos, entity.position))89
{ continue; }90
return entity.entityId;91
}92
93
// Aggressive mobs nearby.94
let bestId = null;95
let bestDist = Infinity;96
for (const entity of world.ecs.query(Component.creature, Component.position))97
{98
if (entity.entityId === shadeId || entity.entityId === ownerEntityId)99
{ continue; }100
if (world.ecs.has(entity.handle, Component.dead))101
{ continue; }102
if (world.ecs.get(entity.handle, Component.summon))103
{ continue; }104
const def = mobDefinition(entity.creature.mobTypeId);105
const origin = world.ecs.get(entity.handle, Component.spawnOrigin);106
const aggressive = origin ? !!origin.aggressive : mobIsAggressive(def);107
if (!aggressive || !mobCanFight(def))108
{ continue; }109
const dist = chebyshev(110
shadePos.tileX,111
shadePos.tileY,112
entity.position.tileX,113
entity.position.tileY114
);115
if (dist < 1 || dist > SHADE_AGGRO_RANGE || dist >= bestDist)116
{ continue; }117
if (!inRangeLos(world, shadePos, entity.position))118
{ continue; }119
bestDist = dist;120
bestId = entity.entityId;121
}122
return bestId;123
}124
125
function inRangeLos (world, fromPos, toPos)126
{127
const dist = chebyshev(fromPos.tileX, fromPos.tileY, toPos.tileX, toPos.tileY);128
if (dist < 1 || dist > SHADE_AGGRO_RANGE)129
{ return false; }130
return hasCombatLineOfSight(world, fromPos.tileX, fromPos.tileY, toPos.tileX, toPos.tileY);131
}132
133
/** Build ECS components for a Shade summon spawn. */134
export function shadeSummonComponents ({ tileX, tileY, level, ownerEntityId, expiresAt, dimensionId })135
{136
const components = mobComponents({137
mobTypeId: MobId.shade,138
tileX,139
tileY,140
level,141
dimensionId,142
displayName: "Shade",143
aggressive: false144
});145
components.summon = {146
ownerEntityId,147
expiresAt148
};149
return components;150
}151
152
export function publicSummonDespawn (entityId)153
{154
return { type: "entity-despawn", entityId };155
}@@ -0,0 +1,250 @@
1
import { Component } from "../ecs/components.js";
2
import { BlockType } from "../../../shared/definitions/tiles.js";
3
import { CraftingItemId } from "../../../shared/definitions/craftingItems.js";
4
import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";
5
import { itemDefinition } from "../../../shared/definitions/items.js";
6
import { cookedFishItemId } from "../../../shared/definitions/fishItems.js";
7
import { SkillId } from "../../../shared/definitions/skills.js";
8
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
9
import { rollSkill } from "../../../shared/combat/rolls.js";
10
import { firestartingDifficulty, campfireDurationMs } from "../../../shared/definitions/craftingStations.js";
11
import { MATERIAL_DISPLAY_NAME } from "../../../shared/definitions/materialTiers.js";
12
import { stackQuantity } from "../../../shared/items/inventory.js";
13
import { attachOrigins } from "../../../shared/items/origin.js";
14
import
15
{
16
addGroundItem,
17
publicGroundItem,
18
removeGroundItem
19
} from "../items/bags.js";
20
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
21
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22
23
const TINDERS_COOK_BURN_CHANCE = 0.4;
24
const COOK_DIFFICULTY = 1;
25
26
function woodTierFromLogItemId (itemId)
27
{
28
const def = itemDefinition(itemId);
29
if (!def || def.familyId !== ItemFamilyId.log)
30
{ return null; }
31
return def.tier ?? null;
32
}
33
34
function groundItemsAt (world, tileX, tileY)
35
{
36
const out = [];
37
for (const item of world.groundItems?.values?.() ?? [])
38
{
39
if (item.tileX === tileX && item.tileY === tileY)
40
{ out.push(item); }
41
}
42
return out;
43
}
44
45
function blockAt (world, tileX, tileY)
46
{
47
const chunkX = tileToChunk(tileX);
48
const chunkY = tileToChunk(tileY);
49
const data = world.chunkData?.(chunkX, chunkY);
50
if (!data)
51
{ return null; }
52
const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
53
return data.blocks?.[index] ?? null;
54
}
55
56
function placeCampfire (world, tileX, tileY, woodTier, now)
57
{
58
const chunkX = tileToChunk(tileX);
59
const chunkY = tileToChunk(tileY);
60
const localX = tileToLocal(tileX);
61
const localY = tileToLocal(tileY);
62
const data = world.chunkData(chunkX, chunkY);
63
const index = localY * CHUNK_SIZE + localX;
64
const expiresAt = now + campfireDurationMs(woodTier);
65
const block = {
66
typeId: BlockType.campfire,
67
state: woodTier,
68
config: { woodTier, litAt: now, expiresAt }
69
};
70
data.blocks[index] = block;
71
if (!world.campfireExpires)
72
{ world.campfireExpires = new Map(); }
73
world.campfireExpires.set(`${tileX},${tileY}`, {
74
tileX,
75
tileY,
76
woodTier,
77
expiresAt
78
});
79
return {
80
type: "chunk-delta",
81
chunkX,
82
chunkY,
83
tileX,
84
tileY,
85
localX,
86
localY,
87
block
88
};
89
}
90
91
function consumeOneGroundStack (world, item, events)
92
{
93
const qty = stackQuantity(item.stack?.quantity);
94
if (qty <= 1)
95
{
96
removeGroundItem(world, item.groundItemId);
97
events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
98
return;
99
}
100
item.stack.quantity = qty - 1;
101
events.push({
102
type: "ground-item-appear",
103
...publicGroundItem(item),
104
stack: item.stack,
105
droppedAt: item.droppedAt,
106
source: item.source,
107
expiresAt: item.expiresAt
108
});
109
}
110
111
function cookableRawDef (itemId)
112
{
113
const def = itemDefinition(itemId);
114
if (!def?.cookable || def.cookState !== "raw")
115
{ return null; }
116
return def;
117
}
118
119
function cookedItemIdForRaw (rawDef)
120
{
121
if (rawDef.fishSpeciesId)
122
{ return cookedFishItemId(rawDef.fishSpeciesId); }
123
if (rawDef.itemId === CraftingItemId.rawMeat)
124
{ return CraftingItemId.cookedMeat; }
125
return rawDef.cookedItemId ?? CraftingItemId.cookedMeat;
126
}
127
128
function spawnGroundStack (world, tileX, tileY, stack, now, events)
129
{
130
const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
131
const item = {
132
groundItemId,
133
tileX,
134
tileY,
135
stack,
136
droppedAt: now,
137
source: "tinders",
138
expiresAt: now + 1000 * 60 * 30
139
};
140
addGroundItem(world, item);
141
events.push({
142
type: "ground-item-appear",
143
...publicGroundItem(item),
144
stack: item.stack,
145
droppedAt: item.droppedAt,
146
source: item.source,
147
expiresAt: item.expiresAt
148
});
149
}
150
151
/**
152
* Tinders: Mind roll lights ground logs (as firestarting) or cooks raw meat/fish (40% burn).
153
*/
154
export function applyTindersAtTile (world, impact, now)
155
{
156
const events = [];
157
const tileX = impact.targetTileX | 0;
158
const tileY = impact.targetTileY | 0;
159
const mind = impact.levels?.mind | 0 || 0;
160
const rng = world.rng ?? Math.random;
161
const items = groundItemsAt(world, tileX, tileY);
162
163
const logItem = items.find((item) => woodTierFromLogItemId(item.stack?.itemId));
164
if (logItem)
165
{
166
const woodTier = woodTierFromLogItemId(logItem.stack.itemId);
167
const difficulty = firestartingDifficulty(woodTier);
168
if (mind < difficulty)
169
{
170
const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
171
events.push({
172
type: "command-error",
173
sessionId: null,
174
message: `Your mind is too weak to light ${label} logs.`
175
});
176
return events;
177
}
178
if (blockAt(world, tileX, tileY))
179
{
180
events.push({
181
type: "command-error",
182
sessionId: null,
183
message: "There is no room for a fire there."
184
});
185
return events;
186
}
187
const roll = rollSkill(mind, rng);
188
if (roll < difficulty)
189
{
190
events.push({
191
type: "command-error",
192
sessionId: null,
193
message: "The sparks fail to catch."
194
});
195
return events;
196
}
197
consumeOneGroundStack(world, logItem, events);
198
events.push(placeCampfire(world, tileX, tileY, woodTier, now));
199
return events;
200
}
201
202
const meatItem = items.find((item) => cookableRawDef(item.stack?.itemId));
203
if (meatItem)
204
{
205
const rawDef = cookableRawDef(meatItem.stack.itemId);
206
const roll = rollSkill(mind, rng);
207
if (roll < COOK_DIFFICULTY)
208
{
209
events.push({
210
type: "command-error",
211
sessionId: null,
212
message: "The meat fails to cook."
213
});
214
return events;
215
}
216
const burned = rng() < TINDERS_COOK_BURN_CHANCE;
217
const outId = burned
218
? (rawDef.burntItemId ?? CraftingItemId.burntMeat)
219
: cookedItemIdForRaw(rawDef);
220
consumeOneGroundStack(world, meatItem, events);
221
const stack = attachOrigins({ itemId: outId, quantity: 1, origins: [] });
222
spawnGroundStack(world, tileX, tileY, stack, now, events);
223
224
const casterHandle = world.ecs.handleOf(impact.casterEntityId);
225
const skills = casterHandle != null ? world.ecs.get(casterHandle, Component.skills) : null;
226
if (skills?.xp && impact.casterCharacterId)
227
{
228
const result = applySkillXp(skills, SkillId.cooking, COOK_DIFFICULTY);
229
if (result.changed)
230
{
231
events.push({
232
type: "skills-updated",
233
entityId: impact.casterEntityId,
234
characterId: impact.casterCharacterId,
235
skills: publicSkillsView(skills),
236
stored: storedSkillXp(skills),
237
levelUps: result.levelUp ? [result.levelUp] : []
238
});
239
}
240
}
241
return events;
242
}
243
244
events.push({
245
type: "command-error",
246
sessionId: null,
247
message: "There is nothing here to light or cook."
248
});
249
return events;
250
}
@@ -0,0 +1,250 @@1
import { Component } from "../ecs/components.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { CraftingItemId } from "../../../shared/definitions/craftingItems.js";4
import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";5
import { itemDefinition } from "../../../shared/definitions/items.js";6
import { cookedFishItemId } from "../../../shared/definitions/fishItems.js";7
import { SkillId } from "../../../shared/definitions/skills.js";8
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";9
import { rollSkill } from "../../../shared/combat/rolls.js";10
import { firestartingDifficulty, campfireDurationMs } from "../../../shared/definitions/craftingStations.js";11
import { MATERIAL_DISPLAY_NAME } from "../../../shared/definitions/materialTiers.js";12
import { stackQuantity } from "../../../shared/items/inventory.js";13
import { attachOrigins } from "../../../shared/items/origin.js";14
import15
{16
addGroundItem,17
publicGroundItem,18
removeGroundItem19
} from "../items/bags.js";20
import { tileToChunk, tileToLocal } from "../world/coordinates.js";21
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";22
23
const TINDERS_COOK_BURN_CHANCE = 0.4;24
const COOK_DIFFICULTY = 1;25
26
function woodTierFromLogItemId (itemId)27
{28
const def = itemDefinition(itemId);29
if (!def || def.familyId !== ItemFamilyId.log)30
{ return null; }31
return def.tier ?? null;32
}33
34
function groundItemsAt (world, tileX, tileY)35
{36
const out = [];37
for (const item of world.groundItems?.values?.() ?? [])38
{39
if (item.tileX === tileX && item.tileY === tileY)40
{ out.push(item); }41
}42
return out;43
}44
45
function blockAt (world, tileX, tileY)46
{47
const chunkX = tileToChunk(tileX);48
const chunkY = tileToChunk(tileY);49
const data = world.chunkData?.(chunkX, chunkY);50
if (!data)51
{ return null; }52
const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);53
return data.blocks?.[index] ?? null;54
}55
56
function placeCampfire (world, tileX, tileY, woodTier, now)57
{58
const chunkX = tileToChunk(tileX);59
const chunkY = tileToChunk(tileY);60
const localX = tileToLocal(tileX);61
const localY = tileToLocal(tileY);62
const data = world.chunkData(chunkX, chunkY);63
const index = localY * CHUNK_SIZE + localX;64
const expiresAt = now + campfireDurationMs(woodTier);65
const block = {66
typeId: BlockType.campfire,67
state: woodTier,68
config: { woodTier, litAt: now, expiresAt }69
};70
data.blocks[index] = block;71
if (!world.campfireExpires)72
{ world.campfireExpires = new Map(); }73
world.campfireExpires.set(`${tileX},${tileY}`, {74
tileX,75
tileY,76
woodTier,77
expiresAt78
});79
return {80
type: "chunk-delta",81
chunkX,82
chunkY,83
tileX,84
tileY,85
localX,86
localY,87
block88
};89
}90
91
function consumeOneGroundStack (world, item, events)92
{93
const qty = stackQuantity(item.stack?.quantity);94
if (qty <= 1)95
{96
removeGroundItem(world, item.groundItemId);97
events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });98
return;99
}100
item.stack.quantity = qty - 1;101
events.push({102
type: "ground-item-appear",103
...publicGroundItem(item),104
stack: item.stack,105
droppedAt: item.droppedAt,106
source: item.source,107
expiresAt: item.expiresAt108
});109
}110
111
function cookableRawDef (itemId)112
{113
const def = itemDefinition(itemId);114
if (!def?.cookable || def.cookState !== "raw")115
{ return null; }116
return def;117
}118
119
function cookedItemIdForRaw (rawDef)120
{121
if (rawDef.fishSpeciesId)122
{ return cookedFishItemId(rawDef.fishSpeciesId); }123
if (rawDef.itemId === CraftingItemId.rawMeat)124
{ return CraftingItemId.cookedMeat; }125
return rawDef.cookedItemId ?? CraftingItemId.cookedMeat;126
}127
128
function spawnGroundStack (world, tileX, tileY, stack, now, events)129
{130
const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);131
const item = {132
groundItemId,133
tileX,134
tileY,135
stack,136
droppedAt: now,137
source: "tinders",138
expiresAt: now + 1000 * 60 * 30139
};140
addGroundItem(world, item);141
events.push({142
type: "ground-item-appear",143
...publicGroundItem(item),144
stack: item.stack,145
droppedAt: item.droppedAt,146
source: item.source,147
expiresAt: item.expiresAt148
});149
}150
151
/**152
* Tinders: Mind roll lights ground logs (as firestarting) or cooks raw meat/fish (40% burn).153
*/154
export function applyTindersAtTile (world, impact, now)155
{156
const events = [];157
const tileX = impact.targetTileX | 0;158
const tileY = impact.targetTileY | 0;159
const mind = impact.levels?.mind | 0 || 0;160
const rng = world.rng ?? Math.random;161
const items = groundItemsAt(world, tileX, tileY);162
163
const logItem = items.find((item) => woodTierFromLogItemId(item.stack?.itemId));164
if (logItem)165
{166
const woodTier = woodTierFromLogItemId(logItem.stack.itemId);167
const difficulty = firestartingDifficulty(woodTier);168
if (mind < difficulty)169
{170
const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;171
events.push({172
type: "command-error",173
sessionId: null,174
message: `Your mind is too weak to light ${label} logs.`175
});176
return events;177
}178
if (blockAt(world, tileX, tileY))179
{180
events.push({181
type: "command-error",182
sessionId: null,183
message: "There is no room for a fire there."184
});185
return events;186
}187
const roll = rollSkill(mind, rng);188
if (roll < difficulty)189
{190
events.push({191
type: "command-error",192
sessionId: null,193
message: "The sparks fail to catch."194
});195
return events;196
}197
consumeOneGroundStack(world, logItem, events);198
events.push(placeCampfire(world, tileX, tileY, woodTier, now));199
return events;200
}201
202
const meatItem = items.find((item) => cookableRawDef(item.stack?.itemId));203
if (meatItem)204
{205
const rawDef = cookableRawDef(meatItem.stack.itemId);206
const roll = rollSkill(mind, rng);207
if (roll < COOK_DIFFICULTY)208
{209
events.push({210
type: "command-error",211
sessionId: null,212
message: "The meat fails to cook."213
});214
return events;215
}216
const burned = rng() < TINDERS_COOK_BURN_CHANCE;217
const outId = burned218
? (rawDef.burntItemId ?? CraftingItemId.burntMeat)219
: cookedItemIdForRaw(rawDef);220
consumeOneGroundStack(world, meatItem, events);221
const stack = attachOrigins({ itemId: outId, quantity: 1, origins: [] });222
spawnGroundStack(world, tileX, tileY, stack, now, events);223
224
const casterHandle = world.ecs.handleOf(impact.casterEntityId);225
const skills = casterHandle != null ? world.ecs.get(casterHandle, Component.skills) : null;226
if (skills?.xp && impact.casterCharacterId)227
{228
const result = applySkillXp(skills, SkillId.cooking, COOK_DIFFICULTY);229
if (result.changed)230
{231
events.push({232
type: "skills-updated",233
entityId: impact.casterEntityId,234
characterId: impact.casterCharacterId,235
skills: publicSkillsView(skills),236
stored: storedSkillXp(skills),237
levelUps: result.levelUp ? [result.levelUp] : []238
});239
}240
}241
return events;242
}243
244
events.push({245
type: "command-error",246
sessionId: null,247
message: "There is nothing here to light or cook."248
});249
return events;250
}@@ -10,17 +10,18 @@ import { publicEntityView } from "../ecs/serialize.js";
10
10
import { syncPlayerHealth } from "../skills/service.js";
11
11
12
12
/**
13
* Tick timed potion effects: health/stamina regen & drain.
13
* Tick timed potion / spell effects: health/stamina regen & drain.
14
14
* Returns replication events (health/stamina/appearance/status-effects).
15
15
*/
16
16
export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
17
17
{
18
18
const events = [];
19
for (const entity of world.ecs.query(Component.character, Component.statusEffects))
19
for (const entity of world.ecs.query(Component.statusEffects, Component.health))
20
20
{
21
const { handle, entityId, character, statusEffects } = entity;
21
const { handle, entityId, statusEffects } = entity;
22
22
if (world.ecs.has(handle, Component.dead))
23
23
{ continue; }
24
const character = world.ecs.get(handle, Component.character);
24
25
25
26
const beforeScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);
26
27
const beforeGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);
@@ -48,6 +49,14 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
48
49
if ((next | 0) !== beforeInt)
49
50
{ healthChanged = true; }
50
51
}
52
if (entry.type === StatusEffectType.healthDrain && health)
53
{
54
const beforeInt = health.current | 0;
55
const next = Math.max(0, (Number(health.current) || 0) - rate * dt);
56
health.current = next;
57
if ((next | 0) !== beforeInt)
58
{ healthChanged = true; }
59
}
51
60
if (entry.type === StatusEffectType.staminaRegen && stamina)
52
61
{
53
62
const before = Number(stamina.current) || 0;
@@ -64,7 +73,7 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
64
73
}
65
74
}
66
75
67
if (healthChanged)
76
if (healthChanged && character)
68
77
{
69
78
syncPlayerHealth(world.ecs, handle);
70
79
const view = publicEntityView(world.ecs, entityId);
@@ -81,8 +90,23 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
81
90
});
82
91
}
83
92
}
93
else if (healthChanged)
94
{
95
const view = publicEntityView(world.ecs, entityId);
96
if (view)
97
{
98
events.push({
99
type: "entity-health",
100
entityId,
101
health: view.health,
102
maxHealth: view.maxHealth,
103
tileX: view.tileX,
104
tileY: view.tileY
105
});
106
}
107
}
84
108
85
if (staminaChanged)
109
if (staminaChanged && character && stamina)
86
110
{
87
111
events.push({
88
112
type: "stamina",
@@ -111,7 +135,7 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
111
135
});
112
136
}
113
137
}
114
if (statusChanged || healthChanged)
138
if (character && (statusChanged || healthChanged))
115
139
{
116
140
events.push({
117
141
type: "status-effects",
@@ -10,17 +10,18 @@ import { publicEntityView } from "../ecs/serialize.js";10
import { syncPlayerHealth } from "../skills/service.js";10
import { syncPlayerHealth } from "../skills/service.js";11
11
12
/**12
/**13
* Tick timed potion effects: health/stamina regen & drain.13
* Tick timed potion / spell effects: health/stamina regen & drain.14
* Returns replication events (health/stamina/appearance/status-effects).14
* Returns replication events (health/stamina/appearance/status-effects).15
*/15
*/16
export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)16
export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)17
{17
{18
const events = [];18
const events = [];19
for (const entity of world.ecs.query(Component.character, Component.statusEffects))19
for (const entity of world.ecs.query(Component.statusEffects, Component.health))20
{20
{21
const { handle, entityId, character, statusEffects } = entity;21
const { handle, entityId, statusEffects } = entity;22
if (world.ecs.has(handle, Component.dead))22
if (world.ecs.has(handle, Component.dead))23
{ continue; }23
{ continue; }24
const character = world.ecs.get(handle, Component.character);24
25
25
const beforeScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);26
const beforeScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);26
const beforeGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);27
const beforeGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);@@ -48,6 +49,14 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)48
if ((next | 0) !== beforeInt)49
if ((next | 0) !== beforeInt)49
{ healthChanged = true; }50
{ healthChanged = true; }50
}51
}52
if (entry.type === StatusEffectType.healthDrain && health)53
{54
const beforeInt = health.current | 0;55
const next = Math.max(0, (Number(health.current) || 0) - rate * dt);56
health.current = next;57
if ((next | 0) !== beforeInt)58
{ healthChanged = true; }59
}51
if (entry.type === StatusEffectType.staminaRegen && stamina)60
if (entry.type === StatusEffectType.staminaRegen && stamina)52
{61
{53
const before = Number(stamina.current) || 0;62
const before = Number(stamina.current) || 0;@@ -64,7 +73,7 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)64
}73
}65
}74
}66
75
67
if (healthChanged)76
if (healthChanged && character)68
{77
{69
syncPlayerHealth(world.ecs, handle);78
syncPlayerHealth(world.ecs, handle);70
const view = publicEntityView(world.ecs, entityId);79
const view = publicEntityView(world.ecs, entityId);@@ -81,8 +90,23 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)81
});90
});82
}91
}83
}92
}93
else if (healthChanged)94
{95
const view = publicEntityView(world.ecs, entityId);96
if (view)97
{98
events.push({99
type: "entity-health",100
entityId,101
health: view.health,102
maxHealth: view.maxHealth,103
tileX: view.tileX,104
tileY: view.tileY105
});106
}107
}84
108
85
if (staminaChanged)109
if (staminaChanged && character && stamina)86
{110
{87
events.push({111
events.push({88
type: "stamina",112
type: "stamina",@@ -111,7 +135,7 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)111
});135
});112
}136
}113
}137
}114
if (statusChanged || healthChanged)138
if (character && (statusChanged || healthChanged))115
{139
{116
events.push({140
events.push({117
type: "status-effects",141
type: "status-effects",