| 1 | import { Component } from "../ecs/components.js"; |
| 2 | import { tileToChunk, tileToLocal } from "../world/coordinates.js"; |
| 3 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 4 | import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; |
| 5 | |
| 6 | /** Find a neighbouring (or same) tile with the given block type. Prefer non-self when possible. */ |
| 7 | export function findAdjacentBlockTile (world, tileX, tileY, blockType, dimensionId = OVERWORLD_ID) |
| 8 | { |
| 9 | const dim = normalizeDimensionId(dimensionId); |
| 10 | let fallback = null; |
| 11 | for (let dy = -1; dy <= 1; dy++) |
| 12 | { |
| 13 | for (let dx = -1; dx <= 1; dx++) |
| 14 | { |
| 15 | const x = tileX + dx; |
| 16 | const y = tileY + dy; |
| 17 | const data = world.chunkData(tileToChunk(x), tileToChunk(y), dim); |
| 18 | const index = tileToLocal(y) * CHUNK_SIZE + tileToLocal(x); |
| 19 | if (data.blocks[index]?.typeId !== blockType) |
| 20 | { continue; } |
| 21 | if (dx !== 0 || dy !== 0) |
| 22 | { return { tileX: x, tileY: y }; } |
| 23 | fallback = { tileX: x, tileY: y }; |
| 24 | } |
| 25 | } |
| 26 | return fallback; |
| 27 | } |
| 28 | |
| 29 | /** Shove the actor toward a world tile (bank, furnace, mine, craft, …). */ |
| 30 | export function tileShoveEvent (entityId, fromTileX, fromTileY, tileX, tileY) |
| 31 | { |
| 32 | return { |
| 33 | type: "tile-shove", |
| 34 | attackerId: entityId, |
| 35 | fromTileX, |
| 36 | fromTileY, |
| 37 | tileX, |
| 38 | tileY |
| 39 | }; |
| 40 | } |
| 41 | |
| 42 | export function tileShoveTowardBlock (world, handle, entityId, blockType) |
| 43 | { |
| 44 | const position = world.ecs.get(handle, Component.position); |
| 45 | if (!position) |
| 46 | { return null; } |
| 47 | const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 48 | const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType, dim); |
| 49 | if (!target) |
| 50 | { return null; } |
| 51 | return tileShoveEvent(entityId, position.tileX, position.tileY, target.tileX, target.tileY); |
| 52 | } |