| 1 | import { CHUNK_SIZE, MessageType } from "../../../shared/protocol/constants.js"; |
| 2 | import { obscureSpeech, speechReadability } from "../../../shared/speech/proximity.js"; |
| 3 | |
| 4 | let nextMessageId = 1; |
| 5 | |
| 6 | export function broadcastSpeech (sessions, simulation, speakerSession, rawText) |
| 7 | { |
| 8 | const maxChars = Math.max(1, Math.round(simulation.settings.chatMaxCharacters || 100)); |
| 9 | const text = String(rawText ?? "").trim().slice(0, maxChars); |
| 10 | if (!text) |
| 11 | { return; } |
| 12 | |
| 13 | const speakerPos = simulation.positionOf(speakerSession.entityId); |
| 14 | if (!speakerPos) |
| 15 | { return; } |
| 16 | |
| 17 | const messageId = nextMessageId++; |
| 18 | const createdAt = Date.now(); |
| 19 | for (const other of sessions.values()) |
| 20 | { |
| 21 | if (!other.entityId) |
| 22 | { continue; } |
| 23 | let readable = text; |
| 24 | if (other !== speakerSession) |
| 25 | { |
| 26 | const listenerPos = simulation.positionOf(other.entityId); |
| 27 | if (!listenerPos) |
| 28 | { continue; } |
| 29 | const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY); |
| 30 | const readability = speechReadability(distance, CHUNK_SIZE); |
| 31 | if (readability <= 0) |
| 32 | { continue; } |
| 33 | readable = obscureSpeech(text, readability, messageId ^ other.id); |
| 34 | if (!readable) |
| 35 | { continue; } |
| 36 | } |
| 37 | if (other.socket.readyState === 1) |
| 38 | { |
| 39 | other.socket.send(JSON.stringify({ |
| 40 | type: MessageType.chatBubble, |
| 41 | messageId, |
| 42 | entityId: speakerSession.entityId, |
| 43 | characterId: speakerSession.characterId, |
| 44 | text: readable, |
| 45 | createdAt |
| 46 | })); |
| 47 | } |
| 48 | } |
| 49 | } |