@quake2ts/cgame 0.0.739
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.global.js +10 -0
- package/dist/browser/index.global.js.map +1 -0
- package/dist/cjs/index.cjs +947 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/esm/index.js +940 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/index.cjs +1353 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +202 -0
- package/dist/index.d.ts +202 -0
- package/dist/index.js +1346 -0
- package/dist/index.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/types/hud/blends.d.ts +4 -0
- package/dist/types/hud/blends.d.ts.map +1 -0
- package/dist/types/hud/crosshair.d.ts +7 -0
- package/dist/types/hud/crosshair.d.ts.map +1 -0
- package/dist/types/hud/damage.d.ts +5 -0
- package/dist/types/hud/damage.d.ts.map +1 -0
- package/dist/types/hud/diagnostics.d.ts +3 -0
- package/dist/types/hud/diagnostics.d.ts.map +1 -0
- package/dist/types/hud/icons.d.ts +12 -0
- package/dist/types/hud/icons.d.ts.map +1 -0
- package/dist/types/hud/layout.d.ts +30 -0
- package/dist/types/hud/layout.d.ts.map +1 -0
- package/dist/types/hud/messages.d.ts +15 -0
- package/dist/types/hud/messages.d.ts.map +1 -0
- package/dist/types/hud/numbers.d.ts +3 -0
- package/dist/types/hud/numbers.d.ts.map +1 -0
- package/dist/types/hud/pickup.d.ts +4 -0
- package/dist/types/hud/pickup.d.ts.map +1 -0
- package/dist/types/hud/statusbar.d.ts +16 -0
- package/dist/types/hud/statusbar.d.ts.map +1 -0
- package/dist/types/hud/subtitles.d.ts +7 -0
- package/dist/types/hud/subtitles.d.ts.map +1 -0
- package/dist/types/hud/types.d.ts +39 -0
- package/dist/types/hud/types.d.ts.map +1 -0
- package/dist/types/index.d.ts +21 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/parse.d.ts +7 -0
- package/dist/types/parse.d.ts.map +1 -0
- package/dist/types/prediction/index.d.ts +53 -0
- package/dist/types/prediction/index.d.ts.map +1 -0
- package/dist/types/screen.d.ts +64 -0
- package/dist/types/screen.d.ts.map +1 -0
- package/dist/types/types.d.ts +109 -0
- package/dist/types/types.d.ts.map +1 -0
- package/dist/types/view/camera.d.ts +4 -0
- package/dist/types/view/camera.d.ts.map +1 -0
- package/dist/types/view/effects.d.ts +42 -0
- package/dist/types/view/effects.d.ts.map +1 -0
- package/package.json +56 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../../shared/src/math/vec3.ts","../../../shared/src/math/angles.ts","../../../shared/src/math/anorms.ts","../../../shared/src/math/color.ts","../../../shared/src/math/random.ts","../../../shared/src/math/mat4.ts","../../../shared/src/bsp/contents.ts","../../../shared/src/bsp/spatial.ts","../../../shared/src/bsp/collision.ts","../../../shared/src/protocol/cvar.ts","../../../shared/src/protocol/configstrings.ts","../../../shared/src/replay/index.ts","../../../shared/src/replay/io.ts","../../../shared/src/protocol/contracts.ts","../../../shared/src/pmove/constants.ts","../../../shared/src/pmove/jump.ts","../../../shared/src/pmove/currents.ts","../../../shared/src/pmove/slide.ts","../../../shared/src/pmove/move.ts","../../../shared/src/pmove/water.ts","../../../shared/src/pmove/categorize.ts","../../../shared/src/pmove/dimensions.ts","../../../shared/src/pmove/duck.ts","../../../shared/src/pmove/pmove.ts","../../../shared/src/pmove/stuck.ts","../../../shared/src/pmove/fly.ts","../../../shared/src/pmove/special.ts","../../../shared/src/pmove/snap.ts","../../../shared/src/pmove/view.ts","../../../shared/src/protocol/usercmd.ts","../../../shared/src/protocol/ops.ts","../../../shared/src/protocol/tempEntity.ts","../../../shared/src/protocol/constants.ts","../../../shared/src/protocol/layout.ts","../../../shared/src/protocol/bitpack.ts","../../../shared/src/items/powerups.ts","../../../shared/src/protocol/stats.ts","../../../shared/src/protocol/writeUserCmd.ts","../../../shared/src/protocol/renderFx.ts","../../../shared/src/protocol/crc.ts","../../../shared/src/protocol/effects.ts","../../../shared/src/protocol/entityEvent.ts","../../../shared/src/protocol/entity.ts","../../../shared/src/protocol/player.ts","../../../shared/src/pmove/apply.ts","../../../shared/src/io/binaryStream.ts","../../../shared/src/io/binaryWriter.ts","../../../shared/src/io/messageBuilder.ts","../../../shared/src/net/netchan.ts","../../../shared/src/items/weapons.ts","../../../shared/src/items/ammo.ts","../../../shared/src/items/weaponInfo.ts","../../../shared/src/audio/constants.ts","../../../shared/src/inventory-helpers.ts","../../../shared/src/testing.ts","../../src/hud/crosshair.ts","../../src/hud/icons.ts","../../src/hud/damage.ts","../../src/hud/messages.ts","../../src/hud/subtitles.ts","../../src/hud/blends.ts","../../src/hud/pickup.ts","../../src/hud/numbers.ts","../../src/hud/statusbar.ts","../../src/hud/layout.ts","../../src/screen.ts","../../src/parse.ts","../../../../node_modules/.pnpm/gl-matrix@3.4.4/node_modules/gl-matrix/esm/common.js","../../../../node_modules/.pnpm/gl-matrix@3.4.4/node_modules/gl-matrix/esm/vec3.js","../../src/view/camera.ts","../../src/view/effects.ts","../../src/prediction/index.ts"],"sourcesContent":["/**\n * CGame Module Entry Point\n * Reference: rerelease/cg_main.cpp\n *\n * This module provides the GetCGameAPI() function that returns the cgame_export_t\n * interface to the client engine.\n */\n\nimport type { CGameImport, CGameExport, PmoveInfo } from './types.js';\nimport { PlayerState, PlayerStat, Vec3, applyPmove, PmoveTraceResult, WEAPON_WHEEL_ORDER, WEAPON_AMMO_MAP, G_GetAmmoStat, G_GetPowerupStat, PowerupId } from '@quake2ts/shared';\nimport { LayoutFlags } from '@quake2ts/shared';\nimport { CG_InitScreen, CG_TouchPics, CG_DrawHUD, CG_GetMessageSystem, CG_GetSubtitleSystem } from './screen.js';\nimport { CG_ParseConfigString } from './parse.js';\n\nexport type { CGameImport, CGameExport } from './types.js';\n\n// Re-export new modules\nexport * from './view/camera.js';\nexport * from './view/effects.js';\nexport * from './prediction/index.js';\n\n// Module-level state\nlet cgi: CGameImport | null = null;\nlet cg_predict: { value: number } | null = null;\nlet cg_showmiss: { value: number } | null = null;\n\n/**\n * Initialize the CGame module.\n * Reference: rerelease/cg_main.cpp InitCGame()\n */\nfunction Init(): void {\n if (!cgi) {\n console.error('CGame Init: cgame imports not set');\n return;\n }\n\n cgi.Com_Print('===== CGame Initialization =====\\n');\n\n // Initialize screen/HUD module\n CG_InitScreen(cgi);\n\n // Register CVars\n cg_predict = cgi.Cvar_Get('cg_predict', '1', 0);\n cg_showmiss = cgi.Cvar_Get('cg_showmiss', '0', 0);\n\n cgi.Com_Print('CGame initialized\\n');\n}\n\n/**\n * Shutdown the CGame module.\n * Reference: rerelease/cg_main.cpp ShutdownCGame()\n */\nfunction Shutdown(): void {\n if (cgi) {\n cgi.Com_Print('CGame shutdown\\n');\n }\n cgi = null;\n}\n\n/**\n * Main HUD drawing function (wrapper for CG_DrawHUD).\n * Reference: rerelease/cg_screen.cpp CG_DrawHUD()\n */\nfunction DrawHUD(\n isplit: number,\n data: unknown,\n hud_vrect: { x: number; y: number; width: number; height: number },\n hud_safe: { x: number; y: number; width: number; height: number },\n scale: number,\n playernum: number,\n ps: PlayerState\n): void {\n CG_DrawHUD(isplit, data, hud_vrect, hud_safe, scale, playernum, ps);\n}\n\n/**\n * Precache all HUD images.\n * Reference: rerelease/cg_screen.cpp TouchPics()\n */\nfunction TouchPics(): void {\n CG_TouchPics();\n}\n\n/**\n * Get layout flags for current player state.\n * Reference: rerelease/cg_screen.cpp\n */\nfunction GetLayoutFlags(ps: PlayerState): LayoutFlags {\n // TODO: Implement proper layout flag calculation\n // Based on inventory state, help state, intermission, etc.\n return 0 as LayoutFlags; // No flags set by default\n}\n\n/**\n * Placeholder stubs for remaining CGameExport functions.\n * These will be implemented as needed.\n */\n\nfunction GetActiveWeaponWheelWeapon(ps: PlayerState): number {\n return ps.stats[PlayerStat.STAT_ACTIVE_WHEEL_WEAPON] ?? 0;\n}\n\nfunction GetOwnedWeaponWheelWeapons(ps: PlayerState): number[] {\n const owned: number[] = [];\n const bits1 = ps.stats[PlayerStat.STAT_WEAPONS_OWNED_1] || 0;\n const bits2 = ps.stats[PlayerStat.STAT_WEAPONS_OWNED_2] || 0;\n const fullBits = bits1 | (bits2 << 16);\n\n for (let i = 0; i < WEAPON_WHEEL_ORDER.length; i++) {\n if (fullBits & (1 << i)) {\n owned.push(i);\n }\n }\n return owned;\n}\n\nfunction GetWeaponWheelAmmoCount(ps: PlayerState, weapon: number): number {\n if (weapon < 0 || weapon >= WEAPON_WHEEL_ORDER.length) {\n return 0;\n }\n const weaponId = WEAPON_WHEEL_ORDER[weapon];\n const ammoType = WEAPON_AMMO_MAP[weaponId];\n if (ammoType === null) {\n return -1; // Infinite/No ammo\n }\n return G_GetAmmoStat(ps.stats, ammoType);\n}\n\nfunction GetPowerupWheelCount(ps: PlayerState): number {\n let count = 0;\n // Iterate over all known powerups to check if they are active\n const powerups = Object.values(PowerupId);\n for (const id of powerups) {\n if (G_GetPowerupStat(ps.stats, id) > 0) {\n count++;\n }\n }\n return count;\n}\n\nfunction GetHitMarkerDamage(ps: PlayerState): number {\n return ps.stats[PlayerStat.STAT_HIT_MARKER] ?? 0;\n}\n\n/**\n * Pmove implementation for client-side prediction.\n * Calls the shared Pmove() function (applyPmove in TS port).\n *\n * @param pmove - PmoveInfo structure (similar to pmove_t)\n */\nfunction Pmove(pmove: unknown): void {\n const pm = pmove as PmoveInfo;\n if (!pm || !pm.s || !pm.cmd || !cgi) {\n return;\n }\n\n // If prediction is disabled, do nothing (server state prevails)\n if (cg_predict && cg_predict.value === 0) {\n return;\n }\n\n // Adapter for PmoveTraceFn using CGameImport trace\n const traceAdapter = (start: Vec3, end: Vec3, mins?: Vec3, maxs?: Vec3): PmoveTraceResult => {\n // Shared PmoveTraceFn uses optional mins/maxs, CGameImport expects them.\n // If not provided, assume point trace (0,0,0)\n const zero: Vec3 = { x: 0, y: 0, z: 0 };\n return cgi!.PM_Trace(\n start,\n end,\n mins || zero,\n maxs || zero\n );\n };\n\n // Adapter for PmovePointContentsFn using CGameImport trace\n const pointContentsAdapter = (point: Vec3): number => {\n const zero: Vec3 = { x: 0, y: 0, z: 0 };\n // Perform a point trace to get contents\n const tr = cgi!.PM_Trace(point, point, zero, zero);\n return tr.contents || 0;\n };\n\n // Check for prediction errors if enabled\n // Note: The actual prediction logic (reconciliation) happens in ClientPrediction class which\n // drives the client-side state update. However, Pmove here is called by the client engine\n // to execute the *current* frame's prediction during the client loop.\n\n // In Quake 2, CL_PredictMovement calls Pmove repeatedly.\n // The client prediction class we built (ClientPrediction) encapsulates state management.\n // Ideally, the client engine should use ClientPrediction to get the state to render.\n\n // But keeping with the Pmove API:\n // This function simply advances the physics for one command.\n\n // Call shared Pmove implementation\n // This returns a NEW PlayerState, so we must update pm.s\n const newState = applyPmove(pm.s, pm.cmd, traceAdapter, pointContentsAdapter);\n\n // Update mutable state\n pm.s.origin = newState.origin;\n pm.s.velocity = newState.velocity;\n pm.s.onGround = newState.onGround;\n pm.s.waterLevel = newState.waterLevel;\n // applyPmove might update other fields in the future\n\n // If debug enabled, we might log something here, but Pmove is high frequency.\n // We defer logging to the reconciliation step in ClientPrediction.\n}\n\nfunction ParseConfigString(i: number, s: string): void {\n if (!cgi) return;\n CG_ParseConfigString(cgi, i, s);\n}\n\nfunction ParseCenterPrint(str: string, isplit: number, instant: boolean): void {\n if (!cgi) return;\n const messageSystem = CG_GetMessageSystem();\n // TODO: Parse layout strings and handle key bindings\n messageSystem.setCenterPrint(str, cgi.CL_ClientTime());\n}\n\nfunction NotifyMessage(isplit: number, msg: string, is_chat: boolean): void {\n if (!cgi) return;\n const messageSystem = CG_GetMessageSystem();\n messageSystem.addNotification(msg, is_chat, cgi.CL_ClientTime());\n}\n\nfunction ClearNotify(isplit: number): void {\n const messageSystem = CG_GetMessageSystem();\n messageSystem.clearNotifications();\n}\n\nfunction ClearCenterprint(isplit: number): void {\n const messageSystem = CG_GetMessageSystem();\n messageSystem.clearCenterPrint();\n}\n\nfunction ShowSubtitle(text: string, soundName: string): void {\n if (!cgi) return;\n const subtitleSystem = CG_GetSubtitleSystem();\n subtitleSystem.addSubtitle(text, cgi.CL_ClientTime());\n}\n\nfunction GetMonsterFlashOffset(id: number): Vec3 {\n return { x: 0, y: 0, z: 0 };\n}\n\nfunction GetExtension(name: string): unknown {\n return null;\n}\n\n/**\n * Main entry point for CGame module.\n * Reference: rerelease/cg_main.cpp GetCGameAPI()\n *\n * @param imports - Functions provided by the client engine\n * @returns CGame export interface\n */\nexport function GetCGameAPI(imports: CGameImport): CGameExport {\n cgi = imports;\n\n return {\n // Lifecycle\n Init,\n Shutdown,\n\n // Rendering\n DrawHUD,\n TouchPics,\n\n // Layout\n LayoutFlags: GetLayoutFlags,\n\n // Weapon wheel\n GetActiveWeaponWheelWeapon,\n GetOwnedWeaponWheelWeapons,\n GetWeaponWheelAmmoCount,\n GetPowerupWheelCount,\n\n // Hit markers\n GetHitMarkerDamage,\n\n // Prediction\n Pmove,\n\n // Parsing\n ParseConfigString,\n ParseCenterPrint,\n NotifyMessage,\n ShowSubtitle,\n\n // State management\n ClearNotify,\n ClearCenterprint,\n\n // Effects\n GetMonsterFlashOffset,\n\n // Extension\n GetExtension,\n };\n}\n","export interface Vec3 {\n readonly x: number;\n readonly y: number;\n readonly z: number;\n readonly [index: number]: number;\n}\n\nexport const ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\n\n// Matches STOP_EPSILON from rerelease q_vec3.h\nexport const STOP_EPSILON = 0.1;\n\nconst DEG_TO_RAD = Math.PI / 180;\n\nexport interface Bounds3 {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n}\n\nexport type Mat3Row = readonly [number, number, number];\nexport type Mat3 = readonly [Mat3Row, Mat3Row, Mat3Row];\n\nexport function copyVec3(a: Vec3): Vec3 {\n return { x: a.x, y: a.y, z: a.z };\n}\n\nexport function addVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };\n}\n\nexport function subtractVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };\n}\n\nexport function multiplyVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x * b.x, y: a.y * b.y, z: a.z * b.z };\n}\n\nexport function scaleVec3(a: Vec3, scalar: number): Vec3 {\n return { x: a.x * scalar, y: a.y * scalar, z: a.z * scalar };\n}\n\nexport function negateVec3(a: Vec3): Vec3 {\n return scaleVec3(a, -1);\n}\n\nexport function dotVec3(a: Vec3, b: Vec3): number {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\nexport function crossVec3(a: Vec3, b: Vec3): Vec3 {\n return {\n x: a.y * b.z - a.z * b.y,\n y: a.z * b.x - a.x * b.z,\n z: a.x * b.y - a.y * b.x,\n };\n}\n\nexport function lengthSquaredVec3(a: Vec3): number {\n return dotVec3(a, a);\n}\n\nexport function lengthVec3(a: Vec3): number {\n return Math.sqrt(lengthSquaredVec3(a));\n}\n\nexport function distance(a: Vec3, b: Vec3): number {\n return lengthVec3(subtractVec3(a, b));\n}\n\nexport function vec3Equals(a: Vec3, b: Vec3): boolean {\n return a.x === b.x && a.y === b.y && a.z === b.z;\n}\n\n/**\n * Returns the normalized vector. If the vector is zero-length, the\n * input is returned to mirror the rerelease q_vec3 semantics.\n */\nexport function normalizeVec3(a: Vec3): Vec3 {\n const len = lengthVec3(a);\n return len === 0 ? a : scaleVec3(a, 1 / len);\n}\n\n/**\n * Projects a point onto a plane defined by the given normal.\n * Based on ProjectPointOnPlane in the rerelease q_vec3 helpers.\n */\nexport function projectPointOnPlane(point: Vec3, normal: Vec3): Vec3 {\n const invDenom = 1 / dotVec3(normal, normal);\n const d = dotVec3(normal, point) * invDenom;\n return subtractVec3(point, scaleVec3(normal, invDenom * d));\n}\n\n/**\n * Computes a perpendicular vector to the provided direction using the\n * smallest axial component heuristic used by the rerelease.\n * Assumes the input is normalized.\n */\nexport function perpendicularVec3(src: Vec3): Vec3 {\n let pos = 0;\n let minElement = Math.abs(src.x);\n\n if (Math.abs(src.y) < minElement) {\n pos = 1;\n minElement = Math.abs(src.y);\n }\n\n if (Math.abs(src.z) < minElement) {\n pos = 2;\n }\n\n const axis = pos === 0 ? { x: 1, y: 0, z: 0 } : pos === 1 ? { x: 0, y: 1, z: 0 } : { x: 0, y: 0, z: 1 };\n return normalizeVec3(projectPointOnPlane(axis, src));\n}\n\nexport function closestPointToBox(point: Vec3, mins: Vec3, maxs: Vec3): Vec3 {\n return {\n x: point.x < mins.x ? mins.x : point.x > maxs.x ? maxs.x : point.x,\n y: point.y < mins.y ? mins.y : point.y > maxs.y ? maxs.y : point.y,\n z: point.z < mins.z ? mins.z : point.z > maxs.z ? maxs.z : point.z,\n };\n}\n\nexport function distanceBetweenBoxesSquared(aMins: Vec3, aMaxs: Vec3, bMins: Vec3, bMaxs: Vec3): number {\n let lengthSq = 0;\n\n if (aMaxs.x < bMins.x) {\n const d = aMaxs.x - bMins.x;\n lengthSq += d * d;\n } else if (aMins.x > bMaxs.x) {\n const d = aMins.x - bMaxs.x;\n lengthSq += d * d;\n }\n\n if (aMaxs.y < bMins.y) {\n const d = aMaxs.y - bMins.y;\n lengthSq += d * d;\n } else if (aMins.y > bMaxs.y) {\n const d = aMins.y - bMaxs.y;\n lengthSq += d * d;\n }\n\n if (aMaxs.z < bMins.z) {\n const d = aMaxs.z - bMins.z;\n lengthSq += d * d;\n } else if (aMins.z > bMaxs.z) {\n const d = aMins.z - bMaxs.z;\n lengthSq += d * d;\n }\n\n return lengthSq;\n}\n\nexport function createEmptyBounds3(): Bounds3 {\n return {\n mins: { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY },\n maxs: { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY },\n };\n}\n\nexport function addPointToBounds(point: Vec3, bounds: Bounds3): Bounds3 {\n return {\n mins: {\n x: Math.min(bounds.mins.x, point.x),\n y: Math.min(bounds.mins.y, point.y),\n z: Math.min(bounds.mins.z, point.z),\n },\n maxs: {\n x: Math.max(bounds.maxs.x, point.x),\n y: Math.max(bounds.maxs.y, point.y),\n z: Math.max(bounds.maxs.z, point.z),\n },\n };\n}\n\nexport function boxesIntersect(a: Bounds3, b: Bounds3): boolean {\n return (\n a.mins.x <= b.maxs.x &&\n a.maxs.x >= b.mins.x &&\n a.mins.y <= b.maxs.y &&\n a.maxs.y >= b.mins.y &&\n a.mins.z <= b.maxs.z &&\n a.maxs.z >= b.mins.z\n );\n}\n\n/**\n * Mirrors PM_ClipVelocity from `rerelease/p_move.cpp`: slide the incoming velocity off\n * a plane normal, applying an overbounce scale and zeroing tiny components so callers can\n * detect blocked axes using STOP_EPSILON.\n */\nexport function clipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n const backoff = dotVec3(inVel, normal) * overbounce;\n\n let outX = inVel.x - normal.x * backoff;\n let outY = inVel.y - normal.y * backoff;\n let outZ = inVel.z - normal.z * backoff;\n\n if (outX > -STOP_EPSILON && outX < STOP_EPSILON) {\n outX = 0;\n }\n\n if (outY > -STOP_EPSILON && outY < STOP_EPSILON) {\n outY = 0;\n }\n\n if (outZ > -STOP_EPSILON && outZ < STOP_EPSILON) {\n outZ = 0;\n }\n\n return { x: outX, y: outY, z: outZ };\n}\n\n/**\n * Slide a velocity across one or more clip planes using the same plane set resolution logic\n * seen in the inner loop of `PM_StepSlideMove_Generic` (rerelease `p_move.cpp`). When a single\n * plane is provided this devolves to PM_ClipVelocity; with two planes it projects onto the\n * crease defined by their cross product; with more planes it zeroes the velocity to avoid\n * oscillations.\n */\nexport function clipVelocityAgainstPlanes(\n velocity: Vec3,\n planes: readonly Vec3[],\n overbounce: number,\n primalVelocity?: Vec3,\n): Vec3 {\n if (planes.length === 0) {\n return velocity;\n }\n\n let working = velocity;\n\n for (let i = 0; i < planes.length; i++) {\n working = clipVelocityVec3(working, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) {\n continue;\n }\n\n if (dotVec3(working, planes[j]) < 0) {\n break;\n }\n }\n\n if (j === planes.length) {\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return working;\n }\n }\n\n if (planes.length === 2) {\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n const creaseVelocity = scaleVec3(dir, d);\n\n if (primalVelocity && dotVec3(creaseVelocity, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return creaseVelocity;\n }\n\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return ZERO_VEC3;\n}\n\n/**\n * Alias retained for ergonomics; mirrors PM_ClipVelocity semantics.\n */\nexport function slideClipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n return clipVelocityVec3(inVel, normal, overbounce);\n}\n\n/**\n * Project an offset from a point in forward/right(/up) space into world space.\n * Mirrors G_ProjectSource and G_ProjectSource2 in rerelease q_vec3.\n */\nexport function projectSourceVec3(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y,\n y: point.y + forward.y * distance.x + right.y * distance.y,\n z: point.z + forward.z * distance.x + right.z * distance.y + distance.z,\n };\n}\n\nexport function projectSourceVec3WithUp(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3, up: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y + up.x * distance.z,\n y: point.y + forward.y * distance.x + right.y * distance.y + up.y * distance.z,\n z: point.z + forward.z * distance.x + right.z * distance.y + up.z * distance.z,\n };\n}\n\n/**\n * Spherical linear interpolation between two vectors, mirroring q_vec3::slerp.\n * This is intended for direction vectors; callers should pre-normalize if needed.\n */\nexport function slerpVec3(from: Vec3, to: Vec3, t: number): Vec3 {\n const dot = dotVec3(from, to);\n let aFactor: number;\n let bFactor: number;\n\n if (Math.abs(dot) > 0.9995) {\n aFactor = 1 - t;\n bFactor = t;\n } else {\n const ang = Math.acos(dot);\n const sinOmega = Math.sin(ang);\n const sinAOmega = Math.sin((1 - t) * ang);\n const sinBOmega = Math.sin(t * ang);\n aFactor = sinAOmega / sinOmega;\n bFactor = sinBOmega / sinOmega;\n }\n\n return {\n x: from.x * aFactor + to.x * bFactor,\n y: from.y * aFactor + to.y * bFactor,\n z: from.z * aFactor + to.z * bFactor,\n };\n}\n\nexport function concatRotationMatrices(a: Mat3, b: Mat3): Mat3 {\n const row = (rowIndex: number): Mat3Row => [\n a[rowIndex][0] * b[0][0] + a[rowIndex][1] * b[1][0] + a[rowIndex][2] * b[2][0],\n a[rowIndex][0] * b[0][1] + a[rowIndex][1] * b[1][1] + a[rowIndex][2] * b[2][1],\n a[rowIndex][0] * b[0][2] + a[rowIndex][1] * b[1][2] + a[rowIndex][2] * b[2][2],\n ];\n\n const result = [row(0), row(1), row(2)] as Mat3;\n return result;\n}\n\nexport function rotatePointAroundVector(dir: Vec3, point: Vec3, degrees: number): Vec3 {\n const axisLength = lengthVec3(dir);\n if (axisLength === 0) {\n return point;\n }\n\n const vf = normalizeVec3(dir);\n const vr = perpendicularVec3(vf);\n const vup = crossVec3(vr, vf);\n\n const m: Mat3 = [\n [vr.x, vup.x, vf.x],\n [vr.y, vup.y, vf.y],\n [vr.z, vup.z, vf.z],\n ];\n\n const im: Mat3 = [\n [m[0][0], m[1][0], m[2][0]],\n [m[0][1], m[1][1], m[2][1]],\n [m[0][2], m[1][2], m[2][2]],\n ];\n\n const radians = degrees * DEG_TO_RAD;\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n const zrot: Mat3 = [\n [cos, sin, 0],\n [-sin, cos, 0],\n [0, 0, 1],\n ];\n\n const rot = concatRotationMatrices(concatRotationMatrices(m, zrot), im);\n\n return {\n x: rot[0][0] * point.x + rot[0][1] * point.y + rot[0][2] * point.z,\n y: rot[1][0] * point.x + rot[1][1] * point.y + rot[1][2] * point.z,\n z: rot[2][0] * point.x + rot[2][1] * point.y + rot[2][2] * point.z,\n };\n}\n","import { Vec3 } from './vec3.js';\n\nexport const PITCH = 0;\nexport const YAW = 1;\nexport const ROLL = 2;\n\nconst DEG2RAD_FACTOR = Math.PI / 180;\nconst RAD2DEG_FACTOR = 180 / Math.PI;\n\n// Export constants for direct use in matrix operations\nexport const DEG2RAD = DEG2RAD_FACTOR;\nexport const RAD2DEG = RAD2DEG_FACTOR;\n\nfunction axisComponent(vec: Vec3, axis: number): number {\n switch (axis) {\n case PITCH:\n return vec.x;\n case YAW:\n return vec.y;\n case ROLL:\n default:\n return vec.z;\n }\n}\n\nexport interface AngleVectorsResult {\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly up: Vec3;\n}\n\nexport function degToRad(degrees: number): number {\n return degrees * DEG2RAD_FACTOR;\n}\n\nexport function radToDeg(radians: number): number {\n return radians * RAD2DEG_FACTOR;\n}\n\nexport function lerpAngle(from: number, to: number, frac: number): number {\n let target = to;\n\n if (target - from > 180) {\n target -= 360;\n } else if (target - from < -180) {\n target += 360;\n }\n\n return from + frac * (target - from);\n}\n\nexport function angleMod(angle: number): number {\n const value = angle % 360;\n return value < 0 ? 360 + value : value;\n}\n\nexport function angleVectors(angles: Vec3): AngleVectorsResult {\n const yaw = degToRad(axisComponent(angles, YAW));\n const pitch = degToRad(axisComponent(angles, PITCH));\n const roll = degToRad(axisComponent(angles, ROLL));\n\n const sy = Math.sin(yaw);\n const cy = Math.cos(yaw);\n const sp = Math.sin(pitch);\n const cp = Math.cos(pitch);\n const sr = Math.sin(roll);\n const cr = Math.cos(roll);\n\n const forward: Vec3 = {\n x: cp * cy,\n y: cp * sy,\n z: -sp,\n };\n\n const right: Vec3 = {\n x: -sr * sp * cy - cr * -sy,\n y: -sr * sp * sy - cr * cy,\n z: -sr * cp,\n };\n\n const up: Vec3 = {\n x: cr * sp * cy - sr * -sy,\n y: cr * sp * sy - sr * cy,\n z: cr * cp,\n };\n\n return { forward, right, up };\n}\n\nexport function vectorToYaw(vec: Vec3): number {\n const pitch = axisComponent(vec, PITCH);\n const yawAxis = axisComponent(vec, YAW);\n\n if (pitch === 0) {\n if (yawAxis === 0) {\n return 0;\n }\n\n return yawAxis > 0 ? 90 : 270;\n }\n\n const yaw = radToDeg(Math.atan2(yawAxis, pitch));\n return yaw < 0 ? yaw + 360 : yaw;\n}\n\nexport function vectorToAngles(vec: Vec3): Vec3 {\n const x = vec.x;\n const y = vec.y;\n const z = vec.z;\n\n if (y === 0 && x === 0) {\n return { x: z > 0 ? -90 : -270, y: 0, z: 0 };\n }\n\n let yaw: number;\n if (x) {\n yaw = radToDeg(Math.atan2(y, x));\n } else if (y > 0) {\n yaw = 90;\n } else {\n yaw = 270;\n }\n\n if (yaw < 0) {\n yaw += 360;\n }\n\n const forward = Math.sqrt(x * x + y * y);\n let pitch = radToDeg(Math.atan2(z, forward));\n if (pitch < 0) {\n pitch += 360;\n }\n\n return { x: -pitch, y: yaw, z: 0 };\n}\n","// Extracted from full/client/anorms.h\nexport const ANORMS: [number, number, number][] = [\n [-0.525731, 0.000000, 0.850651],\n [-0.442863, 0.238856, 0.864188],\n [-0.295242, 0.000000, 0.955423],\n [-0.309017, 0.500000, 0.809017],\n [-0.162460, 0.262866, 0.951056],\n [0.000000, 0.000000, 1.000000],\n [0.000000, 0.850651, 0.525731],\n [-0.147621, 0.716567, 0.681718],\n [0.147621, 0.716567, 0.681718],\n [0.000000, 0.525731, 0.850651],\n [0.309017, 0.500000, 0.809017],\n [0.525731, 0.000000, 0.850651],\n [0.295242, 0.000000, 0.955423],\n [0.442863, 0.238856, 0.864188],\n [0.162460, 0.262866, 0.951056],\n [-0.681718, 0.147621, 0.716567],\n [-0.809017, 0.309017, 0.500000],\n [-0.587785, 0.425325, 0.688191],\n [-0.850651, 0.525731, 0.000000],\n [-0.864188, 0.442863, 0.238856],\n [-0.716567, 0.681718, 0.147621],\n [-0.688191, 0.587785, 0.425325],\n [-0.500000, 0.809017, 0.309017],\n [-0.238856, 0.864188, 0.442863],\n [-0.425325, 0.688191, 0.587785],\n [-0.716567, 0.681718, -0.147621],\n [-0.500000, 0.809017, -0.309017],\n [-0.525731, 0.850651, 0.000000],\n [0.000000, 0.850651, -0.525731],\n [-0.238856, 0.864188, -0.442863],\n [0.000000, 0.955423, -0.295242],\n [-0.262866, 0.951056, -0.162460],\n [0.000000, 1.000000, 0.000000],\n [0.000000, 0.955423, 0.295242],\n [-0.262866, 0.951056, 0.162460],\n [0.238856, 0.864188, 0.442863],\n [0.262866, 0.951056, 0.162460],\n [0.500000, 0.809017, 0.309017],\n [0.238856, 0.864188, -0.442863],\n [0.262866, 0.951056, -0.162460],\n [0.500000, 0.809017, -0.309017],\n [0.850651, 0.525731, 0.000000],\n [0.716567, 0.681718, 0.147621],\n [0.716567, 0.681718, -0.147621],\n [0.525731, 0.850651, 0.000000],\n [0.425325, 0.688191, 0.587785],\n [0.864188, 0.442863, 0.238856],\n [0.688191, 0.587785, 0.425325],\n [0.809017, 0.309017, 0.500000],\n [0.681718, 0.147621, 0.716567],\n [0.587785, 0.425325, 0.688191],\n [0.955423, 0.295242, 0.000000],\n [1.000000, 0.000000, 0.000000],\n [0.951056, 0.162460, 0.262866],\n [0.850651, -0.525731, 0.000000],\n [0.955423, -0.295242, 0.000000],\n [0.864188, -0.442863, 0.238856],\n [0.951056, -0.162460, 0.262866],\n [0.809017, -0.309017, 0.500000],\n [0.681718, -0.147621, 0.716567],\n [0.850651, 0.000000, 0.525731],\n [0.864188, 0.442863, -0.238856],\n [0.809017, 0.309017, -0.500000],\n [0.951056, 0.162460, -0.262866],\n [0.525731, 0.000000, -0.850651],\n [0.681718, 0.147621, -0.716567],\n [0.681718, -0.147621, -0.716567],\n [0.850651, 0.000000, -0.525731],\n [0.809017, -0.309017, -0.500000],\n [0.864188, -0.442863, -0.238856],\n [0.951056, -0.162460, -0.262866],\n [0.147621, 0.716567, -0.681718],\n [0.309017, 0.500000, -0.809017],\n [0.425325, 0.688191, -0.587785],\n [0.442863, 0.238856, -0.864188],\n [0.587785, 0.425325, -0.688191],\n [0.688191, 0.587785, -0.425325],\n [-0.147621, 0.716567, -0.681718],\n [-0.309017, 0.500000, -0.809017],\n [0.000000, 0.525731, -0.850651],\n [-0.525731, 0.000000, -0.850651],\n [-0.442863, 0.238856, -0.864188],\n [-0.295242, 0.000000, -0.955423],\n [-0.162460, 0.262866, -0.951056],\n [0.000000, 0.000000, -1.000000],\n [0.295242, 0.000000, -0.955423],\n [0.162460, 0.262866, -0.951056],\n [-0.442863, -0.238856, -0.864188],\n [-0.309017, -0.500000, -0.809017],\n [-0.162460, -0.262866, -0.951056],\n [0.000000, -0.850651, -0.525731],\n [-0.147621, -0.716567, -0.681718],\n [0.147621, -0.716567, -0.681718],\n [0.000000, -0.525731, -0.850651],\n [0.309017, -0.500000, -0.809017],\n [0.442863, -0.238856, -0.864188],\n [0.162460, -0.262866, -0.951056],\n [0.238856, -0.864188, -0.442863],\n [0.500000, -0.809017, -0.309017],\n [0.425325, -0.688191, -0.587785],\n [0.716567, -0.681718, -0.147621],\n [0.688191, -0.587785, -0.425325],\n [0.587785, -0.425325, -0.688191],\n [0.000000, -0.955423, -0.295242],\n [0.000000, -1.000000, 0.000000],\n [0.262866, -0.951056, -0.162460],\n [0.000000, -0.850651, 0.525731],\n [0.000000, -0.955423, 0.295242],\n [0.238856, -0.864188, 0.442863],\n [0.262866, -0.951056, 0.162460],\n [0.500000, -0.809017, 0.309017],\n [0.716567, -0.681718, 0.147621],\n [0.525731, -0.850651, 0.000000],\n [-0.238856, -0.864188, -0.442863],\n [-0.500000, -0.809017, -0.309017],\n [-0.262866, -0.951056, -0.162460],\n [-0.850651, -0.525731, 0.000000],\n [-0.716567, -0.681718, -0.147621],\n [-0.716567, -0.681718, 0.147621],\n [-0.525731, -0.850651, 0.000000],\n [-0.500000, -0.809017, 0.309017],\n [-0.238856, -0.864188, 0.442863],\n [-0.262866, -0.951056, 0.162460],\n [-0.864188, -0.442863, 0.238856],\n [-0.809017, -0.309017, 0.500000],\n [-0.688191, -0.587785, 0.425325],\n [-0.681718, -0.147621, 0.716567],\n [-0.442863, -0.238856, 0.864188],\n [-0.587785, -0.425325, 0.688191],\n [-0.309017, -0.500000, 0.809017],\n [-0.147621, -0.716567, 0.681718],\n [-0.425325, -0.688191, 0.587785],\n [-0.162460, -0.262866, 0.951056],\n [0.442863, -0.238856, 0.864188],\n [0.162460, -0.262866, 0.951056],\n [0.309017, -0.500000, 0.809017],\n [0.147621, -0.716567, 0.681718],\n [0.000000, -0.525731, 0.850651],\n [0.425325, -0.688191, 0.587785],\n [0.587785, -0.425325, 0.688191],\n [0.688191, -0.587785, 0.425325],\n [-0.955423, 0.295242, 0.000000],\n [-0.951056, 0.162460, 0.262866],\n [-1.000000, 0.000000, 0.000000],\n [-0.850651, 0.000000, 0.525731],\n [-0.955423, -0.295242, 0.000000],\n [-0.951056, -0.162460, 0.262866],\n [-0.864188, 0.442863, -0.238856],\n [-0.951056, 0.162460, -0.262866],\n [-0.809017, 0.309017, -0.500000],\n [-0.864188, -0.442863, -0.238856],\n [-0.951056, -0.162460, -0.262866],\n [-0.809017, -0.309017, -0.500000],\n [-0.681718, 0.147621, -0.716567],\n [-0.681718, -0.147621, -0.716567],\n [-0.850651, 0.000000, -0.525731],\n [-0.688191, 0.587785, -0.425325],\n [-0.587785, 0.425325, -0.688191],\n [-0.425325, 0.688191, -0.587785],\n [-0.425325, -0.688191, -0.587785],\n [-0.587785, -0.425325, -0.688191],\n [-0.688191, -0.587785, -0.425325]\n];\n","export type Color4 = [number, number, number, number];\n\n/**\n * TypeScript port of G_AddBlend from rerelease q_std.h.\n *\n * Given an incoming RGBA color and an existing blend color, computes the new\n * blended color where alpha is accumulated and RGB is mixed proportionally\n * to the previous vs. new alpha contribution.\n *\n * This function is pure and does not mutate its inputs.\n */\nexport function addBlendColor(\n r: number,\n g: number,\n b: number,\n a: number,\n current: Color4,\n): Color4 {\n if (a <= 0) {\n return current;\n }\n\n const oldR = current[0];\n const oldG = current[1];\n const oldB = current[2];\n const oldA = current[3];\n\n const a2 = oldA + (1 - oldA) * a;\n\n if (a2 <= 0) {\n return [0, 0, 0, 0];\n }\n\n const a3 = oldA / a2;\n\n const newR = oldR * a3 + r * (1 - a3);\n const newG = oldG * a3 + g * (1 - a3);\n const newB = oldB * a3 + b * (1 - a3);\n\n return [newR, newG, newB, a2];\n}\n\n","const STATE_SIZE = 624;\nconst MIDDLE_WORD = 397;\nconst MATRIX_A = 0x9908b0df;\nconst UPPER_MASK = 0x80000000;\nconst LOWER_MASK = 0x7fffffff;\nconst TWO_POW_32 = 0x100000000;\n\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\n\n/**\n * Minimal MT19937 implementation mirroring the rerelease's std::mt19937 usage in g_local.h.\n * The generator outputs deterministic unsigned 32-bit integers which drive the\n * higher-level helpers such as frandom/crandom/irandom.\n */\nexport class MersenneTwister19937 {\n private state = new Uint32Array(STATE_SIZE);\n private index = STATE_SIZE;\n\n constructor(seed = 5489) {\n this.seed(seed);\n }\n\n seed(seed: number): void {\n this.state[0] = seed >>> 0;\n for (let i = 1; i < STATE_SIZE; i++) {\n const prev = this.state[i - 1] ^ (this.state[i - 1] >>> 30);\n const next = Math.imul(prev >>> 0, 1812433253) + i;\n this.state[i] = next >>> 0;\n }\n this.index = STATE_SIZE;\n }\n\n nextUint32(): number {\n if (this.index >= STATE_SIZE) {\n this.twist();\n }\n\n let y = this.state[this.index++];\n y ^= y >>> 11;\n y ^= (y << 7) & 0x9d2c5680;\n y ^= (y << 15) & 0xefc60000;\n y ^= y >>> 18;\n return y >>> 0;\n }\n\n private twist(): void {\n for (let i = 0; i < STATE_SIZE; i++) {\n const y = (this.state[i] & UPPER_MASK) | (this.state[(i + 1) % STATE_SIZE] & LOWER_MASK);\n let next = this.state[(i + MIDDLE_WORD) % STATE_SIZE] ^ (y >>> 1);\n if ((y & 1) !== 0) {\n next ^= MATRIX_A;\n }\n this.state[i] = next >>> 0;\n }\n this.index = 0;\n }\n\n getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\n}\n\n/**\n * Deterministic helper mirroring the random helpers defined in rerelease g_local.h.\n */\nexport class RandomGenerator {\n private readonly mt: MersenneTwister19937;\n\n constructor(options: RandomGeneratorOptions = {}) {\n this.mt = new MersenneTwister19937(options.seed);\n }\n\n seed(seed: number): void {\n this.mt.seed(seed);\n }\n\n /** Uniform float in [0, 1). */\n frandom(): number {\n return this.mt.nextUint32() / TWO_POW_32;\n }\n\n /** Uniform float in [min, max). */\n frandomRange(minInclusive: number, maxExclusive: number): number {\n return minInclusive + (maxExclusive - minInclusive) * this.frandom();\n }\n\n /** Uniform float in [0, max). */\n frandomMax(maxExclusive: number): number {\n return this.frandomRange(0, maxExclusive);\n }\n\n /** Uniform float in [-1, 1). */\n crandom(): number {\n return this.frandomRange(-1, 1);\n }\n\n /** Uniform float in (-1, 1). */\n crandomOpen(): number {\n const epsilon = Number.EPSILON;\n return this.frandomRange(-1 + epsilon, 1);\n }\n\n /** Raw uint32 sample. */\n irandomUint32(): number {\n return this.mt.nextUint32();\n }\n\n /** Uniform integer in [min, max). */\n irandomRange(minInclusive: number, maxExclusive: number): number {\n if (maxExclusive - minInclusive <= 1) {\n return minInclusive;\n }\n\n const span = maxExclusive - minInclusive;\n const limit = TWO_POW_32 - (TWO_POW_32 % span);\n let sample: number;\n do {\n sample = this.mt.nextUint32();\n } while (sample >= limit);\n return minInclusive + (sample % span);\n }\n\n /** Uniform integer in [0, max). */\n irandom(maxExclusive: number): number {\n if (maxExclusive <= 0) {\n return 0;\n }\n return this.irandomRange(0, maxExclusive);\n }\n\n /** Uniform time in milliseconds [min, max). */\n randomTimeRange(minMs: number, maxMs: number): number {\n if (maxMs <= minMs) {\n return minMs;\n }\n return this.irandomRange(minMs, maxMs);\n }\n\n /** Uniform time in milliseconds [0, max). */\n randomTime(maxMs: number): number {\n return this.irandom(maxMs);\n }\n\n randomIndex<T extends { length: number }>(container: T): number {\n return this.irandom(container.length);\n }\n\n getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\n }\n}\n\nexport function createRandomGenerator(options?: RandomGeneratorOptions): RandomGenerator {\n return new RandomGenerator(options);\n}\n","import { Vec3 } from './vec3.js';\n\nexport type Mat4 = Float32Array;\n\nexport function createMat4Identity(): Mat4 {\n return new Float32Array([\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1,\n ]);\n}\n\nexport function multiplyMat4(a: Float32Array, b: Float32Array): Mat4 {\n const out = new Float32Array(16);\n for (let row = 0; row < 4; row += 1) {\n for (let col = 0; col < 4; col += 1) {\n out[col * 4 + row] =\n a[0 * 4 + row] * b[col * 4 + 0] +\n a[1 * 4 + row] * b[col * 4 + 1] +\n a[2 * 4 + row] * b[col * 4 + 2] +\n a[3 * 4 + row] * b[col * 4 + 3];\n }\n }\n return out;\n}\n\nexport function transformPointMat4(mat: Float32Array, point: Vec3): Vec3 {\n const x = point.x;\n const y = point.y;\n const z = point.z;\n return {\n x: mat[0] * x + mat[4] * y + mat[8] * z + mat[12],\n y: mat[1] * x + mat[5] * y + mat[9] * z + mat[13],\n z: mat[2] * x + mat[6] * y + mat[10] * z + mat[14],\n };\n}\n\nexport function mat4FromBasis(origin: Vec3, axis: readonly [Vec3, Vec3, Vec3]): Mat4 {\n const out = createMat4Identity();\n out[0] = axis[0].x;\n out[1] = axis[0].y;\n out[2] = axis[0].z;\n\n out[4] = axis[1].x;\n out[5] = axis[1].y;\n out[6] = axis[1].z;\n\n out[8] = axis[2].x;\n out[9] = axis[2].y;\n out[10] = axis[2].z;\n\n out[12] = origin.x;\n out[13] = origin.y;\n out[14] = origin.z;\n\n return out;\n}\n","/**\n * Bitflag constants mirroring the Quake II rerelease `contents_t` and\n * `surfflags_t` enumerations from `game.h`. The helpers here operate purely on\n * numeric bitmasks so both the authoritative game simulation and the client can\n * share the same semantic checks.\n */\nexport type ContentsFlag = number;\nexport type SurfaceFlag = number;\n\nexport const CONTENTS_NONE: ContentsFlag = 0;\nexport const CONTENTS_SOLID: ContentsFlag = 1 << 0;\nexport const CONTENTS_WINDOW: ContentsFlag = 1 << 1;\nexport const CONTENTS_AUX: ContentsFlag = 1 << 2;\nexport const CONTENTS_LAVA: ContentsFlag = 1 << 3;\nexport const CONTENTS_SLIME: ContentsFlag = 1 << 4;\nexport const CONTENTS_WATER: ContentsFlag = 1 << 5;\nexport const CONTENTS_MIST: ContentsFlag = 1 << 6;\nexport const CONTENTS_TRIGGER: ContentsFlag = 0x40000000;\nexport const CONTENTS_NO_WATERJUMP: ContentsFlag = 1 << 13;\nexport const CONTENTS_PROJECTILECLIP: ContentsFlag = 1 << 14;\nexport const CONTENTS_AREAPORTAL: ContentsFlag = 1 << 15;\nexport const CONTENTS_PLAYERCLIP: ContentsFlag = 1 << 16;\nexport const CONTENTS_MONSTERCLIP: ContentsFlag = 1 << 17;\nexport const CONTENTS_CURRENT_0: ContentsFlag = 1 << 18;\nexport const CONTENTS_CURRENT_90: ContentsFlag = 1 << 19;\nexport const CONTENTS_CURRENT_180: ContentsFlag = 1 << 20;\nexport const CONTENTS_CURRENT_270: ContentsFlag = 1 << 21;\nexport const CONTENTS_CURRENT_UP: ContentsFlag = 1 << 22;\nexport const CONTENTS_CURRENT_DOWN: ContentsFlag = 1 << 23;\nexport const CONTENTS_ORIGIN: ContentsFlag = 1 << 24;\nexport const CONTENTS_MONSTER: ContentsFlag = 1 << 25;\nexport const CONTENTS_DEADMONSTER: ContentsFlag = 1 << 26;\nexport const CONTENTS_DETAIL: ContentsFlag = 1 << 27;\nexport const CONTENTS_TRANSLUCENT: ContentsFlag = 1 << 28;\nexport const CONTENTS_LADDER: ContentsFlag = 1 << 29;\nexport const CONTENTS_PLAYER: ContentsFlag = 1 << 30;\nexport const CONTENTS_PROJECTILE: ContentsFlag = 1 << 31;\n\nexport const LAST_VISIBLE_CONTENTS: ContentsFlag = CONTENTS_MIST;\n\nexport const SURF_NONE: SurfaceFlag = 0;\nexport const SURF_LIGHT: SurfaceFlag = 1 << 0;\nexport const SURF_SLICK: SurfaceFlag = 1 << 1;\nexport const SURF_SKY: SurfaceFlag = 1 << 2;\nexport const SURF_WARP: SurfaceFlag = 1 << 3;\nexport const SURF_TRANS33: SurfaceFlag = 1 << 4;\nexport const SURF_TRANS66: SurfaceFlag = 1 << 5;\nexport const SURF_FLOWING: SurfaceFlag = 1 << 6;\nexport const SURF_NODRAW: SurfaceFlag = 1 << 7;\nexport const SURF_ALPHATEST: SurfaceFlag = 1 << 25;\nexport const SURF_N64_UV: SurfaceFlag = 1 << 28;\nexport const SURF_N64_SCROLL_X: SurfaceFlag = 1 << 29;\nexport const SURF_N64_SCROLL_Y: SurfaceFlag = 1 << 30;\nexport const SURF_N64_SCROLL_FLIP: SurfaceFlag = 1 << 31;\n\nexport const MASK_ALL: ContentsFlag = 0xffffffff;\nexport const MASK_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_PLAYERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_DEADSOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_MONSTERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_WATER: ContentsFlag = CONTENTS_WATER | CONTENTS_LAVA | CONTENTS_SLIME;\nexport const MASK_OPAQUE: ContentsFlag = CONTENTS_SOLID | CONTENTS_SLIME | CONTENTS_LAVA;\nexport const MASK_SHOT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_PLAYER | CONTENTS_WINDOW | CONTENTS_DEADMONSTER;\nexport const MASK_CURRENT: ContentsFlag =\n CONTENTS_CURRENT_0 |\n CONTENTS_CURRENT_90 |\n CONTENTS_CURRENT_180 |\n CONTENTS_CURRENT_270 |\n CONTENTS_CURRENT_UP |\n CONTENTS_CURRENT_DOWN;\nexport const MASK_BLOCK_SIGHT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_LADDER_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_WALK_NAV_SOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTERCLIP;\nexport const MASK_PROJECTILE: ContentsFlag = MASK_SHOT | CONTENTS_PROJECTILECLIP;\n\nexport function hasAllContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) === flags;\n}\n\nexport function hasAnyContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) !== 0;\n}\n\nexport function addContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask | flags;\n}\n\nexport function removeContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask & ~flags;\n}\n\nexport function hasSurfaceFlags(surface: SurfaceFlag, flags: SurfaceFlag): boolean {\n return (surface & flags) === flags;\n}\n\nexport function combineSurfaceFlags(...flags: SurfaceFlag[]): SurfaceFlag {\n let mask = SURF_NONE;\n for (const flag of flags) {\n mask |= flag;\n }\n return mask;\n}\n","import type { Vec3 } from '../math/vec3.js';\n\nexport const AREA_DEPTH = 4;\nexport const WORLD_SIZE = 8192; // Standard Q2 world extent\n\nexport interface SpatialNode {\n axis: number; // 0=X, 1=Y, -1=Leaf\n dist: number;\n children: [SpatialNode, SpatialNode] | null;\n items: Set<number>;\n}\n\nexport function createSpatialTree(\n depth = 0,\n mins: Vec3 = { x: -WORLD_SIZE, y: -WORLD_SIZE, z: -WORLD_SIZE },\n maxs: Vec3 = { x: WORLD_SIZE, y: WORLD_SIZE, z: WORLD_SIZE }\n): SpatialNode {\n if (depth >= AREA_DEPTH) {\n return {\n axis: -1,\n dist: 0,\n children: null,\n items: new Set(),\n };\n }\n\n const axis = depth % 2; // Alternates X (0) and Y (1)\n const dist = 0.5 * (axis === 0 ? mins.x + maxs.x : mins.y + maxs.y);\n\n const mins1 = { ...mins };\n const maxs1 = { ...maxs };\n const mins2 = { ...mins };\n const maxs2 = { ...maxs };\n\n if (axis === 0) {\n maxs1.x = dist;\n mins2.x = dist;\n } else {\n maxs1.y = dist;\n mins2.y = dist;\n }\n\n const child1 = createSpatialTree(depth + 1, mins1, maxs1);\n const child2 = createSpatialTree(depth + 1, mins2, maxs2);\n\n return {\n axis,\n dist,\n children: [child1, child2],\n items: new Set(),\n };\n}\n\nexport function linkEntityToSpatialTree(\n node: SpatialNode,\n id: number,\n absmin: Vec3,\n absmax: Vec3\n): SpatialNode {\n let current = node;\n\n while (current.axis !== -1 && current.children) {\n const axis = current.axis;\n const dist = current.dist;\n\n const min = axis === 0 ? absmin.x : absmin.y;\n const max = axis === 0 ? absmax.x : absmax.y;\n\n if (min > dist) {\n current = current.children[1];\n } else if (max < dist) {\n current = current.children[0];\n } else {\n break; // Straddles the plane, resides in this node\n }\n }\n\n current.items.add(id);\n return current;\n}\n\nexport function querySpatialTree(\n node: SpatialNode,\n absmin: Vec3,\n absmax: Vec3,\n results: Set<number>\n): void {\n // Add all items in the current node (because if we are here, we overlap this node's space\n // and straddling items definitely overlap us or are at least in the parent region)\n // Actually, strictly speaking, items in this node straddle the split plane.\n // Since we are traversing down, we are within the node's volume.\n // The items in this node are those that couldn't be pushed further down.\n // So we must check them.\n\n // NOTE: This collects candidates. Precise collision check still needed.\n for (const id of node.items) {\n results.add(id);\n }\n\n if (node.axis === -1 || !node.children) {\n return;\n }\n\n const axis = node.axis;\n const dist = node.dist;\n\n const min = axis === 0 ? absmin.x : absmin.y;\n const max = axis === 0 ? absmax.x : absmax.y;\n\n if (max > dist) {\n querySpatialTree(node.children[1], absmin, absmax, results);\n }\n if (min < dist) {\n querySpatialTree(node.children[0], absmin, absmax, results);\n }\n}\n","import { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } from '../math/vec3.js';\nimport { createSpatialTree, linkEntityToSpatialTree, querySpatialTree, SpatialNode } from './spatial.js';\n\nexport interface CollisionPlane {\n normal: Vec3;\n dist: number;\n type: number;\n signbits: number;\n}\n\nexport interface CollisionBrushSide {\n plane: CollisionPlane;\n surfaceFlags: number;\n}\n\nexport interface CollisionBrush {\n contents: number;\n sides: CollisionBrushSide[];\n checkcount?: number;\n}\n\nexport interface CollisionLeaf {\n contents: number;\n cluster: number;\n area: number;\n firstLeafBrush: number;\n numLeafBrushes: number;\n}\n\nexport interface CollisionNode {\n plane: CollisionPlane;\n children: [number, number];\n}\n\nexport interface CollisionBmodel {\n mins: Vec3;\n maxs: Vec3;\n origin: Vec3;\n headnode: number;\n}\n\nexport interface CollisionModel {\n planes: CollisionPlane[];\n nodes: CollisionNode[];\n leaves: CollisionLeaf[];\n brushes: CollisionBrush[];\n leafBrushes: number[];\n bmodels: CollisionBmodel[];\n visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\n}\n\nexport interface CollisionLumpData {\n planes: Array<{ normal: Vec3; dist: number; type: number }>;\n nodes: Array<{ planenum: number; children: [number, number] }>;\n leaves: Array<{ contents: number; cluster: number; area: number; firstLeafBrush: number; numLeafBrushes: number }>;\n brushes: Array<{ firstSide: number; numSides: number; contents: number }>;\n brushSides: Array<{ planenum: number; surfaceFlags: number }>;\n leafBrushes: number[];\n bmodels: Array<{ mins: Vec3; maxs: Vec3; origin: Vec3; headnode: number }>;\n visibility?: CollisionVisibility;\n}\n\nexport interface TraceResult {\n fraction: number;\n plane: CollisionPlane | null;\n contents: number;\n surfaceFlags: number;\n startsolid: boolean;\n allsolid: boolean;\n}\n\nexport interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\n contents?: number;\n surfaceFlags?: number;\n startsolid: boolean;\n allsolid: boolean;\n}\n\nexport enum PlaneSide {\n FRONT = 1,\n BACK = 2,\n CROSS = 3,\n}\n\nexport interface TraceDebugInfo {\n nodesTraversed: number;\n leafsReached: number;\n brushesTested: number;\n}\n\nexport let traceDebugInfo: TraceDebugInfo | null = null;\n\nexport function enableTraceDebug(): void {\n traceDebugInfo = { nodesTraversed: 0, leafsReached: 0, brushesTested: 0 };\n // console.log('DEBUG: Trace debug enabled');\n}\n\nexport function disableTraceDebug(): void {\n traceDebugInfo = null;\n}\n\nexport const DIST_EPSILON = 0.03125;\n\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\n\nexport function buildCollisionModel(lumps: CollisionLumpData): CollisionModel {\n const planes: CollisionPlane[] = lumps.planes.map((plane) => ({\n ...plane,\n signbits: computePlaneSignBits(plane.normal),\n }));\n\n const nodes: CollisionNode[] = lumps.nodes.map((node) => ({\n plane: planes[node.planenum],\n children: node.children,\n }));\n\n const brushes: CollisionBrush[] = lumps.brushes.map((brush) => {\n const sides = lumps.brushSides.slice(brush.firstSide, brush.firstSide + brush.numSides).map((side) => ({\n plane: planes[side.planenum],\n surfaceFlags: side.surfaceFlags,\n }));\n\n return {\n contents: brush.contents,\n sides,\n checkcount: 0,\n };\n });\n\n const leaves: CollisionLeaf[] = lumps.leaves.map((leaf) => ({\n contents: leaf.contents,\n cluster: leaf.cluster,\n area: leaf.area,\n firstLeafBrush: leaf.firstLeafBrush,\n numLeafBrushes: leaf.numLeafBrushes,\n }));\n\n const bmodels: CollisionBmodel[] = lumps.bmodels.map((model) => ({\n mins: model.mins,\n maxs: model.maxs,\n origin: model.origin,\n headnode: model.headnode,\n }));\n\n return {\n planes,\n nodes,\n leaves,\n brushes,\n leafBrushes: lumps.leafBrushes,\n bmodels,\n visibility: lumps.visibility,\n };\n}\n\nexport function computePlaneSignBits(normal: Vec3): number {\n let bits = 0;\n if (normal.x < 0) bits |= 1;\n if (normal.y < 0) bits |= 2;\n if (normal.z < 0) bits |= 4;\n return bits;\n}\n\nexport function planeDistanceToPoint(plane: CollisionPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z - plane.dist;\n}\n\nexport function pointOnPlaneSide(plane: CollisionPlane, point: Vec3, epsilon = 0): PlaneSide.FRONT | PlaneSide.BACK | PlaneSide.CROSS {\n const dist = planeDistanceToPoint(plane, point);\n if (dist > epsilon) {\n return PlaneSide.FRONT;\n }\n if (dist < -epsilon) {\n return PlaneSide.BACK;\n }\n return PlaneSide.CROSS;\n}\n\nexport function boxOnPlaneSide(mins: Vec3, maxs: Vec3, plane: CollisionPlane, epsilon = 0): PlaneSide {\n let dist1: number;\n let dist2: number;\n\n switch (plane.signbits) {\n case 0:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 1:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 2:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 3:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 4:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 5:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 6:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n default:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n }\n\n let sides = 0;\n if (dist1 - plane.dist >= -epsilon) sides = PlaneSide.FRONT;\n if (dist2 - plane.dist <= epsilon) sides |= PlaneSide.BACK;\n return sides as PlaneSide;\n}\n\nexport function pointInsideBrush(point: Vec3, brush: CollisionBrush, epsilon = DIST_EPSILON): boolean {\n for (const side of brush.sides) {\n const dist = planeDistanceToPoint(side.plane, point);\n if (dist > epsilon) {\n return false;\n }\n }\n return true;\n}\n\nexport interface BoxBrushTestResult {\n startsolid: boolean;\n allsolid: boolean;\n contents: number;\n}\n\nexport function testBoxInBrush(origin: Vec3, mins: Vec3, maxs: Vec3, brush: CollisionBrush): BoxBrushTestResult {\n for (const side of brush.sides) {\n const offset = side.plane.normal.x * (side.plane.normal.x < 0 ? maxs.x : mins.x) +\n side.plane.normal.y * (side.plane.normal.y < 0 ? maxs.y : mins.y) +\n side.plane.normal.z * (side.plane.normal.z < 0 ? maxs.z : mins.z);\n\n const dist = side.plane.dist - offset;\n const d1 = origin.x * side.plane.normal.x + origin.y * side.plane.normal.y + origin.z * side.plane.normal.z - dist;\n\n if (d1 > 0) {\n return { startsolid: false, allsolid: false, contents: 0 };\n }\n }\n\n return { startsolid: true, allsolid: true, contents: brush.contents };\n}\n\nexport interface ClipBoxParams {\n start: Vec3;\n end: Vec3;\n mins: Vec3;\n maxs: Vec3;\n brush: CollisionBrush;\n trace: TraceResult;\n}\n\n/**\n * Clips a movement box against a brush using the Liang-Barsky algorithm.\n *\n * This function determines if and where the swept box (from start to end) intersects the brush.\n * It works by clipping the movement line segment against the infinite planes defined by the brush sides.\n *\n * Algorithm Overview (Liang-Barsky):\n * The movement is treated as a parameterized line P(t) = Start + t * (End - Start), for t in [0, 1].\n * We maintain an interval [enterfrac, leavefrac] (initially [-1, 1]) representing the portion of the\n * line that is potentially inside the brush.\n * For each plane:\n * 1. We determine the distance of Start (d1) and End (d2) from the plane.\n * - For box traces, planes are expanded by the box extents, effectively treating the box as a point.\n * 2. If both points are in front (outside), the line is outside the brush.\n * 3. If the line crosses the plane:\n * - If entering (d1 > d2), we update `enterfrac` (max of entry times).\n * - If leaving (d1 < d2), we update `leavefrac` (min of exit times).\n * 4. If at any point enterfrac > leavefrac, the line misses the brush.\n *\n * @see CM_ClipBoxToBrush in qcommon/cm_trace.c:145-220\n *\n * @param params ClipBoxParams containing start/end vectors, box mins/maxs, target brush, and trace result to update.\n */\nexport function clipBoxToBrush({ start, end, mins, maxs, brush, trace }: ClipBoxParams): void {\n if (brush.sides.length === 0) return;\n\n const isPoint = mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n\n // enterfrac: The fraction of movement where the box FIRST fully enters the brush volume (intersection start).\n // leavefrac: The fraction of movement where the box STARTS to leave the brush volume (intersection end).\n // Initialized to -1 and 1 to cover the full potential range + buffers.\n let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false; // True if the end point is outside at least one plane (not trapped in brush)\n let startout = false; // True if the start point is outside at least one plane (not starting stuck)\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\n\n // Expand the plane by the box extents to perform a point-plane test.\n // This reduces the AABB sweep vs convex brush problem to a line segment vs expanded planes problem.\n if (!isPoint) {\n const ofsX = plane.normal.x < 0 ? maxs.x : mins.x;\n const ofsY = plane.normal.y < 0 ? maxs.y : mins.y;\n const ofsZ = plane.normal.z < 0 ? maxs.z : mins.z;\n dist -= plane.normal.x * ofsX + plane.normal.y * ofsY + plane.normal.z * ofsZ;\n }\n\n // d1: Distance of start point from the (expanded) plane. Positive = in front (outside).\n // d2: Distance of end point from the (expanded) plane.\n const d1 = start.x * plane.normal.x + start.y * plane.normal.y + start.z * plane.normal.z - dist;\n const d2 = end.x * plane.normal.x + end.y * plane.normal.y + end.z * plane.normal.z - dist;\n\n if (d2 > 0) getout = true;\n if (d1 > 0) startout = true;\n\n // Case 1: Entirely outside this plane.\n // Since brushes are convex intersections of half-spaces (defined by planes pointing OUT),\n // being in front of ANY plane means being outside the brush.\n // The d2 >= d1 check handles the case where the line is parallel or moving away from the plane.\n if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n // Case 2: Entirely inside this plane (back side).\n // Does not restrict the entry/exit interval further than other planes might.\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n // Case 3: Line intersects the plane.\n // d1 > d2 means we are moving from Front (outside) to Back (inside) -> Entering.\n if (d1 > d2) {\n // Calculate intersection fraction f.\n // DIST_EPSILON is subtracted to ensure we stop slightly *before* the plane,\n // preventing the object from getting stuck in the next frame due to float precision.\n const f = (d1 - DIST_EPSILON) / (d1 - d2);\n if (f > enterfrac) {\n enterfrac = f;\n clipplane = plane;\n leadside = side;\n }\n } else {\n // Moving from Back (inside) to Front (outside) -> Leaving.\n // DIST_EPSILON is added to push the exit point slightly further out (or in depending on perspective),\n // effectively narrowing the \"inside\" interval.\n const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n // If we never started outside any plane, we started inside the brush.\n if (!startout) {\n trace.startsolid = true;\n // If we also never got out of any plane (meaning we stayed behind all planes),\n // then the entire movement is inside the brush (allsolid).\n if (!getout) {\n trace.allsolid = true;\n }\n trace.fraction = 0;\n return;\n }\n\n // If the entry fraction is less than the exit fraction, we have a valid intersection interval.\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n if (enterfrac < 0) enterfrac = 0;\n trace.fraction = enterfrac;\n trace.plane = clipplane;\n trace.contents = brush.contents;\n trace.surfaceFlags = leadside?.surfaceFlags ?? 0;\n }\n}\n\nexport function createDefaultTrace(): TraceResult {\n return {\n fraction: 1,\n plane: null,\n contents: 0,\n surfaceFlags: 0,\n startsolid: false,\n allsolid: false,\n };\n}\n\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\n/**\n * Recursively checks a hull sweep against a BSP tree.\n * Implements a Liang-Barsky like clipping algorithm against the BSP planes.\n *\n * Based on CM_RecursiveHullCheck in qcommon/cm_trace.c.\n */\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n // If we've already hit something earlier in the trace than where we are starting this check,\n // we can stop.\n if (trace.fraction <= startFraction) {\n return;\n }\n\n // If we reached a leaf, check the brushes in it.\n if (nodeIndex < 0) {\n if (traceDebugInfo) {\n traceDebugInfo.leafsReached++;\n }\n\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n // Optimization: Avoid checking the same brush multiple times in a single trace.\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n if (traceDebugInfo) {\n traceDebugInfo.brushesTested++;\n }\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n if (traceDebugInfo) {\n traceDebugInfo.nodesTraversed++;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n\n // Calculate the distance from the plane to the box's nearest corner.\n // This effectively expands the plane by the box extents.\n // Use absolute value of offset like original C code (full/qcommon/cmodel.c:1269-1271).\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start);\n const endDist = planeDistanceToPoint(plane, end);\n\n // If both start and end points are in front of the plane (including offset),\n // we only need to check the front child.\n if (startDist >= offset && endDist >= offset) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n // If both start and end points are behind the plane (including offset),\n // we only need to check the back child.\n if (startDist < -offset && endDist < -offset) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n // The segment straddles the plane. We need to split the segment and recurse down both sides.\n // Put the crosspoint DIST_EPSILON pixels on the near side to avoid precision issues.\n // See full/qcommon/cmodel.c:1293-1313 (CM_RecursiveHullCheck)\n // fraction1 (frac) is used for \"move up to node\" - the near-side recursion\n // fraction2 (frac2) is used for \"go past the node\" - the far-side recursion\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1, fraction2;\n\n if (startDist < endDist) {\n side = 1;\n fraction2 = (startDist + offset + DIST_EPSILON) * idist;\n fraction1 = (startDist - offset + DIST_EPSILON) * idist;\n } else {\n side = 0;\n fraction2 = (startDist - offset - DIST_EPSILON) * idist;\n fraction1 = (startDist + offset + DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n // Recurse down the near side\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n // Optimisation: if we hit something closer than the split point, we don't need to check the far side\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n // Recurse down the far side\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n if (traceDebugInfo) {\n traceDebugInfo.leafsReached++;\n }\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): boolean {\n return !(\n a.mins.x > b.maxs.x ||\n a.maxs.x < b.mins.x ||\n a.mins.y > b.maxs.y ||\n a.maxs.y < b.mins.y ||\n a.mins.z > b.maxs.z ||\n a.maxs.z < b.mins.z\n );\n}\n\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n private readonly entityNodes = new Map<number, SpatialNode>();\n private readonly rootNode = createSpatialTree();\n\n link(entity: CollisionEntityLink): void {\n const state = makeEntityState(entity);\n this.entities.set(entity.id, state);\n\n // Update spatial index\n const existingNode = this.entityNodes.get(entity.id);\n if (existingNode) {\n existingNode.items.delete(entity.id);\n }\n\n const newNode = linkEntityToSpatialTree(\n this.rootNode,\n entity.id,\n state.bounds.mins,\n state.bounds.maxs\n );\n this.entityNodes.set(entity.id, newNode);\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n\n const node = this.entityNodes.get(entityId);\n if (node) {\n node.items.delete(entityId);\n this.entityNodes.delete(entityId);\n }\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n // Determine query bounds for spatial lookup\n const traceAbsMin = {\n x: Math.min(params.start.x, params.end.x) + mins.x,\n y: Math.min(params.start.y, params.end.y) + mins.y,\n z: Math.min(params.start.z, params.end.z) + mins.z,\n };\n const traceAbsMax = {\n x: Math.max(params.start.x, params.end.x) + maxs.x,\n y: Math.max(params.start.y, params.end.y) + maxs.y,\n z: Math.max(params.start.z, params.end.z) + maxs.z,\n };\n\n const candidates = new Set<number>();\n querySpatialTree(this.rootNode, traceAbsMin, traceAbsMax, candidates);\n\n for (const entityId of candidates) {\n if (entityId === passId) continue;\n\n const entity = this.entities.get(entityId);\n if (!entity) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n if (trace.startsolid || trace.allsolid || trace.fraction < bestTrace.fraction) {\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n const candidates = new Set<number>();\n querySpatialTree(this.rootNode, queryBounds.mins, queryBounds.maxs, candidates);\n\n for (const entityId of candidates) {\n const entity = this.entities.get(entityId);\n if (!entity) continue;\n\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\n }\n}\n","export const enum CvarFlags {\n None = 0,\n Archive = 1 << 0,\n UserInfo = 1 << 1,\n ServerInfo = 1 << 2,\n Latch = 1 << 3,\n Cheat = 1 << 4,\n}\n\nexport interface CvarDefinition {\n readonly name: string;\n readonly defaultValue: string;\n readonly description?: string;\n readonly flags?: CvarFlags;\n}\n","// Mirrors the Quake II rerelease configstring/index layout from `game.h`.\n// These constants intentionally track the numeric values used in the C++\n// game and client modules so the TypeScript engine/game/client layers can\n// share deterministic indices for precaches and HUD parsing.\n\nexport const MAX_STRING_CHARS = 1024;\nexport const MAX_STRING_TOKENS = 80;\nexport const MAX_TOKEN_CHARS = 512;\n\nexport const MAX_QPATH = 64;\nexport const MAX_OSPATH = 128;\n\nexport const MAX_CLIENTS = 256;\nexport const MAX_EDICTS = 8192;\nexport const MAX_LIGHTSTYLES = 256;\nexport const MAX_MODELS = 8192;\nexport const MAX_SOUNDS = 2048;\nexport const MAX_IMAGES = 512;\nexport const MAX_ITEMS = 256;\nexport const MAX_GENERAL = MAX_CLIENTS * 2;\nexport const MAX_SHADOW_LIGHTS = 256;\nexport const MAX_WHEEL_ITEMS = 32;\n\nexport const CS_MAX_STRING_LENGTH = 96;\nexport const CS_MAX_STRING_LENGTH_OLD = 64;\n\n// Enum-style numeric constants that mirror the C++ `configstrings` enum. Only\n// the explicitly numbered entries are re-stated here; everything else follows\n// sequentially to keep the arithmetic (e.g., CS_SOUNDS = CS_MODELS +\n// MAX_MODELS) intact.\nexport enum ConfigStringIndex {\n Name = 0,\n CdTrack = 1,\n Sky = 2,\n SkyAxis = 3,\n SkyRotate = 4,\n StatusBar = 5,\n\n // Matching bg_local.h:55-76\n HealthBarName = 55,\n CONFIG_N64_PHYSICS = 56,\n CONFIG_CTF_TEAMS = 57,\n CONFIG_COOP_RESPAWN_STRING = 58,\n Story = 54, // Arbitrarily placed in the gap for now\n\n AirAccel = 59,\n MaxClients = 60,\n MapChecksum = 61,\n\n Models = 62,\n Sounds = Models + MAX_MODELS,\n Images = Sounds + MAX_SOUNDS,\n Lights = Images + MAX_IMAGES,\n ShadowLights = Lights + MAX_LIGHTSTYLES,\n Items = ShadowLights + MAX_SHADOW_LIGHTS,\n Players = Items + MAX_ITEMS, // CS_PLAYERS (contains userinfo with name, skin, etc.)\n PlayerSkins = Players, // Alias for legacy code compatibility\n General = Players + MAX_CLIENTS,\n WheelWeapons = General + MAX_GENERAL,\n WheelAmmo = WheelWeapons + MAX_WHEEL_ITEMS,\n WheelPowerups = WheelAmmo + MAX_WHEEL_ITEMS,\n CdLoopCount = WheelPowerups + MAX_WHEEL_ITEMS,\n GameStyle = CdLoopCount + 1,\n MaxConfigStrings = GameStyle + 1,\n}\n\n// Mirror the C++ MAX_CONFIGSTRINGS value for consumers that prefer a standalone constant.\nexport const MAX_CONFIGSTRINGS = ConfigStringIndex.MaxConfigStrings;\n\n/**\n * Returns the maximum string length permitted for the given configstring index,\n * mirroring the `CS_SIZE` helper in the rerelease. Statusbar and general ranges\n * can legally occupy multiple 96-character slots; everything else is capped at\n * `CS_MAX_STRING_LENGTH`.\n */\nexport function configStringSize(index: number): number {\n if (index >= ConfigStringIndex.StatusBar && index < ConfigStringIndex.AirAccel) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.AirAccel - index);\n }\n\n if (index >= ConfigStringIndex.General && index < ConfigStringIndex.WheelWeapons) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.MaxConfigStrings - index);\n }\n\n return CS_MAX_STRING_LENGTH;\n}\n\n// Legacy constants\nexport const CS_NAME = ConfigStringIndex.Name;\nexport const CS_CDTRACK = ConfigStringIndex.CdTrack;\nexport const CS_SKY = ConfigStringIndex.Sky;\nexport const CS_SKYAXIS = ConfigStringIndex.SkyAxis;\nexport const CS_SKYROTATE = ConfigStringIndex.SkyRotate;\nexport const CS_STATUSBAR = ConfigStringIndex.StatusBar;\nexport const CS_AIRACCEL = ConfigStringIndex.AirAccel;\nexport const CS_MAXCLIENTS = ConfigStringIndex.MaxClients;\nexport const CS_MAPCHECKSUM = ConfigStringIndex.MapChecksum;\nexport const CS_MODELS = ConfigStringIndex.Models;\nexport const CS_SOUNDS = ConfigStringIndex.Sounds;\nexport const CS_IMAGES = ConfigStringIndex.Images;\nexport const CS_LIGHTS = ConfigStringIndex.Lights;\nexport const CS_ITEMS = ConfigStringIndex.Items;\nexport const CS_PLAYERS = ConfigStringIndex.Players;\nexport const CS_GENERAL = ConfigStringIndex.General;\n","export * from './schema.js';\nexport * from './io.js';\n","import { ReplaySession, ReplayFrame } from './schema.js';\nimport { UserCommand } from '../protocol/usercmd.js';\n\nexport function serializeReplay(session: ReplaySession): string {\n return JSON.stringify(session, null, 2);\n}\n\nexport function deserializeReplay(json: string): ReplaySession {\n const session = JSON.parse(json);\n\n // Validate structure lightly\n if (!session.metadata || !Array.isArray(session.frames)) {\n throw new Error('Invalid replay format: missing metadata or frames');\n }\n\n return session as ReplaySession;\n}\n\nexport function createReplaySession(map: string, seed?: number): ReplaySession {\n return {\n metadata: {\n map,\n date: new Date().toISOString(),\n version: '1.0',\n seed\n },\n frames: []\n };\n}\n\nexport function addReplayFrame(session: ReplaySession, cmd: UserCommand, serverFrame: number, startTime: number) {\n session.frames.push({\n serverFrame,\n cmd,\n timestamp: Date.now() - startTime\n });\n}\n","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\n","/**\n * Mirrors the Quake II rerelease `water_level_t` enumeration from `game.h`\n * (lines 443-449). These numeric values are relied upon throughout the\n * movement code when checking how submerged a player is, so we keep the same\n * ordering to make future porting work straightforward.\n */\nexport enum WaterLevel {\n None = 0,\n Feet = 1,\n Waist = 2,\n Under = 3,\n}\n\n/**\n * Utility that matches the common rerelease checks that treat any level at or\n * above the `WATER_WAIST` constant as \"significantly submerged\" for friction\n * and current calculations.\n */\nexport function isAtLeastWaistDeep(level: WaterLevel): boolean {\n return level >= WaterLevel.Waist;\n}\n\n/**\n * Returns true when the player is considered underwater (the `WATER_UNDER`\n * case in the rerelease). This mirrors the places in `p_move.cpp` that gate\n * effects such as breath timers and screen warping.\n */\nexport function isUnderwater(level: WaterLevel): boolean {\n return level === WaterLevel.Under;\n}\n\n/**\n * Matches the Quake II rerelease `pmflags_t` bit layout from `game.h` so the\n * shared helpers can manipulate the same flag words as the authoritative game\n * and the client prediction layer.\n */\nexport const enum PmFlag {\n Ducked = 1 << 0,\n JumpHeld = 1 << 1,\n OnGround = 1 << 2,\n TimeWaterJump = 1 << 3,\n TimeLand = 1 << 4,\n TimeTeleport = 1 << 5,\n NoPositionalPrediction = 1 << 6,\n OnLadder = 1 << 7,\n NoAngularPrediction = 1 << 8,\n IgnorePlayerCollision = 1 << 9,\n TimeTrick = 1 << 10,\n}\n\nexport type PmFlags = number;\n\nexport function hasPmFlag(flags: PmFlags, flag: PmFlag): boolean {\n return (flags & flag) !== 0;\n}\n\nexport function addPmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags | flag;\n}\n\nexport function removePmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags & ~flag;\n}\n\n/**\n * Player movement types mirrored from the rerelease `pmtype_t` enumeration.\n * The exact numeric values matter when syncing pmove state across the network\n * so we keep the same order as the C++ definition.\n */\nexport enum PmType {\n Normal = 0,\n Grapple = 1,\n NoClip = 2,\n Spectator = 3,\n Dead = 4,\n Gib = 5,\n Freeze = 6,\n}\n\n/**\n * Bitmask constants for the `buttons` field on the Quake II player command\n * structure. These mirror the rerelease `BUTTON_*` definitions so logic such as\n * jump/crouch checks can be shared between the server and client.\n */\nexport const enum PlayerButton {\n None = 0,\n Attack = 1 << 0,\n Use = 1 << 1,\n Holster = 1 << 2,\n Jump = 1 << 3,\n Crouch = 1 << 4,\n Attack2 = 1 << 5,\n Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel, type PmFlags, PmFlag, PmType, PlayerButton, addPmFlag, removePmFlag } from './constants.js';\n\nconst DEFAULT_JUMP_HEIGHT = 270;\n\nexport interface CheckJumpParams {\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly origin: Vec3;\n readonly jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly origin: Vec3;\n readonly jumpSound: boolean;\n readonly jumped: boolean;\n}\n\nfunction hasButton(buttons: number, button: PlayerButton): boolean {\n return (buttons & button) !== 0;\n}\n\n/**\n * Pure translation of the rerelease `PM_CheckJump` helper from `p_move.cpp`.\n * The function takes in the minimal pmove state that the original C++ logic\n * touches and returns the updated flag/origin/velocity tuple so callers can\n * apply the same semantics on both the server and client.\n */\nexport function checkJump(params: CheckJumpParams): CheckJumpResult {\n const { pmFlags, pmType, buttons, waterlevel, onGround, velocity, origin, jumpHeight = DEFAULT_JUMP_HEIGHT } = params;\n\n // PM_CheckJump immediately bails while the landing timer is active.\n if (pmFlags & PmFlag.TimeLand) {\n return { pmFlags, onGround, velocity, origin, jumpSound: false, jumped: false };\n }\n\n const holdingJump = hasButton(buttons, PlayerButton.Jump);\n let nextFlags = pmFlags;\n let nextOnGround = onGround;\n let jumpSound = false;\n let jumped = false;\n let nextVelocity = velocity;\n let nextOrigin = origin;\n\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n nextFlags = addPmFlag(nextFlags, PmFlag.JumpHeld);\n nextFlags = removePmFlag(nextFlags, PmFlag.OnGround);\n nextOnGround = false;\n jumpSound = true;\n jumped = true;\n\n const z = velocity.z + jumpHeight;\n const finalZ = z < jumpHeight ? jumpHeight : z;\n nextVelocity = { ...velocity, z: finalZ };\n\n // Unstuck from ground: pm->s.origin[2] += 1;\n nextOrigin = { ...origin, z: origin.z + 1 };\n\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\n}\n","import type { ContentsFlag } from '../bsp/contents.js';\nimport {\n CONTENTS_CURRENT_0,\n CONTENTS_CURRENT_180,\n CONTENTS_CURRENT_270,\n CONTENTS_CURRENT_90,\n CONTENTS_CURRENT_DOWN,\n CONTENTS_CURRENT_UP,\n CONTENTS_LADDER,\n MASK_CURRENT,\n} from '../bsp/contents.js';\nimport { addVec3, crossVec3, normalizeVec3, scaleVec3, ZERO_VEC3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, WaterLevel, isAtLeastWaistDeep } from './constants.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nexport interface WaterCurrentParams {\n readonly watertype: ContentsFlag;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly waterSpeed: number;\n}\n\nexport interface GroundCurrentParams {\n readonly groundContents: ContentsFlag;\n readonly scale?: number;\n}\n\nexport interface AddCurrentsParams {\n readonly wishVelocity: Vec3;\n readonly onLadder: boolean;\n readonly onGround: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n readonly groundContents: ContentsFlag;\n readonly cmd: PmoveCmd;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly waterSpeed: number;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace?: PmoveTraceFn;\n}\n\nconst DEFAULT_GROUND_CURRENT_SCALE = 100;\nconst DEFAULT_FORWARD_LADDER_CLAMP = 200;\nconst DEFAULT_SIDE_LADDER_CLAMP = 150;\nconst LADDER_HORIZONTAL_CAP = 25;\nconst LADDER_ASCEND_PITCH_THRESHOLD = 15;\nconst LADDER_TRACE_DISTANCE = 1;\nconst UP_VECTOR: Vec3 = { x: 0, y: 0, z: 1 };\n\nconst DEFAULT_TRACE: PmoveTraceFn = (_, end) => ({\n fraction: 1,\n endpos: end,\n allsolid: false,\n startsolid: false,\n});\n\n/**\n * Mirrors the rerelease pattern in `p_move.cpp` (lines 730-765) that turns the\n * directional CONTENTS_CURRENT_* flags into a unit-ish direction vector.\n */\nexport function currentVectorFromContents(contents: ContentsFlag): Vec3 {\n let x = 0;\n let y = 0;\n let z = 0;\n\n if (contents & CONTENTS_CURRENT_0) {\n x += 1;\n }\n if (contents & CONTENTS_CURRENT_90) {\n y += 1;\n }\n if (contents & CONTENTS_CURRENT_180) {\n x -= 1;\n }\n if (contents & CONTENTS_CURRENT_270) {\n y -= 1;\n }\n if (contents & CONTENTS_CURRENT_UP) {\n z += 1;\n }\n if (contents & CONTENTS_CURRENT_DOWN) {\n z -= 1;\n }\n\n if (x === 0 && y === 0 && z === 0) {\n return ZERO_VEC3;\n }\n\n return { x, y, z };\n}\n\n/**\n * Computes the velocity contribution from water currents using the same rules\n * as `PM_WaterMove`: the CONTENTS_CURRENT_* bits are turned into a direction\n * vector, scaled by `pm_waterspeed`, and halved when the player only has their\n * feet submerged while standing on solid ground.\n */\nexport function waterCurrentVelocity(params: WaterCurrentParams): Vec3 {\n const { watertype, waterlevel, onGround, waterSpeed } = params;\n\n if ((watertype & MASK_CURRENT) === 0) {\n return ZERO_VEC3;\n }\n\n const direction = currentVectorFromContents(watertype);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n let scale = waterSpeed;\n if (waterlevel === WaterLevel.Feet && onGround) {\n scale *= 0.5;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Computes the conveyor-style velocity that should be applied while touching a\n * ground plane that carries CONTENTS_CURRENT_* bits. The rerelease multiplies\n * the direction vector by 100 units per second, so we expose the same default\n * while allowing callers to override the scalar for tests.\n */\nexport function groundCurrentVelocity(params: GroundCurrentParams): Vec3 {\n const { groundContents, scale = DEFAULT_GROUND_CURRENT_SCALE } = params;\n\n const direction = currentVectorFromContents(groundContents);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Pure mirror of PM_AddCurrents from rerelease `p_move.cpp`: handles ladder\n * specific motion tweaks, water currents, and conveyor-style ground currents\n * before pmove acceleration is applied.\n */\nexport function applyPmoveAddCurrents(params: AddCurrentsParams): Vec3 {\n const {\n wishVelocity,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed,\n ladderMod,\n waterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace = DEFAULT_TRACE,\n } = params;\n\n let adjusted = wishVelocity;\n\n if (onLadder) {\n adjusted = applyLadderAdjustments({\n wishVelocity: adjusted,\n cmd,\n waterlevel,\n viewPitch,\n maxSpeed,\n ladderMod,\n onGround,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n }\n\n const waterVelocity = waterCurrentVelocity({ watertype, waterlevel, onGround, waterSpeed });\n if (waterVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, waterVelocity);\n }\n\n if (onGround) {\n const groundVelocity = groundCurrentVelocity({ groundContents });\n if (groundVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, groundVelocity);\n }\n }\n\n return adjusted;\n}\n\ninterface LadderAdjustParams {\n readonly wishVelocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly onGround: boolean;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nfunction applyLadderAdjustments(params: LadderAdjustParams): Vec3 {\n const { wishVelocity, cmd, waterlevel, viewPitch, maxSpeed, ladderMod, onGround, forward, origin, mins, maxs, trace } = params;\n const buttons = cmd.buttons ?? 0;\n let adjusted = { ...wishVelocity };\n\n if ((buttons & (PlayerButton.Jump | PlayerButton.Crouch)) !== 0) {\n const ladderSpeed = isAtLeastWaistDeep(waterlevel) ? maxSpeed : DEFAULT_FORWARD_LADDER_CLAMP;\n adjusted = {\n ...adjusted,\n z: buttons & PlayerButton.Jump ? ladderSpeed : -ladderSpeed,\n };\n } else if (cmd.forwardmove) {\n const clamped = clamp(cmd.forwardmove, -DEFAULT_FORWARD_LADDER_CLAMP, DEFAULT_FORWARD_LADDER_CLAMP);\n if (cmd.forwardmove > 0) {\n const climb = viewPitch < LADDER_ASCEND_PITCH_THRESHOLD ? clamped : -clamped;\n adjusted = { ...adjusted, z: climb };\n } else {\n if (!onGround) {\n adjusted = { ...adjusted, x: 0, y: 0 };\n }\n adjusted = { ...adjusted, z: clamped };\n }\n } else {\n adjusted = { ...adjusted, z: 0 };\n }\n\n if (!onGround) {\n if (cmd.sidemove) {\n let sideSpeed = clamp(cmd.sidemove, -DEFAULT_SIDE_LADDER_CLAMP, DEFAULT_SIDE_LADDER_CLAMP);\n if (waterlevel < WaterLevel.Waist) {\n sideSpeed *= ladderMod;\n }\n\n const flatForward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n if (flatForward.x !== 0 || flatForward.y !== 0) {\n const spot = addVec3(origin, scaleVec3(flatForward, LADDER_TRACE_DISTANCE));\n const tr = trace(origin, spot, mins, maxs);\n if (\n tr.fraction !== 1 &&\n !tr.allsolid &&\n tr.contents !== undefined &&\n (tr.contents & CONTENTS_LADDER) !== 0 &&\n tr.planeNormal\n ) {\n const right = crossVec3(tr.planeNormal, UP_VECTOR);\n adjusted = { ...adjusted, x: 0, y: 0 };\n adjusted = addVec3(adjusted, scaleVec3(right, -sideSpeed));\n }\n }\n } else {\n adjusted = {\n ...adjusted,\n x: clampHorizontal(adjusted.x),\n y: clampHorizontal(adjusted.y),\n };\n }\n }\n\n return adjusted;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction clampHorizontal(value: number): number {\n if (value < -LADDER_HORIZONTAL_CAP) {\n return -LADDER_HORIZONTAL_CAP;\n }\n if (value > LADDER_HORIZONTAL_CAP) {\n return LADDER_HORIZONTAL_CAP;\n }\n return value;\n}\n","import { addVec3, ZERO_VEC3, clipVelocityVec3, crossVec3, dotVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst DEFAULT_MAX_CLIP_PLANES = 5;\nconst DEFAULT_MAX_BUMPS = 4;\nconst DEFAULT_STEP_SIZE = 18;\nconst MIN_STEP_NORMAL = 0.7;\n\nexport const SLIDEMOVE_BLOCKED_FLOOR = 1;\nexport const SLIDEMOVE_BLOCKED_WALL = 2;\n\nexport interface SlideMoveResult {\n readonly velocity: Vec3;\n readonly planes: readonly Vec3[];\n readonly stopped: boolean;\n}\n\nexport interface SlideMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly overbounce: number;\n readonly trace: PmoveTraceFn;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n /**\n * Mirrors the pm->s.pm_time check in PM_StepSlideMove_Generic: if true, the\n * returned velocity is reset to the primal velocity after collision\n * resolution so time-based effects (like knockbacks) don't dampen.\n */\n readonly hasTime?: boolean;\n}\n\nexport interface SlideMoveOutcome extends SlideMoveResult {\n readonly origin: Vec3;\n readonly blocked: number;\n}\n\nexport interface StepSlideMoveParams extends SlideMoveParams {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly stepSize?: number;\n}\n\nexport interface StepSlideMoveOutcome extends SlideMoveOutcome {\n readonly stepped: boolean;\n readonly stepHeight: number;\n readonly stepNormal?: Vec3;\n}\n\n/**\n * Resolves a sequence of collision planes against a primal velocity using the same\n * plane iteration logic seen in PM_StepSlideMove_Generic (rerelease p_move.cpp).\n * The incoming planes should be ordered as they were encountered during traces;\n * the function will accumulate them, clip the velocity to be parallel to all planes,\n * and return zero velocity when three planes form an unresolvable corner or when\n * the adjusted velocity would oppose the primal direction.\n */\nexport function resolveSlideMove(\n initialVelocity: Vec3,\n planesEncountered: readonly Vec3[],\n overbounce: number,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n primalVelocity: Vec3 = initialVelocity,\n): SlideMoveResult {\n if (planesEncountered.length === 0) {\n return { velocity: initialVelocity, planes: [], stopped: false };\n }\n\n const planes: Vec3[] = [];\n let velocity: Vec3 = initialVelocity;\n\n for (const plane of planesEncountered) {\n if (planes.length >= maxClipPlanes) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n // Skip near-duplicate planes to mirror the epsilon guard in PM_StepSlideMove_Generic.\n const duplicate = planes.find((existing) => dotVec3(existing, plane) > 0.99);\n if (duplicate) {\n continue;\n }\n\n planes.push(plane);\n\n let clipped: Vec3 | undefined;\n let i = 0;\n for (; i < planes.length; i++) {\n const candidate = clipVelocityVec3(velocity, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) continue;\n if (dotVec3(candidate, planes[j]) < 0) break;\n }\n\n if (j === planes.length) {\n clipped = candidate;\n break;\n }\n }\n\n if (clipped) {\n velocity = clipped;\n } else {\n if (planes.length !== 2) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n velocity = scaleVec3(dir, d);\n }\n\n // If velocity reversed relative to the primal direction, stop to avoid oscillations.\n if (dotVec3(velocity, primalVelocity) <= 0) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n }\n\n const stopped = velocity.x === 0 && velocity.y === 0 && velocity.z === 0;\n return { velocity, planes, stopped };\n}\n\n/**\n * Pure mirror of PM_SlideMoveGeneric from rerelease `p_move.cpp` (minus gravity/step handling).\n * Uses a caller-provided trace to collect collision planes, accumulates them through\n * `resolveSlideMove`, and returns the resulting origin/velocity/blocking state.\n */\nexport function slideMove(params: SlideMoveParams): SlideMoveOutcome {\n const {\n origin: initialOrigin,\n velocity: initialVelocity,\n frametime,\n overbounce,\n trace,\n maxBumps = DEFAULT_MAX_BUMPS,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n mins,\n maxs,\n hasTime = false,\n } = params;\n\n let origin = initialOrigin;\n let velocity = initialVelocity;\n const planes: Vec3[] = [];\n const primalVelocity = initialVelocity;\n let timeLeft = frametime;\n let blocked = 0;\n\n for (let bump = 0; bump < maxBumps; bump++) {\n if (velocity.x === 0 && velocity.y === 0 && velocity.z === 0) {\n break;\n }\n\n const end = addVec3(origin, scaleVec3(velocity, timeLeft));\n const tr = trace(origin, end, mins, maxs);\n\n if (tr.allsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.startsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.fraction > 0) {\n origin = tr.endpos;\n }\n\n if (tr.fraction === 1) {\n break;\n }\n\n if (!tr.planeNormal) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.planeNormal.z > 0.7) {\n blocked |= SLIDEMOVE_BLOCKED_FLOOR;\n }\n if (tr.planeNormal.z === 0) {\n blocked |= SLIDEMOVE_BLOCKED_WALL;\n }\n\n planes.push(tr.planeNormal);\n timeLeft -= timeLeft * tr.fraction;\n\n const resolved = resolveSlideMove(velocity, planes, overbounce, maxClipPlanes, primalVelocity);\n velocity = resolved.velocity;\n planes.splice(0, planes.length, ...resolved.planes);\n\n if (primalVelocity.z > 0 && velocity.z < 0) {\n velocity = { ...velocity, z: 0 };\n }\n\n if (resolved.stopped) {\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: true, blocked };\n }\n }\n\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: velocityOut.x === 0 && velocityOut.y === 0 && velocityOut.z === 0, blocked };\n}\n\n/**\n * Mirrors PM_StepSlideMove (rerelease p_move.cpp) in a pure form: attempts a\n * regular slide move, then retries from a stepped-up position when the first\n * attempt was blocked. The function compares planar distance traveled and the\n * steepness of the landing plane to decide whether to keep the step.\n */\nexport function stepSlideMove(params: StepSlideMoveParams): StepSlideMoveOutcome {\n const { mins, maxs, stepSize = DEFAULT_STEP_SIZE, ...rest } = params;\n\n const startOrigin = params.origin;\n const startVelocity = params.velocity;\n\n const downResult = slideMove({ ...rest, mins, maxs });\n\n const upTarget = addVec3(startOrigin, { x: 0, y: 0, z: stepSize });\n const upTrace = rest.trace(startOrigin, upTarget, mins, maxs);\n if (upTrace.allsolid) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const actualStep = upTrace.endpos.z - startOrigin.z;\n const steppedResult = slideMove({ ...rest, origin: upTrace.endpos, velocity: startVelocity, mins, maxs });\n\n const pushDownTarget = addVec3(steppedResult.origin, { x: 0, y: 0, z: -actualStep });\n const downTrace = rest.trace(steppedResult.origin, pushDownTarget, mins, maxs);\n\n let steppedOrigin = steppedResult.origin;\n let stepNormal = downTrace.planeNormal;\n\n if (!downTrace.allsolid) {\n steppedOrigin = downTrace.endpos;\n }\n\n const planarDistanceSquared = (a: Vec3, b: Vec3) => (a.x - b.x) ** 2 + (a.y - b.y) ** 2;\n const downDist = planarDistanceSquared(downResult.origin, startOrigin);\n const upDist = planarDistanceSquared(steppedOrigin, startOrigin);\n\n if (downDist > upDist || (stepNormal && stepNormal.z < MIN_STEP_NORMAL)) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const steppedVelocity = { ...steppedResult.velocity, z: downResult.velocity.z };\n const steppedBlocked = steppedResult.blocked;\n const stopped = steppedVelocity.x === 0 && steppedVelocity.y === 0 && steppedVelocity.z === 0;\n\n return {\n origin: steppedOrigin,\n velocity: steppedVelocity,\n planes: steppedResult.planes,\n blocked: steppedBlocked,\n stopped,\n stepped: true,\n stepHeight: actualStep,\n stepNormal,\n };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport { applyPmoveAccelerate, applyPmoveAirAccelerate } from './pmove.js';\nimport { applyPmoveAddCurrents } from './currents.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n PlayerButton,\n WaterLevel,\n hasPmFlag,\n} from './constants.js';\n\ninterface BaseMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly hasTime?: boolean;\n}\n\nexport interface AirMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly gravity: number;\n readonly pmType: PmType;\n readonly pmAccelerate: number;\n readonly pmAirAccelerate?: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly onLadder: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly groundContents: number;\n readonly viewPitch: number;\n readonly ladderMod: number;\n readonly pmWaterSpeed: number;\n}\n\nexport interface WaterMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly pmWaterAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly onLadder: boolean;\n readonly watertype: number;\n readonly groundContents: number;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly ladderMod: number;\n}\n\nexport interface WalkMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly gravity: number;\n readonly pmType: PmType;\n readonly pmAccelerate: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly onLadder: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly groundContents: number;\n readonly viewPitch: number;\n readonly ladderMod: number;\n readonly pmWaterSpeed: number;\n}\n\nconst DEFAULT_AIR_ACCELERATE = 1;\nconst WATER_DRIFT_SPEED = 60;\nconst DEFAULT_STEP_OVERBOUNCE = 1.01;\n\nexport function applyPmoveAirMove(params: AirMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n gravity,\n pmType,\n pmAccelerate,\n pmAirAccelerate = DEFAULT_AIR_ACCELERATE,\n pmMaxSpeed,\n pmDuckSpeed,\n onLadder,\n waterlevel,\n watertype,\n groundContents,\n viewPitch,\n ladderMod,\n pmWaterSpeed,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildPlanarWishVelocity(forward, right, cmd);\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n const maxSpeed = ducked ? pmDuckSpeed : pmMaxSpeed;\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n if (onLadder) {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (Math.abs(wishvel.z) < Number.EPSILON) {\n velocity = dampVerticalVelocity(velocity, gravity, frametime);\n }\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (onGround) {\n velocity = { ...velocity, z: 0 };\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (gravity > 0) {\n velocity = { ...velocity, z: 0 };\n } else {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n if (velocity.x === 0 && velocity.y === 0) {\n return {\n origin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: true,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (pmAirAccelerate > 0) {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir,\n wishspeed,\n accel: pmAirAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: DEFAULT_AIR_ACCELERATE, frametime });\n }\n\n if (pmType !== PmType.Grapple) {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nexport function applyPmoveWaterMove(params: WaterMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n pmMaxSpeed,\n pmDuckSpeed,\n pmWaterAccelerate,\n pmWaterSpeed,\n onLadder,\n watertype,\n groundContents,\n waterlevel,\n viewPitch,\n ladderMod,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildFullWishVelocity(forward, right, cmd);\n\n if (isIdleInWater(cmd, onGround)) {\n wishvel = { ...wishvel, z: wishvel.z - WATER_DRIFT_SPEED };\n } else {\n if (hasButton(cmd, PlayerButton.Crouch)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: -pmWaterSpeed * 0.5 });\n } else if (hasButton(cmd, PlayerButton.Jump)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: pmWaterSpeed * 0.5 });\n }\n }\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmMaxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n wishspeed *= 0.5;\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n if (ducked && wishspeed > pmDuckSpeed) {\n const scale = pmDuckSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmDuckSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmWaterAccelerate, frametime });\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nexport function applyPmoveWalkMove(params: WalkMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n gravity,\n pmAccelerate,\n pmMaxSpeed,\n pmDuckSpeed,\n onLadder,\n waterlevel,\n watertype,\n groundContents,\n viewPitch,\n ladderMod,\n pmWaterSpeed,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildPlanarWishVelocity(forward, right, cmd);\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n const maxSpeed = ducked ? pmDuckSpeed : pmMaxSpeed;\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n // Ground friction handled by caller (applyPmoveFriction)\n\n velocity = { ...velocity, z: 0 };\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n\n if (gravity > 0) {\n velocity = { ...velocity, z: 0 };\n } else {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n if (velocity.x === 0 && velocity.y === 0) {\n return {\n origin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: true,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nfunction buildPlanarWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n}\n\nfunction buildFullWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: forward.z * cmd.forwardmove + right.z * cmd.sidemove,\n } satisfies Vec3;\n}\n\nfunction hasButton(cmd: PmoveCmd, button: PlayerButton): boolean {\n return (cmd.buttons ?? 0) & button ? true : false;\n}\n\nfunction isIdleInWater(cmd: PmoveCmd, onGround: boolean): boolean {\n const noMove = cmd.forwardmove === 0 && cmd.sidemove === 0;\n const noButtons = (cmd.buttons ?? 0) & (PlayerButton.Jump | PlayerButton.Crouch) ? false : true;\n return noMove && noButtons && !onGround;\n}\n\nfunction dampVerticalVelocity(velocity: Vec3, gravity: number, frametime: number): Vec3 {\n let z = velocity.z;\n const delta = gravity * frametime;\n if (z > 0) {\n z -= delta;\n if (z < 0) {\n z = 0;\n }\n } else {\n z += delta;\n if (z > 0) {\n z = 0;\n }\n }\n return { ...velocity, z };\n}\n\ninterface StepParams extends BaseMoveParams {\n readonly velocity: Vec3;\n}\n\nfunction runStepSlideMove(params: StepParams): StepSlideMoveOutcome {\n const { origin, velocity, frametime, mins, maxs, trace, overbounce = DEFAULT_STEP_OVERBOUNCE, stepSize, maxBumps, maxClipPlanes, hasTime } = params;\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n","import { MASK_WATER, CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel } from './constants.js';\nimport type { PmovePointContentsFn } from './types.js';\n\nexport interface WaterLevelParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly viewheight: number;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface WaterLevelResult {\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n}\n\n/**\n * Mirrors the rerelease `PM_GetWaterLevel` helper: probes the player's feet,\n * waist, and viewheight to determine how submerged they are and returns both\n * the enum level plus the contents bits encountered at the lowest sample.\n */\nexport function getWaterLevel(params: WaterLevelParams): WaterLevelResult {\n const { origin, mins, viewheight, pointContents } = params;\n\n const sample2 = viewheight - mins.z;\n const sample1 = sample2 / 2;\n\n const point: Vec3 = {\n x: origin.x,\n y: origin.y,\n z: origin.z + mins.z + 1,\n };\n\n let contents = pointContents(point);\n if ((contents & MASK_WATER) === 0) {\n return { waterlevel: WaterLevel.None, watertype: CONTENTS_NONE };\n }\n\n const watertype = contents;\n let waterlevel = WaterLevel.Feet;\n\n let point2: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample1 };\n contents = pointContents(point2);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Waist;\n\n let point3: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample2 };\n contents = pointContents(point3);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Under;\n }\n }\n\n return { waterlevel, watertype };\n}\n","import { CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport { addVec3, clipVelocityVec3, type Vec3 } from '../math/vec3.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport { getWaterLevel } from './water.js';\nimport type { PmovePointContentsFn, PmoveTraceFn, PmoveTraceResult } from './types.js';\n\nconst GROUND_PROBE_DISTANCE = 0.25;\nconst LADDER_BYPASS_VELOCITY = 180;\nconst TRICK_VELOCITY_THRESHOLD = 100;\nconst SLANTED_NORMAL_THRESHOLD = 0.7;\nconst TRICK_NORMAL_THRESHOLD = 0.9;\nconst TRICK_PM_TIME = 64;\nconst LAND_PM_TIME = 128;\nconst IMPACT_CLIP_OVERBOUNCE = 1.01;\n\nconst WATERJUMP_CLEAR =\n PmFlag.TimeWaterJump | PmFlag.TimeLand | PmFlag.TimeTeleport | PmFlag.TimeTrick;\n\nexport interface CategorizePositionParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly n64Physics: boolean;\n readonly velocity: Vec3;\n readonly startVelocity: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface CategorizePositionResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly onGround: boolean;\n readonly groundTrace?: PmoveTraceResult;\n readonly groundContents: ContentsFlag;\n readonly waterlevel: number;\n readonly watertype: ContentsFlag;\n readonly impactDelta?: number;\n}\n\n/**\n * Pure mirror of PM_CatagorizePosition from `rerelease/p_move.cpp`: traces a quarter-unit\n * below the player bounds to determine whether they stand on solid ground, updates timers\n * and pmflags accordingly, records the latest ground plane data, and recalculates waterlevel\n * by probing feet/waist/viewheight samples.\n */\nexport function categorizePosition(params: CategorizePositionParams): CategorizePositionResult {\n const {\n pmType,\n n64Physics,\n velocity,\n startVelocity,\n origin,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n } = params;\n\n let pmFlags = params.pmFlags;\n let pmTime = params.pmTime;\n let impactDelta: number | undefined;\n let onGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n let groundTrace: PmoveTraceResult | undefined;\n let groundContents: ContentsFlag = CONTENTS_NONE;\n\n const forceAirborne = velocity.z > LADDER_BYPASS_VELOCITY || pmType === PmType.Grapple;\n\n if (forceAirborne) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n const end: Vec3 = { x: origin.x, y: origin.y, z: origin.z - GROUND_PROBE_DISTANCE };\n const traceResult = trace(origin, end, mins, maxs);\n groundTrace = traceResult;\n groundContents = traceResult.contents ?? CONTENTS_NONE;\n\n const planeNormal = traceResult.planeNormal;\n\n let slantedGround =\n traceResult.fraction < 1 && !!planeNormal && planeNormal.z < SLANTED_NORMAL_THRESHOLD;\n\n if (slantedGround && planeNormal) {\n const slantEnd = addVec3(origin, planeNormal);\n const slantTrace = trace(origin, slantEnd, mins, maxs);\n if (slantTrace.fraction < 1 && !slantTrace.startsolid) {\n slantedGround = false;\n }\n }\n\n if (\n traceResult.fraction === 1 ||\n !planeNormal ||\n (slantedGround && !traceResult.startsolid)\n ) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n onGround = true;\n\n if (hasPmFlag(pmFlags, PmFlag.TimeWaterJump)) {\n pmFlags &= ~WATERJUMP_CLEAR;\n pmTime = 0;\n }\n\n const wasOnGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround) {\n if (\n !n64Physics &&\n velocity.z >= TRICK_VELOCITY_THRESHOLD &&\n planeNormal.z >= TRICK_NORMAL_THRESHOLD &&\n !hasPmFlag(pmFlags, PmFlag.Ducked)\n ) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeTrick);\n pmTime = TRICK_PM_TIME;\n }\n\n const clipped = clipVelocityVec3(velocity, planeNormal, IMPACT_CLIP_OVERBOUNCE);\n impactDelta = startVelocity.z - clipped.z;\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround && (n64Physics || hasPmFlag(pmFlags, PmFlag.Ducked))) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeLand);\n pmTime = LAND_PM_TIME;\n }\n }\n }\n\n const { waterlevel, watertype } = getWaterLevel({\n origin,\n mins,\n viewheight,\n pointContents,\n });\n\n return {\n pmFlags,\n pmTime,\n onGround: hasPmFlag(pmFlags, PmFlag.OnGround),\n groundTrace,\n groundContents,\n waterlevel,\n watertype,\n impactDelta,\n };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { PmFlag, type PmFlags, PmType } from './constants.js';\n\nexport interface PlayerDimensions {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n}\n\nfunction createVec3(x: number, y: number, z: number): Vec3 {\n return { x, y, z } satisfies Vec3;\n}\n\n/**\n * Pure mirror of PM_SetDimensions from rerelease `p_move.cpp`.\n * Computes the mins/maxs/viewheight triplet for a player based on\n * their movement type and ducked flag without mutating inputs.\n */\nexport function computePlayerDimensions(pmType: PmType, pmFlags: PmFlags): PlayerDimensions {\n const minsBase = createVec3(-16, -16, 0);\n const maxsBase = createVec3(16, 16, 16);\n\n if (pmType === PmType.Gib) {\n return {\n mins: minsBase,\n maxs: maxsBase,\n viewheight: 8,\n } satisfies PlayerDimensions;\n }\n\n const ducked = pmType === PmType.Dead || (pmFlags & PmFlag.Ducked) !== 0;\n const mins = createVec3(minsBase.x, minsBase.y, -24);\n const maxs = createVec3(maxsBase.x, maxsBase.y, ducked ? 4 : 32);\n\n return {\n mins,\n maxs,\n viewheight: ducked ? -2 : 22,\n } satisfies PlayerDimensions;\n}\n","import { MASK_SOLID, MASK_WATER, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport {\n PlayerButton,\n PmFlag,\n type PmFlags,\n PmType,\n WaterLevel,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport type { PmoveTraceResult } from './types.js';\nimport { computePlayerDimensions, type PlayerDimensions } from './dimensions.js';\n\nconst CROUCH_MAX_Z = 4;\nconst STAND_MAX_Z = 32;\nconst ABOVE_WATER_OFFSET = 8;\n\nexport interface DuckTraceParams {\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly mask: ContentsFlag;\n}\n\nexport type DuckTraceFn = (params: DuckTraceParams) => PmoveTraceResult;\n\nexport interface CheckDuckParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly hasGroundEntity: boolean;\n readonly onLadder: boolean;\n readonly n64Physics: boolean;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: DuckTraceFn;\n}\n\nexport interface CheckDuckResult extends PlayerDimensions {\n readonly pmFlags: PmFlags;\n readonly ducked: boolean;\n readonly changed: boolean;\n}\n\n/**\n * Pure port of PM_CheckDuck from rerelease `p_move.cpp`. Updates the PMF_DUCKED flag\n * based on crouch input, obstruction traces, and special cases (dead bodies) without\n * mutating the provided mins/maxs. Returns the updated flag word plus the dimensions\n * computed from PM_SetDimensions so callers can update collision bounds atomically.\n */\nexport function checkDuckState(params: CheckDuckParams): CheckDuckResult {\n const { pmType } = params;\n\n if (pmType === PmType.Gib) {\n const dims = computePlayerDimensions(pmType, params.pmFlags);\n return { pmFlags: params.pmFlags, ducked: hasPmFlag(params.pmFlags, PmFlag.Ducked), changed: false, ...dims };\n }\n\n let flags = params.pmFlags;\n let changed = false;\n\n if (pmType === PmType.Dead) {\n if (!hasPmFlag(flags, PmFlag.Ducked)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (shouldDuck(params)) {\n if (!hasPmFlag(flags, PmFlag.Ducked) && !isDuckBlocked(params)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (hasPmFlag(flags, PmFlag.Ducked) && !isStandBlocked(params)) {\n flags = removePmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n\n const dims = computePlayerDimensions(pmType, flags);\n const ducked = pmType === PmType.Dead || hasPmFlag(flags, PmFlag.Ducked);\n\n return { pmFlags: flags, ducked, changed, ...dims };\n}\n\nfunction shouldDuck(params: CheckDuckParams): boolean {\n if ((params.buttons & PlayerButton.Crouch) === 0) {\n return false;\n }\n if (params.onLadder || params.n64Physics) {\n return false;\n }\n if (params.hasGroundEntity) {\n return true;\n }\n if (params.waterlevel <= WaterLevel.Feet && !isAboveWater(params)) {\n return true;\n }\n return false;\n}\n\nfunction isDuckBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, CROUCH_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isStandBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, STAND_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isAboveWater(params: CheckDuckParams): boolean {\n const below: Vec3 = { x: params.origin.x, y: params.origin.y, z: params.origin.z - ABOVE_WATER_OFFSET };\n\n const solidTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_SOLID,\n });\n\n if (solidTrace.fraction < 1) {\n return false;\n }\n\n const waterTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_WATER,\n });\n\n return waterTrace.fraction < 1;\n}\n\nfunction withZ(vec: Vec3, z: number): Vec3 {\n return { x: vec.x, y: vec.y, z };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport { angleVectors } from '../math/angles.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n PmoveState,\n PmoveImports,\n PmoveTraceResult\n} from './types.js';\nimport { PlayerButton, PmFlag, PmType, addPmFlag, removePmFlag } from './constants.js';\nimport { checkJump } from './jump.js';\nimport { applyPmoveAirMove, applyPmoveWaterMove, applyPmoveWalkMove } from './move.js';\nimport { categorizePosition } from './categorize.js';\nimport { checkDuckState, DuckTraceParams } from './duck.js';\n// import { updateViewOffsets } from './view.js';\n\nconst FRAMETIME = 0.025; // Define FRAMETIME here or import if available in constants? Using local definition for now as per previous context.\n\n/**\n * Pure version of PM_Friction from rerelease p_move.cpp.\n * Handles ground and water friction and returns a new velocity.\n */\nexport function applyPmoveFriction(params: PmoveFrictionParams): Vec3 {\n const {\n velocity,\n frametime,\n onGround,\n groundIsSlick,\n onLadder,\n waterlevel,\n pmFriction,\n pmStopSpeed,\n pmWaterFriction,\n } = params;\n\n const speed = lengthVec3(velocity);\n\n // Matches the \"if (speed < 1)\" early-out: clears X/Y but preserves Z.\n if (speed < 1) {\n return { x: 0, y: 0, z: velocity.z };\n }\n\n let drop = 0;\n\n // Ground friction (or ladder)\n if ((onGround && !groundIsSlick) || onLadder) {\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const friction = pmFriction;\n drop += control * friction * frametime;\n }\n\n // Water friction (only when not on ladder)\n if (waterlevel > 0 && !onLadder) {\n drop += speed * pmWaterFriction * waterlevel * frametime;\n }\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n const scale = newspeed / speed;\n return scaleVec3(velocity, scale);\n}\n\n/**\n * Pure version of PM_Accelerate from rerelease p_move.cpp.\n * Returns a new velocity with wishdir/wishspeed acceleration applied.\n */\nexport function applyPmoveAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspeed - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * frametime * wishspeed;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Mirrors PM_AirAccelerate in rerelease `p_move.cpp` (lines ~612-636): wishspeed is clamped\n * to 30 for the addspeed calculation but the acceleration magnitude still uses the full wishspeed.\n */\nexport function applyPmoveAirAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const wishspd = Math.min(wishspeed, 30);\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspd - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * wishspeed * frametime;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Pure mirror of PM_CmdScale from rerelease `p_move.cpp`. Computes the scalar applied to\n * the command directional inputs so that the resulting wish velocity caps at `maxSpeed`\n * regardless of the directional mix.\n */\nexport function pmoveCmdScale(cmd: PmoveCmd, maxSpeed: number): number {\n const forward = Math.abs(cmd.forwardmove);\n const side = Math.abs(cmd.sidemove);\n const up = Math.abs(cmd.upmove);\n\n const max = Math.max(forward, side, up);\n if (max === 0) {\n return 0;\n }\n\n const total = Math.sqrt(cmd.forwardmove * cmd.forwardmove + cmd.sidemove * cmd.sidemove + cmd.upmove * cmd.upmove);\n return (maxSpeed * max) / (127 * total);\n}\n\n/**\n * Computes wishdir/wishspeed for ground/air movement as done in PM_AirMove and\n * PM_GroundMove. Z is forced to zero and wishspeed is clamped to maxSpeed, matching\n * the rerelease p_move.cpp helpers before they call PM_Accelerate/PM_AirAccelerate.\n */\nexport function buildAirGroundWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n\n/**\n * Computes the wishdir/wishspeed mix for water movement, matching PM_WaterMove in\n * rerelease p_move.cpp: includes the upward bias when no strong upmove is requested,\n * clamps wishspeed to maxSpeed, and halves the returned wishspeed before acceleration.\n */\nexport function buildWaterWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n // Use full 3D components for water movement\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: forward.z * cmd.forwardmove + right.z * cmd.sidemove,\n } satisfies Vec3;\n\n if (cmd.upmove > 10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else if (cmd.upmove < -10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else if (Math.abs(cmd.forwardmove) < 10 && Math.abs(cmd.sidemove) < 10) {\n // Standard drift down when no vertical input AND no significant horizontal input\n // Matches Quake 2 rerelease behavior (sinking slowly)\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: -60 });\n } else {\n // When moving horizontally but not vertically, drift slightly up\n // This matches the \"else { wishvel[2] += 10 }\" logic in PM_WaterMove\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: 10 });\n }\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n wishspeed *= 0.5;\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n\n/**\n * Runs the full player movement simulation for a single frame.\n */\nexport function runPmove(state: PmoveState, imports: PmoveImports): PmoveState {\n if (state.pmType === PmType.Dead) {\n return state;\n }\n\n let nextState = { ...state };\n\n // Categorize Position\n const catResult = categorizePosition({\n pmType: nextState.pmType,\n pmFlags: nextState.pmFlags,\n pmTime: 0,\n n64Physics: false,\n velocity: nextState.velocity,\n startVelocity: nextState.velocity,\n origin: nextState.origin,\n mins: nextState.mins,\n maxs: nextState.maxs,\n viewheight: nextState.viewHeight,\n trace: imports.trace,\n pointContents: imports.pointcontents\n });\n\n // Merge result back to state\n nextState.pmFlags = catResult.pmFlags;\n nextState.waterlevel = catResult.waterlevel;\n nextState.watertype = catResult.watertype;\n\n // Check Ducking (Before Jump)\n const duckResult = checkDuckState({\n pmType: nextState.pmType,\n pmFlags: nextState.pmFlags,\n buttons: nextState.cmd.buttons,\n waterlevel: nextState.waterlevel,\n hasGroundEntity: (nextState.pmFlags & PmFlag.OnGround) !== 0,\n onLadder: false,\n n64Physics: false,\n origin: nextState.origin,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: (params: DuckTraceParams): PmoveTraceResult => {\n // Adapter from DuckTraceFn (obj) to PmoveTraceFn (args)\n return imports.trace(params.start, params.end, params.mins, params.maxs);\n }\n });\n\n nextState.pmFlags = duckResult.pmFlags;\n nextState.mins = duckResult.mins;\n nextState.maxs = duckResult.maxs;\n nextState.viewHeight = duckResult.viewheight;\n\n // Check Jump\n const jumpResult = checkJump({\n pmFlags: nextState.pmFlags,\n pmType: nextState.pmType,\n buttons: nextState.cmd.buttons,\n waterlevel: nextState.waterlevel,\n onGround: (nextState.pmFlags & PmFlag.OnGround) !== 0,\n velocity: nextState.velocity,\n origin: nextState.origin\n });\n\n nextState.pmFlags = jumpResult.pmFlags;\n nextState.velocity = jumpResult.velocity;\n nextState.origin = jumpResult.origin;\n\n if (jumpResult.onGround !== ((nextState.pmFlags & PmFlag.OnGround) !== 0)) {\n if (jumpResult.onGround) {\n nextState.pmFlags = addPmFlag(nextState.pmFlags, PmFlag.OnGround);\n } else {\n nextState.pmFlags = removePmFlag(nextState.pmFlags, PmFlag.OnGround);\n }\n }\n\n // Frictional movement\n const onGround = (nextState.pmFlags & PmFlag.OnGround) !== 0;\n\n // Apply friction\n const velocityBeforeFriction = nextState.velocity;\n nextState.velocity = applyPmoveFriction({\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n onGround,\n groundIsSlick: false,\n onLadder: false, // Defaulting to false for now as ladder logic is complex\n waterlevel: nextState.waterlevel,\n pmFriction: 6, // Default\n pmStopSpeed: 100, // Default\n pmWaterFriction: 1 // Default\n });\n\n // Calculate view vectors from angles\n const { forward, right } = angleVectors(nextState.viewAngles);\n\n if (nextState.pmType === PmType.NoClip) {\n // PM_NoclipMove\n // Simplified noclip\n const wishvel = {\n x: forward.x * nextState.cmd.forwardmove + right.x * nextState.cmd.sidemove,\n y: forward.y * nextState.cmd.forwardmove + right.y * nextState.cmd.sidemove,\n z: nextState.cmd.upmove\n };\n const scale = FRAMETIME; // Just move by velocity\n // Actually we need to apply velocity based on input\n // But sticking to just what's needed for jumping/movement:\n nextState.velocity = wishvel; // Simple override for noclip\n nextState.origin = {\n x: nextState.origin.x + wishvel.x * scale,\n y: nextState.origin.y + wishvel.y * scale,\n z: nextState.origin.z + wishvel.z * scale\n };\n\n } else if (nextState.waterlevel >= 2) {\n const outcome = applyPmoveWaterMove({\n origin: nextState.origin,\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: imports.trace,\n cmd: nextState.cmd,\n forward,\n right,\n pmFlags: nextState.pmFlags,\n onGround,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n pmWaterAccelerate: 4,\n pmWaterSpeed: 400,\n onLadder: false,\n watertype: nextState.watertype,\n groundContents: 0, // Should be passed in?\n waterlevel: nextState.waterlevel,\n viewPitch: nextState.viewAngles.x,\n ladderMod: 1,\n stepSize: 18 // Added stepSize for consistency, though water move might not use it heavily\n });\n nextState.origin = outcome.origin;\n nextState.velocity = outcome.velocity;\n\n } else if ((nextState.pmFlags & PmFlag.OnGround) === 0) {\n const outcome = applyPmoveAirMove({\n origin: nextState.origin,\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: imports.trace,\n cmd: nextState.cmd,\n forward,\n right,\n pmFlags: nextState.pmFlags,\n onGround,\n gravity: nextState.gravity,\n pmType: nextState.pmType,\n pmAccelerate: 10,\n pmAirAccelerate: 1,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n onLadder: false,\n waterlevel: nextState.waterlevel,\n watertype: nextState.watertype,\n groundContents: 0,\n viewPitch: nextState.viewAngles.x,\n ladderMod: 1,\n pmWaterSpeed: 400,\n stepSize: 18 // Added stepSize\n });\n nextState.origin = outcome.origin;\n nextState.velocity = outcome.velocity;\n\n } else {\n const outcome = applyPmoveWalkMove({\n origin: nextState.origin,\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: imports.trace,\n cmd: nextState.cmd,\n forward,\n right,\n pmFlags: nextState.pmFlags,\n onGround,\n gravity: nextState.gravity,\n pmType: nextState.pmType,\n pmAccelerate: 10,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n onLadder: false,\n waterlevel: nextState.waterlevel,\n watertype: nextState.watertype,\n groundContents: 0,\n viewPitch: nextState.viewAngles.x,\n ladderMod: 1,\n pmWaterSpeed: 400,\n stepSize: 18 // Added stepSize\n });\n nextState.origin = outcome.origin;\n nextState.velocity = outcome.velocity;\n }\n\n // Categorize Position again at end of frame\n const catResultEnd = categorizePosition({\n pmType: nextState.pmType,\n pmFlags: nextState.pmFlags,\n pmTime: 0,\n n64Physics: false,\n velocity: nextState.velocity,\n startVelocity: nextState.velocity,\n origin: nextState.origin,\n mins: nextState.mins,\n maxs: nextState.maxs,\n viewheight: nextState.viewHeight,\n trace: imports.trace,\n pointContents: imports.pointcontents\n });\n\n nextState.pmFlags = catResultEnd.pmFlags;\n nextState.waterlevel = catResultEnd.waterlevel;\n nextState.watertype = catResultEnd.watertype;\n\n // Update view offsets (bobbing, etc)\n // nextState = updateViewOffsets(nextState);\n\n return nextState;\n}\n","import {\n addVec3,\n lengthSquaredVec3,\n scaleVec3,\n subtractVec3,\n type Vec3,\n} from '../math/vec3.js';\nimport type { PmoveTraceResult } from './types.js';\n\nconst AXES = ['x', 'y', 'z'] as const;\ntype Axis = (typeof AXES)[number];\n\ntype AxisTuple = readonly [number, number, number];\ntype SideBoundCode = -1 | 0 | 1;\n\ninterface SideCheck {\n readonly normal: AxisTuple;\n readonly mins: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n readonly maxs: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n}\n\nconst SIDE_CHECKS: readonly SideCheck[] = [\n { normal: [0, 0, 1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [0, 0, -1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [-1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [0, 1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n { normal: [0, -1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n];\n\nexport interface FixStuckParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: FixStuckTraceFn;\n}\n\nexport type FixStuckResult = 'good-position' | 'fixed' | 'no-good-position';\n\nexport interface FixStuckOutcome {\n readonly result: FixStuckResult;\n readonly origin: Vec3;\n}\n\nexport type FixStuckTraceFn = (\n start: Vec3,\n mins: Vec3,\n maxs: Vec3,\n end: Vec3,\n) => PmoveTraceResult;\n\ninterface CandidatePosition {\n readonly distance: number;\n readonly origin: Vec3;\n}\n\nconst ZERO_VEC: Vec3 = { x: 0, y: 0, z: 0 };\n\ntype MutableVec3 = { x: number; y: number; z: number };\n\nfunction cloneMutable(vec: Vec3): MutableVec3 {\n return { x: vec.x, y: vec.y, z: vec.z };\n}\n\nfunction tupleToVec3(tuple: AxisTuple): Vec3 {\n return { x: tuple[0], y: tuple[1], z: tuple[2] };\n}\n\nfunction adjustAxis(vec: MutableVec3, axis: Axis, delta: number): void {\n if (delta === 0) return;\n switch (axis) {\n case 'x':\n vec.x += delta;\n break;\n case 'y':\n vec.y += delta;\n break;\n case 'z':\n vec.z += delta;\n break;\n }\n}\n\nfunction setAxis(vec: MutableVec3, axis: Axis, value: number): void {\n switch (axis) {\n case 'x':\n vec.x = value;\n break;\n case 'y':\n vec.y = value;\n break;\n case 'z':\n vec.z = value;\n break;\n }\n}\n\nfunction axisValue(vec: Vec3, axis: Axis): number {\n switch (axis) {\n case 'x':\n return vec.x;\n case 'y':\n return vec.y;\n case 'z':\n default:\n return vec.z;\n }\n}\n\nfunction boundValue(code: SideBoundCode, axis: Axis, mins: Vec3, maxs: Vec3): number {\n if (code === -1) {\n return axisValue(mins, axis);\n }\n if (code === 1) {\n return axisValue(maxs, axis);\n }\n return 0;\n}\n\nfunction applySideOffset(base: Vec3, side: SideCheck, mins: Vec3, maxs: Vec3): MutableVec3 {\n const result = cloneMutable(base);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n const normal = side.normal[i];\n if (normal < 0) {\n adjustAxis(result, axis, axisValue(mins, axis));\n } else if (normal > 0) {\n adjustAxis(result, axis, axisValue(maxs, axis));\n }\n }\n return result;\n}\n\nfunction buildSideBounds(side: SideCheck, mins: Vec3, maxs: Vec3): { mins: MutableVec3; maxs: MutableVec3 } {\n const localMins = cloneMutable(ZERO_VEC);\n const localMaxs = cloneMutable(ZERO_VEC);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n setAxis(localMins, axis, boundValue(side.mins[i], axis, mins, maxs));\n setAxis(localMaxs, axis, boundValue(side.maxs[i], axis, mins, maxs));\n }\n return { mins: localMins, maxs: localMaxs };\n}\n\nfunction addEpsilon(\n source: MutableVec3,\n axis: Axis | undefined,\n direction: number,\n): MutableVec3 {\n if (!axis || direction === 0) {\n return source;\n }\n const clone = cloneMutable(source);\n adjustAxis(clone, axis, direction);\n return clone;\n}\n\nfunction addEpsilonImmutable(vec: Vec3, axis: Axis | undefined, direction: number): Vec3 {\n if (!axis || direction === 0) {\n return vec;\n }\n switch (axis) {\n case 'x':\n return { ...vec, x: vec.x + direction };\n case 'y':\n return { ...vec, y: vec.y + direction };\n case 'z':\n default:\n return { ...vec, z: vec.z + direction };\n }\n}\n\n/**\n * TypeScript port of G_FixStuckObject_Generic from rerelease p_move.cpp. Attempts to\n * nudge a stuck bounding box out of solid space by probing the faces of the box and\n * moving towards the opposite side, keeping the smallest successful displacement.\n */\nexport function fixStuckObjectGeneric(params: FixStuckParams): FixStuckOutcome {\n const { origin, mins, maxs, trace } = params;\n\n const initial = trace(origin, mins, maxs, origin);\n if (!initial.startsolid) {\n return { result: 'good-position', origin: { ...origin } };\n }\n\n const candidates: CandidatePosition[] = [];\n\n for (let i = 0; i < SIDE_CHECKS.length; i++) {\n const side = SIDE_CHECKS[i];\n const { mins: localMins, maxs: localMaxs } = buildSideBounds(side, mins, maxs);\n\n let start = applySideOffset(origin, side, mins, maxs);\n let tr = trace(start, localMins, localMaxs, start);\n\n let epsilonAxis: Axis | undefined;\n let epsilonDir = 0;\n\n if (tr.startsolid) {\n for (let axisIndex = 0; axisIndex < AXES.length; axisIndex++) {\n if (side.normal[axisIndex] !== 0) {\n continue;\n }\n const axis = AXES[axisIndex];\n let epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, 1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = 1;\n break;\n }\n epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, -1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = -1;\n break;\n }\n }\n }\n\n if (tr.startsolid) {\n continue;\n }\n\n const otherSide = SIDE_CHECKS[i ^ 1];\n let oppositeStart = applySideOffset(origin, otherSide, mins, maxs);\n oppositeStart = addEpsilon(oppositeStart, epsilonAxis, epsilonDir);\n\n tr = trace(start, localMins, localMaxs, oppositeStart);\n if (tr.startsolid) {\n continue;\n }\n\n const normal = tupleToVec3(side.normal);\n const end = addVec3(tr.endpos ?? oppositeStart, scaleVec3(normal, 0.125));\n const delta = subtractVec3(end, oppositeStart);\n let newOrigin = addVec3(origin, delta);\n newOrigin = addEpsilonImmutable(newOrigin, epsilonAxis, epsilonDir);\n\n const validation = trace(newOrigin, mins, maxs, newOrigin);\n if (validation.startsolid) {\n continue;\n }\n\n candidates.push({ origin: newOrigin, distance: lengthSquaredVec3(delta) });\n }\n\n if (candidates.length === 0) {\n return { result: 'no-good-position', origin: { ...origin } };\n }\n\n candidates.sort((a, b) => a.distance - b.distance);\n return { result: 'fixed', origin: { ...candidates[0].origin } };\n}\n","import { addVec3, lengthVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from './constants.js';\nimport { applyPmoveAccelerate } from './pmove.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nconst FLY_FRICTION_MULTIPLIER = 1.5;\nconst BUTTON_VERTICAL_SCALE = 0.5;\nconst DEFAULT_OVERBOUNCE = 1.01;\n\nexport interface FlyMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly frametime: number;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly pmMaxSpeed: number;\n readonly pmAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly doclip: boolean;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly trace?: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport type FlyMoveResult = StepSlideMoveOutcome;\n\n/**\n * Pure translation of PM_FlyMove from rerelease `p_move.cpp`: applies the\n * spectator/noclip friction and acceleration rules, then either advances the\n * origin freely or resolves movement through `stepSlideMove` when clipping is\n * requested. This keeps the spectator and noclip physics deterministic between\n * the client and server.\n */\nexport function applyPmoveFlyMove(params: FlyMoveParams): FlyMoveResult {\n const {\n origin,\n cmd,\n frametime,\n pmFriction,\n pmStopSpeed,\n pmMaxSpeed,\n pmAccelerate,\n pmWaterSpeed,\n doclip,\n forward,\n right,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n let velocity = applyFlyFriction({ velocity: params.velocity, pmFriction, pmStopSpeed, frametime });\n\n const wishdirVelocity = buildFlyWishVelocity({\n cmd,\n forward,\n right,\n pmMaxSpeed,\n pmWaterSpeed,\n });\n\n if (wishdirVelocity.wishspeed > 0) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wishdirVelocity.wishdir,\n wishspeed: wishdirVelocity.accelSpeed,\n accel: pmAccelerate,\n frametime,\n });\n }\n\n if (!doclip) {\n const originDelta = scaleVec3(velocity, frametime);\n const nextOrigin = addVec3(origin, originDelta);\n return {\n origin: nextOrigin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: velocity.x === 0 && velocity.y === 0 && velocity.z === 0,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n if (!trace || !mins || !maxs) {\n throw new Error('applyPmoveFlyMove: doclip=true requires trace/mins/maxs');\n }\n\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n overbounce,\n trace,\n mins,\n maxs,\n stepSize,\n maxBumps,\n maxClipPlanes,\n });\n}\n\ninterface FlyFrictionParams {\n readonly velocity: Vec3;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly frametime: number;\n}\n\nfunction applyFlyFriction(params: FlyFrictionParams): Vec3 {\n const { velocity, pmFriction, pmStopSpeed, frametime } = params;\n const speed = lengthVec3(velocity);\n\n if (speed < 1) {\n return { x: 0, y: 0, z: 0 };\n }\n\n const friction = pmFriction * FLY_FRICTION_MULTIPLIER;\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const drop = control * friction * frametime;\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n return scaleVec3(velocity, newspeed / speed);\n}\n\ninterface FlyWishVelocityParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmMaxSpeed: number;\n readonly pmWaterSpeed: number;\n}\n\ninterface FlyWishVelocityResult {\n readonly wishdir: Vec3;\n readonly wishspeed: number;\n readonly accelSpeed: number;\n}\n\nfunction buildFlyWishVelocity(params: FlyWishVelocityParams): FlyWishVelocityResult {\n const { cmd, forward, right, pmMaxSpeed, pmWaterSpeed } = params;\n\n const forwardNorm = normalizeVec3(forward);\n const rightNorm = normalizeVec3(right);\n\n const wishvel = {\n x: forwardNorm.x * cmd.forwardmove + rightNorm.x * cmd.sidemove,\n y: forwardNorm.y * cmd.forwardmove + rightNorm.y * cmd.sidemove,\n z: forwardNorm.z * cmd.forwardmove + rightNorm.z * cmd.sidemove,\n } satisfies Vec3;\n\n let adjusted = wishvel;\n const buttons = cmd.buttons ?? 0;\n\n if (buttons & PlayerButton.Jump) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n if (buttons & PlayerButton.Crouch) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: -pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n let wishspeed = lengthVec3(adjusted);\n let wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n adjusted = scaleVec3(adjusted, scale);\n wishspeed = pmMaxSpeed;\n wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n }\n\n const accelSpeed = wishspeed * 2;\n\n return { wishdir, wishspeed, accelSpeed };\n}\n","import { CONTENTS_LADDER, CONTENTS_NONE, CONTENTS_NO_WATERJUMP } from '../bsp/contents.js';\nimport { addVec3, lengthSquaredVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, PmFlag, type PmFlags, addPmFlag, removePmFlag, WaterLevel } from './constants.js';\nimport { stepSlideMove } from './slide.js';\nimport type { PmoveCmd, PmovePointContentsFn, PmoveTraceFn } from './types.js';\nimport { getWaterLevel } from './water.js';\n\nconst LADDER_TRACE_DISTANCE = 1;\nconst WATERJUMP_FORWARD_CHECK = 40;\nconst WATERJUMP_FORWARD_SPEED = 50;\nconst WATERJUMP_UPWARD_SPEED = 350;\nconst WATERJUMP_PM_TIME = 2048;\nconst WATERJUMP_SIM_STEP = 0.1;\nconst WATERJUMP_BASE_GRAVITY = 800;\nconst WATERJUMP_MAX_STEPS = 50;\nconst GROUND_NORMAL_THRESHOLD = 0.7;\nconst WATERJUMP_STEP_TOLERANCE = 18;\nconst DEFAULT_OVERBOUNCE = 1.01;\nconst WATERJUMP_DOWN_PROBE = 2;\n\nexport interface SpecialMovementParams {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly gravity: number;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n readonly onGround: boolean;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport interface SpecialMovementResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly velocity: Vec3;\n readonly performedWaterJump: boolean;\n}\n\n/**\n * Mirrors the ladder detection and water-jump probing logic from\n * `PM_CheckSpecialMovement` in `rerelease/p_move.cpp`. The helper clears and\n * re-adds the ladder flag based on nearby CONTENTS_LADDER brushes, then\n * simulates a potential water jump by firing the same 40-unit probe and\n * step-slide loop the C++ uses before committing to the upward velocity.\n */\nexport function checkSpecialMovement(params: SpecialMovementParams): SpecialMovementResult {\n const {\n pmFlags: initialFlags,\n pmTime: initialPmTime,\n waterlevel,\n watertype,\n gravity,\n cmd,\n forward,\n origin,\n velocity: initialVelocity,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n onGround,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize = WATERJUMP_STEP_TOLERANCE,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n if (initialPmTime > 0) {\n return { pmFlags: initialFlags, pmTime: initialPmTime, velocity: initialVelocity, performedWaterJump: false };\n }\n\n let pmFlags = removePmFlag(initialFlags, PmFlag.OnLadder);\n let pmTime = initialPmTime;\n let velocity = initialVelocity;\n\n const flatforward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n const hasForward = lengthSquaredVec3(flatforward) > 0;\n\n if (waterlevel < WaterLevel.Waist && hasForward) {\n const ladderEnd = addVec3(origin, scaleVec3(flatforward, LADDER_TRACE_DISTANCE));\n const ladderTrace = trace(origin, ladderEnd, mins, maxs);\n const contents = ladderTrace.contents ?? CONTENTS_NONE;\n\n if (ladderTrace.fraction < 1 && (contents & CONTENTS_LADDER) !== 0) {\n pmFlags = addPmFlag(pmFlags, PmFlag.OnLadder);\n }\n }\n\n if (gravity === 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (((cmd.buttons ?? 0) & PlayerButton.Jump) === 0 && cmd.forwardmove <= 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (waterlevel !== WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if ((watertype & CONTENTS_NO_WATERJUMP) !== 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (!hasForward) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const forwardCheckEnd = addVec3(origin, scaleVec3(flatforward, WATERJUMP_FORWARD_CHECK));\n const forwardTrace = trace(origin, forwardCheckEnd, mins, maxs);\n\n if (\n forwardTrace.fraction === 1 ||\n !forwardTrace.planeNormal ||\n forwardTrace.planeNormal.z >= GROUND_NORMAL_THRESHOLD\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n let simVelocity: Vec3 = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n };\n\n let simOrigin = origin;\n let hasTime = true;\n const stepCount = computeWaterJumpSteps(gravity);\n\n for (let i = 0; i < stepCount; i++) {\n simVelocity = { x: simVelocity.x, y: simVelocity.y, z: simVelocity.z - gravity * WATERJUMP_SIM_STEP };\n if (simVelocity.z < 0) {\n hasTime = false;\n }\n\n const move = stepSlideMove({\n origin: simOrigin,\n velocity: simVelocity,\n frametime: WATERJUMP_SIM_STEP,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n simOrigin = move.origin;\n simVelocity = move.velocity;\n }\n\n const downEnd = addVec3(simOrigin, { x: 0, y: 0, z: -WATERJUMP_DOWN_PROBE });\n const downTrace = trace(simOrigin, downEnd, mins, maxs);\n\n if (\n downTrace.fraction === 1 ||\n !downTrace.planeNormal ||\n downTrace.planeNormal.z < GROUND_NORMAL_THRESHOLD ||\n downTrace.endpos.z < origin.z\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (onGround && Math.abs(origin.z - downTrace.endpos.z) <= stepSize) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const landingWater = getWaterLevel({ origin: downTrace.endpos, mins, viewheight, pointContents });\n if (landingWater.waterlevel >= WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeWaterJump);\n pmTime = WATERJUMP_PM_TIME;\n velocity = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n } satisfies Vec3;\n\n return { pmFlags, pmTime, velocity, performedWaterJump: true };\n}\n\nfunction computeWaterJumpSteps(gravity: number): number {\n if (gravity === 0) {\n return 0;\n }\n\n const scaled = Math.floor(10 * (WATERJUMP_BASE_GRAVITY / gravity));\n if (scaled <= 0) {\n return 0;\n }\n return Math.min(WATERJUMP_MAX_STEPS, scaled);\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { fixStuckObjectGeneric } from './stuck.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst SNAP_OFFSETS = [0, -1, 1] as const;\n\nexport interface GoodPositionParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nexport function goodPosition(params: GoodPositionParams): boolean {\n const { origin, mins, maxs, trace } = params;\n const result = trace(origin, origin, mins, maxs);\n return result.allsolid ? false : true;\n}\n\nexport type SnapResolution = 'unchanged' | 'fixed' | 'reverted';\n\nexport interface SnapPositionParams extends GoodPositionParams {\n readonly velocity: Vec3;\n readonly previousOrigin: Vec3;\n}\n\nexport interface SnapPositionResult {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly resolution: SnapResolution;\n}\n\n/**\n * Pure translation of PM_SnapPosition from rerelease `p_move.cpp`.\n * Attempts to keep the caller's origin in a valid location by first\n * checking the current origin against collision traces, then falling\n * back to the shared `fixStuckObjectGeneric` helper before finally\n * reverting to the provided previous origin when no fix is possible.\n */\nexport function snapPosition(params: SnapPositionParams): SnapPositionResult {\n const { origin, velocity, mins, maxs, previousOrigin, trace } = params;\n\n if (goodPosition({ origin, mins, maxs, trace })) {\n return { origin: { ...origin }, velocity: { ...velocity }, resolution: 'unchanged' };\n }\n\n const fix = fixStuckObjectGeneric({\n origin,\n mins,\n maxs,\n trace: (start, localMins, localMaxs, end) => trace(start, end, localMins, localMaxs),\n });\n\n if (fix.result === 'fixed' || fix.result === 'good-position') {\n return { origin: fix.origin, velocity: { ...velocity }, resolution: 'fixed' };\n }\n\n return { origin: { ...previousOrigin }, velocity: { ...velocity }, resolution: 'reverted' };\n}\n\nexport interface InitialSnapPositionParams extends GoodPositionParams {}\n\nexport interface InitialSnapPositionResult {\n readonly origin: Vec3;\n readonly snapped: boolean;\n}\n\n/**\n * Pure translation of PM_InitialSnapPosition from rerelease `p_move.cpp`.\n * Tries a 3x3x3 grid of +/-1 unit offsets around the base origin to find\n * a valid collision-free spot, mirroring the search order of the C++ code.\n */\nexport function initialSnapPosition(params: InitialSnapPositionParams): InitialSnapPositionResult {\n const { origin, mins, maxs, trace } = params;\n\n for (const oz of SNAP_OFFSETS) {\n for (const oy of SNAP_OFFSETS) {\n for (const ox of SNAP_OFFSETS) {\n const candidate = { x: origin.x + ox, y: origin.y + oy, z: origin.z + oz } satisfies Vec3;\n if (goodPosition({ origin: candidate, mins, maxs, trace })) {\n const snapped = ox !== 0 || oy !== 0 || oz !== 0;\n return { origin: candidate, snapped };\n }\n }\n }\n }\n\n return { origin: { ...origin }, snapped: false };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { angleVectors, type AngleVectorsResult } from '../math/angles.js';\nimport { PmFlag, type PmFlags } from './constants.js';\n\nexport interface ClampViewAnglesParams {\n readonly pmFlags: PmFlags;\n readonly cmdAngles: Vec3;\n readonly deltaAngles: Vec3;\n}\n\nexport interface ClampViewAnglesResult extends AngleVectorsResult {\n readonly viewangles: Vec3;\n}\n\nfunction addAngles(cmdAngles: Vec3, deltaAngles: Vec3): Vec3 {\n return {\n x: cmdAngles.x + deltaAngles.x,\n y: cmdAngles.y + deltaAngles.y,\n z: cmdAngles.z + deltaAngles.z,\n } satisfies Vec3;\n}\n\nfunction clampPitch(pitch: number): number {\n if (pitch > 89 && pitch < 180) {\n return 89;\n }\n if (pitch < 271 && pitch >= 180) {\n return 271;\n }\n return pitch;\n}\n\n/**\n * Pure translation of `PM_ClampAngles` from `rerelease/p_move.cpp`. The helper\n * fuses the latest command angles with the stored delta, applies the teleport\n * pitch/roll reset, enforces the ±90° pitch window, and returns the resulting\n * axis vectors that the C version stored in `pml.forward/right/up`.\n */\nexport function clampViewAngles(params: ClampViewAnglesParams): ClampViewAnglesResult {\n const { pmFlags, cmdAngles, deltaAngles } = params;\n\n let viewangles: Vec3;\n\n if ((pmFlags & PmFlag.TimeTeleport) !== 0) {\n viewangles = {\n x: 0,\n y: cmdAngles.y + deltaAngles.y,\n z: 0,\n } satisfies Vec3;\n } else {\n viewangles = addAngles(cmdAngles, deltaAngles);\n viewangles = { ...viewangles, x: clampPitch(viewangles.x) };\n }\n\n const vectors = angleVectors(viewangles);\n return { viewangles, ...vectors };\n}\n","import { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n readonly sequence: number;\n readonly lightlevel: number;\n readonly impulse: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\n}\n","\nexport enum ServerCommand {\n bad = 0,\n\n // these ops are known to the game dll\n muzzleflash = 1,\n muzzleflash2 = 2,\n temp_entity = 3,\n layout = 4,\n inventory = 5,\n\n // the rest are private to the client and server\n nop = 6,\n disconnect = 7,\n reconnect = 8,\n sound = 9, // <see code>\n print = 10, // [byte] id [string] null terminated string\n stufftext = 11, // [string] stuffed into client's console buffer, should be \\n terminated\n serverdata = 12, // [long] protocol ...\n configstring = 13, // [short] [string]\n spawnbaseline = 14,\n centerprint = 15, // [string] to put in center of the screen\n download = 16, // [short] size [size bytes]\n playerinfo = 17, // variable\n packetentities = 18, // [...]\n deltapacketentities = 19, // [...]\n frame = 20,\n splitclient = 21,\n configblast = 22,\n spawnbaselineblast = 23,\n level_restart = 24,\n damage = 25,\n locprint = 26,\n fog = 27,\n waitingforplayers = 28,\n bot_chat = 29,\n poi = 30,\n help_path = 31,\n muzzleflash3 = 32,\n achievement = 33\n}\n\nexport enum ClientCommand {\n bad = 0,\n nop = 1,\n move = 2, // [[usercmd_t]\n userinfo = 3, // [[userinfo string]\n stringcmd = 4 // [string] message\n}\n","\n// Temp entity constants from Quake 2\nexport enum TempEntity {\n GUNSHOT = 0,\n BLOOD = 1,\n BLASTER = 2,\n RAILTRAIL = 3,\n SHOTGUN = 4,\n EXPLOSION1 = 5,\n EXPLOSION2 = 6,\n ROCKET_EXPLOSION = 7,\n GRENADE_EXPLOSION = 8,\n SPARKS = 9,\n SPLASH = 10,\n BUBBLETRAIL = 11,\n SCREEN_SPARKS = 12,\n SHIELD_SPARKS = 13,\n BULLET_SPARKS = 14,\n LASER_SPARKS = 15,\n PARASITE_ATTACK = 16,\n ROCKET_EXPLOSION_WATER = 17,\n GRENADE_EXPLOSION_WATER = 18,\n MEDIC_CABLE_ATTACK = 19,\n BFG_EXPLOSION = 20,\n BFG_BIGEXPLOSION = 21,\n BOSSTPORT = 22,\n BFG_LASER = 23,\n GRAPPLE_CABLE = 24,\n WELDING_SPARKS = 25,\n GREENBLOOD = 26,\n BLUEHYPERBLASTER = 27,\n PLASMA_EXPLOSION = 28,\n TUNNEL_SPARKS = 29,\n // ROGUE\n BLASTER2 = 30,\n RAILTRAIL2 = 31,\n FLAME = 32,\n LIGHTNING = 33,\n DEBUGTRAIL = 34,\n PLAIN_EXPLOSION = 35,\n FLASHLIGHT = 36,\n FORCEWALL = 37,\n HEATBEAM = 38,\n MONSTER_HEATBEAM = 39,\n STEAM = 40,\n BUBBLETRAIL2 = 41,\n MOREBLOOD = 42,\n HEATBEAM_SPARKS = 43,\n HEATBEAM_STEAM = 44,\n CHAINFIST_SMOKE = 45,\n ELECTRIC_SPARKS = 46,\n TRACKER_EXPLOSION = 47,\n TELEPORT_EFFECT = 48,\n DBALL_GOAL = 49,\n WIDOWBEAMOUT = 50,\n NUKEBLAST = 51,\n WIDOWSPLASH = 52,\n EXPLOSION1_BIG = 53,\n EXPLOSION1_NP = 54,\n FLECHETTE = 55,\n BLUEHYPERBLASTER_KEX = 56,\n BFG_ZAP = 57,\n BERSERK_SLAM = 58,\n GRAPPLE_CABLE_2 = 59,\n POWER_SPLASH = 60,\n LIGHTNING_BEAM = 61,\n EXPLOSION1_NL = 62,\n EXPLOSION2_NL = 63\n}\n","\nexport const MAX_CHALLENGES = 1024;\nexport const MAX_PACKET_ENTITIES = 256; // Standard Q2 value\nexport const UPDATE_BACKUP = 16;\nexport const CMD_BACKUP = 64;\nexport const MAX_INFO_STRING = 512;\nexport const MAX_MSGLEN = 1400; // MTU safe limit\n\n// Muzzle Flash Constants\nexport const MZ_BLASTER = 0;\nexport const MZ_MACHINEGUN = 1;\nexport const MZ_SHOTGUN = 2;\nexport const MZ_CHAINGUN1 = 3;\nexport const MZ_CHAINGUN2 = 4;\nexport const MZ_CHAINGUN3 = 5;\nexport const MZ_RAILGUN = 6;\nexport const MZ_ROCKET = 7;\nexport const MZ_GRENADE = 8;\nexport const MZ_LOGIN = 9;\nexport const MZ_LOGOUT = 10;\nexport const MZ_SSHOTGUN = 11;\nexport const MZ_BFG = 12;\nexport const MZ_HYPERBLASTER = 13;\n\n// Xatrix / Rogue Extensions\nexport const MZ_IONRIPPER = 16;\nexport const MZ_BLUEHYPERBLASTER = 17;\nexport const MZ_PHALANX = 18;\nexport const MZ_BFG2 = 19;\nexport const MZ_PHALANX2 = 20;\nexport const MZ_ETF_RIFLE = 30;\nexport const MZ_PROX = 31;\nexport const MZ_ETF_RIFLE_2 = 32;\nexport const MZ_HEATBEAM = 33;\nexport const MZ_BLASTER2 = 34;\nexport const MZ_TRACKER = 35;\nexport const MZ_NUKE1 = 36;\nexport const MZ_NUKE2 = 37;\nexport const MZ_NUKE4 = 38;\nexport const MZ_NUKE8 = 39;\n","// Matching rerelease/game.h:1584-1593\nexport enum LayoutFlags {\n LAYOUTS_LAYOUT = 1,\n LAYOUTS_INVENTORY = 2,\n LAYOUTS_HIDE_HUD = 4,\n LAYOUTS_INTERMISSION = 8,\n LAYOUTS_HELP = 16,\n LAYOUTS_HIDE_CROSSHAIR = 32\n}\n","\n/**\n * Helper to force a number into a signed 16-bit integer range (-32768 to 32767).\n * This mimics the behavior of casting to `short` in C++.\n */\nfunction toSigned16(val: number): number {\n return (val << 16) >> 16;\n}\n\n/**\n * Reads a 16-bit integer (unsigned) from the stats array at the given byte offset.\n * Mimics reading `*(uint16_t*)((uint8_t*)stats + byteOffset)` in Little Endian.\n */\nfunction readUint16LE(stats: number[], startIndex: number, byteOffset: number): number {\n // Determine which element(s) of the array we are accessing\n // stats is int16[], so each element is 2 bytes.\n // absolute byte offset from stats[startIndex]\n const elementIndex = Math.floor(byteOffset / 2);\n const isOdd = (byteOffset % 2) !== 0;\n\n // Access the array at the calculated index relative to startIndex\n const index = startIndex + elementIndex;\n\n // Read the primary element\n const val0 = stats[index] || 0; // Handle potentially undefined/uninitialized slots as 0\n\n if (!isOdd) {\n // Aligned access: just return the element as uint16\n return val0 & 0xFFFF;\n } else {\n // Unaligned access: High byte of val0 + Low byte of val1\n const val1 = stats[index + 1] || 0;\n\n // Low byte of result comes from High byte of val0\n const low = (val0 >>> 8) & 0xFF;\n // High byte of result comes from Low byte of val1\n const high = val1 & 0xFF;\n\n return (high << 8) | low;\n }\n}\n\n/**\n * Writes a 16-bit integer to the stats array at the given byte offset.\n * Mimics writing `*(uint16_t*)((uint8_t*)stats + byteOffset) = value` in Little Endian.\n */\nfunction writeUint16LE(stats: number[], startIndex: number, byteOffset: number, value: number): void {\n const elementIndex = Math.floor(byteOffset / 2);\n const isOdd = (byteOffset % 2) !== 0;\n const index = startIndex + elementIndex;\n\n // Ensure array has values at these indices to avoid NaN math\n if (stats[index] === undefined) stats[index] = 0;\n\n if (!isOdd) {\n // Aligned access: overwrite the element\n stats[index] = toSigned16(value);\n } else {\n // Unaligned access\n if (stats[index + 1] === undefined) stats[index + 1] = 0;\n\n const val0 = stats[index];\n const val1 = stats[index + 1];\n\n // We want to write `value` (which is Low byte `L_v` and High byte `H_v`)\n // into the bytes at `byteOffset` and `byteOffset + 1`.\n\n // Byte at `byteOffset` corresponds to High byte of `stats[index]`.\n // It should become `value & 0xFF` (L_v).\n // So `stats[index]` becomes `(Old_Low) | (L_v << 8)`.\n const newHigh0 = value & 0xFF;\n const newVal0 = (val0 & 0xFF) | (newHigh0 << 8);\n stats[index] = toSigned16(newVal0);\n\n // Byte at `byteOffset + 1` corresponds to Low byte of `stats[index+1]`.\n // It should become `(value >> 8) & 0xFF` (H_v).\n // So `stats[index+1]` becomes `(H_v) | (Old_High << 8)`.\n const newLow1 = (value >>> 8) & 0xFF;\n const newVal1 = newLow1 | (val1 & 0xFF00);\n stats[index + 1] = toSigned16(newVal1);\n }\n}\n\n/**\n * Packs a value into the stats array using a specific bit width.\n * Equivalent to C++ `set_compressed_integer`.\n *\n * @param stats The stats array (number[] representing int16s)\n * @param startIndex The index in the stats array where the packed region begins (e.g. STAT_AMMO_INFO_START)\n * @param id The ID of the item to set (0-based index within the packed region)\n * @param count The value to set\n * @param bitsPerValue Number of bits per item (e.g. 9 for ammo, 2 for powerups)\n */\nexport function setCompressedInteger(\n stats: number[],\n startIndex: number,\n id: number,\n count: number,\n bitsPerValue: number\n): void {\n const bitOffset = bitsPerValue * id;\n const byteOffset = Math.floor(bitOffset / 8);\n const bitShift = bitOffset % 8;\n const mask = ((1 << bitsPerValue) - 1) << bitShift;\n\n // Read the 16-bit word at the target byte address\n let base = readUint16LE(stats, startIndex, byteOffset);\n\n // Apply the mask and value\n // Note: (count << bitShift) might overflow 16 bits if we aren't careful,\n // but the mask will handle the high bits.\n // However, in JS, bitwise ops are 32-bit.\n // We need to ensure we only write back 16 bits.\n\n const valueToWrite = (base & ~mask) | ((count << bitShift) & mask);\n\n // Write the modified 16-bit word back\n writeUint16LE(stats, startIndex, byteOffset, valueToWrite & 0xFFFF);\n}\n\n/**\n * Unpacks a value from the stats array.\n * Equivalent to C++ `get_compressed_integer`.\n */\nexport function getCompressedInteger(\n stats: number[],\n startIndex: number,\n id: number,\n bitsPerValue: number\n): number {\n const bitOffset = bitsPerValue * id;\n const byteOffset = Math.floor(bitOffset / 8);\n const bitShift = bitOffset % 8;\n const mask = ((1 << bitsPerValue) - 1) << bitShift;\n\n const base = readUint16LE(stats, startIndex, byteOffset);\n\n return (base & mask) >>> bitShift;\n}\n","/**\n * Powerup identifiers shared across game and cgame.\n * Reference: rerelease/g_items.cpp, game/src/inventory/playerInventory.ts\n */\n\nexport enum PowerupId {\n QuadDamage = 'quad',\n Invulnerability = 'invulnerability',\n EnviroSuit = 'enviro_suit',\n Rebreather = 'rebreather',\n Silencer = 'silencer',\n // New additions for demo playback and extended support\n PowerScreen = 'power_screen',\n PowerShield = 'power_shield',\n QuadFire = 'quad_fire',\n Invisibility = 'invisibility',\n Bandolier = 'bandolier',\n AmmoPack = 'ammo_pack',\n IRGoggles = 'ir_goggles',\n DoubleDamage = 'double_damage',\n SphereVengeance = 'sphere_vengeance',\n SphereHunter = 'sphere_hunter',\n SphereDefender = 'sphere_defender',\n Doppelganger = 'doppelganger',\n TagToken = 'tag_token',\n TechResistance = 'tech_resistance',\n TechStrength = 'tech_strength',\n TechHaste = 'tech_haste',\n TechRegeneration = 'tech_regeneration',\n Flashlight = 'flashlight',\n Compass = 'compass',\n}\n","import { setCompressedInteger, getCompressedInteger } from './bitpack.js';\nimport { PowerupId } from '../items/powerups.js';\n\n// Matching rerelease/bg_local.h:196-262\nexport enum PlayerStat {\n STAT_HEALTH_ICON = 0,\n STAT_HEALTH,\n STAT_AMMO_ICON,\n STAT_AMMO,\n STAT_ARMOR_ICON,\n STAT_ARMOR,\n STAT_SELECTED_ICON,\n STAT_PICKUP_ICON,\n STAT_PICKUP_STRING,\n STAT_TIMER_ICON,\n STAT_TIMER,\n STAT_HELPICON,\n STAT_SELECTED_ITEM,\n STAT_LAYOUTS,\n STAT_FRAGS,\n STAT_FLASHES,\n STAT_CHASE,\n STAT_SPECTATOR,\n\n // CTF Stats (Rerelease/KEX)\n STAT_CTF_TEAM1_PIC = 18,\n STAT_CTF_TEAM1_CAPS = 19,\n STAT_CTF_TEAM2_PIC = 20,\n STAT_CTF_TEAM2_CAPS = 21,\n STAT_CTF_FLAG_PIC = 22,\n STAT_CTF_JOINED_TEAM1_PIC = 23,\n STAT_CTF_JOINED_TEAM2_PIC = 24,\n STAT_CTF_TEAM1_HEADER = 25,\n STAT_CTF_TEAM2_HEADER = 26,\n STAT_CTF_TECH = 27,\n STAT_CTF_ID_VIEW = 28,\n STAT_CTF_MATCH = 29,\n STAT_CTF_ID_VIEW_COLOR = 30,\n STAT_CTF_TEAMINFO = 31,\n\n // Rerelease additions\n STAT_WEAPONS_OWNED_1 = 32,\n STAT_WEAPONS_OWNED_2 = 33,\n\n // Ammo counts (start index)\n STAT_AMMO_INFO_START = 34,\n // Calculated below, but enum needs literal or constant if we want to use it as type.\n // However, for TS Enum, we can just define start.\n\n // Powerups start after Ammo.\n // AMMO_MAX=12, 9 bits each -> 108 bits -> 7 int16s.\n // 34 + 7 = 41.\n STAT_POWERUP_INFO_START = 41,\n\n // Keys and other KEX stats (Start after Powerups)\n // POWERUP_MAX=23, 2 bits each -> 46 bits -> 3 int16s.\n // 41 + 3 = 44.\n STAT_KEY_A = 44,\n STAT_KEY_B = 45,\n STAT_KEY_C = 46,\n\n STAT_ACTIVE_WHEEL_WEAPON = 47,\n STAT_COOP_RESPAWN = 48,\n STAT_LIVES = 49,\n STAT_HIT_MARKER = 50,\n STAT_SELECTED_ITEM_NAME = 51,\n STAT_HEALTH_BARS = 52,\n STAT_ACTIVE_WEAPON = 53,\n\n STAT_LAST\n}\n\n// Constants for bit packing logic\nexport const AMMO_MAX = 12;\nexport const NUM_BITS_FOR_AMMO = 9;\nexport const NUM_AMMO_STATS = Math.ceil((AMMO_MAX * NUM_BITS_FOR_AMMO) / 16); // 7\n\nexport const POWERUP_MAX = 23; // Adjusted to include TechRegeneration (index 22)\nexport const NUM_BITS_FOR_POWERUP = 2;\nexport const NUM_POWERUP_STATS = Math.ceil((POWERUP_MAX * NUM_BITS_FOR_POWERUP) / 16); // 3\n\n// Powerup ID mapping from string to C++ integer index (powerup_t in bg_local.h)\nconst POWERUP_STAT_MAP: Partial<Record<PowerupId, number>> = {\n [PowerupId.PowerScreen]: 0,\n [PowerupId.PowerShield]: 1,\n // 2 is POWERUP_AM_BOMB (not in PowerupId?)\n [PowerupId.QuadDamage]: 3,\n [PowerupId.QuadFire]: 4,\n [PowerupId.Invulnerability]: 5,\n [PowerupId.Invisibility]: 6,\n [PowerupId.Silencer]: 7,\n [PowerupId.Rebreather]: 8,\n [PowerupId.EnviroSuit]: 9,\n [PowerupId.Bandolier]: 10, // Placeholder/Map mismatch handling?\n [PowerupId.AmmoPack]: 10, // Original reused indices or had gaps?\n [PowerupId.IRGoggles]: 11,\n [PowerupId.DoubleDamage]: 12,\n [PowerupId.SphereVengeance]: 13,\n [PowerupId.SphereHunter]: 14,\n [PowerupId.SphereDefender]: 15,\n [PowerupId.Doppelganger]: 16,\n [PowerupId.Flashlight]: 17,\n [PowerupId.Compass]: 18,\n [PowerupId.TechResistance]: 19,\n [PowerupId.TechStrength]: 20,\n [PowerupId.TechHaste]: 21,\n [PowerupId.TechRegeneration]: 22,\n // Add missing mappings to avoid runtime lookups failing for new types\n [PowerupId.TagToken]: -1,\n};\n\n// 9 bits for ammo count\nexport function G_SetAmmoStat(stats: number[], ammoId: number, count: number): void {\n if (ammoId < 0 || ammoId >= AMMO_MAX) return;\n\n // Clamp count to 9 bits (0-511)\n let val = count;\n if (val > 511) val = 511;\n if (val < 0) val = 0;\n\n setCompressedInteger(stats, PlayerStat.STAT_AMMO_INFO_START, ammoId, val, NUM_BITS_FOR_AMMO);\n}\n\nexport function G_GetAmmoStat(stats: number[], ammoId: number): number {\n if (ammoId < 0 || ammoId >= AMMO_MAX) return 0;\n return getCompressedInteger(stats, PlayerStat.STAT_AMMO_INFO_START, ammoId, NUM_BITS_FOR_AMMO);\n}\n\n// 2 bits for powerup active/inactive state\nexport function G_SetPowerupStat(stats: number[], powerupId: PowerupId | number, val: number): void {\n let index: number | undefined;\n\n if (typeof powerupId === 'number') {\n index = powerupId;\n } else {\n index = POWERUP_STAT_MAP[powerupId];\n }\n\n if (index === undefined || index < 0 || index >= POWERUP_MAX) return;\n\n // Clamp value to 2 bits (0-3)\n let safeVal = val;\n if (safeVal > 3) safeVal = 3;\n if (safeVal < 0) safeVal = 0;\n\n setCompressedInteger(stats, PlayerStat.STAT_POWERUP_INFO_START, index, safeVal, NUM_BITS_FOR_POWERUP);\n}\n\nexport function G_GetPowerupStat(stats: number[], powerupId: PowerupId | number): number {\n let index: number | undefined;\n\n if (typeof powerupId === 'number') {\n index = powerupId;\n } else {\n index = POWERUP_STAT_MAP[powerupId];\n }\n\n if (index === undefined || index < 0 || index >= POWERUP_MAX) return 0;\n\n return getCompressedInteger(stats, PlayerStat.STAT_POWERUP_INFO_START, index, NUM_BITS_FOR_POWERUP);\n}\n","import { BinaryWriter } from '../io/binaryWriter.js';\nimport { UserCommand } from './usercmd.js';\n\nexport function writeUserCommand(writer: BinaryWriter, cmd: UserCommand): void {\n // msec (byte)\n writer.writeByte(cmd.msec);\n\n // buttons (byte)\n writer.writeByte(cmd.buttons);\n\n // angles (short * 3) - Scaled 360 -> 65536\n writer.writeAngle16(cmd.angles.x);\n writer.writeAngle16(cmd.angles.y);\n writer.writeAngle16(cmd.angles.z);\n\n // forwardmove (short)\n writer.writeShort(cmd.forwardmove);\n\n // sidemove (short)\n writer.writeShort(cmd.sidemove);\n\n // upmove (short)\n writer.writeShort(cmd.upmove);\n\n // impulse (byte)\n writer.writeByte(cmd.impulse);\n\n // lightlevel (byte)\n writer.writeByte(0); // TODO: Lightlevel\n}\n","export enum RenderFx {\n MinLight = 1,\n ViewerModel = 2,\n WeaponModel = 4,\n FullBright = 8,\n DepthHack = 16,\n Translucent = 32,\n FrameLerp = 64,\n Beam = 128,\n CustomLight = 256,\n Glow = 512,\n ShellRed = 1024,\n ShellGreen = 2048,\n ShellBlue = 4096,\n IrVisible = 32768,\n ShellDouble = 65536,\n ShellHalfDam = 131072,\n MinLightPlus = 262144,\n ExtraLight = 524288,\n BeamLightning = 1048576,\n Flashlight = 2097152, // 1 << 21\n}\n","// Quake 2 CRC implementation\n// Ported from qcommon/crc.c\n\nconst crc_table: number[] = [\n 0x00, 0x91, 0xe3, 0x72, 0x07, 0x96, 0xe4, 0x75, 0x0e, 0x9f, 0xed, 0x7c, 0x09, 0x98, 0xea, 0x7b,\n 0x1c, 0x8d, 0xff, 0x6e, 0x1b, 0x8a, 0xf8, 0x69, 0x12, 0x83, 0xf1, 0x60, 0x15, 0x84, 0xf6, 0x67,\n 0x38, 0xa9, 0xdb, 0x4a, 0x3f, 0xae, 0xdc, 0x4d, 0x36, 0xa7, 0xd5, 0x44, 0x31, 0xa0, 0xd2, 0x43,\n 0x24, 0xb5, 0xc7, 0x56, 0x23, 0xb2, 0xc0, 0x51, 0x2a, 0xbb, 0xc9, 0x58, 0x2d, 0xbc, 0xce, 0x5f,\n 0x70, 0xe1, 0x93, 0x02, 0x77, 0xe6, 0x94, 0x05, 0x7e, 0xef, 0x9d, 0x0c, 0x79, 0xe8, 0x9a, 0x0b,\n 0x6c, 0xfd, 0x8f, 0x1e, 0x6b, 0xfa, 0x88, 0x19, 0x62, 0xf3, 0x81, 0x10, 0x65, 0xf4, 0x86, 0x17,\n 0x48, 0xd9, 0xab, 0x3a, 0x4f, 0xde, 0xac, 0x3d, 0x46, 0xd7, 0xa5, 0x34, 0x41, 0xd0, 0xa2, 0x33,\n 0x54, 0xc5, 0xb7, 0x26, 0x53, 0xc2, 0xb0, 0x21, 0x5a, 0xcb, 0xb9, 0x28, 0x5d, 0xcc, 0xbe, 0x2f,\n 0xe0, 0x71, 0x03, 0x92, 0xe7, 0x76, 0x04, 0x95, 0xee, 0x7f, 0x0d, 0x9c, 0xe9, 0x78, 0x0a, 0x9b,\n 0xfc, 0x6d, 0x1f, 0x8e, 0xfb, 0x6a, 0x18, 0x89, 0xf2, 0x63, 0x11, 0x80, 0xf5, 0x64, 0x16, 0x87,\n 0xd8, 0x49, 0x3b, 0xaa, 0xdf, 0x4e, 0x3c, 0xad, 0xd6, 0x47, 0x35, 0xa4, 0xd1, 0x40, 0x32, 0xa3,\n 0xc4, 0x55, 0x27, 0xb6, 0xc3, 0x52, 0x20, 0xb1, 0xca, 0x5b, 0x29, 0xb8, 0xcd, 0x5c, 0x2e, 0xbf,\n 0x90, 0x01, 0x73, 0xe2, 0x97, 0x06, 0x74, 0xe5, 0x9e, 0x0f, 0x7d, 0xec, 0x99, 0x08, 0x7a, 0xeb,\n 0x8c, 0x1d, 0x6f, 0xfe, 0x8b, 0x1a, 0x68, 0xf9, 0x82, 0x13, 0x61, 0xf0, 0x85, 0x14, 0x66, 0xf7,\n 0xa8, 0x39, 0x4b, 0xda, 0xaf, 0x3e, 0x4c, 0xdd, 0xa6, 0x37, 0x45, 0xd4, 0xa1, 0x30, 0x42, 0xd3,\n 0xb4, 0x25, 0x56, 0xc7, 0xb3, 0x22, 0x50, 0xc1, 0xba, 0x2b, 0x59, 0xc8, 0xbd, 0x2c, 0x5e, 0xcf\n];\n\n/**\n * Calculates 8-bit CRC for the given data\n */\nexport function crc8(data: Uint8Array): number {\n let crc = 0;\n for (let i = 0; i < data.length; i++) {\n crc = crc_table[(crc ^ data[i]) & 0xff];\n }\n return crc;\n}\n","// Source: game.h (Quake 2)\nexport enum EntityEffects {\n Rotate = 0x00000004,\n Gib = 0x00000008,\n RotateScript = 0x00000010,\n Blaster = 0x00000020,\n Rocket = 0x00000040,\n Grenade = 0x00000080,\n HyperBlaster = 0x00000100,\n Bfg = 0x00000200,\n ColorShell = 0x00000400,\n Powerscreen = 0x00000800,\n Anim01 = 0x00001000,\n Anim23 = 0x00002000,\n AnimAll = 0x00004000,\n AnimAllFast = 0x00008000,\n Quad = 0x00010000,\n Pent = 0x00020000,\n Explosion = 0x00040000,\n Teleport = 0x00080000,\n Flag1 = 0x00100000,\n Flag2 = 0x00200000,\n Boomerang = 0x00400000,\n Greengibs = 0x00800000,\n Bluehyperblaster = 0x01000000,\n Spinning = 0x02000000,\n Plasma = 0x04000000,\n Trap = 0x08000000,\n Tracker = 0x10000000,\n Double = 0x20000000,\n Sphinx = 0x40000000,\n TagTrail = 0x80000000,\n}\n","export enum EntityEvent {\n None = 0,\n ItemRespawn = 1,\n Footstep = 2,\n FallShort = 3,\n Fall = 4,\n FallFar = 5,\n PlayerTeleport = 6,\n OtherTeleport = 7,\n\n // [Paril-KEX]\n OtherFootstep = 8,\n LadderStep = 9,\n}\n","import { BinaryWriter } from '../io/index.js';\nimport { EntityState } from './entityState.js';\n\n// Constants matching packages/engine/src/demo/parser.ts\nexport const U_ORIGIN1 = (1 << 0);\nexport const U_ORIGIN2 = (1 << 1);\nexport const U_ANGLE2 = (1 << 2);\nexport const U_ANGLE3 = (1 << 3);\nexport const U_FRAME8 = (1 << 4);\nexport const U_EVENT = (1 << 5);\nexport const U_REMOVE = (1 << 6);\nexport const U_MOREBITS1 = (1 << 7);\n\nexport const U_NUMBER16 = (1 << 8);\nexport const U_ORIGIN3 = (1 << 9);\nexport const U_ANGLE1 = (1 << 10);\nexport const U_MODEL = (1 << 11);\nexport const U_RENDERFX8 = (1 << 12);\nexport const U_ALPHA = (1 << 13); // Rerelease: Alpha\nexport const U_EFFECTS8 = (1 << 14);\nexport const U_MOREBITS2 = (1 << 15);\n\nexport const U_SKIN8 = (1 << 16);\nexport const U_FRAME16 = (1 << 17);\nexport const U_RENDERFX16 = (1 << 18);\nexport const U_EFFECTS16 = (1 << 19);\nexport const U_MODEL2 = (1 << 20); // Rerelease\nexport const U_MODEL3 = (1 << 21); // Rerelease\nexport const U_MODEL4 = (1 << 22); // Rerelease\nexport const U_MOREBITS3 = (1 << 23);\n\nexport const U_OLDORIGIN = (1 << 24);\nexport const U_SKIN16 = (1 << 25);\nexport const U_SOUND = (1 << 26);\nexport const U_SOLID = (1 << 27);\nexport const U_SCALE = (1 << 28); // Rerelease\nexport const U_INSTANCE_BITS = (1 << 29); // Rerelease\nexport const U_LOOP_VOLUME = (1 << 30); // Rerelease\nexport const U_MOREBITS4 = 0x80000000 | 0; // Bit 31 (sign bit)\n\n// Rerelease Extension Bits (Byte 5 - High Bits)\nexport const U_LOOP_ATTENUATION_HIGH = (1 << 0);\nexport const U_OWNER_HIGH = (1 << 1);\nexport const U_OLD_FRAME_HIGH = (1 << 2);\n\n\n// A null state for new entities, used as a baseline for comparison.\nconst NULL_STATE: EntityState = {\n number: 0,\n origin: { x: 0, y: 0, z: 0 },\n angles: { x: 0, y: 0, z: 0 },\n modelIndex: 0,\n frame: 0,\n skinNum: 0,\n effects: 0,\n renderfx: 0,\n solid: 0,\n sound: 0,\n event: 0,\n alpha: 0,\n scale: 0,\n instanceBits: 0,\n loopVolume: 0,\n loopAttenuation: 0,\n owner: 0,\n oldFrame: 0,\n modelIndex2: 0,\n modelIndex3: 0,\n modelIndex4: 0\n};\n\n/**\n * Writes the remove bit for an entity.\n */\nexport function writeRemoveEntity(\n number: number,\n writer: BinaryWriter\n): void {\n let bits = U_REMOVE;\n\n if (number >= 256) {\n bits |= U_NUMBER16;\n }\n\n // Determine needed bytes for header (U_NUMBER16 is in bits 8-15)\n if (bits & 0xFF00) {\n bits |= U_MOREBITS1;\n }\n\n // Write Header\n writer.writeByte(bits & 0xFF);\n if (bits & U_MOREBITS1) {\n writer.writeByte((bits >> 8) & 0xFF);\n }\n\n // Write Number\n if (bits & U_NUMBER16) {\n writer.writeShort(number);\n } else {\n writer.writeByte(number);\n }\n}\n\n/**\n * Writes the delta between two entity states to a binary writer.\n */\nexport function writeDeltaEntity(\n from: EntityState,\n to: EntityState,\n writer: BinaryWriter,\n force: boolean,\n newEntity: boolean\n): void {\n let bits = 0;\n let bitsHigh = 0;\n\n // If this is a new entity, use a null baseline\n if (newEntity) {\n from = NULL_STATE;\n }\n\n // --- Compare fields and build the bitmask ---\n if (to.modelIndex !== from.modelIndex || force) {\n bits |= U_MODEL;\n }\n if (to.modelIndex2 !== from.modelIndex2 || force) {\n bits |= U_MODEL2;\n }\n if (to.modelIndex3 !== from.modelIndex3 || force) {\n bits |= U_MODEL3;\n }\n if (to.modelIndex4 !== from.modelIndex4 || force) {\n bits |= U_MODEL4;\n }\n\n if (to.origin.x !== from.origin.x || force) {\n bits |= U_ORIGIN1;\n }\n if (to.origin.y !== from.origin.y || force) {\n bits |= U_ORIGIN2;\n }\n if (to.origin.z !== from.origin.z || force) {\n bits |= U_ORIGIN3;\n }\n if (to.angles.x !== from.angles.x || force) {\n bits |= U_ANGLE1;\n }\n if (to.angles.y !== from.angles.y || force) {\n bits |= U_ANGLE2;\n }\n if (to.angles.z !== from.angles.z || force) {\n bits |= U_ANGLE3;\n }\n\n if (to.frame !== from.frame || force) {\n if (to.frame >= 256) bits |= U_FRAME16;\n else bits |= U_FRAME8;\n }\n\n if (to.skinNum !== from.skinNum || force) {\n if (to.skinNum >= 256) bits |= U_SKIN16;\n else bits |= U_SKIN8;\n }\n\n if (to.effects !== from.effects || force) {\n if (to.effects >= 256) bits |= U_EFFECTS16;\n else bits |= U_EFFECTS8;\n }\n\n if (to.renderfx !== from.renderfx || force) {\n if (to.renderfx >= 256) bits |= U_RENDERFX16;\n else bits |= U_RENDERFX8;\n }\n\n if (to.solid !== from.solid || force) {\n bits |= U_SOLID;\n }\n if (to.sound !== from.sound || force) {\n bits |= U_SOUND;\n }\n if (to.event !== from.event || force) {\n bits |= U_EVENT;\n }\n\n // Rerelease Fields\n if ((to.alpha !== from.alpha || force) && to.alpha !== undefined) {\n bits |= U_ALPHA;\n }\n if ((to.scale !== from.scale || force) && to.scale !== undefined) {\n bits |= U_SCALE;\n }\n if ((to.instanceBits !== from.instanceBits || force) && to.instanceBits !== undefined) {\n bits |= U_INSTANCE_BITS;\n }\n if ((to.loopVolume !== from.loopVolume || force) && to.loopVolume !== undefined) {\n bits |= U_LOOP_VOLUME;\n }\n\n // High Bits Fields\n if ((to.loopAttenuation !== from.loopAttenuation || force) && to.loopAttenuation !== undefined) {\n bitsHigh |= U_LOOP_ATTENUATION_HIGH;\n }\n if ((to.owner !== from.owner || force) && to.owner !== undefined) {\n bitsHigh |= U_OWNER_HIGH;\n }\n if ((to.oldFrame !== from.oldFrame || force) && to.oldFrame !== undefined) {\n bitsHigh |= U_OLD_FRAME_HIGH;\n }\n\n\n // Handle entity number\n if (to.number >= 256) {\n bits |= U_NUMBER16;\n }\n\n // Determine needed bytes for header\n\n // If we have high bits, we set U_MOREBITS4 on the 4th byte\n if (bitsHigh > 0) {\n bits |= U_MOREBITS4;\n }\n\n // Now calculate cascading flags\n if (bits & 0xFF000000) { // e.g. U_MOREBITS4 (bit 31) is here\n bits |= U_MOREBITS3;\n }\n if (bits & 0xFFFF0000) { // e.g. U_MOREBITS3 (bit 23) is here\n bits |= U_MOREBITS2;\n }\n if (bits & 0xFFFFFF00) { // e.g. U_MOREBITS2 (bit 15) is here\n bits |= U_MOREBITS1;\n }\n\n // Write Header\n writer.writeByte(bits & 0xFF);\n\n if (bits & U_MOREBITS1) {\n writer.writeByte((bits >> 8) & 0xFF);\n }\n if (bits & U_MOREBITS2) {\n writer.writeByte((bits >> 16) & 0xFF);\n }\n if (bits & U_MOREBITS3) {\n writer.writeByte((bits >> 24) & 0xFF);\n }\n if (bits & U_MOREBITS4) {\n writer.writeByte(bitsHigh & 0xFF);\n }\n\n // Write Number\n if (bits & U_NUMBER16) {\n writer.writeShort(to.number);\n } else {\n writer.writeByte(to.number);\n }\n\n // Write Fields in Order (matching NetworkMessageParser.parseDelta)\n if (bits & U_MODEL) writer.writeByte(to.modelIndex);\n if (bits & U_MODEL2) writer.writeByte(to.modelIndex2 ?? 0);\n if (bits & U_MODEL3) writer.writeByte(to.modelIndex3 ?? 0);\n if (bits & U_MODEL4) writer.writeByte(to.modelIndex4 ?? 0);\n\n if (bits & U_FRAME8) writer.writeByte(to.frame);\n if (bits & U_FRAME16) writer.writeShort(to.frame);\n\n if (bits & U_SKIN8) writer.writeByte(to.skinNum);\n if (bits & U_SKIN16) writer.writeShort(to.skinNum);\n\n if (bits & U_EFFECTS8) writer.writeByte(to.effects);\n if (bits & U_EFFECTS16) writer.writeShort(to.effects);\n\n if (bits & U_RENDERFX8) writer.writeByte(to.renderfx);\n if (bits & U_RENDERFX16) writer.writeShort(to.renderfx);\n\n if (bits & U_ORIGIN1) writer.writeCoord(to.origin.x);\n if (bits & U_ORIGIN2) writer.writeCoord(to.origin.y);\n if (bits & U_ORIGIN3) writer.writeCoord(to.origin.z);\n\n if (bits & U_ANGLE1) writer.writeAngle(to.angles.x);\n if (bits & U_ANGLE2) writer.writeAngle(to.angles.y);\n if (bits & U_ANGLE3) writer.writeAngle(to.angles.z);\n\n if (bits & U_OLDORIGIN) {\n // Not implemented in EntityState usually, skip or zero\n // writer.writePos(to.old_origin);\n }\n\n if (bits & U_SOUND) writer.writeByte(to.sound ?? 0);\n\n if (bits & U_EVENT) writer.writeByte(to.event ?? 0);\n\n if (bits & U_SOLID) writer.writeShort(to.solid);\n\n // Rerelease Fields Writing\n if (bits & U_ALPHA) writer.writeByte(Math.floor((to.alpha ?? 0) * 255));\n if (bits & U_SCALE) writer.writeFloat(to.scale ?? 0);\n if (bits & U_INSTANCE_BITS) writer.writeLong(to.instanceBits ?? 0);\n if (bits & U_LOOP_VOLUME) writer.writeByte(Math.floor((to.loopVolume ?? 0) * 255));\n\n // High bits fields\n if (bitsHigh & U_LOOP_ATTENUATION_HIGH) writer.writeByte(Math.floor((to.loopAttenuation ?? 0) * 255));\n if (bitsHigh & U_OWNER_HIGH) writer.writeShort(to.owner ?? 0);\n if (bitsHigh & U_OLD_FRAME_HIGH) writer.writeShort(to.oldFrame ?? 0);\n}\n","import { BinaryWriter, Vec3 } from '../index.js';\n\nexport interface ProtocolPlayerState {\n pm_type: number;\n origin: Vec3;\n velocity: Vec3;\n pm_time: number;\n pm_flags: number;\n gravity: number;\n delta_angles: Vec3;\n viewoffset: Vec3;\n viewangles: Vec3;\n kick_angles: Vec3;\n gun_index: number;\n gun_frame: number;\n gun_offset: Vec3;\n gun_angles: Vec3;\n blend: number[]; // [r,g,b,a]\n fov: number;\n rdflags: number;\n stats: number[];\n watertype: number;\n\n // Optional / Extension fields if needed\n gunskin?: number;\n gunrate?: number;\n damage_blend?: number[];\n team_id?: number;\n}\n\n// Bitflags matching demo/parser.ts\nconst PS_M_TYPE = (1 << 0);\nconst PS_M_ORIGIN = (1 << 1);\nconst PS_M_VELOCITY = (1 << 2);\nconst PS_M_TIME = (1 << 3);\nconst PS_M_FLAGS = (1 << 4);\nconst PS_M_GRAVITY = (1 << 5);\nconst PS_M_DELTA_ANGLES = (1 << 6);\nconst PS_VIEWOFFSET = (1 << 7);\nconst PS_VIEWANGLES = (1 << 8);\nconst PS_KICKANGLES = (1 << 9);\nconst PS_BLEND = (1 << 10);\nconst PS_FOV = (1 << 11);\nconst PS_WEAPONINDEX = (1 << 12);\nconst PS_WEAPONFRAME = (1 << 13);\nconst PS_RDFLAGS = (1 << 14);\nconst PS_WATERTYPE = (1 << 15);\n\nexport function writePlayerState(writer: BinaryWriter, ps: ProtocolPlayerState): void {\n // Determine mask\n let mask = 0;\n\n if (ps.pm_type !== 0) mask |= PS_M_TYPE;\n if (ps.origin.x !== 0 || ps.origin.y !== 0 || ps.origin.z !== 0) mask |= PS_M_ORIGIN;\n if (ps.velocity.x !== 0 || ps.velocity.y !== 0 || ps.velocity.z !== 0) mask |= PS_M_VELOCITY;\n if (ps.pm_time !== 0) mask |= PS_M_TIME;\n if (ps.pm_flags !== 0) mask |= PS_M_FLAGS;\n if (ps.gravity !== 0) mask |= PS_M_GRAVITY;\n if (ps.delta_angles.x !== 0 || ps.delta_angles.y !== 0 || ps.delta_angles.z !== 0) mask |= PS_M_DELTA_ANGLES;\n if (ps.viewoffset.x !== 0 || ps.viewoffset.y !== 0 || ps.viewoffset.z !== 0) mask |= PS_VIEWOFFSET;\n if (ps.viewangles.x !== 0 || ps.viewangles.y !== 0 || ps.viewangles.z !== 0) mask |= PS_VIEWANGLES;\n if (ps.kick_angles.x !== 0 || ps.kick_angles.y !== 0 || ps.kick_angles.z !== 0) mask |= PS_KICKANGLES;\n if (ps.gun_index !== 0) mask |= PS_WEAPONINDEX;\n\n // Weapon frame includes offset/angles\n if (ps.gun_frame !== 0 ||\n ps.gun_offset.x !== 0 || ps.gun_offset.y !== 0 || ps.gun_offset.z !== 0 ||\n ps.gun_angles.x !== 0 || ps.gun_angles.y !== 0 || ps.gun_angles.z !== 0) {\n mask |= PS_WEAPONFRAME;\n }\n\n if (ps.blend && (ps.blend[0] !== 0 || ps.blend[1] !== 0 || ps.blend[2] !== 0 || ps.blend[3] !== 0)) {\n mask |= PS_BLEND;\n }\n\n if (ps.fov !== 0) mask |= PS_FOV;\n if (ps.rdflags !== 0) mask |= PS_RDFLAGS;\n if (ps.watertype !== 0) mask |= PS_WATERTYPE;\n\n // Stats mask calculation\n let statsMask = 0;\n // Only support first 32 stats for now\n for (let i = 0; i < 32; i++) {\n if (ps.stats[i] && ps.stats[i] !== 0) {\n statsMask |= (1 << i);\n }\n }\n\n // Write header\n writer.writeShort(mask);\n\n // Write fields\n if (mask & PS_M_TYPE) writer.writeByte(ps.pm_type);\n\n if (mask & PS_M_ORIGIN) {\n writer.writeShort(Math.round(ps.origin.x * 8));\n writer.writeShort(Math.round(ps.origin.y * 8));\n writer.writeShort(Math.round(ps.origin.z * 8));\n }\n\n if (mask & PS_M_VELOCITY) {\n writer.writeShort(Math.round(ps.velocity.x * 8));\n writer.writeShort(Math.round(ps.velocity.y * 8));\n writer.writeShort(Math.round(ps.velocity.z * 8));\n }\n\n if (mask & PS_M_TIME) writer.writeByte(ps.pm_time);\n if (mask & PS_M_FLAGS) writer.writeByte(ps.pm_flags);\n if (mask & PS_M_GRAVITY) writer.writeShort(ps.gravity);\n\n if (mask & PS_M_DELTA_ANGLES) {\n writer.writeShort(Math.round(ps.delta_angles.x * (32768 / 180)));\n writer.writeShort(Math.round(ps.delta_angles.y * (32768 / 180)));\n writer.writeShort(Math.round(ps.delta_angles.z * (32768 / 180)));\n }\n\n if (mask & PS_VIEWOFFSET) {\n writer.writeChar(Math.round(ps.viewoffset.x * 4));\n writer.writeChar(Math.round(ps.viewoffset.y * 4));\n writer.writeChar(Math.round(ps.viewoffset.z * 4));\n }\n\n if (mask & PS_VIEWANGLES) {\n writer.writeAngle16(ps.viewangles.x);\n writer.writeAngle16(ps.viewangles.y);\n writer.writeAngle16(ps.viewangles.z);\n }\n\n if (mask & PS_KICKANGLES) {\n writer.writeChar(Math.round(ps.kick_angles.x * 4));\n writer.writeChar(Math.round(ps.kick_angles.y * 4));\n writer.writeChar(Math.round(ps.kick_angles.z * 4));\n }\n\n if (mask & PS_WEAPONINDEX) writer.writeByte(ps.gun_index);\n\n if (mask & PS_WEAPONFRAME) {\n writer.writeByte(ps.gun_frame);\n writer.writeChar(Math.round(ps.gun_offset.x * 4));\n writer.writeChar(Math.round(ps.gun_offset.y * 4));\n writer.writeChar(Math.round(ps.gun_offset.z * 4));\n writer.writeChar(Math.round(ps.gun_angles.x * 4));\n writer.writeChar(Math.round(ps.gun_angles.y * 4));\n writer.writeChar(Math.round(ps.gun_angles.z * 4));\n }\n\n if (mask & PS_BLEND) {\n writer.writeByte(Math.round(ps.blend[0]));\n writer.writeByte(Math.round(ps.blend[1]));\n writer.writeByte(Math.round(ps.blend[2]));\n writer.writeByte(Math.round(ps.blend[3]));\n }\n\n if (mask & PS_FOV) writer.writeByte(ps.fov);\n if (mask & PS_RDFLAGS) writer.writeByte(ps.rdflags);\n if (mask & PS_WATERTYPE) writer.writeByte(ps.watertype);\n\n // Write Stats\n writer.writeLong(statsMask);\n for (let i = 0; i < 32; i++) {\n if (statsMask & (1 << i)) {\n writer.writeShort(ps.stats[i]);\n }\n }\n}\n","\nimport { PmoveCmd, PmoveTraceFn } from './types.js';\nimport { Vec3 } from '../math/vec3.js';\n\nimport { applyPmoveAccelerate, applyPmoveFriction, buildAirGroundWish, buildWaterWish } from './pmove.js';\nimport { PlayerState } from '../protocol/player-state.js';\nimport { angleVectors } from '../math/angles.js';\nimport { MASK_WATER } from '../bsp/contents.js';\n\nconst FRAMETIME = 0.025;\n\n// Local definition to avoid dependency issues if constants.ts is missing\n// Matches packages/shared/src/pmove/constants.ts\nconst WaterLevel = {\n None: 0,\n Feet: 1,\n Waist: 2,\n Under: 3,\n} as const;\n\nconst categorizePosition = (state: PlayerState, trace: PmoveTraceFn): PlayerState => {\n const point = { ...state.origin };\n point.z -= 0.25;\n const traceResult = trace(state.origin, point);\n\n return {\n ...state,\n onGround: traceResult.fraction < 1,\n };\n};\n\nconst checkWater = (state: PlayerState, pointContents: (point: Vec3) => number): PlayerState => {\n const point = { ...state.origin };\n const { mins, maxs } = state;\n\n // Default to feet\n point.z = state.origin.z + mins.z + 1;\n\n const feetContents = pointContents(point);\n\n if (!(feetContents & MASK_WATER)) {\n return { ...state, waterLevel: WaterLevel.None, watertype: 0 };\n }\n\n let waterLevel: number = WaterLevel.Feet;\n let watertype = feetContents;\n\n // Check waist\n const waist = state.origin.z + (mins.z + maxs.z) * 0.5;\n point.z = waist;\n const waistContents = pointContents(point);\n\n if (waistContents & MASK_WATER) {\n waterLevel = WaterLevel.Waist;\n watertype = waistContents;\n\n // Check head (eyes)\n // Standard Quake 2 viewheight is 22. maxs.z is typically 32.\n // So eyes are roughly at origin.z + 22.\n // We'll use origin.z + 22 to check if eyes are underwater.\n // If viewheight was available in PlayerState, we'd use that.\n const head = state.origin.z + 22;\n point.z = head;\n const headContents = pointContents(point);\n\n if (headContents & MASK_WATER) {\n waterLevel = WaterLevel.Under;\n watertype = headContents;\n }\n }\n\n return { ...state, waterLevel, watertype };\n};\n\n\nexport const applyPmove = (\n state: PlayerState,\n cmd: PmoveCmd,\n trace: PmoveTraceFn,\n pointContents: (point: Vec3) => number\n): PlayerState => {\n let newState = { ...state };\n newState = categorizePosition(newState, trace);\n newState = checkWater(newState, pointContents);\n\n const { origin, velocity, onGround, waterLevel, viewAngles } = newState;\n\n // Calculate forward and right vectors from view angles\n // For water movement, use full view angles including pitch\n // For ground/air movement, reduce pitch influence by dividing by 3\n // See: rerelease/p_move.cpp lines 1538, 1686-1691, 800, 858\n const adjustedAngles = waterLevel >= 2\n ? viewAngles\n : {\n // For ground/air movement, reduce pitch influence (rerelease/p_move.cpp:1689)\n x: viewAngles.x > 180 ? (viewAngles.x - 360) / 3 : viewAngles.x / 3,\n y: viewAngles.y,\n z: viewAngles.z,\n };\n\n const { forward, right } = angleVectors(adjustedAngles);\n\n // Apply friction BEFORE acceleration to match original Quake 2 rerelease behavior\n // See: rerelease/src/game/player/pmove.c lines 1678 (PM_Friction) then 1693 (PM_AirMove->PM_Accelerate)\n const frictionedVelocity = applyPmoveFriction({\n velocity,\n frametime: FRAMETIME,\n onGround,\n groundIsSlick: false,\n onLadder: false,\n waterlevel: waterLevel,\n pmFriction: 6,\n pmStopSpeed: 100,\n pmWaterFriction: 1,\n });\n\n const wish = waterLevel >= 2\n ? buildWaterWish({\n forward,\n right,\n cmd,\n maxSpeed: 320,\n })\n : buildAirGroundWish({\n forward,\n right,\n cmd,\n maxSpeed: 320,\n });\n\n const finalVelocity = applyPmoveAccelerate({\n velocity: frictionedVelocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n // Water movement uses ground acceleration (10), not air acceleration (1)\n accel: (onGround || waterLevel >= 2) ? 10 : 1,\n frametime: FRAMETIME,\n });\n\n const traceResult = trace(origin, {\n x: origin.x + finalVelocity.x * FRAMETIME,\n y: origin.y + finalVelocity.y * FRAMETIME,\n z: origin.z + finalVelocity.z * FRAMETIME,\n });\n\n return {\n ...newState,\n origin: traceResult.endpos,\n velocity: finalVelocity,\n };\n};\n","import { Vec3 } from '../math/vec3.js';\nimport { ANORMS } from '../math/anorms.js';\n\nexport class BinaryStream {\n private view: DataView;\n private offset: number;\n private length: number;\n\n constructor(buffer: ArrayBuffer | Uint8Array) {\n if (buffer instanceof Uint8Array) {\n this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n } else {\n this.view = new DataView(buffer);\n }\n this.offset = 0;\n this.length = this.view.byteLength;\n }\n\n public getPosition(): number {\n return this.offset;\n }\n\n public getReadPosition(): number {\n return this.offset;\n }\n\n public getLength(): number {\n return this.length;\n }\n\n public getRemaining(): number {\n return this.length - this.offset;\n }\n\n public seek(position: number): void {\n if (position < 0 || position > this.length) {\n throw new Error(`Seek out of bounds: ${position} (length: ${this.length})`);\n }\n this.offset = position;\n }\n\n public setReadPosition(position: number): void {\n this.seek(position);\n }\n\n public hasMore(): boolean {\n return this.offset < this.length;\n }\n\n public hasBytes(count: number): boolean {\n return this.offset + count <= this.length;\n }\n\n public readChar(): number {\n const value = this.view.getInt8(this.offset);\n this.offset += 1;\n return value;\n }\n\n public readByte(): number {\n const value = this.view.getUint8(this.offset);\n this.offset += 1;\n return value;\n }\n\n public readShort(): number {\n const value = this.view.getInt16(this.offset, true);\n this.offset += 2;\n return value;\n }\n\n public readUShort(): number {\n const value = this.view.getUint16(this.offset, true);\n this.offset += 2;\n return value;\n }\n\n public readLong(): number {\n const value = this.view.getInt32(this.offset, true);\n this.offset += 4;\n return value;\n }\n\n public readULong(): number {\n const value = this.view.getUint32(this.offset, true);\n this.offset += 4;\n return value;\n }\n\n public readFloat(): number {\n const value = this.view.getFloat32(this.offset, true);\n this.offset += 4;\n return value;\n }\n\n public readString(): string {\n let str = '';\n while (this.offset < this.length) {\n const charCode = this.readChar();\n if (charCode === -1 || charCode === 0) {\n break;\n }\n str += String.fromCharCode(charCode);\n }\n return str;\n }\n\n public readStringLine(): string {\n let str = '';\n while (this.offset < this.length) {\n const charCode = this.readChar();\n if (charCode === -1 || charCode === 0 || charCode === 10) { // 10 is \\n\n break;\n }\n str += String.fromCharCode(charCode);\n }\n return str;\n }\n\n public readCoord(): number {\n return this.readShort() * (1.0 / 8.0);\n }\n\n public readAngle(): number {\n return this.readChar() * (360.0 / 256.0);\n }\n\n public readAngle16(): number {\n return (this.readShort() * 360.0) / 65536.0;\n }\n\n public readData(length: number): Uint8Array {\n if (this.offset + length > this.length) {\n throw new Error(`Read out of bounds: ${this.offset + length} (length: ${this.length})`);\n }\n const data = new Uint8Array(this.view.buffer, this.view.byteOffset + this.offset, length);\n this.offset += length;\n // Return a copy to avoid side effects if the original buffer is modified or reused\n return new Uint8Array(data);\n }\n\n public readPos(out: { x: number, y: number, z: number }): void {\n out.x = this.readCoord();\n out.y = this.readCoord();\n out.z = this.readCoord();\n }\n\n public readDir(out: { x: number, y: number, z: number }): void {\n const b = this.readByte();\n if (b >= 162) { // NUMVERTEXNORMALS\n out.x = 0; out.y = 0; out.z = 0;\n return;\n }\n const norm = ANORMS[b];\n out.x = norm[0];\n out.y = norm[1];\n out.z = norm[2];\n }\n}\n","import { ANORMS } from '../math/anorms.js';\nimport { Vec3 } from '../math/vec3.js';\n\nexport class BinaryWriter {\n private buffer: Uint8Array;\n private view: DataView;\n private offset: number;\n private readonly fixed: boolean;\n\n constructor(sizeOrBuffer: number | Uint8Array = 1400) {\n if (typeof sizeOrBuffer === 'number') {\n this.buffer = new Uint8Array(sizeOrBuffer);\n this.fixed = false;\n } else {\n this.buffer = sizeOrBuffer;\n this.fixed = true;\n }\n this.view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n this.offset = 0;\n }\n\n private ensureSpace(bytes: number) {\n if (this.offset + bytes > this.buffer.byteLength) {\n if (this.fixed) {\n throw new Error(`Buffer overflow: capacity ${this.buffer.byteLength}, needed ${this.offset + bytes}`);\n }\n // Expand buffer (double size)\n const newSize = Math.max(this.buffer.byteLength * 2, this.offset + bytes);\n const newBuffer = new Uint8Array(newSize);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n this.view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n }\n }\n\n public writeByte(value: number): void {\n this.ensureSpace(1);\n this.view.setUint8(this.offset, value);\n this.offset += 1;\n }\n\n public writeBytes(data: Uint8Array): void {\n this.ensureSpace(data.byteLength);\n this.buffer.set(data, this.offset);\n this.offset += data.byteLength;\n }\n\n public writeChar(value: number): void {\n this.ensureSpace(1);\n this.view.setInt8(this.offset, value);\n this.offset += 1;\n }\n\n public writeShort(value: number): void {\n this.ensureSpace(2);\n // Use setUint16 to allow writing 0xFFFF as a valid pattern even if it represents -1\n // But value might be negative (-1). setUint16(-1) wraps to 65535.\n // So setInt16 is fine if value is in range.\n // If value is 65535 (from bit manipulation), setInt16 might throw?\n // Let's safe cast.\n this.view.setInt16(this.offset, value, true);\n this.offset += 2;\n }\n\n public writeLong(value: number): void {\n this.ensureSpace(4);\n this.view.setInt32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeFloat(value: number): void {\n this.ensureSpace(4);\n this.view.setFloat32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeString(value: string): void {\n // UTF-8 encoding of string + null terminator\n // We iterate manually to match readString behavior (ASCII/Latin1 mostly)\n // and avoid TextEncoder overhead if simple\n const len = value.length;\n this.ensureSpace(len + 1);\n for (let i = 0; i < len; i++) {\n this.view.setUint8(this.offset + i, value.charCodeAt(i));\n }\n this.view.setUint8(this.offset + len, 0);\n this.offset += len + 1;\n }\n\n public writeCoord(value: number): void {\n this.writeShort(Math.trunc(value * 8));\n }\n\n public writeAngle(value: number): void {\n this.writeByte(Math.trunc(value * 256.0 / 360.0) & 255);\n }\n\n public writeAngle16(value: number): void {\n this.writeShort(Math.trunc(value * 65536.0 / 360.0) & 65535);\n }\n\n public writePos(pos: Vec3): void {\n this.writeCoord(pos.x);\n this.writeCoord(pos.y);\n this.writeCoord(pos.z);\n }\n\n public writeDir(dir: Vec3): void {\n // Find closest normal\n let maxDot = -1.0;\n let bestIndex = 0;\n\n // Check for zero vector\n if (dir.x === 0 && dir.y === 0 && dir.z === 0) {\n this.writeByte(0);\n return;\n }\n\n for (let i = 0; i < ANORMS.length; i++) {\n const norm = ANORMS[i];\n const dot = dir.x * norm[0] + dir.y * norm[1] + dir.z * norm[2];\n if (dot > maxDot) {\n maxDot = dot;\n bestIndex = i;\n }\n }\n\n this.writeByte(bestIndex);\n }\n\n public getData(): Uint8Array {\n return this.buffer.slice(0, this.offset);\n }\n\n public getBuffer(): Uint8Array {\n return this.buffer;\n }\n\n public getOffset(): number {\n return this.offset;\n }\n\n public reset(): void {\n this.offset = 0;\n }\n}\n","import { ANORMS } from '../math/anorms.js';\n\nexport class NetworkMessageBuilder {\n private buffer: Uint8Array;\n private view: DataView;\n private offset: number;\n\n constructor(initialSize: number = 1024) {\n this.buffer = new Uint8Array(initialSize);\n this.view = new DataView(this.buffer.buffer);\n this.offset = 0;\n }\n\n private ensureCapacity(needed: number): void {\n if (this.offset + needed > this.buffer.length) {\n const newSize = Math.max(this.buffer.length * 2, this.offset + needed);\n const newBuffer = new Uint8Array(newSize);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n this.view = new DataView(this.buffer.buffer);\n }\n }\n\n public getData(): Uint8Array {\n return this.buffer.slice(0, this.offset);\n }\n\n public writeByte(value: number): void {\n this.ensureCapacity(1);\n this.view.setUint8(this.offset, value);\n this.offset += 1;\n }\n\n public writeChar(value: number): void {\n this.ensureCapacity(1);\n this.view.setInt8(this.offset, value);\n this.offset += 1;\n }\n\n public writeShort(value: number): void {\n this.ensureCapacity(2);\n this.view.setInt16(this.offset, value, true);\n this.offset += 2;\n }\n\n public writeUShort(value: number): void {\n this.ensureCapacity(2);\n this.view.setUint16(this.offset, value, true);\n this.offset += 2;\n }\n\n public writeLong(value: number): void {\n this.ensureCapacity(4);\n this.view.setInt32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeFloat(value: number): void {\n this.ensureCapacity(4);\n this.view.setFloat32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeString(value: string): void {\n const len = value.length + 1; // +1 for null terminator\n this.ensureCapacity(len);\n for (let i = 0; i < value.length; i++) {\n this.view.setUint8(this.offset + i, value.charCodeAt(i));\n }\n this.view.setUint8(this.offset + value.length, 0);\n this.offset += len;\n }\n\n public writeData(data: Uint8Array): void {\n this.ensureCapacity(data.length);\n this.buffer.set(data, this.offset);\n this.offset += data.length;\n }\n\n public writeCoord(value: number): void {\n this.writeShort(Math.round(value * 8.0));\n }\n\n public writeAngle(value: number): void {\n this.writeByte(Math.round(value * 256.0 / 360.0) & 255);\n }\n\n public writeAngle16(value: number): void {\n this.writeShort(Math.round(value * 65536.0 / 360.0));\n }\n\n public writeDir(x: number, y: number, z: number): void {\n // Find closest normal from ANORMS\n // Simple brute force or use lookup if needed.\n // For now, let's just use 0 if implementation is complex to find best match.\n // Or unimplemented for now?\n // \"WriteDir\" in Q2 usually means writing a byte index into ANORMS.\n\n let best = 0;\n let bestDot = -999999;\n\n const len = Math.sqrt(x*x + y*y + z*z);\n if (len > 0) {\n x /= len; y /= len; z /= len;\n\n for (let i=0; i<162; i++) {\n const dot = x*ANORMS[i][0] + y*ANORMS[i][1] + z*ANORMS[i][2];\n if (dot > bestDot) {\n bestDot = dot;\n best = i;\n }\n }\n }\n\n this.writeByte(best);\n }\n}\n","import { BinaryWriter } from '../io/binaryWriter.js';\n\nexport interface NetAddress {\n type: string;\n port: number;\n}\n\n/**\n * NetChan handles reliable message delivery over an unreliable channel (UDP/WebSocket).\n * Fragmentation support is planned but not fully implemented.\n *\n * Ported from qcommon/net_chan.c\n */\nexport class NetChan {\n // Constants from net_chan.c\n static readonly MAX_MSGLEN = 1400;\n static readonly FRAGMENT_SIZE = 1024;\n static readonly PACKET_HEADER = 10; // sequence(4) + ack(4) + qport(2)\n static readonly HEADER_OVERHEAD = NetChan.PACKET_HEADER + 2; // +2 for reliable length prefix\n\n // Increase internal reliable buffer to support large messages (fragmentation)\n // Quake 2 uses MAX_MSGLEN for the reliable buffer, limiting single messages to ~1400 bytes.\n // We expand this to allow larger messages (e.g. snapshots, downloads) which are then fragmented.\n static readonly MAX_RELIABLE_BUFFER = 0x40000; // 256KB\n\n // Public state\n qport = 0; // qport value to distinguish multiple clients from same IP\n\n // Sequencing\n incomingSequence = 0;\n outgoingSequence = 0;\n incomingAcknowledged = 0;\n\n // Reliable messaging\n incomingReliableAcknowledged = false; // single bit\n incomingReliableSequence = 0; // last reliable message sequence received\n outgoingReliableSequence = 0; // reliable message sequence number to send\n reliableMessage: BinaryWriter;\n reliableLength = 0;\n\n // Fragmentation State (Sending)\n fragmentSendOffset = 0;\n\n // Fragmentation State (Receiving)\n fragmentBuffer: Uint8Array | null = null;\n fragmentLength = 0;\n fragmentReceived = 0;\n\n // Timing\n lastReceived = 0;\n lastSent = 0;\n\n remoteAddress: NetAddress | null = null;\n\n constructor() {\n // Initialize buffers\n this.reliableMessage = new BinaryWriter(NetChan.MAX_RELIABLE_BUFFER);\n\n // Set initial timestamps\n const now = Date.now();\n this.lastReceived = now;\n this.lastSent = now;\n\n // Random qport by default (can be overridden)\n // Ensure we use global Math.random which is usually seeded or random enough for basic collision avoidance\n this.qport = Math.floor(Math.random() * 65536);\n }\n\n /**\n * Setup the netchan with specific settings\n */\n setup(qport: number, address: NetAddress | null = null): void {\n this.qport = qport;\n this.remoteAddress = address;\n this.reset();\n }\n\n /**\n * Reset the netchan state\n */\n reset(): void {\n this.incomingSequence = 0;\n this.outgoingSequence = 0;\n this.incomingAcknowledged = 0;\n this.incomingReliableAcknowledged = false;\n this.incomingReliableSequence = 0;\n this.outgoingReliableSequence = 0;\n this.reliableLength = 0;\n this.reliableMessage.reset();\n\n this.fragmentSendOffset = 0;\n this.fragmentBuffer = null;\n this.fragmentLength = 0;\n this.fragmentReceived = 0;\n\n this.lastReceived = Date.now();\n this.lastSent = Date.now();\n }\n\n /**\n * Transmits a packet containing reliable and unreliable data\n */\n transmit(unreliableData?: Uint8Array): Uint8Array {\n this.outgoingSequence++;\n this.lastSent = Date.now();\n\n // Determine how much reliable data to send in this packet\n let sendReliableLength = 0;\n let isFragment = false;\n let fragmentStart = 0;\n\n if (this.reliableLength > 0) {\n // Check if we need to fragment\n if (this.reliableLength > NetChan.FRAGMENT_SIZE) {\n // We are in fragment mode\n isFragment = true;\n\n // If we have finished sending all fragments but still haven't received ACK,\n // we must loop back to the beginning to retransmit.\n if (this.fragmentSendOffset >= this.reliableLength) {\n this.fragmentSendOffset = 0;\n }\n\n // Calculate chunk size\n const remaining = this.reliableLength - this.fragmentSendOffset;\n sendReliableLength = remaining;\n if (sendReliableLength > NetChan.FRAGMENT_SIZE) {\n sendReliableLength = NetChan.FRAGMENT_SIZE;\n }\n\n fragmentStart = this.fragmentSendOffset;\n\n // Advance offset for the next packet\n this.fragmentSendOffset += sendReliableLength;\n } else {\n // Fits in one packet\n sendReliableLength = this.reliableLength;\n }\n }\n\n // Calculate total size\n // Header + Reliable + Unreliable\n const headerSize = NetChan.PACKET_HEADER;\n const reliableHeaderSize = sendReliableLength > 0 ? 2 + (isFragment ? 8 : 0) : 0; // +2 length, +8 fragment info\n\n let unreliableSize = unreliableData ? unreliableData.length : 0;\n\n // Check for overflow\n if (headerSize + reliableHeaderSize + sendReliableLength + unreliableSize > NetChan.MAX_MSGLEN) {\n unreliableSize = NetChan.MAX_MSGLEN - headerSize - reliableHeaderSize - sendReliableLength;\n // We truncate unreliable data if it doesn't fit with reliable data\n if (unreliableSize < 0) unreliableSize = 0;\n }\n\n const buffer = new ArrayBuffer(headerSize + reliableHeaderSize + sendReliableLength + unreliableSize);\n const view = new DataView(buffer);\n const result = new Uint8Array(buffer);\n\n // Write Header\n // Sequence\n let sequence = this.outgoingSequence;\n\n // Set reliable bit if we are sending reliable data\n if (sendReliableLength > 0) {\n sequence |= 0x80000000;\n // Also set the reliable sequence bit (0/1 toggle) at bit 30\n if ((this.outgoingReliableSequence & 1) !== 0) {\n sequence |= 0x40000000;\n }\n }\n\n view.setUint32(0, sequence, true);\n\n // Acknowledge\n // Set reliable ack bit at bit 31\n let ack = this.incomingSequence;\n if ((this.incomingReliableSequence & 1) !== 0) {\n ack |= 0x80000000;\n }\n view.setUint32(4, ack, true);\n\n view.setUint16(8, this.qport, true);\n\n // Copy Reliable Data\n let offset = headerSize;\n if (sendReliableLength > 0) {\n // Write length of reliable data (2 bytes)\n // Extension: If length has high bit (0x8000), it's a fragment.\n let lengthField = sendReliableLength;\n if (isFragment) {\n lengthField |= 0x8000;\n }\n\n view.setUint16(offset, lengthField, true);\n offset += 2;\n\n if (isFragment) {\n // Write fragment info: 4 bytes start offset, 4 bytes total length\n view.setUint32(offset, fragmentStart, true);\n offset += 4;\n view.setUint32(offset, this.reliableLength, true);\n offset += 4;\n }\n\n // Copy data\n const reliableBuffer = this.reliableMessage.getBuffer();\n const reliableBytes = reliableBuffer.subarray(fragmentStart, fragmentStart + sendReliableLength);\n result.set(reliableBytes, offset);\n offset += sendReliableLength;\n }\n\n // Copy Unreliable Data\n if (unreliableData && unreliableSize > 0) {\n const chunk = unreliableData.slice(0, unreliableSize);\n result.set(chunk, offset);\n }\n\n return result;\n }\n\n /**\n * Processes a received packet\n * Returns the payload data (reliable + unreliable) to be processed, or null if discarded\n */\n process(packet: Uint8Array): Uint8Array | null {\n if (packet.length < NetChan.PACKET_HEADER) {\n return null;\n }\n\n this.lastReceived = Date.now();\n\n const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);\n const sequence = view.getUint32(0, true);\n const ack = view.getUint32(4, true);\n const qport = view.getUint16(8, true);\n\n if (this.qport !== qport) {\n return null;\n }\n\n // Check for duplicate or out of order\n const seqNumberClean = sequence & ~(0x80000000 | 0x40000000); // Mask out flags\n\n // Handle wrapping using signed difference\n if (((seqNumberClean - this.incomingSequence) | 0) <= 0) {\n return null;\n }\n\n // Update incoming sequence\n this.incomingSequence = seqNumberClean;\n\n // Handle reliable acknowledgment\n const ackNumber = ack & ~0x80000000;\n const ackReliable = (ack & 0x80000000) !== 0;\n\n if (ackNumber > this.incomingAcknowledged) {\n this.incomingAcknowledged = ackNumber;\n }\n\n // Check if our reliable message was acknowledged\n // If the receiver has toggled their reliable bit, it means they got the WHOLE message\n if (this.reliableLength > 0) {\n const receivedAckBit = ackReliable ? 1 : 0;\n const currentReliableBit = this.outgoingReliableSequence & 1;\n\n if (receivedAckBit !== currentReliableBit) {\n // Acked!\n this.reliableLength = 0;\n this.reliableMessage.reset();\n this.outgoingReliableSequence ^= 1;\n this.fragmentSendOffset = 0; // Reset fragment offset\n }\n }\n\n // Handle incoming reliable data\n const hasReliableData = (sequence & 0x80000000) !== 0;\n const reliableSeqBit = (sequence & 0x40000000) !== 0 ? 1 : 0;\n\n let payloadOffset = NetChan.PACKET_HEADER;\n let reliableData: Uint8Array | null = null;\n\n if (hasReliableData) {\n if (payloadOffset + 2 > packet.byteLength) return null; // Malformed\n\n let reliableLen = view.getUint16(payloadOffset, true);\n payloadOffset += 2;\n\n const isFragment = (reliableLen & 0x8000) !== 0;\n reliableLen &= 0x7FFF;\n\n // Check if this is the expected reliable sequence\n const expectedBit = this.incomingReliableSequence & 1;\n\n if (reliableSeqBit === expectedBit) {\n // It's the sequence we are waiting for\n\n if (isFragment) {\n // Read fragment info\n if (payloadOffset + 8 > packet.byteLength) return null;\n const fragStart = view.getUint32(payloadOffset, true);\n payloadOffset += 4;\n const fragTotal = view.getUint32(payloadOffset, true);\n payloadOffset += 4;\n\n // Validate fragTotal against MAX_RELIABLE_BUFFER\n if (fragTotal > NetChan.MAX_RELIABLE_BUFFER) {\n console.warn(`NetChan: received invalid fragment total ${fragTotal} > ${NetChan.MAX_RELIABLE_BUFFER}`);\n return null;\n }\n\n // Initialize fragment buffer if needed\n if (!this.fragmentBuffer || this.fragmentBuffer.length !== fragTotal) {\n this.fragmentBuffer = new Uint8Array(fragTotal);\n this.fragmentLength = fragTotal;\n this.fragmentReceived = 0;\n }\n\n // Check for valid fragment offset\n if (payloadOffset + reliableLen > packet.byteLength) return null;\n const data = packet.subarray(payloadOffset, payloadOffset + reliableLen);\n\n // Only accept if it matches our expected offset (enforce in-order delivery for simplicity)\n // or check if we haven't received this part yet.\n // Since we use a simple 'fragmentReceived' counter, we effectively expect in-order delivery\n // of streams if we just use append logic.\n // BUT UDP can reorder.\n // To be robust, we should enforce strict ordering: fragStart must equal fragmentReceived.\n // If we miss a chunk, we ignore subsequent chunks until the missing one arrives (via retransmit loop).\n\n if (fragStart === this.fragmentReceived && fragStart + reliableLen <= fragTotal) {\n this.fragmentBuffer.set(data, fragStart);\n this.fragmentReceived += reliableLen;\n\n // Check if complete\n if (this.fragmentReceived >= fragTotal) {\n reliableData = this.fragmentBuffer;\n this.incomingReliableSequence++;\n this.fragmentBuffer = null;\n this.fragmentLength = 0;\n this.fragmentReceived = 0;\n }\n }\n\n } else {\n // Not a fragment (standard)\n this.incomingReliableSequence++;\n if (payloadOffset + reliableLen > packet.byteLength) return null;\n reliableData = packet.slice(payloadOffset, payloadOffset + reliableLen);\n }\n }\n\n // Advance past reliable data regardless\n payloadOffset += reliableLen;\n }\n\n // Get unreliable data\n const unreliableData = packet.slice(payloadOffset);\n\n // Combine if we have reliable data\n if (reliableData && reliableData.length > 0) {\n const totalLen = reliableData.length + unreliableData.length;\n const result = new Uint8Array(totalLen);\n result.set(reliableData, 0);\n result.set(unreliableData, reliableData.length);\n return result;\n }\n\n if (unreliableData) {\n return unreliableData;\n }\n\n return new Uint8Array(0);\n }\n\n /**\n * Checks if reliable message buffer is empty and ready for new data\n */\n canSendReliable(): boolean {\n return this.reliableLength === 0;\n }\n\n /**\n * Writes a byte to the reliable message buffer\n */\n writeReliableByte(value: number): void {\n if (this.reliableLength + 1 > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeByte(value);\n this.reliableLength++;\n }\n\n /**\n * Writes a short to the reliable message buffer\n */\n writeReliableShort(value: number): void {\n if (this.reliableLength + 2 > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeShort(value);\n this.reliableLength += 2;\n }\n\n /**\n * Writes a long to the reliable message buffer\n */\n writeReliableLong(value: number): void {\n if (this.reliableLength + 4 > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeLong(value);\n this.reliableLength += 4;\n }\n\n /**\n * Writes a string to the reliable message buffer\n */\n writeReliableString(value: string): void {\n const len = value.length + 1; // +1 for null terminator\n if (this.reliableLength + len > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeString(value);\n this.reliableLength += len;\n }\n\n /**\n * Returns the current reliable data buffer\n */\n getReliableData(): Uint8Array {\n if (this.reliableLength === 0) {\n return new Uint8Array(0);\n }\n const buffer = this.reliableMessage.getBuffer();\n return buffer.subarray(0, this.reliableLength);\n }\n\n /**\n * Checks if we need to send a keepalive packet\n */\n needsKeepalive(currentTime: number): boolean {\n return (currentTime - this.lastSent) > 1000;\n }\n\n /**\n * Checks if the connection has timed out\n */\n isTimedOut(currentTime: number, timeoutMs: number = 30000): boolean {\n return (currentTime - this.lastReceived) > timeoutMs;\n }\n}\n","/**\n * Weapon identifiers shared across game and cgame.\n * Reference: rerelease/g_items.cpp, game/src/inventory/playerInventory.ts\n */\n\nexport enum WeaponId {\n Blaster = 'blaster',\n Shotgun = 'shotgun',\n SuperShotgun = 'supershotgun', // Matched to assets (w_supershotgun, weapon_supershotgun)\n Machinegun = 'machinegun',\n Chaingun = 'chaingun',\n HandGrenade = 'grenades', // Matched to assets (w_grenades, weapon_grenades)\n GrenadeLauncher = 'grenadelauncher', // Matched to assets (w_grenadelauncher)\n RocketLauncher = 'rocketlauncher', // Matched to assets (w_rocketlauncher)\n HyperBlaster = 'hyperblaster',\n Railgun = 'railgun',\n BFG10K = 'bfg10k',\n // New additions for demo playback and extended support\n Grapple = 'grapple',\n ChainFist = 'chainfist',\n EtfRifle = 'etf_rifle', // Confirm asset?\n ProxLauncher = 'prox_launcher', // Confirm asset?\n IonRipper = 'ionripper',\n PlasmaBeam = 'plasmabeam',\n Phalanx = 'phalanx',\n Disruptor = 'disruptor',\n Trap = 'trap',\n}\n","/**\n * Ammo type identifiers shared across game and cgame.\n * Reference: rerelease/g_items.cpp, game/src/inventory/ammo.ts\n */\n\nexport enum AmmoType {\n Bullets = 0,\n Shells,\n Rockets,\n Grenades,\n Cells,\n Slugs,\n // RAFAEL\n MagSlugs,\n Trap,\n // RAFAEL\n // ROGUE\n Flechettes,\n Tesla,\n Disruptor, // Was missing or named differently?\n Prox,\n // ROGUE\n // Custom or Extras?\n Nuke,\n Rounds,\n}\n\nexport const AMMO_TYPE_COUNT = Object.keys(AmmoType).length / 2;\n\n/**\n * Item classnames for ammo pickups.\n * Used for spawning and identifying ammo items.\n */\nexport enum AmmoItemId {\n Shells = 'ammo_shells',\n Bullets = 'ammo_bullets',\n Rockets = 'ammo_rockets',\n Grenades = 'ammo_grenades',\n Cells = 'ammo_cells',\n Slugs = 'ammo_slugs',\n MagSlugs = 'ammo_magslug',\n Flechettes = 'ammo_flechettes',\n Disruptor = 'ammo_disruptor',\n Tesla = 'ammo_tesla',\n Trap = 'ammo_trap',\n Prox = 'ammo_prox',\n}\n","import { WeaponId } from './weapons.js';\nimport { AmmoType } from './ammo.js';\n\n// Order matches Q2 original weapon wheel index order for bitmask generation\n// Used by both Game (for STAT_WEAPONS_OWNED calculation) and CGame (for weapon wheel UI)\nexport const WEAPON_WHEEL_ORDER: WeaponId[] = [\n WeaponId.Blaster,\n WeaponId.Shotgun,\n WeaponId.SuperShotgun,\n WeaponId.Machinegun,\n WeaponId.Chaingun,\n WeaponId.GrenadeLauncher,\n WeaponId.RocketLauncher,\n WeaponId.HandGrenade,\n WeaponId.HyperBlaster,\n WeaponId.Railgun,\n WeaponId.BFG10K\n];\n\n// Mapping of weapon to its ammo type\n// Used by CGame to lookup ammo counts for weapon wheel\nexport const WEAPON_AMMO_MAP: Record<WeaponId, AmmoType | null> = {\n [WeaponId.Blaster]: null,\n [WeaponId.Shotgun]: AmmoType.Shells,\n [WeaponId.SuperShotgun]: AmmoType.Shells,\n [WeaponId.Machinegun]: AmmoType.Bullets,\n [WeaponId.Chaingun]: AmmoType.Bullets,\n [WeaponId.HandGrenade]: AmmoType.Grenades,\n [WeaponId.GrenadeLauncher]: AmmoType.Grenades,\n [WeaponId.RocketLauncher]: AmmoType.Rockets,\n [WeaponId.HyperBlaster]: AmmoType.Cells,\n [WeaponId.Railgun]: AmmoType.Slugs,\n [WeaponId.BFG10K]: AmmoType.Cells,\n\n // Extensions / Rogue / Xatrix\n [WeaponId.Grapple]: null,\n [WeaponId.ChainFist]: null,\n [WeaponId.EtfRifle]: AmmoType.Flechettes,\n [WeaponId.ProxLauncher]: AmmoType.Prox,\n [WeaponId.IonRipper]: AmmoType.Cells,\n [WeaponId.PlasmaBeam]: AmmoType.Cells,\n [WeaponId.Phalanx]: AmmoType.MagSlugs,\n [WeaponId.Disruptor]: AmmoType.Disruptor,\n [WeaponId.Trap]: AmmoType.Trap,\n};\n","export const MAX_SOUND_CHANNELS = 32;\n\n// Sound channel identifiers and flags from the rerelease game headers.\nexport enum SoundChannel {\n Auto = 0,\n Weapon = 1,\n Voice = 2,\n Item = 3,\n Body = 4,\n Aux = 5,\n Footstep = 6,\n Aux3 = 7,\n\n NoPhsAdd = 1 << 3,\n Reliable = 1 << 4,\n ForcePos = 1 << 5,\n}\n\nexport const ATTN_LOOP_NONE = -1;\nexport const ATTN_NONE = 0;\nexport const ATTN_NORM = 1;\nexport const ATTN_IDLE = 2;\nexport const ATTN_STATIC = 3;\n\nexport const SOUND_FULLVOLUME = 80;\nexport const SOUND_LOOP_ATTENUATE = 0.003;\n\nexport function attenuationToDistanceMultiplier(attenuation: number): number {\n return attenuation * 0.001;\n}\n\nexport function calculateMaxAudibleDistance(attenuation: number): number {\n const distMult = attenuationToDistanceMultiplier(attenuation);\n return distMult <= 0 ? Number.POSITIVE_INFINITY : SOUND_FULLVOLUME + 1 / distMult;\n}\n","import { PlayerState } from './protocol/index.js';\nimport { AmmoItemId, AmmoType, WeaponId } from './items/index.js';\nimport { G_GetAmmoStat } from './protocol/stats.js';\nimport { WEAPON_AMMO_MAP } from './items/index.js';\nimport { ConfigStringIndex } from './protocol/configstrings.js';\n\n// Blaster uses no ammo in standard Q2.\n// We handle mapping `AmmoItemId` (string) to `AmmoType` (enum).\nexport const AMMO_ITEM_MAP: Record<AmmoItemId, AmmoType> = {\n [AmmoItemId.Shells]: AmmoType.Shells,\n [AmmoItemId.Bullets]: AmmoType.Bullets,\n [AmmoItemId.Rockets]: AmmoType.Rockets,\n [AmmoItemId.Grenades]: AmmoType.Grenades,\n [AmmoItemId.Cells]: AmmoType.Cells,\n [AmmoItemId.Slugs]: AmmoType.Slugs,\n [AmmoItemId.MagSlugs]: AmmoType.MagSlugs,\n [AmmoItemId.Flechettes]: AmmoType.Flechettes,\n [AmmoItemId.Disruptor]: AmmoType.Disruptor,\n [AmmoItemId.Tesla]: AmmoType.Tesla,\n [AmmoItemId.Trap]: AmmoType.Trap,\n [AmmoItemId.Prox]: AmmoType.Prox,\n};\n\n/**\n * Retrieves the ammo count for a given item (Weapon or Ammo).\n * @param playerState The current player state.\n * @param item The item identifier (WeaponId or AmmoItemId).\n * @returns The ammo count, or 0 if not found/applicable. Returns -1 for infinite ammo (e.g. Blaster).\n */\nexport function getAmmoCount(playerState: PlayerState, item: WeaponId | AmmoItemId): number {\n let ammoType: AmmoType | null | undefined;\n\n // Check if it's an Ammo Item ID\n if (Object.values(AmmoItemId).includes(item as AmmoItemId)) {\n ammoType = AMMO_ITEM_MAP[item as AmmoItemId];\n }\n // Check if it's a Weapon ID\n else if (Object.values(WeaponId).includes(item as WeaponId)) {\n ammoType = WEAPON_AMMO_MAP[item as WeaponId];\n\n // Existing map has null for Blaster, Grapple, etc.\n if (ammoType === null) {\n return -1;\n }\n }\n\n if (ammoType === undefined || ammoType === null) {\n return 0;\n }\n\n return G_GetAmmoStat(playerState.stats, ammoType);\n}\n\n/**\n * Resolves the icon path for a given stat index (e.g. STAT_SELECTED_ICON).\n * @param statIndex The index in the stats array to read (e.g. PlayerStat.STAT_SELECTED_ICON).\n * @param playerState The player state containing the stats.\n * @param configStrings The array of configuration strings (from client state).\n * @returns The path to the icon image, or undefined if invalid.\n */\nexport function getIconPath(\n statIndex: number,\n playerState: PlayerState,\n configStrings: string[]\n): string | undefined {\n const iconIndex = playerState.stats[statIndex];\n\n // 0 usually means no icon or null\n if (iconIndex === undefined || iconIndex <= 0) {\n return undefined;\n }\n\n // The value in the stat is the index into the Config Strings relative to ConfigStringIndex.Images.\n const configIndex = ConfigStringIndex.Images + iconIndex;\n\n if (configIndex < 0 || configIndex >= configStrings.length) {\n return undefined;\n }\n\n return configStrings[configIndex];\n}\n","import type { PmoveTraceFn, PmoveTraceResult } from './pmove/types.js';\nimport type { Vec3 } from './math/vec3.js';\nimport { CONTENTS_LADDER } from './bsp/contents.js';\n\nexport const intersects = (end: Vec3, maxs: Vec3, mins: Vec3, boxMins: Vec3, boxMaxs: Vec3): boolean => {\n return (\n end.x + maxs.x > boxMins.x &&\n end.x + mins.x < boxMaxs.x &&\n end.y + maxs.y > boxMins.y &&\n end.y + mins.y < boxMaxs.y &&\n end.z + maxs.z > boxMins.z &&\n end.z + mins.z < boxMaxs.z\n );\n};\n\nexport const stairTrace: PmoveTraceFn = (start: Vec3, end: Vec3, mins?: Vec3, maxs?: Vec3): PmoveTraceResult => {\n // Default bbox if not provided\n const useMins = mins ?? { x: -16, y: -16, z: -24 };\n const useMaxs = maxs ?? { x: 16, y: 16, z: 32 };\n\n // Step: x from 0 forward, z from 0 to 8\n const STEP_HEIGHT = 8;\n const STEP_X_START = 0;\n\n const isHorizontal = Math.abs(end.z - start.z) < 1;\n const isMovingDown = end.z < start.z;\n\n // Check if trying to go below the floor\n const endMinZ = end.z + useMins.z;\n const startMinZ = start.z + useMins.z;\n const endMaxX = end.x + useMaxs.x;\n\n // If moving horizontally, check if we'd hit the vertical face of the step\n // The step only blocks if the player's origin is below the step height\n if (isHorizontal && end.z < STEP_HEIGHT && endMaxX > STEP_X_START) {\n // Check if we're crossing into the step area\n const startMaxX = start.x + useMaxs.x;\n if (startMaxX <= STEP_X_START) {\n // We're moving from before the step to past it, block\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: -1, y: 0, z: 0 },\n contents: 1,\n };\n }\n }\n\n // If moving down and over the step area, land on the step surface\n if (isMovingDown && end.x >= STEP_X_START) {\n // The step surface is at z=STEP_HEIGHT in world space\n // The player's bbox bottom reaches this plane when origin.z + mins.z = STEP_HEIGHT\n // So the player's origin should be at z = STEP_HEIGHT - mins.z\n const landZ = STEP_HEIGHT - useMins.z;\n\n // Check if we'd pass through the step surface\n // We cross the plane if start is above it and end would be below it\n if (startMinZ > STEP_HEIGHT && endMinZ < STEP_HEIGHT) {\n // Calculate the fraction along the ray where we intersect the plane\n // The bbox bottom is at: start.z + useMins.z + t * (end.z - start.z + 0) = STEP_HEIGHT\n // Solving for t: t = (STEP_HEIGHT - (start.z + useMins.z)) / ((end.z + useMins.z) - (start.z + useMins.z))\n const fraction = (STEP_HEIGHT - startMinZ) / (endMinZ - startMinZ);\n\n // Clamp to valid range [0, 1]\n const clampedFraction = Math.max(0, Math.min(1, fraction));\n\n // Calculate the endpos along the ray at this fraction\n const finalX = start.x + clampedFraction * (end.x - start.x);\n const finalY = start.y + clampedFraction * (end.y - start.y);\n const finalZ = start.z + clampedFraction * (end.z - start.z);\n\n return {\n allsolid: false,\n startsolid: false,\n fraction: clampedFraction,\n endpos: { x: finalX, y: finalY, z: finalZ },\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n }\n\n // If moving down and would go below floor level, block at floor\n if (isMovingDown && endMinZ < 0) {\n // Floor is at z=0, so player origin should be at z = -mins.z when landing\n const landZ = -useMins.z;\n\n // Only apply if we're crossing the floor plane\n if (startMinZ >= 0) {\n // Calculate fraction where bbox bottom hits z=0\n const fraction = (0 - startMinZ) / (endMinZ - startMinZ);\n const clampedFraction = Math.max(0, Math.min(1, fraction));\n\n const finalX = start.x + clampedFraction * (end.x - start.x);\n const finalY = start.y + clampedFraction * (end.y - start.y);\n const finalZ = start.z + clampedFraction * (end.z - start.z);\n\n return {\n allsolid: false,\n startsolid: false,\n fraction: clampedFraction,\n endpos: { x: finalX, y: finalY, z: finalZ },\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n\n // Already below floor, block immediately\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n\n // Free movement\n return {\n allsolid: false,\n startsolid: false,\n fraction: 1.0,\n endpos: end,\n contents: 0,\n };\n};\n\nexport const ladderTrace: PmoveTraceFn = (start: Vec3, end: Vec3, mins?: Vec3, maxs?: Vec3): PmoveTraceResult => {\n // Default bbox if not provided\n const useMins = mins ?? { x: -16, y: -16, z: -24 };\n const useMaxs = maxs ?? { x: 16, y: 16, z: 32 };\n\n // Define the ladder volume (x=0 to x=8, y=-16 to y=16, z=0 to z=100)\n const LADDER_X_MIN = 0;\n const LADDER_X_MAX = 8;\n const LADDER_Y_MIN = -16;\n const LADDER_Y_MAX = 16;\n const LADDER_Z_MIN = 0;\n const LADDER_Z_MAX = 100;\n\n // Check if end position is within the ladder volume\n const endInLadder =\n end.x + useMins.x < LADDER_X_MAX &&\n end.x + useMaxs.x > LADDER_X_MIN &&\n end.y + useMins.y < LADDER_Y_MAX &&\n end.y + useMaxs.y > LADDER_Y_MIN &&\n end.z + useMins.z < LADDER_Z_MAX &&\n end.z + useMaxs.z > LADDER_Z_MIN;\n\n // If moving into the ladder from outside (moving forward into it)\n const movingIntoLadder = start.x < LADDER_X_MIN && end.x >= LADDER_X_MIN;\n\n // If moving horizontally into the ladder front face, block with ladder surface\n if (movingIntoLadder && Math.abs(end.z - start.z) < 0.1) {\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: -1, y: 0, z: 0 },\n contents: CONTENTS_LADDER,\n };\n }\n\n // If we're in the ladder volume, return success but with CONTENTS_LADDER\n // This allows the player to detect they're on a ladder without blocking movement\n if (endInLadder) {\n return {\n allsolid: false,\n startsolid: false,\n fraction: 1.0,\n endpos: end,\n contents: CONTENTS_LADDER,\n };\n }\n\n // Floor at z=0\n if (end.z + useMins.z <= 0) {\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n\n // No collision - free movement\n return {\n allsolid: false,\n startsolid: false,\n fraction: 1.0,\n endpos: end,\n contents: 0,\n };\n};\n","import { CGameImport } from '../types.js';\n\nlet crosshairPic: unknown | null = null;\nlet crosshairIndex = 0; // Default to ch1\nlet crosshairColor: [number, number, number, number] = [1, 1, 1, 1]; // Default white\nlet crosshairEnabled = true;\n\nconst CROSSHAIR_NAMES = ['ch1', 'ch2', 'ch3'];\nconst crosshairPics: (unknown | null)[] = [null, null, null];\n\nexport const Init_Crosshair = (cgi: CGameImport) => {\n for (let i = 0; i < CROSSHAIR_NAMES.length; i++) {\n const name = CROSSHAIR_NAMES[i];\n try {\n crosshairPics[i] = cgi.Draw_RegisterPic(`pics/${name}.pcx`);\n } catch (e) {\n if (i === 0) {\n try {\n crosshairPics[i] = cgi.Draw_RegisterPic('pics/crosshair.pcx');\n } catch (e2) {\n cgi.Com_Print('Failed to load crosshair image\\n');\n }\n }\n }\n }\n\n crosshairPic = crosshairPics[0];\n}\n\nexport const Set_Crosshair = (index: number) => {\n // If index is 0, we treat it as disabled if we want to follow Q2 convention strictly,\n // but here index maps to CROSSHAIR_NAMES.\n // If we want a \"None\" option, we can check for that.\n\n // For now, let's keep index pointing to textures.\n // We can add a separate enable/disable function or make index -1 disable it.\n\n if (index === -1) {\n crosshairEnabled = false;\n return;\n }\n\n crosshairEnabled = true;\n if (index >= 0 && index < crosshairPics.length) {\n crosshairIndex = index;\n crosshairPic = crosshairPics[index];\n }\n};\n\nexport const Set_CrosshairColor = (r: number, g: number, b: number, a: number = 1) => {\n crosshairColor = [r, g, b, a];\n}\n\nexport const Cycle_Crosshair = () => {\n // Cycle includes a \"None\" state (represented by index -1 or just disabling)\n // 0 -> 1 -> 2 -> ... -> Disabled -> 0\n\n if (!crosshairEnabled) {\n crosshairEnabled = true;\n crosshairIndex = 0;\n } else {\n crosshairIndex++;\n if (crosshairIndex >= CROSSHAIR_NAMES.length) {\n crosshairEnabled = false;\n crosshairIndex = 0; // Reset for next cycle\n }\n }\n\n if (crosshairEnabled) {\n crosshairPic = crosshairPics[crosshairIndex];\n if (!crosshairPic) {\n let found = false;\n for (let i = 0; i < CROSSHAIR_NAMES.length; i++) {\n const idx = (crosshairIndex + i) % CROSSHAIR_NAMES.length;\n if (crosshairPics[idx]) {\n crosshairIndex = idx;\n crosshairPic = crosshairPics[idx];\n found = true;\n break;\n }\n }\n if (!found) crosshairPic = null;\n }\n } else {\n crosshairPic = null;\n }\n\n return crosshairEnabled ? crosshairIndex : -1;\n};\n\nexport const Draw_Crosshair = (cgi: CGameImport, width: number, height: number) => {\n if (crosshairEnabled && crosshairPic) {\n const size = cgi.Draw_GetPicSize(crosshairPic);\n const x = (width - size.width) / 2;\n const y = (height - size.height) / 2;\n // Draw with color\n cgi.SCR_DrawColorPic(x, y, crosshairPic, { x: crosshairColor[0], y: crosshairColor[1], z: crosshairColor[2] }, crosshairColor[3]);\n }\n};\n","import { CGameImport } from '../types.js';\n\n/**\n * Global map of loaded HUD icons.\n * This is imported and used by statusbar.ts for rendering.\n */\nexport const iconPics = new Map<string, unknown>();\n\nconst ICON_NAMES = [\n // Weapons\n 'w_blaster', 'w_shotgun', 'w_sshotgun', 'w_machinegun', 'w_chaingun',\n 'w_glauncher', 'w_rlauncher', 'w_hyperblaster', 'w_railgun', 'w_bfg',\n 'w_grapple',\n // Ammo\n 'a_grenades', 'a_bullets', 'a_cells', 'a_rockets', 'a_shells', 'a_slugs',\n // Powerups\n 'p_quad', 'p_invulnerability', 'p_silencer', 'p_rebreather', 'p_envirosuit',\n 'p_adrenaline', 'p_megahealth',\n // Armor\n 'i_jacketarmor', 'i_combatarmor', 'i_bodyarmor', 'i_powerscreen', 'i_powershield',\n // Keys\n 'k_datacd', 'k_powercube', 'k_pyramid', 'k_dataspin', 'k_security', 'k_bluekey', 'k_redkey'\n];\n\n/**\n * Initialize and precache all HUD icon images.\n * Called during level load via CG_TouchPics().\n */\nexport const Init_Icons = (cgi: CGameImport) => {\n for (const name of ICON_NAMES) {\n try {\n const pic = cgi.Draw_RegisterPic(`pics/${name}.pcx`);\n iconPics.set(name, pic);\n } catch (e) {\n cgi.Com_Print(`Failed to load HUD image: pics/${name}.pcx\\n`);\n }\n }\n};\n","import { CGameImport } from '../types.js';\nimport { PlayerState, Vec3, dotVec3, angleVectors } from '@quake2ts/shared';\n\nconst damagePics = new Map<string, unknown>();\n\nconst DAMAGE_INDICATOR_NAMES = [\n 'd_left', 'd_right', 'd_up', 'd_down'\n];\n\nexport const Init_Damage = (cgi: CGameImport) => {\n for (const name of DAMAGE_INDICATOR_NAMES) {\n try {\n const pic = cgi.Draw_RegisterPic(`pics/${name}.pcx`);\n damagePics.set(name, pic);\n } catch (e) {\n cgi.Com_Print(`Failed to load HUD image: pics/${name}.pcx\\n`);\n }\n }\n};\n\nconst WHITE: Vec3 = { x: 1, y: 1, z: 1 };\n\nexport const Draw_Damage = (cgi: CGameImport, ps: PlayerState, width: number, height: number) => {\n // Check if we have damage to show\n if ((!ps.damageAlpha || ps.damageAlpha <= 0) && (!ps.damageIndicators || ps.damageIndicators.length === 0)) {\n return;\n }\n\n if (!ps.damageIndicators || ps.damageIndicators.length === 0) {\n return;\n }\n\n const cx = width * 0.5;\n const cy = height * 0.5;\n const { forward, right } = angleVectors(ps.viewAngles);\n\n // Draw indicators at a fixed radius from the center of the screen\n const radius = Math.min(width, height) * 0.25;\n\n for (const indicator of ps.damageIndicators) {\n // Project the direction vector onto the player's view plane\n // indicator.direction is assumed to be the vector pointing TO the damage source\n const localRight = dotVec3(indicator.direction, right);\n const localForward = dotVec3(indicator.direction, forward);\n\n // Calculate the angle relative to the player's view\n // 0 degrees = Right, 90 degrees = Forward\n const angle = Math.atan2(localForward, localRight) * (180 / Math.PI);\n\n let picName = '';\n let xOff = 0;\n let yOff = 0;\n\n // Map angle to quadrants\n if (angle >= 45 && angle < 135) {\n // Front (Up)\n picName = 'd_up';\n yOff = -radius;\n } else if (angle >= -45 && angle < 45) {\n // Right\n picName = 'd_right';\n xOff = radius;\n } else if (angle >= -135 && angle < -45) {\n // Back (Down)\n picName = 'd_down';\n yOff = radius;\n } else {\n // Left (angle >= 135 || angle < -135)\n picName = 'd_left';\n xOff = -radius;\n }\n\n const pic = damagePics.get(picName);\n if (pic) {\n const size = cgi.Draw_GetPicSize(pic);\n // Center the sprite at the calculated offset position\n const x = cx + xOff - size.width * 0.5;\n const y = cy + yOff - size.height * 0.5;\n\n // Use indicator strength as alpha, clamped to [0, 1]\n const alpha = Math.max(0, Math.min(1, indicator.strength));\n cgi.SCR_DrawColorPic(x, y, pic, WHITE, alpha);\n }\n }\n};\n","import type { CGameImport } from '../types.js';\nimport { getHudLayout } from './layout.js';\n\ninterface Message {\n text: string;\n startTime: number;\n duration: number;\n}\n\nconst CENTER_PRINT_DURATION = 3000;\nconst NOTIFY_DURATION = 5000;\nconst MAX_NOTIFY_MESSAGES = 4;\n\nexport class MessageSystem {\n private centerPrintMsg: Message | null = null;\n private notifyMessages: Message[] = [];\n\n addCenterPrint(text: string, now: number) {\n this.centerPrintMsg = {\n text,\n startTime: now,\n duration: CENTER_PRINT_DURATION,\n };\n }\n\n addNotify(text: string, now: number) {\n this.notifyMessages.push({\n text,\n startTime: now,\n duration: NOTIFY_DURATION,\n });\n\n if (this.notifyMessages.length > MAX_NOTIFY_MESSAGES) {\n this.notifyMessages.shift();\n }\n }\n\n // Additional methods for cgame API\n setCenterPrint(text: string, now: number) {\n this.centerPrintMsg = {\n text,\n startTime: now,\n duration: CENTER_PRINT_DURATION,\n };\n }\n\n addNotification(text: string, is_chat: boolean, now: number) {\n this.notifyMessages.push({\n text,\n startTime: now,\n duration: NOTIFY_DURATION,\n });\n\n if (this.notifyMessages.length > MAX_NOTIFY_MESSAGES) {\n this.notifyMessages.shift();\n }\n }\n\n clearNotifications() {\n this.notifyMessages = [];\n }\n\n clearCenterPrint() {\n this.centerPrintMsg = null;\n }\n\n drawCenterPrint(cgi: CGameImport, now: number, layout: ReturnType<typeof getHudLayout>) {\n if (!this.centerPrintMsg) return;\n\n if (now > this.centerPrintMsg.startTime + this.centerPrintMsg.duration) {\n this.centerPrintMsg = null;\n return;\n }\n\n // Draw centered text\n const y = layout.CENTER_PRINT_Y;\n\n cgi.SCR_DrawCenterString(y, this.centerPrintMsg.text);\n }\n\n drawNotifications(cgi: CGameImport, now: number) {\n // Remove expired messages\n while (this.notifyMessages.length > 0 && now > this.notifyMessages[0].startTime + this.notifyMessages[0].duration) {\n this.notifyMessages.shift();\n }\n\n let y = 10; // Start near top-left\n for (const msg of this.notifyMessages) {\n cgi.SCR_DrawFontString(10, y, msg.text); // Use SCR_DrawFontString instead of drawString\n y += cgi.SCR_FontLineHeight();\n }\n }\n}\n","import { CGameImport } from '../types.js';\n\ninterface Subtitle {\n text: string;\n startTime: number;\n duration: number;\n}\n\nconst SUBTITLE_DURATION = 3000;\n\nexport class SubtitleSystem {\n private subtitle: Subtitle | null = null;\n\n addSubtitle(text: string, now: number) {\n this.subtitle = {\n text,\n startTime: now,\n duration: SUBTITLE_DURATION,\n };\n }\n\n drawSubtitles(cgi: CGameImport, now: number) {\n if (!this.subtitle) {\n return;\n }\n\n if (now > this.subtitle.startTime + this.subtitle.duration) {\n this.subtitle = null;\n return;\n }\n\n // Draw centered text at the bottom of the screen\n // We assume 240 is roughly 480/2 or similar scale, but typically CGame uses virtual coordinates.\n // If SCR_DrawCenterString uses virtual coords (usually based on 320x240 or similar),\n // we need to know the virtual screen height.\n // However, existing SCR_DrawCenterString likely handles centering horizontally.\n // We just need a Y coordinate.\n // In original Q2, HUD is drawn in a virtual 320x240 space usually, or scaled.\n // Let's assume SCR_DrawCenterString takes a Y coordinate in virtual space.\n // Typically bottom of screen.\n\n // For now, let's try a reasonable offset from bottom.\n // If standard Q2 res is 320x240, bottom is 240.\n const y = 200;\n\n cgi.SCR_DrawCenterString(y, this.subtitle.text);\n }\n}\n","import { CGameImport } from '../types.js';\nimport { PlayerState } from '@quake2ts/shared';\n\nexport const Draw_Blends = (cgi: CGameImport, ps: PlayerState, width: number, height: number) => {\n if (!ps.blend) return;\n\n const [r, g, b, a] = ps.blend;\n\n if (a > 0) {\n // Use SCR_DrawColorPic with a white pixel/texture stretched?\n // Or cgi needs a fill rect function.\n // SCR_DrawPic usually takes a pic.\n // Rerelease might use a specific blend function or just a 1x1 white texture scaled up.\n // Assuming cgi can draw colored quads if we register a \"white\" texture or similar.\n // For now, let's assume we can draw a colored rectangle if we had a white texture.\n\n // Since we don't have a fillRect in CGameImport, we might need to add it or use a registered texture.\n // Let's assume for now we skip or need to register a 'pics/white.pcx' or similar if it existed.\n // A common trick is to use any opaque texture and tint it, but that shows the texture.\n\n // Let's defer this or add a \"DrawFill\" to CGameImport if strictly needed,\n // OR standard Q2 just uses the poly drawing which isn't exposed yet.\n // Actually, Q2 V_CalcBlend handles this by setting palette/gamma or drawing a full screen poly.\n\n // For this port, we likely want a SCR_DrawFill calls.\n // Let's add SCR_DrawFill to CGameImport in types.ts in next step if it's missing.\n // Checking types.ts... it has SCR_DrawChar, SCR_DrawPic... no DrawFill.\n\n // I'll leave it commented/TODO for now or assume a 'white' pic is available.\n // cgi.SCR_DrawColorPic(0, 0, whitePic, {x:r, y:g, z:b}, a);\n }\n};\n","import { CGameImport } from '../types.js';\nimport { PlayerState } from '@quake2ts/shared';\nimport { iconPics } from './icons.js'; // Reuse loaded icons\n\nexport const Draw_Pickup = (cgi: CGameImport, ps: PlayerState, width: number, height: number) => {\n if (!ps.pickupIcon) return;\n\n const icon = iconPics.get(ps.pickupIcon);\n if (icon) {\n const size = cgi.Draw_GetPicSize(icon);\n const x = width - size.width - 10;\n const y = height - size.height - 10;\n cgi.SCR_DrawPic(x, y, icon);\n }\n};\n","import { CGameImport } from '../types.js';\n\nexport const Draw_Number = (cgi: CGameImport, x: number, y: number, value: number, pics: readonly unknown[], width: number, color?: [number, number, number, number]) => {\n const s = Math.abs(value).toString();\n for (let i = 0; i < s.length; i++) {\n const digit = parseInt(s[i]);\n const pic = pics[digit];\n if (pic) {\n if (color) {\n // cgi expects color as Vec3 (x,y,z) and alpha separate.\n // Assuming color is [r, g, b, a]\n cgi.SCR_DrawColorPic(x + i * width, y, pic, { x: color[0], y: color[1], z: color[2] }, color[3]);\n } else {\n cgi.SCR_DrawPic(x + i * width, y, pic);\n }\n }\n }\n};\n","import { CGameImport } from '../types.js';\nimport { Draw_Number } from './numbers.js';\nimport { getHudLayout } from './layout.js';\nimport { PlayerState, PlayerStat, ConfigStringIndex } from '@quake2ts/shared';\n\nlet colorblindMode = false;\n\nexport const Set_ColorblindMode = (enabled: boolean) => {\n colorblindMode = enabled;\n};\n\n/**\n * Draws the status bar (health, armor, ammo, icons) using ps.stats.\n *\n * NOTE: This implementation relies on the server correctly populating ps.stats\n * (STAT_HEALTH, STAT_ARMOR, STAT_AMMO, etc.) and valid configstring mappings\n * for icons (STAT_SELECTED_ICON, STAT_ARMOR_ICON, etc.).\n *\n * If ps.stats is not yet populated by the server (or is empty), the HUD will\n * display zeros or nothing. This is expected behavior during the migration phase.\n */\nexport const Draw_StatusBar = (\n cgi: CGameImport,\n ps: PlayerState,\n hudNumberPics: readonly unknown[],\n numberWidth: number,\n timeMs: number,\n layout: ReturnType<typeof getHudLayout>\n) => {\n // Stat Indices\n const health = ps.stats[PlayerStat.STAT_HEALTH] || 0;\n const armor = ps.stats[PlayerStat.STAT_ARMOR] || 0;\n // STAT_AMMO is no longer packed, it's just the integer count of the current ammo.\n const ammo = ps.stats[PlayerStat.STAT_AMMO] || 0;\n\n // Icon Indices (into ConfigStrings or predefined map)\n const armorIconIdx = ps.stats[PlayerStat.STAT_ARMOR_ICON] || 0;\n // const ammoIconIdx = ps.stats[PlayerStat.STAT_AMMO_ICON] || 0; // Unused in standard Q2 HUD?\n\n // Draw Health\n let healthColor: [number, number, number, number] | undefined = undefined;\n\n if (health <= 25) {\n if (colorblindMode) {\n // Use Blue/Cyan for low health in colorblind mode instead of Red\n healthColor = [0.2, 0.6, 1, 1];\n } else {\n healthColor = [1, 0, 0, 1]; // Red for low health\n }\n }\n\n if (hudNumberPics.length > 0) {\n Draw_Number(cgi, layout.HEALTH_X, layout.HEALTH_Y, health, hudNumberPics, numberWidth, healthColor);\n Draw_Number(cgi, layout.ARMOR_X, layout.ARMOR_Y, armor, hudNumberPics, numberWidth);\n Draw_Number(cgi, layout.AMMO_X, layout.AMMO_Y, ammo, hudNumberPics, numberWidth);\n }\n\n // Draw Armor Icon\n if (armorIconIdx > 0) {\n const iconName = cgi.get_configstring(ConfigStringIndex.Images + armorIconIdx);\n if (iconName) {\n const icon = cgi.Draw_RegisterPic(iconName);\n if (icon) {\n cgi.SCR_DrawPic(layout.ARMOR_X - 24, layout.ARMOR_Y - 2, icon);\n }\n }\n }\n\n // Draw Weapon Icon\n // Uses STAT_SELECTED_ICON\n if (ps.pickupIcon) {\n // Fallback to legacy string field if present, helpful for transition\n const icon = cgi.Draw_RegisterPic(ps.pickupIcon);\n if (icon) {\n cgi.SCR_DrawPic(layout.WEAPON_ICON_X, layout.WEAPON_ICON_Y, icon);\n }\n } else {\n // Standard Q2 path via STAT_SELECTED_ICON\n const selectedIconIdx = ps.stats[PlayerStat.STAT_SELECTED_ICON] || 0;\n if (selectedIconIdx > 0) {\n const iconName = cgi.get_configstring(ConfigStringIndex.Images + selectedIconIdx);\n if (iconName) {\n const icon = cgi.Draw_RegisterPic(iconName);\n if (icon) {\n cgi.SCR_DrawPic(layout.WEAPON_ICON_X, layout.WEAPON_ICON_Y, icon);\n }\n }\n }\n }\n\n // Draw Keys\n // Rerelease/Q2 uses STAT_LAYOUTS to determine if inventory/keys overlay is shown.\n // But for the persistent key icons on the HUD (Q2TS specific feature?), we might need logic.\n // Standard Q2 doesn't show key icons on the main HUD, only in inventory.\n // If we want to keep Q2TS specific key icons, we need to know which keys we have.\n // Since we don't have the inventory set in ps.stats easily (unless packed),\n // we might lose this feature until we implement a \"Key Stat\" or read inventory bits.\n //\n // For now, we omit the key drawing if we don't have the data, matching standard Q2 behavior.\n\n // Draw Powerups\n // Handled by Draw_Blends or STAT_TIMER logic usually.\n};\n","// Dynamic Layout Scaling\nconst REFERENCE_WIDTH = 640;\nconst REFERENCE_HEIGHT = 480;\n\nexport const getHudLayout = (width: number, height: number) => {\n // Determine scale factor - usually based on height to preserve aspect ratio logic or just scale uniform\n // Quake 2 typically scales 2D elements.\n const scaleX = width / REFERENCE_WIDTH;\n const scaleY = height / REFERENCE_HEIGHT;\n const scale = Math.min(scaleX, scaleY); // Uniform scaling\n\n // Or we can just center the 640x480 rect?\n // Modern approach: Scale UI to fit, or anchor to edges.\n // Let's implement edge anchoring logic relative to 640x480 coordinates.\n\n // Original constants (approximate):\n // HEALTH_X: 100, HEALTH_Y: 450\n // ARMOR_X: 200, ARMOR_Y: 450\n // AMMO_X: 540, AMMO_Y: 450\n // CENTER_PRINT: Center screen\n // WEAPON_ICON: Bottom left\n // POWERUP: Bottom right?\n\n // We'll return scaled coordinates.\n // For bottom elements, we should anchor to bottom.\n\n return {\n // Status bar numbers - Anchored Bottom-Left / Center / Right\n HEALTH_X: 100 * scale,\n HEALTH_Y: height - (REFERENCE_HEIGHT - 450) * scale,\n\n ARMOR_X: 200 * scale,\n ARMOR_Y: height - (REFERENCE_HEIGHT - 450) * scale,\n\n AMMO_X: width - (REFERENCE_WIDTH - 540) * scale, // Anchor right? 540 is near right (640)\n AMMO_Y: height - (REFERENCE_HEIGHT - 450) * scale,\n\n // Center print messages - Center\n CENTER_PRINT_X: width / 2,\n CENTER_PRINT_Y: 100 * scale, // Top anchor\n\n // Weapon and powerup icons\n WEAPON_ICON_X: 10 * scale,\n WEAPON_ICON_Y: height - (REFERENCE_HEIGHT - 450) * scale,\n\n POWERUP_X: width - (REFERENCE_WIDTH - 610) * scale,\n POWERUP_Y: height - (REFERENCE_HEIGHT - 450) * scale,\n\n scale: scale\n };\n};\n\n// Backward compatibility (deprecated, but useful for initial refactor)\nexport const HUD_LAYOUT = {\n HEALTH_X: 100,\n HEALTH_Y: 450,\n ARMOR_X: 200,\n ARMOR_Y: 450,\n AMMO_X: 540,\n AMMO_Y: 450,\n CENTER_PRINT_X: 320,\n CENTER_PRINT_Y: 100,\n WEAPON_ICON_X: 10,\n WEAPON_ICON_Y: 450,\n POWERUP_X: 610,\n POWERUP_Y: 450,\n};\n","/**\n * CGame HUD Screen Drawing\n * Reference: rerelease/cg_screen.cpp\n *\n * This module handles all HUD rendering for the cgame package, including:\n * - Status bar (health, armor, ammo)\n * - Crosshair\n * - Damage indicators\n * - Pickup notifications\n * - Messages and center print\n * - Subtitles\n */\n\nimport type { PlayerState } from '@quake2ts/shared';\nimport type { CGameImport } from './types.js';\n\n// HUD component imports\nimport { Draw_Crosshair, Init_Crosshair } from './hud/crosshair.js';\nimport { Init_Icons } from './hud/icons.js';\nimport { Draw_Damage, Init_Damage } from './hud/damage.js';\nimport { Draw_Diagnostics } from './hud/diagnostics.js';\nimport { MessageSystem } from './hud/messages.js';\nimport { SubtitleSystem } from './hud/subtitles.js';\nimport { Draw_Blends } from './hud/blends.js';\nimport { Draw_Pickup } from './hud/pickup.js';\nimport { Draw_StatusBar } from './hud/statusbar.js';\nimport { getHudLayout } from './hud/layout.js';\n\n// Module-level state\nlet cgi: CGameImport | null = null;\nconst hudNumberPics: unknown[] = []; // Will hold pic handles from cgi.Draw_RegisterPic()\nlet numberWidth = 0;\n\n// Message and subtitle systems\nconst messageSystem = new MessageSystem();\nconst subtitleSystem = new SubtitleSystem();\n\n/**\n * Initialize the CGame screen module with import functions.\n * Reference: rerelease/cg_screen.cpp InitCGame()\n */\nexport function CG_InitScreen(imports: CGameImport): void {\n cgi = imports;\n}\n\n/**\n * Precache all HUD images.\n * Reference: rerelease/cg_screen.cpp:1689 (TouchPics)\n *\n * This is called during level load to register all required HUD assets.\n */\nexport function CG_TouchPics(): void {\n if (!cgi) return;\n\n // Load HUD number pics\n hudNumberPics.length = 0;\n for (let i = 0; i < 10; i++) {\n try {\n const pic = cgi.Draw_RegisterPic(`pics/hud/num_${i}.pcx`);\n hudNumberPics.push(pic);\n if (i === 0) {\n const size = cgi.Draw_GetPicSize(pic);\n numberWidth = size.width;\n }\n } catch (e) {\n cgi.Com_Print(`Warning: Failed to load HUD image: pics/hud/num_${i}.pcx\\n`);\n }\n }\n\n Init_Crosshair(cgi);\n Init_Icons(cgi);\n Init_Damage(cgi);\n}\n\n/**\n * Main HUD drawing function.\n * Reference: rerelease/cg_screen.cpp CG_DrawHUD()\n *\n * Called each frame by the client to render the HUD overlay.\n *\n * @param isplit - Split-screen index (0 for single player)\n * @param data - Additional HUD data (unused in initial implementation)\n * @param hud_vrect - Virtual HUD rectangle (screen coordinates)\n * @param hud_safe - Safe area rectangle (for overscan)\n * @param scale - HUD scale factor\n * @param playernum - Player number\n * @param ps - Current player state\n */\nexport function CG_DrawHUD(\n isplit: number,\n data: unknown,\n hud_vrect: { x: number; y: number; width: number; height: number },\n hud_safe: { x: number; y: number; width: number; height: number },\n scale: number,\n playernum: number,\n ps: PlayerState\n): void {\n if (!cgi) {\n console.error('CG_DrawHUD: cgame imports not initialized');\n return;\n }\n\n const timeMs = cgi.CL_ClientTime();\n const layout = getHudLayout(hud_vrect.width, hud_vrect.height);\n\n // Screen blends (damage, powerups)\n Draw_Blends(cgi, ps, hud_vrect.width, hud_vrect.height);\n\n // Status bar\n // Now directly using ps.stats via Draw_StatusBar\n Draw_StatusBar(cgi, ps, hudNumberPics, numberWidth, timeMs, layout);\n\n // Pickup messages\n Draw_Pickup(cgi, ps, hud_vrect.width, hud_vrect.height);\n\n // Damage indicators\n Draw_Damage(cgi, ps, hud_vrect.width, hud_vrect.height);\n\n // Center print (Legacy PS support)\n if (ps.centerPrint) {\n const lines = ps.centerPrint.split('\\n');\n let y = hud_vrect.height / 2 - (lines.length * 10); // Approximation\n for (const line of lines) {\n cgi.SCR_DrawCenterString(y, line);\n y += 16;\n }\n }\n\n // Message System (CenterPrint & Notifications)\n messageSystem.drawCenterPrint(cgi, timeMs, layout);\n messageSystem.drawNotifications(cgi, timeMs);\n\n // Subtitles\n subtitleSystem.drawSubtitles(cgi, timeMs);\n\n // Crosshair\n Draw_Crosshair(cgi, hud_vrect.width, hud_vrect.height);\n}\n\n/**\n * Get message system instance.\n * Used by parsing functions to add messages.\n */\nexport function CG_GetMessageSystem(): MessageSystem {\n return messageSystem;\n}\n\n/**\n * Get subtitle system instance.\n * Used by audio system to display subtitles.\n */\nexport function CG_GetSubtitleSystem(): SubtitleSystem {\n return subtitleSystem;\n}\n","import type { CGameImport } from './types.js';\nimport { ConfigStringIndex, MAX_MODELS, MAX_SOUNDS, MAX_IMAGES } from '@quake2ts/shared';\n\n/**\n * Parses a config string update and precaches assets if necessary.\n * Reference: rerelease/cg_main.cpp CL_ParseConfigString\n */\nexport function CG_ParseConfigString(cgi: CGameImport, i: number, s: string): void {\n if (i >= ConfigStringIndex.Models && i < ConfigStringIndex.Models + MAX_MODELS) {\n cgi.RegisterModel(s);\n } else if (i >= ConfigStringIndex.Sounds && i < ConfigStringIndex.Sounds + MAX_SOUNDS) {\n cgi.RegisterSound(s);\n } else if (i >= ConfigStringIndex.Images && i < ConfigStringIndex.Images + MAX_IMAGES) {\n cgi.Draw_RegisterPic(s);\n }\n}\n","/**\n * Common utilities\n * @module glMatrix\n */\n\n// Configuration Constants\nexport var EPSILON = 0.000001;\nexport var ARRAY_TYPE = typeof Float32Array !== \"undefined\" ? Float32Array : Array;\nexport var RANDOM = Math.random;\nexport var ANGLE_ORDER = \"zyx\";\n\n/**\n * Symmetric round\n * see https://www.npmjs.com/package/round-half-up-symmetric#user-content-detailed-background\n *\n * @param {Number} a value to round\n */\nexport function round(a) {\n if (a >= 0) return Math.round(a);\n return a % 0.5 === 0 ? Math.floor(a) : Math.round(a);\n}\n\n/**\n * Sets the type of array used when creating new vectors and matrices\n *\n * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array\n */\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\nvar degree = Math.PI / 180;\nvar radian = 180 / Math.PI;\n\n/**\n * Convert Degree To Radian\n *\n * @param {Number} a Angle in Degrees\n */\nexport function toRadian(a) {\n return a * degree;\n}\n\n/**\n * Convert Radian To Degree\n *\n * @param {Number} a Angle in Radians\n */\nexport function toDegree(a) {\n return a * radian;\n}\n\n/**\n * Tests whether or not the arguments have approximately the same value, within an absolute\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\n * than or equal to 1.0, and a relative tolerance is used for larger values)\n *\n * @param {Number} a The first number to test.\n * @param {Number} b The second number to test.\n * @param {Number} tolerance Absolute or relative tolerance (default glMatrix.EPSILON)\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\n */\nexport function equals(a, b) {\n var tolerance = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EPSILON;\n return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));\n}","import * as glMatrix from \"./common.js\";\n\n/**\n * 3 Dimensional Vector\n * @module vec3\n */\n\n/**\n * Creates a new, empty vec3\n *\n * @returns {vec3} a new 3D vector\n */\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(3);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n return out;\n}\n\n/**\n * Creates a new vec3 initialized with values from an existing vector\n *\n * @param {ReadonlyVec3} a vector to clone\n * @returns {vec3} a new 3D vector\n */\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n\n/**\n * Calculates the length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return Math.sqrt(x * x + y * y + z * z);\n}\n\n/**\n * Creates a new vec3 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} a new 3D vector\n */\nexport function fromValues(x, y, z) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n\n/**\n * Copy the values from one vec3 to another\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the source vector\n * @returns {vec3} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n\n/**\n * Set the components of a vec3 to the given values\n *\n * @param {vec3} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} out\n */\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n\n/**\n * Adds two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n return out;\n}\n\n/**\n * Multiplies two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n return out;\n}\n\n/**\n * Divides two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n return out;\n}\n\n/**\n * Math.ceil the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to ceil\n * @returns {vec3} out\n */\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n return out;\n}\n\n/**\n * Math.floor the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to floor\n * @returns {vec3} out\n */\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n return out;\n}\n\n/**\n * Returns the minimum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n return out;\n}\n\n/**\n * Returns the maximum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n return out;\n}\n\n/**\n * symmetric round the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to round\n * @returns {vec3} out\n */\nexport function round(out, a) {\n out[0] = glMatrix.round(a[0]);\n out[1] = glMatrix.round(a[1]);\n out[2] = glMatrix.round(a[2]);\n return out;\n}\n\n/**\n * Scales a vec3 by a scalar number\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec3} out\n */\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n return out;\n}\n\n/**\n * Adds two vec3's after scaling the second operand by a scalar value\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec3} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return Math.sqrt(x * x + y * y + z * z);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return x * x + y * y + z * z;\n}\n\n/**\n * Calculates the squared length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return x * x + y * y + z * z;\n}\n\n/**\n * Negates the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to negate\n * @returns {vec3} out\n */\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n return out;\n}\n\n/**\n * Returns the inverse of the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to invert\n * @returns {vec3} out\n */\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n return out;\n}\n\n/**\n * Normalize a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to normalize\n * @returns {vec3} out\n */\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var len = x * x + y * y + z * z;\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n\n/**\n * Calculates the dot product of two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\n/**\n * Computes the cross product of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function cross(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2];\n var bx = b[0],\n by = b[1],\n bz = b[2];\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n\n/**\n * Performs a linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n\n/**\n * Performs a spherical linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function slerp(out, a, b, t) {\n var angle = Math.acos(Math.min(Math.max(dot(a, b), -1), 1));\n var sinTotal = Math.sin(angle);\n var ratioA = Math.sin((1 - t) * angle) / sinTotal;\n var ratioB = Math.sin(t * angle) / sinTotal;\n out[0] = ratioA * a[0] + ratioB * b[0];\n out[1] = ratioA * a[1] + ratioB * b[1];\n out[2] = ratioA * a[2] + ratioB * b[2];\n return out;\n}\n\n/**\n * Performs a hermite interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function hermite(out, a, b, c, d, t) {\n var factorTimes2 = t * t;\n var factor1 = factorTimes2 * (2 * t - 3) + 1;\n var factor2 = factorTimes2 * (t - 2) + t;\n var factor3 = factorTimes2 * (t - 1);\n var factor4 = factorTimes2 * (3 - 2 * t);\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n\n/**\n * Performs a bezier interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function bezier(out, a, b, c, d, t) {\n var inverseFactor = 1 - t;\n var inverseFactorTimesTwo = inverseFactor * inverseFactor;\n var factorTimes2 = t * t;\n var factor1 = inverseFactorTimesTwo * inverseFactor;\n var factor2 = 3 * t * inverseFactorTimesTwo;\n var factor3 = 3 * factorTimes2 * inverseFactor;\n var factor4 = factorTimes2 * t;\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec3} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {vec3} out\n */\nexport function random(out, scale) {\n scale = scale === undefined ? 1.0 : scale;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n var z = glMatrix.RANDOM() * 2.0 - 1.0;\n var zScale = Math.sqrt(1.0 - z * z) * scale;\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n\n/**\n * Transforms the vec3 with a mat4.\n * 4th vector component is implicitly '1'\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec3} out\n */\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n\n/**\n * Transforms the vec3 with a mat3.\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\n * @returns {vec3} out\n */\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n\n/**\n * Transforms the vec3 with a quat\n * Can also be used for dual quaternions. (Multiply it with the real part)\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyQuat} q normalized quaternion to transform with\n * @returns {vec3} out\n */\nexport function transformQuat(out, a, q) {\n // Fast Vector Rotation using Quaternions by Robert Eisele\n // https://raw.org/proof/vector-rotation-using-quaternions/\n\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3];\n var vx = a[0],\n vy = a[1],\n vz = a[2];\n\n // t = q x v\n var tx = qy * vz - qz * vy;\n var ty = qz * vx - qx * vz;\n var tz = qx * vy - qy * vx;\n\n // t = 2t\n tx = tx + tx;\n ty = ty + ty;\n tz = tz + tz;\n\n // v + w t + q x t\n out[0] = vx + qw * tx + qy * tz - qz * ty;\n out[1] = vy + qw * ty + qz * tx - qx * tz;\n out[2] = vz + qw * tz + qx * ty - qy * tx;\n return out;\n}\n\n/**\n * Rotate a 3D vector around the x-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateX(out, a, b, rad) {\n var p = [],\n r = [];\n //Translate point to the origin\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2];\n\n //perform rotation\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad);\n\n //translate to correct position\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n\n/**\n * Rotate a 3D vector around the y-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateY(out, a, b, rad) {\n var p = [],\n r = [];\n //Translate point to the origin\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2];\n\n //perform rotation\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad);\n\n //translate to correct position\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n\n/**\n * Rotate a 3D vector around the z-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateZ(out, a, b, rad) {\n var p = [],\n r = [];\n //Translate point to the origin\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2];\n\n //perform rotation\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2];\n\n //translate to correct position\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n\n/**\n * Get the angle between two 3D vectors\n * @param {ReadonlyVec3} a The first operand\n * @param {ReadonlyVec3} b The second operand\n * @returns {Number} The angle in radians\n */\nexport function angle(a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n bx = b[0],\n by = b[1],\n bz = b[2],\n mag = Math.sqrt((ax * ax + ay * ay + az * az) * (bx * bx + by * by + bz * bz)),\n cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n\n/**\n * Set the components of a vec3 to zero\n *\n * @param {vec3} out the receiving vector\n * @returns {vec3} out\n */\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec3} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n return \"vec3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \")\";\n}\n\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));\n}\n\n/**\n * Alias for {@link vec3.subtract}\n * @function\n */\nexport var sub = subtract;\n\n/**\n * Alias for {@link vec3.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Alias for {@link vec3.divide}\n * @function\n */\nexport var div = divide;\n\n/**\n * Alias for {@link vec3.distance}\n * @function\n */\nexport var dist = distance;\n\n/**\n * Alias for {@link vec3.squaredDistance}\n * @function\n */\nexport var sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec3.length}\n * @function\n */\nexport var len = length;\n\n/**\n * Alias for {@link vec3.squaredLength}\n * @function\n */\nexport var sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec3s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n if (!stride) {\n stride = 3;\n }\n if (!offset) {\n offset = 0;\n }\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n return a;\n };\n}();","import { Camera } from '@quake2ts/engine';\nimport { ViewSample } from './effects.js';\nimport { vec3 } from 'gl-matrix';\nimport { Vec3 } from '@quake2ts/shared';\n\nconst toGlMatrixVec3 = (v: Vec3): vec3 => {\n return vec3.fromValues(v.x, v.y, v.z);\n};\n\nexport const updateCamera = (camera: Camera, viewSample: ViewSample) => {\n // Apply the view model effects to the camera\n camera.bobAngles = toGlMatrixVec3(viewSample.angles);\n camera.bobOffset = toGlMatrixVec3(viewSample.offset);\n};\n","import { ZERO_VEC3, angleVectors, clampViewAngles, dotVec3, hasPmFlag, PmFlag, type PmFlags, type Vec3 } from '@quake2ts/shared';\nimport type { PredictionState } from '../prediction/index.js';\n\nexport interface ViewEffectSettings {\n readonly runPitch: number;\n readonly runRoll: number;\n readonly bobUp: number;\n readonly bobPitch: number;\n readonly bobRoll: number;\n readonly maxBobHeight: number;\n readonly maxBobAngle: number;\n}\n\nconst DEFAULT_SETTINGS: ViewEffectSettings = {\n runPitch: 0.002,\n runRoll: 0.01,\n bobUp: 0.005,\n bobPitch: 0.002,\n bobRoll: 0.002,\n maxBobHeight: 6,\n maxBobAngle: 1.2,\n};\n\nexport interface ViewKick {\n readonly pitch: number;\n readonly roll: number;\n readonly durationMs: number;\n readonly origin?: Vec3; // Optional origin offset (weapon recoil)\n}\n\nexport interface ActiveKick extends ViewKick {\n remainingMs: number;\n}\n\nexport interface ViewSample {\n readonly angles: Vec3;\n readonly offset: Vec3;\n readonly bobCycle: number;\n readonly bobCycleRun: number;\n readonly bobFracSin: number;\n readonly xyspeed: number;\n}\n\nfunction clampViewOffset(offset: Vec3): Vec3 {\n return {\n x: Math.max(-14, Math.min(14, offset.x)),\n y: Math.max(-14, Math.min(14, offset.y)),\n z: Math.max(-22, Math.min(30, offset.z)),\n };\n}\n\nfunction computeBobMove(xyspeed: number, onGround: boolean, frameTimeMs: number): number {\n if (!onGround) return 0;\n\n if (xyspeed > 210) return frameTimeMs / 400;\n if (xyspeed > 100) return frameTimeMs / 800;\n return frameTimeMs / 1600;\n}\n\nfunction computeBobValues(\n previousBobTime: number,\n xyspeed: number,\n pmFlags: PmFlags,\n onGround: boolean,\n frameTimeMs: number,\n): { bobTime: number; bobCycle: number; bobCycleRun: number; bobFracSin: number } {\n if (xyspeed < 5) {\n return { bobTime: 0, bobCycle: 0, bobCycleRun: 0, bobFracSin: 0 };\n }\n\n const bobMove = computeBobMove(xyspeed, onGround, frameTimeMs);\n const bobTimeRun = previousBobTime + bobMove;\n const crouched = hasPmFlag(pmFlags, PmFlag.Ducked) && onGround;\n const bobTime = crouched ? bobTimeRun * 4 : bobTimeRun;\n\n return {\n bobTime: bobTimeRun,\n bobCycle: Math.floor(bobTime),\n bobCycleRun: Math.floor(bobTimeRun),\n bobFracSin: Math.abs(Math.sin(bobTime * Math.PI)),\n };\n}\n\nexport class ViewEffects {\n private readonly settings: ViewEffectSettings;\n private bobTime = 0;\n private bobCycle = 0;\n private bobCycleRun = 0;\n private bobFracSin = 0;\n private kick: ActiveKick | undefined;\n private lastSample: ViewSample | undefined;\n\n constructor(settings: Partial<ViewEffectSettings> = {}) {\n this.settings = { ...DEFAULT_SETTINGS, ...settings } satisfies ViewEffectSettings;\n }\n\n addKick(kick: ViewKick): void {\n if (kick.durationMs <= 0) return;\n this.kick = { ...kick, remainingMs: kick.durationMs } satisfies ActiveKick;\n }\n\n get last(): ViewSample | undefined {\n return this.lastSample;\n }\n\n sample(state: PredictionState, frameTimeMs: number): ViewSample {\n const { forward, right } = angleVectors(\n clampViewAngles({ pmFlags: state.pmFlags, cmdAngles: state.viewAngles, deltaAngles: state.deltaAngles ?? ZERO_VEC3 }).viewangles,\n );\n\n const xyspeed = Math.sqrt(state.velocity.x * state.velocity.x + state.velocity.y * state.velocity.y);\n const onGround = hasPmFlag(state.pmFlags, PmFlag.OnGround);\n\n const bobValues = computeBobValues(this.bobTime, xyspeed, state.pmFlags, onGround, frameTimeMs);\n this.bobTime = bobValues.bobTime;\n this.bobCycle = bobValues.bobCycle;\n this.bobCycleRun = bobValues.bobCycleRun;\n this.bobFracSin = bobValues.bobFracSin;\n\n // Velocity-based tilt\n let pitchTilt = dotVec3(state.velocity, forward) * this.settings.runPitch;\n\n const side = dotVec3(state.velocity, right);\n const sign = side < 0 ? -1 : 1;\n const absSide = Math.abs(side);\n\n let rollTilt = absSide * this.settings.runRoll;\n if (rollTilt > 2.0) {\n rollTilt = 2.0;\n }\n rollTilt *= sign;\n\n // Bob tilt\n let pitchDelta = this.bobFracSin * this.settings.bobPitch * xyspeed;\n let rollDelta = this.bobFracSin * this.settings.bobRoll * xyspeed;\n if (hasPmFlag(state.pmFlags, PmFlag.Ducked) && onGround) {\n pitchDelta *= 6;\n rollDelta *= 6;\n }\n\n pitchTilt += Math.min(pitchDelta, this.settings.maxBobAngle);\n rollDelta = Math.min(rollDelta, this.settings.maxBobAngle);\n if (this.bobCycle & 1) rollDelta = -rollDelta;\n rollTilt += rollDelta;\n\n // Bob height\n const bobHeight = Math.min(this.bobFracSin * xyspeed * this.settings.bobUp, this.settings.maxBobHeight);\n\n let kickPitch = 0;\n let kickRoll = 0;\n let kickX = 0;\n let kickY = 0;\n let kickZ = 0;\n\n // Apply active kick\n // Reference: rerelease/p_view.cpp CalcKickOffset\n // Matches the \"interpolation\" requested in the task\n if (this.kick && this.kick.remainingMs > 0) {\n // ratio goes from 1.0 (start) to 0.0 (end)\n const ratio = Math.max(0, Math.min(1, this.kick.remainingMs / this.kick.durationMs));\n\n kickPitch += ratio * this.kick.pitch;\n kickRoll += ratio * this.kick.roll;\n\n if (this.kick.origin) {\n kickX += ratio * this.kick.origin.x;\n kickY += ratio * this.kick.origin.y;\n kickZ += ratio * this.kick.origin.z;\n }\n\n this.kick.remainingMs = Math.max(0, this.kick.remainingMs - frameTimeMs);\n if (this.kick.remainingMs === 0) this.kick = undefined;\n }\n\n const angles: Vec3 = { x: pitchTilt + kickPitch, y: 0, z: rollTilt + kickRoll };\n const offset: Vec3 = { x: kickX, y: kickY, z: bobHeight + kickZ };\n\n const sample: ViewSample = {\n angles,\n offset: clampViewOffset(offset),\n bobCycle: this.bobCycle,\n bobCycleRun: this.bobCycleRun,\n bobFracSin: this.bobFracSin,\n xyspeed,\n } satisfies ViewSample;\n this.lastSample = sample;\n return sample;\n }\n}\n","import {\n addVec3,\n subtractVec3,\n lengthVec3,\n angleMod,\n scaleVec3,\n type Vec3,\n buildAirGroundWish,\n buildWaterWish,\n clampViewAngles,\n hasPmFlag,\n PmFlag,\n PmType,\n WaterLevel,\n type PmFlags,\n type UserCommand,\n PlayerState,\n applyPmove,\n PmoveCmd,\n PmoveTraceFn\n} from '@quake2ts/shared';\nimport type { GameFrameResult } from '@quake2ts/engine';\nimport type { PlayerClient } from '@quake2ts/game';\n\n\n// PredictionState extends PlayerState with fields needed for physics simulation\n// that might not be in the base PlayerState interface yet or are client-side specific.\nexport interface PredictionState extends PlayerState {\n deltaAngles?: Vec3;\n pmFlags: PmFlags;\n pmType: PmType;\n gravity?: number;\n waterLevel: WaterLevel;\n\n // Client-side fields for HUD/rendering, added to satisfy client package usage\n client?: PlayerClient;\n health?: number;\n armor?: number;\n ammo?: number;\n}\n\nexport interface PredictionSettings {\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly pmAccelerate: number;\n readonly pmAirAccelerate: number;\n readonly pmWaterAccelerate: number;\n readonly pmWaterFriction: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly pmWaterSpeed: number;\n readonly groundIsSlick: boolean;\n readonly errorTolerance: number;\n readonly errorSnapThreshold: number;\n}\n\nconst DEFAULTS: PredictionSettings = {\n pmFriction: 6,\n pmStopSpeed: 100,\n pmAccelerate: 10,\n pmAirAccelerate: 1,\n pmWaterAccelerate: 4,\n pmWaterFriction: 1,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n pmWaterSpeed: 400,\n groundIsSlick: false,\n errorTolerance: 0.1,\n errorSnapThreshold: 10,\n};\n\nconst DEFAULT_GRAVITY = 800;\nconst ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\nconst MSEC_MAX = 250;\nconst CMD_BACKUP = 64;\n\nexport function defaultPredictionState(): PredictionState {\n return {\n origin: ZERO_VEC3,\n velocity: ZERO_VEC3,\n viewAngles: ZERO_VEC3,\n onGround: false,\n\n // Physics fields\n pmFlags: PmFlag.OnGround,\n pmType: PmType.Normal,\n waterLevel: WaterLevel.None,\n watertype: 0,\n gravity: DEFAULT_GRAVITY,\n deltaAngles: ZERO_VEC3,\n\n // Bounds\n mins: { x: -16, y: -16, z: -24 },\n maxs: { x: 16, y: 16, z: 32 },\n\n // Visual/Game fields\n damageAlpha: 0,\n damageIndicators: [],\n blend: [0, 0, 0, 0],\n stats: [],\n kick_angles: ZERO_VEC3,\n kick_origin: ZERO_VEC3,\n gunoffset: ZERO_VEC3,\n gunangles: ZERO_VEC3,\n gunindex: 0,\n\n // New fields\n pm_time: 0,\n pm_type: PmType.Normal,\n pm_flags: PmFlag.OnGround,\n gun_frame: 0,\n rdflags: 0,\n fov: 90,\n renderfx: 0,\n\n // Optional fields\n pickupIcon: undefined,\n centerPrint: undefined,\n notify: undefined,\n client: undefined,\n health: 0,\n armor: 0,\n ammo: 0\n };\n}\n\nfunction normalizeState(state: PredictionState | undefined): PredictionState {\n if (!state) return defaultPredictionState();\n\n return {\n ...defaultPredictionState(),\n ...state,\n origin: { ...state.origin },\n velocity: { ...state.velocity },\n viewAngles: { ...state.viewAngles },\n deltaAngles: state.deltaAngles ? { ...state.deltaAngles } : ZERO_VEC3,\n blend: state.blend ? [...state.blend] : [0, 0, 0, 0],\n damageIndicators: state.damageIndicators ? [...state.damageIndicators] : [],\n stats: state.stats ? [...state.stats] : [],\n } satisfies PredictionState;\n}\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\nfunction lerpAngle(a: number, b: number, t: number): number {\n let delta = angleMod(b - a);\n if (delta > 180) {\n delta -= 360;\n }\n return angleMod(a + delta * t);\n}\n\nexport function interpolatePredictionState(\n previous: PredictionState,\n latest: PredictionState,\n alpha: number,\n): PredictionState {\n const clamped = Math.max(0, Math.min(alpha, 1));\n\n return {\n ...latest, // Default to latest for discrete fields\n origin: {\n x: lerp(previous.origin.x, latest.origin.x, clamped),\n y: lerp(previous.origin.y, latest.origin.y, clamped),\n z: lerp(previous.origin.z, latest.origin.z, clamped),\n },\n velocity: {\n x: lerp(previous.velocity.x, latest.velocity.x, clamped),\n y: lerp(previous.velocity.y, latest.velocity.y, clamped),\n z: lerp(previous.velocity.z, latest.velocity.z, clamped),\n },\n viewAngles: {\n x: lerpAngle(previous.viewAngles.x, latest.viewAngles.x, clamped),\n y: lerpAngle(previous.viewAngles.y, latest.viewAngles.y, clamped),\n z: lerpAngle(previous.viewAngles.z, latest.viewAngles.z, clamped),\n },\n damageAlpha: lerp(previous.damageAlpha, latest.damageAlpha, clamped),\n blend: [\n lerp(previous.blend[0], latest.blend[0], clamped),\n lerp(previous.blend[1], latest.blend[1], clamped),\n lerp(previous.blend[2], latest.blend[2], clamped),\n lerp(previous.blend[3], latest.blend[3], clamped),\n ],\n // Interpolate health/armor for smooth HUD? Usually step.\n health: lerp(previous.health || 0, latest.health || 0, clamped),\n armor: lerp(previous.armor || 0, latest.armor || 0, clamped),\n ammo: lerp(previous.ammo || 0, latest.ammo || 0, clamped)\n } satisfies PredictionState;\n}\n\nfunction simulateCommand(\n state: PredictionState,\n cmd: UserCommand,\n settings: PredictionSettings,\n trace: PmoveTraceFn,\n pointContents: (p: Vec3) => number\n): PredictionState {\n // Convert UserCommand to PmoveCmd\n const pmoveCmd: PmoveCmd = {\n forwardmove: cmd.forwardmove,\n sidemove: cmd.sidemove,\n upmove: cmd.upmove,\n buttons: cmd.buttons,\n angles: cmd.angles // Added missing property\n };\n\n // Delegate physics to shared applyPmove\n // Note: applyPmove returns a NEW PlayerState, it does not mutate.\n // We must ensure that PredictionState specific fields are preserved if they are not part of PlayerState\n // But since PredictionState extends PlayerState and applyPmove spreads ...state, we should get them back.\n\n const newState = applyPmove(state, pmoveCmd, trace, pointContents);\n\n // applyPmove calculates physics.\n // However, applyPmove also handles view angle clamping?\n // shared/pmove/apply.ts imports categorizePosition, checkWater etc.\n\n // One detail: applyPmove uses the cmd to update viewAngles?\n // Looking at applyPmove in shared: it returns `...newState` which comes from `...state`\n // But `applyPmove` doesn't seem to modify viewAngles directly unless it's implicit?\n // Wait, applyPmove handles origin and velocity.\n // View angle changes (like from mouse input) are usually pre-applied to the command angles.\n // But physics might affect view angles? (Not usually, except maybe knockback?)\n\n // The original simulateCommand implementation clamped view angles.\n const { viewangles } = clampViewAngles({\n pmFlags: state.pmFlags,\n cmdAngles: cmd.angles,\n deltaAngles: state.deltaAngles ?? ZERO_VEC3,\n });\n\n return {\n ...newState,\n viewAngles: viewangles\n } as PredictionState;\n}\n\nexport interface PredictionPhysics {\n trace: PmoveTraceFn;\n pointContents: (p: Vec3) => number;\n}\n\nexport class ClientPrediction {\n private readonly settings: PredictionSettings;\n private readonly physics: PredictionPhysics;\n private enabled = true;\n private baseFrame: GameFrameResult<PredictionState> = {\n frame: 0,\n timeMs: 0,\n state: defaultPredictionState(),\n } satisfies GameFrameResult<PredictionState>;\n private commands: UserCommand[] = [];\n private predicted: PredictionState = defaultPredictionState();\n private predictionError: Vec3 = ZERO_VEC3;\n\n constructor(physics: PredictionPhysics, settings: Partial<PredictionSettings> = {}) {\n this.settings = { ...DEFAULTS, ...settings } satisfies PredictionSettings;\n this.physics = physics;\n this.predicted = this.baseFrame.state ?? defaultPredictionState();\n }\n\n setPredictionEnabled(enabled: boolean): void {\n this.enabled = enabled;\n }\n\n setAuthoritative(frame: GameFrameResult<PredictionState>): PredictionState {\n const normalized = normalizeState(frame.state);\n\n if (frame.frame <= this.baseFrame.frame) {\n return this.predicted; // Ignore old or duplicate frames\n }\n\n if (this.enabled) {\n // Calculate prediction error before updating baseFrame\n // We need to know what we *thought* the state was at this frame.\n // Since we don't store history, we'll re-simulate from the OLD base frame up to this new frame's sequence.\n\n // 1. Find the command that matches the new frame's sequence (if we have it)\n // The new frame corresponds to state AFTER executing command with sequence = frame.frame\n\n let predictedAtFrame: PredictionState | undefined;\n\n // We can only check error if we have the commands to reproduce the state up to this point\n const relevantCommands = this.commands.filter(c => c.sequence <= frame.frame && c.sequence > this.baseFrame.frame);\n\n if (relevantCommands.length > 0 || this.baseFrame.frame === frame.frame) {\n let tempState = normalizeState(this.baseFrame.state);\n for (const cmd of relevantCommands) {\n tempState = simulateCommand(tempState, cmd, this.settings, this.physics.trace, this.physics.pointContents);\n }\n predictedAtFrame = tempState;\n }\n\n if (predictedAtFrame) {\n const error = subtractVec3(predictedAtFrame.origin, normalized.origin);\n const errorLen = lengthVec3(error);\n\n // If error is large (> errorSnapThreshold), snap immediately (reset error)\n // If error is small, add it to existing error to smooth out\n if (errorLen > this.settings.errorSnapThreshold) {\n this.predictionError = ZERO_VEC3;\n } else if (errorLen > this.settings.errorTolerance) {\n // Accumulate error? Or just set it?\n // Usually we set it, and then decay it in simulateCommand or frame update.\n // But wait, \"prediction error\" is usually added to the view position to keep the camera\n // where the client PREDICTED it was, then slowly slide it to the server position.\n // So if we predicted X, and server says X-5, we are at X-5 but we want to render at X-5+5 = X.\n // So error = predicted - server.\n this.predictionError = error;\n } else {\n this.predictionError = ZERO_VEC3;\n }\n } else {\n // Can't verify prediction, reset error\n this.predictionError = ZERO_VEC3;\n }\n } else {\n this.predictionError = ZERO_VEC3;\n }\n\n this.baseFrame = { ...frame, state: normalized };\n\n // Discard commands that have been acknowledged/processed by the server\n this.commands = this.commands.filter((cmd) => cmd.sequence > frame.frame);\n\n return this.recompute();\n }\n\n getPredictionError(): Vec3 {\n return this.predictionError;\n }\n\n // Decay error over time - usually called once per client frame\n decayError(frametime: number) {\n const len = lengthVec3(this.predictionError);\n if (len > 0) {\n const decay = len * 10 * frametime; // Decay speed\n const scale = Math.max(0, len - decay) / len;\n this.predictionError = scaleVec3(this.predictionError, scale);\n }\n }\n\n enqueueCommand(cmd: UserCommand): PredictionState {\n this.commands.push(cmd);\n if (this.commands.length > CMD_BACKUP) {\n this.commands.shift();\n }\n return this.recompute();\n }\n\n getCommand(sequence: number): UserCommand | undefined {\n return this.commands.find((c) => c.sequence === sequence);\n }\n\n getPredictedState(): PredictionState {\n return this.predicted;\n }\n\n private recompute(): PredictionState {\n let state = normalizeState(this.baseFrame.state);\n\n if (this.enabled) {\n for (const cmd of this.commands) {\n state = simulateCommand(state, cmd, this.settings, this.physics.trace, this.physics.pointContents);\n }\n }\n\n this.predicted = state;\n return state;\n }\n}\n"],"mappings":"6cAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,sBAAAE,GAAA,gBAAAC,GAAA,gBAAAC,GAAA,2BAAAC,EAAA,+BAAAC,GAAA,iBAAAC,8FCOaC,GAAkB,CAAE,EAAG,EAAG,EAAG,EAAG,EAAG,CAAA,EAKhD,IAAMC,GAAa,KAAK,GAAK,IActB,SAASC,EAAQC,EAASC,EAAe,CAC9C,MAAO,CAAE,EAAGD,EAAE,EAAIC,EAAE,EAAG,EAAGD,EAAE,EAAIC,EAAE,EAAG,EAAGD,EAAE,EAAIC,EAAE,CAAA,CAClD,CAEO,SAASC,GAAaF,EAASC,EAAe,CACnD,MAAO,CA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+D,GAAYxD,EAAsB,CACjBoD,EAAoB,EAC5B,mBAAmB,CACrC,CAEA,SAASK,GAAiBzD,EAAsB,CACtBoD,EAAoB,EAC5B,iBAAiB,CACnC,CAEA,SAASM,GAAaC,EAAcC,EAAyB,CAC3D,GAAI,CAACnE,EAAK,OACaoE,GAAqB,EAC7B,YAAYF,EAAMlE,EAAI,cAAc,CAAC,CACtD,CAEA,SAASqE,GAAsBhC,EAAkB,CAC7C,MAAO,CAAE,EAAG,EAAG,EAAG,EAAG,EAAG,CAAE,CAC9B,CAEA,SAASiC,GAAaC,EAAuB,CACzC,OAAO,IACX,CASO,SAASC,GAAYC,EAAmC,CAC3D,OAAAzE,EAAMyE,EAEC,CAEH,KAAAtE,GACA,SAAAE,GAGA,QAAAC,GACA,UAAAS,GAGA,YAAaE,GAGb,2BAAAC,GACA,2BAAAE,GACA,wBAAAO,GACA,qBAAAM,GAGA,mBAAAM,GAGA,MAAAC,GAGA,kBAAAa,GACA,iBAAAG,GACA,cAAAI,GACA,aAAAK,GAGA,YAAAF,GACA,iBAAAC,GAGA,sBAAAK,GAGA,aAAAC,EACJ,CACJ","names":["src_exports","__export","ClientPrediction","GetCGameAPI","ViewEffects","defaultPredictionState","interpolatePredictionState","updateCamera","ZERO_VEC3","DEG_TO_RAD","addVec3","a","b","subtractVec3","scaleVec3","a","scalar","dotVec3","a","b","lengthSquaredVec3","a","dotVec3","lengthVec3","normalizeVec3","a","len","lengthVec3","scaleVec3","PITCH","YAW","ROLL","DEG2RAD_FACTOR","RAD2DEG_FACTOR","axisComponent","vec","axis","PITCH","YAW","ROLL","degToRad","degrees","DEG2RAD_FACTOR","angleMod","angle","value","angleVectors","angles","yaw","degToRad","axisComponent","YAW","pitch","PITCH","roll","ROLL","sy","cy","sp","cp","sr","cr","forward","right","up","ANORMS","CONTENTS_SOLID","CONTENTS_WINDOW","CONTENTS_LAVA","CONTENTS_SLIME","CONTENTS_WATER","CONTENTS_PROJECTILECLIP","CONTENTS_PLAYERCLIP","CONTENTS_MONSTERCLIP","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","CONTENTS_ORIGIN","CONTENTS_MONSTER","CONTENTS_DEADMONSTER","CONTENTS_DETAIL","CONTENTS_TRANSLUCENT","CONTENTS_LADDER","CONTENTS_PLAYER","CONTENTS_PROJECTILE","SURF_ALPHATEST","SURF_N64_UV","SURF_N64_SCROLL_X","SURF_N64_SCROLL_Y","SURF_N64_SCROLL_FLIP","MASK_SOLID","CONTENTS_SOLID","CONTENTS_WINDOW","MASK_PLAYERSOLID","CONTENTS_PLAYERCLIP","CONTENTS_MONSTER","CONTENTS_PLAYER","MASK_DEADSOLID","MASK_MONSTERSOLID","CONTENTS_MONSTERCLIP","MASK_WATER","CONTENTS_WATER","CONTENTS_LAVA","CONTENTS_SLIME","MASK_OPAQUE","MASK_SHOT","CONTENTS_DEADMONSTER","MASK_CURRENT","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","MASK_BLOCK_SIGHT","MASK_NAV_SOLID","MASK_LADDER_NAV_SOLID","MASK_WALK_NAV_SOLID","MASK_PROJECTILE","CONTENTS_PROJECTILECLIP","MAX_CHECKCOUNT","MAX_CLIENTS","MAX_LIGHTSTYLES","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_ITEMS","MAX_GENERAL","MAX_CLIENTS","MAX_SHADOW_LIGHTS","MAX_WHEEL_ITEMS","ConfigStringIndex","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_LIGHTSTYLES","MAX_SHADOW_LIGHTS","MAX_ITEMS","MAX_CLIENTS","MAX_GENERAL","MAX_WHEEL_ITEMS","MAX_CONFIGSTRINGS","CS_SOUNDS","ConfigStringIndex","CS_IMAGES","CS_LIGHTS","CS_ITEMS","CS_PLAYERS","CS_GENERAL","replay_exports","__export","addReplayFrame","createReplaySession","deserializeReplay","serializeReplay","session","json","map","seed","cmd","serverFrame","startTime","WaterLevel","PmFlag","hasPmFlag","flags","flag","PmType","applyPmoveFriction","params","velocity","frametime","onGround","groundIsSlick","onLadder","waterlevel","pmFriction","pmStopSpeed","pmWaterFriction","speed","lengthVec3","drop","control","newspeed","scale","scaleVec3","applyPmoveAccelerate","wishdir","wishspeed","accel","currentSpeed","dotVec3","addSpeed","accelSpeed","buildAirGroundWish","params","forward","right","cmd","maxSpeed","wishvel","wishspeed","lengthVec3","scale","scaleVec3","normalizeVec3","buildWaterWish","addVec3","addAngles","cmdAngles","deltaAngles","clampPitch","pitch","clampViewAngles","params","pmFlags","viewangles","vectors","angleVectors","readUint16LE","stats","startIndex","byteOffset","elementIndex","isOdd","index","val0","val1","low","getCompressedInteger","stats","startIndex","id","bitsPerValue","bitOffset","byteOffset","bitShift","mask","readUint16LE","PowerupId","PlayerStat","AMMO_MAX","NUM_BITS_FOR_AMMO","NUM_AMMO_STATS","POWERUP_MAX","NUM_BITS_FOR_POWERUP","NUM_POWERUP_STATS","POWERUP_STAT_MAP","G_GetAmmoStat","stats","ammoId","AMMO_MAX","getCompressedInteger","NUM_BITS_FOR_AMMO","G_GetPowerupStat","stats","powerupId","index","POWERUP_STAT_MAP","POWERUP_MAX","getCompressedInteger","NUM_BITS_FOR_POWERUP","U_FRAME16","U_RENDERFX16","U_EFFECTS16","U_MODEL2","U_MODEL3","U_MODEL4","U_MOREBITS3","U_OLDORIGIN","U_SKIN16","U_SOUND","U_SOLID","U_SCALE","U_INSTANCE_BITS","U_LOOP_VOLUME","FRAMETIME","WaterLevel","categorizePosition","state","trace","point","traceResult","checkWater","pointContents","mins","maxs","feetContents","MASK_WATER","waterLevel","watertype","waist","waistContents","head","headContents","applyPmove","cmd","newState","origin","velocity","onGround","viewAngles","adjustedAngles","forward","right","angleVectors","frictionedVelocity","applyPmoveFriction","wish","buildWaterWish","buildAirGroundWish","finalVelocity","applyPmoveAccelerate","BinaryWriter","sizeOrBuffer","bytes","newSize","newBuffer","value","data","len","i","pos","dir","maxDot","bestIndex","ANORMS","norm","dot","_NetChan","BinaryWriter","now","qport","address","unreliableData","sendReliableLength","isFragment","fragmentStart","headerSize","reliableHeaderSize","unreliableSize","buffer","view","result","sequence","ack","offset","lengthField","reliableBytes","chunk","packet","seqNumberClean","ackNumber","ackReliable","receivedAckBit","currentReliableBit","hasReliableData","reliableSeqBit","payloadOffset","reliableData","reliableLen","expectedBit","fragStart","fragTotal","data","totalLen","value","len","currentTime","timeoutMs","AmmoType","AMMO_TYPE_COUNT","WEAPON_WHEEL_ORDER","WEAPON_AMMO_MAP","crosshairPic","crosshairColor","crosshairEnabled","CROSSHAIR_NAMES","crosshairPics","Init_Crosshair","cgi","i","name","crosshairPic","Draw_Crosshair","cgi","width","height","crosshairEnabled","crosshairPic","size","x","y","crosshairColor","iconPics","ICON_NAMES","Init_Icons","cgi","name","pic","damagePics","DAMAGE_INDICATOR_NAMES","Init_Damage","cgi","name","pic","WHITE","Draw_Damage","ps","width","height","cx","cy","forward","right","angleVectors","radius","indicator","localRight","dotVec3","localForward","angle","picName","xOff","yOff","size","x","y","alpha","CENTER_PRINT_DURATION","NOTIFY_DURATION","MAX_NOTIFY_MESSAGES","MessageSystem","text","now","is_chat","cgi","layout","y","msg","SUBTITLE_DURATION","SubtitleSystem","text","now","cgi","Draw_Blends","cgi","ps","width","height","r","g","b","Draw_Pickup","cgi","ps","width","height","icon","iconPics","size","x","y","Draw_Number","cgi","x","y","value","pics","width","color","s","i","digit","pic","colorblindMode","Draw_StatusBar","cgi","ps","hudNumberPics","numberWidth","timeMs","layout","health","PlayerStat","armor","ammo","armorIconIdx","healthColor","colorblindMode","Draw_Number","iconName","ConfigStringIndex","icon","selectedIconIdx","getHudLayout","width","height","scaleX","scaleY","scale","cgi","hudNumberPics","numberWidth","messageSystem","MessageSystem","subtitleSystem","SubtitleSystem","CG_InitScreen","imports","CG_TouchPics","i","pic","Init_Crosshair","Init_Icons","Init_Damage","CG_DrawHUD","isplit","data","hud_vrect","hud_safe","scale","playernum","ps","timeMs","layout","getHudLayout","Draw_Blends","Draw_StatusBar","Draw_Pickup","Draw_Damage","lines","y","line","Draw_Crosshair","CG_GetMessageSystem","CG_GetSubtitleSystem","CG_ParseConfigString","cgi","i","s","ConfigStringIndex","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","EPSILON","ARRAY_TYPE","RANDOM","round","a","degree","radian","vec3_exports","__export","add","angle","bezier","ceil","clone","copy","create","cross","dist","distance","div","divide","dot","equals","exactEquals","floor","forEach","fromValues","hermite","inverse","len","length","lerp","max","min","mul","multiply","negate","normalize","random","rotateX","rotateY","rotateZ","round","scale","scaleAndAdd","set","slerp","sqrDist","sqrLen","squaredDistance","squaredLength","str","sub","subtract","transformMat3","transformMat4","transformQuat","zero","create","out","ARRAY_TYPE","clone","a","length","x","y","z","fromValues","copy","set","add","b","subtract","multiply","divide","ceil","floor","min","max","round","scale","scaleAndAdd","distance","squaredDistance","squaredLength","negate","inverse","normalize","len","dot","cross","ax","ay","az","bx","by","bz","lerp","t","slerp","angle","sinTotal","ratioA","ratioB","hermite","c","d","factorTimes2","factor1","factor2","factor3","factor4","bezier","inverseFactor","inverseFactorTimesTwo","random","RANDOM","zScale","transformMat4","m","w","transformMat3","transformQuat","q","qx","qy","qz","qw","vx","vy","vz","tx","ty","tz","rotateX","rad","p","r","rotateY","rotateZ","mag","cosine","zero","str","exactEquals","equals","a0","a1","a2","b0","b1","b2","EPSILON","sub","mul","div","dist","sqrDist","sqrLen","forEach","vec","stride","offset","count","fn","arg","i","toGlMatrixVec3","v","vec3_exports","updateCamera","camera","viewSample","DEFAULT_SETTINGS","clampViewOffset","offset","computeBobMove","xyspeed","onGround","frameTimeMs","computeBobValues","previousBobTime","pmFlags","bobMove","bobTimeRun","bobTime","hasPmFlag","PmFlag","ViewEffects","settings","kick","state","forward","right","angleVectors","clampViewAngles","ZERO_VEC3","bobValues","pitchTilt","dotVec3","side","sign","rollTilt","pitchDelta","rollDelta","bobHeight","kickPitch","kickRoll","kickX","kickY","kickZ","ratio","angles","sample","DEFAULTS","DEFAULT_GRAVITY","ZERO_VEC3","CMD_BACKUP","defaultPredictionState","ZERO_VEC3","PmFlag","PmType","WaterLevel","DEFAULT_GRAVITY","normalizeState","state","lerp","a","b","t","lerpAngle","delta","angleMod","interpolatePredictionState","previous","latest","alpha","clamped","simulateCommand","cmd","settings","trace","pointContents","pmoveCmd","newState","applyPmove","viewangles","clampViewAngles","ClientPrediction","physics","DEFAULTS","enabled","frame","normalized","predictedAtFrame","relevantCommands","c","tempState","error","subtractVec3","errorLen","lengthVec3","frametime","len","decay","scale","scaleVec3","sequence","cgi","cg_predict","cg_showmiss","Init","CG_InitScreen","Shutdown","DrawHUD","isplit","data","hud_vrect","hud_safe","scale","playernum","ps","CG_DrawHUD","TouchPics","CG_TouchPics","GetLayoutFlags","GetActiveWeaponWheelWeapon","PlayerStat","GetOwnedWeaponWheelWeapons","owned","bits1","bits2","fullBits","i","WEAPON_WHEEL_ORDER","GetWeaponWheelAmmoCount","weapon","weaponId","ammoType","WEAPON_AMMO_MAP","G_GetAmmoStat","GetPowerupWheelCount","count","powerups","PowerupId","id","G_GetPowerupStat","GetHitMarkerDamage","Pmove","pmove","pm","traceAdapter","start","end","mins","maxs","zero","pointContentsAdapter","point","newState","applyPmove","ParseConfigString","s","CG_ParseConfigString","ParseCenterPrint","str","instant","CG_GetMessageSystem","NotifyMessage","msg","is_chat","ClearNotify","ClearCenterprint","ShowSubtitle","text","soundName","CG_GetSubtitleSystem","GetMonsterFlashOffset","GetExtension","name","GetCGameAPI","imports"]}
|