quake2ts 0.0.80 → 0.0.82

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.
Files changed (63) hide show
  1. package/package.json +1 -1
  2. package/packages/client/dist/browser/index.global.js +1 -1
  3. package/packages/client/dist/browser/index.global.js.map +1 -1
  4. package/packages/client/dist/cjs/index.cjs +9 -1
  5. package/packages/client/dist/cjs/index.cjs.map +1 -1
  6. package/packages/client/dist/esm/index.js +9 -1
  7. package/packages/client/dist/esm/index.js.map +1 -1
  8. package/packages/client/dist/tsconfig.tsbuildinfo +1 -1
  9. package/packages/client/dist/types/hud.d.ts.map +1 -1
  10. package/packages/client/dist/types/prediction.d.ts +2 -0
  11. package/packages/client/dist/types/prediction.d.ts.map +1 -1
  12. package/packages/engine/dist/browser/index.global.js +4 -2
  13. package/packages/engine/dist/browser/index.global.js.map +1 -1
  14. package/packages/engine/dist/cjs/index.cjs +6 -2
  15. package/packages/engine/dist/cjs/index.cjs.map +1 -1
  16. package/packages/engine/dist/esm/index.js +6 -2
  17. package/packages/engine/dist/esm/index.js.map +1 -1
  18. package/packages/engine/dist/tsconfig.tsbuildinfo +1 -1
  19. package/packages/engine/dist/types/render/light.d.ts +10 -0
  20. package/packages/engine/dist/types/render/light.d.ts.map +1 -0
  21. package/packages/engine/dist/types/render/md2Pipeline.d.ts +3 -1
  22. package/packages/engine/dist/types/render/md2Pipeline.d.ts.map +1 -1
  23. package/packages/engine/dist/types/render/renderer.d.ts +1 -0
  24. package/packages/engine/dist/types/render/renderer.d.ts.map +1 -1
  25. package/packages/engine/dist/types/render/scene.d.ts +1 -0
  26. package/packages/engine/dist/types/render/scene.d.ts.map +1 -1
  27. package/packages/game/dist/browser/index.global.js +1 -1
  28. package/packages/game/dist/browser/index.global.js.map +1 -1
  29. package/packages/game/dist/cjs/index.cjs +724 -440
  30. package/packages/game/dist/cjs/index.cjs.map +1 -1
  31. package/packages/game/dist/esm/index.js +719 -440
  32. package/packages/game/dist/esm/index.js.map +1 -1
  33. package/packages/game/dist/tsconfig.tsbuildinfo +1 -1
  34. package/packages/game/dist/types/ai/monster.d.ts +3 -2
  35. package/packages/game/dist/types/ai/monster.d.ts.map +1 -1
  36. package/packages/game/dist/types/ai/movement.d.ts +2 -1
  37. package/packages/game/dist/types/ai/movement.d.ts.map +1 -1
  38. package/packages/game/dist/types/ai/targeting.d.ts +4 -3
  39. package/packages/game/dist/types/ai/targeting.d.ts.map +1 -1
  40. package/packages/game/dist/types/entities/entity.d.ts +3 -2
  41. package/packages/game/dist/types/entities/entity.d.ts.map +1 -1
  42. package/packages/game/dist/types/entities/funcs.d.ts.map +1 -1
  43. package/packages/game/dist/types/entities/items/ammo.d.ts +5 -0
  44. package/packages/game/dist/types/entities/items/ammo.d.ts.map +1 -0
  45. package/packages/game/dist/types/entities/items/index.d.ts +5 -0
  46. package/packages/game/dist/types/entities/items/index.d.ts.map +1 -1
  47. package/packages/game/dist/types/entities/items.d.ts.map +1 -1
  48. package/packages/game/dist/types/entities/monsters/attack.d.ts +8 -0
  49. package/packages/game/dist/types/entities/monsters/attack.d.ts.map +1 -0
  50. package/packages/game/dist/types/entities/monsters/gunner.d.ts +3 -0
  51. package/packages/game/dist/types/entities/monsters/gunner.d.ts.map +1 -0
  52. package/packages/game/dist/types/entities/monsters/soldier.d.ts.map +1 -1
  53. package/packages/game/dist/types/entities/projectiles.d.ts +6 -5
  54. package/packages/game/dist/types/entities/projectiles.d.ts.map +1 -1
  55. package/packages/game/dist/types/entities/spawn.d.ts.map +1 -1
  56. package/packages/game/dist/types/entities/system.d.ts +3 -1
  57. package/packages/game/dist/types/entities/system.d.ts.map +1 -1
  58. package/packages/game/dist/types/imports.d.ts +4 -2
  59. package/packages/game/dist/types/imports.d.ts.map +1 -1
  60. package/packages/shared/dist/tsconfig.tsbuildinfo +1 -1
  61. package/packages/shared/dist/types/protocol/player-state.d.ts +2 -0
  62. package/packages/shared/dist/types/protocol/player-state.d.ts.map +1 -1
  63. package/packages/tools/dist/tsconfig.tsbuildinfo +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.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/mat4.js","../../../../node_modules/.pnpm/gl-matrix@3.4.4/node_modules/gl-matrix/esm/vec3.js","../../../engine/src/loop.ts","../../../engine/src/host.ts","../../../shared/src/math/vec3.ts","../../../shared/src/math/angles.ts","../../../shared/src/math/color.ts","../../../shared/src/math/random.ts","../../../shared/src/math/mat4.ts","../../../shared/src/bsp/contents.ts","../../../shared/src/bsp/collision.ts","../../../shared/src/protocol/cvar.ts","../../../shared/src/protocol/configstrings.ts","../../../shared/src/protocol/contracts.ts","../../../shared/src/pmove/constants.ts","../../../shared/src/pmove/pmove.ts","../../../shared/src/pmove/slide.ts","../../../shared/src/pmove/stuck.ts","../../../shared/src/pmove/currents.ts","../../../shared/src/pmove/fly.ts","../../../shared/src/pmove/water.ts","../../../shared/src/pmove/jump.ts","../../../shared/src/pmove/dimensions.ts","../../../shared/src/pmove/duck.ts","../../../shared/src/pmove/categorize.ts","../../../shared/src/pmove/move.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/pmove/apply.ts","../../../shared/src/io/binaryStream.ts","../../../engine/src/configstrings.ts","../../../engine/src/runtime.ts","../../../engine/src/cvars.ts","../../../engine/src/assets/pak.ts","../../../engine/src/assets/vfs.ts","../../../engine/src/assets/pakValidation.ts","../../../engine/src/assets/ingestion.ts","../../../engine/src/assets/cache.ts","../../../engine/src/assets/browserIngestion.ts","../../../engine/src/assets/bsp.ts","../../../engine/src/assets/md2.ts","../../../engine/src/assets/md3.ts","../../../engine/src/assets/sprite.ts","../../../engine/src/assets/animation.ts","../../../engine/src/assets/wal.ts","../../../engine/src/assets/pcx.ts","../../../engine/src/assets/texture.ts","../../../engine/src/assets/wav.ts","../../../engine/src/assets/ogg.ts","../../../engine/src/assets/audio.ts","../../../engine/src/assets/pakIndexStore.ts","../../../engine/src/assets/manager.ts","../../../engine/src/audio/constants.ts","../../../engine/src/audio/context.ts","../../../engine/src/audio/registry.ts","../../../engine/src/audio/precache.ts","../../../engine/src/audio/channels.ts","../../../engine/src/audio/spatialization.ts","../../../engine/src/audio/system.ts","../../../engine/src/audio/music.ts","../../../engine/src/audio/api.ts","../../../engine/src/render/context.ts","../../../engine/src/render/shaderProgram.ts","../../../engine/src/render/resources.ts","../../../engine/src/render/bsp.ts","../../../engine/src/render/culling.ts","../../../engine/src/render/bspTraversal.ts","../../../engine/src/render/bspPipeline.ts","../../../engine/src/render/skybox.ts","../../../engine/src/render/md2Pipeline.ts","../../../engine/src/render/camera.ts","../../../engine/src/render/md3Pipeline.ts","../../../engine/src/render/particleSystem.ts","../../../engine/src/demo/demoReader.ts","../../../engine/src/demo/parser.ts","../../../engine/src/demo/playback.ts","../../../engine/src/index.ts","../../../shared/src/math/vec3.ts","../../../shared/src/math/angles.ts","../../../shared/src/math/color.ts","../../../shared/src/math/random.ts","../../../shared/src/math/mat4.ts","../../../shared/src/bsp/contents.ts","../../../shared/src/bsp/collision.ts","../../../shared/src/protocol/cvar.ts","../../../shared/src/protocol/configstrings.ts","../../../shared/src/protocol/contracts.ts","../../../shared/src/pmove/constants.ts","../../../shared/src/pmove/pmove.ts","../../../shared/src/pmove/slide.ts","../../../shared/src/pmove/stuck.ts","../../../shared/src/pmove/currents.ts","../../../shared/src/pmove/fly.ts","../../../shared/src/pmove/water.ts","../../../shared/src/pmove/jump.ts","../../../shared/src/pmove/dimensions.ts","../../../shared/src/pmove/duck.ts","../../../shared/src/pmove/categorize.ts","../../../shared/src/pmove/move.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/pmove/apply.ts","../../../shared/src/io/binaryStream.ts","../../src/prediction.ts","../../src/view-effects.ts","../../src/hud/numbers.ts","../../src/hud/layout.ts","../../src/hud/crosshair.ts","../../src/hud/icons.ts","../../src/hud/damage.ts","../../src/hud/diagnostics.ts","../../src/hud.ts","../../src/input/bindings.ts","../../src/input/controller.ts","../../src/input/command-buffer.ts"],"sourcesContent":["import {\n ClientRenderer,\n EngineImports,\n GameFrameResult,\n GameRenderSample,\n Camera,\n Renderer,\n DemoPlaybackController,\n} from '@quake2ts/engine';\nimport { UserCommand, Vec3, PlayerState, hasPmFlag, PmFlag } from '@quake2ts/shared';\nimport { vec3, mat4 } from 'gl-matrix';\nimport { ClientPrediction, interpolatePredictionState } from './prediction.js';\nimport type { PredictionState } from './prediction.js';\nimport { ViewEffects, type ViewSample } from './view-effects.js';\nimport { Draw_Hud, Init_Hud } from './hud.js';\nimport { FrameRenderStats } from '@quake2ts/engine';\nexport { createDefaultBindings, InputBindings, normalizeCommand, normalizeInputCode } from './input/bindings.js';\nexport {\n GamepadLike,\n GamepadLikeButton,\n InputAction,\n InputController,\n TouchInputState,\n type InputControllerOptions,\n} from './input/controller.js';\nexport {\n InputCommandBuffer,\n type QueuedFrameCommands,\n} from './input/command-buffer.js';\nexport {\n ClientPrediction,\n defaultPredictionState,\n interpolatePredictionState,\n type PredictionSettings,\n type PredictionState,\n} from './prediction.js';\nexport { ViewEffects, type ViewEffectSettings, type ViewKick, type ViewSample } from './view-effects.js';\n\nexport interface ClientImports {\n readonly engine: EngineImports & { renderer: Renderer };\n}\n\nexport interface ClientExports extends ClientRenderer<PredictionState> {\n predict(command: UserCommand): PredictionState;\n readonly prediction: ClientPrediction;\n readonly lastRendered?: PredictionState;\n readonly view: ViewEffects;\n readonly lastView?: ViewSample;\n camera?: Camera;\n demoPlayback: DemoPlaybackController;\n}\n\nexport function createClient(imports: ClientImports): ClientExports {\n const prediction = new ClientPrediction(imports.engine.trace);\n const view = new ViewEffects();\n const demoPlayback = new DemoPlaybackController();\n let latestFrame: GameFrameResult<PredictionState> | undefined;\n let lastRendered: PredictionState | undefined;\n let lastView: ViewSample | undefined;\n let camera: Camera | undefined;\n\n return {\n init(initial) {\n latestFrame = initial;\n if (initial?.state) {\n prediction.setAuthoritative(initial);\n }\n void imports.engine.trace({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });\n },\n predict(command: UserCommand): PredictionState {\n return prediction.enqueueCommand(command);\n },\n render(sample: GameRenderSample<PredictionState>): UserCommand {\n if (sample.latest?.state) {\n prediction.setAuthoritative(sample.latest);\n latestFrame = sample.latest;\n }\n\n if (sample.previous?.state && sample.latest?.state) {\n lastRendered = interpolatePredictionState(sample.previous.state, sample.latest.state, sample.alpha);\n } else {\n lastRendered = sample.latest?.state ?? sample.previous?.state ?? prediction.getPredictedState();\n }\n\n const frameTimeMs = sample.latest && sample.previous ? Math.max(0, sample.latest.timeMs - sample.previous.timeMs) : 0;\n lastView = view.sample(lastRendered, frameTimeMs);\n\n if (lastRendered) {\n const { origin, viewangles } = lastRendered;\n camera = new Camera();\n camera.position = vec3.fromValues(origin.x, origin.y, origin.z);\n camera.angles = vec3.fromValues(viewangles.x, viewangles.y, viewangles.z);\n camera.fov = 90;\n camera.aspect = 4 / 3;\n }\n\n const command = {} as UserCommand;\n\n if (imports.engine.renderer && lastRendered && lastRendered.client) {\n const stats: FrameRenderStats = {\n batches: 0,\n facesDrawn: 0,\n drawCalls: 0,\n skyDrawn: false,\n viewModelDrawn: false,\n fps: 0,\n vertexCount: 0,\n };\n\n const playerState: PlayerState = {\n origin: lastRendered.origin,\n velocity: lastRendered.velocity,\n viewAngles: lastRendered.viewangles,\n onGround: hasPmFlag(lastRendered.pmFlags, PmFlag.OnGround),\n waterLevel: lastRendered.waterlevel,\n mins: { x: -16, y: -16, z: -24 },\n maxs: { x: 16, y: 16, z: 32 },\n damageAlpha: 0,\n damageIndicators: [],\n };\n Draw_Hud(imports.engine.renderer, playerState, lastRendered.client, lastRendered.health, lastRendered.armor, lastRendered.ammo, stats);\n }\n\n void imports;\n void sample;\n\n return command;\n },\n shutdown() {\n latestFrame = undefined;\n lastRendered = undefined;\n },\n get prediction(): ClientPrediction {\n return prediction;\n },\n get lastRendered(): PredictionState | undefined {\n return lastRendered;\n },\n get view(): ViewEffects {\n return view;\n },\n get lastView(): ViewSample | undefined {\n return lastView;\n },\n get camera(): Camera | undefined {\n return camera;\n },\n demoPlayback\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 * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns {mat4} a new 4x4 matrix\n */\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(16);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\nexport function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\nexport function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a12 = a[6],\n a13 = a[7];\n var a23 = a[11];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n return out;\n}\n\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4 | null} out, or null if source matrix is not invertible\n */\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32;\n\n // Calculate the determinant\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n if (!det) {\n return null;\n }\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n return out;\n}\n\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32;\n out[0] = a11 * b11 - a12 * b10 + a13 * b09;\n out[1] = a02 * b10 - a01 * b11 - a03 * b09;\n out[2] = a31 * b05 - a32 * b04 + a33 * b03;\n out[3] = a22 * b04 - a21 * b05 - a23 * b03;\n out[4] = a12 * b08 - a10 * b11 - a13 * b07;\n out[5] = a00 * b11 - a02 * b08 + a03 * b07;\n out[6] = a32 * b02 - a30 * b05 - a33 * b01;\n out[7] = a20 * b05 - a22 * b02 + a23 * b01;\n out[8] = a10 * b10 - a11 * b08 + a13 * b06;\n out[9] = a01 * b08 - a00 * b10 - a03 * b06;\n out[10] = a30 * b04 - a31 * b02 + a33 * b00;\n out[11] = a21 * b02 - a20 * b04 - a23 * b00;\n out[12] = a11 * b07 - a10 * b09 - a12 * b06;\n out[13] = a00 * b09 - a01 * b07 + a02 * b06;\n out[14] = a31 * b01 - a30 * b03 - a32 * b00;\n out[15] = a20 * b03 - a21 * b01 + a22 * b00;\n return out;\n}\n\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b0 = a00 * a11 - a01 * a10;\n var b1 = a00 * a12 - a02 * a10;\n var b2 = a01 * a12 - a02 * a11;\n var b3 = a20 * a31 - a21 * a30;\n var b4 = a20 * a32 - a22 * a30;\n var b5 = a21 * a32 - a22 * a31;\n var b6 = a00 * b5 - a01 * b4 + a02 * b3;\n var b7 = a10 * b5 - a11 * b4 + a12 * b3;\n var b8 = a20 * b2 - a21 * b1 + a22 * b0;\n var b9 = a30 * b2 - a31 * b1 + a32 * b0;\n\n // Calculate the determinant\n return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9;\n}\n\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n\n // Cache only the current line of the second matrix\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\nexport function translate(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n return out;\n}\n\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function rotate(out, a, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.sqrt(x * x + y * y + z * z);\n var s, c, t;\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n var b00, b01, b02;\n var b10, b11, b12;\n var b20, b21, b22;\n if (len < glMatrix.EPSILON) {\n return null;\n }\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n\n // Construct the elements of the rotation matrix\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c;\n\n // Perform rotation-specific matrix multiplication\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateX(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateY(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateZ(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function fromRotation(out, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.sqrt(x * x + y * y + z * z);\n var s, c, t;\n if (len < glMatrix.EPSILON) {\n return null;\n }\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n\n // Perform rotation-specific matrix multiplication\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromXRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromYRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromZRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n * let quatMat = mat4.create();\n * mat4.fromQuat(quatMat, quat);\n * mat4.multiply(dest, dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\nexport function fromQuat2(out, a) {\n var translation = new glMatrix.ARRAY_TYPE(3);\n var bx = -a[0],\n by = -a[1],\n bz = -a[2],\n bw = a[3],\n ax = a[4],\n ay = a[5],\n az = a[6],\n aw = a[7];\n var magnitude = bx * bx + by * by + bz * bz + bw * bw;\n //Only scale if it makes sense\n if (magnitude > 0) {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n fromRotationTranslation(out, a, translation);\n return out;\n}\n\n/**\n * Returns the translation vector component of a transformation\n * matrix. If a matrix is built with fromRotationTranslation,\n * the returned vector will be the same as the translation vector\n * originally supplied.\n * @param {vec3} out Vector to receive translation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n return out;\n}\n\n/**\n * Returns the scaling factor component of a transformation\n * matrix. If a matrix is built with fromRotationTranslationScale\n * with a normalized Quaternion parameter, the returned vector will be\n * the same as the scaling vector\n * originally supplied.\n * @param {vec3} out Vector to receive scaling factor component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getScaling(out, mat) {\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n out[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n out[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n return out;\n}\n\n/**\n * Returns a quaternion representing the rotational component\n * of a transformation matrix. If a matrix is built with\n * fromRotationTranslation, the returned quaternion will be the\n * same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\nexport function getRotation(out, mat) {\n var scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n var is1 = 1 / scaling[0];\n var is2 = 1 / scaling[1];\n var is3 = 1 / scaling[2];\n var sm11 = mat[0] * is1;\n var sm12 = mat[1] * is2;\n var sm13 = mat[2] * is3;\n var sm21 = mat[4] * is1;\n var sm22 = mat[5] * is2;\n var sm23 = mat[6] * is3;\n var sm31 = mat[8] * is1;\n var sm32 = mat[9] * is2;\n var sm33 = mat[10] * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n return out;\n}\n\n/**\n * Decomposes a transformation matrix into its rotation, translation\n * and scale components. Returns only the rotation component\n * @param {quat} out_r Quaternion to receive the rotation component\n * @param {vec3} out_t Vector to receive the translation vector\n * @param {vec3} out_s Vector to receive the scaling factor\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @returns {quat} out_r\n */\nexport function decompose(out_r, out_t, out_s, mat) {\n out_t[0] = mat[12];\n out_t[1] = mat[13];\n out_t[2] = mat[14];\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out_s[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n out_s[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n out_s[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n var is1 = 1 / out_s[0];\n var is2 = 1 / out_s[1];\n var is3 = 1 / out_s[2];\n var sm11 = m11 * is1;\n var sm12 = m12 * is2;\n var sm13 = m13 * is3;\n var sm21 = m21 * is1;\n var sm22 = m22 * is2;\n var sm23 = m23 * is3;\n var sm31 = m31 * is1;\n var sm32 = m32 * is2;\n var sm33 = m33 * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out_r[3] = 0.25 * S;\n out_r[0] = (sm23 - sm32) / S;\n out_r[1] = (sm31 - sm13) / S;\n out_r[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out_r[3] = (sm23 - sm32) / S;\n out_r[0] = 0.25 * S;\n out_r[1] = (sm12 + sm21) / S;\n out_r[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out_r[3] = (sm31 - sm13) / S;\n out_r[0] = (sm12 + sm21) / S;\n out_r[1] = 0.25 * S;\n out_r[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out_r[3] = (sm12 - sm21) / S;\n out_r[0] = (sm31 + sm13) / S;\n out_r[1] = (sm23 + sm32) / S;\n out_r[2] = 0.25 * S;\n }\n return out_r;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n * let quatMat = mat4.create();\n * mat4.fromQuat(quatMat, quat);\n * mat4.multiply(dest, dest, quatMat);\n * mat4.scale(dest, dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n * mat4.translate(dest, dest, origin);\n * let quatMat = mat4.create();\n * mat4.fromQuat(quatMat, quat);\n * mat4.multiply(dest, dest, quatMat);\n * mat4.scale(dest, dest, scale)\n * mat4.translate(dest, dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n var ox = o[0];\n var oy = o[1];\n var oz = o[2];\n var out0 = (1 - (yy + zz)) * sx;\n var out1 = (xy + wz) * sx;\n var out2 = (xz - wy) * sx;\n var out4 = (xy - wz) * sy;\n var out5 = (1 - (xx + zz)) * sy;\n var out6 = (yz + wx) * sy;\n var out8 = (xz + wy) * sz;\n var out9 = (yz - wx) * sz;\n var out10 = (1 - (xx + yy)) * sz;\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n return out;\n}\n\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function frustum(out, left, right, bottom, top, near, far) {\n var rl = 1 / (right - left);\n var tb = 1 / (top - bottom);\n var nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2);\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n if (far != null && far !== Infinity) {\n var nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n return out;\n}\n\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\nexport var perspective = perspectiveNO;\n\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2);\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n if (far != null && far !== Infinity) {\n var nf = 1 / (near - far);\n out[10] = far * nf;\n out[14] = far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -near;\n }\n return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = far * near / (near - far);\n out[15] = 0.0;\n return out;\n}\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\nexport var ortho = orthoNO;\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = near * nf;\n out[15] = 1;\n return out;\n}\n\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function lookAt(out, eye, center, up) {\n var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;\n var eyex = eye[0];\n var eyey = eye[1];\n var eyez = eye[2];\n var upx = up[0];\n var upy = up[1];\n var upz = up[2];\n var centerx = center[0];\n var centery = center[1];\n var centerz = center[2];\n if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {\n return identity(out);\n }\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n return out;\n}\n\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} target Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function targetTo(out, eye, target, up) {\n var eyex = eye[0],\n eyey = eye[1],\n eyez = eye[2],\n upx = up[0],\n upy = up[1],\n upz = up[2];\n var z0 = eyex - target[0],\n z1 = eyey - target[1],\n z2 = eyez - target[2];\n var len = z0 * z0 + z1 * z1 + z2 * z2;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n var x0 = upy * z2 - upz * z1,\n x1 = upz * z0 - upx * z2,\n x2 = upx * z1 - upy * z0;\n len = x0 * x0 + x1 * x1 + x2 * x2;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\nexport function str(a) {\n return \"mat4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \", \" + a[9] + \", \" + a[10] + \", \" + a[11] + \", \" + a[12] + \", \" + a[13] + \", \" + a[14] + \", \" + a[15] + \")\";\n}\n\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\nexport function frob(a) {\n return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3] + a[4] * a[4] + a[5] * a[5] + a[6] * a[6] + a[7] * a[7] + a[8] * a[8] + a[9] * a[9] + a[10] * a[10] + a[11] * a[11] + a[12] * a[12] + a[13] * a[13] + a[14] * a[14] + a[15] * a[15]);\n}\n\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} 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 out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} 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 out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\nexport function multiplyScalarAndAdd(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 out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];\n}\n\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7];\n var a8 = a[8],\n a9 = a[9],\n a10 = a[10],\n a11 = a[11];\n var a12 = a[12],\n a13 = a[13],\n a14 = a[14],\n a15 = a[15];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n var b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7];\n var b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11];\n var b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\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)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));\n}\n\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\nexport var sub = subtract;","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}();","export interface FixedStepContext {\n readonly frame: number;\n readonly deltaMs: number;\n readonly nowMs: number;\n}\n\nexport interface RenderContext {\n readonly alpha: number;\n readonly nowMs: number;\n readonly accumulatorMs: number;\n readonly frame: number;\n}\n\nexport interface LoopCallbacks {\n simulate(step: FixedStepContext): void;\n render?(sample: RenderContext): void;\n}\n\nexport interface LoopOptions {\n readonly fixedDeltaMs: number;\n readonly maxSubSteps: number;\n readonly maxDeltaMs: number;\n readonly startTimeMs?: number;\n readonly now: () => number;\n readonly schedule: (tick: () => void) => unknown;\n}\n\nconst DEFAULT_FIXED_DELTA_MS = 25;\nconst DEFAULT_MAX_SUBSTEPS = 5;\n\nconst defaultNow = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\nconst defaultScheduler = (tick: () => void) => {\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => tick());\n } else {\n setTimeout(tick, DEFAULT_FIXED_DELTA_MS);\n }\n};\n\nexport class FixedTimestepLoop {\n private readonly options: LoopOptions;\n private accumulatorMs = 0;\n private frame = 0;\n private lastTimeMs: number | undefined;\n private running = false;\n\n constructor(private readonly callbacks: LoopCallbacks, options: Partial<LoopOptions> = {}) {\n const fixedDeltaMs = options.fixedDeltaMs ?? DEFAULT_FIXED_DELTA_MS;\n const maxSubSteps = options.maxSubSteps ?? DEFAULT_MAX_SUBSTEPS;\n this.options = {\n fixedDeltaMs,\n maxSubSteps,\n maxDeltaMs: options.maxDeltaMs ?? fixedDeltaMs * maxSubSteps,\n startTimeMs: options.startTimeMs,\n now: options.now ?? defaultNow,\n schedule: options.schedule ?? defaultScheduler,\n } satisfies LoopOptions;\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n this.lastTimeMs = this.options.startTimeMs ?? this.options.now();\n this.options.schedule(this.tick);\n }\n\n stop(): void {\n this.running = false;\n }\n\n pump(elapsedMs: number): void {\n const nowMs = (this.lastTimeMs ?? 0) + elapsedMs;\n this.lastTimeMs = nowMs;\n this.advance(elapsedMs, nowMs);\n }\n\n isRunning(): boolean {\n return this.running;\n }\n\n get frameNumber(): number {\n return this.frame;\n }\n\n private tick = (): void => {\n if (!this.running) return;\n\n const nowMs = this.options.now();\n const elapsed = this.lastTimeMs === undefined ? 0 : nowMs - this.lastTimeMs;\n this.lastTimeMs = nowMs;\n\n this.advance(elapsed, nowMs);\n\n if (this.running) {\n this.options.schedule(this.tick);\n }\n };\n\n private advance(elapsedMs: number, nowMs: number): void {\n const clampedDelta = Math.min(Math.max(elapsedMs, 0), this.options.maxDeltaMs);\n this.accumulatorMs = Math.min(\n this.accumulatorMs + clampedDelta,\n this.options.fixedDeltaMs * this.options.maxSubSteps,\n );\n\n let steps = 0;\n while (this.accumulatorMs >= this.options.fixedDeltaMs && steps < this.options.maxSubSteps) {\n this.frame += 1;\n this.callbacks.simulate({ frame: this.frame, deltaMs: this.options.fixedDeltaMs, nowMs });\n this.accumulatorMs -= this.options.fixedDeltaMs;\n steps += 1;\n }\n\n const alpha = this.options.fixedDeltaMs === 0 ? 0 : this.accumulatorMs / this.options.fixedDeltaMs;\n this.callbacks.render?.({ alpha, nowMs, accumulatorMs: this.accumulatorMs, frame: this.frame });\n }\n}\n","import {\n FixedTimestepLoop,\n type FixedStepContext,\n type LoopOptions,\n type RenderContext,\n} from './loop.js';\n\nexport interface GameFrameResult<FrameState = unknown> {\n readonly frame: number;\n readonly timeMs: number;\n readonly state?: FrameState;\n}\n\nexport interface GameSimulation<FrameState = unknown> {\n init(startTimeMs: number): GameFrameResult<FrameState> | void;\n frame(step: FixedStepContext, command?: any): GameFrameResult<FrameState>;\n shutdown(): void;\n}\n\nexport interface GameRenderSample<FrameState = unknown> extends RenderContext {\n readonly previous?: GameFrameResult<FrameState>;\n readonly latest?: GameFrameResult<FrameState>;\n}\n\nimport { UserCommand } from '@quake2ts/shared';\nimport { Camera } from './render/camera.js';\n\nexport interface ClientRenderer<FrameState = unknown> {\n init(initial?: GameFrameResult<FrameState>): void;\n render(sample: GameRenderSample<FrameState>): any;\n shutdown(): void;\n camera?: Camera;\n}\n\nexport interface EngineHostOptions {\n readonly loop?: Partial<LoopOptions>;\n readonly startTimeMs?: number;\n}\n\nexport class EngineHost<FrameState = unknown> {\n private readonly loop: FixedTimestepLoop;\n private readonly startTimeMs: number;\n private previousFrame?: GameFrameResult<FrameState>;\n private latestFrame?: GameFrameResult<FrameState>;\n private started = false;\n private latestCommand?: UserCommand;\n\n constructor(\n private readonly game: GameSimulation<FrameState>,\n private readonly client?: ClientRenderer<FrameState>,\n options: EngineHostOptions = {},\n ) {\n const now = options.loop?.now?.() ?? Date.now();\n this.startTimeMs = options.startTimeMs ?? options.loop?.startTimeMs ?? now;\n this.loop = new FixedTimestepLoop(\n {\n simulate: this.stepSimulation,\n render: this.renderClient,\n },\n { ...options.loop, startTimeMs: this.startTimeMs },\n );\n }\n\n start(): void {\n if (this.started) return;\n\n this.latestFrame = this.game.init(this.startTimeMs) ?? this.latestFrame;\n this.client?.init(this.latestFrame);\n\n this.started = true;\n this.loop.start();\n }\n\n stop(): void {\n if (!this.started) return;\n\n this.loop.stop();\n this.client?.shutdown();\n this.game.shutdown();\n this.previousFrame = undefined;\n this.latestFrame = undefined;\n this.started = false;\n }\n\n pump(elapsedMs: number): void {\n this.loop.pump(elapsedMs);\n }\n\n getLatestFrame(): GameFrameResult<FrameState> | undefined {\n return this.latestFrame;\n }\n\n isRunning(): boolean {\n return this.loop.isRunning();\n }\n\n private stepSimulation = (step: FixedStepContext): void => {\n this.previousFrame = this.latestFrame;\n this.latestFrame = this.game.frame(step, this.latestCommand);\n };\n\n private renderClient = (renderContext: RenderContext): void => {\n if (!this.client) return;\n\n this.latestCommand = this.client.render({\n ...renderContext,\n previous: this.previousFrame,\n latest: this.latestFrame,\n });\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 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","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 /** 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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } from '../math/vec3.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 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\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 let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false;\n let startout = false;\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\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 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 if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n if (d1 > d2) {\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 const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n if (!startout) {\n trace.startsolid = true;\n if (!getout) {\n trace.allsolid = true;\n }\n trace.fraction = 0;\n return;\n }\n\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n trace.fraction = enterfrac < 0 ? 0 : 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\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 (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\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 if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n // Use absolute value of offset like original C code (full/qcommon/cmodel.c:1269-1271)\n // which uses fabs() on each component\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start);\n const endDist = planeDistanceToPoint(plane, end);\n\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 (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 // Put the crosspoint DIST_EPSILON pixels on the near side\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 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 if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\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 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\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\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 for (const entity of this.entities.values()) {\n if (entity.id === passId) 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 const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\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 for (const entity of this.entities.values()) {\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 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 PlayerSkins = Items + MAX_ITEMS,\n General = PlayerSkins + 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","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 Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n} from './types.js';\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 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 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 {\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","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 {\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 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, 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 { 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 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 jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: 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, 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, 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\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, 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 return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\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 { 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 { 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\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\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 { 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}\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}\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}\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';\n\nconst FRAMETIME = 0.025;\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 point.z += state.mins.z + 1;\n const contents = pointContents(point);\n if (contents & 0x2000000) {\n return { ...state, waterLevel: 1 };\n }\n return { ...state, waterLevel: 0 };\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 } = newState;\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: { x: 1, y: 0, z: 0 },\n right: { x: 0, y: 1, z: 0 },\n cmd,\n maxSpeed: 320,\n })\n : buildAirGroundWish({\n forward: { x: 1, y: 0, z: 0 },\n right: { x: 0, y: 1, z: 0 },\n cmd,\n maxSpeed: 320,\n });\n\n const finalVelocity = applyPmoveAccelerate({\n velocity: frictionedVelocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: onGround ? 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';\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 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 hasMore(): boolean {\n return this.offset < 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 readLong(): number {\n const value = this.view.getInt32(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 // TODO: Implement bytedirs lookup\n // For now, zero it out\n out.x = 0; out.y = 0; out.z = 0;\n }\n}\n","import {\n ConfigStringIndex,\n CS_MAX_STRING_LENGTH,\n MAX_CONFIGSTRINGS,\n MAX_GENERAL,\n MAX_IMAGES,\n MAX_ITEMS,\n MAX_LIGHTSTYLES,\n MAX_MODELS,\n MAX_CLIENTS,\n MAX_SHADOW_LIGHTS,\n MAX_SOUNDS,\n MAX_WHEEL_ITEMS,\n configStringSize,\n} from '@quake2ts/shared';\n\nexport type ConfigStringEntry = Readonly<{ index: number; value: string }>;\n\nfunction assertWithinBounds(index: number): void {\n if (index < 0 || index >= ConfigStringIndex.MaxConfigStrings) {\n throw new RangeError(`Configstring index ${index} is out of range (0-${ConfigStringIndex.MaxConfigStrings - 1})`);\n }\n}\n\nfunction assertLength(index: number, value: string): void {\n const maxLength = configStringSize(index);\n if (value.length > maxLength) {\n throw new RangeError(\n `Configstring ${index} exceeds maximum length (${value.length} > ${maxLength}); limit is ${CS_MAX_STRING_LENGTH} chars per slot`,\n );\n }\n}\n\n/**\n * Minimal configstring/config index registry that mirrors the rerelease asset\n * indexing routines (`modelindex`, `soundindex`, etc.). The registry maintains\n * deterministic ordering within each configstring range and enforces the same\n * length/slot limits as the C++ helpers.\n */\nexport class ConfigStringRegistry {\n private readonly values = new Map<number, string>();\n private modelCursor = ConfigStringIndex.Models;\n private soundCursor = ConfigStringIndex.Sounds;\n private imageCursor = ConfigStringIndex.Images;\n private lightCursor = ConfigStringIndex.Lights;\n private shadowLightCursor = ConfigStringIndex.ShadowLights;\n private itemCursor = ConfigStringIndex.Items;\n private playerSkinCursor = ConfigStringIndex.PlayerSkins;\n private generalCursor = ConfigStringIndex.General;\n\n set(index: number, value: string): number {\n assertWithinBounds(index);\n assertLength(index, value);\n this.values.set(index, value);\n return index;\n }\n\n get(index: number): string | undefined {\n return this.values.get(index);\n }\n\n getAll(): string[] {\n const result: string[] = new Array(MAX_CONFIGSTRINGS).fill('');\n for (const [index, value] of this.values.entries()) {\n result[index] = value;\n }\n return result;\n }\n\n modelIndex(path: string): number {\n return this.register(path, ConfigStringIndex.Models, MAX_MODELS, 'modelCursor');\n }\n\n soundIndex(path: string): number {\n return this.register(path, ConfigStringIndex.Sounds, MAX_SOUNDS, 'soundCursor');\n }\n\n findSoundIndex(path: string): number | undefined {\n for (let i = ConfigStringIndex.Sounds; i < ConfigStringIndex.Sounds + MAX_SOUNDS; i += 1) {\n if (this.values.get(i) === path) {\n return i;\n }\n }\n return undefined;\n }\n\n imageIndex(path: string): number {\n return this.register(path, ConfigStringIndex.Images, MAX_IMAGES, 'imageCursor');\n }\n\n lightIndex(definition: string): number {\n return this.register(definition, ConfigStringIndex.Lights, MAX_LIGHTSTYLES, 'lightCursor');\n }\n\n shadowLightIndex(definition: string): number {\n return this.register(definition, ConfigStringIndex.ShadowLights, MAX_SHADOW_LIGHTS, 'shadowLightCursor');\n }\n\n itemIndex(name: string): number {\n return this.register(name, ConfigStringIndex.Items, MAX_ITEMS, 'itemCursor');\n }\n\n playerSkinIndex(name: string): number {\n return this.register(name, ConfigStringIndex.PlayerSkins, MAX_CLIENTS, 'playerSkinCursor');\n }\n\n generalIndex(value: string): number {\n return this.register(value, ConfigStringIndex.General, MAX_GENERAL, 'generalCursor');\n }\n\n private register(\n value: string,\n start: ConfigStringIndex,\n maxCount: number,\n cursorKey:\n | 'modelCursor'\n | 'soundCursor'\n | 'imageCursor'\n | 'lightCursor'\n | 'shadowLightCursor'\n | 'itemCursor'\n | 'playerSkinCursor'\n | 'generalCursor',\n ): number {\n // Reuse an existing slot if the caller tries to register the same value in the same range.\n for (let i = start; i < start + maxCount; i += 1) {\n if (this.values.get(i) === value) {\n return i;\n }\n }\n\n const next = this[cursorKey];\n const limit = start + maxCount;\n if (next >= limit) {\n throw new RangeError(`Out of configstring slots for range starting at ${start}`);\n }\n\n assertLength(next, value);\n this.values.set(next, value);\n this[cursorKey] = next + 1;\n return next;\n }\n}\n","import type { EngineExports } from './index.js';\nimport { EngineHost, type ClientRenderer, type EngineHostOptions, type GameFrameResult, type GameSimulation } from './host.js';\n\nexport class EngineRuntime<FrameState = unknown> {\n private started = false;\n\n constructor(private readonly engine: EngineExports, private readonly host: EngineHost<FrameState>) {}\n\n start(): void {\n if (this.started) return;\n this.engine.init();\n this.host.start();\n this.started = true;\n }\n\n stop(): void {\n if (!this.started) return;\n this.host.stop();\n this.engine.shutdown();\n this.started = false;\n }\n\n pump(elapsedMs: number): void {\n this.host.pump(elapsedMs);\n }\n\n getLatestFrame(): GameFrameResult<FrameState> | undefined {\n return this.host.getLatestFrame();\n }\n\n isRunning(): boolean {\n return this.started && this.host.isRunning();\n }\n}\n\nexport function createEngineRuntime<FrameState = unknown>(\n engine: EngineExports,\n game: GameSimulation<FrameState>,\n client?: ClientRenderer<FrameState>,\n options?: EngineHostOptions,\n): EngineRuntime<FrameState> {\n return new EngineRuntime(engine, new EngineHost(game, client, options));\n}\n","import { CvarFlags } from '@quake2ts/shared';\n\nexport type CvarChangeHandler = (cvar: Cvar, previousValue: string) => void;\n\nexport class Cvar {\n readonly name: string;\n readonly defaultValue: string;\n readonly description?: string;\n readonly flags: CvarFlags;\n private _value: string;\n private latched?: string;\n private onChange?: CvarChangeHandler;\n modifiedCount = 0;\n\n constructor({\n name,\n defaultValue,\n description,\n flags = CvarFlags.None,\n onChange,\n }: {\n name: string;\n defaultValue: string;\n description?: string;\n flags?: CvarFlags;\n onChange?: CvarChangeHandler;\n }) {\n this.name = name;\n this.defaultValue = defaultValue;\n this.description = description;\n this.flags = flags;\n this._value = defaultValue;\n this.onChange = onChange;\n }\n\n get string(): string {\n return this._value;\n }\n\n get number(): number {\n return Number(this._value);\n }\n\n get integer(): number {\n return Math.trunc(this.number);\n }\n\n get boolean(): boolean {\n return Boolean(this.integer);\n }\n\n set(value: string): void {\n if (this.flags & CvarFlags.Latch) {\n if (value === this._value) {\n this.latched = undefined;\n return;\n }\n\n if (this.latched === value) {\n return;\n }\n\n if (this.latched !== value) {\n this.latched = value;\n }\n return;\n }\n\n this.apply(value);\n }\n\n reset(): void {\n this.latched = undefined;\n this.apply(this.defaultValue);\n }\n\n applyLatched(): boolean {\n if (this.latched === undefined) {\n return false;\n }\n\n const pending = this.latched;\n this.latched = undefined;\n if (pending === this._value) {\n return false;\n }\n this.apply(pending);\n return true;\n }\n\n private apply(next: string): void {\n if (this._value === next) {\n return;\n }\n\n const previous = this._value;\n this._value = next;\n this.modifiedCount += 1;\n this.onChange?.(this, previous);\n }\n}\n\nexport class CvarRegistry {\n private readonly cvars = new Map<string, Cvar>();\n\n register(def: {\n name: string;\n defaultValue: string;\n description?: string;\n flags?: CvarFlags;\n onChange?: CvarChangeHandler;\n }): Cvar {\n const existing = this.cvars.get(def.name);\n if (existing) {\n return existing;\n }\n\n const cvar = new Cvar(def);\n this.cvars.set(def.name, cvar);\n return cvar;\n }\n\n get(name: string): Cvar | undefined {\n return this.cvars.get(name);\n }\n\n setValue(name: string, value: string): Cvar {\n const cvar = this.get(name);\n if (!cvar) {\n throw new Error(`Unknown cvar: ${name}`);\n }\n\n cvar.set(value);\n return cvar;\n }\n\n resetAll(): void {\n for (const cvar of this.cvars.values()) {\n cvar.reset();\n }\n }\n\n applyLatched(): boolean {\n let changed = false;\n for (const cvar of this.cvars.values()) {\n changed = cvar.applyLatched() || changed;\n }\n return changed;\n }\n\n list(): Cvar[] {\n return [...this.cvars.values()].sort((a, b) => a.name.localeCompare(b.name));\n }\n}\n","const PAK_MAGIC = 'PACK';\nconst HEADER_SIZE = 12;\nconst DIRECTORY_ENTRY_SIZE = 64;\n\nexport interface PakDirectoryEntry {\n readonly name: string;\n readonly offset: number;\n readonly length: number;\n}\n\nexport interface PakValidationResult {\n readonly checksum: number;\n readonly entries: readonly PakDirectoryEntry[];\n}\n\nfunction readCString(view: DataView, offset: number, maxLength: number): string {\n const codes: number[] = [];\n for (let i = 0; i < maxLength; i += 1) {\n const code = view.getUint8(offset + i);\n if (code === 0) {\n break;\n }\n codes.push(code);\n }\n return String.fromCharCode(...codes);\n}\n\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/').replace(/^\\/+/, '').toLowerCase();\n}\n\nfunction createCrcTable(): Uint32Array {\n const table = new Uint32Array(256);\n for (let i = 0; i < 256; i += 1) {\n let crc = i;\n for (let j = 0; j < 8; j += 1) {\n crc = (crc & 1) !== 0 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;\n }\n table[i] = crc >>> 0;\n }\n return table;\n}\n\nconst CRC_TABLE = createCrcTable();\n\nfunction crc32(data: Uint8Array): number {\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i += 1) {\n const byte = data[i];\n crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ 0xffffffff) >>> 0;\n}\n\nexport class PakParseError extends Error {}\n\nexport class PakArchive {\n static fromArrayBuffer(name: string, buffer: ArrayBuffer): PakArchive {\n const view = new DataView(buffer);\n if (buffer.byteLength < HEADER_SIZE) {\n throw new PakParseError('PAK buffer too small to contain header');\n }\n\n const magic = String.fromCharCode(\n view.getUint8(0),\n view.getUint8(1),\n view.getUint8(2),\n view.getUint8(3),\n );\n\n if (magic !== PAK_MAGIC) {\n throw new PakParseError(`Invalid PAK header magic: ${magic}`);\n }\n\n const dirOffset = view.getInt32(4, true);\n const dirLength = view.getInt32(8, true);\n\n if (dirOffset < HEADER_SIZE) {\n throw new PakParseError(`Invalid directory offset: ${dirOffset}`);\n }\n\n if (dirLength <= 0 || dirLength % DIRECTORY_ENTRY_SIZE !== 0) {\n throw new PakParseError(`Invalid directory length: ${dirLength}`);\n }\n\n const dirEnd = dirOffset + dirLength;\n if (dirEnd > buffer.byteLength) {\n throw new PakParseError('Directory exceeds buffer length');\n }\n\n const entryCount = dirLength / DIRECTORY_ENTRY_SIZE;\n const entries: PakDirectoryEntry[] = [];\n const dedupe = new Map<string, PakDirectoryEntry>();\n\n for (let i = 0; i < entryCount; i += 1) {\n const offset = dirOffset + i * DIRECTORY_ENTRY_SIZE;\n const rawName = readCString(view, offset, 56);\n const normalized = normalizePath(rawName);\n\n const fileOffset = view.getInt32(offset + 56, true);\n const fileLength = view.getInt32(offset + 60, true);\n\n if (fileOffset < 0 || fileLength < 0 || fileOffset + fileLength > buffer.byteLength) {\n throw new PakParseError(\n `Invalid entry bounds for ${rawName || '<unnamed>'} (offset=${fileOffset}, length=${fileLength})`,\n );\n }\n\n if (!normalized) {\n throw new PakParseError(`Entry ${i} has an empty name`);\n }\n\n const entry: PakDirectoryEntry = { name: normalized, offset: fileOffset, length: fileLength };\n dedupe.set(normalized, entry);\n }\n\n entries.push(...dedupe.values());\n\n return new PakArchive(name, buffer, entries, crc32(new Uint8Array(buffer)));\n }\n\n readonly entries: ReadonlyMap<string, PakDirectoryEntry>;\n readonly checksum: number;\n readonly size: number;\n\n private constructor(\n readonly name: string,\n private readonly buffer: ArrayBuffer,\n entries: PakDirectoryEntry[],\n checksum: number,\n ) {\n this.entries = new Map(entries.map((entry) => [entry.name, entry]));\n this.checksum = checksum;\n this.size = buffer.byteLength;\n }\n\n getEntry(path: string): PakDirectoryEntry | undefined {\n return this.entries.get(normalizePath(path));\n }\n\n listEntries(): PakDirectoryEntry[] {\n return Array.from(this.entries.values());\n }\n\n readFile(path: string): Uint8Array {\n const entry = this.getEntry(path);\n if (!entry) {\n throw new PakParseError(`File not found in PAK: ${path}`);\n }\n return new Uint8Array(this.buffer, entry.offset, entry.length);\n }\n\n validate(): PakValidationResult {\n return {\n checksum: this.checksum,\n entries: this.listEntries(),\n };\n }\n}\n\nexport function calculatePakChecksum(buffer: ArrayBuffer): number {\n return crc32(new Uint8Array(buffer));\n}\n\nexport { normalizePath };\n","import { PakArchive, PakDirectoryEntry, normalizePath } from './pak.js';\n\ntype VfsSource = { archive: PakArchive; entry: PakDirectoryEntry };\n\nexport interface VirtualFileHandle {\n readonly path: string;\n readonly size: number;\n readonly sourcePak: string;\n}\n\nexport interface DirectoryListing {\n readonly files: VirtualFileHandle[];\n readonly directories: string[];\n}\n\nexport class VirtualFileSystem {\n private readonly mounts: PakArchive[] = [];\n private readonly files = new Map<string, VfsSource>();\n\n constructor(archives: PakArchive[] = []) {\n archives.forEach((archive) => this.mountPak(archive));\n }\n\n mountPak(archive: PakArchive): void {\n this.mounts.push(archive);\n for (const entry of archive.listEntries()) {\n const key = normalizePath(entry.name);\n this.files.set(key, { archive, entry });\n }\n }\n\n get mountedPaks(): readonly PakArchive[] {\n return [...this.mounts];\n }\n\n hasFile(path: string): boolean {\n return this.files.has(normalizePath(path));\n }\n\n stat(path: string): VirtualFileHandle | undefined {\n const source = this.files.get(normalizePath(path));\n if (!source) {\n return undefined;\n }\n return { path: source.entry.name, size: source.entry.length, sourcePak: source.archive.name };\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n const source = this.files.get(normalizePath(path));\n if (!source) {\n throw new Error(`File not found in VFS: ${path}`);\n }\n return source.archive.readFile(path);\n }\n\n list(directory = ''): DirectoryListing {\n const dir = normalizePath(directory).replace(/\\/+$|^\\//g, '');\n const files: VirtualFileHandle[] = [];\n const directories = new Set<string>();\n const prefix = dir ? `${dir}/` : '';\n\n for (const source of this.files.values()) {\n if (dir && !source.entry.name.startsWith(prefix)) {\n continue;\n }\n const relative = dir ? source.entry.name.slice(prefix.length) : source.entry.name;\n const separatorIndex = relative.indexOf('/');\n if (separatorIndex === -1) {\n files.push({ path: source.entry.name, size: source.entry.length, sourcePak: source.archive.name });\n } else {\n directories.add(relative.slice(0, separatorIndex));\n }\n }\n\n files.sort((a, b) => a.path.localeCompare(b.path));\n\n return { files, directories: [...directories].sort() };\n }\n\n findByExtension(extension: string): VirtualFileHandle[] {\n const normalizedExt = extension.startsWith('.') ? extension.toLowerCase() : `.${extension.toLowerCase()}`;\n const results: VirtualFileHandle[] = [];\n for (const source of this.files.values()) {\n if (source.entry.name.toLowerCase().endsWith(normalizedExt)) {\n results.push({ path: source.entry.name, size: source.entry.length, sourcePak: source.archive.name });\n }\n }\n return results.sort((a, b) => a.path.localeCompare(b.path));\n }\n}\n","import { PakArchive, normalizePath, type PakValidationResult } from './pak.js';\n\nexport interface KnownPakChecksum {\n readonly name: string;\n readonly checksum: number;\n readonly size?: number;\n readonly description?: string;\n}\n\nexport interface PakValidationOutcome {\n readonly name: string;\n readonly checksum: number;\n readonly expectedChecksum?: number;\n readonly size?: number;\n readonly status: 'valid' | 'mismatch' | 'unknown';\n readonly description?: string;\n}\n\nexport const RERELEASE_KNOWN_PAKS: readonly KnownPakChecksum[] = Object.freeze([\n // Base campaign\n { name: 'pak0.pak', checksum: 0x8dbe2e6d, description: 'Base game assets' },\n { name: 'pak0.pak@baseq2', checksum: 0x8dbe2e6d, description: 'Base game assets (baseq2)' },\n // Mission packs bundled with the rerelease\n { name: 'pak0.pak@rogue', checksum: 0xc90f1e6d, description: 'Ground Zero (rogue) mission pack' },\n { name: 'pak0.pak@xatrix', checksum: 0x50f58d80, description: 'The Reckoning (xatrix) mission pack' },\n]);\n\nexport class PakValidationError extends Error {\n constructor(readonly result: PakValidationOutcome) {\n super(\n result.status === 'unknown'\n ? `Unknown PAK not allowed: ${result.name}`\n : `PAK checksum mismatch for ${result.name}`,\n );\n this.name = 'PakValidationError';\n }\n}\n\nexport class PakValidator {\n private readonly known = new Map<string, KnownPakChecksum>();\n\n constructor(knownPaks: readonly KnownPakChecksum[] = RERELEASE_KNOWN_PAKS) {\n knownPaks.forEach((pak) => this.known.set(this.normalizePakName(pak.name), pak));\n }\n\n validateArchive(archive: PakArchive | PakValidationResult, nameOverride?: string): PakValidationOutcome {\n const pakName = this.normalizePakName(nameOverride ?? ('name' in archive ? archive.name : 'unknown'));\n const checksum = archive.checksum;\n const size = 'size' in archive ? archive.size : undefined;\n\n const known = this.known.get(pakName);\n if (!known) {\n return { name: pakName, checksum, status: 'unknown', size };\n }\n\n if (known.checksum !== checksum) {\n return {\n name: pakName,\n checksum,\n expectedChecksum: known.checksum,\n status: 'mismatch',\n size,\n description: known.description,\n };\n }\n\n return {\n name: pakName,\n checksum,\n expectedChecksum: known.checksum,\n status: 'valid',\n size,\n description: known.description,\n };\n }\n\n assertValid(archive: PakArchive | PakValidationResult, nameOverride?: string): PakValidationOutcome {\n const outcome = this.validateArchive(archive, nameOverride);\n if (outcome.status === 'mismatch') {\n throw new PakValidationError(outcome);\n }\n return outcome;\n }\n\n private normalizePakName(name: string): string {\n const normalized = normalizePath(name);\n const parts = normalized.split('/');\n const filename = parts.pop() ?? normalized;\n const directory = parts.pop();\n return directory ? `${filename}@${directory}` : filename;\n }\n}\n","import { PakArchive } from './pak.js';\nimport { VirtualFileSystem } from './vfs.js';\nimport { PakIndexStore } from './pakIndexStore.js';\nimport { PakValidationError, PakValidator, type PakValidationOutcome } from './pakValidation.js';\n\nexport interface PakSource {\n readonly name: string;\n readonly data: ArrayBuffer | Blob | ArrayBufferView;\n}\n\nexport interface PakIngestionProgress {\n readonly file: string;\n readonly loadedBytes: number;\n readonly totalBytes: number;\n readonly state: 'reading' | 'parsed' | 'error';\n}\n\nexport interface PakIngestionResult {\n readonly archive: PakArchive;\n readonly mounted: boolean;\n readonly validation?: PakValidationOutcome;\n}\n\nexport interface PakIngestionOptions {\n readonly onProgress?: (progress: PakIngestionProgress) => void;\n readonly onError?: (file: string, error: unknown) => void;\n /**\n * Whether ingestion should abort when a single PAK fails to parse or mount.\n * Defaults to false to allow partial success in multi-PAK scenarios.\n */\n readonly stopOnError?: boolean;\n /**\n * Optional persistence target for PAK directory indexes. When provided, each successfully\n * parsed archive will be stored in IndexedDB so the browser can rebuild listings without\n * reparsing the binary payload.\n */\n readonly pakIndexStore?: PakIndexStore;\n /**\n * Whether to persist parsed PAK indexes. Defaults to true when a pakIndexStore is provided.\n */\n readonly persistIndexes?: boolean;\n /**\n * Optional checksum validator. When provided, PAKs whose checksums do not match the known list will\n * raise a PakValidationError unless `enforceValidation` is explicitly set to false.\n */\n readonly validator?: PakValidator;\n /**\n * Whether checksum mismatches should prevent mounting the archive. Defaults to true when a validator\n * is supplied.\n */\n readonly enforceValidation?: boolean;\n /**\n * Whether unknown PAKs (not present in the validator list) are allowed. Defaults to true.\n */\n readonly allowUnknownPaks?: boolean;\n /**\n * Callback invoked with the validation outcome when a validator is provided.\n */\n readonly onValidationResult?: (outcome: PakValidationOutcome) => void;\n}\n\nexport class PakIngestionError extends Error {\n constructor(readonly file: string, cause: unknown) {\n super(`Failed to ingest PAK: ${file}`);\n this.name = 'PakIngestionError';\n if (cause instanceof Error && cause.stack) {\n this.stack = cause.stack;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).cause = cause;\n }\n}\n\nasync function readBlobWithProgress(source: Blob, onProgress?: (progress: PakIngestionProgress) => void): Promise<ArrayBuffer> {\n if (typeof source.arrayBuffer === 'function') {\n const buffer = await source.arrayBuffer();\n onProgress?.({ file: 'blob', loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'reading' });\n return buffer;\n }\n\n if (typeof FileReader !== 'undefined') {\n return new Promise<ArrayBuffer>((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = () => reject(reader.error ?? new Error('Unknown FileReader error'));\n reader.onprogress = (event) => {\n onProgress?.({\n file: 'blob',\n loadedBytes: event.loaded,\n totalBytes: event.total || source.size,\n state: 'reading',\n });\n };\n reader.onload = () => {\n const result = reader.result;\n if (result instanceof ArrayBuffer) {\n resolve(result);\n } else {\n reject(new Error('Unexpected FileReader result'));\n }\n };\n reader.readAsArrayBuffer(source);\n });\n }\n\n if (typeof Response !== 'undefined') {\n const buffer = await new Response(source).arrayBuffer();\n onProgress?.({ file: 'blob', loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'reading' });\n return buffer;\n }\n\n if (typeof source.stream === 'function') {\n const reader = (source.stream() as ReadableStream<Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n let loaded = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (!value) {\n continue;\n }\n\n const chunk = value as Uint8Array;\n\n chunks.push(chunk);\n loaded += chunk.byteLength;\n onProgress?.({ file: 'blob', loadedBytes: loaded, totalBytes: source.size, state: 'reading' });\n }\n\n const result = new Uint8Array(loaded);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result.buffer;\n }\n\n throw new PakIngestionError('blob', new Error('Unsupported Blob type'));\n}\n\nasync function toArrayBuffer(source: PakSource, onProgress?: (progress: PakIngestionProgress) => void): Promise<ArrayBuffer> {\n if (source.data instanceof ArrayBuffer) {\n onProgress?.({ file: source.name, loadedBytes: source.data.byteLength, totalBytes: source.data.byteLength, state: 'reading' });\n return source.data;\n }\n if (source.data instanceof Blob) {\n const totalBytes = source.data.size;\n return readBlobWithProgress(source.data, (progress) =>\n onProgress?.({ ...progress, file: source.name, totalBytes }),\n );\n }\n\n const buffer = source.data.buffer.slice(source.data.byteOffset, source.data.byteOffset + source.data.byteLength) as ArrayBuffer;\n onProgress?.({ file: source.name, loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'reading' });\n return buffer;\n}\n\nexport async function ingestPaks(\n vfs: VirtualFileSystem,\n sources: PakSource[],\n onProgressOrOptions?: PakIngestionOptions | ((progress: PakIngestionProgress) => void),\n): Promise<PakIngestionResult[]> {\n const options: PakIngestionOptions =\n typeof onProgressOrOptions === 'function' ? { onProgress: onProgressOrOptions } : onProgressOrOptions ?? {};\n\n const shouldPersist = options.persistIndexes ?? Boolean(options.pakIndexStore);\n const enforceValidation = options.enforceValidation ?? Boolean(options.validator);\n const allowUnknownPaks = options.allowUnknownPaks ?? true;\n const stopOnError = options.stopOnError ?? false;\n\n const results: PakIngestionResult[] = [];\n\n for (const source of sources) {\n try {\n const buffer = await toArrayBuffer(source, options.onProgress);\n const archive = PakArchive.fromArrayBuffer(source.name, buffer);\n const validation = options.validator?.validateArchive(archive);\n if (validation) {\n options.onValidationResult?.(validation);\n const isMismatch = validation.status === 'mismatch';\n const isUnknown = validation.status === 'unknown';\n if ((isMismatch && enforceValidation) || (isUnknown && !allowUnknownPaks)) {\n const validationError = new PakValidationError(validation);\n options.onError?.(source.name, validationError);\n if (stopOnError) {\n throw new PakIngestionError(source.name, validationError);\n }\n results.push({ archive, mounted: false, validation });\n continue;\n }\n }\n vfs.mountPak(archive);\n if (shouldPersist && options.pakIndexStore) {\n try {\n await options.pakIndexStore.persist(archive);\n } catch (error) {\n options.onError?.(source.name, error);\n if (stopOnError) {\n throw new PakIngestionError(source.name, error);\n }\n }\n }\n options.onProgress?.({ file: source.name, loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'parsed' });\n results.push({ archive, mounted: true, validation });\n } catch (error) {\n options.onProgress?.({ file: source.name, loadedBytes: 0, totalBytes: 0, state: 'error' });\n options.onError?.(source.name, error);\n\n if (stopOnError) {\n throw new PakIngestionError(source.name, error);\n }\n }\n }\n\n return results;\n}\n","export interface CacheEntry<T> {\n key: string;\n value: T;\n}\n\nexport class LruCache<T> {\n private readonly map = new Map<string, T>();\n\n constructor(private readonly capacity: number) {\n if (capacity <= 0) {\n throw new RangeError('LRU cache capacity must be greater than zero');\n }\n }\n\n get size(): number {\n return this.map.size;\n }\n\n has(key: string): boolean {\n return this.map.has(key);\n }\n\n get(key: string): T | undefined {\n const value = this.map.get(key);\n if (value === undefined) {\n return undefined;\n }\n this.map.delete(key);\n this.map.set(key, value);\n return value;\n }\n\n set(key: string, value: T): void {\n if (this.map.has(key)) {\n this.map.delete(key);\n }\n this.map.set(key, value);\n if (this.map.size > this.capacity) {\n const oldestKey = this.map.keys().next();\n if (!oldestKey.done) {\n this.map.delete(oldestKey.value);\n }\n }\n }\n\n delete(key: string): boolean {\n return this.map.delete(key);\n }\n\n clear(): void {\n this.map.clear();\n }\n\n entries(): CacheEntry<T>[] {\n return Array.from(this.map.entries()).reverse().map(([key, value]) => ({ key, value }));\n }\n}\n","import { ingestPaks, type PakIngestionOptions, type PakIngestionResult, type PakSource } from './ingestion.js';\nimport { VirtualFileSystem } from './vfs.js';\n\nfunction toArray(files: Iterable<File>): File[] {\n return Array.isArray(files) ? files : Array.from(files);\n}\n\nexport function filesToPakSources(files: Iterable<File>): PakSource[] {\n return toArray(files).map((file) => ({ name: file.name, data: file }));\n}\n\nexport async function ingestPakFiles(\n vfs: VirtualFileSystem,\n files: Iterable<File>,\n options?: PakIngestionOptions,\n): Promise<PakIngestionResult[]> {\n const sources = filesToPakSources(files);\n return ingestPaks(vfs, sources, options ?? {});\n}\n\nexport function wireDropTarget(\n element: HTMLElement,\n handler: (files: File[]) => void,\n): () => void {\n const onDragOver = (event: DragEvent) => {\n event.preventDefault();\n event.dataTransfer?.dropEffect && (event.dataTransfer.dropEffect = 'copy');\n };\n\n const onDrop = (event: DragEvent) => {\n event.preventDefault();\n const droppedFiles = event.dataTransfer?.files;\n if (droppedFiles && droppedFiles.length > 0) {\n handler(Array.from(droppedFiles));\n }\n };\n\n element.addEventListener('dragover', onDragOver);\n element.addEventListener('drop', onDrop);\n\n return () => {\n element.removeEventListener('dragover', onDragOver);\n element.removeEventListener('drop', onDrop);\n };\n}\n\nexport function wireFileInput(\n input: HTMLInputElement,\n handler: (files: FileList) => void,\n): () => void {\n const onChange = (event: Event) => {\n const target = event.target as HTMLInputElement | null;\n if (!target || !target.files || target.files.length === 0) {\n return;\n }\n handler(target.files);\n target.value = '';\n };\n\n input.addEventListener('change', onChange);\n return () => input.removeEventListener('change', onChange);\n}\n","// BSP loader for Quake II (version 38)\n// Parses lumps, decompresses visibility (PVS), and exposes derived structures for rendering and collision.\n\nimport { VirtualFileSystem } from './vfs.js';\n\nconst BSP_MAGIC = 'IBSP';\nconst BSP_VERSION = 38;\nconst HEADER_LUMPS = 19;\nconst HEADER_SIZE = 4 + 4 + HEADER_LUMPS * 8; // magic + version + lump infos\n\nexport type Vec3 = [number, number, number];\n\nexport interface BspLumpInfo {\n readonly offset: number;\n readonly length: number;\n}\n\nexport interface BspHeader {\n readonly version: number;\n readonly lumps: ReadonlyMap<BspLump, BspLumpInfo>;\n}\n\nexport interface BspEntities {\n readonly raw: string;\n readonly entities: BspEntity[];\n readonly worldspawn: BspEntity | undefined;\n}\n\nexport interface BspEntity {\n readonly classname?: string;\n readonly properties: Record<string, string>;\n}\n\nexport interface BspPlane {\n readonly normal: Vec3;\n readonly dist: number;\n readonly type: number;\n}\n\nexport interface BspNode {\n readonly planeIndex: number;\n readonly children: [number, number];\n readonly mins: [number, number, number];\n readonly maxs: [number, number, number];\n readonly firstFace: number;\n readonly numFaces: number;\n}\n\nexport interface BspLeaf {\n readonly contents: number;\n readonly cluster: number;\n readonly area: number;\n readonly mins: [number, number, number];\n readonly maxs: [number, number, number];\n readonly firstLeafFace: number;\n readonly numLeafFaces: number;\n readonly firstLeafBrush: number;\n readonly numLeafBrushes: number;\n}\n\nexport interface BspTexInfo {\n readonly s: Vec3;\n readonly sOffset: number;\n readonly t: Vec3;\n readonly tOffset: number;\n readonly flags: number;\n readonly value: number;\n readonly texture: string;\n readonly nextTexInfo: number;\n}\n\nexport interface BspFace {\n readonly planeIndex: number;\n readonly side: number;\n readonly firstEdge: number;\n readonly numEdges: number;\n readonly texInfo: number;\n readonly styles: [number, number, number, number];\n readonly lightOffset: number;\n}\n\nexport interface BspEdge {\n readonly vertices: [number, number];\n}\n\nexport interface BspModel {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly origin: Vec3;\n readonly headNode: number;\n readonly firstFace: number;\n readonly numFaces: number;\n}\n\nexport interface BspBrush {\n readonly firstSide: number;\n readonly numSides: number;\n readonly contents: number;\n}\n\nexport interface BspBrushSide {\n readonly planeIndex: number;\n readonly texInfo: number;\n}\n\nexport interface BspArea {\n readonly numAreaPortals: number;\n readonly firstAreaPortal: number;\n}\n\nexport interface BspAreaPortal {\n readonly portalNumber: number;\n readonly otherArea: number;\n}\n\nexport interface BspVisibilityCluster {\n readonly pvs: Uint8Array;\n readonly phs: Uint8Array;\n}\n\nexport interface BspVisibility {\n readonly numClusters: number;\n readonly clusters: readonly BspVisibilityCluster[];\n}\n\nexport interface BspLightmapInfo {\n readonly offset: number;\n readonly length: number;\n}\n\nexport interface BspLeafLists {\n readonly leafFaces: readonly number[][];\n readonly leafBrushes: readonly number[][];\n}\n\nexport interface BspMap {\n readonly header: BspHeader;\n readonly entities: BspEntities;\n readonly planes: readonly BspPlane[];\n readonly vertices: readonly Vec3[];\n readonly nodes: readonly BspNode[];\n readonly texInfo: readonly BspTexInfo[];\n readonly faces: readonly BspFace[];\n readonly lightMaps: Uint8Array;\n readonly lightMapInfo: readonly (BspLightmapInfo | undefined)[];\n readonly leafs: readonly BspLeaf[];\n readonly leafLists: BspLeafLists;\n readonly edges: readonly BspEdge[];\n readonly surfEdges: Int32Array;\n readonly models: readonly BspModel[];\n readonly brushes: readonly BspBrush[];\n readonly brushSides: readonly BspBrushSide[];\n readonly visibility: BspVisibility | undefined;\n}\n\nexport enum BspLump {\n Entities = 0,\n Planes = 1,\n Vertices = 2,\n Visibility = 3,\n Nodes = 4,\n TexInfo = 5,\n Faces = 6,\n Lighting = 7,\n Leafs = 8,\n LeafFaces = 9,\n LeafBrushes = 10,\n Edges = 11,\n SurfEdges = 12,\n Models = 13,\n Brushes = 14,\n BrushSides = 15,\n Pop = 16,\n Areas = 17,\n AreaPortals = 18,\n}\n\nexport class BspParseError extends Error {}\n\nexport class BspLoader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<BspMap> {\n const buffer = await this.vfs.readFile(path);\n const copy = new Uint8Array(buffer.byteLength);\n copy.set(buffer);\n return parseBsp(copy.buffer);\n }\n}\n\nexport function parseBsp(buffer: ArrayBuffer): BspMap {\n if (buffer.byteLength < HEADER_SIZE) {\n throw new BspParseError('BSP too small to contain header');\n }\n\n const view = new DataView(buffer);\n const magic = String.fromCharCode(view.getUint8(0), view.getUint8(1), view.getUint8(2), view.getUint8(3));\n if (magic !== BSP_MAGIC) {\n throw new BspParseError(`Invalid BSP magic ${magic}`);\n }\n const version = view.getInt32(4, true);\n if (version !== BSP_VERSION) {\n throw new BspParseError(`Unsupported BSP version ${version}`);\n }\n\n const lumps = new Map<BspLump, BspLumpInfo>();\n for (let i = 0; i < HEADER_LUMPS; i += 1) {\n const offset = view.getInt32(8 + i * 8, true);\n const length = view.getInt32(12 + i * 8, true);\n if (offset < 0 || length < 0 || offset + length > buffer.byteLength) {\n throw new BspParseError(`Invalid lump bounds for index ${i}`);\n }\n lumps.set(i as BspLump, { offset, length });\n }\n\n const header: BspHeader = { version, lumps };\n const entities = parseEntities(buffer, lumps.get(BspLump.Entities)!);\n const planes = parsePlanes(buffer, lumps.get(BspLump.Planes)!);\n const vertices = parseVertices(buffer, lumps.get(BspLump.Vertices)!);\n const nodes = parseNodes(buffer, lumps.get(BspLump.Nodes)!);\n const texInfo = parseTexInfo(buffer, lumps.get(BspLump.TexInfo)!);\n const faces = parseFaces(buffer, lumps.get(BspLump.Faces)!);\n const lightMaps = new Uint8Array(buffer, lumps.get(BspLump.Lighting)!.offset, lumps.get(BspLump.Lighting)!.length);\n const lightMapInfo = buildLightMapInfo(faces, lumps.get(BspLump.Lighting)!);\n const leafs = parseLeafs(buffer, lumps.get(BspLump.Leafs)!);\n const edges = parseEdges(buffer, lumps.get(BspLump.Edges)!);\n const surfEdges = parseSurfEdges(buffer, lumps.get(BspLump.SurfEdges)!);\n const models = parseModels(buffer, lumps.get(BspLump.Models)!);\n const brushes = parseBrushes(buffer, lumps.get(BspLump.Brushes)!);\n const brushSides = parseBrushSides(buffer, lumps.get(BspLump.BrushSides)!);\n const leafLists = parseLeafLists(buffer, lumps.get(BspLump.LeafFaces)!, lumps.get(BspLump.LeafBrushes)!, leafs);\n const visibility = parseVisibility(buffer, lumps.get(BspLump.Visibility)!);\n\n return {\n header,\n entities,\n planes,\n vertices,\n nodes,\n texInfo,\n faces,\n lightMaps,\n lightMapInfo,\n leafs,\n leafLists,\n edges,\n surfEdges,\n models,\n brushes,\n brushSides,\n visibility,\n };\n}\n\nfunction parseEntities(buffer: ArrayBuffer, info: BspLumpInfo): BspEntities {\n const raw = new TextDecoder().decode(new Uint8Array(buffer, info.offset, info.length));\n const entities = parseEntityString(raw);\n const worldspawn = entities.find((ent) => ent.classname === 'worldspawn');\n return { raw, entities, worldspawn };\n}\n\nfunction parseEntityString(text: string): BspEntity[] {\n const entities: BspEntity[] = [];\n const tokenizer = /\\{([^}]*)\\}/gms;\n let match: RegExpExecArray | null;\n while ((match = tokenizer.exec(text)) !== null) {\n const entityText = match[1];\n const properties: Record<string, string> = {};\n const kvRegex = /\"([^\\\"]*)\"\\s+\"([^\\\"]*)\"/g;\n let kv: RegExpExecArray | null;\n while ((kv = kvRegex.exec(entityText)) !== null) {\n properties[kv[1]] = kv[2];\n }\n entities.push({ classname: properties.classname, properties });\n }\n return entities;\n}\n\nfunction parsePlanes(buffer: ArrayBuffer, info: BspLumpInfo): BspPlane[] {\n const view = new DataView(buffer, info.offset, info.length);\n const count = info.length / 20;\n if (count % 1 !== 0) {\n throw new BspParseError('Plane lump has invalid length');\n }\n const planes: BspPlane[] = [];\n for (let i = 0; i < count; i += 1) {\n const normal: Vec3 = [view.getFloat32(i * 20, true), view.getFloat32(i * 20 + 4, true), view.getFloat32(i * 20 + 8, true)];\n const dist = view.getFloat32(i * 20 + 12, true);\n const type = view.getInt32(i * 20 + 16, true);\n planes.push({ normal, dist, type });\n }\n return planes;\n}\n\nfunction parseVertices(buffer: ArrayBuffer, info: BspLumpInfo): Vec3[] {\n const view = new DataView(buffer, info.offset, info.length);\n const count = info.length / 12;\n if (count % 1 !== 0) {\n throw new BspParseError('Vertex lump has invalid length');\n }\n const vertices: Vec3[] = [];\n for (let i = 0; i < count; i += 1) {\n vertices.push([\n view.getFloat32(i * 12, true),\n view.getFloat32(i * 12 + 4, true),\n view.getFloat32(i * 12 + 8, true),\n ]);\n }\n return vertices;\n}\n\nfunction parseNodes(buffer: ArrayBuffer, info: BspLumpInfo): BspNode[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 36;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Node lump has invalid length');\n }\n const nodes: BspNode[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const planeIndex = view.getInt32(base, true);\n const children: [number, number] = [view.getInt32(base + 4, true), view.getInt32(base + 8, true)];\n const mins: [number, number, number] = [view.getInt16(base + 12, true), view.getInt16(base + 14, true), view.getInt16(base + 16, true)];\n const maxs: [number, number, number] = [view.getInt16(base + 18, true), view.getInt16(base + 20, true), view.getInt16(base + 22, true)];\n const firstFace = view.getUint16(base + 24, true);\n const numFaces = view.getUint16(base + 26, true);\n nodes.push({ planeIndex, children, mins, maxs, firstFace, numFaces });\n }\n return nodes;\n}\n\nfunction parseTexInfo(buffer: ArrayBuffer, info: BspLumpInfo): BspTexInfo[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 76;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('TexInfo lump has invalid length');\n }\n const texInfos: BspTexInfo[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const s: Vec3 = [view.getFloat32(base, true), view.getFloat32(base + 4, true), view.getFloat32(base + 8, true)];\n const sOffset = view.getFloat32(base + 12, true);\n const t: Vec3 = [view.getFloat32(base + 16, true), view.getFloat32(base + 20, true), view.getFloat32(base + 24, true)];\n const tOffset = view.getFloat32(base + 28, true);\n const flags = view.getInt32(base + 32, true);\n const value = view.getInt32(base + 36, true);\n const textureBytes = new Uint8Array(buffer, info.offset + base + 40, 32);\n const texture = new TextDecoder('utf-8').decode(textureBytes).replace(/\\0.*$/, '');\n const nextTexInfo = view.getInt32(base + 72, true);\n texInfos.push({ s, sOffset, t, tOffset, flags, value, texture, nextTexInfo });\n }\n return texInfos;\n}\n\nfunction parseFaces(buffer: ArrayBuffer, info: BspLumpInfo): BspFace[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 20;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Face lump has invalid length');\n }\n const faces: BspFace[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const planeIndex = view.getUint16(base, true);\n const side = view.getInt16(base + 2, true);\n const firstEdge = view.getInt32(base + 4, true);\n const numEdges = view.getInt16(base + 8, true);\n const texInfo = view.getInt16(base + 10, true);\n const styles: [number, number, number, number] = [\n view.getUint8(base + 12),\n view.getUint8(base + 13),\n view.getUint8(base + 14),\n view.getUint8(base + 15),\n ];\n const lightOffset = view.getInt32(base + 16, true);\n faces.push({ planeIndex, side, firstEdge, numEdges, texInfo, styles, lightOffset });\n }\n return faces;\n}\n\nfunction parseLeafs(buffer: ArrayBuffer, info: BspLumpInfo): BspLeaf[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 28;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Leaf lump has invalid length');\n }\n const leafs: BspLeaf[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const contents = view.getInt32(base, true);\n const cluster = view.getInt16(base + 4, true);\n const area = view.getInt16(base + 6, true);\n const mins: [number, number, number] = [view.getInt16(base + 8, true), view.getInt16(base + 10, true), view.getInt16(base + 12, true)];\n const maxs: [number, number, number] = [view.getInt16(base + 14, true), view.getInt16(base + 16, true), view.getInt16(base + 18, true)];\n const firstLeafFace = view.getUint16(base + 20, true);\n const numLeafFaces = view.getUint16(base + 22, true);\n const firstLeafBrush = view.getUint16(base + 24, true);\n const numLeafBrushes = view.getUint16(base + 26, true);\n leafs.push({ contents, cluster, area, mins, maxs, firstLeafFace, numLeafFaces, firstLeafBrush, numLeafBrushes });\n }\n return leafs;\n}\n\nfunction parseEdges(buffer: ArrayBuffer, info: BspLumpInfo): BspEdge[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 4;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Edge lump has invalid length');\n }\n const edges: BspEdge[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n edges.push({ vertices: [view.getUint16(base, true), view.getUint16(base + 2, true)] });\n }\n return edges;\n}\n\nfunction parseSurfEdges(buffer: ArrayBuffer, info: BspLumpInfo): Int32Array {\n const count = info.length / 4;\n if (count % 1 !== 0) {\n throw new BspParseError('SurfEdge lump has invalid length');\n }\n const view = new DataView(buffer, info.offset, info.length);\n const edges = new Int32Array(count);\n for (let i = 0; i < count; i += 1) {\n edges[i] = view.getInt32(i * 4, true);\n }\n return edges;\n}\n\nfunction parseModels(buffer: ArrayBuffer, info: BspLumpInfo): BspModel[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 48;\n if (info.length % entrySize !== 0) {\n throw new BspParseError('Model lump has invalid length');\n }\n const count = info.length / entrySize;\n const models: BspModel[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const mins: Vec3 = [view.getFloat32(base, true), view.getFloat32(base + 4, true), view.getFloat32(base + 8, true)];\n const maxs: Vec3 = [view.getFloat32(base + 12, true), view.getFloat32(base + 16, true), view.getFloat32(base + 20, true)];\n const origin: Vec3 = [view.getFloat32(base + 24, true), view.getFloat32(base + 28, true), view.getFloat32(base + 32, true)];\n const headNode = view.getInt32(base + 36, true);\n const firstFace = view.getInt32(base + 40, true);\n const numFaces = view.getInt32(base + 44, true);\n models.push({ mins, maxs, origin, headNode, firstFace, numFaces });\n }\n return models;\n}\n\nfunction parseBrushes(buffer: ArrayBuffer, info: BspLumpInfo): BspBrush[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 12;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Brush lump has invalid length');\n }\n const brushes: BspBrush[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n brushes.push({\n firstSide: view.getInt32(base, true),\n numSides: view.getInt32(base + 4, true),\n contents: view.getInt32(base + 8, true),\n });\n }\n return brushes;\n}\n\nfunction parseBrushSides(buffer: ArrayBuffer, info: BspLumpInfo): BspBrushSide[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 8;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Brush side lump has invalid length');\n }\n const sides: BspBrushSide[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n sides.push({ planeIndex: view.getUint16(base, true), texInfo: view.getInt16(base + 2, true) });\n }\n return sides;\n}\n\nfunction parseLeafLists(\n buffer: ArrayBuffer,\n leafFacesInfo: BspLumpInfo,\n leafBrushesInfo: BspLumpInfo,\n leafs: readonly BspLeaf[],\n): BspLeafLists {\n const leafFaces: number[][] = [];\n const leafBrushes: number[][] = [];\n\n const maxLeafFaceIndex = leafFacesInfo.length / 2;\n const maxLeafBrushIndex = leafBrushesInfo.length / 2;\n\n const faceView = new DataView(buffer, leafFacesInfo.offset, leafFacesInfo.length);\n const brushView = new DataView(buffer, leafBrushesInfo.offset, leafBrushesInfo.length);\n\n for (const leaf of leafs) {\n if (leaf.firstLeafFace + leaf.numLeafFaces > maxLeafFaceIndex) {\n throw new BspParseError('Leaf faces reference data past lump bounds');\n }\n if (leaf.firstLeafBrush + leaf.numLeafBrushes > maxLeafBrushIndex) {\n throw new BspParseError('Leaf brushes reference data past lump bounds');\n }\n const faces: number[] = [];\n for (let i = 0; i < leaf.numLeafFaces; i += 1) {\n faces.push(faceView.getUint16((leaf.firstLeafFace + i) * 2, true));\n }\n\n const brushes: number[] = [];\n for (let i = 0; i < leaf.numLeafBrushes; i += 1) {\n brushes.push(brushView.getUint16((leaf.firstLeafBrush + i) * 2, true));\n }\n\n leafFaces.push(faces);\n leafBrushes.push(brushes);\n }\n\n return { leafFaces, leafBrushes };\n}\n\nfunction parseVisibility(buffer: ArrayBuffer, info: BspLumpInfo): BspVisibility | undefined {\n if (info.length === 0) {\n return undefined;\n }\n if (info.length < 4) {\n throw new BspParseError('Visibility lump too small');\n }\n const view = new DataView(buffer, info.offset, info.length);\n const numClusters = view.getInt32(0, true);\n const headerBytes = 4 + numClusters * 8;\n if (numClusters < 0 || headerBytes > info.length) {\n throw new BspParseError('Visibility lump truncated');\n }\n let cursor = 4;\n const clusters: BspVisibilityCluster[] = [];\n for (let i = 0; i < numClusters; i += 1) {\n const pvsOffset = view.getInt32(cursor, true);\n const phsOffset = view.getInt32(cursor + 4, true);\n cursor += 8;\n const absolutePvs = info.offset + pvsOffset;\n const absolutePhs = info.offset + phsOffset;\n const lumpEnd = info.offset + info.length;\n if (\n pvsOffset < 0 ||\n phsOffset < 0 ||\n absolutePvs >= lumpEnd ||\n absolutePhs >= lumpEnd\n ) {\n throw new BspParseError('Visibility offsets out of range');\n }\n clusters.push({\n pvs: decompressVis(buffer, absolutePvs, numClusters, info),\n phs: decompressVis(buffer, absolutePhs, numClusters, info),\n });\n }\n return { numClusters, clusters };\n}\n\nfunction decompressVis(buffer: ArrayBuffer, offset: number, numClusters: number, lump: BspLumpInfo): Uint8Array {\n const rowBytes = Math.ceil(numClusters / 8);\n const result = new Uint8Array(rowBytes);\n const src = new Uint8Array(buffer);\n let srcIndex = offset;\n let destIndex = 0;\n const maxOffset = lump.offset + lump.length;\n while (destIndex < rowBytes) {\n if (srcIndex >= maxOffset) {\n throw new BspParseError('Visibility data truncated');\n }\n const value = src[srcIndex++];\n if (value !== 0) {\n result[destIndex++] = value;\n continue;\n }\n if (srcIndex >= maxOffset) {\n throw new BspParseError('Visibility run exceeds lump bounds');\n }\n const runLength = src[srcIndex++];\n for (let i = 0; i < runLength && destIndex < rowBytes; i += 1) {\n result[destIndex++] = 0;\n }\n }\n return result;\n}\n\nfunction buildLightMapInfo(faces: readonly BspFace[], lightingLump: BspLumpInfo): (BspLightmapInfo | undefined)[] {\n return faces.map((face) => {\n if (face.lightOffset < 0) {\n return undefined;\n }\n return {\n offset: face.lightOffset,\n length: Math.max(0, lightingLump.length - face.lightOffset),\n };\n });\n}\n\nexport function createFaceLightmap(\n face: BspFace,\n lightMaps: Uint8Array,\n info?: BspLightmapInfo,\n): Uint8Array | undefined {\n if (face.lightOffset < 0 || face.lightOffset >= lightMaps.byteLength) {\n return undefined;\n }\n const available = lightMaps.byteLength - face.lightOffset;\n const length = Math.min(info?.length ?? available, available);\n if (length <= 0) {\n return undefined;\n }\n return lightMaps.subarray(face.lightOffset, face.lightOffset + length);\n}\n\nexport function parseWorldspawnSettings(entities: BspEntities): Record<string, string> {\n return entities.worldspawn?.properties ?? {};\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { VirtualFileSystem } from './vfs.js';\n\nconst MD2_MAGIC = 844121161; // 'IDP2'\nconst MD2_VERSION = 8;\nconst HEADER_SIZE = 17 * 4;\nconst MD2_NORMALS: ReadonlyArray<Vec3> = [\n { x: -0.525731, y: 0.0, z: 0.850651 },\n { x: -0.442863, y: 0.238856, z: 0.864188 },\n { x: -0.295242, y: 0.0, z: 0.955423 },\n { x: -0.309017, y: 0.5, z: 0.809017 },\n { x: -0.16246, y: 0.262866, z: 0.951056 },\n { x: 0.0, y: 0.0, z: 1.0 },\n { x: 0.0, y: 0.850651, z: 0.525731 },\n { x: -0.147621, y: 0.716567, z: 0.681718 },\n { x: 0.147621, y: 0.716567, z: 0.681718 },\n { x: 0.0, y: 0.525731, z: 0.850651 },\n { x: 0.309017, y: 0.5, z: 0.809017 },\n { x: 0.525731, y: 0.0, z: 0.850651 },\n { x: 0.295242, y: 0.0, z: 0.955423 },\n { x: 0.442863, y: 0.238856, z: 0.864188 },\n { x: 0.16246, y: 0.262866, z: 0.951056 },\n { x: -0.681718, y: 0.147621, z: 0.716567 },\n { x: -0.809017, y: 0.309017, z: 0.5 },\n { x: -0.587785, y: 0.425325, z: 0.688191 },\n { x: -0.850651, y: 0.525731, z: 0.0 },\n { x: -0.864188, y: 0.442863, z: 0.238856 },\n { x: -0.716567, y: 0.681718, z: 0.147621 },\n { x: -0.688191, y: 0.587785, z: 0.425325 },\n { x: -0.5000, y: 0.809017, z: 0.309017 },\n { x: -0.238856, y: 0.864188, z: 0.442863 },\n { x: -0.425325, y: 0.688191, z: 0.587785 },\n { x: -0.716567, y: 0.681718, z: -0.147621 },\n { x: -0.5000, y: 0.809017, z: -0.309017 },\n { x: -0.525731, y: 0.850651, z: 0.0 },\n { x: 0.0, y: 0.850651, z: -0.525731 },\n { x: -0.238856, y: 0.864188, z: -0.442863 },\n { x: 0.0, y: 0.955423, z: -0.295242 },\n { x: -0.262866, y: 0.951056, z: -0.16246 },\n { x: 0.0, y: 1.0, z: 0.0 },\n { x: 0.0, y: 0.955423, z: 0.295242 },\n { x: -0.262866, y: 0.951056, z: 0.16246 },\n { x: 0.238856, y: 0.864188, z: 0.442863 },\n { x: 0.262866, y: 0.951056, z: 0.16246 },\n { x: 0.5, y: 0.809017, z: 0.309017 },\n { x: 0.238856, y: 0.864188, z: -0.442863 },\n { x: 0.262866, y: 0.951056, z: -0.16246 },\n { x: 0.5, y: 0.809017, z: -0.309017 },\n { x: 0.850651, y: 0.525731, z: 0.0 },\n { x: 0.716567, y: 0.681718, z: 0.147621 },\n { x: 0.716567, y: 0.681718, z: -0.147621 },\n { x: 0.525731, y: 0.850651, z: 0.0 },\n { x: 0.425325, y: 0.688191, z: 0.587785 },\n { x: 0.864188, y: 0.442863, z: 0.238856 },\n { x: 0.688191, y: 0.587785, z: 0.425325 },\n { x: 0.809017, y: 0.309017, z: 0.5 },\n { x: 0.681718, y: 0.147621, z: 0.716567 },\n { x: 0.587785, y: 0.425325, z: 0.688191 },\n { x: 0.955423, y: 0.295242, z: 0.0 },\n { x: 1.0, y: 0.0, z: 0.0 },\n { x: 0.951056, y: 0.16246, z: 0.262866 },\n { x: 0.850651, y: -0.525731, z: 0.0 },\n { x: 0.955423, y: -0.295242, z: 0.0 },\n { x: 0.864188, y: -0.442863, z: 0.238856 },\n { x: 0.951056, y: -0.16246, z: 0.262866 },\n { x: 0.809017, y: -0.309017, z: 0.5 },\n { x: 0.681718, y: -0.147621, z: 0.716567 },\n { x: 0.850651, y: 0.0, z: 0.525731 },\n { x: 0.864188, y: 0.442863, z: -0.238856 },\n { x: 0.809017, y: 0.309017, z: -0.5 },\n { x: 0.951056, y: 0.16246, z: -0.262866 },\n { x: 0.525731, y: 0.0, z: -0.850651 },\n { x: 0.681718, y: 0.147621, z: -0.716567 },\n { x: 0.681718, y: -0.147621, z: -0.716567 },\n { x: 0.850651, y: 0.0, z: -0.525731 },\n { x: 0.809017, y: -0.309017, z: -0.5 },\n { x: 0.864188, y: -0.442863, z: -0.238856 },\n { x: 0.951056, y: -0.16246, z: -0.262866 },\n { x: 0.147621, y: 0.716567, z: -0.681718 },\n { x: 0.309017, y: 0.5, z: -0.809017 },\n { x: 0.425325, y: 0.688191, z: -0.587785 },\n { x: 0.442863, y: 0.238856, z: -0.864188 },\n { x: 0.587785, y: 0.425325, z: -0.688191 },\n { x: 0.688191, y: 0.587785, z: -0.425325 },\n { x: -0.147621, y: 0.716567, z: -0.681718 },\n { x: -0.309017, y: 0.5, z: -0.809017 },\n { x: 0.0, y: 0.525731, z: -0.850651 },\n { x: -0.525731, y: 0.0, z: -0.850651 },\n { x: -0.442863, y: 0.238856, z: -0.864188 },\n { x: -0.295242, y: 0.0, z: -0.955423 },\n { x: -0.16246, y: 0.262866, z: -0.951056 },\n { x: 0.0, y: 0.0, z: -1.0 },\n { x: 0.295242, y: 0.0, z: -0.955423 },\n { x: 0.16246, y: 0.262866, z: -0.951056 },\n { x: -0.442863, y: -0.238856, z: -0.864188 },\n { x: -0.309017, y: -0.5, z: -0.809017 },\n { x: -0.16246, y: -0.262866, z: -0.951056 },\n { x: 0.0, y: -0.850651, z: -0.525731 },\n { x: -0.147621, y: -0.716567, z: -0.681718 },\n { x: 0.147621, y: -0.716567, z: -0.681718 },\n { x: 0.0, y: -0.525731, z: -0.850651 },\n { x: 0.309017, y: -0.5, z: -0.809017 },\n { x: 0.442863, y: -0.238856, z: -0.864188 },\n { x: 0.16246, y: -0.262866, z: -0.951056 },\n { x: 0.238856, y: -0.864188, z: -0.442863 },\n { x: 0.5, y: -0.809017, z: -0.309017 },\n { x: 0.425325, y: -0.688191, z: -0.587785 },\n { x: 0.716567, y: -0.681718, z: -0.147621 },\n { x: 0.688191, y: -0.587785, z: -0.425325 },\n { x: 0.587785, y: -0.425325, z: -0.688191 },\n { x: 0.0, y: -0.955423, z: -0.295242 },\n { x: 0.0, y: -1.0, z: 0.0 },\n { x: 0.262866, y: -0.951056, z: -0.16246 },\n { x: 0.0, y: -0.850651, z: 0.525731 },\n { x: 0.0, y: -0.955423, z: 0.295242 },\n { x: 0.238856, y: -0.864188, z: 0.442863 },\n { x: 0.262866, y: -0.951056, z: 0.16246 },\n { x: 0.5, y: -0.809017, z: 0.309017 },\n { x: 0.716567, y: -0.681718, z: 0.147621 },\n { x: 0.525731, y: -0.850651, z: 0.0 },\n { x: -0.238856, y: -0.864188, z: -0.442863 },\n { x: -0.5, y: -0.809017, z: -0.309017 },\n { x: -0.262866, y: -0.951056, z: -0.16246 },\n { x: -0.850651, y: -0.525731, z: 0.0 },\n { x: -0.716567, y: -0.681718, z: -0.147621 },\n { x: -0.716567, y: -0.681718, z: 0.147621 },\n { x: -0.525731, y: -0.850651, z: 0.0 },\n { x: -0.5, y: -0.809017, z: 0.309017 },\n { x: -0.238856, y: -0.864188, z: 0.442863 },\n { x: -0.262866, y: -0.951056, z: 0.16246 },\n { x: -0.864188, y: -0.442863, z: 0.238856 },\n { x: -0.809017, y: -0.309017, z: 0.5 },\n { x: -0.688191, y: -0.587785, z: 0.425325 },\n { x: -0.681718, y: -0.147621, z: 0.716567 },\n { x: -0.442863, y: -0.238856, z: 0.864188 },\n { x: -0.587785, y: -0.425325, z: 0.688191 },\n { x: -0.309017, y: -0.5, z: 0.809017 },\n { x: -0.147621, y: -0.716567, z: 0.681718 },\n { x: -0.425325, y: -0.688191, z: 0.587785 },\n { x: -0.16246, y: -0.262866, z: 0.951056 },\n { x: 0.442863, y: -0.238856, z: 0.864188 },\n { x: 0.16246, y: -0.262866, z: 0.951056 },\n { x: 0.309017, y: -0.5, z: 0.809017 },\n { x: 0.147621, y: -0.716567, z: 0.681718 },\n { x: 0.0, y: -0.525731, z: 0.850651 },\n { x: 0.425325, y: -0.688191, z: 0.587785 },\n { x: 0.587785, y: -0.425325, z: 0.688191 },\n { x: 0.688191, y: -0.587785, z: 0.425325 },\n { x: -0.955423, y: 0.295242, z: 0.0 },\n { x: -0.951056, y: 0.16246, z: 0.262866 },\n { x: -1.0, y: 0.0, z: 0.0 },\n { x: -0.850651, y: 0.0, z: 0.525731 },\n { x: -0.955423, y: -0.295242, z: 0.0 },\n { x: -0.951056, y: -0.16246, z: 0.262866 },\n { x: -0.864188, y: 0.442863, z: -0.238856 },\n { x: -0.951056, y: 0.16246, z: -0.262866 },\n { x: -0.809017, y: 0.309017, z: -0.5 },\n { x: -0.864188, y: -0.442863, z: -0.238856 },\n { x: -0.951056, y: -0.16246, z: -0.262866 },\n { x: -0.809017, y: -0.309017, z: -0.5 },\n { x: -0.681718, y: 0.147621, z: -0.716567 },\n { x: -0.681718, y: -0.147621, z: -0.716567 },\n { x: -0.850651, y: 0.0, z: -0.525731 },\n { x: -0.688191, y: 0.587785, z: -0.425325 },\n { x: -0.587785, y: 0.425325, z: -0.688191 },\n { x: -0.425325, y: 0.688191, z: -0.587785 },\n { x: -0.425325, y: -0.688191, z: -0.587785 },\n { x: -0.587785, y: -0.425325, z: -0.688191 },\n { x: -0.688191, y: -0.587785, z: -0.425325 },\n];\n\nexport interface Md2Header {\n readonly ident: number;\n readonly version: number;\n readonly skinWidth: number;\n readonly skinHeight: number;\n readonly frameSize: number;\n readonly numSkins: number;\n readonly numVertices: number;\n readonly numTexCoords: number;\n readonly numTriangles: number;\n readonly numGlCommands: number;\n readonly numFrames: number;\n readonly offsetSkins: number;\n readonly offsetTexCoords: number;\n readonly offsetTriangles: number;\n readonly offsetFrames: number;\n readonly offsetGlCommands: number;\n readonly offsetEnd: number;\n}\n\nexport interface Md2Skin {\n readonly name: string;\n}\n\nexport interface Md2TexCoord {\n readonly s: number;\n readonly t: number;\n}\n\nexport interface Md2Triangle {\n readonly vertexIndices: [number, number, number];\n readonly texCoordIndices: [number, number, number];\n}\n\nexport interface Md2Vertex {\n readonly position: Vec3;\n readonly normalIndex: number;\n readonly normal: Vec3;\n}\n\nexport interface Md2Frame {\n readonly name: string;\n readonly vertices: readonly Md2Vertex[];\n}\n\nexport interface Md2GlCommandVertex {\n readonly s: number;\n readonly t: number;\n readonly vertexIndex: number;\n}\n\nexport interface Md2GlCommand {\n readonly mode: 'strip' | 'fan';\n readonly vertices: readonly Md2GlCommandVertex[];\n}\n\nexport interface Md2Model {\n readonly header: Md2Header;\n readonly skins: readonly Md2Skin[];\n readonly texCoords: readonly Md2TexCoord[];\n readonly triangles: readonly Md2Triangle[];\n readonly frames: readonly Md2Frame[];\n readonly glCommands: readonly Md2GlCommand[];\n}\n\nexport interface Md2Animation {\n readonly name: string;\n readonly firstFrame: number;\n readonly lastFrame: number;\n}\n\nexport class Md2ParseError extends Error {}\n\nexport class Md2Loader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<Md2Model> {\n const bytes = await this.vfs.readFile(path);\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return parseMd2(copy.buffer);\n }\n}\n\nfunction readCString(view: DataView, offset: number, maxLength: number): string {\n const chars: number[] = [];\n for (let i = 0; i < maxLength; i += 1) {\n const code = view.getUint8(offset + i);\n if (code === 0) break;\n chars.push(code);\n }\n return String.fromCharCode(...chars);\n}\n\nfunction validateSection(buffer: ArrayBuffer, offset: number, length: number, label: string): void {\n if (length === 0) return;\n if (offset < HEADER_SIZE || offset + length > buffer.byteLength) {\n throw new Md2ParseError(`${label} section is out of bounds`);\n }\n}\n\nfunction parseHeader(buffer: ArrayBuffer): Md2Header {\n if (buffer.byteLength < HEADER_SIZE) {\n throw new Md2ParseError('MD2 buffer too small to contain header');\n }\n\n const view = new DataView(buffer);\n const ident = view.getInt32(0, true);\n const version = view.getInt32(4, true);\n\n if (ident !== MD2_MAGIC) {\n throw new Md2ParseError(`Invalid MD2 ident: ${ident}`);\n }\n if (version !== MD2_VERSION) {\n throw new Md2ParseError(`Unsupported MD2 version: ${version}`);\n }\n\n const header: Md2Header = {\n ident,\n version,\n skinWidth: view.getInt32(8, true),\n skinHeight: view.getInt32(12, true),\n frameSize: view.getInt32(16, true),\n numSkins: view.getInt32(20, true),\n numVertices: view.getInt32(24, true),\n numTexCoords: view.getInt32(28, true),\n numTriangles: view.getInt32(32, true),\n numGlCommands: view.getInt32(36, true),\n numFrames: view.getInt32(40, true),\n offsetSkins: view.getInt32(44, true),\n offsetTexCoords: view.getInt32(48, true),\n offsetTriangles: view.getInt32(52, true),\n offsetFrames: view.getInt32(56, true),\n offsetGlCommands: view.getInt32(60, true),\n offsetEnd: view.getInt32(64, true),\n };\n\n const expectedFrameSize = 40 + header.numVertices * 4;\n if (header.frameSize !== expectedFrameSize) {\n throw new Md2ParseError(`Unexpected frame size ${header.frameSize}, expected ${expectedFrameSize}`);\n }\n\n if (header.offsetEnd > buffer.byteLength) {\n throw new Md2ParseError('MD2 offset_end exceeds buffer length');\n }\n\n return header;\n}\n\nfunction parseSkins(buffer: ArrayBuffer, header: Md2Header): Md2Skin[] {\n const size = header.numSkins * 64;\n validateSection(buffer, header.offsetSkins, size, 'skins');\n const view = new DataView(buffer, header.offsetSkins, size);\n const skins: Md2Skin[] = [];\n for (let i = 0; i < header.numSkins; i += 1) {\n skins.push({ name: readCString(view, i * 64, 64) });\n }\n return skins;\n}\n\nfunction parseTexCoords(buffer: ArrayBuffer, header: Md2Header): Md2TexCoord[] {\n const size = header.numTexCoords * 4;\n validateSection(buffer, header.offsetTexCoords, size, 'texcoords');\n const view = new DataView(buffer, header.offsetTexCoords, size);\n const texCoords: Md2TexCoord[] = [];\n for (let i = 0; i < header.numTexCoords; i += 1) {\n const base = i * 4;\n texCoords.push({ s: view.getInt16(base, true), t: view.getInt16(base + 2, true) });\n }\n return texCoords;\n}\n\nfunction parseTriangles(buffer: ArrayBuffer, header: Md2Header): Md2Triangle[] {\n const size = header.numTriangles * 12;\n validateSection(buffer, header.offsetTriangles, size, 'triangles');\n const view = new DataView(buffer, header.offsetTriangles, size);\n const triangles: Md2Triangle[] = [];\n\n for (let i = 0; i < header.numTriangles; i += 1) {\n const base = i * 12;\n const vertexIndices: [number, number, number] = [\n view.getUint16(base, true),\n view.getUint16(base + 2, true),\n view.getUint16(base + 4, true),\n ];\n const texCoordIndices: [number, number, number] = [\n view.getUint16(base + 6, true),\n view.getUint16(base + 8, true),\n view.getUint16(base + 10, true),\n ];\n\n if (vertexIndices.some((v) => v >= header.numVertices) || texCoordIndices.some((t) => t >= header.numTexCoords)) {\n throw new Md2ParseError('Triangle references out of range vertex or texcoord');\n }\n\n triangles.push({ vertexIndices, texCoordIndices });\n }\n\n return triangles;\n}\n\nfunction parseFrames(buffer: ArrayBuffer, header: Md2Header): Md2Frame[] {\n const size = header.numFrames * header.frameSize;\n validateSection(buffer, header.offsetFrames, size, 'frames');\n const frames: Md2Frame[] = [];\n\n for (let i = 0; i < header.numFrames; i += 1) {\n const base = header.offsetFrames + i * header.frameSize;\n const view = new DataView(buffer, base, header.frameSize);\n const scale: Vec3 = { x: view.getFloat32(0, true), y: view.getFloat32(4, true), z: view.getFloat32(8, true) };\n const translate: Vec3 = {\n x: view.getFloat32(12, true),\n y: view.getFloat32(16, true),\n z: view.getFloat32(20, true),\n };\n const name = readCString(view, 24, 16);\n const vertices: Md2Vertex[] = [];\n\n for (let v = 0; v < header.numVertices; v += 1) {\n const offset = 40 + v * 4;\n const position: Vec3 = {\n x: view.getUint8(offset) * scale.x + translate.x,\n y: view.getUint8(offset + 1) * scale.y + translate.y,\n z: view.getUint8(offset + 2) * scale.z + translate.z,\n };\n const normalIndex = view.getUint8(offset + 3);\n const normal = MD2_NORMALS[normalIndex];\n if (!normal) {\n throw new Md2ParseError(`Invalid normal index ${normalIndex} in frame ${name}`);\n }\n vertices.push({ position, normalIndex, normal });\n }\n\n frames.push({ name, vertices });\n }\n\n return frames;\n}\n\nfunction parseGlCommands(buffer: ArrayBuffer, header: Md2Header): Md2GlCommand[] {\n const size = header.numGlCommands * 4;\n validateSection(buffer, header.offsetGlCommands, size, 'gl commands');\n if (size === 0) {\n return [];\n }\n const view = new DataView(buffer, header.offsetGlCommands, size);\n const commands: Md2GlCommand[] = [];\n let cursor = 0;\n\n while (true) {\n if (cursor + 4 > size) {\n throw new Md2ParseError('GL command list ended unexpectedly');\n }\n const count = view.getInt32(cursor, true);\n cursor += 4;\n if (count === 0) break;\n const vertexCount = Math.abs(count);\n const vertices: Md2GlCommandVertex[] = [];\n const bytesNeeded = vertexCount * 12;\n if (cursor + bytesNeeded > size) {\n throw new Md2ParseError('GL command vertex block exceeds buffer');\n }\n for (let i = 0; i < vertexCount; i += 1) {\n const s = view.getFloat32(cursor, true);\n const t = view.getFloat32(cursor + 4, true);\n const vertexIndex = view.getInt32(cursor + 8, true);\n cursor += 12;\n if (vertexIndex < 0 || vertexIndex >= header.numVertices) {\n throw new Md2ParseError('GL command references invalid vertex index');\n }\n vertices.push({ s, t, vertexIndex });\n }\n commands.push({ mode: count > 0 ? 'strip' : 'fan', vertices });\n }\n\n if (cursor !== size) {\n throw new Md2ParseError('GL command list did not consume expected data');\n }\n\n return commands;\n}\n\nexport function parseMd2(buffer: ArrayBuffer): Md2Model {\n const header = parseHeader(buffer);\n const skins = parseSkins(buffer, header);\n const texCoords = parseTexCoords(buffer, header);\n const triangles = parseTriangles(buffer, header);\n const frames = parseFrames(buffer, header);\n const glCommands = parseGlCommands(buffer, header);\n\n return { header, skins, texCoords, triangles, frames, glCommands };\n}\n\nexport function groupMd2Animations(frames: readonly Md2Frame[]): Md2Animation[] {\n const animations: Md2Animation[] = [];\n let index = 0;\n while (index < frames.length) {\n const name = frames[index].name;\n const base = name.replace(/\\d+$/, '') || name;\n let end = index;\n while (end + 1 < frames.length) {\n const nextBase = frames[end + 1].name.replace(/\\d+$/, '') || frames[end + 1].name;\n if (nextBase !== base) break;\n end += 1;\n }\n animations.push({ name: base, firstFrame: index, lastFrame: end });\n index = end + 1;\n }\n return animations;\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { VirtualFileSystem } from './vfs.js';\n\nconst MD3_IDENT = 860898377; // 'IDP3'\nconst MD3_VERSION = 15;\n\nexport interface Md3Header {\n readonly ident: number;\n readonly version: number;\n readonly name: string;\n readonly flags: number;\n readonly numFrames: number;\n readonly numTags: number;\n readonly numSurfaces: number;\n readonly numSkins: number;\n readonly ofsFrames: number;\n readonly ofsTags: number;\n readonly ofsSurfaces: number;\n readonly ofsEnd: number;\n}\n\nexport interface Md3Frame {\n readonly minBounds: Vec3;\n readonly maxBounds: Vec3;\n readonly localOrigin: Vec3;\n readonly radius: number;\n readonly name: string;\n}\n\nexport interface Md3Tag {\n readonly name: string;\n readonly origin: Vec3;\n readonly axis: readonly [Vec3, Vec3, Vec3];\n}\n\nexport interface Md3Triangle {\n readonly indices: readonly [number, number, number];\n}\n\nexport interface Md3Shader {\n readonly name: string;\n readonly shaderIndex: number;\n}\n\nexport interface Md3TexCoord {\n readonly s: number;\n readonly t: number;\n}\n\nexport interface Md3Vertex {\n readonly position: Vec3;\n readonly normal: Vec3;\n readonly latLng: number;\n}\n\nexport interface Md3Surface {\n readonly name: string;\n readonly flags: number;\n readonly numFrames: number;\n readonly shaders: readonly Md3Shader[];\n readonly triangles: readonly Md3Triangle[];\n readonly texCoords: readonly Md3TexCoord[];\n readonly vertices: readonly (readonly Md3Vertex[])[];\n}\n\nexport interface Md3Model {\n readonly header: Md3Header;\n readonly frames: readonly Md3Frame[];\n readonly tags: readonly Md3Tag[][];\n readonly surfaces: readonly Md3Surface[];\n}\n\nexport class Md3ParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'Md3ParseError';\n }\n}\n\nfunction readString(view: DataView, offset: number, length: number): string {\n const bytes = new Uint8Array(view.buffer, view.byteOffset + offset, length);\n const decoded = new TextDecoder('utf-8').decode(bytes);\n return decoded.replace(/\\0.*$/, '').trim();\n}\n\nfunction decodeLatLngNormal(latLng: number): Vec3 {\n const lat = ((latLng >> 8) & 0xff) * (2 * Math.PI / 255);\n const lng = (latLng & 0xff) * (2 * Math.PI / 255);\n const sinLng = Math.sin(lng);\n return {\n x: Math.cos(lat) * sinLng,\n y: Math.sin(lat) * sinLng,\n z: Math.cos(lng),\n };\n}\n\nfunction validateOffset(name: string, offset: number, size: number, bufferLength: number): void {\n if (offset < 0 || offset + size > bufferLength) {\n throw new Md3ParseError(`${name} exceeds buffer bounds`);\n }\n}\n\nfunction parseHeader(view: DataView): Md3Header {\n const ident = view.getInt32(0, true);\n if (ident !== MD3_IDENT) {\n throw new Md3ParseError(`Invalid MD3 ident: ${ident}`);\n }\n const version = view.getInt32(4, true);\n if (version !== MD3_VERSION) {\n throw new Md3ParseError(`Unsupported MD3 version: ${version}`);\n }\n\n const name = readString(view, 8, 64);\n const flags = view.getInt32(72, true);\n const numFrames = view.getInt32(76, true);\n const numTags = view.getInt32(80, true);\n const numSurfaces = view.getInt32(84, true);\n const numSkins = view.getInt32(88, true);\n const ofsFrames = view.getInt32(92, true);\n const ofsTags = view.getInt32(96, true);\n const ofsSurfaces = view.getInt32(100, true);\n const ofsEnd = view.getInt32(104, true);\n\n if (numFrames <= 0 || numSurfaces < 0 || numTags < 0) {\n throw new Md3ParseError('Invalid MD3 counts');\n }\n\n return {\n ident,\n version,\n name,\n flags,\n numFrames,\n numTags,\n numSurfaces,\n numSkins,\n ofsFrames,\n ofsTags,\n ofsSurfaces,\n ofsEnd,\n };\n}\n\nfunction parseFrames(view: DataView, header: Md3Header): Md3Frame[] {\n const frames: Md3Frame[] = [];\n const frameSize = 56;\n validateOffset('Frames', header.ofsFrames, header.numFrames * frameSize, view.byteLength);\n\n for (let i = 0; i < header.numFrames; i += 1) {\n const base = header.ofsFrames + i * frameSize;\n frames.push({\n minBounds: {\n x: view.getFloat32(base, true),\n y: view.getFloat32(base + 4, true),\n z: view.getFloat32(base + 8, true),\n },\n maxBounds: {\n x: view.getFloat32(base + 12, true),\n y: view.getFloat32(base + 16, true),\n z: view.getFloat32(base + 20, true),\n },\n localOrigin: {\n x: view.getFloat32(base + 24, true),\n y: view.getFloat32(base + 28, true),\n z: view.getFloat32(base + 32, true),\n },\n radius: view.getFloat32(base + 36, true),\n name: readString(view, base + 40, 16),\n });\n }\n\n return frames;\n}\n\nfunction parseTags(view: DataView, header: Md3Header): Md3Tag[][] {\n const tags: Md3Tag[][] = [];\n const tagSize = 112;\n const totalSize = header.numFrames * header.numTags * tagSize;\n validateOffset('Tags', header.ofsTags, totalSize, view.byteLength);\n\n for (let frame = 0; frame < header.numFrames; frame += 1) {\n const frameTags: Md3Tag[] = [];\n for (let tagIndex = 0; tagIndex < header.numTags; tagIndex += 1) {\n const base = header.ofsTags + (frame * header.numTags + tagIndex) * tagSize;\n const originOffset = base + 64;\n const axisOffset = originOffset + 12;\n frameTags.push({\n name: readString(view, base, 64),\n origin: {\n x: view.getFloat32(originOffset, true),\n y: view.getFloat32(originOffset + 4, true),\n z: view.getFloat32(originOffset + 8, true),\n },\n axis: [\n {\n x: view.getFloat32(axisOffset, true),\n y: view.getFloat32(axisOffset + 4, true),\n z: view.getFloat32(axisOffset + 8, true),\n },\n {\n x: view.getFloat32(axisOffset + 12, true),\n y: view.getFloat32(axisOffset + 16, true),\n z: view.getFloat32(axisOffset + 20, true),\n },\n {\n x: view.getFloat32(axisOffset + 24, true),\n y: view.getFloat32(axisOffset + 28, true),\n z: view.getFloat32(axisOffset + 32, true),\n },\n ],\n });\n }\n tags.push(frameTags);\n }\n\n return tags;\n}\n\nfunction parseSurface(view: DataView, offset: number): { surface: Md3Surface; nextOffset: number } {\n const ident = view.getInt32(offset, true);\n if (ident !== MD3_IDENT) {\n throw new Md3ParseError(`Invalid surface ident at ${offset}: ${ident}`);\n }\n\n const name = readString(view, offset + 4, 64);\n const flags = view.getInt32(offset + 68, true);\n const numFrames = view.getInt32(offset + 72, true);\n const numShaders = view.getInt32(offset + 76, true);\n const numVerts = view.getInt32(offset + 80, true);\n const numTriangles = view.getInt32(offset + 84, true);\n const ofsTriangles = view.getInt32(offset + 88, true);\n const ofsShaders = view.getInt32(offset + 92, true);\n const ofsSt = view.getInt32(offset + 96, true);\n const ofsXyzNormals = view.getInt32(offset + 100, true);\n const ofsEnd = view.getInt32(offset + 104, true);\n\n if (numFrames <= 0 || numVerts <= 0 || numTriangles <= 0) {\n throw new Md3ParseError(`Invalid surface counts for ${name}`);\n }\n\n const surfaceSize = ofsEnd;\n validateOffset(`Surface ${name}`, offset, surfaceSize, view.byteLength);\n\n const triangles: Md3Triangle[] = [];\n const triangleStart = offset + ofsTriangles;\n for (let i = 0; i < numTriangles; i += 1) {\n const base = triangleStart + i * 12;\n triangles.push({\n indices: [view.getInt32(base, true), view.getInt32(base + 4, true), view.getInt32(base + 8, true)],\n });\n }\n\n const shaders: Md3Shader[] = [];\n const shaderStart = offset + ofsShaders;\n for (let i = 0; i < numShaders; i += 1) {\n const base = shaderStart + i * 68;\n shaders.push({ name: readString(view, base, 64), shaderIndex: view.getInt32(base + 64, true) });\n }\n\n const texCoords: Md3TexCoord[] = [];\n const stStart = offset + ofsSt;\n for (let i = 0; i < numVerts; i += 1) {\n const base = stStart + i * 8;\n texCoords.push({ s: view.getFloat32(base, true), t: view.getFloat32(base + 4, true) });\n }\n\n const vertices: Md3Vertex[][] = [];\n const xyzStart = offset + ofsXyzNormals;\n for (let frame = 0; frame < numFrames; frame += 1) {\n const frameVertices: Md3Vertex[] = [];\n for (let i = 0; i < numVerts; i += 1) {\n const base = xyzStart + (frame * numVerts + i) * 8;\n const x = view.getInt16(base, true) / 64;\n const y = view.getInt16(base + 2, true) / 64;\n const z = view.getInt16(base + 4, true) / 64;\n const latLng = view.getUint16(base + 6, true);\n frameVertices.push({ position: { x, y, z }, latLng, normal: decodeLatLngNormal(latLng) });\n }\n vertices.push(frameVertices);\n }\n\n return {\n surface: { name, flags, numFrames, shaders, triangles, texCoords, vertices },\n nextOffset: offset + ofsEnd,\n };\n}\n\nexport function parseMd3(buffer: ArrayBufferLike): Md3Model {\n if (buffer.byteLength < 108) {\n throw new Md3ParseError('MD3 buffer too small for header');\n }\n\n const view = new DataView(buffer);\n const header = parseHeader(view);\n validateOffset('MD3 end', header.ofsEnd, 0, buffer.byteLength);\n\n const frames = parseFrames(view, header);\n const tags = parseTags(view, header);\n\n const surfaces: Md3Surface[] = [];\n let surfaceOffset = header.ofsSurfaces;\n for (let i = 0; i < header.numSurfaces; i += 1) {\n const { surface, nextOffset } = parseSurface(view, surfaceOffset);\n surfaces.push(surface);\n surfaceOffset = nextOffset;\n }\n\n if (surfaceOffset !== header.ofsEnd) {\n throw new Md3ParseError('Surface parsing did not reach ofsEnd');\n }\n\n return { header, frames, tags, surfaces };\n}\n\nexport class Md3Loader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<Md3Model> {\n const data = await this.vfs.readFile(path);\n return parseMd3(data.slice().buffer);\n }\n}\n","import { VirtualFileSystem } from './vfs.js';\n\nconst IDSPRITEHEADER = 0x49445332; // 'IDS2'\nconst SPRITE_VERSION = 2;\nconst MAX_SKINNAME = 64;\nconst HEADER_SIZE = 12;\n\nexport interface SpriteFrame {\n readonly width: number;\n readonly height: number;\n readonly originX: number;\n readonly originY: number;\n readonly name: string;\n}\n\nexport interface SpriteModel {\n readonly ident: number;\n readonly version: number;\n readonly numFrames: number;\n readonly frames: readonly SpriteFrame[];\n}\n\nexport class SpriteParseError extends Error {}\n\nfunction readCString(view: DataView, offset: number, maxLength: number): string {\n const chars: number[] = [];\n for (let i = 0; i < maxLength; i += 1) {\n const code = view.getUint8(offset + i);\n if (code === 0) break;\n chars.push(code);\n }\n return String.fromCharCode(...chars);\n}\n\nexport function parseSprite(buffer: ArrayBuffer): SpriteModel {\n if (buffer.byteLength < HEADER_SIZE) {\n throw new SpriteParseError('Sprite buffer too small to contain header');\n }\n\n const view = new DataView(buffer);\n const ident = view.getInt32(0, true);\n const version = view.getInt32(4, true);\n const numFrames = view.getInt32(8, true);\n\n if (ident !== IDSPRITEHEADER) {\n throw new SpriteParseError(`Invalid Sprite ident: ${ident}`);\n }\n if (version !== SPRITE_VERSION) {\n throw new SpriteParseError(`Unsupported Sprite version: ${version}`);\n }\n\n const frames: SpriteFrame[] = [];\n const frameSize = 16 + MAX_SKINNAME; // 4 * 4 bytes + 64 bytes = 80 bytes\n let offset = HEADER_SIZE;\n\n for (let i = 0; i < numFrames; i += 1) {\n if (offset + frameSize > buffer.byteLength) {\n throw new SpriteParseError('Sprite frame data exceeds buffer length');\n }\n\n const width = view.getInt32(offset, true);\n const height = view.getInt32(offset + 4, true);\n const originX = view.getInt32(offset + 8, true);\n const originY = view.getInt32(offset + 12, true);\n const name = readCString(view, offset + 16, MAX_SKINNAME);\n\n frames.push({\n width,\n height,\n originX,\n originY,\n name,\n });\n\n offset += frameSize;\n }\n\n return {\n ident,\n version,\n numFrames,\n frames,\n };\n}\n\nexport class SpriteLoader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<SpriteModel> {\n const bytes = await this.vfs.readFile(path);\n // Copy the buffer to ensure it's an ArrayBuffer and not a view\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return parseSprite(copy.buffer);\n }\n}\n","export interface FrameBlend {\n readonly frame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface AnimationSequence {\n readonly name: string;\n readonly start: number;\n readonly end: number;\n readonly fps: number;\n readonly loop?: boolean;\n}\n\nexport interface AnimationState {\n readonly sequence: AnimationSequence;\n readonly time: number;\n}\n\nexport function advanceAnimation(state: AnimationState, deltaSeconds: number): AnimationState {\n const duration = (state.sequence.end - state.sequence.start + 1) / state.sequence.fps;\n const loop = state.sequence.loop !== false;\n let time = state.time + deltaSeconds;\n\n if (loop) {\n time = ((time % duration) + duration) % duration;\n } else if (time > duration) {\n time = duration;\n }\n\n return { ...state, time: Math.max(0, Math.min(time, duration)) };\n}\n\nexport function computeFrameBlend(state: AnimationState): FrameBlend {\n const totalFrames = state.sequence.end - state.sequence.start + 1;\n const frameDuration = 1 / state.sequence.fps;\n const loop = state.sequence.loop !== false;\n const framePosition = state.time / frameDuration;\n\n if (!loop && framePosition >= totalFrames) {\n return { frame: state.sequence.end, nextFrame: state.sequence.end, lerp: 0 };\n }\n\n const normalizedPosition = loop ? framePosition % totalFrames : Math.min(framePosition, totalFrames - 1);\n const baseFrame = Math.floor(normalizedPosition);\n const frame = state.sequence.start + baseFrame;\n const nextFrame = baseFrame + 1 >= totalFrames ? (loop ? state.sequence.start : state.sequence.end) : frame + 1;\n const lerp = !loop && baseFrame >= totalFrames - 1 ? 0 : normalizedPosition - baseFrame;\n return { frame, nextFrame, lerp };\n}\n\nexport function createAnimationState(sequence: AnimationSequence): AnimationState {\n return { sequence, time: 0 };\n}\n\nexport function interpolateVec3(\n a: { x: number; y: number; z: number },\n b: { x: number; y: number; z: number },\n t: number,\n): { x: number; y: number; z: number } {\n return {\n x: a.x + (b.x - a.x) * t,\n y: a.y + (b.y - a.y) * t,\n z: a.z + (b.z - a.z) * t,\n };\n}\n","export interface WalTexture {\n readonly name: string;\n readonly width: number;\n readonly height: number;\n readonly mipmaps: readonly WalMipmap[];\n readonly animName: string;\n readonly flags: number;\n readonly contents: number;\n readonly value: number;\n}\n\nexport interface WalMipmap {\n readonly level: number;\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\nexport class WalParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WalParseError';\n }\n}\n\nexport function parseWal(buffer: ArrayBuffer): WalTexture {\n if (buffer.byteLength < 100) {\n throw new WalParseError('WAL buffer too small');\n }\n\n const view = new DataView(buffer);\n const nameBytes = new Uint8Array(buffer, 0, 32);\n const name = new TextDecoder('utf-8').decode(nameBytes).replace(/\\0.*$/, '').trim();\n const width = view.getInt32(32, true);\n const height = view.getInt32(36, true);\n const offsets = [view.getInt32(40, true), view.getInt32(44, true), view.getInt32(48, true), view.getInt32(52, true)];\n const animNameBytes = new Uint8Array(buffer, 56, 32);\n const animName = new TextDecoder('utf-8').decode(animNameBytes).replace(/\\0.*$/, '').trim();\n const flags = view.getInt32(88, true);\n const contents = view.getInt32(92, true);\n const value = view.getInt32(96, true);\n\n if (width <= 0 || height <= 0) {\n throw new WalParseError('Invalid WAL dimensions');\n }\n\n const mipmaps: WalMipmap[] = [];\n let currentWidth = width;\n let currentHeight = height;\n\n for (let level = 0; level < offsets.length; level += 1) {\n const offset = offsets[level];\n const expectedSize = Math.max(1, (currentWidth * currentHeight) | 0);\n if (offset <= 0 || offset + expectedSize > buffer.byteLength) {\n throw new WalParseError(`Invalid WAL mip offset for level ${level}`);\n }\n const data = new Uint8Array(buffer, offset, expectedSize);\n mipmaps.push({ level, width: currentWidth, height: currentHeight, data });\n currentWidth = Math.max(1, currentWidth >> 1);\n currentHeight = Math.max(1, currentHeight >> 1);\n }\n\n return { name, width, height, mipmaps, animName, flags, contents, value };\n}\n","export interface PcxImage {\n readonly width: number;\n readonly height: number;\n readonly bitsPerPixel: number;\n readonly pixels: Uint8Array;\n readonly palette: Uint8Array;\n}\n\nexport class PcxParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'PcxParseError';\n }\n}\n\nexport function parsePcx(buffer: ArrayBuffer): PcxImage {\n if (buffer.byteLength < 128) {\n throw new PcxParseError('PCX buffer too small for header');\n }\n\n const view = new DataView(buffer);\n const manufacturer = view.getUint8(0);\n const encoding = view.getUint8(2);\n const bitsPerPixel = view.getUint8(3);\n const xMin = view.getUint16(4, true);\n const yMin = view.getUint16(6, true);\n const xMax = view.getUint16(8, true);\n const yMax = view.getUint16(10, true);\n\n if (manufacturer !== 0x0a || encoding !== 1) {\n throw new PcxParseError('Unsupported PCX encoding');\n }\n if (bitsPerPixel !== 8) {\n throw new PcxParseError('Only 8bpp PCX files are supported');\n }\n\n const width = xMax - xMin + 1;\n const height = yMax - yMin + 1;\n const bytesPerLine = view.getUint16(66, true);\n\n const paletteMarkerOffset = buffer.byteLength - 769;\n if (paletteMarkerOffset < 128 || new DataView(buffer, paletteMarkerOffset, 1).getUint8(0) !== 0x0c) {\n throw new PcxParseError('Missing PCX palette');\n }\n\n const palette = new Uint8Array(buffer, paletteMarkerOffset + 1, 768);\n const encoded = new Uint8Array(buffer, 128, paletteMarkerOffset - 128);\n const pixels = new Uint8Array(width * height);\n\n let srcIndex = 0;\n let dstIndex = 0;\n\n for (let y = 0; y < height; y += 1) {\n let written = 0;\n while (written < bytesPerLine && srcIndex < encoded.length) {\n let count = 1;\n let value = encoded[srcIndex++]!;\n\n if ((value & 0xc0) === 0xc0) {\n count = value & 0x3f;\n if (srcIndex >= encoded.length) {\n throw new PcxParseError('Unexpected end of PCX RLE data');\n }\n value = encoded[srcIndex++]!;\n }\n\n for (let i = 0; i < count && written < bytesPerLine; i += 1) {\n if (written < width) {\n pixels[dstIndex++] = value;\n }\n written += 1;\n }\n }\n }\n\n return { width, height, bitsPerPixel, pixels, palette };\n}\n\nexport function pcxToRgba(image: PcxImage): Uint8Array {\n const rgba = new Uint8Array(image.width * image.height * 4);\n for (let i = 0; i < image.pixels.length; i += 1) {\n const colorIndex = image.pixels[i]!;\n const paletteIndex = colorIndex * 3;\n const rgbaIndex = i * 4;\n rgba[rgbaIndex] = image.palette[paletteIndex]!;\n rgba[rgbaIndex + 1] = image.palette[paletteIndex + 1]!;\n rgba[rgbaIndex + 2] = image.palette[paletteIndex + 2]!;\n rgba[rgbaIndex + 3] = colorIndex === 255 ? 0 : 255;\n }\n return rgba;\n}\n","import { LruCache } from './cache.js';\nimport { pcxToRgba, type PcxImage } from './pcx.js';\nimport { parseWal, type WalTexture } from './wal.js';\n\nexport interface PreparedTexture {\n readonly width: number;\n readonly height: number;\n readonly levels: readonly TextureLevel[];\n readonly source: 'pcx' | 'wal';\n}\n\nexport interface TextureLevel {\n readonly level: number;\n readonly width: number;\n readonly height: number;\n readonly rgba: Uint8Array;\n}\n\nexport interface TextureCacheOptions {\n readonly capacity?: number;\n}\n\nexport class TextureCache {\n private readonly cache: LruCache<PreparedTexture>;\n\n constructor(options: TextureCacheOptions = {}) {\n this.cache = new LruCache<PreparedTexture>(options.capacity ?? 128);\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n get(key: string): PreparedTexture | undefined {\n return this.cache.get(key.toLowerCase());\n }\n\n set(key: string, texture: PreparedTexture): void {\n this.cache.set(key.toLowerCase(), texture);\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\nexport function walToRgba(wal: WalTexture, palette: Uint8Array): PreparedTexture {\n const levels: TextureLevel[] = [];\n for (const mip of wal.mipmaps) {\n const rgba = new Uint8Array(mip.width * mip.height * 4);\n for (let i = 0; i < mip.data.length; i += 1) {\n const colorIndex = mip.data[i]!;\n const paletteIndex = colorIndex * 3;\n const outIndex = i * 4;\n rgba[outIndex] = palette[paletteIndex]!;\n rgba[outIndex + 1] = palette[paletteIndex + 1]!;\n rgba[outIndex + 2] = palette[paletteIndex + 2]!;\n rgba[outIndex + 3] = colorIndex === 255 ? 0 : 255;\n }\n levels.push({ level: mip.level, width: mip.width, height: mip.height, rgba });\n }\n\n return { width: wal.width, height: wal.height, levels, source: 'wal' };\n}\n\nexport function preparePcxTexture(pcx: PcxImage): PreparedTexture {\n const rgba = pcxToRgba(pcx);\n const level: TextureLevel = { level: 0, width: pcx.width, height: pcx.height, rgba };\n return { width: pcx.width, height: pcx.height, levels: [level], source: 'pcx' };\n}\n\nexport function parseWalTexture(buffer: ArrayBuffer, palette: Uint8Array): PreparedTexture {\n return walToRgba(parseWal(buffer), palette);\n}\n","export interface WavData {\n readonly sampleRate: number;\n readonly channels: number;\n readonly bitsPerSample: number;\n readonly samples: Float32Array;\n}\n\nexport class WavParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WavParseError';\n }\n}\n\nfunction readString(view: DataView, offset: number, length: number): string {\n return new TextDecoder('ascii').decode(new Uint8Array(view.buffer, view.byteOffset + offset, length));\n}\n\nexport function parseWav(buffer: ArrayBuffer): WavData {\n if (buffer.byteLength < 44) {\n throw new WavParseError('WAV buffer too small');\n }\n\n const view = new DataView(buffer);\n if (readString(view, 0, 4) !== 'RIFF' || readString(view, 8, 4) !== 'WAVE') {\n throw new WavParseError('Invalid WAV header');\n }\n\n let offset = 12;\n let fmtOffset = -1;\n let dataOffset = -1;\n let fmtSize = 0;\n let dataSize = 0;\n\n while (offset + 8 <= buffer.byteLength) {\n const chunkId = readString(view, offset, 4);\n const chunkSize = view.getUint32(offset + 4, true);\n const chunkDataOffset = offset + 8;\n\n if (chunkId === 'fmt ') {\n fmtOffset = chunkDataOffset;\n fmtSize = chunkSize;\n } else if (chunkId === 'data') {\n dataOffset = chunkDataOffset;\n dataSize = chunkSize;\n }\n\n offset = chunkDataOffset + chunkSize;\n }\n\n if (fmtOffset === -1 || dataOffset === -1) {\n throw new WavParseError('Missing fmt or data chunk');\n }\n\n const audioFormat = view.getUint16(fmtOffset, true);\n const channels = view.getUint16(fmtOffset + 2, true);\n const sampleRate = view.getUint32(fmtOffset + 4, true);\n const bitsPerSample = view.getUint16(fmtOffset + 14, true);\n\n if (audioFormat !== 1) {\n throw new WavParseError('Only PCM WAV is supported');\n }\n\n const bytesPerSample = bitsPerSample / 8;\n const frameCount = dataSize / (bytesPerSample * channels);\n const samples = new Float32Array(frameCount * channels);\n\n for (let frame = 0; frame < frameCount; frame += 1) {\n for (let ch = 0; ch < channels; ch += 1) {\n const sampleIndex = frame * channels + ch;\n const byteOffset = dataOffset + sampleIndex * bytesPerSample;\n let value = 0;\n if (bitsPerSample === 8) {\n value = view.getUint8(byteOffset);\n samples[sampleIndex] = (value - 128) / 128;\n } else if (bitsPerSample === 16) {\n value = view.getInt16(byteOffset, true);\n samples[sampleIndex] = value / 32768;\n } else if (bitsPerSample === 24) {\n const b0 = view.getUint8(byteOffset);\n const b1 = view.getUint8(byteOffset + 1);\n const b2 = view.getInt8(byteOffset + 2);\n value = b0 | (b1 << 8) | (b2 << 16);\n samples[sampleIndex] = value / 8388608;\n } else {\n throw new WavParseError(`Unsupported bitsPerSample: ${bitsPerSample}`);\n }\n }\n }\n\n return { sampleRate, channels, bitsPerSample, samples };\n}\n","import { OggVorbisDecoder } from '@wasm-audio-decoders/ogg-vorbis';\n\nexport interface OggAudio {\n readonly sampleRate: number;\n readonly channels: number;\n readonly bitDepth: number;\n readonly channelData: readonly Float32Array[];\n}\n\nexport class OggDecodeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OggDecodeError';\n }\n}\n\nexport async function decodeOgg(buffer: ArrayBuffer, decoder: OggVorbisDecoder = new OggVorbisDecoder()): Promise<OggAudio> {\n await decoder.ready;\n const result = await decoder.decode(new Uint8Array(buffer));\n\n const errors = (result as { errors?: { message: string }[] }).errors;\n if (errors && errors.length > 0) {\n throw new OggDecodeError(errors.map((err) => err.message).join('; '));\n }\n\n return {\n sampleRate: result.sampleRate,\n channels: result.channelData.length,\n bitDepth: result.bitDepth,\n channelData: result.channelData,\n };\n}\n","import { decodeOgg, type OggAudio } from './ogg.js';\nimport { parseWav } from './wav.js';\nimport { VirtualFileSystem } from './vfs.js';\nimport { LruCache } from './cache.js';\n\nexport type DecodedAudio = OggAudio;\n\nexport class AudioRegistryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AudioRegistryError';\n }\n}\n\nexport interface AudioRegistryOptions {\n readonly cacheSize?: number;\n}\n\nexport class AudioRegistry {\n private readonly cache: LruCache<DecodedAudio>;\n private readonly refCounts = new Map<string, number>();\n\n constructor(private readonly vfs: VirtualFileSystem, options: AudioRegistryOptions = {}) {\n this.cache = new LruCache<DecodedAudio>(options.cacheSize ?? 64);\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n async load(path: string): Promise<DecodedAudio> {\n const normalized = path.toLowerCase();\n const cached = this.cache.get(normalized);\n if (cached) {\n this.refCounts.set(normalized, (this.refCounts.get(normalized) ?? 0) + 1);\n return cached;\n }\n\n const data = await this.vfs.readFile(path);\n const arrayBuffer = data.slice().buffer;\n const audio = await this.decodeByExtension(path, arrayBuffer);\n this.cache.set(normalized, audio);\n this.refCounts.set(normalized, 1);\n return audio;\n }\n\n release(path: string): void {\n const normalized = path.toLowerCase();\n const count = this.refCounts.get(normalized) ?? 0;\n if (count <= 1) {\n this.cache.delete(normalized);\n this.refCounts.delete(normalized);\n } else {\n this.refCounts.set(normalized, count - 1);\n }\n }\n\n clearAll(): void {\n this.cache.clear();\n this.refCounts.clear();\n }\n\n private async decodeByExtension(path: string, buffer: ArrayBuffer): Promise<DecodedAudio> {\n const lower = path.toLowerCase();\n if (lower.endsWith('.wav')) {\n const wav = parseWav(buffer);\n const channels = wav.channels;\n const channelData: Float32Array[] = Array.from({ length: channels }, () => new Float32Array(wav.samples.length / channels));\n for (let i = 0; i < wav.samples.length; i += 1) {\n channelData[i % channels]![Math.floor(i / channels)] = wav.samples[i]!;\n }\n return { sampleRate: wav.sampleRate, channels, bitDepth: wav.bitsPerSample, channelData } satisfies OggAudio;\n }\n if (lower.endsWith('.ogg') || lower.endsWith('.oga')) {\n return decodeOgg(buffer);\n }\n throw new AudioRegistryError(`Unsupported audio format: ${path}`);\n }\n}\n","import { PakArchive, type PakDirectoryEntry, type PakValidationResult, normalizePath } from './pak.js';\n\nconst DEFAULT_DB_NAME = 'quake2ts-pak-indexes';\nconst DEFAULT_STORE_NAME = 'pak-indexes';\n\nexport interface StoredPakIndex extends PakValidationResult {\n readonly key: string;\n readonly name: string;\n readonly size: number;\n readonly persistedAt: number;\n}\n\nfunction getIndexedDb(): IDBFactory | undefined {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof window !== 'undefined' && 'indexedDB' in window) {\n return window.indexedDB;\n }\n if (typeof globalThis !== 'undefined' && 'indexedDB' in globalThis) {\n return (globalThis as unknown as { indexedDB?: IDBFactory }).indexedDB;\n }\n return undefined;\n}\n\nfunction openDatabase(dbName: string, storeName: string): Promise<IDBDatabase> {\n const idb = getIndexedDb();\n if (!idb) {\n return Promise.reject(new Error('IndexedDB is not available in this environment'));\n }\n\n return new Promise<IDBDatabase>((resolve, reject) => {\n const request = idb.open(dbName, 1);\n\n request.onupgradeneeded = () => {\n const { result } = request;\n if (!result.objectStoreNames.contains(storeName)) {\n result.createObjectStore(storeName, { keyPath: 'key' });\n }\n };\n\n request.onerror = () => reject(request.error ?? new Error('Unknown IndexedDB error'));\n request.onsuccess = () => resolve(request.result);\n });\n}\n\nfunction runTransaction<T>(\n db: IDBDatabase,\n storeName: string,\n mode: IDBTransactionMode,\n runner: (store: IDBObjectStore) => IDBRequest<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const transaction = db.transaction(storeName, mode);\n const store = transaction.objectStore(storeName);\n const request = runner(store);\n\n request.onsuccess = () => resolve(request.result as T);\n request.onerror = () => reject(request.error ?? new Error('IndexedDB transaction error'));\n });\n}\n\nfunction buildKey(name: string, checksum: number): string {\n return `${normalizePath(name)}:${checksum.toString(16)}`;\n}\n\nfunction cloneEntries(entries: readonly PakDirectoryEntry[]): PakDirectoryEntry[] {\n return entries.map((entry) => ({ ...entry }));\n}\n\nexport class PakIndexStore {\n constructor(\n private readonly dbName = DEFAULT_DB_NAME,\n private readonly storeName = DEFAULT_STORE_NAME,\n ) {}\n\n get isSupported(): boolean {\n return Boolean(getIndexedDb());\n }\n\n async persist(archive: PakArchive): Promise<StoredPakIndex | undefined> {\n if (!this.isSupported) {\n return undefined;\n }\n\n const validation = archive.validate();\n const record: StoredPakIndex = {\n ...validation,\n key: buildKey(archive.name, validation.checksum),\n name: archive.name,\n size: archive.size,\n persistedAt: Date.now(),\n entries: cloneEntries(validation.entries),\n };\n\n const db = await openDatabase(this.dbName, this.storeName);\n await runTransaction(db, this.storeName, 'readwrite', (store) => store.put(record));\n db.close();\n return record;\n }\n\n async find(name: string, checksum?: number): Promise<StoredPakIndex | undefined> {\n if (!this.isSupported) {\n return undefined;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const key = checksum !== undefined ? buildKey(name, checksum) : undefined;\n\n const record = await runTransaction(db, this.storeName, 'readonly', (store) => {\n if (key) {\n return store.get(key);\n }\n return store.getAll();\n });\n\n db.close();\n\n if (!record) {\n return undefined;\n }\n\n if (Array.isArray(record)) {\n const normalized = normalizePath(name);\n const matches = record.filter((candidate: StoredPakIndex) => normalizePath(candidate.name) === normalized);\n if (matches.length === 0) {\n return undefined;\n }\n return matches.sort((a, b) => b.persistedAt - a.persistedAt)[0];\n }\n\n return record as StoredPakIndex;\n }\n\n async remove(name: string, checksum?: number): Promise<boolean> {\n if (!this.isSupported) {\n return false;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const key = checksum !== undefined ? buildKey(name, checksum) : undefined;\n const result = await runTransaction(db, this.storeName, 'readwrite', (store) => {\n if (key) {\n return store.delete(key);\n }\n const prefix = `${normalizePath(name)}:`;\n return store.delete(IDBKeyRange.bound(prefix, `${prefix}￿`, false, true));\n });\n db.close();\n return typeof result === 'number' ? result > 0 : true;\n }\n\n async clear(): Promise<void> {\n if (!this.isSupported) {\n return;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n await runTransaction(db, this.storeName, 'readwrite', (store) => store.clear());\n db.close();\n }\n\n async list(): Promise<StoredPakIndex[]> {\n if (!this.isSupported) {\n return [];\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const result = await runTransaction(db, this.storeName, 'readonly', (store) => store.getAll());\n db.close();\n return (result as StoredPakIndex[]).sort((a, b) => b.persistedAt - a.persistedAt);\n }\n}\n","import { normalizePath } from './pak.js';\nimport { TextureCache, type PreparedTexture } from './texture.js';\nimport { AudioRegistry, type DecodedAudio } from './audio.js';\nimport { Md2Loader, type Md2Model } from './md2.js';\nimport { Md3Loader, type Md3Model } from './md3.js';\nimport { SpriteLoader, type SpriteModel } from './sprite.js';\nimport { VirtualFileSystem } from './vfs.js';\n\ntype AssetType = 'texture' | 'model' | 'sound' | 'sprite';\n\ninterface DependencyNode {\n readonly dependencies: Set<string>;\n loaded: boolean;\n}\n\nexport class AssetDependencyError extends Error {\n constructor(readonly missing: readonly string[], message?: string) {\n super(message ?? `Missing dependencies: ${missing.join(', ')}`);\n this.name = 'AssetDependencyError';\n }\n}\n\nexport class AssetDependencyTracker {\n private readonly nodes = new Map<string, DependencyNode>();\n\n register(assetKey: string, dependencies: readonly string[] = []): void {\n const node = this.nodes.get(assetKey) ?? { dependencies: new Set<string>(), loaded: false };\n dependencies.forEach((dependency) => node.dependencies.add(dependency));\n this.nodes.set(assetKey, node);\n dependencies.forEach((dependency) => {\n if (!this.nodes.has(dependency)) {\n this.nodes.set(dependency, { dependencies: new Set<string>(), loaded: false });\n }\n });\n }\n\n markLoaded(assetKey: string): void {\n const node = this.nodes.get(assetKey) ?? { dependencies: new Set<string>(), loaded: false };\n const missing = this.getMissingDependencies(assetKey, node);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${assetKey} is missing dependencies: ${missing.join(', ')}`);\n }\n node.loaded = true;\n this.nodes.set(assetKey, node);\n }\n\n markUnloaded(assetKey: string): void {\n const node = this.nodes.get(assetKey);\n if (node) {\n node.loaded = false;\n }\n }\n\n isLoaded(assetKey: string): boolean {\n return this.nodes.get(assetKey)?.loaded ?? false;\n }\n\n missingDependencies(assetKey: string): string[] {\n const node = this.nodes.get(assetKey);\n if (!node) {\n return [];\n }\n return this.getMissingDependencies(assetKey, node);\n }\n\n reset(): void {\n this.nodes.clear();\n }\n\n private getMissingDependencies(assetKey: string, node: DependencyNode): string[] {\n const missing: string[] = [];\n for (const dependency of node.dependencies) {\n if (!this.nodes.get(dependency)?.loaded) {\n missing.push(dependency);\n }\n }\n return missing;\n }\n}\n\nexport interface AssetManagerOptions {\n readonly textureCacheCapacity?: number;\n readonly audioCacheSize?: number;\n readonly dependencyTracker?: AssetDependencyTracker;\n}\n\nexport class AssetManager {\n readonly textures: TextureCache;\n readonly audio: AudioRegistry;\n readonly dependencyTracker: AssetDependencyTracker;\n private readonly md2: Md2Loader;\n private readonly md3: Md3Loader;\n private readonly sprite: SpriteLoader;\n\n constructor(private readonly vfs: VirtualFileSystem, options: AssetManagerOptions = {}) {\n this.textures = new TextureCache({ capacity: options.textureCacheCapacity ?? 128 });\n this.audio = new AudioRegistry(vfs, { cacheSize: options.audioCacheSize ?? 64 });\n this.dependencyTracker = options.dependencyTracker ?? new AssetDependencyTracker();\n this.md2 = new Md2Loader(vfs);\n this.md3 = new Md3Loader(vfs);\n this.sprite = new SpriteLoader(vfs);\n }\n\n isAssetLoaded(type: AssetType, path: string): boolean {\n return this.dependencyTracker.isLoaded(this.makeKey(type, path));\n }\n\n registerTexture(path: string, texture: PreparedTexture): void {\n this.textures.set(path, texture);\n const key = this.makeKey('texture', path);\n this.dependencyTracker.register(key);\n this.dependencyTracker.markLoaded(key);\n }\n\n async loadSound(path: string): Promise<DecodedAudio> {\n const audio = await this.audio.load(path);\n const key = this.makeKey('sound', path);\n this.dependencyTracker.register(key);\n this.dependencyTracker.markLoaded(key);\n return audio;\n }\n\n async loadMd2Model(path: string, textureDependencies: readonly string[] = []): Promise<Md2Model> {\n const modelKey = this.makeKey('model', path);\n const dependencyKeys = textureDependencies.map((dep) => this.makeKey('texture', dep));\n this.dependencyTracker.register(modelKey, dependencyKeys);\n const missing = this.dependencyTracker.missingDependencies(modelKey);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${modelKey} is missing dependencies: ${missing.join(', ')}`);\n }\n const model = await this.md2.load(path);\n this.dependencyTracker.markLoaded(modelKey);\n return model;\n }\n\n async loadMd3Model(path: string, textureDependencies: readonly string[] = []): Promise<Md3Model> {\n const modelKey = this.makeKey('model', path);\n const dependencyKeys = textureDependencies.map((dep) => this.makeKey('texture', dep));\n this.dependencyTracker.register(modelKey, dependencyKeys);\n const missing = this.dependencyTracker.missingDependencies(modelKey);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${modelKey} is missing dependencies: ${missing.join(', ')}`);\n }\n const model = await this.md3.load(path);\n this.dependencyTracker.markLoaded(modelKey);\n return model;\n }\n\n async loadSprite(path: string): Promise<SpriteModel> {\n const spriteKey = this.makeKey('sprite', path);\n this.dependencyTracker.register(spriteKey);\n const sprite = await this.sprite.load(path);\n this.dependencyTracker.markLoaded(spriteKey);\n return sprite;\n }\n\n resetForLevelChange(): void {\n this.textures.clear();\n this.audio.clearAll();\n this.dependencyTracker.reset();\n }\n\n private makeKey(type: AssetType, path: string): string {\n return `${type}:${normalizePath(path)}`;\n }\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 === ATTN_STATIC ? attenuation * 0.001 : attenuation * 0.0005;\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","export interface AudioParamLike {\n value: number;\n}\n\nexport interface AudioNodeLike {\n connect(destination: AudioNodeLike): void;\n}\n\nexport interface BiquadFilterNodeLike extends AudioNodeLike {\n frequency: AudioParamLike;\n Q: AudioParamLike;\n type: string;\n}\n\nexport interface GainNodeLike extends AudioNodeLike {\n gain: AudioParamLike;\n}\n\nexport interface DynamicsCompressorNodeLike extends AudioNodeLike {}\n\nexport interface AudioBufferLike {\n readonly duration: number;\n}\n\nexport interface AudioBufferSourceNodeLike extends AudioNodeLike {\n buffer: AudioBufferLike | null;\n loop: boolean;\n onended: (() => void) | null;\n start(when?: number, offset?: number, duration?: number): void;\n stop(when?: number): void;\n}\n\nexport interface PannerNodeLike extends AudioNodeLike {\n positionX: AudioParamLike;\n positionY: AudioParamLike;\n positionZ: AudioParamLike;\n refDistance?: number;\n maxDistance?: number;\n rolloffFactor?: number;\n distanceModel?: string;\n}\n\nexport interface AudioDestinationNodeLike extends AudioNodeLike {}\n\nexport interface AudioContextLike {\n readonly destination: AudioDestinationNodeLike;\n readonly currentTime: number;\n state: 'suspended' | 'running' | 'closed';\n resume(): Promise<void>;\n suspend(): Promise<void>;\n createGain(): GainNodeLike;\n createDynamicsCompressor(): DynamicsCompressorNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n createPanner?(): PannerNodeLike;\n createBiquadFilter?(): BiquadFilterNodeLike;\n decodeAudioData?(data: ArrayBuffer): Promise<AudioBufferLike>;\n}\n\nexport type AudioContextFactory = () => AudioContextLike;\n\nexport interface AudioGraph {\n context: AudioContextLike;\n master: GainNodeLike;\n compressor: DynamicsCompressorNodeLike;\n filter?: BiquadFilterNodeLike;\n}\n\nexport class AudioContextController {\n private context?: AudioContextLike;\n\n constructor(private readonly factory: AudioContextFactory) {}\n\n getContext(): AudioContextLike {\n if (!this.context) {\n this.context = this.factory();\n }\n return this.context;\n }\n\n async resume(): Promise<void> {\n const ctx = this.getContext();\n if (ctx.state === 'suspended') {\n await ctx.resume();\n }\n }\n\n getState(): AudioContextLike['state'] {\n return this.context?.state ?? 'suspended';\n }\n}\n\nexport function createAudioGraph(controller: AudioContextController): AudioGraph {\n const context = controller.getContext();\n const master = context.createGain();\n master.gain.value = 1;\n const compressor = context.createDynamicsCompressor();\n const filter = context.createBiquadFilter?.();\n if (filter) {\n filter.type = 'lowpass';\n filter.frequency.value = 20000;\n filter.Q.value = 0.707;\n master.connect(filter);\n filter.connect(compressor);\n } else {\n master.connect(compressor);\n }\n compressor.connect(context.destination);\n return { context, master, compressor, filter };\n}\n","import { ConfigStringRegistry } from '../configstrings.js';\nimport type { AudioBufferLike } from './context.js';\n\nexport class SoundRegistry {\n private readonly buffers = new Map<number, AudioBufferLike>();\n\n constructor(private readonly configStrings = new ConfigStringRegistry()) {}\n\n registerName(name: string): number {\n return this.configStrings.soundIndex(name);\n }\n\n register(name: string, buffer: AudioBufferLike): number {\n const index = this.registerName(name);\n this.buffers.set(index, buffer);\n return index;\n }\n\n find(name: string): number | undefined {\n return this.configStrings.findSoundIndex(name);\n }\n\n get(index: number): AudioBufferLike | undefined {\n return this.buffers.get(index);\n }\n\n has(index: number): boolean {\n return this.buffers.has(index);\n }\n}\n","import { normalizePath } from '../assets/pak.js';\nimport type { VirtualFileSystem } from '../assets/vfs.js';\nimport type { AudioBufferLike, AudioContextLike } from './context.js';\nimport { AudioContextController } from './context.js';\nimport { SoundRegistry } from './registry.js';\n\nexport interface SoundPrecacheOptions {\n vfs: Pick<VirtualFileSystem, 'readFile' | 'stat'>;\n registry: SoundRegistry;\n context: AudioContextController;\n decodeAudio?: (context: AudioContextLike, data: ArrayBuffer) => Promise<AudioBufferLike>;\n soundRoot?: string;\n}\n\nexport interface SoundPrecacheReport {\n loaded: string[];\n skipped: string[];\n missing: string[];\n errors: Record<string, Error>;\n}\n\nexport class SoundPrecache {\n private readonly vfs: SoundPrecacheOptions['vfs'];\n private readonly registry: SoundRegistry;\n private readonly contextController: AudioContextController;\n private readonly decodeAudio: NonNullable<SoundPrecacheOptions['decodeAudio']>;\n private readonly soundRoot: string;\n\n constructor(options: SoundPrecacheOptions) {\n this.vfs = options.vfs;\n this.registry = options.registry;\n this.contextController = options.context;\n this.soundRoot = options.soundRoot ?? 'sound/';\n this.decodeAudio =\n options.decodeAudio ??\n ((context: AudioContextLike, data: ArrayBuffer) => {\n if (!context.decodeAudioData) {\n throw new Error('decodeAudioData is not available on the provided audio context');\n }\n return context.decodeAudioData(data);\n });\n }\n\n async precache(paths: string[]): Promise<SoundPrecacheReport> {\n const unique = [...new Set(paths.map((p) => this.normalize(p)))];\n const report: SoundPrecacheReport = { loaded: [], skipped: [], missing: [], errors: {} };\n const context = this.contextController.getContext();\n\n for (const path of unique) {\n try {\n const existingIndex = this.registry.find(path);\n if (existingIndex !== undefined && this.registry.has(existingIndex)) {\n report.skipped.push(path);\n continue;\n }\n\n const stat = this.vfs.stat(path);\n if (!stat) {\n report.missing.push(path);\n continue;\n }\n\n const bytes = await this.vfs.readFile(path);\n const copy = bytes.slice().buffer;\n const buffer = await this.decodeAudio(context, copy);\n this.registry.register(path, buffer);\n report.loaded.push(path);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n report.errors[path] = err;\n }\n }\n\n return report;\n }\n\n private normalize(path: string): string {\n const normalized = normalizePath(path.replace(/^\\//, ''));\n if (normalized.startsWith(this.soundRoot)) {\n return normalized;\n }\n return normalizePath(`${this.soundRoot}${normalized}`);\n }\n}\n","import { MAX_SOUND_CHANNELS, SoundChannel } from './constants.js';\n\nconst CHANNEL_MASK = 0x07;\n\nexport const baseChannel = (entchannel: number): number => entchannel & CHANNEL_MASK;\n\nexport interface ChannelState {\n entnum: number;\n entchannel: number;\n endTimeMs: number;\n isPlayer: boolean;\n active: boolean;\n}\n\nexport interface ChannelPickContext {\n readonly nowMs: number;\n readonly playerEntity?: number;\n}\n\nexport function createInitialChannels(playerEntity?: number): ChannelState[] {\n return Array.from({ length: MAX_SOUND_CHANNELS }, () => ({\n entnum: 0,\n entchannel: SoundChannel.Auto,\n endTimeMs: 0,\n isPlayer: false,\n active: false,\n } satisfies ChannelState)).map((channel) => ({ ...channel, isPlayer: channel.entnum === playerEntity }));\n}\n\nexport function pickChannel(\n channels: ChannelState[],\n entnum: number,\n entchannel: number,\n context: ChannelPickContext,\n): number | undefined {\n if (entchannel < 0) {\n throw new Error('pickChannel: entchannel must be non-negative');\n }\n\n const normalizedEntchannel = baseChannel(entchannel);\n let firstToDie = -1;\n let lifeLeft = Number.POSITIVE_INFINITY;\n\n for (let i = 0; i < channels.length; i += 1) {\n const channel = channels[i];\n const channelBase = baseChannel(channel.entchannel);\n\n if (\n normalizedEntchannel !== SoundChannel.Auto &&\n channel.entnum === entnum &&\n channelBase === normalizedEntchannel\n ) {\n firstToDie = i;\n break;\n }\n\n if (channel.active && channel.entnum === context.playerEntity && entnum !== context.playerEntity) {\n continue;\n }\n\n const remainingLife = channel.endTimeMs - context.nowMs;\n if (firstToDie === -1 || remainingLife < lifeLeft) {\n lifeLeft = remainingLife;\n firstToDie = i;\n }\n }\n\n return firstToDie === -1 ? undefined : firstToDie;\n}\n","import { Vec3, dotVec3, lengthVec3, normalizeVec3, subtractVec3 } from '@quake2ts/shared';\nimport { SOUND_FULLVOLUME, attenuationToDistanceMultiplier } from './constants.js';\n\nexport interface ListenerState {\n origin: Vec3;\n right: Vec3;\n mono?: boolean;\n playerEntity?: number;\n}\n\nexport interface SpatializationResult {\n left: number;\n right: number;\n distanceComponent: number;\n}\n\nexport function spatializeOrigin(\n origin: Vec3,\n listener: ListenerState,\n masterVolume: number,\n attenuation: number,\n isListenerSound: boolean,\n): SpatializationResult {\n if (isListenerSound) {\n return { left: masterVolume, right: masterVolume, distanceComponent: 0 };\n }\n\n const sourceVec = subtractVec3(origin, listener.origin);\n const distance = lengthVec3(sourceVec);\n const normalized = normalizeVec3(sourceVec);\n let dist = distance - SOUND_FULLVOLUME;\n if (dist < 0) dist = 0;\n dist *= attenuationToDistanceMultiplier(attenuation);\n\n const dot = dotVec3(listener.right, normalized);\n const mono = listener.mono ?? false;\n const rscale = mono || attenuation === 0 ? 1 : 0.5 * (1 + dot);\n const lscale = mono || attenuation === 0 ? 1 : 0.5 * (1 - dot);\n\n const right = Math.max(0, Math.floor(masterVolume * (1 - dist) * rscale));\n const left = Math.max(0, Math.floor(masterVolume * (1 - dist) * lscale));\n\n return { left, right, distanceComponent: dist };\n}\n","import { ZERO_VEC3, type Vec3 } from '@quake2ts/shared';\nimport {\n ATTN_NONE,\n SOUND_FULLVOLUME,\n attenuationToDistanceMultiplier,\n calculateMaxAudibleDistance,\n SoundChannel,\n} from './constants.js';\nimport {\n AudioContextController,\n createAudioGraph,\n type AudioContextLike,\n type AudioBufferSourceNodeLike,\n type AudioGraph,\n type BiquadFilterNodeLike,\n type GainNodeLike,\n type PannerNodeLike,\n} from './context.js';\nimport { SoundRegistry } from './registry.js';\nimport { baseChannel, createInitialChannels, pickChannel, type ChannelState } from './channels.js';\nimport { spatializeOrigin, type ListenerState } from './spatialization.js';\n\nexport interface SoundRequest {\n entity: number;\n channel: number;\n soundIndex: number;\n volume: number;\n attenuation: number;\n origin?: Vec3;\n timeOffsetMs?: number;\n looping?: boolean;\n}\n\nexport interface AudioSystemOptions {\n context: AudioContextController;\n registry: SoundRegistry;\n playerEntity?: number;\n listener?: ListenerState;\n sfxVolume?: number;\n masterVolume?: number;\n resolveOcclusion?: OcclusionResolver;\n}\n\ninterface ActiveSound {\n channelIndex: number;\n entnum: number;\n entchannel: number;\n endTimeMs: number;\n source: AudioBufferSourceNodeLike;\n panner: PannerNodeLike;\n gain: GainNodeLike;\n baseGain: number;\n origin: Vec3;\n attenuation: number;\n occlusion?: OcclusionState;\n}\n\ninterface OcclusionState {\n scale: number;\n lowpassHz?: number;\n filter?: BiquadFilterNodeLike;\n}\n\nexport interface OcclusionResult {\n gainScale?: number;\n lowpassHz?: number;\n}\n\nexport type OcclusionResolver = (\n listener: ListenerState,\n source: Vec3,\n attenuation: number,\n) => OcclusionResult | undefined;\n\nexport interface AudioDiagnostics {\n activeChannels: number;\n masterVolume: number;\n sfxVolume: number;\n channels: ChannelState[];\n activeSounds: Array<{\n entnum: number;\n entchannel: number;\n channelIndex: number;\n origin: Vec3;\n gain: number;\n baseGain: number;\n attenuation: number;\n maxDistance?: number;\n distanceModel?: string;\n occlusion?: { scale: number; lowpassHz?: number };\n }>;\n}\n\nexport class AudioSystem {\n private readonly channels: ChannelState[];\n private readonly registry: SoundRegistry;\n private readonly contextController: AudioContextController;\n private readonly graph: AudioGraph;\n private readonly playerEntity?: number;\n private readonly activeSources = new Map<number, ActiveSound>();\n private readonly resolveOcclusion?: OcclusionResolver;\n private listener: ListenerState;\n private sfxVolume: number;\n private masterVolume: number;\n\n constructor(options: AudioSystemOptions) {\n this.contextController = options.context;\n this.registry = options.registry;\n this.playerEntity = options.playerEntity;\n this.channels = createInitialChannels(options.playerEntity);\n this.listener = options.listener ?? { origin: ZERO_VEC3, right: { x: 1, y: 0, z: 0 } };\n this.sfxVolume = options.sfxVolume ?? 1;\n this.masterVolume = options.masterVolume ?? 1;\n this.resolveOcclusion = options.resolveOcclusion;\n this.graph = createAudioGraph(this.contextController);\n this.graph.master.gain.value = this.masterVolume;\n }\n\n setListener(listener: ListenerState): void {\n this.listener = listener;\n }\n\n setMasterVolume(volume: number): void {\n this.masterVolume = volume;\n this.graph.master.gain.value = volume;\n }\n\n setSfxVolume(volume: number): void {\n this.sfxVolume = volume;\n }\n\n async ensureRunning(): Promise<void> {\n await this.contextController.resume();\n }\n\n play(request: SoundRequest): ActiveSound | undefined {\n const buffer = this.registry.get(request.soundIndex);\n if (!buffer) return undefined;\n\n const ctx = this.graph.context;\n const nowMs = ctx.currentTime * 1000;\n const channelIndex = pickChannel(this.channels, request.entity, request.channel, {\n nowMs,\n playerEntity: this.playerEntity,\n });\n\n if (channelIndex === undefined) return undefined;\n\n const existing = this.activeSources.get(channelIndex);\n if (existing) {\n existing.source.onended = null;\n existing.source.stop();\n this.activeSources.delete(channelIndex);\n }\n\n const source = ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = request.looping ?? false;\n\n const origin = request.origin ?? this.listener.origin;\n const gain = ctx.createGain();\n const panner = this.createPanner(ctx, request.attenuation);\n const occlusion = this.resolveOcclusion?.(this.listener, origin, request.attenuation);\n const occlusionScale = clamp01(occlusion?.gainScale ?? 1);\n const occlusionFilter = this.resolveOcclusion\n ? this.createOcclusionFilter(ctx, occlusion?.lowpassHz ?? 20000)\n : undefined;\n this.applyOriginToPanner(panner, origin);\n const isListenerSound = request.entity === this.playerEntity;\n const spatial = spatializeOrigin(origin, this.listener, request.volume, request.attenuation, isListenerSound);\n\n const attenuationScale = request.volume === 0 ? 0 : Math.max(spatial.left, spatial.right) / Math.max(1, request.volume);\n const gainValue = attenuationScale * (request.volume / 255) * this.masterVolume * this.sfxVolume;\n gain.gain.value = gainValue * occlusionScale;\n\n const startTimeSec = ctx.currentTime + (request.timeOffsetMs ?? 0) / 1000;\n const endTimeMs = (request.looping ? Number.POSITIVE_INFINITY : buffer.duration * 1000) + startTimeSec * 1000;\n\n source.connect(panner);\n if (occlusionFilter) {\n panner.connect(occlusionFilter);\n occlusionFilter.connect(gain);\n } else {\n panner.connect(gain);\n }\n gain.connect(this.graph.master);\n\n source.start(startTimeSec);\n source.onended = () => {\n this.channels[channelIndex].active = false;\n this.activeSources.delete(channelIndex);\n };\n\n const active: ActiveSound = {\n channelIndex,\n entnum: request.entity,\n entchannel: baseChannel(request.channel),\n endTimeMs,\n source,\n panner,\n gain,\n baseGain: gainValue,\n origin,\n attenuation: request.attenuation,\n occlusion: occlusionFilter\n ? { scale: occlusionScale, lowpassHz: occlusion?.lowpassHz, filter: occlusionFilter }\n : occlusion\n ? { scale: occlusionScale, lowpassHz: occlusion.lowpassHz }\n : undefined,\n };\n\n this.channels[channelIndex] = {\n entnum: request.entity,\n entchannel: baseChannel(request.channel),\n endTimeMs,\n isPlayer: request.entity === this.playerEntity,\n active: true,\n };\n\n this.activeSources.set(channelIndex, active);\n return active;\n }\n\n stop(channelIndex: number): void {\n const active = this.activeSources.get(channelIndex);\n if (!active) return;\n active.source.stop();\n this.channels[channelIndex].active = false;\n this.activeSources.delete(channelIndex);\n }\n\n stopEntitySounds(entnum: number): void {\n for (const [index, active] of [...this.activeSources.entries()]) {\n if (active.entnum !== entnum) continue;\n active.source.stop();\n this.channels[index].active = false;\n this.activeSources.delete(index);\n }\n }\n\n updateEntityPosition(entnum: number, origin: Vec3): void {\n for (const active of this.activeSources.values()) {\n if (active.entnum !== entnum) continue;\n this.applyOriginToPanner(active.panner, origin);\n active.origin = origin;\n if (this.resolveOcclusion) {\n const occlusion = this.resolveOcclusion(this.listener, origin, active.attenuation);\n this.applyOcclusion(active, occlusion);\n }\n }\n }\n\n positionedSound(origin: Vec3, soundIndex: number, volume: number, attenuation: number): ActiveSound | undefined {\n return this.play({\n entity: 0,\n channel: SoundChannel.Auto,\n soundIndex,\n volume,\n attenuation,\n origin,\n });\n }\n\n ambientSound(origin: Vec3, soundIndex: number, volume: number): ActiveSound | undefined {\n return this.play({\n entity: 0,\n channel: SoundChannel.Auto,\n soundIndex,\n volume,\n attenuation: ATTN_NONE,\n origin,\n looping: true,\n });\n }\n\n getChannelState(index: number): ChannelState | undefined {\n return this.channels[index];\n }\n\n getDiagnostics(): AudioDiagnostics {\n return {\n activeChannels: this.activeSources.size,\n masterVolume: this.masterVolume,\n sfxVolume: this.sfxVolume,\n channels: [...this.channels],\n activeSounds: [...this.activeSources.values()].map((sound) => ({\n entnum: sound.entnum,\n entchannel: sound.entchannel,\n channelIndex: sound.channelIndex,\n origin: sound.origin,\n gain: sound.gain.gain.value,\n baseGain: sound.baseGain,\n attenuation: sound.attenuation,\n maxDistance: sound.panner.maxDistance,\n distanceModel: sound.panner.distanceModel,\n occlusion: sound.occlusion ? { scale: sound.occlusion.scale, lowpassHz: sound.occlusion.lowpassHz } : undefined,\n })),\n };\n }\n\n setUnderwater(enabled: boolean, cutoffHz = 400): void {\n const filter = this.graph.filter;\n if (!filter) return;\n filter.type = 'lowpass';\n filter.Q.value = 0.707;\n filter.frequency.value = enabled ? cutoffHz : 20000;\n }\n\n private createPanner(context: AudioContextLike, attenuation: number): PannerNodeLike {\n const panner = context.createPanner\n ? context.createPanner()\n : Object.assign(context.createGain(), {\n positionX: { value: this.listener.origin.x },\n positionY: { value: this.listener.origin.y },\n positionZ: { value: this.listener.origin.z },\n } satisfies Partial<PannerNodeLike>);\n\n return this.configurePanner(panner, attenuation);\n }\n\n private configurePanner(panner: PannerNodeLike, attenuation: number): PannerNodeLike {\n const distMult = attenuationToDistanceMultiplier(attenuation);\n panner.refDistance = SOUND_FULLVOLUME;\n panner.maxDistance = calculateMaxAudibleDistance(attenuation);\n panner.rolloffFactor = distMult;\n panner.distanceModel = attenuation === 0 ? 'linear' : 'inverse';\n panner.positionX.value = this.listener.origin.x;\n panner.positionY.value = this.listener.origin.y;\n panner.positionZ.value = this.listener.origin.z;\n return panner;\n }\n\n private applyOriginToPanner(panner: PannerNodeLike, origin: Vec3): void {\n panner.positionX.value = origin.x;\n panner.positionY.value = origin.y;\n panner.positionZ.value = origin.z;\n }\n\n private createOcclusionFilter(context: AudioContextLike, cutoffHz: number): BiquadFilterNodeLike | undefined {\n if (!context.createBiquadFilter) return undefined;\n const filter = context.createBiquadFilter();\n filter.type = 'lowpass';\n filter.Q.value = 0.707;\n filter.frequency.value = clamp(cutoffHz, 10, 20000);\n return filter;\n }\n\n private applyOcclusion(active: ActiveSound, occlusion?: OcclusionResult): void {\n const scale = clamp01(occlusion?.gainScale ?? 1);\n active.gain.gain.value = active.baseGain * scale;\n if (active.occlusion?.filter) {\n const cutoff = occlusion?.lowpassHz ?? 20000;\n active.occlusion.filter.frequency.value = clamp(cutoff, 10, 20000);\n }\n if (active.occlusion) {\n active.occlusion.scale = scale;\n active.occlusion.lowpassHz = occlusion?.lowpassHz;\n } else if (occlusion) {\n active.occlusion = { scale, lowpassHz: occlusion.lowpassHz };\n }\n }\n}\n\nconst clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));\nconst clamp01 = (value: number): number => clamp(value, 0, 1);\n\n","export interface AudioElementLike {\n src: string;\n loop: boolean;\n volume: number;\n currentTime: number;\n paused: boolean;\n ended: boolean;\n play(): Promise<void>;\n pause(): void;\n load(): void;\n}\n\nexport type AudioElementFactory = () => AudioElementLike;\nexport type MusicSourceResolver = (path: string) => Promise<string>;\n\nexport interface MusicSystemOptions {\n createElement: AudioElementFactory;\n resolveSource?: MusicSourceResolver;\n volume?: number;\n}\n\nexport interface MusicState {\n readonly track?: string;\n readonly paused: boolean;\n readonly playing: boolean;\n readonly volume: number;\n}\n\nexport class MusicSystem {\n private readonly createElement: AudioElementFactory;\n private readonly resolveSource: MusicSourceResolver;\n private element?: AudioElementLike;\n private track?: string;\n private volume: number;\n\n constructor(options: MusicSystemOptions) {\n this.createElement = options.createElement;\n this.resolveSource = options.resolveSource ?? (async (path) => path);\n this.volume = options.volume ?? 1;\n }\n\n async play(track: string, { loop = true, restart = false }: { loop?: boolean; restart?: boolean } = {}): Promise<void> {\n if (this.track === track && this.element) {\n this.element.loop = loop;\n this.element.volume = this.volume;\n if (restart) {\n this.element.currentTime = 0;\n }\n if (this.element.paused || restart) {\n await this.element.play();\n }\n return;\n }\n\n const src = await this.resolveSource(track);\n const element = this.createElement();\n element.src = src;\n element.loop = loop;\n element.volume = this.volume;\n element.currentTime = 0;\n element.load();\n await element.play();\n\n this.element = element;\n this.track = track;\n }\n\n pause(): void {\n if (!this.element || this.element.paused) return;\n this.element.pause();\n }\n\n async resume(): Promise<void> {\n if (!this.element || !this.element.paused) return;\n await this.element.play();\n }\n\n stop(): void {\n if (!this.element) return;\n this.element.pause();\n this.element.currentTime = 0;\n this.element = undefined;\n this.track = undefined;\n }\n\n setVolume(volume: number): void {\n this.volume = volume;\n if (this.element) {\n this.element.volume = volume;\n }\n }\n\n getState(): MusicState {\n const playing = Boolean(this.element && !this.element.paused && !this.element.ended);\n const paused = Boolean(this.element?.paused);\n return { track: this.track, paused, playing, volume: this.volume };\n }\n}\n","import { type Vec3 } from '@quake2ts/shared';\nimport { MusicSystem } from './music.js';\nimport { SoundRegistry } from './registry.js';\nimport { AudioSystem, type SoundRequest } from './system.js';\n\nexport interface AudioApiOptions {\n registry: SoundRegistry;\n system: AudioSystem;\n music?: MusicSystem;\n}\n\nexport class AudioApi {\n private readonly registry: SoundRegistry;\n private readonly system: AudioSystem;\n private readonly music?: MusicSystem;\n\n constructor(options: AudioApiOptions) {\n this.registry = options.registry;\n this.system = options.system;\n this.music = options.music;\n }\n\n soundindex(name: string): number {\n return this.registry.registerName(name);\n }\n\n sound(entity: number, channel: number, soundindex: number, volume: number, attenuation: number, timeofs: number): void {\n this.system.play({\n entity,\n channel,\n soundIndex: soundindex,\n volume,\n attenuation,\n timeOffsetMs: timeofs,\n });\n }\n\n positioned_sound(origin: Vec3, soundindex: number, volume: number, attenuation: number): void {\n this.system.positionedSound(origin, soundindex, volume, attenuation);\n }\n\n loop_sound(entity: number, channel: number, soundindex: number, volume: number, attenuation: number): void {\n this.system.play({\n entity,\n channel,\n soundIndex: soundindex,\n volume,\n attenuation,\n looping: true,\n });\n }\n\n stop_entity_sounds(entnum: number): void {\n this.system.stopEntitySounds(entnum);\n }\n\n set_listener(listener: Parameters<AudioSystem['setListener']>[0]): void {\n this.system.setListener(listener);\n }\n\n play_music(track: string, loop = true): Promise<void> {\n if (!this.music) {\n return Promise.resolve();\n }\n return this.music.play(track, { loop });\n }\n\n pause_music(): void {\n this.music?.pause();\n }\n\n resume_music(): Promise<void> {\n return this.music?.resume() ?? Promise.resolve();\n }\n\n stop_music(): void {\n this.music?.stop();\n }\n\n set_music_volume(volume: number): void {\n this.music?.setVolume(volume);\n }\n\n play_ambient(origin: Vec3, soundindex: number, volume: number): void {\n this.system.ambientSound(origin, soundindex, volume);\n }\n\n play_channel(request: Omit<SoundRequest, 'looping'>): void {\n this.system.play({ ...request });\n }\n}\n","export interface WebGLContextInitOptions {\n /**\n * Options passed to `canvas.getContext`. Defaults to antialias enabled to match the rerelease renderer's smoothing.\n */\n readonly contextAttributes?: WebGLContextAttributes;\n /**\n * Extensions that must be present. Missing entries throw during construction so callers can fall back early.\n */\n readonly requiredExtensions?: readonly string[];\n /**\n * Extensions that will be queried if available. Missing optional extensions are ignored.\n */\n readonly optionalExtensions?: readonly string[];\n}\n\nexport interface WebGLContextState {\n readonly gl: WebGL2RenderingContext;\n readonly extensions: Map<string, unknown>;\n /**\n * Returns true once a `webglcontextlost` event has been observed.\n */\n isLost(): boolean;\n /**\n * Registers a callback that fires on context loss. Returns an unsubscribe function.\n */\n onLost(callback: () => void): () => void;\n /**\n * Registers a callback that fires on context restoration. Returns an unsubscribe function.\n */\n onRestored(callback: () => void): () => void;\n /**\n * Remove event listeners and release references.\n */\n dispose(): void;\n}\n\nfunction configureDefaultGLState(gl: WebGL2RenderingContext): void {\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n gl.enable(gl.CULL_FACE);\n gl.cullFace(gl.BACK);\n gl.enable(gl.BLEND);\n gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nfunction queryExtensions(\n gl: WebGL2RenderingContext,\n required: readonly string[],\n optional: readonly string[],\n collector: Map<string, unknown>\n): void {\n for (const name of required) {\n const ext = gl.getExtension(name);\n if (!ext) {\n throw new Error(`Missing required WebGL extension: ${name}`);\n }\n collector.set(name, ext);\n }\n\n for (const name of optional) {\n const ext = gl.getExtension(name);\n if (ext) {\n collector.set(name, ext);\n }\n }\n}\n\nexport function createWebGLContext(\n canvas: HTMLCanvasElement,\n options: WebGLContextInitOptions = {}\n): WebGLContextState {\n const { contextAttributes, requiredExtensions = [], optionalExtensions = [] } = options;\n const gl = canvas.getContext('webgl2', contextAttributes ?? { antialias: true });\n if (!gl) {\n throw new Error('WebGL2 not supported or failed to initialize');\n }\n\n configureDefaultGLState(gl);\n\n const extensions = new Map<string, unknown>();\n queryExtensions(gl, requiredExtensions, optionalExtensions, extensions);\n\n let lost = false;\n const lostCallbacks = new Set<() => void>();\n const restoreCallbacks = new Set<() => void>();\n\n const lostListener = (event: Event): void => {\n lost = true;\n event.preventDefault();\n for (const callback of lostCallbacks) {\n callback();\n }\n };\n const restoreListener = (): void => {\n lost = false;\n for (const callback of restoreCallbacks) {\n callback();\n }\n };\n\n canvas.addEventListener('webglcontextlost', lostListener);\n canvas.addEventListener('webglcontextrestored', restoreListener);\n\n return {\n gl,\n extensions,\n isLost: () => lost,\n onLost(callback: () => void) {\n lostCallbacks.add(callback);\n return () => lostCallbacks.delete(callback);\n },\n onRestored(callback: () => void) {\n restoreCallbacks.add(callback);\n return () => restoreCallbacks.delete(callback);\n },\n dispose() {\n canvas.removeEventListener('webglcontextlost', lostListener);\n canvas.removeEventListener('webglcontextrestored', restoreListener);\n lostCallbacks.clear();\n restoreCallbacks.clear();\n extensions.clear();\n },\n };\n}\n","export interface ShaderSources {\n readonly vertex: string;\n readonly fragment: string;\n}\n\nfunction compileShader(gl: WebGL2RenderingContext, type: GLenum, source: string): WebGLShader {\n const shader = gl.createShader(type);\n if (!shader) {\n throw new Error('Failed to allocate shader');\n }\n\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n const ok = gl.getShaderParameter(shader, gl.COMPILE_STATUS) as boolean;\n if (!ok) {\n const log = gl.getShaderInfoLog(shader) ?? 'Unknown shader compile failure';\n gl.deleteShader(shader);\n throw new Error(log);\n }\n\n return shader;\n}\n\nfunction linkProgram(\n gl: WebGL2RenderingContext,\n vertexShader: WebGLShader,\n fragmentShader: WebGLShader,\n attributeLocations?: Record<string, number>\n): WebGLProgram {\n const program = gl.createProgram();\n if (!program) {\n throw new Error('Failed to allocate shader program');\n }\n\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n\n if (attributeLocations) {\n for (const [name, location] of Object.entries(attributeLocations)) {\n gl.bindAttribLocation(program, location, name);\n }\n }\n\n gl.linkProgram(program);\n const ok = gl.getProgramParameter(program, gl.LINK_STATUS) as boolean;\n if (!ok) {\n const log = gl.getProgramInfoLog(program) ?? 'Unknown shader link failure';\n gl.deleteProgram(program);\n throw new Error(log);\n }\n\n return program;\n}\n\nexport class ShaderProgram {\n readonly gl: WebGL2RenderingContext;\n readonly program: WebGLProgram;\n private readonly uniformLocations = new Map<string, WebGLUniformLocation | null>();\n private readonly attributeLocations = new Map<string, number>();\n\n private constructor(gl: WebGL2RenderingContext, program: WebGLProgram) {\n this.gl = gl;\n this.program = program;\n }\n\n static create(\n gl: WebGL2RenderingContext,\n sources: ShaderSources,\n attributeLocations?: Record<string, number>\n ): ShaderProgram {\n const vertexShader = compileShader(gl, gl.VERTEX_SHADER, sources.vertex);\n const fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, sources.fragment);\n try {\n const program = linkProgram(gl, vertexShader, fragmentShader, attributeLocations);\n return new ShaderProgram(gl, program);\n } finally {\n gl.deleteShader(vertexShader);\n gl.deleteShader(fragmentShader);\n }\n }\n\n use(): void {\n this.gl.useProgram(this.program);\n }\n\n getUniformLocation(name: string): WebGLUniformLocation | null {\n if (!this.uniformLocations.has(name)) {\n const location = this.gl.getUniformLocation(this.program, name);\n this.uniformLocations.set(name, location);\n }\n\n return this.uniformLocations.get(name) ?? null;\n }\n\n getAttributeLocation(name: string): number {\n if (!this.attributeLocations.has(name)) {\n const location = this.gl.getAttribLocation(this.program, name);\n this.attributeLocations.set(name, location);\n }\n\n return this.attributeLocations.get(name) ?? -1;\n }\n\n dispose(): void {\n this.gl.deleteProgram(this.program);\n this.uniformLocations.clear();\n this.attributeLocations.clear();\n }\n}\n\nexport function createProgramFromSources(\n gl: WebGL2RenderingContext,\n sources: ShaderSources,\n attributeLocations?: Record<string, number>\n): ShaderProgram {\n return ShaderProgram.create(gl, sources, attributeLocations);\n}\n","export type BufferUsage = GLenum;\n\nexport interface VertexAttributeLayout {\n readonly index: number;\n readonly size: number;\n readonly type: GLenum;\n readonly normalized?: boolean;\n readonly stride?: number;\n readonly offset?: number;\n readonly divisor?: number;\n}\n\nexport class VertexBuffer {\n readonly gl: WebGL2RenderingContext;\n readonly buffer: WebGLBuffer;\n readonly target: GLenum;\n\n constructor(gl: WebGL2RenderingContext, usage: BufferUsage = gl.STATIC_DRAW, target?: GLenum) {\n this.gl = gl;\n this.target = target ?? gl.ARRAY_BUFFER;\n const buffer = gl.createBuffer();\n if (!buffer) {\n throw new Error('Failed to allocate buffer');\n }\n this.buffer = buffer;\n gl.bindBuffer(this.target, this.buffer);\n gl.bufferData(this.target, 0, usage);\n }\n\n bind(): void {\n this.gl.bindBuffer(this.target, this.buffer);\n }\n\n upload(data: BufferSource, usage: BufferUsage = this.gl.STATIC_DRAW): void {\n this.bind();\n this.gl.bufferData(this.target, data, usage);\n }\n\n update(data: BufferSource, offset = 0): void {\n this.bind();\n this.gl.bufferSubData(this.target, offset, data);\n }\n\n dispose(): void {\n this.gl.deleteBuffer(this.buffer);\n }\n}\n\nexport class IndexBuffer extends VertexBuffer {\n constructor(gl: WebGL2RenderingContext, usage: BufferUsage = gl.STATIC_DRAW) {\n super(gl, usage, gl.ELEMENT_ARRAY_BUFFER);\n }\n}\n\nexport class VertexArray {\n readonly gl: WebGL2RenderingContext;\n readonly vao: WebGLVertexArrayObject;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n const vao = gl.createVertexArray();\n if (!vao) {\n throw new Error('Failed to allocate vertex array object');\n }\n this.vao = vao;\n }\n\n bind(): void {\n this.gl.bindVertexArray(this.vao);\n }\n\n configureAttributes(layouts: readonly VertexAttributeLayout[], buffer?: VertexBuffer): void {\n this.bind();\n if (buffer) {\n buffer.bind();\n }\n\n for (const layout of layouts) {\n this.gl.enableVertexAttribArray(layout.index);\n this.gl.vertexAttribPointer(\n layout.index,\n layout.size,\n layout.type,\n layout.normalized ?? false,\n layout.stride ?? 0,\n layout.offset ?? 0\n );\n if (layout.divisor !== undefined) {\n this.gl.vertexAttribDivisor(layout.index, layout.divisor);\n }\n }\n }\n\n dispose(): void {\n this.gl.deleteVertexArray(this.vao);\n }\n}\n\nexport interface TextureParameters {\n readonly wrapS?: GLenum;\n readonly wrapT?: GLenum;\n readonly minFilter?: GLenum;\n readonly magFilter?: GLenum;\n}\n\nexport class Texture2D {\n readonly gl: WebGL2RenderingContext;\n readonly texture: WebGLTexture;\n readonly target: GLenum;\n\n width = 0;\n height = 0;\n\n constructor(gl: WebGL2RenderingContext, target: GLenum = gl.TEXTURE_2D) {\n this.gl = gl;\n this.target = target;\n const texture = gl.createTexture();\n if (!texture) {\n throw new Error('Failed to allocate texture');\n }\n this.texture = texture;\n }\n\n bind(unit = 0): void {\n this.gl.activeTexture(this.gl.TEXTURE0 + unit);\n this.gl.bindTexture(this.target, this.texture);\n }\n\n setParameters(params: TextureParameters): void {\n this.bind();\n if (params.wrapS !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_S, params.wrapS);\n }\n if (params.wrapT !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_T, params.wrapT);\n }\n if (params.minFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MIN_FILTER, params.minFilter);\n }\n if (params.magFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MAG_FILTER, params.magFilter);\n }\n }\n\n upload(width: number, height: number, data: TexImageSource | ArrayBufferView | null) {\n this.width = width;\n this.height = height;\n this.uploadImage(0, this.gl.RGBA, width, height, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, data);\n }\n\n uploadImage(\n level: number,\n internalFormat: GLenum,\n width: number,\n height: number,\n border: number,\n format: GLenum,\n type: GLenum,\n data: TexImageSource | ArrayBufferView | null\n ): void {\n this.bind();\n this.gl.texImage2D(this.target, level, internalFormat, width, height, border, format, type, data as any);\n }\n\n dispose(): void {\n this.gl.deleteTexture(this.texture);\n }\n}\n\nexport class TextureCubeMap {\n readonly gl: WebGL2RenderingContext;\n readonly texture: WebGLTexture;\n readonly target: GLenum;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.target = gl.TEXTURE_CUBE_MAP;\n const texture = gl.createTexture();\n if (!texture) {\n throw new Error('Failed to allocate cubemap texture');\n }\n this.texture = texture;\n }\n\n bind(unit = 0): void {\n this.gl.activeTexture(this.gl.TEXTURE0 + unit);\n this.gl.bindTexture(this.target, this.texture);\n }\n\n setParameters(params: TextureParameters): void {\n this.bind();\n if (params.wrapS !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_S, params.wrapS);\n }\n if (params.wrapT !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_T, params.wrapT);\n }\n if (params.minFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MIN_FILTER, params.minFilter);\n }\n if (params.magFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MAG_FILTER, params.magFilter);\n }\n }\n\n uploadFace(\n faceTarget: GLenum,\n level: number,\n internalFormat: GLenum,\n width: number,\n height: number,\n border: number,\n format: GLenum,\n type: GLenum,\n data: ArrayBufferView | null\n ): void {\n this.bind();\n this.gl.texImage2D(faceTarget, level, internalFormat, width, height, border, format, type, data);\n }\n\n dispose(): void {\n this.gl.deleteTexture(this.texture);\n }\n}\n\nexport class Framebuffer {\n readonly gl: WebGL2RenderingContext;\n readonly framebuffer: WebGLFramebuffer;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n const framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error('Failed to allocate framebuffer');\n }\n this.framebuffer = framebuffer;\n }\n\n bind(target: GLenum = this.gl.FRAMEBUFFER): void {\n this.gl.bindFramebuffer(target, this.framebuffer);\n }\n\n attachTexture2D(attachment: GLenum, texture: Texture2D, level = 0): void {\n this.bind();\n this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, attachment, texture.target, texture.texture, level);\n }\n\n dispose(): void {\n this.gl.deleteFramebuffer(this.framebuffer);\n }\n}\n","import { SURF_NONE, type SurfaceFlag } from '@quake2ts/shared';\nimport {\n IndexBuffer,\n Texture2D,\n VertexArray,\n VertexBuffer,\n type VertexAttributeLayout,\n} from './resources.js';\nimport { BspMap, createFaceLightmap } from '../assets/bsp.js';\n\nexport interface BspLightmapData {\n readonly width: number;\n readonly height: number;\n readonly samples: Uint8Array;\n}\n\nexport interface BspSurfaceInput {\n readonly vertices: ReadonlyArray<number> | Float32Array;\n readonly textureCoords: ReadonlyArray<number> | Float32Array;\n readonly lightmapCoords?: ReadonlyArray<number> | Float32Array;\n readonly indices?: ReadonlyArray<number> | Uint16Array | Uint32Array;\n readonly texture: string;\n readonly surfaceFlags?: SurfaceFlag;\n readonly lightmap?: BspLightmapData;\n}\n\nexport interface LightmapPlacement {\n readonly atlasIndex: number;\n readonly offset: [number, number];\n readonly scale: [number, number];\n}\n\nexport interface BspSurfaceGeometry {\n readonly vao: VertexArray;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly indexCount: number;\n readonly vertexCount: number;\n readonly texture: string;\n readonly surfaceFlags: SurfaceFlag;\n readonly lightmap?: LightmapPlacement;\n // CPU copies retained for deterministic tests and debugging.\n readonly vertexData: Float32Array;\n readonly indexData: Uint16Array;\n}\n\nexport interface LightmapAtlas {\n readonly texture: Texture2D;\n readonly width: number;\n readonly height: number;\n readonly pixels: Uint8Array;\n}\n\nexport interface BspBuildOptions {\n readonly atlasSize?: number;\n readonly lightmapPadding?: number;\n}\n\nexport interface BspGeometryBuildResult {\n readonly surfaces: readonly BspSurfaceGeometry[];\n readonly lightmaps: readonly LightmapAtlas[];\n}\n\nconst FLOAT_BYTES = 4;\nconst STRIDE = 7 * FLOAT_BYTES;\n\nexport const BSP_VERTEX_LAYOUT: readonly VertexAttributeLayout[] = [\n // Position\n { index: 0, size: 3, type: 0x1406, stride: STRIDE, offset: 0 },\n // Diffuse UV\n { index: 1, size: 2, type: 0x1406, stride: STRIDE, offset: 3 * FLOAT_BYTES },\n // Lightmap UV\n { index: 2, size: 2, type: 0x1406, stride: STRIDE, offset: 5 * FLOAT_BYTES },\n];\n\ninterface LightmapPlacementInfo {\n readonly atlasIndex: number;\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\ninterface AtlasBuilder {\n readonly width: number;\n readonly height: number;\n readonly padding: number;\n readonly data: Uint8Array;\n cursorX: number;\n cursorY: number;\n rowHeight: number;\n}\n\nfunction createAtlasBuilder(size: number, padding: number): AtlasBuilder {\n const channelCount = 4; // We upload as RGBA for compatibility.\n return {\n width: size,\n height: size,\n padding,\n data: new Uint8Array(size * size * channelCount),\n cursorX: 0,\n cursorY: 0,\n rowHeight: 0,\n };\n}\n\nfunction detectChannels(lightmap: BspLightmapData): number {\n const pixels = lightmap.width * lightmap.height;\n if (pixels === 0) {\n throw new Error('Invalid lightmap with zero area');\n }\n const channels = lightmap.samples.byteLength / pixels;\n if (!Number.isInteger(channels) || channels < 3 || channels > 4) {\n throw new Error('Unsupported lightmap channel count');\n }\n return channels;\n}\n\nfunction writeLightmapIntoAtlas(\n atlas: AtlasBuilder,\n placement: LightmapPlacementInfo,\n lightmap: BspLightmapData\n): void {\n const channels = detectChannels(lightmap);\n const stride = atlas.width * 4;\n const startX = placement.x + atlas.padding;\n const startY = placement.y + atlas.padding;\n let srcIndex = 0;\n\n for (let y = 0; y < lightmap.height; y++) {\n const destRow = (startY + y) * stride + startX * 4;\n for (let x = 0; x < lightmap.width; x++) {\n const dest = destRow + x * 4;\n atlas.data[dest] = lightmap.samples[srcIndex];\n atlas.data[dest + 1] = lightmap.samples[srcIndex + 1];\n atlas.data[dest + 2] = lightmap.samples[srcIndex + 2];\n atlas.data[dest + 3] = channels === 4 ? lightmap.samples[srcIndex + 3] : 255;\n srcIndex += channels;\n }\n }\n}\n\nfunction placeLightmap(\n builders: AtlasBuilder[],\n lightmap: BspLightmapData,\n options: Required<BspBuildOptions>\n): { placement: LightmapPlacementInfo; atlas: AtlasBuilder } {\n const paddedWidth = lightmap.width + options.lightmapPadding * 2;\n const paddedHeight = lightmap.height + options.lightmapPadding * 2;\n if (paddedWidth > options.atlasSize || paddedHeight > options.atlasSize) {\n throw new Error('Lightmap too large for atlas');\n }\n\n for (const atlas of builders) {\n if (atlas.cursorX + paddedWidth > atlas.width) {\n atlas.cursorX = 0;\n atlas.cursorY += atlas.rowHeight + options.lightmapPadding;\n atlas.rowHeight = 0;\n }\n\n if (atlas.cursorY + paddedHeight > atlas.height) {\n continue;\n }\n\n const placement: LightmapPlacementInfo = {\n atlasIndex: builders.indexOf(atlas),\n x: atlas.cursorX,\n y: atlas.cursorY,\n width: lightmap.width,\n height: lightmap.height,\n };\n\n atlas.cursorX += paddedWidth + options.lightmapPadding;\n atlas.rowHeight = Math.max(atlas.rowHeight, paddedHeight);\n return { placement, atlas };\n }\n\n const atlas = createAtlasBuilder(options.atlasSize, options.lightmapPadding);\n builders.push(atlas);\n const placement: LightmapPlacementInfo = { atlasIndex: builders.length - 1, x: 0, y: 0, width: lightmap.width, height: lightmap.height };\n atlas.cursorX = paddedWidth + options.lightmapPadding;\n atlas.rowHeight = paddedHeight;\n return { placement, atlas };\n}\n\nfunction ensureFloat32(array: ReadonlyArray<number> | Float32Array): Float32Array {\n return array instanceof Float32Array ? array : new Float32Array(array);\n}\n\nfunction ensureIndexArray(indices: ReadonlyArray<number> | Uint16Array | Uint32Array | undefined, vertexCount: number): Uint16Array {\n if (!indices) {\n const generated = new Uint16Array(vertexCount);\n for (let i = 0; i < vertexCount; i++) {\n generated[i] = i;\n }\n return generated;\n }\n\n const converted = indices instanceof Uint16Array ? indices : new Uint16Array(indices);\n return converted;\n}\n\nfunction remapLightmapCoords(\n coords: Float32Array,\n placement: LightmapPlacement,\n): Float32Array {\n const remapped = new Float32Array(coords.length);\n for (let i = 0; i < coords.length; i += 2) {\n remapped[i] = placement.offset[0] + coords[i] * placement.scale[0];\n remapped[i + 1] = placement.offset[1] + coords[i + 1] * placement.scale[1];\n }\n return remapped;\n}\n\nfunction buildVertexData(\n surface: BspSurfaceInput,\n placement: LightmapPlacement | undefined\n): Float32Array {\n const vertices = ensureFloat32(surface.vertices);\n const texCoords = ensureFloat32(surface.textureCoords);\n const lightmapCoords = placement\n ? remapLightmapCoords(ensureFloat32(surface.lightmapCoords ?? surface.textureCoords), placement)\n : ensureFloat32(surface.lightmapCoords ?? new Float32Array(texCoords.length));\n\n const vertexCount = vertices.length / 3;\n if (texCoords.length / 2 !== vertexCount) {\n throw new Error('Texture coordinates count mismatch');\n }\n if (lightmapCoords.length / 2 !== vertexCount) {\n throw new Error('Lightmap coordinates count mismatch');\n }\n\n const interleaved = new Float32Array(vertexCount * 7);\n for (let i = 0; i < vertexCount; i++) {\n const v = i * 3;\n const t = i * 2;\n const o = i * 7;\n interleaved[o] = vertices[v];\n interleaved[o + 1] = vertices[v + 1];\n interleaved[o + 2] = vertices[v + 2];\n interleaved[o + 3] = texCoords[t];\n interleaved[o + 4] = texCoords[t + 1];\n interleaved[o + 5] = lightmapCoords[t];\n interleaved[o + 6] = lightmapCoords[t + 1];\n }\n return interleaved;\n}\n\n/**\n * Converts a parsed BSP map into a set of flat surface inputs ready for rendering.\n *\n * This function handles:\n * 1. Traversing faces and their edges to build vertex lists.\n * 2. Calculating texture coordinates (UVs) from surface normals and texture info.\n * 3. Generating triangle indices (fan triangulation) for convex polygon faces.\n * 4. Extracting and calculating lightmap data and coordinates.\n *\n * @param map The parsed BSP map structure.\n * @returns An array of surface inputs suitable for consumption by `buildBspGeometry`.\n */\nexport function createBspSurfaces(map: BspMap): BspSurfaceInput[] {\n const results: BspSurfaceInput[] = [];\n\n // Iterate over all faces using index to allow efficient lookups of parallel arrays (e.g. lightMapInfo).\n for (let faceIndex = 0; faceIndex < map.faces.length; faceIndex++) {\n const face = map.faces[faceIndex];\n\n // Skip faces with invalid texture info (e.g., logic/clip brushes).\n if (face.texInfo < 0) continue;\n\n const texInfo = map.texInfo[face.texInfo];\n const vertices: number[] = [];\n const textureCoords: number[] = [];\n const lightmapCoords: number[] = [];\n\n // Retrieve vertices for this face by walking its edges.\n // BSP faces are stored as references to a global edge list.\n for (let i = 0; i < face.numEdges; i++) {\n const edgeIndex = map.surfEdges[face.firstEdge + i];\n const edge = map.edges[Math.abs(edgeIndex)];\n // A positive edge index means traversal from vertex 0 to 1.\n // A negative edge index means traversal from vertex 1 to 0.\n const vIndex = edgeIndex >= 0 ? edge.vertices[0] : edge.vertices[1];\n const vertex = map.vertices[vIndex];\n\n vertices.push(vertex[0], vertex[1], vertex[2]);\n\n // Calculate standard texture coordinates (s, t) using the texture axes.\n // s = dot(v, s_vector) + s_offset\n // t = dot(v, t_vector) + t_offset\n const s = vertex[0] * texInfo.s[0] + vertex[1] * texInfo.s[1] + vertex[2] * texInfo.s[2] + texInfo.sOffset;\n const t = vertex[0] * texInfo.t[0] + vertex[1] * texInfo.t[1] + vertex[2] * texInfo.t[2] + texInfo.tOffset;\n\n textureCoords.push(s, t);\n\n // Lightmap coordinates are tentatively set to texture coordinates.\n // If valid lightmap data exists, they will be recalculated later.\n lightmapCoords.push(s, t);\n }\n\n // Triangulate the face. BSP faces are convex polygons, so a simple triangle fan\n // originating from the first vertex (index 0) covers the surface.\n const indices: number[] = [];\n const vertexCount = vertices.length / 3;\n for (let i = 1; i < vertexCount - 1; i++) {\n indices.push(0, i, i + 1);\n }\n\n // Process lightmap data if available.\n let lightmapData: BspLightmapData | undefined;\n const lightmapInfo = map.lightMapInfo[faceIndex];\n\n if (lightmapInfo) {\n // Calculate the extents of the texture coordinates to determine lightmap dimensions.\n // Quake 2 lightmaps are 1/16th scale of the texture coordinates.\n let minS = Infinity, maxS = -Infinity, minT = Infinity, maxT = -Infinity;\n for (let k = 0; k < textureCoords.length; k+=2) {\n const s = textureCoords[k];\n const t = textureCoords[k+1];\n if (s < minS) minS = s;\n if (s > maxS) maxS = s;\n if (t < minT) minT = t;\n if (t > maxT) maxT = t;\n }\n\n // Lightmap dimensions are ceil(max/16) - floor(min/16) + 1\n const floorMinS = Math.floor(minS / 16);\n const floorMinT = Math.floor(minT / 16);\n const lmWidth = Math.ceil(maxS / 16) - floorMinS + 1;\n const lmHeight = Math.ceil(maxT / 16) - floorMinT + 1;\n\n // Extract the raw lightmap samples from the BSP lump.\n const samples = createFaceLightmap(face, map.lightMaps, lightmapInfo);\n\n if (samples) {\n // Sanity check: the extracted sample count must match the calculated dimensions.\n if (samples.length === lmWidth * lmHeight * 3) {\n lightmapData = { width: lmWidth, height: lmHeight, samples };\n\n // Recalculate lightmap UVs based on the 1/16th scale and min offset.\n // We add 0.5 to center the sample.\n for (let k = 0; k < lightmapCoords.length; k+=2) {\n lightmapCoords[k] = (textureCoords[k] / 16) - floorMinS + 0.5;\n lightmapCoords[k+1] = (textureCoords[k+1] / 16) - floorMinT + 0.5;\n }\n }\n }\n }\n\n results.push({\n vertices: new Float32Array(vertices),\n textureCoords: new Float32Array(textureCoords),\n lightmapCoords: new Float32Array(lightmapCoords),\n indices: new Uint16Array(indices),\n texture: texInfo.texture,\n surfaceFlags: texInfo.flags,\n lightmap: lightmapData\n });\n }\n\n return results;\n}\n\nexport function buildBspGeometry(\n gl: WebGL2RenderingContext,\n surfaces: readonly BspSurfaceInput[],\n options: BspBuildOptions = {}\n): BspGeometryBuildResult {\n const resolved: Required<BspBuildOptions> = {\n atlasSize: options.atlasSize ?? 1024,\n lightmapPadding: options.lightmapPadding ?? 1,\n };\n\n const atlasBuilders: AtlasBuilder[] = [];\n const placements = new Map<number, LightmapPlacement>();\n\n surfaces.forEach((surface, index) => {\n if (!surface.lightmap) {\n return;\n }\n const { placement, atlas } = placeLightmap(atlasBuilders, surface.lightmap, resolved);\n writeLightmapIntoAtlas(atlas, placement, surface.lightmap);\n placements.set(index, {\n atlasIndex: placement.atlasIndex,\n offset: [\n (placement.x + resolved.lightmapPadding) / resolved.atlasSize,\n (placement.y + resolved.lightmapPadding) / resolved.atlasSize,\n ],\n scale: [placement.width / resolved.atlasSize, placement.height / resolved.atlasSize],\n });\n });\n\n const lightmaps: LightmapAtlas[] = atlasBuilders.map((builder) => {\n const texture = new Texture2D(gl);\n texture.setParameters({\n wrapS: gl.CLAMP_TO_EDGE,\n wrapT: gl.CLAMP_TO_EDGE,\n minFilter: gl.LINEAR,\n magFilter: gl.LINEAR,\n });\n texture.uploadImage(0, gl.RGBA, builder.width, builder.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, builder.data);\n return { texture, width: builder.width, height: builder.height, pixels: builder.data };\n });\n\n const results: BspSurfaceGeometry[] = surfaces.map((surface, index) => {\n const placement = placements.get(index);\n const vertexData = buildVertexData(surface, placement);\n const indexData = ensureIndexArray(surface.indices, vertexData.length / 7);\n\n const vertexBuffer = new VertexBuffer(gl, gl.STATIC_DRAW, gl.ARRAY_BUFFER);\n vertexBuffer.upload(vertexData as unknown as BufferSource);\n\n const indexBuffer = new IndexBuffer(gl, gl.STATIC_DRAW);\n indexBuffer.upload(indexData as unknown as BufferSource);\n\n const vao = new VertexArray(gl);\n vao.configureAttributes(BSP_VERTEX_LAYOUT, vertexBuffer);\n\n return {\n vao,\n vertexBuffer,\n indexBuffer,\n indexCount: indexData.length,\n vertexCount: vertexData.length / 7,\n texture: surface.texture,\n surfaceFlags: surface.surfaceFlags ?? SURF_NONE,\n lightmap: placement,\n vertexData,\n indexData,\n };\n });\n\n return { surfaces: results, lightmaps };\n}\n","import { type Vec3 } from '@quake2ts/shared';\n\nexport interface FrustumPlane {\n readonly normal: Vec3;\n readonly distance: number;\n}\n\nfunction normalizePlane(plane: FrustumPlane): FrustumPlane {\n const { normal, distance } = plane;\n const length = Math.sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z);\n if (length === 0) {\n return plane;\n }\n const inv = 1 / length;\n return {\n normal: { x: normal.x * inv, y: normal.y * inv, z: normal.z * inv },\n distance: distance * inv,\n };\n}\n\nexport function extractFrustumPlanes(matrix: readonly number[]): readonly FrustumPlane[] {\n if (matrix.length !== 16) {\n throw new Error('View-projection matrix must contain 16 elements');\n }\n\n const m00 = matrix[0];\n const m01 = matrix[4];\n const m02 = matrix[8];\n const m03 = matrix[12];\n const m10 = matrix[1];\n const m11 = matrix[5];\n const m12 = matrix[9];\n const m13 = matrix[13];\n const m20 = matrix[2];\n const m21 = matrix[6];\n const m22 = matrix[10];\n const m23 = matrix[14];\n const m30 = matrix[3];\n const m31 = matrix[7];\n const m32 = matrix[11];\n const m33 = matrix[15];\n\n const planes: FrustumPlane[] = [\n // Left\n normalizePlane({ normal: { x: m30 + m00, y: m31 + m01, z: m32 + m02 }, distance: m33 + m03 }),\n // Right\n normalizePlane({ normal: { x: m30 - m00, y: m31 - m01, z: m32 - m02 }, distance: m33 - m03 }),\n // Bottom\n normalizePlane({ normal: { x: m30 + m10, y: m31 + m11, z: m32 + m12 }, distance: m33 + m13 }),\n // Top\n normalizePlane({ normal: { x: m30 - m10, y: m31 - m11, z: m32 - m12 }, distance: m33 - m13 }),\n // Near\n normalizePlane({ normal: { x: m30 + m20, y: m31 + m21, z: m32 + m22 }, distance: m33 + m23 }),\n // Far\n normalizePlane({ normal: { x: m30 - m20, y: m31 - m21, z: m32 - m22 }, distance: m33 - m23 }),\n ];\n\n return planes;\n}\n\nfunction planeDistance(plane: FrustumPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z + plane.distance;\n}\n\nexport function boxIntersectsFrustum(mins: Vec3, maxs: Vec3, planes: readonly FrustumPlane[]): boolean {\n for (const plane of planes) {\n // Choose the corner most likely to be outside based on the plane normal.\n const x = plane.normal.x >= 0 ? maxs.x : mins.x;\n const y = plane.normal.y >= 0 ? maxs.y : mins.y;\n const z = plane.normal.z >= 0 ? maxs.z : mins.z;\n if (planeDistance(plane, { x, y, z }) < 0) {\n return false;\n }\n }\n return true;\n}\n","import { type Vec3 } from '@quake2ts/shared';\nimport type {\n BspLeaf,\n BspMap,\n BspNode,\n BspPlane,\n BspVisibility,\n} from '../assets/bsp.js';\nimport { boxIntersectsFrustum, type FrustumPlane } from './culling.js';\n\nexport interface VisibleFace {\n readonly faceIndex: number;\n readonly leafIndex: number;\n readonly sortKey: number;\n}\n\nfunction childIsLeaf(index: number): boolean {\n return index < 0;\n}\n\nfunction childLeafIndex(index: number): number {\n return -index - 1;\n}\n\nfunction distanceToPlane(plane: BspPlane, point: Vec3): number {\n return plane.normal[0] * point.x + plane.normal[1] * point.y + plane.normal[2] * point.z - plane.dist;\n}\n\nfunction isClusterVisible(visibility: BspVisibility | undefined, fromCluster: number, testCluster: number): boolean {\n if (!visibility) {\n return true;\n }\n if (fromCluster < 0 || testCluster < 0) {\n return true;\n }\n const rowBytes = Math.ceil(visibility.numClusters / 8);\n const row = visibility.clusters[fromCluster].pvs;\n const byteIndex = Math.floor(testCluster / 8);\n const bit = 1 << (testCluster % 8);\n if (byteIndex < 0 || byteIndex >= rowBytes) {\n return false;\n }\n return (row[byteIndex] & bit) !== 0;\n}\n\nfunction leafIntersectsFrustum(leaf: BspLeaf, planes: readonly FrustumPlane[]): boolean {\n const mins = { x: leaf.mins[0], y: leaf.mins[1], z: leaf.mins[2] };\n const maxs = { x: leaf.maxs[0], y: leaf.maxs[1], z: leaf.maxs[2] };\n return boxIntersectsFrustum(mins, maxs, planes);\n}\n\nexport function findLeafForPoint(map: BspMap, point: Vec3): number {\n let nodeIndex = 0;\n while (nodeIndex >= 0) {\n const node: BspNode = map.nodes[nodeIndex];\n const plane = map.planes[node.planeIndex];\n const dist = distanceToPlane(plane, point);\n const side = dist >= 0 ? 0 : 1;\n const child = node.children[side];\n if (childIsLeaf(child)) {\n return childLeafIndex(child);\n }\n nodeIndex = child;\n }\n return -1;\n}\n\nfunction collectFacesFromLeaf(map: BspMap, leafIndex: number): number[] {\n const leaf = map.leafs[leafIndex];\n const faces: number[] = [];\n for (let i = 0; i < leaf.numLeafFaces; i += 1) {\n faces.push(map.leafLists.leafFaces[leafIndex][i]);\n }\n return faces;\n}\n\nfunction traverse(\n map: BspMap,\n nodeIndex: number,\n camera: Vec3,\n frustum: readonly FrustumPlane[],\n viewCluster: number,\n visibleFaces: VisibleFace[],\n visitedFaces: Set<number>\n): void {\n if (childIsLeaf(nodeIndex)) {\n const leafIndex = childLeafIndex(nodeIndex);\n const leaf = map.leafs[leafIndex];\n if (!isClusterVisible(map.visibility, viewCluster, leaf.cluster)) {\n return;\n }\n if (!leafIntersectsFrustum(leaf, frustum)) {\n return;\n }\n const center = {\n x: (leaf.mins[0] + leaf.maxs[0]) * 0.5,\n y: (leaf.mins[1] + leaf.maxs[1]) * 0.5,\n z: (leaf.mins[2] + leaf.maxs[2]) * 0.5,\n };\n const dx = center.x - camera.x;\n const dy = center.y - camera.y;\n const dz = center.z - camera.z;\n const leafSortKey = -(dx * dx + dy * dy + dz * dz);\n for (const faceIndex of collectFacesFromLeaf(map, leafIndex)) {\n if (visitedFaces.has(faceIndex)) {\n continue;\n }\n visitedFaces.add(faceIndex);\n visibleFaces.push({ faceIndex, leafIndex, sortKey: leafSortKey });\n }\n return;\n }\n\n const node = map.nodes[nodeIndex];\n const plane = map.planes[node.planeIndex];\n const dist = distanceToPlane(plane, camera);\n const nearChild = dist >= 0 ? node.children[0] : node.children[1];\n const farChild = dist >= 0 ? node.children[1] : node.children[0];\n\n if (boxIntersectsFrustum(\n { x: node.mins[0], y: node.mins[1], z: node.mins[2] },\n { x: node.maxs[0], y: node.maxs[1], z: node.maxs[2] },\n frustum,\n )) {\n traverse(map, nearChild, camera, frustum, viewCluster, visibleFaces, visitedFaces);\n traverse(map, farChild, camera, frustum, viewCluster, visibleFaces, visitedFaces);\n }\n}\n\nexport function gatherVisibleFaces(\n map: BspMap,\n cameraPosition: Vec3,\n frustum: readonly FrustumPlane[],\n): VisibleFace[] {\n const viewLeaf = findLeafForPoint(map, cameraPosition);\n const viewCluster = viewLeaf >= 0 ? map.leafs[viewLeaf].cluster : -1;\n const visibleFaces: VisibleFace[] = [];\n const visitedFaces = new Set<number>();\n traverse(map, 0, cameraPosition, frustum, viewCluster, visibleFaces, visitedFaces);\n return visibleFaces;\n}\n","import {\n SURF_FLOWING,\n SURF_NONE,\n SURF_SKY,\n SURF_TRANS33,\n SURF_TRANS66,\n SURF_WARP,\n type SurfaceFlag,\n} from '@quake2ts/shared';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface SurfaceRenderState {\n readonly alpha: number;\n readonly blend: boolean;\n readonly depthWrite: boolean;\n readonly warp: boolean;\n readonly flowOffset: readonly [number, number];\n readonly sky: boolean;\n}\n\nexport interface BspSurfaceBindOptions {\n readonly modelViewProjection: Float32List;\n readonly styleIndices?: readonly number[];\n readonly styleValues?: ReadonlyArray<number>;\n readonly diffuseSampler?: number;\n readonly lightmapSampler?: number;\n readonly surfaceFlags?: SurfaceFlag;\n readonly timeSeconds?: number;\n}\n\nexport const BSP_SURFACE_VERTEX_SOURCE = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_texCoord;\nlayout(location = 2) in vec2 a_lightmapCoord;\n\nuniform mat4 u_modelViewProjection;\nuniform vec2 u_texScroll;\nuniform vec2 u_lightmapScroll;\n\nout vec2 v_texCoord;\nout vec2 v_lightmapCoord;\n\nvec2 applyScroll(vec2 uv, vec2 scroll) {\n return uv + scroll;\n}\n\nvoid main() {\n v_texCoord = applyScroll(a_texCoord, u_texScroll);\n v_lightmapCoord = applyScroll(a_lightmapCoord, u_lightmapScroll);\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const BSP_SURFACE_FRAGMENT_SOURCE = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin vec2 v_lightmapCoord;\n\nuniform sampler2D u_diffuseMap;\nuniform sampler2D u_lightmapAtlas;\nuniform vec4 u_lightStyleFactors;\nuniform float u_alpha;\nuniform bool u_applyLightmap;\nuniform bool u_warp;\nuniform float u_time;\n\nout vec4 o_color;\n\nvec2 warpCoords(vec2 uv) {\n // Quake II warp applies a subtle sinusoidal offset; we mirror the rerelease scale.\n if (!u_warp) {\n return uv;\n }\n float s = uv.x + sin(uv.y * 0.125 + u_time) * 0.125;\n float t = uv.y + sin(uv.x * 0.125 + u_time) * 0.125;\n return vec2(s, t);\n}\n\nvoid main() {\n vec2 warpedTex = warpCoords(v_texCoord);\n vec4 base = texture(u_diffuseMap, warpedTex);\n\n if (u_applyLightmap) {\n vec3 light = texture(u_lightmapAtlas, warpCoords(v_lightmapCoord)).rgb;\n float styleScale = dot(u_lightStyleFactors, vec4(1.0));\n base.rgb *= light * styleScale;\n }\n\n o_color = vec4(base.rgb, base.a * u_alpha);\n}`;\n\nconst DEFAULT_STYLE_INDICES: readonly number[] = [0, 255, 255, 255];\n\nexport function resolveLightStyles(\n styleIndices: readonly number[] = DEFAULT_STYLE_INDICES,\n styleValues: ReadonlyArray<number> = []\n): Float32Array {\n const factors = new Float32Array(4);\n for (let i = 0; i < 4; i += 1) {\n const styleIndex = styleIndices[i] ?? 255;\n if (styleIndex === 255) {\n factors[i] = 0;\n continue;\n }\n const value = styleValues[styleIndex];\n factors[i] = value !== undefined ? value : 1;\n }\n return factors;\n}\n\nfunction computeFlowOffset(timeSeconds: number): readonly [number, number] {\n const cycle = (timeSeconds * 0.25) % 1;\n // Match Quake II's negative scroll direction for flowing water/conveyors.\n return [-cycle, 0];\n}\n\nexport function deriveSurfaceRenderState(\n surfaceFlags: SurfaceFlag = SURF_NONE,\n timeSeconds = 0\n): SurfaceRenderState {\n const flowing = (surfaceFlags & SURF_FLOWING) !== 0;\n const warp = (surfaceFlags & SURF_WARP) !== 0;\n const sky = (surfaceFlags & SURF_SKY) !== 0;\n const trans33 = (surfaceFlags & SURF_TRANS33) !== 0;\n const trans66 = (surfaceFlags & SURF_TRANS66) !== 0;\n\n const alpha = trans33 ? 0.33 : trans66 ? 0.66 : 1;\n const blend = trans33 || trans66;\n const depthWrite = !blend && !sky;\n const flowOffset: readonly [number, number] = flowing ? computeFlowOffset(timeSeconds) : [0, 0];\n\n return {\n alpha,\n blend,\n depthWrite,\n warp,\n flowOffset,\n sky,\n };\n}\n\nexport class BspSurfacePipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformTexScroll: WebGLUniformLocation | null;\n private readonly uniformLmScroll: WebGLUniformLocation | null;\n private readonly uniformLightStyles: WebGLUniformLocation | null;\n private readonly uniformAlpha: WebGLUniformLocation | null;\n private readonly uniformApplyLightmap: WebGLUniformLocation | null;\n private readonly uniformWarp: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n private readonly uniformLightmap: WebGLUniformLocation | null;\n private readonly uniformTime: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: BSP_SURFACE_VERTEX_SOURCE, fragment: BSP_SURFACE_FRAGMENT_SOURCE },\n { a_position: 0, a_texCoord: 1, a_lightmapCoord: 2 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformTexScroll = this.program.getUniformLocation('u_texScroll');\n this.uniformLmScroll = this.program.getUniformLocation('u_lightmapScroll');\n this.uniformLightStyles = this.program.getUniformLocation('u_lightStyleFactors');\n this.uniformAlpha = this.program.getUniformLocation('u_alpha');\n this.uniformApplyLightmap = this.program.getUniformLocation('u_applyLightmap');\n this.uniformWarp = this.program.getUniformLocation('u_warp');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n this.uniformLightmap = this.program.getUniformLocation('u_lightmapAtlas');\n this.uniformTime = this.program.getUniformLocation('u_time');\n }\n\n bind(options: BspSurfaceBindOptions): SurfaceRenderState {\n const {\n modelViewProjection,\n styleIndices = DEFAULT_STYLE_INDICES,\n styleValues = [],\n diffuseSampler = 0,\n lightmapSampler,\n surfaceFlags = SURF_NONE,\n timeSeconds = 0,\n } = options;\n\n const state = deriveSurfaceRenderState(surfaceFlags, timeSeconds);\n const styles = resolveLightStyles(styleIndices, styleValues);\n\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform2f(this.uniformTexScroll, state.flowOffset[0], state.flowOffset[1]);\n this.gl.uniform2f(this.uniformLmScroll, state.flowOffset[0], state.flowOffset[1]);\n this.gl.uniform4fv(this.uniformLightStyles, styles);\n this.gl.uniform1f(this.uniformAlpha, state.alpha);\n const applyLightmap = !state.sky && lightmapSampler !== undefined;\n this.gl.uniform1i(this.uniformApplyLightmap, applyLightmap ? 1 : 0);\n this.gl.uniform1i(this.uniformWarp, state.warp ? 1 : 0);\n this.gl.uniform1f(this.uniformTime, timeSeconds);\n this.gl.uniform1i(this.uniformDiffuse, diffuseSampler);\n this.gl.uniform1i(this.uniformLightmap, lightmapSampler ?? 0);\n\n return state;\n }\n\n dispose(): void {\n this.program.dispose();\n }\n}\n\nexport function applySurfaceState(gl: WebGL2RenderingContext, state: SurfaceRenderState): void {\n gl.depthMask(state.depthWrite);\n if (state.blend) {\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);\n } else {\n gl.disable(gl.BLEND);\n }\n}\n","import { ShaderProgram } from './shaderProgram.js';\nimport { TextureCubeMap, VertexArray, VertexBuffer, type VertexAttributeLayout } from './resources.js';\nimport type { ReadonlyMat4 } from 'gl-matrix';\n\nconst SKYBOX_POSITIONS = new Float32Array([\n // Front\n -1, -1, 1,\n 1, -1, 1,\n 1, 1, 1,\n -1, -1, 1,\n 1, 1, 1,\n -1, 1, 1,\n // Back\n -1, -1, -1,\n -1, 1, -1,\n 1, 1, -1,\n -1, -1, -1,\n 1, 1, -1,\n 1, -1, -1,\n // Left\n -1, -1, -1,\n -1, -1, 1,\n -1, 1, 1,\n -1, -1, -1,\n -1, 1, 1,\n -1, 1, -1,\n // Right\n 1, -1, -1,\n 1, 1, -1,\n 1, 1, 1,\n 1, -1, -1,\n 1, 1, 1,\n 1, -1, 1,\n // Top\n -1, 1, -1,\n -1, 1, 1,\n 1, 1, 1,\n -1, 1, -1,\n 1, 1, 1,\n 1, 1, -1,\n // Bottom\n -1, -1, -1,\n 1, -1, -1,\n 1, -1, 1,\n -1, -1, -1,\n 1, -1, 1,\n -1, -1, 1,\n]);\n\nexport const SKYBOX_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\n\nuniform mat4 u_viewProjectionNoTranslation;\nuniform vec2 u_scroll;\n\nout vec3 v_direction;\n\nvoid main() {\n vec3 dir = normalize(a_position);\n dir.xy += u_scroll;\n v_direction = dir;\n gl_Position = u_viewProjectionNoTranslation * vec4(a_position, 1.0);\n}`;\n\nexport const SKYBOX_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec3 v_direction;\nuniform samplerCube u_skybox;\n\nout vec4 o_color;\n\nvoid main() {\n o_color = texture(u_skybox, v_direction);\n}`;\n\nexport interface SkyboxBindOptions {\n readonly viewProjection: Float32List;\n readonly scroll: readonly [number, number];\n readonly textureUnit?: number;\n}\n\nexport class SkyboxPipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n readonly vao: VertexArray;\n readonly vbo: VertexBuffer;\n readonly cubemap: TextureCubeMap;\n\n private readonly uniformViewProj: WebGLUniformLocation | null;\n private readonly uniformScroll: WebGLUniformLocation | null;\n private readonly uniformSampler: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: SKYBOX_VERTEX_SHADER, fragment: SKYBOX_FRAGMENT_SHADER },\n { a_position: 0 }\n );\n\n this.vao = new VertexArray(gl);\n this.vbo = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.vbo.upload(SKYBOX_POSITIONS, gl.STATIC_DRAW);\n\n const layout: VertexAttributeLayout[] = [{ index: 0, size: 3, type: gl.FLOAT, stride: 12, offset: 0 }];\n this.vao.configureAttributes(layout, this.vbo);\n\n this.uniformViewProj = this.program.getUniformLocation('u_viewProjectionNoTranslation');\n this.uniformScroll = this.program.getUniformLocation('u_scroll');\n this.uniformSampler = this.program.getUniformLocation('u_skybox');\n\n this.cubemap = new TextureCubeMap(gl);\n this.cubemap.setParameters({\n minFilter: gl.LINEAR,\n magFilter: gl.LINEAR,\n wrapS: gl.CLAMP_TO_EDGE,\n wrapT: gl.CLAMP_TO_EDGE,\n });\n }\n\n bind(options: SkyboxBindOptions): void {\n const { viewProjection, scroll, textureUnit = 0 } = options;\n this.program.use();\n this.gl.depthMask(false);\n this.gl.uniformMatrix4fv(this.uniformViewProj, false, viewProjection);\n this.gl.uniform2f(this.uniformScroll, scroll[0], scroll[1]);\n this.gl.uniform1i(this.uniformSampler, textureUnit);\n this.cubemap.bind(textureUnit);\n this.vao.bind();\n }\n\n draw(): void {\n this.gl.drawArrays(this.gl.TRIANGLES, 0, SKYBOX_POSITIONS.length / 3);\n }\n\n dispose(): void {\n this.vbo.dispose();\n this.vao.dispose();\n this.cubemap.dispose();\n this.program.dispose();\n }\n}\n\nexport function removeViewTranslation(viewMatrix: ReadonlyMat4 | Float32Array): Float32Array {\n const noTranslation = new Float32Array(viewMatrix);\n noTranslation[12] = 0;\n noTranslation[13] = 0;\n noTranslation[14] = 0;\n return noTranslation;\n}\n\nexport function computeSkyScroll(timeSeconds: number, scrollSpeeds: readonly [number, number] = [0.01, 0.02]): [number, number] {\n const [sx, sy] = scrollSpeeds;\n return [sx * timeSeconds, sy * timeSeconds];\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { Md2Model } from '../assets/md2.js';\nimport { IndexBuffer, VertexArray, VertexBuffer } from './resources.js';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface Md2DrawVertex {\n readonly vertexIndex: number;\n readonly texCoord: readonly [number, number];\n}\n\nexport interface Md2Geometry {\n readonly vertices: readonly Md2DrawVertex[];\n readonly indices: Uint16Array;\n}\n\nexport interface Md2FrameBlend {\n readonly currentFrame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface Md2BindOptions {\n readonly modelViewProjection: Float32List;\n readonly lightDirection?: readonly [number, number, number];\n readonly tint?: readonly [number, number, number, number];\n readonly diffuseSampler?: number;\n}\n\nexport const MD2_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_modelViewProjection;\nuniform vec3 u_lightDir;\n\nout vec2 v_texCoord;\nout float v_light;\n\nvoid main() {\n vec3 normal = normalize(a_normal);\n v_light = max(dot(normal, normalize(u_lightDir)), 0.0);\n v_texCoord = a_texCoord;\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const MD2_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin float v_light;\n\nuniform sampler2D u_diffuseMap;\nuniform vec4 u_tint;\n\nout vec4 o_color;\n\nvoid main() {\n vec4 albedo = texture(u_diffuseMap, v_texCoord) * u_tint;\n o_color = vec4(albedo.rgb * v_light, albedo.a);\n}`;\n\nfunction normalizeVec3(v: Vec3): Vec3 {\n const lengthSq = v.x * v.x + v.y * v.y + v.z * v.z;\n if (lengthSq <= 0) {\n return { x: 0, y: 0, z: 1 };\n }\n const inv = 1 / Math.sqrt(lengthSq);\n return { x: v.x * inv, y: v.y * inv, z: v.z * inv };\n}\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\nfunction lerpVec3(a: Vec3, b: Vec3, t: number): Vec3 {\n return {\n x: lerp(a.x, b.x, t),\n y: lerp(a.y, b.y, t),\n z: lerp(a.z, b.z, t),\n };\n}\n\nfunction normalizeUv(s: number, t: number, header: Md2Model['header']): readonly [number, number] {\n return [s / header.skinWidth, 1 - t / header.skinHeight];\n}\n\nexport function buildMd2Geometry(model: Md2Model): Md2Geometry {\n if (model.glCommands.length === 0) {\n const vertices: Md2DrawVertex[] = [];\n const indices: number[] = [];\n model.triangles.forEach((triangle) => {\n const baseIndex = vertices.length;\n for (let i = 0; i < 3; i += 1) {\n const vertexIndex = triangle.vertexIndices[i];\n const texCoordIndex = triangle.texCoordIndices[i];\n const texCoord = model.texCoords[texCoordIndex];\n vertices.push({\n vertexIndex,\n texCoord: normalizeUv(texCoord.s, texCoord.t, model.header),\n });\n }\n indices.push(baseIndex, baseIndex + 1, baseIndex + 2);\n });\n\n return { vertices, indices: new Uint16Array(indices) };\n }\n\n const vertices: Md2DrawVertex[] = [];\n const indices: number[] = [];\n\n for (const command of model.glCommands) {\n const start = vertices.length;\n vertices.push(\n ...command.vertices.map((vertex) => ({\n vertexIndex: vertex.vertexIndex,\n texCoord: [vertex.s, 1 - vertex.t] as const,\n }))\n );\n\n if (command.mode === 'strip') {\n for (let i = 0; i < command.vertices.length - 2; i += 1) {\n const even = i % 2 === 0;\n const a = start + i + (even ? 0 : 1);\n const b = start + i + (even ? 1 : 0);\n const c = start + i + 2;\n indices.push(a, b, c);\n }\n } else {\n for (let i = 1; i < command.vertices.length - 1; i += 1) {\n indices.push(start, start + i, start + i + 1);\n }\n }\n }\n\n return { vertices, indices: new Uint16Array(indices) };\n}\n\nexport function buildMd2VertexData(\n model: Md2Model,\n geometry: Md2Geometry,\n blend: Md2FrameBlend\n): Float32Array {\n const { currentFrame, nextFrame, lerp } = blend;\n const frameA = model.frames[currentFrame];\n const frameB = model.frames[nextFrame];\n\n if (!frameA || !frameB) {\n throw new Error('Requested MD2 frames are out of range');\n }\n\n const data = new Float32Array(geometry.vertices.length * 8);\n geometry.vertices.forEach((vertex, index) => {\n const vA = frameA.vertices[vertex.vertexIndex];\n const vB = frameB.vertices[vertex.vertexIndex];\n if (!vA || !vB) {\n throw new Error('MD2 vertex index out of range for frame');\n }\n\n const position = lerpVec3(vA.position, vB.position, lerp);\n const normal = normalizeVec3(lerpVec3(vA.normal, vB.normal, lerp));\n\n const base = index * 8;\n data[base] = position.x;\n data[base + 1] = position.y;\n data[base + 2] = position.z;\n data[base + 3] = normal.x;\n data[base + 4] = normal.y;\n data[base + 5] = normal.z;\n data[base + 6] = vertex.texCoord[0];\n data[base + 7] = vertex.texCoord[1];\n });\n\n return data;\n}\n\nexport class Md2MeshBuffers {\n readonly gl: WebGL2RenderingContext;\n readonly geometry: Md2Geometry;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly vertexArray: VertexArray;\n readonly indexCount: number;\n\n constructor(gl: WebGL2RenderingContext, model: Md2Model, blend: Md2FrameBlend) {\n this.gl = gl;\n this.geometry = buildMd2Geometry(model);\n this.vertexBuffer = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.indexBuffer = new IndexBuffer(gl, gl.STATIC_DRAW);\n this.vertexArray = new VertexArray(gl);\n this.indexCount = this.geometry.indices.length;\n\n this.vertexArray.configureAttributes(\n [\n { index: 0, size: 3, type: gl.FLOAT, stride: 32, offset: 0 },\n { index: 1, size: 3, type: gl.FLOAT, stride: 32, offset: 12 },\n { index: 2, size: 2, type: gl.FLOAT, stride: 32, offset: 24 },\n ],\n this.vertexBuffer\n );\n\n this.vertexArray.bind();\n this.indexBuffer.bind();\n this.indexBuffer.upload(this.geometry.indices as unknown as BufferSource, gl.STATIC_DRAW);\n this.update(model, blend);\n }\n\n update(model: Md2Model, blend: Md2FrameBlend): void {\n const data = buildMd2VertexData(model, this.geometry, blend);\n this.vertexBuffer.upload(data as unknown as BufferSource, this.gl.STATIC_DRAW);\n }\n\n bind(): void {\n this.vertexArray.bind();\n this.indexBuffer.bind();\n }\n\n dispose(): void {\n this.vertexBuffer.dispose();\n this.indexBuffer.dispose();\n this.vertexArray.dispose();\n }\n}\n\nexport class Md2Pipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformLightDir: WebGLUniformLocation | null;\n private readonly uniformTint: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: MD2_VERTEX_SHADER, fragment: MD2_FRAGMENT_SHADER },\n { a_position: 0, a_normal: 1, a_texCoord: 2 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformLightDir = this.program.getUniformLocation('u_lightDir');\n this.uniformTint = this.program.getUniformLocation('u_tint');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n }\n\n bind(options: Md2BindOptions): void {\n const { modelViewProjection, lightDirection = [0, 0, 1], tint = [1, 1, 1, 1], diffuseSampler = 0 } = options;\n const lightVec = new Float32Array(lightDirection);\n const tintVec = new Float32Array(tint);\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform3fv(this.uniformLightDir, lightVec);\n this.gl.uniform4fv(this.uniformTint, tintVec);\n this.gl.uniform1i(this.uniformDiffuse, diffuseSampler);\n }\n\n draw(mesh: Md2MeshBuffers): void {\n mesh.bind();\n this.gl.drawElements(this.gl.TRIANGLES, mesh.indexCount, this.gl.UNSIGNED_SHORT, 0);\n }\n\n dispose(): void {\n this.program.dispose();\n }\n}\n","import { mat4, vec3 } from 'gl-matrix';\nimport { DEG2RAD } from '@quake2ts/shared';\n\nexport class Camera {\n private _position: vec3 = vec3.create();\n private _angles: vec3 = vec3.create(); // pitch, yaw, roll\n private _bobAngles: vec3 = vec3.create();\n private _bobOffset: vec3 = vec3.create();\n private _kickAngles: vec3 = vec3.create();\n private _rollAngle = 0;\n private _fov = 90;\n private _aspect = 1.0;\n private _near = 0.1;\n private _far = 1000;\n\n private _viewMatrix: mat4 = mat4.create();\n private _projectionMatrix: mat4 = mat4.create();\n private _viewProjectionMatrix: mat4 = mat4.create();\n private _dirty = true;\n\n get position(): vec3 {\n return this._position;\n }\n\n set position(value: vec3) {\n vec3.copy(this._position, value);\n this._dirty = true;\n }\n\n get angles(): vec3 {\n return this._angles;\n }\n\n set angles(value: vec3) {\n vec3.copy(this._angles, value);\n this._dirty = true;\n }\n\n get bobAngles(): vec3 {\n return this._bobAngles;\n }\n\n set bobAngles(value: vec3) {\n vec3.copy(this._bobAngles, value);\n this._dirty = true;\n }\n\n get kickAngles(): vec3 {\n return this._kickAngles;\n }\n\n set kickAngles(value: vec3) {\n vec3.copy(this._kickAngles, value);\n this._dirty = true;\n }\n\n get bobOffset(): vec3 {\n return this._bobOffset;\n }\n\n set bobOffset(value: vec3) {\n vec3.copy(this._bobOffset, value);\n this._dirty = true;\n }\n\n get rollAngle(): number {\n return this._rollAngle;\n }\n\n set rollAngle(value: number) {\n this._rollAngle = value;\n this._dirty = true;\n }\n\n get fov(): number {\n return this._fov;\n }\n\n set fov(value: number) {\n this._fov = value;\n this._dirty = true;\n }\n\n get aspect(): number {\n return this._aspect;\n }\n\n set aspect(value: number) {\n this._aspect = value;\n this._dirty = true;\n }\n\n get viewMatrix(): mat4 {\n this.updateMatrices();\n return this._viewMatrix;\n }\n\n get projectionMatrix(): mat4 {\n this.updateMatrices();\n return this._projectionMatrix;\n }\n\n get viewProjectionMatrix(): mat4 {\n this.updateMatrices();\n return this._viewProjectionMatrix;\n }\n\n getViewmodelProjectionMatrix(fov: number): mat4 {\n const projectionMatrix = mat4.create();\n mat4.perspective(\n projectionMatrix,\n fov * DEG2RAD,\n this._aspect,\n this._near,\n this._far\n );\n return projectionMatrix;\n }\n\n private updateMatrices(): void {\n if (!this._dirty) {\n return;\n }\n\n // 1. Update projection matrix\n mat4.perspective(\n this._projectionMatrix,\n this._fov * DEG2RAD,\n this._aspect,\n this._near,\n this._far\n );\n\n // 2. Create the coordinate system transformation matrix.\n // This matrix transforms vectors from Quake's coordinate system\n // (X forward, Y left, Z up) to WebGL's coordinate system (X right, Y up, Z back).\n //\n // Mapping (column vectors based on test expectations):\n // - Quake X (forward) -> WebGL -Y\n // - Quake Y (left) -> WebGL +Z\n // - Quake Z (up) -> WebGL -X\n const quakeToGl = mat4.fromValues(\n 0, -1, 0, 0, // column 0: Quake X -> WebGL (0, -1, 0)\n 0, 0, 1, 0, // column 1: Quake Y -> WebGL (0, 0, 1)\n -1, 0, 0, 0, // column 2: Quake Z -> WebGL (-1, 0, 0)\n 0, 0, 0, 1 // column 3: no translation\n );\n\n // 3. Construct the Quake rotation matrix\n const pitch = this._angles[0] + this._bobAngles[0] + this._kickAngles[0];\n const yaw = this._angles[1] + this._bobAngles[1] + this._kickAngles[1];\n const roll = this._angles[2] + this._bobAngles[2] + this._kickAngles[2] + this._rollAngle;\n\n const pitchRad = pitch * DEG2RAD;\n const yawRad = yaw * DEG2RAD;\n const rollRad = roll * DEG2RAD;\n\n const rotationQuake = mat4.create();\n mat4.identity(rotationQuake);\n\n // Rotations are applied in reverse order to the world\n // Quake's axes for rotation are: Z(yaw), Y(pitch), X(roll)\n mat4.rotateZ(rotationQuake, rotationQuake, -yawRad);\n mat4.rotateY(rotationQuake, rotationQuake, -pitchRad);\n mat4.rotateX(rotationQuake, rotationQuake, -rollRad);\n\n // 4. Combine Quake rotation with coordinate transformation\n const rotationGl = mat4.create();\n mat4.multiply(rotationGl, quakeToGl, rotationQuake);\n\n // 5. Calculate the view matrix translation\n // Apply rotation in Quake space first, then transform to GL coordinates\n const positionWithOffset = vec3.add(vec3.create(), this._position, this._bobOffset);\n const negativePosition = vec3.negate(vec3.create(), positionWithOffset);\n const rotatedPosQuake = vec3.create();\n vec3.transformMat4(rotatedPosQuake, negativePosition, rotationQuake);\n\n // Transform the rotated position from Quake coordinates to WebGL coordinates\n // using the simple coordinate swizzle (not matrix multiplication)\n const translationGl = vec3.fromValues(\n rotatedPosQuake[1] || 0, // Y in Quake -> X in WebGL (negation already applied above)\n rotatedPosQuake[2] || 0, // Z in Quake -> Y in WebGL\n rotatedPosQuake[0] || 0 // X in Quake -> Z in WebGL (negation already applied above)\n );\n\n // 6. Build the final view matrix by combining rotation and translation\n mat4.copy(this._viewMatrix, rotationGl);\n this._viewMatrix[12] = translationGl[0];\n this._viewMatrix[13] = translationGl[1];\n this._viewMatrix[14] = translationGl[2];\n\n // 7. Update the combined view-projection matrix\n mat4.multiply(\n this._viewProjectionMatrix,\n this._projectionMatrix,\n this._viewMatrix\n );\n\n this._dirty = false;\n }\n}\n","import { Mat4, Vec3, mat4FromBasis, normalizeVec3, transformPointMat4 } from '@quake2ts/shared';\nimport { Md3Model, Md3Surface } from '../assets/md3.js';\nimport { IndexBuffer, VertexArray, VertexBuffer } from './resources.js';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface Md3DrawVertex {\n readonly vertexIndex: number;\n readonly texCoord: readonly [number, number];\n}\n\nexport interface Md3SurfaceGeometry {\n readonly vertices: readonly Md3DrawVertex[];\n readonly indices: Uint16Array;\n}\n\nexport interface Md3FrameBlend {\n readonly currentFrame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface Md3DynamicLight {\n readonly origin: Vec3;\n readonly color: readonly [number, number, number];\n readonly radius: number;\n}\n\nexport interface Md3LightingOptions {\n readonly ambient?: readonly [number, number, number];\n readonly directional?: { direction: Vec3; color: readonly [number, number, number] };\n readonly dynamicLights?: readonly Md3DynamicLight[];\n readonly modelMatrix?: Mat4;\n}\n\nexport interface Md3SurfaceMaterial {\n readonly diffuseSampler?: number;\n readonly tint?: readonly [number, number, number, number];\n}\n\nexport interface Md3TagTransform {\n readonly origin: Vec3;\n readonly axis: readonly [Vec3, Vec3, Vec3];\n readonly matrix: Mat4;\n}\n\nconst DEFAULT_AMBIENT: readonly [number, number, number] = [0.2, 0.2, 0.2];\nconst DEFAULT_DIRECTION: Vec3 = { x: 0, y: 0, z: 1 };\nconst DEFAULT_DIRECTION_COLOR: readonly [number, number, number] = [0.8, 0.8, 0.8];\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\nfunction lerpVec3(a: Vec3, b: Vec3, t: number): Vec3 {\n return { x: lerp(a.x, b.x, t), y: lerp(a.y, b.y, t), z: lerp(a.z, b.z, t) };\n}\n\nfunction clamp01(v: number): number {\n if (v < 0) return 0;\n if (v > 1) return 1;\n return v;\n}\n\nexport function buildMd3SurfaceGeometry(surface: Md3Surface): Md3SurfaceGeometry {\n const vertices: Md3DrawVertex[] = [];\n const indices: number[] = [];\n\n for (const tri of surface.triangles) {\n const base = vertices.length;\n const [a, b, c] = tri.indices;\n const texA = surface.texCoords[a];\n const texB = surface.texCoords[b];\n const texC = surface.texCoords[c];\n\n if (!texA || !texB || !texC) {\n throw new Error(`Missing texCoord for triangle in surface ${surface.name}`);\n }\n\n vertices.push(\n { vertexIndex: a, texCoord: [texA.s, 1 - texA.t] },\n { vertexIndex: b, texCoord: [texB.s, 1 - texB.t] },\n { vertexIndex: c, texCoord: [texC.s, 1 - texC.t] }\n );\n\n indices.push(base, base + 1, base + 2);\n }\n\n return { vertices, indices: new Uint16Array(indices) };\n}\n\nfunction evaluateLighting(normal: Vec3, position: Vec3, lighting?: Md3LightingOptions): readonly [number, number, number] {\n const ambient = lighting?.ambient ?? DEFAULT_AMBIENT;\n const directional = lighting?.directional ?? { direction: DEFAULT_DIRECTION, color: DEFAULT_DIRECTION_COLOR };\n\n const n = normalizeVec3(normal);\n const l = normalizeVec3(directional.direction);\n const ndotl = clamp01(n.x * l.x + n.y * l.y + n.z * l.z);\n\n let r = ambient[0] + directional.color[0] * ndotl;\n let g = ambient[1] + directional.color[1] * ndotl;\n let b = ambient[2] + directional.color[2] * ndotl;\n\n if (lighting?.dynamicLights) {\n const worldPos = lighting.modelMatrix ? transformPointMat4(lighting.modelMatrix, position) : position;\n for (const light of lighting.dynamicLights) {\n const dx = worldPos.x - light.origin.x;\n const dy = worldPos.y - light.origin.y;\n const dz = worldPos.z - light.origin.z;\n const distSq = dx * dx + dy * dy + dz * dz;\n const radiusSq = light.radius * light.radius;\n if (distSq < radiusSq && radiusSq > 0) {\n const attenuation = 1 - Math.sqrt(distSq) / light.radius;\n // Compute dot product with direction to this specific dynamic light\n const dist = Math.sqrt(distSq);\n const lightDotN = dist > 0 ? clamp01(-(dx * n.x + dy * n.y + dz * n.z) / dist) : 0;\n const amount = clamp01(attenuation * lightDotN);\n r += light.color[0] * amount;\n g += light.color[1] * amount;\n b += light.color[2] * amount;\n }\n }\n }\n\n return [clamp01(r), clamp01(g), clamp01(b)];\n}\n\nexport function buildMd3VertexData(\n surface: Md3Surface,\n geometry: Md3SurfaceGeometry,\n blend: Md3FrameBlend,\n lighting?: Md3LightingOptions\n): Float32Array {\n const frameA = surface.vertices[blend.currentFrame];\n const frameB = surface.vertices[blend.nextFrame];\n\n if (!frameA || !frameB) {\n throw new Error('Requested MD3 frames are out of range');\n }\n\n const data = new Float32Array(geometry.vertices.length * 12);\n geometry.vertices.forEach((vertex, index) => {\n const vA = frameA[vertex.vertexIndex];\n const vB = frameB[vertex.vertexIndex];\n\n if (!vA || !vB) {\n throw new Error(`Vertex index ${vertex.vertexIndex} missing for frame`);\n }\n\n const position = lerpVec3(vA.position, vB.position, blend.lerp);\n const normal = normalizeVec3(lerpVec3(vA.normal, vB.normal, blend.lerp));\n const color = evaluateLighting(normal, position, lighting);\n\n const base = index * 12;\n data[base] = position.x;\n data[base + 1] = position.y;\n data[base + 2] = position.z;\n data[base + 3] = normal.x;\n data[base + 4] = normal.y;\n data[base + 5] = normal.z;\n data[base + 6] = vertex.texCoord[0];\n data[base + 7] = vertex.texCoord[1];\n data[base + 8] = color[0];\n data[base + 9] = color[1];\n data[base + 10] = color[2];\n data[base + 11] = 1;\n });\n\n return data;\n}\n\nexport function interpolateMd3Tag(model: Md3Model, blend: Md3FrameBlend, tagName: string): Md3TagTransform | null {\n const firstFrameTags = model.tags[0];\n if (!firstFrameTags) {\n return null;\n }\n\n const tagIndex = firstFrameTags.findIndex((tag) => tag.name === tagName);\n if (tagIndex === -1) {\n return null;\n }\n\n const tagA = model.tags[blend.currentFrame]?.[tagIndex];\n const tagB = model.tags[blend.nextFrame]?.[tagIndex];\n if (!tagA || !tagB) {\n throw new Error(`Tag ${tagName} is missing for one of the interpolated frames`);\n }\n\n const origin = lerpVec3(tagA.origin, tagB.origin, blend.lerp);\n const axis0 = normalizeVec3(lerpVec3(tagA.axis[0], tagB.axis[0], blend.lerp));\n const axis1 = normalizeVec3(lerpVec3(tagA.axis[1], tagB.axis[1], blend.lerp));\n const axis2 = normalizeVec3(lerpVec3(tagA.axis[2], tagB.axis[2], blend.lerp));\n\n // Re-orthogonalize to match rerelease attachment stability expectations\n const corrected0 = axis0;\n const corrected1 = normalizeVec3({\n x: axis1.x - corrected0.x * (corrected0.x * axis1.x + corrected0.y * axis1.y + corrected0.z * axis1.z),\n y: axis1.y - corrected0.y * (corrected0.x * axis1.x + corrected0.y * axis1.y + corrected0.z * axis1.z),\n z: axis1.z - corrected0.z * (corrected0.x * axis1.x + corrected0.y * axis1.y + corrected0.z * axis1.z),\n });\n const corrected2 = normalizeVec3({\n x: corrected0.y * corrected1.z - corrected0.z * corrected1.y,\n y: corrected0.z * corrected1.x - corrected0.x * corrected1.z,\n z: corrected0.x * corrected1.y - corrected0.y * corrected1.x,\n });\n\n const axis: readonly [Vec3, Vec3, Vec3] = [corrected0, corrected1, corrected2];\n return { origin, axis, matrix: mat4FromBasis(origin, axis) };\n}\n\nexport const MD3_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_color;\n\nuniform mat4 u_modelViewProjection;\n\nout vec2 v_texCoord;\nout vec4 v_color;\n\nvoid main() {\n v_texCoord = a_texCoord;\n v_color = a_color;\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const MD3_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin vec4 v_color;\n\nuniform sampler2D u_diffuseMap;\nuniform vec4 u_tint;\n\nout vec4 o_color;\n\nvoid main() {\n vec4 albedo = texture(u_diffuseMap, v_texCoord) * u_tint;\n o_color = vec4(albedo.rgb * v_color.rgb, albedo.a * v_color.a);\n}`;\n\nexport class Md3SurfaceMesh {\n readonly gl: WebGL2RenderingContext;\n readonly geometry: Md3SurfaceGeometry;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly vertexArray: VertexArray;\n readonly indexCount: number;\n\n constructor(gl: WebGL2RenderingContext, surface: Md3Surface, blend: Md3FrameBlend, lighting?: Md3LightingOptions) {\n this.gl = gl;\n this.geometry = buildMd3SurfaceGeometry(surface);\n this.vertexBuffer = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.indexBuffer = new IndexBuffer(gl, gl.STATIC_DRAW);\n this.vertexArray = new VertexArray(gl);\n this.indexCount = this.geometry.indices.length;\n\n this.vertexArray.configureAttributes(\n [\n { index: 0, size: 3, type: gl.FLOAT, stride: 48, offset: 0 },\n { index: 1, size: 3, type: gl.FLOAT, stride: 48, offset: 12 },\n { index: 2, size: 2, type: gl.FLOAT, stride: 48, offset: 24 },\n { index: 3, size: 4, type: gl.FLOAT, stride: 48, offset: 32 },\n ],\n this.vertexBuffer\n );\n\n this.vertexArray.bind();\n this.indexBuffer.bind();\n this.indexBuffer.upload(this.geometry.indices as unknown as BufferSource, gl.STATIC_DRAW);\n this.update(surface, blend, lighting);\n }\n\n update(surface: Md3Surface, blend: Md3FrameBlend, lighting?: Md3LightingOptions): void {\n const data = buildMd3VertexData(surface, this.geometry, blend, lighting);\n this.vertexBuffer.upload(data as unknown as BufferSource, this.gl.STATIC_DRAW);\n }\n\n bind(): void {\n this.vertexArray.bind();\n this.indexBuffer.bind();\n }\n\n dispose(): void {\n this.vertexBuffer.dispose();\n this.indexBuffer.dispose();\n this.vertexArray.dispose();\n }\n}\n\nexport class Md3ModelMesh {\n readonly surfaces = new Map<string, Md3SurfaceMesh>();\n readonly gl: WebGL2RenderingContext;\n readonly model: Md3Model;\n blend: Md3FrameBlend;\n lighting?: Md3LightingOptions;\n\n constructor(gl: WebGL2RenderingContext, model: Md3Model, blend: Md3FrameBlend, lighting?: Md3LightingOptions) {\n this.gl = gl;\n this.model = model;\n this.blend = blend;\n this.lighting = lighting;\n\n model.surfaces.forEach((surface) => {\n this.surfaces.set(surface.name, new Md3SurfaceMesh(gl, surface, blend, lighting));\n });\n }\n\n update(blend: Md3FrameBlend, lighting?: Md3LightingOptions): void {\n this.blend = blend;\n this.lighting = lighting ?? this.lighting;\n for (const surface of this.model.surfaces) {\n const mesh = this.surfaces.get(surface.name);\n mesh?.update(surface, blend, this.lighting);\n }\n }\n\n dispose(): void {\n for (const mesh of this.surfaces.values()) {\n mesh.dispose();\n }\n this.surfaces.clear();\n }\n}\n\nexport class Md3Pipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformTint: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: MD3_VERTEX_SHADER, fragment: MD3_FRAGMENT_SHADER },\n { a_position: 0, a_normal: 1, a_texCoord: 2, a_color: 3 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformTint = this.program.getUniformLocation('u_tint');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n }\n\n bind(modelViewProjection: Float32List, tint: readonly [number, number, number, number] = [1, 1, 1, 1], sampler = 0): void {\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform4fv(this.uniformTint, new Float32Array(tint));\n this.gl.uniform1i(this.uniformDiffuse, sampler);\n }\n\n drawSurface(mesh: Md3SurfaceMesh, material?: Md3SurfaceMaterial): void {\n const sampler = material?.diffuseSampler ?? 0;\n const tint = material?.tint ?? [1, 1, 1, 1];\n this.gl.uniform4fv(this.uniformTint, new Float32Array(tint));\n this.gl.uniform1i(this.uniformDiffuse, sampler);\n mesh.bind();\n this.gl.drawElements(this.gl.TRIANGLES, mesh.indexCount, this.gl.UNSIGNED_SHORT, 0);\n }\n\n dispose(): void {\n this.program.dispose();\n }\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { IndexBuffer, VertexArray, VertexBuffer } from './resources.js';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport type ParticleBlendMode = 'alpha' | 'additive';\n\nexport interface ParticleSpawnOptions {\n readonly position: Vec3;\n readonly velocity?: Vec3;\n readonly color?: readonly [number, number, number, number];\n readonly size?: number;\n readonly lifetime: number;\n readonly gravity?: number;\n readonly damping?: number;\n readonly bounce?: number;\n readonly blendMode?: ParticleBlendMode;\n /**\n * When true, fades alpha from 1 to 0 across the lifetime instead of remaining constant.\n */\n readonly fade?: boolean;\n}\n\nexport interface ParticleSimulationOptions {\n readonly floorZ?: number;\n}\n\ninterface ParticleMeshBatch {\n readonly blendMode: ParticleBlendMode;\n readonly start: number;\n readonly count: number;\n}\n\nexport interface ParticleMesh {\n readonly vertices: Float32Array;\n readonly indices: Uint16Array;\n readonly batches: readonly ParticleMeshBatch[];\n}\n\nconst DEFAULT_COLOR: [number, number, number, number] = [1, 1, 1, 1];\n\nexport class ParticleSystem {\n readonly maxParticles: number;\n readonly random: () => number;\n\n private readonly alive: Uint8Array;\n private readonly positionX: Float32Array;\n private readonly positionY: Float32Array;\n private readonly positionZ: Float32Array;\n private readonly velocityX: Float32Array;\n private readonly velocityY: Float32Array;\n private readonly velocityZ: Float32Array;\n private readonly colorR: Float32Array;\n private readonly colorG: Float32Array;\n private readonly colorB: Float32Array;\n private readonly colorA: Float32Array;\n private readonly size: Float32Array;\n private readonly lifetime: Float32Array;\n private readonly remaining: Float32Array;\n private readonly gravity: Float32Array;\n private readonly damping: Float32Array;\n private readonly bounce: Float32Array;\n private readonly fade: Uint8Array;\n private readonly blendMode: Uint8Array; // 0 alpha, 1 additive\n\n constructor(maxParticles: number, random: () => number = Math.random) {\n this.maxParticles = maxParticles;\n this.random = random;\n this.alive = new Uint8Array(maxParticles);\n this.positionX = new Float32Array(maxParticles);\n this.positionY = new Float32Array(maxParticles);\n this.positionZ = new Float32Array(maxParticles);\n this.velocityX = new Float32Array(maxParticles);\n this.velocityY = new Float32Array(maxParticles);\n this.velocityZ = new Float32Array(maxParticles);\n this.colorR = new Float32Array(maxParticles);\n this.colorG = new Float32Array(maxParticles);\n this.colorB = new Float32Array(maxParticles);\n this.colorA = new Float32Array(maxParticles);\n this.size = new Float32Array(maxParticles);\n this.lifetime = new Float32Array(maxParticles);\n this.remaining = new Float32Array(maxParticles);\n this.gravity = new Float32Array(maxParticles);\n this.damping = new Float32Array(maxParticles);\n this.bounce = new Float32Array(maxParticles);\n this.fade = new Uint8Array(maxParticles);\n this.blendMode = new Uint8Array(maxParticles);\n }\n\n spawn(options: ParticleSpawnOptions): number | null {\n const index = this.findFreeSlot();\n if (index === -1) {\n return null;\n }\n\n const color = options.color ?? DEFAULT_COLOR;\n const velocity = options.velocity ?? { x: 0, y: 0, z: 0 };\n\n this.alive[index] = 1;\n this.positionX[index] = options.position.x;\n this.positionY[index] = options.position.y;\n this.positionZ[index] = options.position.z;\n this.velocityX[index] = velocity.x;\n this.velocityY[index] = velocity.y;\n this.velocityZ[index] = velocity.z;\n this.colorR[index] = color[0];\n this.colorG[index] = color[1];\n this.colorB[index] = color[2];\n this.colorA[index] = color[3];\n this.size[index] = options.size ?? 2.5;\n this.lifetime[index] = options.lifetime;\n this.remaining[index] = options.lifetime;\n this.gravity[index] = options.gravity ?? 800;\n this.damping[index] = options.damping ?? 0;\n this.bounce[index] = options.bounce ?? 0.25;\n this.fade[index] = options.fade ? 1 : 0;\n this.blendMode[index] = options.blendMode === 'additive' ? 1 : 0;\n\n return index;\n }\n\n update(dt: number, options: ParticleSimulationOptions = {}): void {\n const floorZ = options.floorZ ?? -Infinity;\n for (let i = 0; i < this.maxParticles; i += 1) {\n if (!this.alive[i]) {\n continue;\n }\n\n this.remaining[i] -= dt;\n if (this.remaining[i] <= 0) {\n this.alive[i] = 0;\n continue;\n }\n\n const damping = Math.max(0, 1 - this.damping[i] * dt);\n this.velocityX[i] *= damping;\n this.velocityY[i] *= damping;\n this.velocityZ[i] = this.velocityZ[i] * damping - this.gravity[i] * dt;\n\n this.positionX[i] += this.velocityX[i] * dt;\n this.positionY[i] += this.velocityY[i] * dt;\n this.positionZ[i] += this.velocityZ[i] * dt;\n\n if (this.positionZ[i] < floorZ) {\n this.positionZ[i] = floorZ;\n this.velocityZ[i] = -this.velocityZ[i] * this.bounce[i];\n this.velocityX[i] *= 0.7;\n this.velocityY[i] *= 0.7;\n }\n }\n }\n\n killAll(): void {\n this.alive.fill(0);\n }\n\n aliveCount(): number {\n let count = 0;\n for (let i = 0; i < this.maxParticles; i += 1) {\n if (this.alive[i]) {\n count += 1;\n }\n }\n return count;\n }\n\n getState(index: number): {\n readonly alive: boolean;\n readonly position: Vec3;\n readonly velocity: Vec3;\n readonly remaining: number;\n readonly color: readonly [number, number, number, number];\n readonly size: number;\n readonly blendMode: ParticleBlendMode;\n } {\n return {\n alive: this.alive[index] === 1,\n position: {\n x: this.positionX[index],\n y: this.positionY[index],\n z: this.positionZ[index],\n },\n velocity: {\n x: this.velocityX[index],\n y: this.velocityY[index],\n z: this.velocityZ[index],\n },\n remaining: this.remaining[index],\n color: [this.colorR[index], this.colorG[index], this.colorB[index], this.colorA[index]],\n size: this.size[index],\n blendMode: this.blendMode[index] === 1 ? 'additive' : 'alpha',\n };\n }\n\n buildMesh(viewRight: Vec3, viewUp: Vec3): ParticleMesh {\n const vertices: number[] = [];\n const indices: number[] = [];\n const batches: ParticleMeshBatch[] = [];\n\n const buildBatch = (mode: ParticleBlendMode): void => {\n const startIndex = indices.length;\n let particleCount = 0;\n for (let i = 0; i < this.maxParticles; i += 1) {\n if (!this.alive[i]) {\n continue;\n }\n if ((mode === 'additive' ? 1 : 0) !== this.blendMode[i]) {\n continue;\n }\n\n particleCount += 1;\n const baseVertex = vertices.length / 9;\n const size = this.size[i] * 0.5;\n const fade = this.fade[i] ? Math.max(this.remaining[i] / this.lifetime[i], 0) : 1;\n const colorScale = this.blendMode[i] === 1 ? 1.2 : 1;\n\n const cR = this.colorR[i] * colorScale;\n const cG = this.colorG[i] * colorScale;\n const cB = this.colorB[i] * colorScale;\n const cA = this.colorA[i] * fade;\n\n const px = this.positionX[i];\n const py = this.positionY[i];\n const pz = this.positionZ[i];\n\n const rightX = viewRight.x * size;\n const rightY = viewRight.y * size;\n const rightZ = viewRight.z * size;\n const upX = viewUp.x * size;\n const upY = viewUp.y * size;\n const upZ = viewUp.z * size;\n\n const corners: readonly Vec3[] = [\n { x: px - rightX - upX, y: py - rightY - upY, z: pz - rightZ - upZ },\n { x: px + rightX - upX, y: py + rightY - upY, z: pz + rightZ - upZ },\n { x: px - rightX + upX, y: py - rightY + upY, z: pz - rightZ + upZ },\n { x: px + rightX + upX, y: py + rightY + upY, z: pz + rightZ + upZ },\n ];\n\n const uvs: readonly [number, number][] = [\n [0, 1],\n [1, 1],\n [0, 0],\n [1, 0],\n ];\n\n corners.forEach((corner, cornerIndex) => {\n vertices.push(\n corner.x,\n corner.y,\n corner.z,\n uvs[cornerIndex]?.[0] ?? 0,\n uvs[cornerIndex]?.[1] ?? 0,\n cR,\n cG,\n cB,\n cA\n );\n });\n\n indices.push(baseVertex, baseVertex + 1, baseVertex + 2, baseVertex + 2, baseVertex + 1, baseVertex + 3);\n }\n\n if (particleCount > 0) {\n batches.push({ blendMode: mode, start: startIndex, count: indices.length - startIndex });\n }\n };\n\n buildBatch('alpha');\n buildBatch('additive');\n\n return { vertices: new Float32Array(vertices), indices: new Uint16Array(indices), batches };\n }\n\n private findFreeSlot(): number {\n for (let i = 0; i < this.maxParticles; i += 1) {\n if (!this.alive[i]) {\n return i;\n }\n }\n return -1;\n }\n}\n\nexport const PARTICLE_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_uv;\nlayout(location = 2) in vec4 a_color;\n\nuniform mat4 u_viewProjection;\n\nout vec2 v_uv;\nout vec4 v_color;\n\nvoid main() {\n v_uv = a_uv;\n v_color = a_color;\n gl_Position = u_viewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const PARTICLE_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec2 v_uv;\nin vec4 v_color;\n\nout vec4 o_color;\n\nvoid main() {\n float dist = distance(v_uv, vec2(0.5));\n float alpha = v_color.a * (1.0 - smoothstep(0.35, 0.5, dist));\n o_color = vec4(v_color.rgb, alpha);\n}`;\n\nexport interface ParticleRenderOptions {\n readonly viewProjection: Float32List;\n readonly viewRight: Vec3;\n readonly viewUp: Vec3;\n}\n\nexport class ParticleRenderer {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n readonly system: ParticleSystem;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly vertexArray: VertexArray;\n\n private vertexCapacity = 0;\n private indexCapacity = 0;\n\n constructor(gl: WebGL2RenderingContext, system: ParticleSystem) {\n this.gl = gl;\n this.system = system;\n this.program = ShaderProgram.create(gl, { vertex: PARTICLE_VERTEX_SHADER, fragment: PARTICLE_FRAGMENT_SHADER });\n this.vertexBuffer = new VertexBuffer(gl, gl.DYNAMIC_DRAW);\n this.indexBuffer = new IndexBuffer(gl, gl.DYNAMIC_DRAW);\n this.vertexArray = new VertexArray(gl);\n this.vertexArray.configureAttributes(\n [\n { index: 0, size: 3, type: gl.FLOAT, stride: 36, offset: 0 },\n { index: 1, size: 2, type: gl.FLOAT, stride: 36, offset: 12 },\n { index: 2, size: 4, type: gl.FLOAT, stride: 36, offset: 20 },\n ],\n this.vertexBuffer\n );\n }\n\n render(options: ParticleRenderOptions): void {\n const mesh = this.system.buildMesh(options.viewRight, options.viewUp);\n if (mesh.indices.length === 0) {\n return;\n }\n\n const vertexData = mesh.vertices as unknown as BufferSource;\n if (mesh.vertices.byteLength > this.vertexCapacity) {\n this.vertexCapacity = mesh.vertices.byteLength;\n this.vertexBuffer.upload(vertexData, this.gl.DYNAMIC_DRAW);\n } else {\n this.vertexBuffer.update(vertexData);\n }\n\n const indexData = mesh.indices as unknown as BufferSource;\n if (mesh.indices.byteLength > this.indexCapacity) {\n this.indexCapacity = mesh.indices.byteLength;\n this.indexBuffer.upload(indexData, this.gl.DYNAMIC_DRAW);\n } else {\n this.indexBuffer.update(indexData);\n }\n\n this.gl.depthMask(false);\n this.program.use();\n const vp = this.program.getUniformLocation('u_viewProjection');\n this.gl.uniformMatrix4fv(vp, false, options.viewProjection);\n this.vertexArray.bind();\n\n for (const batch of mesh.batches) {\n if (batch.blendMode === 'additive') {\n this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE);\n } else {\n this.gl.blendFuncSeparate(\n this.gl.SRC_ALPHA,\n this.gl.ONE_MINUS_SRC_ALPHA,\n this.gl.ONE,\n this.gl.ONE_MINUS_SRC_ALPHA\n );\n }\n this.gl.drawElements(this.gl.TRIANGLES, batch.count, this.gl.UNSIGNED_SHORT, batch.start * 2);\n }\n\n this.gl.depthMask(true);\n }\n\n dispose(): void {\n this.program.dispose();\n this.vertexBuffer.dispose();\n this.indexBuffer.dispose();\n this.vertexArray.dispose();\n }\n}\n\nexport interface ParticleEffectContext {\n readonly system: ParticleSystem;\n readonly origin: Vec3;\n readonly normal?: Vec3;\n readonly direction?: Vec3;\n}\n\nexport function spawnBulletImpact(context: ParticleEffectContext): void {\n const { system, origin, normal = { x: 0, y: 0, z: 1 } } = context;\n for (let i = 0; i < 12; i += 1) {\n const speed = 200 + system.random() * 180;\n const spread = system.random() * 0.35;\n system.spawn({\n position: origin,\n velocity: {\n x: normal.x * speed + (system.random() - 0.5) * 80,\n y: normal.y * speed + (system.random() - 0.5) * 80,\n z: Math.max(normal.z * speed, 120) + spread * 80,\n },\n color: [1, 0.8, 0.4, 1],\n size: 2.5,\n lifetime: 0.45 + system.random() * 0.1,\n gravity: 600,\n damping: 2,\n bounce: 0.45,\n blendMode: 'additive',\n fade: true,\n });\n }\n\n for (let i = 0; i < 8; i += 1) {\n system.spawn({\n position: origin,\n velocity: { x: (system.random() - 0.5) * 40, y: (system.random() - 0.5) * 40, z: 80 + system.random() * 40 },\n color: [0.45, 0.45, 0.45, 0.75],\n size: 6,\n lifetime: 0.6,\n gravity: 200,\n damping: 4,\n bounce: 0.15,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n\nexport function spawnExplosion(context: ParticleEffectContext): void {\n const { system, origin } = context;\n for (let i = 0; i < 40; i += 1) {\n const theta = system.random() * Math.PI * 2;\n const phi = Math.acos(2 * system.random() - 1);\n const speed = 220 + system.random() * 260;\n const dir = {\n x: Math.sin(phi) * Math.cos(theta),\n y: Math.sin(phi) * Math.sin(theta),\n z: Math.cos(phi),\n };\n system.spawn({\n position: origin,\n velocity: { x: dir.x * speed, y: dir.y * speed, z: dir.z * speed },\n color: [1, 0.6, 0.2, 1],\n size: 5,\n lifetime: 0.9,\n gravity: 700,\n damping: 1,\n bounce: 0.35,\n blendMode: 'additive',\n fade: true,\n });\n }\n\n for (let i = 0; i < 16; i += 1) {\n system.spawn({\n position: origin,\n velocity: { x: (system.random() - 0.5) * 30, y: (system.random() - 0.5) * 30, z: 120 + system.random() * 120 },\n color: [0.25, 0.25, 0.25, 0.9],\n size: 12,\n lifetime: 1.2,\n gravity: 300,\n damping: 3,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n\nexport function spawnBlood(context: ParticleEffectContext): void {\n const { system, origin, direction = { x: 0, y: 0, z: 1 } } = context;\n for (let i = 0; i < 24; i += 1) {\n const speed = 120 + system.random() * 180;\n system.spawn({\n position: origin,\n velocity: {\n x: direction.x * speed + (system.random() - 0.5) * 70,\n y: direction.y * speed + (system.random() - 0.5) * 70,\n z: direction.z * speed + system.random() * 80,\n },\n color: [0.6, 0, 0, 0.95],\n size: 3,\n lifetime: 0.8,\n gravity: 900,\n damping: 1,\n bounce: 0.2,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n\nexport function spawnTeleportFlash(context: ParticleEffectContext): void {\n const { system, origin } = context;\n for (let i = 0; i < 30; i += 1) {\n const angle = system.random() * Math.PI * 2;\n const radius = 8 + system.random() * 8;\n system.spawn({\n position: origin,\n velocity: { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius, z: 100 + system.random() * 80 },\n color: [0.4, 0.6, 1, 0.9],\n size: 4,\n lifetime: 0.5,\n gravity: 300,\n damping: 2,\n blendMode: 'additive',\n fade: true,\n });\n }\n}\n\nexport function spawnMuzzleFlash(context: ParticleEffectContext): void {\n const { system, origin, direction = { x: 1, y: 0, z: 0 } } = context;\n for (let i = 0; i < 10; i += 1) {\n const speed = 350 + system.random() * 100;\n system.spawn({\n position: origin,\n velocity: {\n x: direction.x * speed + (system.random() - 0.5) * 30,\n y: direction.y * speed + (system.random() - 0.5) * 30,\n z: direction.z * speed + (system.random() - 0.5) * 30,\n },\n color: [1, 0.8, 0.3, 1],\n size: 3,\n lifetime: 0.25,\n gravity: 200,\n damping: 1,\n blendMode: 'additive',\n fade: true,\n });\n }\n}\n\nexport function spawnTrail(context: ParticleEffectContext): void {\n const { system, origin, direction = { x: 0, y: 0, z: 0 } } = context;\n for (let i = 0; i < 6; i += 1) {\n system.spawn({\n position: {\n x: origin.x + direction.x * i * 2,\n y: origin.y + direction.y * i * 2,\n z: origin.z + direction.z * i * 2,\n },\n velocity: { x: (system.random() - 0.5) * 15, y: (system.random() - 0.5) * 15, z: 20 + system.random() * 15 },\n color: [0.6, 0.6, 0.6, 0.8],\n size: 2.2,\n lifetime: 0.6,\n gravity: 200,\n damping: 1.5,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n","import { BinaryStream } from '@quake2ts/shared';\n\nexport interface DemoMessageBlock {\n length: number;\n data: BinaryStream;\n}\n\nexport class DemoReader {\n private buffer: ArrayBuffer;\n private view: DataView;\n private offset: number;\n\n constructor(buffer: ArrayBuffer) {\n this.buffer = buffer;\n this.view = new DataView(buffer);\n this.offset = 0;\n }\n\n /**\n * Checks if there are more blocks to read.\n */\n public hasMore(): boolean {\n return this.offset < this.buffer.byteLength;\n }\n\n /**\n * Reads the next message block from the demo file.\n * Format is [Length (4 bytes)] + [Message Block (Length bytes)].\n * Returns null if end of file or incomplete block.\n */\n public readNextBlock(): DemoMessageBlock | null {\n if (this.offset + 4 > this.buffer.byteLength) {\n // Not enough data for length\n return null;\n }\n\n // Read length (little endian)\n const length = this.view.getInt32(this.offset, true);\n this.offset += 4;\n\n if (length < 0 || length > 0x40000) { // 256k sanity check (MAX_MSGLEN is usually 1400, but demo blocks can be large)\n // Sanity check failed or negative length\n console.warn(`DemoReader: Invalid block length ${length} at offset ${this.offset - 4}`);\n return null;\n }\n\n if (this.offset + length > this.buffer.byteLength) {\n // Not enough data for the block body\n console.warn(`DemoReader: Incomplete block. Expected ${length} bytes, but only ${this.buffer.byteLength - this.offset} remain.`);\n return null;\n }\n\n // Create a view for the block data\n // Slice creates a copy, which is safer but slower.\n // For now, let's slice to ensure the BinaryStream is isolated.\n const blockData = this.buffer.slice(this.offset, this.offset + length);\n this.offset += length;\n\n return {\n length,\n data: new BinaryStream(blockData)\n };\n }\n\n /**\n * Resets the reader to the beginning.\n */\n public reset(): void {\n this.offset = 0;\n }\n\n public getOffset(): number {\n return this.offset;\n }\n}\n","import { BinaryStream } from '@quake2ts/shared';\nimport { ServerCommand } from '@quake2ts/shared';\nimport { Vec3 } from '@quake2ts/shared';\nimport { TempEntity } from '@quake2ts/shared';\n\n// Constants from Q2 source\nconst U_ORIGIN1 = (1 << 0);\nconst U_ORIGIN2 = (1 << 1);\nconst U_ANGLE2 = (1 << 2);\nconst U_ANGLE3 = (1 << 3);\nconst U_FRAME8 = (1 << 4);\nconst U_EVENT = (1 << 5);\nconst U_REMOVE = (1 << 6);\nconst U_MOREBITS1 = (1 << 7);\n\nconst U_NUMBER16 = (1 << 8);\nconst U_ORIGIN3 = (1 << 9);\nconst U_ANGLE1 = (1 << 10);\nconst U_MODEL = (1 << 11);\nconst U_RENDERFX8 = (1 << 12);\nconst U_EFFECTS8 = (1 << 14);\nconst U_MOREBITS2 = (1 << 15);\n\nconst U_SKIN8 = (1 << 16);\nconst U_FRAME16 = (1 << 17);\nconst U_RENDERFX16 = (1 << 18);\nconst U_EFFECTS16 = (1 << 19);\nconst U_MODEL2 = (1 << 20);\nconst U_MODEL3 = (1 << 21);\nconst U_MODEL4 = (1 << 22);\nconst U_MOREBITS3 = (1 << 23);\n\nconst U_OLDORIGIN = (1 << 24);\nconst U_SKIN16 = (1 << 25);\nconst U_SOUND = (1 << 26);\nconst U_SOLID = (1 << 27);\n\n// Mutable Vec3 for internal use\ninterface MutableVec3 {\n x: number;\n y: number;\n z: number;\n}\n\nexport interface EntityState {\n number: number;\n modelindex: number;\n modelindex2: number;\n modelindex3: number;\n modelindex4: number;\n frame: number;\n skinnum: number;\n effects: number;\n renderfx: number;\n origin: MutableVec3;\n old_origin: MutableVec3;\n angles: MutableVec3;\n sound: number;\n event: number;\n solid: number;\n}\n\nexport const createEmptyEntityState = (): EntityState => ({\n number: 0,\n modelindex: 0,\n modelindex2: 0,\n modelindex3: 0,\n modelindex4: 0,\n frame: 0,\n skinnum: 0,\n effects: 0,\n renderfx: 0,\n origin: { x: 0, y: 0, z: 0 },\n old_origin: { x: 0, y: 0, z: 0 },\n angles: { x: 0, y: 0, z: 0 },\n sound: 0,\n event: 0,\n solid: 0\n});\n\nexport class NetworkMessageParser {\n private stream: BinaryStream;\n\n constructor(stream: BinaryStream) {\n this.stream = stream;\n }\n\n public parseMessage(): void {\n while (this.stream.hasMore()) {\n const cmd = this.stream.readByte();\n\n if (cmd === -1) {\n break;\n }\n\n switch (cmd) {\n case ServerCommand.nop:\n break;\n case ServerCommand.disconnect:\n console.log(\"Server disconnected\");\n break;\n case ServerCommand.reconnect:\n console.log(\"Server reconnect\");\n break;\n case ServerCommand.print:\n const printId = this.stream.readByte();\n const printMsg = this.stream.readString();\n console.log(`[Server Print ${printId}]: ${printMsg}`);\n break;\n case ServerCommand.serverdata:\n this.parseServerData();\n break;\n case ServerCommand.configstring:\n this.parseConfigString();\n break;\n case ServerCommand.spawnbaseline:\n this.parseSpawnBaseline();\n break;\n case ServerCommand.centerprint:\n const centerMsg = this.stream.readString();\n console.log(`[Center Print]: ${centerMsg}`);\n break;\n case ServerCommand.download:\n this.parseDownload();\n break;\n case ServerCommand.frame:\n this.parseFrame();\n break;\n case ServerCommand.packetentities:\n this.parsePacketEntities(false);\n break;\n case ServerCommand.deltapacketentities:\n this.parsePacketEntities(true);\n break;\n case ServerCommand.stufftext:\n const text = this.stream.readString();\n console.log(`[StuffText]: ${text}`);\n break;\n case ServerCommand.layout:\n const layout = this.stream.readString();\n break;\n case ServerCommand.inventory:\n this.parseInventory();\n break;\n case ServerCommand.sound:\n this.parseSound();\n break;\n case ServerCommand.muzzleflash:\n this.parseMuzzleFlash();\n break;\n case ServerCommand.muzzleflash2:\n this.parseMuzzleFlash2();\n break;\n case ServerCommand.temp_entity:\n this.parseTempEntity();\n break;\n default:\n console.warn(`Unknown server command: ${cmd}`);\n // If we hit an unknown command, we are likely desynced as we don't know the length to skip.\n return;\n }\n }\n }\n\n private parseServerData(): void {\n const protocol = this.stream.readLong();\n const serverCount = this.stream.readLong();\n const attractLoop = this.stream.readByte();\n const gameDir = this.stream.readString();\n const playerNum = this.stream.readShort();\n const levelName = this.stream.readString();\n\n console.log(`Server Data: Protocol ${protocol}, Level ${levelName}, GameDir ${gameDir}`);\n }\n\n private parseConfigString(): void {\n const index = this.stream.readShort();\n const str = this.stream.readString();\n // In a real implementation, this would update the client's configstring table\n }\n\n private parseDownload(): void {\n const size = this.stream.readShort();\n const percent = this.stream.readByte();\n if (size > 0) {\n this.stream.readData(size);\n }\n }\n\n private parseInventory(): void {\n // MAX_ITEMS is 256 in q_shared.h usually\n // In cl_parse.c CL_ParseInventory:\n // int i;\n // for (i=0 ; i<MAX_ITEMS ; i++)\n // cl.inventory[i] = MSG_ReadShort (&net_message);\n const MAX_ITEMS = 256;\n for (let i = 0; i < MAX_ITEMS; i++) {\n this.stream.readShort();\n }\n }\n\n private parseSound(): void {\n const flags = this.stream.readByte();\n const soundNum = this.stream.readByte();\n\n if (flags & 1) { // SND_VOLUME\n this.stream.readByte();\n }\n if (flags & 2) { // SND_ATTENUATION\n this.stream.readByte();\n }\n if (flags & 16) { // SND_OFFSET\n this.stream.readByte();\n }\n if (flags & 8) { // SND_ENT\n this.stream.readShort();\n }\n if (flags & 4) { // SND_POS\n // We need a temporary object to read into\n const pos = { x: 0, y: 0, z: 0 };\n this.stream.readPos(pos);\n }\n }\n\n private parseMuzzleFlash(): void {\n const ent = this.stream.readShort();\n const weapon = this.stream.readByte();\n }\n\n private parseMuzzleFlash2(): void {\n const ent = this.stream.readShort();\n const weapon = this.stream.readByte();\n }\n\n private parseTempEntity(): void {\n const type = this.stream.readByte();\n\n // Placeholder vars\n const pos = { x: 0, y: 0, z: 0 };\n const pos2 = { x: 0, y: 0, z: 0 };\n const dir = { x: 0, y: 0, z: 0 };\n\n switch (type) {\n case TempEntity.BLOOD:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.GUNSHOT:\n case TempEntity.SPARKS:\n case TempEntity.BULLET_SPARKS:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.SCREEN_SPARKS:\n case TempEntity.SHIELD_SPARKS:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.SHOTGUN:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.SPLASH:\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // r\n break;\n\n case TempEntity.LASER_SPARKS:\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // color\n break;\n\n case TempEntity.BLUEHYPERBLASTER:\n this.stream.readPos(pos);\n this.stream.readPos(dir); // NOTE: original uses MSG_ReadPos for dir here\n break;\n\n case TempEntity.BLASTER:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.RAILTRAIL:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n break;\n\n case TempEntity.EXPLOSION2:\n case TempEntity.GRENADE_EXPLOSION:\n case TempEntity.GRENADE_EXPLOSION_WATER:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.PLASMA_EXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.EXPLOSION1:\n case TempEntity.EXPLOSION1_BIG:\n case TempEntity.ROCKET_EXPLOSION:\n case TempEntity.ROCKET_EXPLOSION_WATER:\n case TempEntity.EXPLOSION1_NP:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.BFG_EXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.BFG_BIGEXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.BFG_LASER:\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n break;\n\n case TempEntity.BUBBLETRAIL:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n break;\n\n case TempEntity.PARASITE_ATTACK:\n case TempEntity.MEDIC_CABLE_ATTACK:\n this.stream.readShort(); // ent\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n break;\n\n case TempEntity.BOSSTPORT:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.GRAPPLE_CABLE:\n this.stream.readShort(); // ent\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n this.stream.readPos(dir); // offset (reusing dir var)\n break;\n\n case TempEntity.WELDING_SPARKS:\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // color\n break;\n\n case TempEntity.GREENBLOOD:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.TUNNEL_SPARKS:\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // color\n break;\n\n case TempEntity.BLASTER2:\n case TempEntity.FLECHETTE:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.LIGHTNING:\n this.stream.readShort(); // srcEnt\n this.stream.readShort(); // destEnt\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n break;\n\n case TempEntity.DEBUGTRAIL:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n break;\n\n case TempEntity.PLAIN_EXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.FLASHLIGHT:\n this.stream.readPos(pos);\n this.stream.readShort(); // ent\n break;\n\n case TempEntity.FORCEWALL:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n this.stream.readByte(); // color\n break;\n\n case TempEntity.HEATBEAM:\n this.stream.readShort(); // ent\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n this.stream.readPos(dir); // offset\n break;\n\n case TempEntity.MONSTER_HEATBEAM:\n this.stream.readShort(); // ent\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n this.stream.readPos(dir); // offset\n break;\n\n case TempEntity.HEATBEAM_SPARKS:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.HEATBEAM_STEAM:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.STEAM:\n const steamId = this.stream.readShort();\n if (steamId !== -1) {\n this.stream.readByte(); // count\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // r\n this.stream.readShort(); // magnitude\n this.stream.readLong(); // endtime (delta?) or something\n } else {\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // r\n this.stream.readShort(); // magnitude\n }\n break;\n\n case TempEntity.BUBBLETRAIL2:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n break;\n\n case TempEntity.MOREBLOOD:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.CHAINFIST_SMOKE:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.ELECTRIC_SPARKS:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.TRACKER_EXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.TELEPORT_EFFECT:\n case TempEntity.DBALL_GOAL:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.WIDOWBEAMOUT:\n const wbId = this.stream.readShort();\n // Logic from CL_ParseWidow:\n // if free sustain -> reads id, pos, endtime=time+2100...\n // else -> read pos\n // BUT WE ARE PARSING, NOT SIMULATING. We must read exactly what is on the wire.\n // CL_ParseWidow logic:\n // id = MSG_ReadShort\n // if (free_sustain) { MSG_ReadPos... } else { MSG_ReadPos... }\n // It always reads a pos.\n this.stream.readPos(pos);\n break;\n\n case TempEntity.NUKEBLAST:\n // Logic from CL_ParseNuke:\n // Always reads pos.\n this.stream.readPos(pos);\n break;\n\n case TempEntity.WIDOWSPLASH:\n this.stream.readPos(pos);\n break;\n\n default:\n console.warn(`CL_ParseTEnt: bad type ${type}`);\n break;\n }\n }\n\n private parseSpawnBaseline(): void {\n const bits = this.parseEntityBits();\n // We would use this to update the baseline table\n // const entityState = createEmptyEntityState();\n // this.parseDelta(createEmptyEntityState(), entityState, bits.number, bits.bits);\n\n // For now just consume the delta\n this.parseDelta(createEmptyEntityState(), createEmptyEntityState(), bits.number, bits.bits);\n }\n\n private parseFrame(): void {\n const serverFrame = this.stream.readLong();\n const deltaFrame = this.stream.readLong();\n const surpressCount = this.stream.readByte(); // Only if protocol != 26? In cl_parse.c: if (cls.serverProtocol != 26) cl.surpressCount = MSG_ReadByte...\n // But we don't track protocol version here yet. Standard Q2 is 34. So we read it.\n\n const areaBytes = this.stream.readByte();\n this.stream.readData(areaBytes);\n\n // The frame command is followed by other commands like svc_playerinfo and svc_packetentities inside the same message block usually?\n // No, svc_frame is a command inside the loop.\n // cl_parse.c CL_ParseFrame calls CL_ParsePlayerstate etc, but those read from net_message.\n // Wait, in CL_ParseFrame, it reads area bits, THEN:\n // cmd = MSG_ReadByte\n // if (cmd != svc_playerinfo) Error\n // ...\n // cmd = MSG_ReadByte\n // if (cmd != svc_packetentities) Error\n\n // So yes, `svc_frame` implies we *expect* `svc_playerinfo` and `svc_packetentities` next.\n // But my main loop dispatch handles them as separate commands if I return?\n // No, `CL_ParseFrame` *consumes* them.\n\n // So I must consume them here.\n\n // Player Info\n const piCmd = this.stream.readByte();\n if (piCmd !== ServerCommand.playerinfo) {\n throw new Error(`Expected svc_playerinfo after svc_frame, got ${piCmd}`);\n }\n this.parsePlayerState();\n\n // Packet Entities\n const peCmd = this.stream.readByte();\n if (peCmd !== ServerCommand.packetentities && peCmd !== ServerCommand.deltapacketentities) {\n throw new Error(`Expected svc_packetentities after svc_playerinfo, got ${peCmd}`);\n }\n this.parsePacketEntities(peCmd === ServerCommand.deltapacketentities);\n }\n\n private parsePlayerState(): void {\n const flags = this.stream.readShort();\n\n // PS_M_TYPE (1<<0)\n if (flags & 1) this.stream.readByte();\n\n // PS_M_ORIGIN (1<<1)\n if (flags & 2) {\n this.stream.readShort();\n this.stream.readShort();\n this.stream.readShort();\n }\n\n // PS_M_VELOCITY (1<<2)\n if (flags & 4) {\n this.stream.readShort();\n this.stream.readShort();\n this.stream.readShort();\n }\n\n // PS_M_TIME (1<<3)\n if (flags & 8) this.stream.readByte();\n\n // PS_M_FLAGS (1<<4)\n if (flags & 16) this.stream.readByte();\n\n // PS_M_GRAVITY (1<<5)\n if (flags & 32) this.stream.readShort();\n\n // PS_M_DELTA_ANGLES (1<<6)\n if (flags & 64) {\n this.stream.readShort();\n this.stream.readShort();\n this.stream.readShort();\n }\n\n // PS_VIEWOFFSET (1<<7)\n if (flags & 128) {\n this.stream.readChar();\n this.stream.readChar();\n this.stream.readChar();\n }\n\n // PS_VIEWANGLES (1<<8)\n if (flags & 256) {\n this.stream.readAngle16();\n this.stream.readAngle16();\n this.stream.readAngle16();\n }\n\n // PS_KICKANGLES (1<<9)\n if (flags & 512) {\n this.stream.readChar();\n this.stream.readChar();\n this.stream.readChar();\n }\n\n // PS_BLEND (1<<10) (Note: skipped WEAPONINDEX/FRAME in headers, check full list order)\n // Header says:\n // #define\tPS_WEAPONINDEX\t\t(1<<12)\n // #define\tPS_WEAPONFRAME\t\t(1<<13)\n // #define\tPS_BLEND\t\t\t(1<<10)\n // #define\tPS_FOV\t\t\t\t(1<<11)\n // #define\tPS_RDFLAGS\t\t\t(1<<14)\n\n // Order in CL_ParsePlayerstate:\n // WEAPONINDEX\n if (flags & 4096) this.stream.readByte();\n\n // WEAPONFRAME\n if (flags & 8192) {\n this.stream.readByte(); // frame\n this.stream.readChar(); // offset x\n this.stream.readChar(); // offset y\n this.stream.readChar(); // offset z\n this.stream.readChar(); // angles x\n this.stream.readChar(); // angles y\n this.stream.readChar(); // angles z\n }\n\n // BLEND\n if (flags & 1024) {\n this.stream.readByte();\n this.stream.readByte();\n this.stream.readByte();\n this.stream.readByte();\n }\n\n // FOV\n if (flags & 2048) this.stream.readByte();\n\n // RDFLAGS\n if (flags & 16384) this.stream.readByte();\n\n // STATS\n const statbits = this.stream.readLong();\n for (let i = 0; i < 32; i++) {\n if (statbits & (1 << i)) {\n this.stream.readShort();\n }\n }\n }\n\n private parsePacketEntities(delta: boolean): void {\n // In CL_ParsePacketEntities\n while (true) {\n const bits = this.parseEntityBits();\n if (bits.number === 0) {\n break;\n }\n\n // Consume the delta\n this.parseDelta(createEmptyEntityState(), createEmptyEntityState(), bits.number, bits.bits);\n }\n }\n\n private parseEntityBits(): { number: number; bits: number } {\n let total = this.stream.readByte();\n if (total & U_MOREBITS1) {\n total |= (this.stream.readByte() << 8);\n }\n if (total & U_MOREBITS2) {\n total |= (this.stream.readByte() << 16);\n }\n if (total & U_MOREBITS3) {\n total |= (this.stream.readByte() << 24);\n }\n\n let number: number;\n if (total & U_NUMBER16) {\n number = this.stream.readShort();\n } else {\n number = this.stream.readByte();\n }\n\n return { number, bits: total };\n }\n\n private parseDelta(from: EntityState, to: EntityState, number: number, bits: number): void {\n // Copy 'from' to 'to'\n to.number = from.number;\n to.modelindex = from.modelindex;\n to.modelindex2 = from.modelindex2;\n to.modelindex3 = from.modelindex3;\n to.modelindex4 = from.modelindex4;\n to.frame = from.frame;\n to.skinnum = from.skinnum;\n to.effects = from.effects;\n to.renderfx = from.renderfx;\n to.origin.x = from.origin.x; to.origin.y = from.origin.y; to.origin.z = from.origin.z;\n to.old_origin.x = from.origin.x; to.old_origin.y = from.origin.y; to.old_origin.z = from.origin.z;\n to.angles.x = from.angles.x; to.angles.y = from.angles.y; to.angles.z = from.angles.z;\n to.sound = from.sound;\n to.event = from.event;\n to.solid = from.solid;\n\n to.number = number;\n\n if (bits & U_MODEL) to.modelindex = this.stream.readByte();\n if (bits & U_MODEL2) to.modelindex2 = this.stream.readByte();\n if (bits & U_MODEL3) to.modelindex3 = this.stream.readByte();\n if (bits & U_MODEL4) to.modelindex4 = this.stream.readByte();\n\n if (bits & U_FRAME8) to.frame = this.stream.readByte();\n if (bits & U_FRAME16) to.frame = this.stream.readShort();\n\n if ((bits & U_SKIN8) && (bits & U_SKIN16)) {\n to.skinnum = this.stream.readLong();\n } else if (bits & U_SKIN8) {\n to.skinnum = this.stream.readByte();\n } else if (bits & U_SKIN16) {\n to.skinnum = this.stream.readShort();\n }\n\n if ((bits & U_EFFECTS8) && (bits & U_EFFECTS16)) {\n to.effects = this.stream.readLong();\n } else if (bits & U_EFFECTS8) {\n to.effects = this.stream.readByte();\n } else if (bits & U_EFFECTS16) {\n to.effects = this.stream.readShort();\n }\n\n if ((bits & U_RENDERFX8) && (bits & U_RENDERFX16)) {\n to.renderfx = this.stream.readLong();\n } else if (bits & U_RENDERFX8) {\n to.renderfx = this.stream.readByte();\n } else if (bits & U_RENDERFX16) {\n to.renderfx = this.stream.readShort();\n }\n\n if (bits & U_ORIGIN1) to.origin.x = this.stream.readCoord();\n if (bits & U_ORIGIN2) to.origin.y = this.stream.readCoord();\n if (bits & U_ORIGIN3) to.origin.z = this.stream.readCoord();\n\n if (bits & U_ANGLE1) to.angles.x = this.stream.readAngle();\n if (bits & U_ANGLE2) to.angles.y = this.stream.readAngle();\n if (bits & U_ANGLE3) to.angles.z = this.stream.readAngle();\n\n if (bits & U_OLDORIGIN) {\n this.stream.readPos(to.old_origin);\n }\n\n if (bits & U_SOUND) to.sound = this.stream.readByte();\n\n if (bits & U_EVENT) {\n to.event = this.stream.readByte();\n } else {\n to.event = 0;\n }\n\n if (bits & U_SOLID) to.solid = this.stream.readShort();\n }\n}\n","import { DemoReader } from './demoReader.js';\nimport { NetworkMessageParser } from './parser.js';\n\nexport enum PlaybackState {\n Stopped,\n Playing,\n Paused,\n Finished\n}\n\nexport class DemoPlaybackController {\n private reader: DemoReader | null = null;\n private state: PlaybackState = PlaybackState.Stopped;\n private playbackSpeed: number = 1.0;\n\n // Timing\n private accumulatedTime: number = 0;\n private frameDuration: number = 100; // ms (10Hz default)\n\n constructor() {}\n\n public loadDemo(buffer: ArrayBuffer) {\n this.reader = new DemoReader(buffer);\n this.state = PlaybackState.Stopped;\n this.accumulatedTime = 0;\n }\n\n public play() {\n if (this.reader) {\n this.state = PlaybackState.Playing;\n }\n }\n\n public pause() {\n if (this.state === PlaybackState.Playing) {\n this.state = PlaybackState.Paused;\n }\n }\n\n public stop() {\n this.state = PlaybackState.Stopped;\n if (this.reader) {\n this.reader.reset();\n }\n this.accumulatedTime = 0;\n }\n\n public update(dt: number) {\n if (this.state !== PlaybackState.Playing || !this.reader) {\n return;\n }\n\n this.accumulatedTime += dt * 1000 * this.playbackSpeed; // Convert to ms\n\n while (this.accumulatedTime >= this.frameDuration) {\n if (!this.reader.hasMore()) {\n this.state = PlaybackState.Finished;\n return;\n }\n\n const block = this.reader.readNextBlock();\n if (!block) {\n this.state = PlaybackState.Finished;\n return;\n }\n\n const parser = new NetworkMessageParser(block.data);\n parser.parseMessage();\n this.accumulatedTime -= this.frameDuration;\n }\n }\n\n public getState(): PlaybackState {\n return this.state;\n }\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport {\n EngineHost,\n type ClientRenderer,\n type EngineHostOptions,\n type GameFrameResult,\n type GameRenderSample,\n type GameSimulation,\n} from './host.js';\nimport { ConfigStringRegistry } from './configstrings.js';\nimport { FixedTimestepLoop, type LoopCallbacks, type LoopOptions } from './loop.js';\nimport { EngineRuntime, createEngineRuntime } from './runtime.js';\n\nimport { PmoveTraceResult } from '@quake2ts/shared';\n\nexport interface TraceResult extends PmoveTraceResult {\n readonly start: Vec3;\n readonly end: Vec3;\n readonly hit?: Vec3;\n}\n\nimport { Renderer } from './render/renderer.js';\n\nexport interface EngineImports {\n trace(start: Vec3, end: Vec3): TraceResult;\n renderer?: Renderer;\n}\n\nexport interface EngineExports {\n init(): void;\n shutdown(): void;\n createMainLoop(callbacks: LoopCallbacks, options?: Partial<LoopOptions>): FixedTimestepLoop;\n}\n\nexport function createEngine(imports: EngineImports): EngineExports {\n return {\n init() {\n void imports.trace({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 });\n },\n shutdown() {\n /* no-op for bootstrap */\n },\n createMainLoop(callbacks: LoopCallbacks, options?: Partial<LoopOptions>): FixedTimestepLoop {\n return new FixedTimestepLoop(callbacks, options);\n },\n };\n}\n\nexport { FixedTimestepLoop };\nexport { ConfigStringRegistry };\nexport { Cvar, CvarRegistry } from './cvars.js';\nexport type { FixedStepContext, LoopCallbacks, LoopOptions, RenderContext } from './loop.js';\nexport { PakArchive, PakParseError, calculatePakChecksum } from './assets/pak.js';\nexport { VirtualFileSystem } from './assets/vfs.js';\nexport {\n ingestPaks,\n PakIngestionError,\n type PakIngestionOptions,\n type PakIngestionProgress,\n type PakIngestionResult,\n type PakSource,\n} from './assets/ingestion.js';\nexport { LruCache } from './assets/cache.js';\nexport { filesToPakSources, ingestPakFiles, wireDropTarget, wireFileInput } from './assets/browserIngestion.js';\nexport {\n BspLoader,\n BspParseError,\n parseBsp,\n createFaceLightmap,\n type BspMap,\n type BspHeader,\n type BspEntities,\n type BspEntity,\n type BspLump,\n type BspLumpInfo,\n type BspFace,\n type BspLeaf,\n type BspNode,\n type BspPlane,\n type BspTexInfo,\n type BspModel,\n type BspVisibility,\n type BspVisibilityCluster,\n} from './assets/bsp.js';\nexport {\n Md2Loader,\n Md2ParseError,\n groupMd2Animations,\n parseMd2,\n type Md2Animation,\n type Md2Frame,\n type Md2GlCommand,\n type Md2Model,\n} from './assets/md2.js';\nexport {\n Md3Loader,\n Md3ParseError,\n parseMd3,\n type Md3Frame,\n type Md3Model,\n type Md3Surface,\n} from './assets/md3.js';\nexport {\n SpriteLoader,\n SpriteParseError,\n parseSprite,\n type SpriteFrame,\n type SpriteModel,\n} from './assets/sprite.js';\nexport {\n advanceAnimation,\n computeFrameBlend,\n createAnimationState,\n interpolateVec3,\n type AnimationSequence,\n type AnimationState,\n type FrameBlend,\n} from './assets/animation.js';\nexport { parseWal, type WalTexture } from './assets/wal.js';\nexport { parsePcx, pcxToRgba, type PcxImage } from './assets/pcx.js';\nexport {\n parseWalTexture,\n preparePcxTexture,\n TextureCache,\n walToRgba,\n type PreparedTexture,\n type TextureLevel,\n} from './assets/texture.js';\nexport { parseWav, type WavData } from './assets/wav.js';\nexport { decodeOgg, type OggAudio } from './assets/ogg.js';\nexport { AudioRegistry, AudioRegistryError, type DecodedAudio } from './assets/audio.js';\nexport { PakIndexStore, type StoredPakIndex } from './assets/pakIndexStore.js';\nexport {\n PakValidationError,\n PakValidator,\n RERELEASE_KNOWN_PAKS,\n type KnownPakChecksum,\n type PakValidationOutcome,\n} from './assets/pakValidation.js';\nexport {\n AssetDependencyError,\n AssetDependencyTracker,\n AssetManager,\n type AssetManagerOptions,\n} from './assets/manager.js';\nexport {\n ATTN_IDLE,\n ATTN_LOOP_NONE,\n ATTN_NONE,\n ATTN_NORM,\n ATTN_STATIC,\n MAX_SOUND_CHANNELS,\n SOUND_FULLVOLUME,\n SOUND_LOOP_ATTENUATE,\n SoundChannel,\n attenuationToDistanceMultiplier,\n calculateMaxAudibleDistance,\n} from './audio/constants.js';\nexport {\n AudioContextController,\n createAudioGraph,\n type AudioBufferLike,\n type AudioContextLike,\n type AudioGraph,\n type AudioNodeLike,\n type GainNodeLike,\n type BiquadFilterNodeLike,\n type PannerNodeLike,\n} from './audio/context.js';\nexport { SoundRegistry } from './audio/registry.js';\nexport { SoundPrecache, type SoundPrecacheOptions, type SoundPrecacheReport } from './audio/precache.js';\nexport { AudioSystem, type AudioSystemOptions, type SoundRequest } from './audio/system.js';\nexport { spatializeOrigin, type ListenerState, type SpatializationResult } from './audio/spatialization.js';\nexport { createInitialChannels, pickChannel, type ChannelState } from './audio/channels.js';\nexport { MusicSystem, type MusicSystemOptions, type MusicState, type AudioElementLike } from './audio/music.js';\nexport { AudioApi, type AudioApiOptions } from './audio/api.js';\nexport {\n EngineHost,\n type ClientRenderer,\n type EngineHostOptions,\n type GameFrameResult,\n type GameRenderSample,\n type GameSimulation,\n};\nexport { EngineRuntime, createEngineRuntime };\nexport { createWebGLContext, type WebGLContextInitOptions, type WebGLContextState } from './render/context.js';\nexport { ShaderProgram, createProgramFromSources, type ShaderSources } from './render/shaderProgram.js';\nexport {\n Framebuffer,\n IndexBuffer,\n Texture2D,\n TextureCubeMap,\n VertexArray,\n VertexBuffer,\n type BufferUsage,\n type TextureParameters,\n type VertexAttributeLayout,\n} from './render/resources.js';\nexport {\n BSP_VERTEX_LAYOUT,\n createBspSurfaces,\n buildBspGeometry,\n type BspGeometryBuildResult,\n type BspLightmapData,\n type BspSurfaceGeometry,\n type BspSurfaceInput,\n type LightmapAtlas,\n type LightmapPlacement,\n} from './render/bsp.js';\nexport { extractFrustumPlanes, boxIntersectsFrustum, type FrustumPlane } from './render/culling.js';\nexport { findLeafForPoint, gatherVisibleFaces, type VisibleFace } from './render/bspTraversal.js';\nexport {\n applySurfaceState,\n BspSurfacePipeline,\n BSP_SURFACE_FRAGMENT_SOURCE,\n BSP_SURFACE_VERTEX_SOURCE,\n deriveSurfaceRenderState,\n resolveLightStyles,\n type BspSurfaceBindOptions,\n type SurfaceRenderState,\n} from './render/bspPipeline.js';\nexport {\n SKYBOX_FRAGMENT_SHADER,\n SKYBOX_VERTEX_SHADER,\n SkyboxPipeline,\n computeSkyScroll,\n removeViewTranslation,\n} from './render/skybox.js';\nexport {\n MD2_FRAGMENT_SHADER,\n MD2_VERTEX_SHADER,\n Md2MeshBuffers,\n Md2Pipeline,\n buildMd2Geometry,\n buildMd2VertexData,\n type Md2BindOptions,\n type Md2FrameBlend,\n type Md2Geometry,\n type Md2DrawVertex,\n} from './render/md2Pipeline.js';\nexport { Camera } from './render/camera.js';\nexport {\n MD3_FRAGMENT_SHADER,\n MD3_VERTEX_SHADER,\n Md3ModelMesh,\n Md3Pipeline,\n Md3SurfaceMesh,\n buildMd3SurfaceGeometry,\n buildMd3VertexData,\n interpolateMd3Tag,\n type Md3FrameBlend,\n type Md3LightingOptions,\n type Md3SurfaceMaterial,\n type Md3TagTransform,\n} from './render/md3Pipeline.js';\nexport {\n PARTICLE_FRAGMENT_SHADER,\n PARTICLE_VERTEX_SHADER,\n ParticleRenderer,\n ParticleSystem,\n spawnBlood,\n spawnBulletImpact,\n spawnExplosion,\n spawnMuzzleFlash,\n spawnTeleportFlash,\n spawnTrail,\n type ParticleBlendMode,\n type ParticleEffectContext,\n type ParticleMesh,\n type ParticleRenderOptions,\n type ParticleSimulationOptions,\n type ParticleSpawnOptions,\n} from './render/particleSystem.js';\nexport { Pic, Renderer } from './render/renderer.js';\nexport { FrameRenderStats, FrameRenderOptions } from './render/frame.js';\nexport { DemoPlaybackController, PlaybackState, DemoReader, NetworkMessageParser } from './demo/index.js';\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 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","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 /** 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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } from '../math/vec3.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 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\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 let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false;\n let startout = false;\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\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 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 if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n if (d1 > d2) {\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 const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n if (!startout) {\n trace.startsolid = true;\n if (!getout) {\n trace.allsolid = true;\n }\n trace.fraction = 0;\n return;\n }\n\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n trace.fraction = enterfrac < 0 ? 0 : 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\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 (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\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 if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n // Use absolute value of offset like original C code (full/qcommon/cmodel.c:1269-1271)\n // which uses fabs() on each component\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start);\n const endDist = planeDistanceToPoint(plane, end);\n\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 (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 // Put the crosspoint DIST_EPSILON pixels on the near side\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 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 if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\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 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\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\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 for (const entity of this.entities.values()) {\n if (entity.id === passId) 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 const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\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 for (const entity of this.entities.values()) {\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 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 PlayerSkins = Items + MAX_ITEMS,\n General = PlayerSkins + 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","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 Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n} from './types.js';\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 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 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 {\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","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 {\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 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, 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 { 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 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 jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: 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, 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, 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\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, 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 return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\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 { 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 { 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\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\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 { 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}\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}\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}\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';\n\nconst FRAMETIME = 0.025;\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 point.z += state.mins.z + 1;\n const contents = pointContents(point);\n if (contents & 0x2000000) {\n return { ...state, waterLevel: 1 };\n }\n return { ...state, waterLevel: 0 };\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 } = newState;\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: { x: 1, y: 0, z: 0 },\n right: { x: 0, y: 1, z: 0 },\n cmd,\n maxSpeed: 320,\n })\n : buildAirGroundWish({\n forward: { x: 1, y: 0, z: 0 },\n right: { x: 0, y: 1, z: 0 },\n cmd,\n maxSpeed: 320,\n });\n\n const finalVelocity = applyPmoveAccelerate({\n velocity: frictionedVelocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: onGround ? 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';\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 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 hasMore(): boolean {\n return this.offset < 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 readLong(): number {\n const value = this.view.getInt32(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 // TODO: Implement bytedirs lookup\n // For now, zero it out\n out.x = 0; out.y = 0; out.z = 0;\n }\n}\n","import {\n addVec3,\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} from '@quake2ts/shared';\nimport {\n applyPmoveAccelerate,\n applyPmoveAirAccelerate,\n applyPmoveFriction,\n} from '@quake2ts/shared';\nimport type { GameFrameResult } from '@quake2ts/engine';\n\nimport { PlayerClient } from '@quake2ts/game';\n\nexport interface PredictionState {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly viewangles: Vec3;\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly waterlevel: WaterLevel;\n readonly gravity: number;\n readonly deltaAngles?: Vec3;\n readonly client?: PlayerClient;\n readonly health: number;\n readonly armor: number;\n readonly 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}\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};\n\nconst DEFAULT_GRAVITY = 800;\nconst ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\nconst MSEC_MAX = 250;\n\nexport function defaultPredictionState(): PredictionState {\n return {\n origin: ZERO_VEC3,\n velocity: ZERO_VEC3,\n viewangles: ZERO_VEC3,\n pmFlags: PmFlag.OnGround,\n pmType: PmType.Normal,\n waterlevel: WaterLevel.None,\n gravity: DEFAULT_GRAVITY,\n deltaAngles: ZERO_VEC3,\n health: 0,\n armor: 0,\n ammo: 0,\n } satisfies PredictionState;\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 } 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 return {\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 pmFlags: latest.pmFlags,\n pmType: latest.pmType,\n waterlevel: latest.waterlevel,\n gravity: latest.gravity,\n deltaAngles: latest.deltaAngles,\n client: latest.client,\n health: lerp(previous.health, latest.health, clamped),\n armor: lerp(previous.armor, latest.armor, clamped),\n ammo: lerp(previous.ammo, latest.ammo, clamped),\n } satisfies PredictionState;\n}\n\nfunction simulateCommand(\n state: PredictionState,\n cmd: UserCommand,\n settings: PredictionSettings,\n trace: PmoveTraceFn,\n): PredictionState {\n const frametime = Math.min(Math.max(cmd.msec, 0), MSEC_MAX) / 1000;\n const onGround = hasPmFlag(state.pmFlags, PmFlag.OnGround);\n const onLadder = hasPmFlag(state.pmFlags, PmFlag.OnLadder);\n\n let velocity = applyPmoveFriction({\n velocity: state.velocity,\n frametime,\n onGround,\n groundIsSlick: settings.groundIsSlick,\n onLadder,\n waterlevel: state.waterlevel,\n pmFriction: settings.pmFriction,\n pmStopSpeed: settings.pmStopSpeed,\n pmWaterFriction: settings.pmWaterFriction,\n });\n\n const { viewangles, forward, right } = clampViewAngles({\n pmFlags: state.pmFlags,\n cmdAngles: cmd.angles,\n deltaAngles: state.deltaAngles ?? ZERO_VEC3,\n });\n\n const wish =\n state.waterlevel > WaterLevel.None\n ? buildWaterWish({ forward, right, cmd, maxSpeed: settings.pmWaterSpeed })\n : buildAirGroundWish({ forward, right, cmd, maxSpeed: settings.pmMaxSpeed });\n\n if (state.waterlevel > WaterLevel.None) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: settings.pmWaterAccelerate,\n frametime,\n });\n } else if (onGround || onLadder) {\n const maxSpeed = hasPmFlag(state.pmFlags, PmFlag.Ducked) ? settings.pmDuckSpeed : settings.pmMaxSpeed;\n const clampedWish =\n wish.wishspeed > maxSpeed\n ? {\n wishdir: wish.wishdir,\n wishspeed: maxSpeed,\n }\n : wish;\n\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: clampedWish.wishdir,\n wishspeed: clampedWish.wishspeed,\n accel: settings.pmAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: settings.pmAirAccelerate,\n frametime,\n });\n velocity = { ...velocity, z: velocity.z - state.gravity * frametime };\n }\n\n const traceResult = trace(state.origin, addVec3(state.origin, scaleVec3(velocity, frametime)));\n const origin = traceResult.endpos;\n\n return {\n ...state,\n origin,\n velocity,\n viewangles,\n } satisfies PredictionState;\n}\n\nimport { PmoveTraceFn } from '@quake2ts/shared';\n\nexport class ClientPrediction {\n private readonly settings: PredictionSettings;\n private readonly trace: PmoveTraceFn;\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\n constructor(trace: PmoveTraceFn, settings: Partial<PredictionSettings> = {}) {\n this.settings = { ...DEFAULTS, ...settings } satisfies PredictionSettings;\n this.trace = trace;\n this.predicted = this.baseFrame.state ?? defaultPredictionState();\n }\n\n setAuthoritative(frame: GameFrameResult<PredictionState>): PredictionState {\n const normalized = normalizeState(frame.state);\n this.baseFrame = { ...frame, state: normalized };\n this.commands = this.commands.filter((cmd) => (cmd.serverFrame ?? Number.MAX_SAFE_INTEGER) > frame.frame);\n return this.recompute();\n }\n\n enqueueCommand(cmd: UserCommand): PredictionState {\n this.commands.push(cmd);\n return this.recompute();\n }\n\n getPredictedState(): PredictionState {\n return this.predicted;\n }\n\n private recompute(): PredictionState {\n let state = normalizeState(this.baseFrame.state);\n\n for (const cmd of this.commands) {\n state = simulateCommand(state, cmd, this.settings, this.trace);\n }\n\n this.predicted = state;\n return state;\n }\n}\n","import { ZERO_VEC3, angleVectors, clampViewAngles, dotVec3, hasPmFlag, PmFlag, type PmFlags, type Vec3 } from '@quake2ts/shared';\nimport type { PredictionState } from './prediction.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.005,\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}\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 let rollTilt = dotVec3(state.velocity, right) * this.settings.runRoll;\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\n // Apply active kick\n if (this.kick && this.kick.remainingMs > 0) {\n const ratio = Math.max(0, Math.min(1, this.kick.remainingMs / this.kick.durationMs));\n kickPitch += ratio * this.kick.pitch;\n kickRoll += ratio * this.kick.roll;\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: 0, y: 0, z: bobHeight };\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 { Pic, Renderer } from '@quake2ts/engine';\n\nexport const Draw_Number = (renderer: Renderer, x: number, y: number, value: number, pics: readonly Pic[], width: 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 renderer.drawPic(x + i * width, y, pic);\n }\n }\n};\n","export const HUD_LAYOUT = {\n // All coordinates are relative to a 640x480 screen resolution\n // and will be scaled accordingly.\n\n // Status bar numbers\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\n // Center print messages\n CENTER_PRINT_X: 320,\n CENTER_PRINT_Y: 100,\n\n // Weapon and powerup icons\n WEAPON_ICON_X: 10,\n WEAPON_ICON_Y: 450,\n POWERUP_X: 610,\n POWERUP_Y: 450,\n};\n","import { PakArchive, Pic, Renderer } from '@quake2ts/engine';\n\nlet crosshairPic: Pic | null = null;\n\nexport const Init_Crosshair = async (renderer: Renderer, pak: PakArchive) => {\n try {\n const data = pak.readFile('pics/crosshair.pcx');\n crosshairPic = await renderer.registerPic('crosshair', data.buffer as ArrayBuffer);\n } catch (e) {\n console.error('Failed to load crosshair image: pics/crosshair.pcx');\n }\n}\n\nexport const Draw_Crosshair = (renderer: Renderer, width: number, height: number) => {\n if (crosshairPic) {\n const x = (width - crosshairPic.width) / 2;\n const y = (height - crosshairPic.height) / 2;\n renderer.drawPic(x, y, crosshairPic);\n }\n};\n","import { PakArchive, Pic, Renderer } from '@quake2ts/engine';\nimport { PlayerClient, WEAPON_ITEMS, WeaponItem, PowerupId } from '@quake2ts/game';\nimport { HUD_LAYOUT } from './layout.js';\n\nconst iconPics = new Map<string, Pic>();\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\nexport const Init_Icons = async (renderer: Renderer, pak: PakArchive) => {\n for (const name of ICON_NAMES) {\n try {\n const data = pak.readFile(`pics/${name}.pcx`);\n const pic = await renderer.registerPic(name, data.buffer as ArrayBuffer);\n iconPics.set(name, pic);\n } catch (e) {\n console.error(`Failed to load HUD image: pics/${name}.pcx`);\n }\n }\n};\n\nexport const Draw_Icons = (renderer: Renderer, client: PlayerClient) => {\n if (!client) {\n return;\n }\n\n // Draw current weapon icon\n const currentWeapon = client.inventory.currentWeapon;\n if (currentWeapon) {\n const weaponDef = Object.values(WEAPON_ITEMS).find((w: WeaponItem) => w.weaponId === currentWeapon);\n if (weaponDef) {\n const iconName = `w_${weaponDef.id.substring(7)}`;\n const icon = iconPics.get(iconName);\n if (icon) {\n renderer.drawPic(HUD_LAYOUT.WEAPON_ICON_X, HUD_LAYOUT.WEAPON_ICON_Y, icon);\n }\n }\n }\n\n // Draw powerup icons\n let powerupX = HUD_LAYOUT.POWERUP_X;\n for (const [powerup, timer] of client.inventory.powerups.entries()) {\n if (timer && timer > 0) {\n const iconName = `p_${powerup}`;\n const icon = iconPics.get(iconName);\n if (icon) {\n renderer.drawPic(powerupX, HUD_LAYOUT.POWERUP_Y, icon);\n powerupX -= (icon.width + 4); // Move to the left for the next icon\n }\n }\n }\n};\n","import { PakArchive, Pic, Renderer } from '@quake2ts/engine';\nimport { PlayerState, angleVectors, dotVec3, Vec3 } from '@quake2ts/shared';\n\nconst damagePics = new Map<string, Pic>();\n\nconst DAMAGE_INDICATOR_NAMES = [\n 'd_left', 'd_right', 'd_up', 'd_down'\n];\n\nexport const Init_Damage = async (renderer: Renderer, pak: PakArchive) => {\n for (const name of DAMAGE_INDICATOR_NAMES) {\n try {\n const data = pak.readFile(`pics/${name}.pcx`);\n const pic = await renderer.registerPic(name, data.buffer as ArrayBuffer);\n damagePics.set(name, pic);\n } catch (e) {\n console.error(`Failed to load HUD image: pics/${name}.pcx`);\n }\n }\n};\n\nexport const Draw_Damage = (renderer: Renderer, ps: PlayerState) => {\n if (!ps.damageIndicators) {\n return;\n }\n\n const screenWidth = renderer.width;\n const screenHeight = renderer.height;\n\n const { forward, right, up } = angleVectors(ps.viewAngles);\n\n for (const indicator of ps.damageIndicators) {\n const { direction, strength } = indicator;\n\n const normalizedDirection = { ...direction };\n const len = Math.sqrt(normalizedDirection.x * normalizedDirection.x + normalizedDirection.y * normalizedDirection.y + normalizedDirection.z * normalizedDirection.z);\n if (len > 0) {\n normalizedDirection.x /= len;\n normalizedDirection.y /= len;\n normalizedDirection.z /= len;\n }\n\n const rightDot = dotVec3(normalizedDirection, right);\n const forwardDot = dotVec3(normalizedDirection, forward);\n\n const angle = Math.atan2(forwardDot, rightDot) * 180 / Math.PI;\n\n let pic: Pic | undefined;\n let x = 0;\n let y = 0;\n\n if (angle > -45 && angle <= 45) {\n pic = damagePics.get('d_right');\n x = screenWidth - (pic?.width || 0);\n y = (screenHeight - (pic?.height || 0)) / 2;\n } else if (angle > 45 && angle <= 135) {\n pic = damagePics.get('d_up');\n x = (screenWidth - (pic?.width || 0)) / 2;\n y = 0;\n } else if (angle > 135 || angle <= -135) {\n pic = damagePics.get('d_left');\n x = 0;\n y = (screenHeight - (pic?.height || 0)) / 2;\n } else {\n pic = damagePics.get('d_down');\n x = (screenWidth - (pic?.width || 0)) / 2;\n y = screenHeight - (pic?.height || 0);\n }\n \n if (pic) {\n renderer.drawPic(x, y, pic);\n }\n }\n};\n","import { Renderer, FrameRenderStats } from '@quake2ts/engine';\n\nexport const Draw_Diagnostics = (renderer: Renderer, stats: FrameRenderStats) => {\n const lines = [\n `FPS: ${stats.fps}`,\n `Draw Calls: ${stats.drawCalls}`,\n `Batches: ${stats.batches}`,\n `Faces Drawn: ${stats.facesDrawn}`,\n `Vertices: ${stats.vertexCount}`,\n ];\n\n let y = 10;\n for (const line of lines) {\n renderer.drawString(10, y, line);\n y += 10;\n }\n};\n","import { PakArchive, FrameRenderStats } from '@quake2ts/engine';\nimport { Pic, Renderer } from '@quake2ts/engine';\nimport { PlayerClient } from '@quake2ts/game';\nimport { PlayerState } from '@quake2ts/shared';\nimport { Draw_Number } from './hud/numbers.js';\nimport { HUD_LAYOUT } from './hud/layout.js';\nimport { Draw_Crosshair, Init_Crosshair } from './hud/crosshair.js';\nimport { Draw_Icons, Init_Icons } from './hud/icons.js';\nimport { Draw_Damage, Init_Damage } from './hud/damage.js';\nimport { Draw_Diagnostics } from './hud/diagnostics.js';\n\nconst hudNumberPics: Pic[] = [];\nlet numberWidth = 0;\n\nexport const Init_Hud = async (renderer: Renderer, pak: PakArchive) => {\n for (let i = 0; i < 10; i++) {\n try {\n const data = pak.readFile(`pics/hud/num_${i}.pcx`);\n const pic = await renderer.registerPic(`hud_num_${i}`, data.buffer as ArrayBuffer);\n hudNumberPics.push(pic);\n } catch (e) {\n console.error(`Failed to load HUD image: pics/hud/num_${i}.pcx`);\n }\n }\n if (hudNumberPics[0]) {\n numberWidth = hudNumberPics[0].width;\n }\n\n await Init_Crosshair(renderer, pak);\n await Init_Icons(renderer, pak);\n await Init_Damage(renderer, pak);\n};\n\nexport const Draw_Hud = (renderer: Renderer, ps: PlayerState, client: PlayerClient, health: number, armor: number, ammo: number, stats: FrameRenderStats) => {\n renderer.begin2D();\n\n if (ps.damageAlpha > 0) {\n renderer.drawfillRect(0, 0, renderer.width, renderer.height, [1, 0, 0, ps.damageAlpha]);\n }\n\n Draw_Number(renderer, HUD_LAYOUT.HEALTH_X, HUD_LAYOUT.HEALTH_Y, health, hudNumberPics, numberWidth);\n Draw_Number(renderer, HUD_LAYOUT.ARMOR_X, HUD_LAYOUT.ARMOR_Y, armor, hudNumberPics, numberWidth);\n Draw_Number(renderer, HUD_LAYOUT.AMMO_X, HUD_LAYOUT.AMMO_Y, ammo, hudNumberPics, numberWidth);\n Draw_Icons(renderer, client);\n Draw_Damage(renderer, ps);\n Draw_Diagnostics(renderer, stats);\n Draw_Crosshair(renderer, renderer.width, renderer.height);\n renderer.end2D();\n};\n","export type InputCode = string;\n\nexport interface BindingEntry {\n readonly code: InputCode;\n readonly command: string;\n}\n\nconst DEFAULT_BINDINGS: readonly BindingEntry[] = [\n { code: 'KeyW', command: '+forward' },\n { code: 'ArrowUp', command: '+forward' },\n { code: 'KeyS', command: '+back' },\n { code: 'ArrowDown', command: '+back' },\n { code: 'KeyA', command: '+moveleft' },\n { code: 'KeyD', command: '+moveright' },\n { code: 'Space', command: '+jump' },\n { code: 'ControlLeft', command: '+crouch' },\n { code: 'ShiftLeft', command: '+speed' },\n { code: 'Mouse1', command: '+attack' },\n { code: 'Mouse2', command: '+use' },\n { code: 'Mouse3', command: '+zoom' },\n { code: 'ArrowLeft', command: '+left' },\n { code: 'ArrowRight', command: '+right' },\n { code: 'PageUp', command: '+lookup' },\n { code: 'PageDown', command: '+lookdown' },\n { code: 'Gamepad0-Button7', command: '+attack' },\n { code: 'Gamepad0-Button6', command: '+zoom' },\n { code: 'Gamepad0-Button0', command: '+jump' },\n { code: 'Gamepad0-Button1', command: '+crouch' },\n { code: 'Gamepad0-Button2', command: '+use' },\n { code: 'Gamepad0-Button4', command: 'prevweapon' },\n { code: 'Gamepad0-Button5', command: 'nextweapon' },\n { code: 'Digit1', command: 'weapon 1' },\n { code: 'Digit2', command: 'weapon 2' },\n { code: 'Digit3', command: 'weapon 3' },\n { code: 'Digit4', command: 'weapon 4' },\n { code: 'Digit5', command: 'weapon 5' },\n { code: 'Digit6', command: 'weapon 6' },\n { code: 'Digit7', command: 'weapon 7' },\n { code: 'Digit8', command: 'weapon 8' },\n { code: 'Digit9', command: 'weapon 9' },\n { code: 'Digit0', command: 'weapon 10' },\n];\n\nexport type BindingMap = ReadonlyMap<InputCode, string>;\n\nexport class InputBindings {\n private readonly bindings = new Map<InputCode, string>();\n\n constructor(entries: Iterable<BindingEntry> = DEFAULT_BINDINGS) {\n for (const entry of entries) {\n this.bind(entry.code, entry.command);\n }\n }\n\n bind(code: InputCode, command: string): void {\n this.bindings.set(code, command);\n }\n\n unbind(code: InputCode): void {\n this.bindings.delete(code);\n }\n\n getBinding(code: InputCode): string | undefined {\n return this.bindings.get(code);\n }\n\n entries(): BindingMap {\n return new Map(this.bindings.entries());\n }\n}\n\nexport function createDefaultBindings(): InputBindings {\n return new InputBindings();\n}\n\nexport function normalizeInputCode(code: string): InputCode {\n return code;\n}\n\nexport function normalizeCommand(command: string): string {\n return command.trim().toLowerCase();\n}\n\n","import {\n DEFAULT_FORWARD_SPEED,\n DEFAULT_MOUSE_SENSITIVITY,\n DEFAULT_PITCH_SPEED,\n DEFAULT_SIDE_SPEED,\n DEFAULT_UP_SPEED,\n DEFAULT_YAW_SPEED,\n PlayerButton,\n addViewAngles,\n mouseDeltaToViewDelta,\n type MouseDelta,\n type UserCommand,\n type Vec3,\n} from '@quake2ts/shared';\nimport { InputBindings, normalizeCommand, normalizeInputCode, type InputCode } from './bindings.js';\n\nconst MSEC_MAX = 250;\n\nexport interface GamepadLikeButton {\n readonly pressed: boolean;\n readonly value: number;\n}\n\nexport interface GamepadLike {\n readonly axes: readonly number[];\n readonly buttons: readonly GamepadLikeButton[];\n readonly index?: number;\n readonly connected?: boolean;\n}\n\ninterface ButtonState {\n readonly active: boolean;\n readonly wasPressed: boolean;\n readonly fraction: number;\n}\n\nexport interface TouchInputState {\n readonly move?: { readonly x: number; readonly y: number };\n readonly look?: { readonly x: number; readonly y: number };\n readonly buttons?: Partial<Record<InputAction, boolean>>;\n}\n\nclass KeyButton {\n private readonly activeCodes = new Set<InputCode>();\n private downTime = 0;\n private msec = 0;\n private pressed = false;\n\n press(code: InputCode, now: number): boolean {\n if (this.activeCodes.has(code)) return false;\n\n this.activeCodes.add(code);\n this.pressed = true;\n if (this.activeCodes.size === 1) {\n this.downTime = now;\n return true;\n }\n\n return false;\n }\n\n release(code: InputCode, now: number): boolean {\n if (!this.activeCodes.delete(code)) return false;\n\n if (this.activeCodes.size === 0) {\n this.msec += now - this.downTime;\n this.downTime = 0;\n return true;\n }\n\n return false;\n }\n\n sample(frameMsec: number, now: number): ButtonState {\n if (frameMsec <= 0) {\n return { active: this.activeCodes.size > 0, wasPressed: this.pressed, fraction: 0 };\n }\n\n let total = this.msec;\n\n if (this.activeCodes.size > 0) {\n total += now - this.downTime;\n this.downTime = now;\n }\n\n this.msec = 0;\n\n const fraction = Math.min(total / frameMsec, 1);\n const wasPressed = this.pressed;\n this.pressed = false;\n\n return { active: this.activeCodes.size > 0, wasPressed, fraction };\n }\n}\n\nexport interface InputControllerOptions {\n readonly forwardSpeed?: number;\n readonly sideSpeed?: number;\n readonly upSpeed?: number;\n readonly yawSpeed?: number;\n readonly pitchSpeed?: number;\n readonly sensitivity?: number;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n readonly invertMouseY?: boolean;\n readonly runByDefault?: boolean;\n readonly requirePointerLock?: boolean;\n readonly jumpAddsUpMove?: boolean;\n readonly crouchAddsDownMove?: boolean;\n readonly mouseFilter?: boolean;\n readonly getGamepads?: () => readonly (GamepadLike | null | undefined)[];\n readonly gamepadDeadZone?: number;\n readonly gamepadLookScale?: number;\n readonly invertGamepadY?: boolean;\n}\n\nexport enum InputAction {\n Forward = '+forward',\n Back = '+back',\n MoveLeft = '+moveleft',\n MoveRight = '+moveright',\n MoveUp = '+moveup',\n MoveDown = '+movedown',\n Jump = '+jump',\n Crouch = '+crouch',\n Attack = '+attack',\n Use = '+use',\n Holster = '+holster',\n TurnLeft = '+left',\n TurnRight = '+right',\n LookUp = '+lookup',\n LookDown = '+lookdown',\n SpeedModifier = '+speed',\n Zoom = '+zoom',\n}\n\nconst BUTTON_ACTIONS: Partial<Record<InputAction, PlayerButton>> = {\n [InputAction.Attack]: PlayerButton.Attack,\n [InputAction.Use]: PlayerButton.Use,\n [InputAction.Holster]: PlayerButton.Holster,\n [InputAction.Jump]: PlayerButton.Jump,\n [InputAction.Crouch]: PlayerButton.Crouch,\n};\n\nconst ACTION_LOOKUP = new Map<string, InputAction>(\n Object.values(InputAction).map((action) => [normalizeCommand(action), action]),\n);\n\nfunction commandToAction(command: string): InputAction | undefined {\n return ACTION_LOOKUP.get(normalizeCommand(command));\n}\n\nfunction nowMs(): number {\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n return performance.now();\n }\n\n return Date.now();\n}\n\nexport class InputController {\n private readonly bindings: InputBindings;\n private readonly buttons = new Map<InputAction, KeyButton>();\n private viewAngles: Vec3 = { x: 0, y: 0, z: 0 };\n private pointerLocked = false;\n private mouseDelta: MouseDelta = { deltaX: 0, deltaY: 0 };\n private previousMouseDelta: MouseDelta = { deltaX: 0, deltaY: 0 };\n private anyPressed = false;\n private commandQueue: string[] = [];\n private pendingGamepads: readonly (GamepadLike | null | undefined)[] | undefined;\n private readonly gamepadButtons = new Map<string, boolean>();\n private gamepadMove = { x: 0, y: 0 };\n private gamepadLook = { x: 0, y: 0 };\n private pendingTouchState: TouchInputState | undefined;\n private readonly touchButtons = new Map<InputAction, boolean>();\n private touchMove = { x: 0, y: 0 };\n private touchLook = { x: 0, y: 0 };\n\n private readonly forwardSpeed: number;\n private readonly sideSpeed: number;\n private readonly upSpeed: number;\n private readonly yawSpeed: number;\n private readonly pitchSpeed: number;\n private readonly sensitivity: number;\n private readonly sensitivityX?: number;\n private readonly sensitivityY?: number;\n private readonly invertMouseY: boolean;\n private readonly runByDefault: boolean;\n private readonly requirePointerLock: boolean;\n private readonly jumpAddsUpMove: boolean;\n private readonly crouchAddsDownMove: boolean;\n private readonly mouseFilter: boolean;\n private readonly getGamepads?: () => readonly (GamepadLike | null | undefined)[];\n private readonly gamepadDeadZone: number;\n private readonly gamepadLookScale: number;\n private readonly invertGamepadY: boolean;\n\n constructor(options: InputControllerOptions = {}, bindings = new InputBindings()) {\n this.bindings = bindings;\n this.forwardSpeed = options.forwardSpeed ?? DEFAULT_FORWARD_SPEED;\n this.sideSpeed = options.sideSpeed ?? DEFAULT_SIDE_SPEED;\n this.upSpeed = options.upSpeed ?? DEFAULT_UP_SPEED;\n this.yawSpeed = options.yawSpeed ?? DEFAULT_YAW_SPEED;\n this.pitchSpeed = options.pitchSpeed ?? DEFAULT_PITCH_SPEED;\n this.sensitivity = options.sensitivity ?? DEFAULT_MOUSE_SENSITIVITY;\n this.sensitivityX = options.sensitivityX;\n this.sensitivityY = options.sensitivityY;\n this.invertMouseY = options.invertMouseY ?? false;\n this.runByDefault = options.runByDefault ?? true;\n this.requirePointerLock = options.requirePointerLock ?? true;\n this.jumpAddsUpMove = options.jumpAddsUpMove ?? true;\n this.crouchAddsDownMove = options.crouchAddsDownMove ?? true;\n this.mouseFilter = options.mouseFilter ?? false;\n this.getGamepads = options.getGamepads;\n this.gamepadDeadZone = options.gamepadDeadZone ?? 0.15;\n this.gamepadLookScale = options.gamepadLookScale ?? 1;\n this.invertGamepadY = options.invertGamepadY ?? this.invertMouseY;\n }\n\n handleKeyDown(code: string, eventTimeMs: number = nowMs()): void {\n const normalized = normalizeInputCode(code);\n const binding = this.bindings.getBinding(normalized);\n if (!binding) return;\n\n this.applyCommand(binding, true, normalized, eventTimeMs);\n }\n\n handleKeyUp(code: string, eventTimeMs: number = nowMs()): void {\n const normalized = normalizeInputCode(code);\n const binding = this.bindings.getBinding(normalized);\n if (!binding) return;\n\n this.applyCommand(binding, false, normalized, eventTimeMs);\n }\n\n handleMouseButtonDown(button: number, eventTimeMs: number = nowMs()): void {\n const code = this.mouseButtonToCode(button);\n this.applyCommand(this.mouseButtonToCommand(code), true, code, eventTimeMs);\n }\n\n handleMouseButtonUp(button: number, eventTimeMs: number = nowMs()): void {\n const code = this.mouseButtonToCode(button);\n this.applyCommand(this.mouseButtonToCommand(code), false, code, eventTimeMs);\n }\n\n handleMouseMove(deltaX: number, deltaY: number): void {\n if (this.requirePointerLock && !this.pointerLocked) return;\n\n this.mouseDelta = {\n deltaX: this.mouseDelta.deltaX + deltaX,\n deltaY: this.mouseDelta.deltaY + deltaY,\n };\n }\n\n setPointerLocked(locked: boolean): void {\n this.pointerLocked = locked;\n }\n\n setGamepadState(gamepads: readonly (GamepadLike | null | undefined)[]): void {\n this.pendingGamepads = gamepads;\n }\n\n setTouchState(state: TouchInputState): void {\n this.pendingTouchState = state;\n }\n\n buildCommand(frameMsec: number, now: number = nowMs(), serverFrame?: number): UserCommand {\n this.pollGamepads(now);\n this.applyTouchState(now);\n\n const yawStep = (this.yawSpeed * frameMsec) / 1000;\n const pitchStep = (this.pitchSpeed * frameMsec) / 1000;\n\n const turnLeft = this.sample(InputAction.TurnLeft, frameMsec, now);\n const turnRight = this.sample(InputAction.TurnRight, frameMsec, now);\n const lookUp = this.sample(InputAction.LookUp, frameMsec, now);\n const lookDown = this.sample(InputAction.LookDown, frameMsec, now);\n\n let viewDelta: Vec3 = {\n x: (lookDown.fraction - lookUp.fraction) * pitchStep,\n y: (turnRight.fraction - turnLeft.fraction) * yawStep,\n z: 0,\n };\n\n if (this.gamepadLook.x !== 0 || this.gamepadLook.y !== 0) {\n const pitch = this.gamepadLook.y * (this.invertGamepadY ? -1 : 1);\n viewDelta = {\n x: viewDelta.x + pitch * pitchStep * this.gamepadLookScale,\n y: viewDelta.y + this.gamepadLook.x * yawStep * this.gamepadLookScale,\n z: 0,\n };\n }\n\n if (this.touchLook.x !== 0 || this.touchLook.y !== 0) {\n const pitch = this.touchLook.y * (this.invertMouseY ? -1 : 1);\n viewDelta = {\n x: viewDelta.x + pitch * pitchStep,\n y: viewDelta.y + this.touchLook.x * yawStep,\n z: 0,\n };\n }\n\n if (this.pointerLocked || !this.requirePointerLock) {\n const sampledDelta = this.sampleMouseDelta();\n const mouseDelta = mouseDeltaToViewDelta(sampledDelta, {\n sensitivity: this.sensitivity,\n sensitivityX: this.sensitivityX,\n sensitivityY: this.sensitivityY,\n invertY: this.invertMouseY,\n });\n viewDelta = {\n x: viewDelta.x + mouseDelta.x,\n y: viewDelta.y + mouseDelta.y,\n z: 0,\n };\n }\n\n const angles = addViewAngles(this.viewAngles, viewDelta);\n this.viewAngles = angles;\n\n const forward = this.sample(InputAction.Forward, frameMsec, now);\n const back = this.sample(InputAction.Back, frameMsec, now);\n const moveLeft = this.sample(InputAction.MoveLeft, frameMsec, now);\n const moveRight = this.sample(InputAction.MoveRight, frameMsec, now);\n const moveUp = this.sample(InputAction.MoveUp, frameMsec, now);\n const moveDown = this.sample(InputAction.MoveDown, frameMsec, now);\n const speed = this.sample(InputAction.SpeedModifier, frameMsec, now);\n const jump = this.sample(InputAction.Jump, frameMsec, now);\n const crouch = this.sample(InputAction.Crouch, frameMsec, now);\n\n const speedScale = this.runByDefault\n ? speed.active\n ? 0.5\n : 1\n : speed.active\n ? 1\n : 0.5;\n\n let forwardmove = this.forwardSpeed * (forward.fraction - back.fraction) * speedScale;\n let sidemove = this.sideSpeed * (moveRight.fraction - moveLeft.fraction) * speedScale;\n let upmove = this.upSpeed * (moveUp.fraction - moveDown.fraction);\n\n if (this.gamepadMove.x !== 0 || this.gamepadMove.y !== 0) {\n forwardmove += this.forwardSpeed * this.gamepadMove.y * speedScale;\n sidemove += this.sideSpeed * this.gamepadMove.x * speedScale;\n }\n\n if (this.touchMove.x !== 0 || this.touchMove.y !== 0) {\n forwardmove += this.forwardSpeed * this.touchMove.y * speedScale;\n sidemove += this.sideSpeed * this.touchMove.x * speedScale;\n }\n\n if (this.jumpAddsUpMove && jump.fraction > 0) {\n upmove += this.upSpeed * jump.fraction;\n }\n\n if (this.crouchAddsDownMove && crouch.fraction > 0) {\n upmove -= this.upSpeed * crouch.fraction;\n }\n\n forwardmove = this.clampMove(forwardmove, this.forwardSpeed);\n sidemove = this.clampMove(sidemove, this.sideSpeed);\n upmove = this.clampMove(upmove, this.upSpeed);\n\n let buttons = this.collectButtonBits(frameMsec, now);\n\n const msec = Math.min(Math.max(Math.round(frameMsec), 1), MSEC_MAX);\n\n if (this.anyPressed || buttons !== PlayerButton.None) {\n buttons |= PlayerButton.Any;\n }\n\n this.anyPressed = false;\n\n return {\n msec,\n buttons,\n angles: { ...this.viewAngles },\n forwardmove,\n sidemove,\n upmove,\n serverFrame,\n } satisfies UserCommand;\n }\n\n consumeConsoleCommands(): readonly string[] {\n const commands = this.commandQueue;\n this.commandQueue = [];\n return commands;\n }\n\n private pollGamepads(now: number): void {\n const gamepads = this.getGamepads?.() ?? this.pendingGamepads ?? [];\n this.pendingGamepads = undefined;\n\n this.gamepadMove = { x: 0, y: 0 };\n this.gamepadLook = { x: 0, y: 0 };\n\n const pressedThisFrame = new Set<InputCode>();\n\n for (const pad of gamepads) {\n if (!pad || pad.connected === false) continue;\n\n const index = pad.index ?? 0;\n const axes = pad.axes ?? [];\n\n this.gamepadMove = {\n x: this.mergeAnalog(this.gamepadMove.x, this.applyDeadZone(axes[0] ?? 0)),\n y: this.mergeAnalog(this.gamepadMove.y, -this.applyDeadZone(axes[1] ?? 0)),\n };\n\n this.gamepadLook = {\n x: this.mergeAnalog(this.gamepadLook.x, this.applyDeadZone(axes[2] ?? 0)),\n y: this.mergeAnalog(this.gamepadLook.y, this.applyDeadZone(axes[3] ?? 0)),\n };\n\n const buttons = pad.buttons ?? [];\n for (let i = 0; i < buttons.length; i++) {\n const button = buttons[i];\n if (!button) continue;\n\n const pressed = button.pressed || button.value > this.gamepadDeadZone;\n const code = this.gamepadButtonCode(index, i);\n if (pressed) pressedThisFrame.add(code);\n\n const wasPressed = this.gamepadButtons.get(code) ?? false;\n if (pressed !== wasPressed) {\n this.applyCommand(this.bindings.getBinding(code), pressed, code, now);\n this.gamepadButtons.set(code, pressed);\n }\n }\n }\n\n for (const [code, wasPressed] of this.gamepadButtons.entries()) {\n if (wasPressed && !pressedThisFrame.has(code)) {\n this.applyCommand(this.bindings.getBinding(code), false, code, now);\n this.gamepadButtons.set(code, false);\n }\n }\n }\n\n private applyTouchState(now: number): void {\n const state = this.pendingTouchState;\n if (!state) return;\n\n this.pendingTouchState = undefined;\n\n if (state.move) {\n this.touchMove = {\n x: this.clampAnalog(state.move.x),\n y: this.clampAnalog(state.move.y),\n };\n }\n\n if (state.look) {\n this.touchLook = {\n x: this.clampAnalog(state.look.x),\n y: this.clampAnalog(state.look.y),\n };\n }\n\n if (state.buttons) {\n for (const [action, pressed] of Object.entries(state.buttons) as Array<\n [InputAction, boolean | undefined]\n >) {\n if (pressed === undefined) continue;\n\n const wasPressed = this.touchButtons.get(action) ?? false;\n if (pressed !== wasPressed) {\n this.applyCommand(action, pressed, this.touchButtonCode(action), now);\n this.touchButtons.set(action, pressed);\n }\n }\n }\n }\n\n private applyCommand(\n command: string | undefined,\n isDown: boolean,\n code: InputCode,\n eventTimeMs: number,\n ): void {\n if (!command) return;\n\n const action = commandToAction(command);\n if (action) {\n const button = this.lookupButton(action);\n if (isDown) {\n if (button.press(code, eventTimeMs)) {\n this.commandQueue.push(action);\n }\n this.anyPressed = true;\n } else if (button.release(code, eventTimeMs)) {\n this.commandQueue.push(action.replace('+', '-'));\n }\n } else if (isDown) {\n this.commandQueue.push(command);\n }\n }\n\n private sampleMouseDelta(): MouseDelta {\n const delta = this.mouseDelta;\n this.mouseDelta = { deltaX: 0, deltaY: 0 };\n\n if (!this.mouseFilter) {\n this.previousMouseDelta = delta;\n return delta;\n }\n\n const filtered = {\n deltaX: (delta.deltaX + this.previousMouseDelta.deltaX) * 0.5,\n deltaY: (delta.deltaY + this.previousMouseDelta.deltaY) * 0.5,\n } satisfies MouseDelta;\n\n this.previousMouseDelta = delta;\n return filtered;\n }\n\n private collectButtonBits(frameMsec: number, now: number): PlayerButton {\n let buttons = PlayerButton.None;\n\n for (const [action, bit] of Object.entries(BUTTON_ACTIONS) as Array<\n [InputAction, PlayerButton]\n >) {\n const sample = this.sample(action, frameMsec, now);\n if (sample.fraction > 0 || sample.active || sample.wasPressed) {\n buttons |= bit;\n }\n }\n\n return buttons;\n }\n\n private lookupButton(action: InputAction): KeyButton {\n let button = this.buttons.get(action);\n if (!button) {\n button = new KeyButton();\n this.buttons.set(action, button);\n }\n return button;\n }\n\n private mouseButtonToCode(button: number): InputCode {\n if (button === 0) return 'Mouse1';\n if (button === 1) return 'Mouse3';\n if (button === 2) return 'Mouse2';\n return `Mouse${button + 1}`;\n }\n\n private mouseButtonToCommand(code: InputCode): string | undefined {\n return this.bindings.getBinding(code);\n }\n\n private sample(action: InputAction, frameMsec: number, now: number): ButtonState {\n const button = this.lookupButton(action);\n return button.sample(frameMsec, now);\n }\n\n private gamepadButtonCode(index: number, button: number): InputCode {\n return `Gamepad${index}-Button${button}`;\n }\n\n private touchButtonCode(action: InputAction): InputCode {\n return `Touch-${action}`;\n }\n\n private clampAnalog(value: number): number {\n return Math.max(-1, Math.min(1, value));\n }\n\n private applyDeadZone(value: number): number {\n return Math.abs(value) < this.gamepadDeadZone ? 0 : value;\n }\n\n private mergeAnalog(current: number, incoming: number): number {\n return Math.abs(incoming) > Math.abs(current) ? incoming : current;\n }\n\n private clampMove(value: number, max: number): number {\n return Math.max(-max, Math.min(max, value));\n }\n}\n\n","import type { UserCommand } from '@quake2ts/shared';\nimport { InputController, type InputControllerOptions } from './controller.js';\n\nexport interface QueuedFrameCommands {\n readonly command: UserCommand;\n readonly console: readonly string[];\n}\n\nexport class InputCommandBuffer {\n private readonly controller: InputController;\n private readonly queued: QueuedFrameCommands[] = [];\n\n constructor(options?: InputControllerOptions, controller = new InputController(options)) {\n this.controller = controller;\n }\n\n captureFrame(frameMsec: number, now?: number, serverFrame?: number): QueuedFrameCommands {\n const command = this.controller.buildCommand(frameMsec, now, serverFrame);\n const console = this.controller.consumeConsoleCommands();\n const entry: QueuedFrameCommands = { command, console };\n this.queued.push(entry);\n return entry;\n }\n\n consumeQueued(): readonly QueuedFrameCommands[] {\n const queued = [...this.queued];\n this.queued.length = 0;\n return queued;\n }\n\n getController(): InputController {\n return this.controller;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMO,IAAI,UAAU;AACd,IAAI,aAAa,OAAO,iBAAiB,cAAc,eAAe;AACtE,IAAI,SAAS,KAAK;AASlB,SAAS,MAAM,GAAG;AACvB,MAAI,KAAK,EAAG,QAAO,KAAK,MAAM,CAAC;AAC/B,SAA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AAQ,aAAa,QAAQ,aAAa,OAAO,aAAa,MAAM,KAAK;AAAA,MACvI;AAEA,WAAK;AACL,WAAK;AAEL,aAAO;AAAA,IACT;AAAA,IACA,WAAW;AACT,oBAAc;AACd,qBAAe;AAAA,IACjB;AAAA,IACA,IAAI,aAA+B;AACjC,aAAO;AAAA,IACT;AAAA,IACA,IAAI,eAA4C;AAC9C,aAAO;AAAA,IACT;AAAA,IACA,IAAI,OAAoB;AACtB,aAAO;AAAA,IACT;AAAA,IACA,IAAI,WAAmC;AACrC,aAAO;AAAA,IACT;AAAA,IACA,IAAI,SAA6B;AAC/B,aAAO;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;","names":["len","scale","add","clone","copy","create","equals","exactEquals","fromValues","mul","multiply","rotateX","rotateY","rotateZ","round","scale","set","str","sub","subtract","create","clone","fromValues","copy","set","add","subtract","multiply","round","scale","len","angle","rotateX","rotateY","rotateZ","str","exactEquals","equals","sub","mul","ConfigStringIndex","ServerCommand","TempEntity","str","length","HEADER_SIZE","HEADER_SIZE","length","str","MAX_ITEMS","DEG_TO_RAD","len","DEG2RAD_FACTOR","RAD2DEG_FACTOR","DEG2RAD_FACTOR","angle","CONTENTS_SOLID","CONTENTS_WINDOW","CONTENTS_AUX","CONTENTS_LAVA","CONTENTS_SLIME","CONTENTS_WATER","CONTENTS_MIST","CONTENTS_NO_WATERJUMP","CONTENTS_PROJECTILECLIP","CONTENTS_AREAPORTAL","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_LIGHT","SURF_SLICK","SURF_SKY","SURF_WARP","SURF_TRANS33","SURF_TRANS66","SURF_FLOWING","SURF_NODRAW","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","WaterLevel","PmFlag","PmType","PlayerButton","scale","scale","WATERJUMP_CLEAR","clampPitch","ZERO_VEC3","lerp","len","angle","MSEC_MAX","InputAction","max","console"]}
1
+ {"version":3,"sources":["../../src/index.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/mat4.js","../../../../node_modules/.pnpm/gl-matrix@3.4.4/node_modules/gl-matrix/esm/vec3.js","../../../engine/src/loop.ts","../../../engine/src/host.ts","../../../shared/src/math/vec3.ts","../../../shared/src/math/angles.ts","../../../shared/src/math/color.ts","../../../shared/src/math/random.ts","../../../shared/src/math/mat4.ts","../../../shared/src/bsp/contents.ts","../../../shared/src/bsp/collision.ts","../../../shared/src/protocol/cvar.ts","../../../shared/src/protocol/configstrings.ts","../../../shared/src/protocol/contracts.ts","../../../shared/src/pmove/constants.ts","../../../shared/src/pmove/pmove.ts","../../../shared/src/pmove/slide.ts","../../../shared/src/pmove/stuck.ts","../../../shared/src/pmove/currents.ts","../../../shared/src/pmove/fly.ts","../../../shared/src/pmove/water.ts","../../../shared/src/pmove/jump.ts","../../../shared/src/pmove/dimensions.ts","../../../shared/src/pmove/duck.ts","../../../shared/src/pmove/categorize.ts","../../../shared/src/pmove/move.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/pmove/apply.ts","../../../shared/src/io/binaryStream.ts","../../../engine/src/configstrings.ts","../../../engine/src/runtime.ts","../../../engine/src/cvars.ts","../../../engine/src/assets/pak.ts","../../../engine/src/assets/vfs.ts","../../../engine/src/assets/pakValidation.ts","../../../engine/src/assets/ingestion.ts","../../../engine/src/assets/cache.ts","../../../engine/src/assets/browserIngestion.ts","../../../engine/src/assets/bsp.ts","../../../engine/src/assets/md2.ts","../../../engine/src/assets/md3.ts","../../../engine/src/assets/sprite.ts","../../../engine/src/assets/animation.ts","../../../engine/src/assets/wal.ts","../../../engine/src/assets/pcx.ts","../../../engine/src/assets/texture.ts","../../../engine/src/assets/wav.ts","../../../engine/src/assets/ogg.ts","../../../engine/src/assets/audio.ts","../../../engine/src/assets/pakIndexStore.ts","../../../engine/src/assets/manager.ts","../../../engine/src/audio/constants.ts","../../../engine/src/audio/context.ts","../../../engine/src/audio/registry.ts","../../../engine/src/audio/precache.ts","../../../engine/src/audio/channels.ts","../../../engine/src/audio/spatialization.ts","../../../engine/src/audio/system.ts","../../../engine/src/audio/music.ts","../../../engine/src/audio/api.ts","../../../engine/src/render/context.ts","../../../engine/src/render/shaderProgram.ts","../../../engine/src/render/resources.ts","../../../engine/src/render/bsp.ts","../../../engine/src/render/culling.ts","../../../engine/src/render/bspTraversal.ts","../../../engine/src/render/bspPipeline.ts","../../../engine/src/render/skybox.ts","../../../engine/src/render/md2Pipeline.ts","../../../engine/src/render/camera.ts","../../../engine/src/render/md3Pipeline.ts","../../../engine/src/render/particleSystem.ts","../../../engine/src/demo/demoReader.ts","../../../engine/src/demo/parser.ts","../../../engine/src/demo/playback.ts","../../../engine/src/index.ts","../../../shared/src/math/vec3.ts","../../../shared/src/math/angles.ts","../../../shared/src/math/color.ts","../../../shared/src/math/random.ts","../../../shared/src/math/mat4.ts","../../../shared/src/bsp/contents.ts","../../../shared/src/bsp/collision.ts","../../../shared/src/protocol/cvar.ts","../../../shared/src/protocol/configstrings.ts","../../../shared/src/protocol/contracts.ts","../../../shared/src/pmove/constants.ts","../../../shared/src/pmove/pmove.ts","../../../shared/src/pmove/slide.ts","../../../shared/src/pmove/stuck.ts","../../../shared/src/pmove/currents.ts","../../../shared/src/pmove/fly.ts","../../../shared/src/pmove/water.ts","../../../shared/src/pmove/jump.ts","../../../shared/src/pmove/dimensions.ts","../../../shared/src/pmove/duck.ts","../../../shared/src/pmove/categorize.ts","../../../shared/src/pmove/move.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/pmove/apply.ts","../../../shared/src/io/binaryStream.ts","../../src/prediction.ts","../../src/view-effects.ts","../../src/hud/numbers.ts","../../src/hud/layout.ts","../../src/hud/crosshair.ts","../../src/hud/icons.ts","../../src/hud/damage.ts","../../src/hud/diagnostics.ts","../../src/hud.ts","../../src/input/bindings.ts","../../src/input/controller.ts","../../src/input/command-buffer.ts"],"sourcesContent":["import {\n ClientRenderer,\n EngineImports,\n GameFrameResult,\n GameRenderSample,\n Camera,\n Renderer,\n DemoPlaybackController,\n} from '@quake2ts/engine';\nimport { UserCommand, Vec3, PlayerState, hasPmFlag, PmFlag } from '@quake2ts/shared';\nimport { vec3, mat4 } from 'gl-matrix';\nimport { ClientPrediction, interpolatePredictionState } from './prediction.js';\nimport type { PredictionState } from './prediction.js';\nimport { ViewEffects, type ViewSample } from './view-effects.js';\nimport { Draw_Hud, Init_Hud } from './hud.js';\nimport { FrameRenderStats } from '@quake2ts/engine';\nexport { createDefaultBindings, InputBindings, normalizeCommand, normalizeInputCode } from './input/bindings.js';\nexport {\n GamepadLike,\n GamepadLikeButton,\n InputAction,\n InputController,\n TouchInputState,\n type InputControllerOptions,\n} from './input/controller.js';\nexport {\n InputCommandBuffer,\n type QueuedFrameCommands,\n} from './input/command-buffer.js';\nexport {\n ClientPrediction,\n defaultPredictionState,\n interpolatePredictionState,\n type PredictionSettings,\n type PredictionState,\n} from './prediction.js';\nexport { ViewEffects, type ViewEffectSettings, type ViewKick, type ViewSample } from './view-effects.js';\n\nexport interface ClientImports {\n readonly engine: EngineImports & { renderer: Renderer };\n}\n\nexport interface ClientExports extends ClientRenderer<PredictionState> {\n predict(command: UserCommand): PredictionState;\n readonly prediction: ClientPrediction;\n readonly lastRendered?: PredictionState;\n readonly view: ViewEffects;\n readonly lastView?: ViewSample;\n camera?: Camera;\n demoPlayback: DemoPlaybackController;\n}\n\nexport function createClient(imports: ClientImports): ClientExports {\n const prediction = new ClientPrediction(imports.engine.trace);\n const view = new ViewEffects();\n const demoPlayback = new DemoPlaybackController();\n let latestFrame: GameFrameResult<PredictionState> | undefined;\n let lastRendered: PredictionState | undefined;\n let lastView: ViewSample | undefined;\n let camera: Camera | undefined;\n\n return {\n init(initial) {\n latestFrame = initial;\n if (initial?.state) {\n prediction.setAuthoritative(initial);\n }\n void imports.engine.trace({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });\n },\n predict(command: UserCommand): PredictionState {\n return prediction.enqueueCommand(command);\n },\n render(sample: GameRenderSample<PredictionState>): UserCommand {\n if (sample.latest?.state) {\n prediction.setAuthoritative(sample.latest);\n latestFrame = sample.latest;\n }\n\n if (sample.previous?.state && sample.latest?.state) {\n lastRendered = interpolatePredictionState(sample.previous.state, sample.latest.state, sample.alpha);\n } else {\n lastRendered = sample.latest?.state ?? sample.previous?.state ?? prediction.getPredictedState();\n }\n\n const frameTimeMs = sample.latest && sample.previous ? Math.max(0, sample.latest.timeMs - sample.previous.timeMs) : 0;\n lastView = view.sample(lastRendered, frameTimeMs);\n\n if (lastRendered) {\n const { origin, viewangles } = lastRendered;\n camera = new Camera();\n camera.position = vec3.fromValues(origin.x, origin.y, origin.z);\n camera.angles = vec3.fromValues(viewangles.x, viewangles.y, viewangles.z);\n camera.fov = 90;\n camera.aspect = 4 / 3;\n }\n\n const command = {} as UserCommand;\n\n if (imports.engine.renderer && lastRendered && lastRendered.client) {\n const stats: FrameRenderStats = {\n batches: 0,\n facesDrawn: 0,\n drawCalls: 0,\n skyDrawn: false,\n viewModelDrawn: false,\n fps: 0,\n vertexCount: 0,\n };\n\n const playerState: PlayerState = {\n origin: lastRendered.origin,\n velocity: lastRendered.velocity,\n viewAngles: lastRendered.viewangles,\n onGround: hasPmFlag(lastRendered.pmFlags, PmFlag.OnGround),\n waterLevel: lastRendered.waterlevel,\n mins: { x: -16, y: -16, z: -24 },\n maxs: { x: 16, y: 16, z: 32 },\n damageAlpha: 0,\n damageIndicators: [],\n };\n Draw_Hud(imports.engine.renderer, playerState, lastRendered.client, lastRendered.health, lastRendered.armor, lastRendered.ammo, stats);\n }\n\n void imports;\n void sample;\n\n return command;\n },\n shutdown() {\n latestFrame = undefined;\n lastRendered = undefined;\n },\n get prediction(): ClientPrediction {\n return prediction;\n },\n get lastRendered(): PredictionState | undefined {\n return lastRendered;\n },\n get view(): ViewEffects {\n return view;\n },\n get lastView(): ViewSample | undefined {\n return lastView;\n },\n get camera(): Camera | undefined {\n return camera;\n },\n demoPlayback\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 * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns {mat4} a new 4x4 matrix\n */\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(16);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\nexport function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\nexport function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a12 = a[6],\n a13 = a[7];\n var a23 = a[11];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n return out;\n}\n\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4 | null} out, or null if source matrix is not invertible\n */\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32;\n\n // Calculate the determinant\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n if (!det) {\n return null;\n }\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n return out;\n}\n\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32;\n out[0] = a11 * b11 - a12 * b10 + a13 * b09;\n out[1] = a02 * b10 - a01 * b11 - a03 * b09;\n out[2] = a31 * b05 - a32 * b04 + a33 * b03;\n out[3] = a22 * b04 - a21 * b05 - a23 * b03;\n out[4] = a12 * b08 - a10 * b11 - a13 * b07;\n out[5] = a00 * b11 - a02 * b08 + a03 * b07;\n out[6] = a32 * b02 - a30 * b05 - a33 * b01;\n out[7] = a20 * b05 - a22 * b02 + a23 * b01;\n out[8] = a10 * b10 - a11 * b08 + a13 * b06;\n out[9] = a01 * b08 - a00 * b10 - a03 * b06;\n out[10] = a30 * b04 - a31 * b02 + a33 * b00;\n out[11] = a21 * b02 - a20 * b04 - a23 * b00;\n out[12] = a11 * b07 - a10 * b09 - a12 * b06;\n out[13] = a00 * b09 - a01 * b07 + a02 * b06;\n out[14] = a31 * b01 - a30 * b03 - a32 * b00;\n out[15] = a20 * b03 - a21 * b01 + a22 * b00;\n return out;\n}\n\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b0 = a00 * a11 - a01 * a10;\n var b1 = a00 * a12 - a02 * a10;\n var b2 = a01 * a12 - a02 * a11;\n var b3 = a20 * a31 - a21 * a30;\n var b4 = a20 * a32 - a22 * a30;\n var b5 = a21 * a32 - a22 * a31;\n var b6 = a00 * b5 - a01 * b4 + a02 * b3;\n var b7 = a10 * b5 - a11 * b4 + a12 * b3;\n var b8 = a20 * b2 - a21 * b1 + a22 * b0;\n var b9 = a30 * b2 - a31 * b1 + a32 * b0;\n\n // Calculate the determinant\n return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9;\n}\n\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n\n // Cache only the current line of the second matrix\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\nexport function translate(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n return out;\n}\n\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function rotate(out, a, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.sqrt(x * x + y * y + z * z);\n var s, c, t;\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n var b00, b01, b02;\n var b10, b11, b12;\n var b20, b21, b22;\n if (len < glMatrix.EPSILON) {\n return null;\n }\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n\n // Construct the elements of the rotation matrix\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c;\n\n // Perform rotation-specific matrix multiplication\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateX(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateY(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateZ(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function fromRotation(out, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.sqrt(x * x + y * y + z * z);\n var s, c, t;\n if (len < glMatrix.EPSILON) {\n return null;\n }\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n\n // Perform rotation-specific matrix multiplication\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromXRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromYRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromZRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n * let quatMat = mat4.create();\n * mat4.fromQuat(quatMat, quat);\n * mat4.multiply(dest, dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\nexport function fromQuat2(out, a) {\n var translation = new glMatrix.ARRAY_TYPE(3);\n var bx = -a[0],\n by = -a[1],\n bz = -a[2],\n bw = a[3],\n ax = a[4],\n ay = a[5],\n az = a[6],\n aw = a[7];\n var magnitude = bx * bx + by * by + bz * bz + bw * bw;\n //Only scale if it makes sense\n if (magnitude > 0) {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n fromRotationTranslation(out, a, translation);\n return out;\n}\n\n/**\n * Returns the translation vector component of a transformation\n * matrix. If a matrix is built with fromRotationTranslation,\n * the returned vector will be the same as the translation vector\n * originally supplied.\n * @param {vec3} out Vector to receive translation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n return out;\n}\n\n/**\n * Returns the scaling factor component of a transformation\n * matrix. If a matrix is built with fromRotationTranslationScale\n * with a normalized Quaternion parameter, the returned vector will be\n * the same as the scaling vector\n * originally supplied.\n * @param {vec3} out Vector to receive scaling factor component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getScaling(out, mat) {\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n out[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n out[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n return out;\n}\n\n/**\n * Returns a quaternion representing the rotational component\n * of a transformation matrix. If a matrix is built with\n * fromRotationTranslation, the returned quaternion will be the\n * same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\nexport function getRotation(out, mat) {\n var scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n var is1 = 1 / scaling[0];\n var is2 = 1 / scaling[1];\n var is3 = 1 / scaling[2];\n var sm11 = mat[0] * is1;\n var sm12 = mat[1] * is2;\n var sm13 = mat[2] * is3;\n var sm21 = mat[4] * is1;\n var sm22 = mat[5] * is2;\n var sm23 = mat[6] * is3;\n var sm31 = mat[8] * is1;\n var sm32 = mat[9] * is2;\n var sm33 = mat[10] * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n return out;\n}\n\n/**\n * Decomposes a transformation matrix into its rotation, translation\n * and scale components. Returns only the rotation component\n * @param {quat} out_r Quaternion to receive the rotation component\n * @param {vec3} out_t Vector to receive the translation vector\n * @param {vec3} out_s Vector to receive the scaling factor\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @returns {quat} out_r\n */\nexport function decompose(out_r, out_t, out_s, mat) {\n out_t[0] = mat[12];\n out_t[1] = mat[13];\n out_t[2] = mat[14];\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out_s[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n out_s[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n out_s[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n var is1 = 1 / out_s[0];\n var is2 = 1 / out_s[1];\n var is3 = 1 / out_s[2];\n var sm11 = m11 * is1;\n var sm12 = m12 * is2;\n var sm13 = m13 * is3;\n var sm21 = m21 * is1;\n var sm22 = m22 * is2;\n var sm23 = m23 * is3;\n var sm31 = m31 * is1;\n var sm32 = m32 * is2;\n var sm33 = m33 * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out_r[3] = 0.25 * S;\n out_r[0] = (sm23 - sm32) / S;\n out_r[1] = (sm31 - sm13) / S;\n out_r[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out_r[3] = (sm23 - sm32) / S;\n out_r[0] = 0.25 * S;\n out_r[1] = (sm12 + sm21) / S;\n out_r[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out_r[3] = (sm31 - sm13) / S;\n out_r[0] = (sm12 + sm21) / S;\n out_r[1] = 0.25 * S;\n out_r[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out_r[3] = (sm12 - sm21) / S;\n out_r[0] = (sm31 + sm13) / S;\n out_r[1] = (sm23 + sm32) / S;\n out_r[2] = 0.25 * S;\n }\n return out_r;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n * let quatMat = mat4.create();\n * mat4.fromQuat(quatMat, quat);\n * mat4.multiply(dest, dest, quatMat);\n * mat4.scale(dest, dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n * mat4.translate(dest, dest, origin);\n * let quatMat = mat4.create();\n * mat4.fromQuat(quatMat, quat);\n * mat4.multiply(dest, dest, quatMat);\n * mat4.scale(dest, dest, scale)\n * mat4.translate(dest, dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n var ox = o[0];\n var oy = o[1];\n var oz = o[2];\n var out0 = (1 - (yy + zz)) * sx;\n var out1 = (xy + wz) * sx;\n var out2 = (xz - wy) * sx;\n var out4 = (xy - wz) * sy;\n var out5 = (1 - (xx + zz)) * sy;\n var out6 = (yz + wx) * sy;\n var out8 = (xz + wy) * sz;\n var out9 = (yz - wx) * sz;\n var out10 = (1 - (xx + yy)) * sz;\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n return out;\n}\n\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function frustum(out, left, right, bottom, top, near, far) {\n var rl = 1 / (right - left);\n var tb = 1 / (top - bottom);\n var nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2);\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n if (far != null && far !== Infinity) {\n var nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n return out;\n}\n\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\nexport var perspective = perspectiveNO;\n\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2);\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n if (far != null && far !== Infinity) {\n var nf = 1 / (near - far);\n out[10] = far * nf;\n out[14] = far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -near;\n }\n return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = far * near / (near - far);\n out[15] = 0.0;\n return out;\n}\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\nexport var ortho = orthoNO;\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = near * nf;\n out[15] = 1;\n return out;\n}\n\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function lookAt(out, eye, center, up) {\n var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;\n var eyex = eye[0];\n var eyey = eye[1];\n var eyez = eye[2];\n var upx = up[0];\n var upy = up[1];\n var upz = up[2];\n var centerx = center[0];\n var centery = center[1];\n var centerz = center[2];\n if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {\n return identity(out);\n }\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n return out;\n}\n\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} target Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function targetTo(out, eye, target, up) {\n var eyex = eye[0],\n eyey = eye[1],\n eyez = eye[2],\n upx = up[0],\n upy = up[1],\n upz = up[2];\n var z0 = eyex - target[0],\n z1 = eyey - target[1],\n z2 = eyez - target[2];\n var len = z0 * z0 + z1 * z1 + z2 * z2;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n var x0 = upy * z2 - upz * z1,\n x1 = upz * z0 - upx * z2,\n x2 = upx * z1 - upy * z0;\n len = x0 * x0 + x1 * x1 + x2 * x2;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\nexport function str(a) {\n return \"mat4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \", \" + a[9] + \", \" + a[10] + \", \" + a[11] + \", \" + a[12] + \", \" + a[13] + \", \" + a[14] + \", \" + a[15] + \")\";\n}\n\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\nexport function frob(a) {\n return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3] + a[4] * a[4] + a[5] * a[5] + a[6] * a[6] + a[7] * a[7] + a[8] * a[8] + a[9] * a[9] + a[10] * a[10] + a[11] * a[11] + a[12] * a[12] + a[13] * a[13] + a[14] * a[14] + a[15] * a[15]);\n}\n\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} 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 out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} 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 out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\nexport function multiplyScalarAndAdd(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 out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];\n}\n\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7];\n var a8 = a[8],\n a9 = a[9],\n a10 = a[10],\n a11 = a[11];\n var a12 = a[12],\n a13 = a[13],\n a14 = a[14],\n a15 = a[15];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n var b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7];\n var b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11];\n var b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\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)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));\n}\n\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\nexport var sub = subtract;","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}();","export interface FixedStepContext {\n readonly frame: number;\n readonly deltaMs: number;\n readonly nowMs: number;\n}\n\nexport interface RenderContext {\n readonly alpha: number;\n readonly nowMs: number;\n readonly accumulatorMs: number;\n readonly frame: number;\n}\n\nexport interface LoopCallbacks {\n simulate(step: FixedStepContext): void;\n render?(sample: RenderContext): void;\n}\n\nexport interface LoopOptions {\n readonly fixedDeltaMs: number;\n readonly maxSubSteps: number;\n readonly maxDeltaMs: number;\n readonly startTimeMs?: number;\n readonly now: () => number;\n readonly schedule: (tick: () => void) => unknown;\n}\n\nconst DEFAULT_FIXED_DELTA_MS = 25;\nconst DEFAULT_MAX_SUBSTEPS = 5;\n\nconst defaultNow = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\nconst defaultScheduler = (tick: () => void) => {\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => tick());\n } else {\n setTimeout(tick, DEFAULT_FIXED_DELTA_MS);\n }\n};\n\nexport class FixedTimestepLoop {\n private readonly options: LoopOptions;\n private accumulatorMs = 0;\n private frame = 0;\n private lastTimeMs: number | undefined;\n private running = false;\n\n constructor(private readonly callbacks: LoopCallbacks, options: Partial<LoopOptions> = {}) {\n const fixedDeltaMs = options.fixedDeltaMs ?? DEFAULT_FIXED_DELTA_MS;\n const maxSubSteps = options.maxSubSteps ?? DEFAULT_MAX_SUBSTEPS;\n this.options = {\n fixedDeltaMs,\n maxSubSteps,\n maxDeltaMs: options.maxDeltaMs ?? fixedDeltaMs * maxSubSteps,\n startTimeMs: options.startTimeMs,\n now: options.now ?? defaultNow,\n schedule: options.schedule ?? defaultScheduler,\n } satisfies LoopOptions;\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n this.lastTimeMs = this.options.startTimeMs ?? this.options.now();\n this.options.schedule(this.tick);\n }\n\n stop(): void {\n this.running = false;\n }\n\n pump(elapsedMs: number): void {\n const nowMs = (this.lastTimeMs ?? 0) + elapsedMs;\n this.lastTimeMs = nowMs;\n this.advance(elapsedMs, nowMs);\n }\n\n isRunning(): boolean {\n return this.running;\n }\n\n get frameNumber(): number {\n return this.frame;\n }\n\n private tick = (): void => {\n if (!this.running) return;\n\n const nowMs = this.options.now();\n const elapsed = this.lastTimeMs === undefined ? 0 : nowMs - this.lastTimeMs;\n this.lastTimeMs = nowMs;\n\n this.advance(elapsed, nowMs);\n\n if (this.running) {\n this.options.schedule(this.tick);\n }\n };\n\n private advance(elapsedMs: number, nowMs: number): void {\n const clampedDelta = Math.min(Math.max(elapsedMs, 0), this.options.maxDeltaMs);\n this.accumulatorMs = Math.min(\n this.accumulatorMs + clampedDelta,\n this.options.fixedDeltaMs * this.options.maxSubSteps,\n );\n\n let steps = 0;\n while (this.accumulatorMs >= this.options.fixedDeltaMs && steps < this.options.maxSubSteps) {\n this.frame += 1;\n this.callbacks.simulate({ frame: this.frame, deltaMs: this.options.fixedDeltaMs, nowMs });\n this.accumulatorMs -= this.options.fixedDeltaMs;\n steps += 1;\n }\n\n const alpha = this.options.fixedDeltaMs === 0 ? 0 : this.accumulatorMs / this.options.fixedDeltaMs;\n this.callbacks.render?.({ alpha, nowMs, accumulatorMs: this.accumulatorMs, frame: this.frame });\n }\n}\n","import {\n FixedTimestepLoop,\n type FixedStepContext,\n type LoopOptions,\n type RenderContext,\n} from './loop.js';\n\nexport interface GameFrameResult<FrameState = unknown> {\n readonly frame: number;\n readonly timeMs: number;\n readonly state?: FrameState;\n}\n\nexport interface GameSimulation<FrameState = unknown> {\n init(startTimeMs: number): GameFrameResult<FrameState> | void;\n frame(step: FixedStepContext, command?: any): GameFrameResult<FrameState>;\n shutdown(): void;\n}\n\nexport interface GameRenderSample<FrameState = unknown> extends RenderContext {\n readonly previous?: GameFrameResult<FrameState>;\n readonly latest?: GameFrameResult<FrameState>;\n}\n\nimport { UserCommand } from '@quake2ts/shared';\nimport { Camera } from './render/camera.js';\n\nexport interface ClientRenderer<FrameState = unknown> {\n init(initial?: GameFrameResult<FrameState>): void;\n render(sample: GameRenderSample<FrameState>): any;\n shutdown(): void;\n camera?: Camera;\n}\n\nexport interface EngineHostOptions {\n readonly loop?: Partial<LoopOptions>;\n readonly startTimeMs?: number;\n}\n\nexport class EngineHost<FrameState = unknown> {\n private readonly loop: FixedTimestepLoop;\n private readonly startTimeMs: number;\n private previousFrame?: GameFrameResult<FrameState>;\n private latestFrame?: GameFrameResult<FrameState>;\n private started = false;\n private latestCommand?: UserCommand;\n\n constructor(\n private readonly game: GameSimulation<FrameState>,\n private readonly client?: ClientRenderer<FrameState>,\n options: EngineHostOptions = {},\n ) {\n const now = options.loop?.now?.() ?? Date.now();\n this.startTimeMs = options.startTimeMs ?? options.loop?.startTimeMs ?? now;\n this.loop = new FixedTimestepLoop(\n {\n simulate: this.stepSimulation,\n render: this.renderClient,\n },\n { ...options.loop, startTimeMs: this.startTimeMs },\n );\n }\n\n start(): void {\n if (this.started) return;\n\n this.latestFrame = this.game.init(this.startTimeMs) ?? this.latestFrame;\n this.client?.init(this.latestFrame);\n\n this.started = true;\n this.loop.start();\n }\n\n stop(): void {\n if (!this.started) return;\n\n this.loop.stop();\n this.client?.shutdown();\n this.game.shutdown();\n this.previousFrame = undefined;\n this.latestFrame = undefined;\n this.started = false;\n }\n\n pump(elapsedMs: number): void {\n this.loop.pump(elapsedMs);\n }\n\n getLatestFrame(): GameFrameResult<FrameState> | undefined {\n return this.latestFrame;\n }\n\n isRunning(): boolean {\n return this.loop.isRunning();\n }\n\n private stepSimulation = (step: FixedStepContext): void => {\n this.previousFrame = this.latestFrame;\n this.latestFrame = this.game.frame(step, this.latestCommand);\n };\n\n private renderClient = (renderContext: RenderContext): void => {\n if (!this.client) return;\n\n this.latestCommand = this.client.render({\n ...renderContext,\n previous: this.previousFrame,\n latest: this.latestFrame,\n });\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 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","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 /** 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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } from '../math/vec3.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 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\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 let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false;\n let startout = false;\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\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 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 if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n if (d1 > d2) {\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 const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n if (!startout) {\n trace.startsolid = true;\n if (!getout) {\n trace.allsolid = true;\n }\n trace.fraction = 0;\n return;\n }\n\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n trace.fraction = enterfrac < 0 ? 0 : 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\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 (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\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 if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n // Use absolute value of offset like original C code (full/qcommon/cmodel.c:1269-1271)\n // which uses fabs() on each component\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start);\n const endDist = planeDistanceToPoint(plane, end);\n\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 (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 // Put the crosspoint DIST_EPSILON pixels on the near side\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 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 if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\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 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\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\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 for (const entity of this.entities.values()) {\n if (entity.id === passId) 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 const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\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 for (const entity of this.entities.values()) {\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 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 PlayerSkins = Items + MAX_ITEMS,\n General = PlayerSkins + 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","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 Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n} from './types.js';\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 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 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 {\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","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 {\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 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, 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 { 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 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 jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: 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, 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, 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\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, 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 return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\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 { 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 { 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\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\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 { 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}\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}\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}\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';\n\nconst FRAMETIME = 0.025;\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 point.z += state.mins.z + 1;\n const contents = pointContents(point);\n if (contents & 0x2000000) {\n return { ...state, waterLevel: 1 };\n }\n return { ...state, waterLevel: 0 };\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 } = newState;\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: { x: 1, y: 0, z: 0 },\n right: { x: 0, y: 1, z: 0 },\n cmd,\n maxSpeed: 320,\n })\n : buildAirGroundWish({\n forward: { x: 1, y: 0, z: 0 },\n right: { x: 0, y: 1, z: 0 },\n cmd,\n maxSpeed: 320,\n });\n\n const finalVelocity = applyPmoveAccelerate({\n velocity: frictionedVelocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: onGround ? 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';\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 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 hasMore(): boolean {\n return this.offset < 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 readLong(): number {\n const value = this.view.getInt32(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 // TODO: Implement bytedirs lookup\n // For now, zero it out\n out.x = 0; out.y = 0; out.z = 0;\n }\n}\n","import {\n ConfigStringIndex,\n CS_MAX_STRING_LENGTH,\n MAX_CONFIGSTRINGS,\n MAX_GENERAL,\n MAX_IMAGES,\n MAX_ITEMS,\n MAX_LIGHTSTYLES,\n MAX_MODELS,\n MAX_CLIENTS,\n MAX_SHADOW_LIGHTS,\n MAX_SOUNDS,\n MAX_WHEEL_ITEMS,\n configStringSize,\n} from '@quake2ts/shared';\n\nexport type ConfigStringEntry = Readonly<{ index: number; value: string }>;\n\nfunction assertWithinBounds(index: number): void {\n if (index < 0 || index >= ConfigStringIndex.MaxConfigStrings) {\n throw new RangeError(`Configstring index ${index} is out of range (0-${ConfigStringIndex.MaxConfigStrings - 1})`);\n }\n}\n\nfunction assertLength(index: number, value: string): void {\n const maxLength = configStringSize(index);\n if (value.length > maxLength) {\n throw new RangeError(\n `Configstring ${index} exceeds maximum length (${value.length} > ${maxLength}); limit is ${CS_MAX_STRING_LENGTH} chars per slot`,\n );\n }\n}\n\n/**\n * Minimal configstring/config index registry that mirrors the rerelease asset\n * indexing routines (`modelindex`, `soundindex`, etc.). The registry maintains\n * deterministic ordering within each configstring range and enforces the same\n * length/slot limits as the C++ helpers.\n */\nexport class ConfigStringRegistry {\n private readonly values = new Map<number, string>();\n private modelCursor = ConfigStringIndex.Models;\n private soundCursor = ConfigStringIndex.Sounds;\n private imageCursor = ConfigStringIndex.Images;\n private lightCursor = ConfigStringIndex.Lights;\n private shadowLightCursor = ConfigStringIndex.ShadowLights;\n private itemCursor = ConfigStringIndex.Items;\n private playerSkinCursor = ConfigStringIndex.PlayerSkins;\n private generalCursor = ConfigStringIndex.General;\n\n set(index: number, value: string): number {\n assertWithinBounds(index);\n assertLength(index, value);\n this.values.set(index, value);\n return index;\n }\n\n get(index: number): string | undefined {\n return this.values.get(index);\n }\n\n getAll(): string[] {\n const result: string[] = new Array(MAX_CONFIGSTRINGS).fill('');\n for (const [index, value] of this.values.entries()) {\n result[index] = value;\n }\n return result;\n }\n\n modelIndex(path: string): number {\n return this.register(path, ConfigStringIndex.Models, MAX_MODELS, 'modelCursor');\n }\n\n soundIndex(path: string): number {\n return this.register(path, ConfigStringIndex.Sounds, MAX_SOUNDS, 'soundCursor');\n }\n\n findSoundIndex(path: string): number | undefined {\n for (let i = ConfigStringIndex.Sounds; i < ConfigStringIndex.Sounds + MAX_SOUNDS; i += 1) {\n if (this.values.get(i) === path) {\n return i;\n }\n }\n return undefined;\n }\n\n imageIndex(path: string): number {\n return this.register(path, ConfigStringIndex.Images, MAX_IMAGES, 'imageCursor');\n }\n\n lightIndex(definition: string): number {\n return this.register(definition, ConfigStringIndex.Lights, MAX_LIGHTSTYLES, 'lightCursor');\n }\n\n shadowLightIndex(definition: string): number {\n return this.register(definition, ConfigStringIndex.ShadowLights, MAX_SHADOW_LIGHTS, 'shadowLightCursor');\n }\n\n itemIndex(name: string): number {\n return this.register(name, ConfigStringIndex.Items, MAX_ITEMS, 'itemCursor');\n }\n\n playerSkinIndex(name: string): number {\n return this.register(name, ConfigStringIndex.PlayerSkins, MAX_CLIENTS, 'playerSkinCursor');\n }\n\n generalIndex(value: string): number {\n return this.register(value, ConfigStringIndex.General, MAX_GENERAL, 'generalCursor');\n }\n\n private register(\n value: string,\n start: ConfigStringIndex,\n maxCount: number,\n cursorKey:\n | 'modelCursor'\n | 'soundCursor'\n | 'imageCursor'\n | 'lightCursor'\n | 'shadowLightCursor'\n | 'itemCursor'\n | 'playerSkinCursor'\n | 'generalCursor',\n ): number {\n // Reuse an existing slot if the caller tries to register the same value in the same range.\n for (let i = start; i < start + maxCount; i += 1) {\n if (this.values.get(i) === value) {\n return i;\n }\n }\n\n const next = this[cursorKey];\n const limit = start + maxCount;\n if (next >= limit) {\n throw new RangeError(`Out of configstring slots for range starting at ${start}`);\n }\n\n assertLength(next, value);\n this.values.set(next, value);\n this[cursorKey] = next + 1;\n return next;\n }\n}\n","import type { EngineExports } from './index.js';\nimport { EngineHost, type ClientRenderer, type EngineHostOptions, type GameFrameResult, type GameSimulation } from './host.js';\n\nexport class EngineRuntime<FrameState = unknown> {\n private started = false;\n\n constructor(private readonly engine: EngineExports, private readonly host: EngineHost<FrameState>) {}\n\n start(): void {\n if (this.started) return;\n this.engine.init();\n this.host.start();\n this.started = true;\n }\n\n stop(): void {\n if (!this.started) return;\n this.host.stop();\n this.engine.shutdown();\n this.started = false;\n }\n\n pump(elapsedMs: number): void {\n this.host.pump(elapsedMs);\n }\n\n getLatestFrame(): GameFrameResult<FrameState> | undefined {\n return this.host.getLatestFrame();\n }\n\n isRunning(): boolean {\n return this.started && this.host.isRunning();\n }\n}\n\nexport function createEngineRuntime<FrameState = unknown>(\n engine: EngineExports,\n game: GameSimulation<FrameState>,\n client?: ClientRenderer<FrameState>,\n options?: EngineHostOptions,\n): EngineRuntime<FrameState> {\n return new EngineRuntime(engine, new EngineHost(game, client, options));\n}\n","import { CvarFlags } from '@quake2ts/shared';\n\nexport type CvarChangeHandler = (cvar: Cvar, previousValue: string) => void;\n\nexport class Cvar {\n readonly name: string;\n readonly defaultValue: string;\n readonly description?: string;\n readonly flags: CvarFlags;\n private _value: string;\n private latched?: string;\n private onChange?: CvarChangeHandler;\n modifiedCount = 0;\n\n constructor({\n name,\n defaultValue,\n description,\n flags = CvarFlags.None,\n onChange,\n }: {\n name: string;\n defaultValue: string;\n description?: string;\n flags?: CvarFlags;\n onChange?: CvarChangeHandler;\n }) {\n this.name = name;\n this.defaultValue = defaultValue;\n this.description = description;\n this.flags = flags;\n this._value = defaultValue;\n this.onChange = onChange;\n }\n\n get string(): string {\n return this._value;\n }\n\n get number(): number {\n return Number(this._value);\n }\n\n get integer(): number {\n return Math.trunc(this.number);\n }\n\n get boolean(): boolean {\n return Boolean(this.integer);\n }\n\n set(value: string): void {\n if (this.flags & CvarFlags.Latch) {\n if (value === this._value) {\n this.latched = undefined;\n return;\n }\n\n if (this.latched === value) {\n return;\n }\n\n if (this.latched !== value) {\n this.latched = value;\n }\n return;\n }\n\n this.apply(value);\n }\n\n reset(): void {\n this.latched = undefined;\n this.apply(this.defaultValue);\n }\n\n applyLatched(): boolean {\n if (this.latched === undefined) {\n return false;\n }\n\n const pending = this.latched;\n this.latched = undefined;\n if (pending === this._value) {\n return false;\n }\n this.apply(pending);\n return true;\n }\n\n private apply(next: string): void {\n if (this._value === next) {\n return;\n }\n\n const previous = this._value;\n this._value = next;\n this.modifiedCount += 1;\n this.onChange?.(this, previous);\n }\n}\n\nexport class CvarRegistry {\n private readonly cvars = new Map<string, Cvar>();\n\n register(def: {\n name: string;\n defaultValue: string;\n description?: string;\n flags?: CvarFlags;\n onChange?: CvarChangeHandler;\n }): Cvar {\n const existing = this.cvars.get(def.name);\n if (existing) {\n return existing;\n }\n\n const cvar = new Cvar(def);\n this.cvars.set(def.name, cvar);\n return cvar;\n }\n\n get(name: string): Cvar | undefined {\n return this.cvars.get(name);\n }\n\n setValue(name: string, value: string): Cvar {\n const cvar = this.get(name);\n if (!cvar) {\n throw new Error(`Unknown cvar: ${name}`);\n }\n\n cvar.set(value);\n return cvar;\n }\n\n resetAll(): void {\n for (const cvar of this.cvars.values()) {\n cvar.reset();\n }\n }\n\n applyLatched(): boolean {\n let changed = false;\n for (const cvar of this.cvars.values()) {\n changed = cvar.applyLatched() || changed;\n }\n return changed;\n }\n\n list(): Cvar[] {\n return [...this.cvars.values()].sort((a, b) => a.name.localeCompare(b.name));\n }\n}\n","const PAK_MAGIC = 'PACK';\nconst HEADER_SIZE = 12;\nconst DIRECTORY_ENTRY_SIZE = 64;\n\nexport interface PakDirectoryEntry {\n readonly name: string;\n readonly offset: number;\n readonly length: number;\n}\n\nexport interface PakValidationResult {\n readonly checksum: number;\n readonly entries: readonly PakDirectoryEntry[];\n}\n\nfunction readCString(view: DataView, offset: number, maxLength: number): string {\n const codes: number[] = [];\n for (let i = 0; i < maxLength; i += 1) {\n const code = view.getUint8(offset + i);\n if (code === 0) {\n break;\n }\n codes.push(code);\n }\n return String.fromCharCode(...codes);\n}\n\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/').replace(/^\\/+/, '').toLowerCase();\n}\n\nfunction createCrcTable(): Uint32Array {\n const table = new Uint32Array(256);\n for (let i = 0; i < 256; i += 1) {\n let crc = i;\n for (let j = 0; j < 8; j += 1) {\n crc = (crc & 1) !== 0 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;\n }\n table[i] = crc >>> 0;\n }\n return table;\n}\n\nconst CRC_TABLE = createCrcTable();\n\nfunction crc32(data: Uint8Array): number {\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i += 1) {\n const byte = data[i];\n crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ 0xffffffff) >>> 0;\n}\n\nexport class PakParseError extends Error {}\n\nexport class PakArchive {\n static fromArrayBuffer(name: string, buffer: ArrayBuffer): PakArchive {\n const view = new DataView(buffer);\n if (buffer.byteLength < HEADER_SIZE) {\n throw new PakParseError('PAK buffer too small to contain header');\n }\n\n const magic = String.fromCharCode(\n view.getUint8(0),\n view.getUint8(1),\n view.getUint8(2),\n view.getUint8(3),\n );\n\n if (magic !== PAK_MAGIC) {\n throw new PakParseError(`Invalid PAK header magic: ${magic}`);\n }\n\n const dirOffset = view.getInt32(4, true);\n const dirLength = view.getInt32(8, true);\n\n if (dirOffset < HEADER_SIZE) {\n throw new PakParseError(`Invalid directory offset: ${dirOffset}`);\n }\n\n if (dirLength <= 0 || dirLength % DIRECTORY_ENTRY_SIZE !== 0) {\n throw new PakParseError(`Invalid directory length: ${dirLength}`);\n }\n\n const dirEnd = dirOffset + dirLength;\n if (dirEnd > buffer.byteLength) {\n throw new PakParseError('Directory exceeds buffer length');\n }\n\n const entryCount = dirLength / DIRECTORY_ENTRY_SIZE;\n const entries: PakDirectoryEntry[] = [];\n const dedupe = new Map<string, PakDirectoryEntry>();\n\n for (let i = 0; i < entryCount; i += 1) {\n const offset = dirOffset + i * DIRECTORY_ENTRY_SIZE;\n const rawName = readCString(view, offset, 56);\n const normalized = normalizePath(rawName);\n\n const fileOffset = view.getInt32(offset + 56, true);\n const fileLength = view.getInt32(offset + 60, true);\n\n if (fileOffset < 0 || fileLength < 0 || fileOffset + fileLength > buffer.byteLength) {\n throw new PakParseError(\n `Invalid entry bounds for ${rawName || '<unnamed>'} (offset=${fileOffset}, length=${fileLength})`,\n );\n }\n\n if (!normalized) {\n throw new PakParseError(`Entry ${i} has an empty name`);\n }\n\n const entry: PakDirectoryEntry = { name: normalized, offset: fileOffset, length: fileLength };\n dedupe.set(normalized, entry);\n }\n\n entries.push(...dedupe.values());\n\n return new PakArchive(name, buffer, entries, crc32(new Uint8Array(buffer)));\n }\n\n readonly entries: ReadonlyMap<string, PakDirectoryEntry>;\n readonly checksum: number;\n readonly size: number;\n\n private constructor(\n readonly name: string,\n private readonly buffer: ArrayBuffer,\n entries: PakDirectoryEntry[],\n checksum: number,\n ) {\n this.entries = new Map(entries.map((entry) => [entry.name, entry]));\n this.checksum = checksum;\n this.size = buffer.byteLength;\n }\n\n getEntry(path: string): PakDirectoryEntry | undefined {\n return this.entries.get(normalizePath(path));\n }\n\n listEntries(): PakDirectoryEntry[] {\n return Array.from(this.entries.values());\n }\n\n readFile(path: string): Uint8Array {\n const entry = this.getEntry(path);\n if (!entry) {\n throw new PakParseError(`File not found in PAK: ${path}`);\n }\n return new Uint8Array(this.buffer, entry.offset, entry.length);\n }\n\n validate(): PakValidationResult {\n return {\n checksum: this.checksum,\n entries: this.listEntries(),\n };\n }\n}\n\nexport function calculatePakChecksum(buffer: ArrayBuffer): number {\n return crc32(new Uint8Array(buffer));\n}\n\nexport { normalizePath };\n","import { PakArchive, PakDirectoryEntry, normalizePath } from './pak.js';\n\ntype VfsSource = { archive: PakArchive; entry: PakDirectoryEntry };\n\nexport interface VirtualFileHandle {\n readonly path: string;\n readonly size: number;\n readonly sourcePak: string;\n}\n\nexport interface DirectoryListing {\n readonly files: VirtualFileHandle[];\n readonly directories: string[];\n}\n\nexport class VirtualFileSystem {\n private readonly mounts: PakArchive[] = [];\n private readonly files = new Map<string, VfsSource>();\n\n constructor(archives: PakArchive[] = []) {\n archives.forEach((archive) => this.mountPak(archive));\n }\n\n mountPak(archive: PakArchive): void {\n this.mounts.push(archive);\n for (const entry of archive.listEntries()) {\n const key = normalizePath(entry.name);\n this.files.set(key, { archive, entry });\n }\n }\n\n get mountedPaks(): readonly PakArchive[] {\n return [...this.mounts];\n }\n\n hasFile(path: string): boolean {\n return this.files.has(normalizePath(path));\n }\n\n stat(path: string): VirtualFileHandle | undefined {\n const source = this.files.get(normalizePath(path));\n if (!source) {\n return undefined;\n }\n return { path: source.entry.name, size: source.entry.length, sourcePak: source.archive.name };\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n const source = this.files.get(normalizePath(path));\n if (!source) {\n throw new Error(`File not found in VFS: ${path}`);\n }\n return source.archive.readFile(path);\n }\n\n list(directory = ''): DirectoryListing {\n const dir = normalizePath(directory).replace(/\\/+$|^\\//g, '');\n const files: VirtualFileHandle[] = [];\n const directories = new Set<string>();\n const prefix = dir ? `${dir}/` : '';\n\n for (const source of this.files.values()) {\n if (dir && !source.entry.name.startsWith(prefix)) {\n continue;\n }\n const relative = dir ? source.entry.name.slice(prefix.length) : source.entry.name;\n const separatorIndex = relative.indexOf('/');\n if (separatorIndex === -1) {\n files.push({ path: source.entry.name, size: source.entry.length, sourcePak: source.archive.name });\n } else {\n directories.add(relative.slice(0, separatorIndex));\n }\n }\n\n files.sort((a, b) => a.path.localeCompare(b.path));\n\n return { files, directories: [...directories].sort() };\n }\n\n findByExtension(extension: string): VirtualFileHandle[] {\n const normalizedExt = extension.startsWith('.') ? extension.toLowerCase() : `.${extension.toLowerCase()}`;\n const results: VirtualFileHandle[] = [];\n for (const source of this.files.values()) {\n if (source.entry.name.toLowerCase().endsWith(normalizedExt)) {\n results.push({ path: source.entry.name, size: source.entry.length, sourcePak: source.archive.name });\n }\n }\n return results.sort((a, b) => a.path.localeCompare(b.path));\n }\n}\n","import { PakArchive, normalizePath, type PakValidationResult } from './pak.js';\n\nexport interface KnownPakChecksum {\n readonly name: string;\n readonly checksum: number;\n readonly size?: number;\n readonly description?: string;\n}\n\nexport interface PakValidationOutcome {\n readonly name: string;\n readonly checksum: number;\n readonly expectedChecksum?: number;\n readonly size?: number;\n readonly status: 'valid' | 'mismatch' | 'unknown';\n readonly description?: string;\n}\n\nexport const RERELEASE_KNOWN_PAKS: readonly KnownPakChecksum[] = Object.freeze([\n // Base campaign\n { name: 'pak0.pak', checksum: 0x8dbe2e6d, description: 'Base game assets' },\n { name: 'pak0.pak@baseq2', checksum: 0x8dbe2e6d, description: 'Base game assets (baseq2)' },\n // Mission packs bundled with the rerelease\n { name: 'pak0.pak@rogue', checksum: 0xc90f1e6d, description: 'Ground Zero (rogue) mission pack' },\n { name: 'pak0.pak@xatrix', checksum: 0x50f58d80, description: 'The Reckoning (xatrix) mission pack' },\n]);\n\nexport class PakValidationError extends Error {\n constructor(readonly result: PakValidationOutcome) {\n super(\n result.status === 'unknown'\n ? `Unknown PAK not allowed: ${result.name}`\n : `PAK checksum mismatch for ${result.name}`,\n );\n this.name = 'PakValidationError';\n }\n}\n\nexport class PakValidator {\n private readonly known = new Map<string, KnownPakChecksum>();\n\n constructor(knownPaks: readonly KnownPakChecksum[] = RERELEASE_KNOWN_PAKS) {\n knownPaks.forEach((pak) => this.known.set(this.normalizePakName(pak.name), pak));\n }\n\n validateArchive(archive: PakArchive | PakValidationResult, nameOverride?: string): PakValidationOutcome {\n const pakName = this.normalizePakName(nameOverride ?? ('name' in archive ? archive.name : 'unknown'));\n const checksum = archive.checksum;\n const size = 'size' in archive ? archive.size : undefined;\n\n const known = this.known.get(pakName);\n if (!known) {\n return { name: pakName, checksum, status: 'unknown', size };\n }\n\n if (known.checksum !== checksum) {\n return {\n name: pakName,\n checksum,\n expectedChecksum: known.checksum,\n status: 'mismatch',\n size,\n description: known.description,\n };\n }\n\n return {\n name: pakName,\n checksum,\n expectedChecksum: known.checksum,\n status: 'valid',\n size,\n description: known.description,\n };\n }\n\n assertValid(archive: PakArchive | PakValidationResult, nameOverride?: string): PakValidationOutcome {\n const outcome = this.validateArchive(archive, nameOverride);\n if (outcome.status === 'mismatch') {\n throw new PakValidationError(outcome);\n }\n return outcome;\n }\n\n private normalizePakName(name: string): string {\n const normalized = normalizePath(name);\n const parts = normalized.split('/');\n const filename = parts.pop() ?? normalized;\n const directory = parts.pop();\n return directory ? `${filename}@${directory}` : filename;\n }\n}\n","import { PakArchive } from './pak.js';\nimport { VirtualFileSystem } from './vfs.js';\nimport { PakIndexStore } from './pakIndexStore.js';\nimport { PakValidationError, PakValidator, type PakValidationOutcome } from './pakValidation.js';\n\nexport interface PakSource {\n readonly name: string;\n readonly data: ArrayBuffer | Blob | ArrayBufferView;\n}\n\nexport interface PakIngestionProgress {\n readonly file: string;\n readonly loadedBytes: number;\n readonly totalBytes: number;\n readonly state: 'reading' | 'parsed' | 'error';\n}\n\nexport interface PakIngestionResult {\n readonly archive: PakArchive;\n readonly mounted: boolean;\n readonly validation?: PakValidationOutcome;\n}\n\nexport interface PakIngestionOptions {\n readonly onProgress?: (progress: PakIngestionProgress) => void;\n readonly onError?: (file: string, error: unknown) => void;\n /**\n * Whether ingestion should abort when a single PAK fails to parse or mount.\n * Defaults to false to allow partial success in multi-PAK scenarios.\n */\n readonly stopOnError?: boolean;\n /**\n * Optional persistence target for PAK directory indexes. When provided, each successfully\n * parsed archive will be stored in IndexedDB so the browser can rebuild listings without\n * reparsing the binary payload.\n */\n readonly pakIndexStore?: PakIndexStore;\n /**\n * Whether to persist parsed PAK indexes. Defaults to true when a pakIndexStore is provided.\n */\n readonly persistIndexes?: boolean;\n /**\n * Optional checksum validator. When provided, PAKs whose checksums do not match the known list will\n * raise a PakValidationError unless `enforceValidation` is explicitly set to false.\n */\n readonly validator?: PakValidator;\n /**\n * Whether checksum mismatches should prevent mounting the archive. Defaults to true when a validator\n * is supplied.\n */\n readonly enforceValidation?: boolean;\n /**\n * Whether unknown PAKs (not present in the validator list) are allowed. Defaults to true.\n */\n readonly allowUnknownPaks?: boolean;\n /**\n * Callback invoked with the validation outcome when a validator is provided.\n */\n readonly onValidationResult?: (outcome: PakValidationOutcome) => void;\n}\n\nexport class PakIngestionError extends Error {\n constructor(readonly file: string, cause: unknown) {\n super(`Failed to ingest PAK: ${file}`);\n this.name = 'PakIngestionError';\n if (cause instanceof Error && cause.stack) {\n this.stack = cause.stack;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).cause = cause;\n }\n}\n\nasync function readBlobWithProgress(source: Blob, onProgress?: (progress: PakIngestionProgress) => void): Promise<ArrayBuffer> {\n if (typeof source.arrayBuffer === 'function') {\n const buffer = await source.arrayBuffer();\n onProgress?.({ file: 'blob', loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'reading' });\n return buffer;\n }\n\n if (typeof FileReader !== 'undefined') {\n return new Promise<ArrayBuffer>((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = () => reject(reader.error ?? new Error('Unknown FileReader error'));\n reader.onprogress = (event) => {\n onProgress?.({\n file: 'blob',\n loadedBytes: event.loaded,\n totalBytes: event.total || source.size,\n state: 'reading',\n });\n };\n reader.onload = () => {\n const result = reader.result;\n if (result instanceof ArrayBuffer) {\n resolve(result);\n } else {\n reject(new Error('Unexpected FileReader result'));\n }\n };\n reader.readAsArrayBuffer(source);\n });\n }\n\n if (typeof Response !== 'undefined') {\n const buffer = await new Response(source).arrayBuffer();\n onProgress?.({ file: 'blob', loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'reading' });\n return buffer;\n }\n\n if (typeof source.stream === 'function') {\n const reader = (source.stream() as ReadableStream<Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n let loaded = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (!value) {\n continue;\n }\n\n const chunk = value as Uint8Array;\n\n chunks.push(chunk);\n loaded += chunk.byteLength;\n onProgress?.({ file: 'blob', loadedBytes: loaded, totalBytes: source.size, state: 'reading' });\n }\n\n const result = new Uint8Array(loaded);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result.buffer;\n }\n\n throw new PakIngestionError('blob', new Error('Unsupported Blob type'));\n}\n\nasync function toArrayBuffer(source: PakSource, onProgress?: (progress: PakIngestionProgress) => void): Promise<ArrayBuffer> {\n if (source.data instanceof ArrayBuffer) {\n onProgress?.({ file: source.name, loadedBytes: source.data.byteLength, totalBytes: source.data.byteLength, state: 'reading' });\n return source.data;\n }\n if (source.data instanceof Blob) {\n const totalBytes = source.data.size;\n return readBlobWithProgress(source.data, (progress) =>\n onProgress?.({ ...progress, file: source.name, totalBytes }),\n );\n }\n\n const buffer = source.data.buffer.slice(source.data.byteOffset, source.data.byteOffset + source.data.byteLength) as ArrayBuffer;\n onProgress?.({ file: source.name, loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'reading' });\n return buffer;\n}\n\nexport async function ingestPaks(\n vfs: VirtualFileSystem,\n sources: PakSource[],\n onProgressOrOptions?: PakIngestionOptions | ((progress: PakIngestionProgress) => void),\n): Promise<PakIngestionResult[]> {\n const options: PakIngestionOptions =\n typeof onProgressOrOptions === 'function' ? { onProgress: onProgressOrOptions } : onProgressOrOptions ?? {};\n\n const shouldPersist = options.persistIndexes ?? Boolean(options.pakIndexStore);\n const enforceValidation = options.enforceValidation ?? Boolean(options.validator);\n const allowUnknownPaks = options.allowUnknownPaks ?? true;\n const stopOnError = options.stopOnError ?? false;\n\n const results: PakIngestionResult[] = [];\n\n for (const source of sources) {\n try {\n const buffer = await toArrayBuffer(source, options.onProgress);\n const archive = PakArchive.fromArrayBuffer(source.name, buffer);\n const validation = options.validator?.validateArchive(archive);\n if (validation) {\n options.onValidationResult?.(validation);\n const isMismatch = validation.status === 'mismatch';\n const isUnknown = validation.status === 'unknown';\n if ((isMismatch && enforceValidation) || (isUnknown && !allowUnknownPaks)) {\n const validationError = new PakValidationError(validation);\n options.onError?.(source.name, validationError);\n if (stopOnError) {\n throw new PakIngestionError(source.name, validationError);\n }\n results.push({ archive, mounted: false, validation });\n continue;\n }\n }\n vfs.mountPak(archive);\n if (shouldPersist && options.pakIndexStore) {\n try {\n await options.pakIndexStore.persist(archive);\n } catch (error) {\n options.onError?.(source.name, error);\n if (stopOnError) {\n throw new PakIngestionError(source.name, error);\n }\n }\n }\n options.onProgress?.({ file: source.name, loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'parsed' });\n results.push({ archive, mounted: true, validation });\n } catch (error) {\n options.onProgress?.({ file: source.name, loadedBytes: 0, totalBytes: 0, state: 'error' });\n options.onError?.(source.name, error);\n\n if (stopOnError) {\n throw new PakIngestionError(source.name, error);\n }\n }\n }\n\n return results;\n}\n","export interface CacheEntry<T> {\n key: string;\n value: T;\n}\n\nexport class LruCache<T> {\n private readonly map = new Map<string, T>();\n\n constructor(private readonly capacity: number) {\n if (capacity <= 0) {\n throw new RangeError('LRU cache capacity must be greater than zero');\n }\n }\n\n get size(): number {\n return this.map.size;\n }\n\n has(key: string): boolean {\n return this.map.has(key);\n }\n\n get(key: string): T | undefined {\n const value = this.map.get(key);\n if (value === undefined) {\n return undefined;\n }\n this.map.delete(key);\n this.map.set(key, value);\n return value;\n }\n\n set(key: string, value: T): void {\n if (this.map.has(key)) {\n this.map.delete(key);\n }\n this.map.set(key, value);\n if (this.map.size > this.capacity) {\n const oldestKey = this.map.keys().next();\n if (!oldestKey.done) {\n this.map.delete(oldestKey.value);\n }\n }\n }\n\n delete(key: string): boolean {\n return this.map.delete(key);\n }\n\n clear(): void {\n this.map.clear();\n }\n\n entries(): CacheEntry<T>[] {\n return Array.from(this.map.entries()).reverse().map(([key, value]) => ({ key, value }));\n }\n}\n","import { ingestPaks, type PakIngestionOptions, type PakIngestionResult, type PakSource } from './ingestion.js';\nimport { VirtualFileSystem } from './vfs.js';\n\nfunction toArray(files: Iterable<File>): File[] {\n return Array.isArray(files) ? files : Array.from(files);\n}\n\nexport function filesToPakSources(files: Iterable<File>): PakSource[] {\n return toArray(files).map((file) => ({ name: file.name, data: file }));\n}\n\nexport async function ingestPakFiles(\n vfs: VirtualFileSystem,\n files: Iterable<File>,\n options?: PakIngestionOptions,\n): Promise<PakIngestionResult[]> {\n const sources = filesToPakSources(files);\n return ingestPaks(vfs, sources, options ?? {});\n}\n\nexport function wireDropTarget(\n element: HTMLElement,\n handler: (files: File[]) => void,\n): () => void {\n const onDragOver = (event: DragEvent) => {\n event.preventDefault();\n event.dataTransfer?.dropEffect && (event.dataTransfer.dropEffect = 'copy');\n };\n\n const onDrop = (event: DragEvent) => {\n event.preventDefault();\n const droppedFiles = event.dataTransfer?.files;\n if (droppedFiles && droppedFiles.length > 0) {\n handler(Array.from(droppedFiles));\n }\n };\n\n element.addEventListener('dragover', onDragOver);\n element.addEventListener('drop', onDrop);\n\n return () => {\n element.removeEventListener('dragover', onDragOver);\n element.removeEventListener('drop', onDrop);\n };\n}\n\nexport function wireFileInput(\n input: HTMLInputElement,\n handler: (files: FileList) => void,\n): () => void {\n const onChange = (event: Event) => {\n const target = event.target as HTMLInputElement | null;\n if (!target || !target.files || target.files.length === 0) {\n return;\n }\n handler(target.files);\n target.value = '';\n };\n\n input.addEventListener('change', onChange);\n return () => input.removeEventListener('change', onChange);\n}\n","// BSP loader for Quake II (version 38)\n// Parses lumps, decompresses visibility (PVS), and exposes derived structures for rendering and collision.\n\nimport { VirtualFileSystem } from './vfs.js';\n\nconst BSP_MAGIC = 'IBSP';\nconst BSP_VERSION = 38;\nconst HEADER_LUMPS = 19;\nconst HEADER_SIZE = 4 + 4 + HEADER_LUMPS * 8; // magic + version + lump infos\n\nexport type Vec3 = [number, number, number];\n\nexport interface BspLumpInfo {\n readonly offset: number;\n readonly length: number;\n}\n\nexport interface BspHeader {\n readonly version: number;\n readonly lumps: ReadonlyMap<BspLump, BspLumpInfo>;\n}\n\nexport interface BspEntities {\n readonly raw: string;\n readonly entities: BspEntity[];\n readonly worldspawn: BspEntity | undefined;\n}\n\nexport interface BspEntity {\n readonly classname?: string;\n readonly properties: Record<string, string>;\n}\n\nexport interface BspPlane {\n readonly normal: Vec3;\n readonly dist: number;\n readonly type: number;\n}\n\nexport interface BspNode {\n readonly planeIndex: number;\n readonly children: [number, number];\n readonly mins: [number, number, number];\n readonly maxs: [number, number, number];\n readonly firstFace: number;\n readonly numFaces: number;\n}\n\nexport interface BspLeaf {\n readonly contents: number;\n readonly cluster: number;\n readonly area: number;\n readonly mins: [number, number, number];\n readonly maxs: [number, number, number];\n readonly firstLeafFace: number;\n readonly numLeafFaces: number;\n readonly firstLeafBrush: number;\n readonly numLeafBrushes: number;\n}\n\nexport interface BspTexInfo {\n readonly s: Vec3;\n readonly sOffset: number;\n readonly t: Vec3;\n readonly tOffset: number;\n readonly flags: number;\n readonly value: number;\n readonly texture: string;\n readonly nextTexInfo: number;\n}\n\nexport interface BspFace {\n readonly planeIndex: number;\n readonly side: number;\n readonly firstEdge: number;\n readonly numEdges: number;\n readonly texInfo: number;\n readonly styles: [number, number, number, number];\n readonly lightOffset: number;\n}\n\nexport interface BspEdge {\n readonly vertices: [number, number];\n}\n\nexport interface BspModel {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly origin: Vec3;\n readonly headNode: number;\n readonly firstFace: number;\n readonly numFaces: number;\n}\n\nexport interface BspBrush {\n readonly firstSide: number;\n readonly numSides: number;\n readonly contents: number;\n}\n\nexport interface BspBrushSide {\n readonly planeIndex: number;\n readonly texInfo: number;\n}\n\nexport interface BspArea {\n readonly numAreaPortals: number;\n readonly firstAreaPortal: number;\n}\n\nexport interface BspAreaPortal {\n readonly portalNumber: number;\n readonly otherArea: number;\n}\n\nexport interface BspVisibilityCluster {\n readonly pvs: Uint8Array;\n readonly phs: Uint8Array;\n}\n\nexport interface BspVisibility {\n readonly numClusters: number;\n readonly clusters: readonly BspVisibilityCluster[];\n}\n\nexport interface BspLightmapInfo {\n readonly offset: number;\n readonly length: number;\n}\n\nexport interface BspLeafLists {\n readonly leafFaces: readonly number[][];\n readonly leafBrushes: readonly number[][];\n}\n\nexport interface BspMap {\n readonly header: BspHeader;\n readonly entities: BspEntities;\n readonly planes: readonly BspPlane[];\n readonly vertices: readonly Vec3[];\n readonly nodes: readonly BspNode[];\n readonly texInfo: readonly BspTexInfo[];\n readonly faces: readonly BspFace[];\n readonly lightMaps: Uint8Array;\n readonly lightMapInfo: readonly (BspLightmapInfo | undefined)[];\n readonly leafs: readonly BspLeaf[];\n readonly leafLists: BspLeafLists;\n readonly edges: readonly BspEdge[];\n readonly surfEdges: Int32Array;\n readonly models: readonly BspModel[];\n readonly brushes: readonly BspBrush[];\n readonly brushSides: readonly BspBrushSide[];\n readonly visibility: BspVisibility | undefined;\n}\n\nexport enum BspLump {\n Entities = 0,\n Planes = 1,\n Vertices = 2,\n Visibility = 3,\n Nodes = 4,\n TexInfo = 5,\n Faces = 6,\n Lighting = 7,\n Leafs = 8,\n LeafFaces = 9,\n LeafBrushes = 10,\n Edges = 11,\n SurfEdges = 12,\n Models = 13,\n Brushes = 14,\n BrushSides = 15,\n Pop = 16,\n Areas = 17,\n AreaPortals = 18,\n}\n\nexport class BspParseError extends Error {}\n\nexport class BspLoader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<BspMap> {\n const buffer = await this.vfs.readFile(path);\n const copy = new Uint8Array(buffer.byteLength);\n copy.set(buffer);\n return parseBsp(copy.buffer);\n }\n}\n\nexport function parseBsp(buffer: ArrayBuffer): BspMap {\n if (buffer.byteLength < HEADER_SIZE) {\n throw new BspParseError('BSP too small to contain header');\n }\n\n const view = new DataView(buffer);\n const magic = String.fromCharCode(view.getUint8(0), view.getUint8(1), view.getUint8(2), view.getUint8(3));\n if (magic !== BSP_MAGIC) {\n throw new BspParseError(`Invalid BSP magic ${magic}`);\n }\n const version = view.getInt32(4, true);\n if (version !== BSP_VERSION) {\n throw new BspParseError(`Unsupported BSP version ${version}`);\n }\n\n const lumps = new Map<BspLump, BspLumpInfo>();\n for (let i = 0; i < HEADER_LUMPS; i += 1) {\n const offset = view.getInt32(8 + i * 8, true);\n const length = view.getInt32(12 + i * 8, true);\n if (offset < 0 || length < 0 || offset + length > buffer.byteLength) {\n throw new BspParseError(`Invalid lump bounds for index ${i}`);\n }\n lumps.set(i as BspLump, { offset, length });\n }\n\n const header: BspHeader = { version, lumps };\n const entities = parseEntities(buffer, lumps.get(BspLump.Entities)!);\n const planes = parsePlanes(buffer, lumps.get(BspLump.Planes)!);\n const vertices = parseVertices(buffer, lumps.get(BspLump.Vertices)!);\n const nodes = parseNodes(buffer, lumps.get(BspLump.Nodes)!);\n const texInfo = parseTexInfo(buffer, lumps.get(BspLump.TexInfo)!);\n const faces = parseFaces(buffer, lumps.get(BspLump.Faces)!);\n const lightMaps = new Uint8Array(buffer, lumps.get(BspLump.Lighting)!.offset, lumps.get(BspLump.Lighting)!.length);\n const lightMapInfo = buildLightMapInfo(faces, lumps.get(BspLump.Lighting)!);\n const leafs = parseLeafs(buffer, lumps.get(BspLump.Leafs)!);\n const edges = parseEdges(buffer, lumps.get(BspLump.Edges)!);\n const surfEdges = parseSurfEdges(buffer, lumps.get(BspLump.SurfEdges)!);\n const models = parseModels(buffer, lumps.get(BspLump.Models)!);\n const brushes = parseBrushes(buffer, lumps.get(BspLump.Brushes)!);\n const brushSides = parseBrushSides(buffer, lumps.get(BspLump.BrushSides)!);\n const leafLists = parseLeafLists(buffer, lumps.get(BspLump.LeafFaces)!, lumps.get(BspLump.LeafBrushes)!, leafs);\n const visibility = parseVisibility(buffer, lumps.get(BspLump.Visibility)!);\n\n return {\n header,\n entities,\n planes,\n vertices,\n nodes,\n texInfo,\n faces,\n lightMaps,\n lightMapInfo,\n leafs,\n leafLists,\n edges,\n surfEdges,\n models,\n brushes,\n brushSides,\n visibility,\n };\n}\n\nfunction parseEntities(buffer: ArrayBuffer, info: BspLumpInfo): BspEntities {\n const raw = new TextDecoder().decode(new Uint8Array(buffer, info.offset, info.length));\n const entities = parseEntityString(raw);\n const worldspawn = entities.find((ent) => ent.classname === 'worldspawn');\n return { raw, entities, worldspawn };\n}\n\nfunction parseEntityString(text: string): BspEntity[] {\n const entities: BspEntity[] = [];\n const tokenizer = /\\{([^}]*)\\}/gms;\n let match: RegExpExecArray | null;\n while ((match = tokenizer.exec(text)) !== null) {\n const entityText = match[1];\n const properties: Record<string, string> = {};\n const kvRegex = /\"([^\\\"]*)\"\\s+\"([^\\\"]*)\"/g;\n let kv: RegExpExecArray | null;\n while ((kv = kvRegex.exec(entityText)) !== null) {\n properties[kv[1]] = kv[2];\n }\n entities.push({ classname: properties.classname, properties });\n }\n return entities;\n}\n\nfunction parsePlanes(buffer: ArrayBuffer, info: BspLumpInfo): BspPlane[] {\n const view = new DataView(buffer, info.offset, info.length);\n const count = info.length / 20;\n if (count % 1 !== 0) {\n throw new BspParseError('Plane lump has invalid length');\n }\n const planes: BspPlane[] = [];\n for (let i = 0; i < count; i += 1) {\n const normal: Vec3 = [view.getFloat32(i * 20, true), view.getFloat32(i * 20 + 4, true), view.getFloat32(i * 20 + 8, true)];\n const dist = view.getFloat32(i * 20 + 12, true);\n const type = view.getInt32(i * 20 + 16, true);\n planes.push({ normal, dist, type });\n }\n return planes;\n}\n\nfunction parseVertices(buffer: ArrayBuffer, info: BspLumpInfo): Vec3[] {\n const view = new DataView(buffer, info.offset, info.length);\n const count = info.length / 12;\n if (count % 1 !== 0) {\n throw new BspParseError('Vertex lump has invalid length');\n }\n const vertices: Vec3[] = [];\n for (let i = 0; i < count; i += 1) {\n vertices.push([\n view.getFloat32(i * 12, true),\n view.getFloat32(i * 12 + 4, true),\n view.getFloat32(i * 12 + 8, true),\n ]);\n }\n return vertices;\n}\n\nfunction parseNodes(buffer: ArrayBuffer, info: BspLumpInfo): BspNode[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 36;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Node lump has invalid length');\n }\n const nodes: BspNode[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const planeIndex = view.getInt32(base, true);\n const children: [number, number] = [view.getInt32(base + 4, true), view.getInt32(base + 8, true)];\n const mins: [number, number, number] = [view.getInt16(base + 12, true), view.getInt16(base + 14, true), view.getInt16(base + 16, true)];\n const maxs: [number, number, number] = [view.getInt16(base + 18, true), view.getInt16(base + 20, true), view.getInt16(base + 22, true)];\n const firstFace = view.getUint16(base + 24, true);\n const numFaces = view.getUint16(base + 26, true);\n nodes.push({ planeIndex, children, mins, maxs, firstFace, numFaces });\n }\n return nodes;\n}\n\nfunction parseTexInfo(buffer: ArrayBuffer, info: BspLumpInfo): BspTexInfo[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 76;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('TexInfo lump has invalid length');\n }\n const texInfos: BspTexInfo[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const s: Vec3 = [view.getFloat32(base, true), view.getFloat32(base + 4, true), view.getFloat32(base + 8, true)];\n const sOffset = view.getFloat32(base + 12, true);\n const t: Vec3 = [view.getFloat32(base + 16, true), view.getFloat32(base + 20, true), view.getFloat32(base + 24, true)];\n const tOffset = view.getFloat32(base + 28, true);\n const flags = view.getInt32(base + 32, true);\n const value = view.getInt32(base + 36, true);\n const textureBytes = new Uint8Array(buffer, info.offset + base + 40, 32);\n const texture = new TextDecoder('utf-8').decode(textureBytes).replace(/\\0.*$/, '');\n const nextTexInfo = view.getInt32(base + 72, true);\n texInfos.push({ s, sOffset, t, tOffset, flags, value, texture, nextTexInfo });\n }\n return texInfos;\n}\n\nfunction parseFaces(buffer: ArrayBuffer, info: BspLumpInfo): BspFace[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 20;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Face lump has invalid length');\n }\n const faces: BspFace[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const planeIndex = view.getUint16(base, true);\n const side = view.getInt16(base + 2, true);\n const firstEdge = view.getInt32(base + 4, true);\n const numEdges = view.getInt16(base + 8, true);\n const texInfo = view.getInt16(base + 10, true);\n const styles: [number, number, number, number] = [\n view.getUint8(base + 12),\n view.getUint8(base + 13),\n view.getUint8(base + 14),\n view.getUint8(base + 15),\n ];\n const lightOffset = view.getInt32(base + 16, true);\n faces.push({ planeIndex, side, firstEdge, numEdges, texInfo, styles, lightOffset });\n }\n return faces;\n}\n\nfunction parseLeafs(buffer: ArrayBuffer, info: BspLumpInfo): BspLeaf[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 28;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Leaf lump has invalid length');\n }\n const leafs: BspLeaf[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const contents = view.getInt32(base, true);\n const cluster = view.getInt16(base + 4, true);\n const area = view.getInt16(base + 6, true);\n const mins: [number, number, number] = [view.getInt16(base + 8, true), view.getInt16(base + 10, true), view.getInt16(base + 12, true)];\n const maxs: [number, number, number] = [view.getInt16(base + 14, true), view.getInt16(base + 16, true), view.getInt16(base + 18, true)];\n const firstLeafFace = view.getUint16(base + 20, true);\n const numLeafFaces = view.getUint16(base + 22, true);\n const firstLeafBrush = view.getUint16(base + 24, true);\n const numLeafBrushes = view.getUint16(base + 26, true);\n leafs.push({ contents, cluster, area, mins, maxs, firstLeafFace, numLeafFaces, firstLeafBrush, numLeafBrushes });\n }\n return leafs;\n}\n\nfunction parseEdges(buffer: ArrayBuffer, info: BspLumpInfo): BspEdge[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 4;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Edge lump has invalid length');\n }\n const edges: BspEdge[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n edges.push({ vertices: [view.getUint16(base, true), view.getUint16(base + 2, true)] });\n }\n return edges;\n}\n\nfunction parseSurfEdges(buffer: ArrayBuffer, info: BspLumpInfo): Int32Array {\n const count = info.length / 4;\n if (count % 1 !== 0) {\n throw new BspParseError('SurfEdge lump has invalid length');\n }\n const view = new DataView(buffer, info.offset, info.length);\n const edges = new Int32Array(count);\n for (let i = 0; i < count; i += 1) {\n edges[i] = view.getInt32(i * 4, true);\n }\n return edges;\n}\n\nfunction parseModels(buffer: ArrayBuffer, info: BspLumpInfo): BspModel[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 48;\n if (info.length % entrySize !== 0) {\n throw new BspParseError('Model lump has invalid length');\n }\n const count = info.length / entrySize;\n const models: BspModel[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n const mins: Vec3 = [view.getFloat32(base, true), view.getFloat32(base + 4, true), view.getFloat32(base + 8, true)];\n const maxs: Vec3 = [view.getFloat32(base + 12, true), view.getFloat32(base + 16, true), view.getFloat32(base + 20, true)];\n const origin: Vec3 = [view.getFloat32(base + 24, true), view.getFloat32(base + 28, true), view.getFloat32(base + 32, true)];\n const headNode = view.getInt32(base + 36, true);\n const firstFace = view.getInt32(base + 40, true);\n const numFaces = view.getInt32(base + 44, true);\n models.push({ mins, maxs, origin, headNode, firstFace, numFaces });\n }\n return models;\n}\n\nfunction parseBrushes(buffer: ArrayBuffer, info: BspLumpInfo): BspBrush[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 12;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Brush lump has invalid length');\n }\n const brushes: BspBrush[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n brushes.push({\n firstSide: view.getInt32(base, true),\n numSides: view.getInt32(base + 4, true),\n contents: view.getInt32(base + 8, true),\n });\n }\n return brushes;\n}\n\nfunction parseBrushSides(buffer: ArrayBuffer, info: BspLumpInfo): BspBrushSide[] {\n const view = new DataView(buffer, info.offset, info.length);\n const entrySize = 8;\n const count = info.length / entrySize;\n if (count % 1 !== 0) {\n throw new BspParseError('Brush side lump has invalid length');\n }\n const sides: BspBrushSide[] = [];\n for (let i = 0; i < count; i += 1) {\n const base = i * entrySize;\n sides.push({ planeIndex: view.getUint16(base, true), texInfo: view.getInt16(base + 2, true) });\n }\n return sides;\n}\n\nfunction parseLeafLists(\n buffer: ArrayBuffer,\n leafFacesInfo: BspLumpInfo,\n leafBrushesInfo: BspLumpInfo,\n leafs: readonly BspLeaf[],\n): BspLeafLists {\n const leafFaces: number[][] = [];\n const leafBrushes: number[][] = [];\n\n const maxLeafFaceIndex = leafFacesInfo.length / 2;\n const maxLeafBrushIndex = leafBrushesInfo.length / 2;\n\n const faceView = new DataView(buffer, leafFacesInfo.offset, leafFacesInfo.length);\n const brushView = new DataView(buffer, leafBrushesInfo.offset, leafBrushesInfo.length);\n\n for (const leaf of leafs) {\n if (leaf.firstLeafFace + leaf.numLeafFaces > maxLeafFaceIndex) {\n throw new BspParseError('Leaf faces reference data past lump bounds');\n }\n if (leaf.firstLeafBrush + leaf.numLeafBrushes > maxLeafBrushIndex) {\n throw new BspParseError('Leaf brushes reference data past lump bounds');\n }\n const faces: number[] = [];\n for (let i = 0; i < leaf.numLeafFaces; i += 1) {\n faces.push(faceView.getUint16((leaf.firstLeafFace + i) * 2, true));\n }\n\n const brushes: number[] = [];\n for (let i = 0; i < leaf.numLeafBrushes; i += 1) {\n brushes.push(brushView.getUint16((leaf.firstLeafBrush + i) * 2, true));\n }\n\n leafFaces.push(faces);\n leafBrushes.push(brushes);\n }\n\n return { leafFaces, leafBrushes };\n}\n\nfunction parseVisibility(buffer: ArrayBuffer, info: BspLumpInfo): BspVisibility | undefined {\n if (info.length === 0) {\n return undefined;\n }\n if (info.length < 4) {\n throw new BspParseError('Visibility lump too small');\n }\n const view = new DataView(buffer, info.offset, info.length);\n const numClusters = view.getInt32(0, true);\n const headerBytes = 4 + numClusters * 8;\n if (numClusters < 0 || headerBytes > info.length) {\n throw new BspParseError('Visibility lump truncated');\n }\n let cursor = 4;\n const clusters: BspVisibilityCluster[] = [];\n for (let i = 0; i < numClusters; i += 1) {\n const pvsOffset = view.getInt32(cursor, true);\n const phsOffset = view.getInt32(cursor + 4, true);\n cursor += 8;\n const absolutePvs = info.offset + pvsOffset;\n const absolutePhs = info.offset + phsOffset;\n const lumpEnd = info.offset + info.length;\n if (\n pvsOffset < 0 ||\n phsOffset < 0 ||\n absolutePvs >= lumpEnd ||\n absolutePhs >= lumpEnd\n ) {\n throw new BspParseError('Visibility offsets out of range');\n }\n clusters.push({\n pvs: decompressVis(buffer, absolutePvs, numClusters, info),\n phs: decompressVis(buffer, absolutePhs, numClusters, info),\n });\n }\n return { numClusters, clusters };\n}\n\nfunction decompressVis(buffer: ArrayBuffer, offset: number, numClusters: number, lump: BspLumpInfo): Uint8Array {\n const rowBytes = Math.ceil(numClusters / 8);\n const result = new Uint8Array(rowBytes);\n const src = new Uint8Array(buffer);\n let srcIndex = offset;\n let destIndex = 0;\n const maxOffset = lump.offset + lump.length;\n while (destIndex < rowBytes) {\n if (srcIndex >= maxOffset) {\n throw new BspParseError('Visibility data truncated');\n }\n const value = src[srcIndex++];\n if (value !== 0) {\n result[destIndex++] = value;\n continue;\n }\n if (srcIndex >= maxOffset) {\n throw new BspParseError('Visibility run exceeds lump bounds');\n }\n const runLength = src[srcIndex++];\n for (let i = 0; i < runLength && destIndex < rowBytes; i += 1) {\n result[destIndex++] = 0;\n }\n }\n return result;\n}\n\nfunction buildLightMapInfo(faces: readonly BspFace[], lightingLump: BspLumpInfo): (BspLightmapInfo | undefined)[] {\n return faces.map((face) => {\n if (face.lightOffset < 0) {\n return undefined;\n }\n return {\n offset: face.lightOffset,\n length: Math.max(0, lightingLump.length - face.lightOffset),\n };\n });\n}\n\nexport function createFaceLightmap(\n face: BspFace,\n lightMaps: Uint8Array,\n info?: BspLightmapInfo,\n): Uint8Array | undefined {\n if (face.lightOffset < 0 || face.lightOffset >= lightMaps.byteLength) {\n return undefined;\n }\n const available = lightMaps.byteLength - face.lightOffset;\n const length = Math.min(info?.length ?? available, available);\n if (length <= 0) {\n return undefined;\n }\n return lightMaps.subarray(face.lightOffset, face.lightOffset + length);\n}\n\nexport function parseWorldspawnSettings(entities: BspEntities): Record<string, string> {\n return entities.worldspawn?.properties ?? {};\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { VirtualFileSystem } from './vfs.js';\n\nconst MD2_MAGIC = 844121161; // 'IDP2'\nconst MD2_VERSION = 8;\nconst HEADER_SIZE = 17 * 4;\nconst MD2_NORMALS: ReadonlyArray<Vec3> = [\n { x: -0.525731, y: 0.0, z: 0.850651 },\n { x: -0.442863, y: 0.238856, z: 0.864188 },\n { x: -0.295242, y: 0.0, z: 0.955423 },\n { x: -0.309017, y: 0.5, z: 0.809017 },\n { x: -0.16246, y: 0.262866, z: 0.951056 },\n { x: 0.0, y: 0.0, z: 1.0 },\n { x: 0.0, y: 0.850651, z: 0.525731 },\n { x: -0.147621, y: 0.716567, z: 0.681718 },\n { x: 0.147621, y: 0.716567, z: 0.681718 },\n { x: 0.0, y: 0.525731, z: 0.850651 },\n { x: 0.309017, y: 0.5, z: 0.809017 },\n { x: 0.525731, y: 0.0, z: 0.850651 },\n { x: 0.295242, y: 0.0, z: 0.955423 },\n { x: 0.442863, y: 0.238856, z: 0.864188 },\n { x: 0.16246, y: 0.262866, z: 0.951056 },\n { x: -0.681718, y: 0.147621, z: 0.716567 },\n { x: -0.809017, y: 0.309017, z: 0.5 },\n { x: -0.587785, y: 0.425325, z: 0.688191 },\n { x: -0.850651, y: 0.525731, z: 0.0 },\n { x: -0.864188, y: 0.442863, z: 0.238856 },\n { x: -0.716567, y: 0.681718, z: 0.147621 },\n { x: -0.688191, y: 0.587785, z: 0.425325 },\n { x: -0.5000, y: 0.809017, z: 0.309017 },\n { x: -0.238856, y: 0.864188, z: 0.442863 },\n { x: -0.425325, y: 0.688191, z: 0.587785 },\n { x: -0.716567, y: 0.681718, z: -0.147621 },\n { x: -0.5000, y: 0.809017, z: -0.309017 },\n { x: -0.525731, y: 0.850651, z: 0.0 },\n { x: 0.0, y: 0.850651, z: -0.525731 },\n { x: -0.238856, y: 0.864188, z: -0.442863 },\n { x: 0.0, y: 0.955423, z: -0.295242 },\n { x: -0.262866, y: 0.951056, z: -0.16246 },\n { x: 0.0, y: 1.0, z: 0.0 },\n { x: 0.0, y: 0.955423, z: 0.295242 },\n { x: -0.262866, y: 0.951056, z: 0.16246 },\n { x: 0.238856, y: 0.864188, z: 0.442863 },\n { x: 0.262866, y: 0.951056, z: 0.16246 },\n { x: 0.5, y: 0.809017, z: 0.309017 },\n { x: 0.238856, y: 0.864188, z: -0.442863 },\n { x: 0.262866, y: 0.951056, z: -0.16246 },\n { x: 0.5, y: 0.809017, z: -0.309017 },\n { x: 0.850651, y: 0.525731, z: 0.0 },\n { x: 0.716567, y: 0.681718, z: 0.147621 },\n { x: 0.716567, y: 0.681718, z: -0.147621 },\n { x: 0.525731, y: 0.850651, z: 0.0 },\n { x: 0.425325, y: 0.688191, z: 0.587785 },\n { x: 0.864188, y: 0.442863, z: 0.238856 },\n { x: 0.688191, y: 0.587785, z: 0.425325 },\n { x: 0.809017, y: 0.309017, z: 0.5 },\n { x: 0.681718, y: 0.147621, z: 0.716567 },\n { x: 0.587785, y: 0.425325, z: 0.688191 },\n { x: 0.955423, y: 0.295242, z: 0.0 },\n { x: 1.0, y: 0.0, z: 0.0 },\n { x: 0.951056, y: 0.16246, z: 0.262866 },\n { x: 0.850651, y: -0.525731, z: 0.0 },\n { x: 0.955423, y: -0.295242, z: 0.0 },\n { x: 0.864188, y: -0.442863, z: 0.238856 },\n { x: 0.951056, y: -0.16246, z: 0.262866 },\n { x: 0.809017, y: -0.309017, z: 0.5 },\n { x: 0.681718, y: -0.147621, z: 0.716567 },\n { x: 0.850651, y: 0.0, z: 0.525731 },\n { x: 0.864188, y: 0.442863, z: -0.238856 },\n { x: 0.809017, y: 0.309017, z: -0.5 },\n { x: 0.951056, y: 0.16246, z: -0.262866 },\n { x: 0.525731, y: 0.0, z: -0.850651 },\n { x: 0.681718, y: 0.147621, z: -0.716567 },\n { x: 0.681718, y: -0.147621, z: -0.716567 },\n { x: 0.850651, y: 0.0, z: -0.525731 },\n { x: 0.809017, y: -0.309017, z: -0.5 },\n { x: 0.864188, y: -0.442863, z: -0.238856 },\n { x: 0.951056, y: -0.16246, z: -0.262866 },\n { x: 0.147621, y: 0.716567, z: -0.681718 },\n { x: 0.309017, y: 0.5, z: -0.809017 },\n { x: 0.425325, y: 0.688191, z: -0.587785 },\n { x: 0.442863, y: 0.238856, z: -0.864188 },\n { x: 0.587785, y: 0.425325, z: -0.688191 },\n { x: 0.688191, y: 0.587785, z: -0.425325 },\n { x: -0.147621, y: 0.716567, z: -0.681718 },\n { x: -0.309017, y: 0.5, z: -0.809017 },\n { x: 0.0, y: 0.525731, z: -0.850651 },\n { x: -0.525731, y: 0.0, z: -0.850651 },\n { x: -0.442863, y: 0.238856, z: -0.864188 },\n { x: -0.295242, y: 0.0, z: -0.955423 },\n { x: -0.16246, y: 0.262866, z: -0.951056 },\n { x: 0.0, y: 0.0, z: -1.0 },\n { x: 0.295242, y: 0.0, z: -0.955423 },\n { x: 0.16246, y: 0.262866, z: -0.951056 },\n { x: -0.442863, y: -0.238856, z: -0.864188 },\n { x: -0.309017, y: -0.5, z: -0.809017 },\n { x: -0.16246, y: -0.262866, z: -0.951056 },\n { x: 0.0, y: -0.850651, z: -0.525731 },\n { x: -0.147621, y: -0.716567, z: -0.681718 },\n { x: 0.147621, y: -0.716567, z: -0.681718 },\n { x: 0.0, y: -0.525731, z: -0.850651 },\n { x: 0.309017, y: -0.5, z: -0.809017 },\n { x: 0.442863, y: -0.238856, z: -0.864188 },\n { x: 0.16246, y: -0.262866, z: -0.951056 },\n { x: 0.238856, y: -0.864188, z: -0.442863 },\n { x: 0.5, y: -0.809017, z: -0.309017 },\n { x: 0.425325, y: -0.688191, z: -0.587785 },\n { x: 0.716567, y: -0.681718, z: -0.147621 },\n { x: 0.688191, y: -0.587785, z: -0.425325 },\n { x: 0.587785, y: -0.425325, z: -0.688191 },\n { x: 0.0, y: -0.955423, z: -0.295242 },\n { x: 0.0, y: -1.0, z: 0.0 },\n { x: 0.262866, y: -0.951056, z: -0.16246 },\n { x: 0.0, y: -0.850651, z: 0.525731 },\n { x: 0.0, y: -0.955423, z: 0.295242 },\n { x: 0.238856, y: -0.864188, z: 0.442863 },\n { x: 0.262866, y: -0.951056, z: 0.16246 },\n { x: 0.5, y: -0.809017, z: 0.309017 },\n { x: 0.716567, y: -0.681718, z: 0.147621 },\n { x: 0.525731, y: -0.850651, z: 0.0 },\n { x: -0.238856, y: -0.864188, z: -0.442863 },\n { x: -0.5, y: -0.809017, z: -0.309017 },\n { x: -0.262866, y: -0.951056, z: -0.16246 },\n { x: -0.850651, y: -0.525731, z: 0.0 },\n { x: -0.716567, y: -0.681718, z: -0.147621 },\n { x: -0.716567, y: -0.681718, z: 0.147621 },\n { x: -0.525731, y: -0.850651, z: 0.0 },\n { x: -0.5, y: -0.809017, z: 0.309017 },\n { x: -0.238856, y: -0.864188, z: 0.442863 },\n { x: -0.262866, y: -0.951056, z: 0.16246 },\n { x: -0.864188, y: -0.442863, z: 0.238856 },\n { x: -0.809017, y: -0.309017, z: 0.5 },\n { x: -0.688191, y: -0.587785, z: 0.425325 },\n { x: -0.681718, y: -0.147621, z: 0.716567 },\n { x: -0.442863, y: -0.238856, z: 0.864188 },\n { x: -0.587785, y: -0.425325, z: 0.688191 },\n { x: -0.309017, y: -0.5, z: 0.809017 },\n { x: -0.147621, y: -0.716567, z: 0.681718 },\n { x: -0.425325, y: -0.688191, z: 0.587785 },\n { x: -0.16246, y: -0.262866, z: 0.951056 },\n { x: 0.442863, y: -0.238856, z: 0.864188 },\n { x: 0.16246, y: -0.262866, z: 0.951056 },\n { x: 0.309017, y: -0.5, z: 0.809017 },\n { x: 0.147621, y: -0.716567, z: 0.681718 },\n { x: 0.0, y: -0.525731, z: 0.850651 },\n { x: 0.425325, y: -0.688191, z: 0.587785 },\n { x: 0.587785, y: -0.425325, z: 0.688191 },\n { x: 0.688191, y: -0.587785, z: 0.425325 },\n { x: -0.955423, y: 0.295242, z: 0.0 },\n { x: -0.951056, y: 0.16246, z: 0.262866 },\n { x: -1.0, y: 0.0, z: 0.0 },\n { x: -0.850651, y: 0.0, z: 0.525731 },\n { x: -0.955423, y: -0.295242, z: 0.0 },\n { x: -0.951056, y: -0.16246, z: 0.262866 },\n { x: -0.864188, y: 0.442863, z: -0.238856 },\n { x: -0.951056, y: 0.16246, z: -0.262866 },\n { x: -0.809017, y: 0.309017, z: -0.5 },\n { x: -0.864188, y: -0.442863, z: -0.238856 },\n { x: -0.951056, y: -0.16246, z: -0.262866 },\n { x: -0.809017, y: -0.309017, z: -0.5 },\n { x: -0.681718, y: 0.147621, z: -0.716567 },\n { x: -0.681718, y: -0.147621, z: -0.716567 },\n { x: -0.850651, y: 0.0, z: -0.525731 },\n { x: -0.688191, y: 0.587785, z: -0.425325 },\n { x: -0.587785, y: 0.425325, z: -0.688191 },\n { x: -0.425325, y: 0.688191, z: -0.587785 },\n { x: -0.425325, y: -0.688191, z: -0.587785 },\n { x: -0.587785, y: -0.425325, z: -0.688191 },\n { x: -0.688191, y: -0.587785, z: -0.425325 },\n];\n\nexport interface Md2Header {\n readonly ident: number;\n readonly version: number;\n readonly skinWidth: number;\n readonly skinHeight: number;\n readonly frameSize: number;\n readonly numSkins: number;\n readonly numVertices: number;\n readonly numTexCoords: number;\n readonly numTriangles: number;\n readonly numGlCommands: number;\n readonly numFrames: number;\n readonly offsetSkins: number;\n readonly offsetTexCoords: number;\n readonly offsetTriangles: number;\n readonly offsetFrames: number;\n readonly offsetGlCommands: number;\n readonly offsetEnd: number;\n}\n\nexport interface Md2Skin {\n readonly name: string;\n}\n\nexport interface Md2TexCoord {\n readonly s: number;\n readonly t: number;\n}\n\nexport interface Md2Triangle {\n readonly vertexIndices: [number, number, number];\n readonly texCoordIndices: [number, number, number];\n}\n\nexport interface Md2Vertex {\n readonly position: Vec3;\n readonly normalIndex: number;\n readonly normal: Vec3;\n}\n\nexport interface Md2Frame {\n readonly name: string;\n readonly vertices: readonly Md2Vertex[];\n}\n\nexport interface Md2GlCommandVertex {\n readonly s: number;\n readonly t: number;\n readonly vertexIndex: number;\n}\n\nexport interface Md2GlCommand {\n readonly mode: 'strip' | 'fan';\n readonly vertices: readonly Md2GlCommandVertex[];\n}\n\nexport interface Md2Model {\n readonly header: Md2Header;\n readonly skins: readonly Md2Skin[];\n readonly texCoords: readonly Md2TexCoord[];\n readonly triangles: readonly Md2Triangle[];\n readonly frames: readonly Md2Frame[];\n readonly glCommands: readonly Md2GlCommand[];\n}\n\nexport interface Md2Animation {\n readonly name: string;\n readonly firstFrame: number;\n readonly lastFrame: number;\n}\n\nexport class Md2ParseError extends Error {}\n\nexport class Md2Loader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<Md2Model> {\n const bytes = await this.vfs.readFile(path);\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return parseMd2(copy.buffer);\n }\n}\n\nfunction readCString(view: DataView, offset: number, maxLength: number): string {\n const chars: number[] = [];\n for (let i = 0; i < maxLength; i += 1) {\n const code = view.getUint8(offset + i);\n if (code === 0) break;\n chars.push(code);\n }\n return String.fromCharCode(...chars);\n}\n\nfunction validateSection(buffer: ArrayBuffer, offset: number, length: number, label: string): void {\n if (length === 0) return;\n if (offset < HEADER_SIZE || offset + length > buffer.byteLength) {\n throw new Md2ParseError(`${label} section is out of bounds`);\n }\n}\n\nfunction parseHeader(buffer: ArrayBuffer): Md2Header {\n if (buffer.byteLength < HEADER_SIZE) {\n throw new Md2ParseError('MD2 buffer too small to contain header');\n }\n\n const view = new DataView(buffer);\n const ident = view.getInt32(0, true);\n const version = view.getInt32(4, true);\n\n if (ident !== MD2_MAGIC) {\n throw new Md2ParseError(`Invalid MD2 ident: ${ident}`);\n }\n if (version !== MD2_VERSION) {\n throw new Md2ParseError(`Unsupported MD2 version: ${version}`);\n }\n\n const header: Md2Header = {\n ident,\n version,\n skinWidth: view.getInt32(8, true),\n skinHeight: view.getInt32(12, true),\n frameSize: view.getInt32(16, true),\n numSkins: view.getInt32(20, true),\n numVertices: view.getInt32(24, true),\n numTexCoords: view.getInt32(28, true),\n numTriangles: view.getInt32(32, true),\n numGlCommands: view.getInt32(36, true),\n numFrames: view.getInt32(40, true),\n offsetSkins: view.getInt32(44, true),\n offsetTexCoords: view.getInt32(48, true),\n offsetTriangles: view.getInt32(52, true),\n offsetFrames: view.getInt32(56, true),\n offsetGlCommands: view.getInt32(60, true),\n offsetEnd: view.getInt32(64, true),\n };\n\n const expectedFrameSize = 40 + header.numVertices * 4;\n if (header.frameSize !== expectedFrameSize) {\n throw new Md2ParseError(`Unexpected frame size ${header.frameSize}, expected ${expectedFrameSize}`);\n }\n\n if (header.offsetEnd > buffer.byteLength) {\n throw new Md2ParseError('MD2 offset_end exceeds buffer length');\n }\n\n return header;\n}\n\nfunction parseSkins(buffer: ArrayBuffer, header: Md2Header): Md2Skin[] {\n const size = header.numSkins * 64;\n validateSection(buffer, header.offsetSkins, size, 'skins');\n const view = new DataView(buffer, header.offsetSkins, size);\n const skins: Md2Skin[] = [];\n for (let i = 0; i < header.numSkins; i += 1) {\n skins.push({ name: readCString(view, i * 64, 64) });\n }\n return skins;\n}\n\nfunction parseTexCoords(buffer: ArrayBuffer, header: Md2Header): Md2TexCoord[] {\n const size = header.numTexCoords * 4;\n validateSection(buffer, header.offsetTexCoords, size, 'texcoords');\n const view = new DataView(buffer, header.offsetTexCoords, size);\n const texCoords: Md2TexCoord[] = [];\n for (let i = 0; i < header.numTexCoords; i += 1) {\n const base = i * 4;\n texCoords.push({ s: view.getInt16(base, true), t: view.getInt16(base + 2, true) });\n }\n return texCoords;\n}\n\nfunction parseTriangles(buffer: ArrayBuffer, header: Md2Header): Md2Triangle[] {\n const size = header.numTriangles * 12;\n validateSection(buffer, header.offsetTriangles, size, 'triangles');\n const view = new DataView(buffer, header.offsetTriangles, size);\n const triangles: Md2Triangle[] = [];\n\n for (let i = 0; i < header.numTriangles; i += 1) {\n const base = i * 12;\n const vertexIndices: [number, number, number] = [\n view.getUint16(base, true),\n view.getUint16(base + 2, true),\n view.getUint16(base + 4, true),\n ];\n const texCoordIndices: [number, number, number] = [\n view.getUint16(base + 6, true),\n view.getUint16(base + 8, true),\n view.getUint16(base + 10, true),\n ];\n\n if (vertexIndices.some((v) => v >= header.numVertices) || texCoordIndices.some((t) => t >= header.numTexCoords)) {\n throw new Md2ParseError('Triangle references out of range vertex or texcoord');\n }\n\n triangles.push({ vertexIndices, texCoordIndices });\n }\n\n return triangles;\n}\n\nfunction parseFrames(buffer: ArrayBuffer, header: Md2Header): Md2Frame[] {\n const size = header.numFrames * header.frameSize;\n validateSection(buffer, header.offsetFrames, size, 'frames');\n const frames: Md2Frame[] = [];\n\n for (let i = 0; i < header.numFrames; i += 1) {\n const base = header.offsetFrames + i * header.frameSize;\n const view = new DataView(buffer, base, header.frameSize);\n const scale: Vec3 = { x: view.getFloat32(0, true), y: view.getFloat32(4, true), z: view.getFloat32(8, true) };\n const translate: Vec3 = {\n x: view.getFloat32(12, true),\n y: view.getFloat32(16, true),\n z: view.getFloat32(20, true),\n };\n const name = readCString(view, 24, 16);\n const vertices: Md2Vertex[] = [];\n\n for (let v = 0; v < header.numVertices; v += 1) {\n const offset = 40 + v * 4;\n const position: Vec3 = {\n x: view.getUint8(offset) * scale.x + translate.x,\n y: view.getUint8(offset + 1) * scale.y + translate.y,\n z: view.getUint8(offset + 2) * scale.z + translate.z,\n };\n const normalIndex = view.getUint8(offset + 3);\n const normal = MD2_NORMALS[normalIndex];\n if (!normal) {\n throw new Md2ParseError(`Invalid normal index ${normalIndex} in frame ${name}`);\n }\n vertices.push({ position, normalIndex, normal });\n }\n\n frames.push({ name, vertices });\n }\n\n return frames;\n}\n\nfunction parseGlCommands(buffer: ArrayBuffer, header: Md2Header): Md2GlCommand[] {\n const size = header.numGlCommands * 4;\n validateSection(buffer, header.offsetGlCommands, size, 'gl commands');\n if (size === 0) {\n return [];\n }\n const view = new DataView(buffer, header.offsetGlCommands, size);\n const commands: Md2GlCommand[] = [];\n let cursor = 0;\n\n while (true) {\n if (cursor + 4 > size) {\n throw new Md2ParseError('GL command list ended unexpectedly');\n }\n const count = view.getInt32(cursor, true);\n cursor += 4;\n if (count === 0) break;\n const vertexCount = Math.abs(count);\n const vertices: Md2GlCommandVertex[] = [];\n const bytesNeeded = vertexCount * 12;\n if (cursor + bytesNeeded > size) {\n throw new Md2ParseError('GL command vertex block exceeds buffer');\n }\n for (let i = 0; i < vertexCount; i += 1) {\n const s = view.getFloat32(cursor, true);\n const t = view.getFloat32(cursor + 4, true);\n const vertexIndex = view.getInt32(cursor + 8, true);\n cursor += 12;\n if (vertexIndex < 0 || vertexIndex >= header.numVertices) {\n throw new Md2ParseError('GL command references invalid vertex index');\n }\n vertices.push({ s, t, vertexIndex });\n }\n commands.push({ mode: count > 0 ? 'strip' : 'fan', vertices });\n }\n\n if (cursor !== size) {\n throw new Md2ParseError('GL command list did not consume expected data');\n }\n\n return commands;\n}\n\nexport function parseMd2(buffer: ArrayBuffer): Md2Model {\n const header = parseHeader(buffer);\n const skins = parseSkins(buffer, header);\n const texCoords = parseTexCoords(buffer, header);\n const triangles = parseTriangles(buffer, header);\n const frames = parseFrames(buffer, header);\n const glCommands = parseGlCommands(buffer, header);\n\n return { header, skins, texCoords, triangles, frames, glCommands };\n}\n\nexport function groupMd2Animations(frames: readonly Md2Frame[]): Md2Animation[] {\n const animations: Md2Animation[] = [];\n let index = 0;\n while (index < frames.length) {\n const name = frames[index].name;\n const base = name.replace(/\\d+$/, '') || name;\n let end = index;\n while (end + 1 < frames.length) {\n const nextBase = frames[end + 1].name.replace(/\\d+$/, '') || frames[end + 1].name;\n if (nextBase !== base) break;\n end += 1;\n }\n animations.push({ name: base, firstFrame: index, lastFrame: end });\n index = end + 1;\n }\n return animations;\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { VirtualFileSystem } from './vfs.js';\n\nconst MD3_IDENT = 860898377; // 'IDP3'\nconst MD3_VERSION = 15;\n\nexport interface Md3Header {\n readonly ident: number;\n readonly version: number;\n readonly name: string;\n readonly flags: number;\n readonly numFrames: number;\n readonly numTags: number;\n readonly numSurfaces: number;\n readonly numSkins: number;\n readonly ofsFrames: number;\n readonly ofsTags: number;\n readonly ofsSurfaces: number;\n readonly ofsEnd: number;\n}\n\nexport interface Md3Frame {\n readonly minBounds: Vec3;\n readonly maxBounds: Vec3;\n readonly localOrigin: Vec3;\n readonly radius: number;\n readonly name: string;\n}\n\nexport interface Md3Tag {\n readonly name: string;\n readonly origin: Vec3;\n readonly axis: readonly [Vec3, Vec3, Vec3];\n}\n\nexport interface Md3Triangle {\n readonly indices: readonly [number, number, number];\n}\n\nexport interface Md3Shader {\n readonly name: string;\n readonly shaderIndex: number;\n}\n\nexport interface Md3TexCoord {\n readonly s: number;\n readonly t: number;\n}\n\nexport interface Md3Vertex {\n readonly position: Vec3;\n readonly normal: Vec3;\n readonly latLng: number;\n}\n\nexport interface Md3Surface {\n readonly name: string;\n readonly flags: number;\n readonly numFrames: number;\n readonly shaders: readonly Md3Shader[];\n readonly triangles: readonly Md3Triangle[];\n readonly texCoords: readonly Md3TexCoord[];\n readonly vertices: readonly (readonly Md3Vertex[])[];\n}\n\nexport interface Md3Model {\n readonly header: Md3Header;\n readonly frames: readonly Md3Frame[];\n readonly tags: readonly Md3Tag[][];\n readonly surfaces: readonly Md3Surface[];\n}\n\nexport class Md3ParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'Md3ParseError';\n }\n}\n\nfunction readString(view: DataView, offset: number, length: number): string {\n const bytes = new Uint8Array(view.buffer, view.byteOffset + offset, length);\n const decoded = new TextDecoder('utf-8').decode(bytes);\n return decoded.replace(/\\0.*$/, '').trim();\n}\n\nfunction decodeLatLngNormal(latLng: number): Vec3 {\n const lat = ((latLng >> 8) & 0xff) * (2 * Math.PI / 255);\n const lng = (latLng & 0xff) * (2 * Math.PI / 255);\n const sinLng = Math.sin(lng);\n return {\n x: Math.cos(lat) * sinLng,\n y: Math.sin(lat) * sinLng,\n z: Math.cos(lng),\n };\n}\n\nfunction validateOffset(name: string, offset: number, size: number, bufferLength: number): void {\n if (offset < 0 || offset + size > bufferLength) {\n throw new Md3ParseError(`${name} exceeds buffer bounds`);\n }\n}\n\nfunction parseHeader(view: DataView): Md3Header {\n const ident = view.getInt32(0, true);\n if (ident !== MD3_IDENT) {\n throw new Md3ParseError(`Invalid MD3 ident: ${ident}`);\n }\n const version = view.getInt32(4, true);\n if (version !== MD3_VERSION) {\n throw new Md3ParseError(`Unsupported MD3 version: ${version}`);\n }\n\n const name = readString(view, 8, 64);\n const flags = view.getInt32(72, true);\n const numFrames = view.getInt32(76, true);\n const numTags = view.getInt32(80, true);\n const numSurfaces = view.getInt32(84, true);\n const numSkins = view.getInt32(88, true);\n const ofsFrames = view.getInt32(92, true);\n const ofsTags = view.getInt32(96, true);\n const ofsSurfaces = view.getInt32(100, true);\n const ofsEnd = view.getInt32(104, true);\n\n if (numFrames <= 0 || numSurfaces < 0 || numTags < 0) {\n throw new Md3ParseError('Invalid MD3 counts');\n }\n\n return {\n ident,\n version,\n name,\n flags,\n numFrames,\n numTags,\n numSurfaces,\n numSkins,\n ofsFrames,\n ofsTags,\n ofsSurfaces,\n ofsEnd,\n };\n}\n\nfunction parseFrames(view: DataView, header: Md3Header): Md3Frame[] {\n const frames: Md3Frame[] = [];\n const frameSize = 56;\n validateOffset('Frames', header.ofsFrames, header.numFrames * frameSize, view.byteLength);\n\n for (let i = 0; i < header.numFrames; i += 1) {\n const base = header.ofsFrames + i * frameSize;\n frames.push({\n minBounds: {\n x: view.getFloat32(base, true),\n y: view.getFloat32(base + 4, true),\n z: view.getFloat32(base + 8, true),\n },\n maxBounds: {\n x: view.getFloat32(base + 12, true),\n y: view.getFloat32(base + 16, true),\n z: view.getFloat32(base + 20, true),\n },\n localOrigin: {\n x: view.getFloat32(base + 24, true),\n y: view.getFloat32(base + 28, true),\n z: view.getFloat32(base + 32, true),\n },\n radius: view.getFloat32(base + 36, true),\n name: readString(view, base + 40, 16),\n });\n }\n\n return frames;\n}\n\nfunction parseTags(view: DataView, header: Md3Header): Md3Tag[][] {\n const tags: Md3Tag[][] = [];\n const tagSize = 112;\n const totalSize = header.numFrames * header.numTags * tagSize;\n validateOffset('Tags', header.ofsTags, totalSize, view.byteLength);\n\n for (let frame = 0; frame < header.numFrames; frame += 1) {\n const frameTags: Md3Tag[] = [];\n for (let tagIndex = 0; tagIndex < header.numTags; tagIndex += 1) {\n const base = header.ofsTags + (frame * header.numTags + tagIndex) * tagSize;\n const originOffset = base + 64;\n const axisOffset = originOffset + 12;\n frameTags.push({\n name: readString(view, base, 64),\n origin: {\n x: view.getFloat32(originOffset, true),\n y: view.getFloat32(originOffset + 4, true),\n z: view.getFloat32(originOffset + 8, true),\n },\n axis: [\n {\n x: view.getFloat32(axisOffset, true),\n y: view.getFloat32(axisOffset + 4, true),\n z: view.getFloat32(axisOffset + 8, true),\n },\n {\n x: view.getFloat32(axisOffset + 12, true),\n y: view.getFloat32(axisOffset + 16, true),\n z: view.getFloat32(axisOffset + 20, true),\n },\n {\n x: view.getFloat32(axisOffset + 24, true),\n y: view.getFloat32(axisOffset + 28, true),\n z: view.getFloat32(axisOffset + 32, true),\n },\n ],\n });\n }\n tags.push(frameTags);\n }\n\n return tags;\n}\n\nfunction parseSurface(view: DataView, offset: number): { surface: Md3Surface; nextOffset: number } {\n const ident = view.getInt32(offset, true);\n if (ident !== MD3_IDENT) {\n throw new Md3ParseError(`Invalid surface ident at ${offset}: ${ident}`);\n }\n\n const name = readString(view, offset + 4, 64);\n const flags = view.getInt32(offset + 68, true);\n const numFrames = view.getInt32(offset + 72, true);\n const numShaders = view.getInt32(offset + 76, true);\n const numVerts = view.getInt32(offset + 80, true);\n const numTriangles = view.getInt32(offset + 84, true);\n const ofsTriangles = view.getInt32(offset + 88, true);\n const ofsShaders = view.getInt32(offset + 92, true);\n const ofsSt = view.getInt32(offset + 96, true);\n const ofsXyzNormals = view.getInt32(offset + 100, true);\n const ofsEnd = view.getInt32(offset + 104, true);\n\n if (numFrames <= 0 || numVerts <= 0 || numTriangles <= 0) {\n throw new Md3ParseError(`Invalid surface counts for ${name}`);\n }\n\n const surfaceSize = ofsEnd;\n validateOffset(`Surface ${name}`, offset, surfaceSize, view.byteLength);\n\n const triangles: Md3Triangle[] = [];\n const triangleStart = offset + ofsTriangles;\n for (let i = 0; i < numTriangles; i += 1) {\n const base = triangleStart + i * 12;\n triangles.push({\n indices: [view.getInt32(base, true), view.getInt32(base + 4, true), view.getInt32(base + 8, true)],\n });\n }\n\n const shaders: Md3Shader[] = [];\n const shaderStart = offset + ofsShaders;\n for (let i = 0; i < numShaders; i += 1) {\n const base = shaderStart + i * 68;\n shaders.push({ name: readString(view, base, 64), shaderIndex: view.getInt32(base + 64, true) });\n }\n\n const texCoords: Md3TexCoord[] = [];\n const stStart = offset + ofsSt;\n for (let i = 0; i < numVerts; i += 1) {\n const base = stStart + i * 8;\n texCoords.push({ s: view.getFloat32(base, true), t: view.getFloat32(base + 4, true) });\n }\n\n const vertices: Md3Vertex[][] = [];\n const xyzStart = offset + ofsXyzNormals;\n for (let frame = 0; frame < numFrames; frame += 1) {\n const frameVertices: Md3Vertex[] = [];\n for (let i = 0; i < numVerts; i += 1) {\n const base = xyzStart + (frame * numVerts + i) * 8;\n const x = view.getInt16(base, true) / 64;\n const y = view.getInt16(base + 2, true) / 64;\n const z = view.getInt16(base + 4, true) / 64;\n const latLng = view.getUint16(base + 6, true);\n frameVertices.push({ position: { x, y, z }, latLng, normal: decodeLatLngNormal(latLng) });\n }\n vertices.push(frameVertices);\n }\n\n return {\n surface: { name, flags, numFrames, shaders, triangles, texCoords, vertices },\n nextOffset: offset + ofsEnd,\n };\n}\n\nexport function parseMd3(buffer: ArrayBufferLike): Md3Model {\n if (buffer.byteLength < 108) {\n throw new Md3ParseError('MD3 buffer too small for header');\n }\n\n const view = new DataView(buffer);\n const header = parseHeader(view);\n validateOffset('MD3 end', header.ofsEnd, 0, buffer.byteLength);\n\n const frames = parseFrames(view, header);\n const tags = parseTags(view, header);\n\n const surfaces: Md3Surface[] = [];\n let surfaceOffset = header.ofsSurfaces;\n for (let i = 0; i < header.numSurfaces; i += 1) {\n const { surface, nextOffset } = parseSurface(view, surfaceOffset);\n surfaces.push(surface);\n surfaceOffset = nextOffset;\n }\n\n if (surfaceOffset !== header.ofsEnd) {\n throw new Md3ParseError('Surface parsing did not reach ofsEnd');\n }\n\n return { header, frames, tags, surfaces };\n}\n\nexport class Md3Loader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<Md3Model> {\n const data = await this.vfs.readFile(path);\n return parseMd3(data.slice().buffer);\n }\n}\n","import { VirtualFileSystem } from './vfs.js';\n\nconst IDSPRITEHEADER = 0x49445332; // 'IDS2'\nconst SPRITE_VERSION = 2;\nconst MAX_SKINNAME = 64;\nconst HEADER_SIZE = 12;\n\nexport interface SpriteFrame {\n readonly width: number;\n readonly height: number;\n readonly originX: number;\n readonly originY: number;\n readonly name: string;\n}\n\nexport interface SpriteModel {\n readonly ident: number;\n readonly version: number;\n readonly numFrames: number;\n readonly frames: readonly SpriteFrame[];\n}\n\nexport class SpriteParseError extends Error {}\n\nfunction readCString(view: DataView, offset: number, maxLength: number): string {\n const chars: number[] = [];\n for (let i = 0; i < maxLength; i += 1) {\n const code = view.getUint8(offset + i);\n if (code === 0) break;\n chars.push(code);\n }\n return String.fromCharCode(...chars);\n}\n\nexport function parseSprite(buffer: ArrayBuffer): SpriteModel {\n if (buffer.byteLength < HEADER_SIZE) {\n throw new SpriteParseError('Sprite buffer too small to contain header');\n }\n\n const view = new DataView(buffer);\n const ident = view.getInt32(0, true);\n const version = view.getInt32(4, true);\n const numFrames = view.getInt32(8, true);\n\n if (ident !== IDSPRITEHEADER) {\n throw new SpriteParseError(`Invalid Sprite ident: ${ident}`);\n }\n if (version !== SPRITE_VERSION) {\n throw new SpriteParseError(`Unsupported Sprite version: ${version}`);\n }\n\n const frames: SpriteFrame[] = [];\n const frameSize = 16 + MAX_SKINNAME; // 4 * 4 bytes + 64 bytes = 80 bytes\n let offset = HEADER_SIZE;\n\n for (let i = 0; i < numFrames; i += 1) {\n if (offset + frameSize > buffer.byteLength) {\n throw new SpriteParseError('Sprite frame data exceeds buffer length');\n }\n\n const width = view.getInt32(offset, true);\n const height = view.getInt32(offset + 4, true);\n const originX = view.getInt32(offset + 8, true);\n const originY = view.getInt32(offset + 12, true);\n const name = readCString(view, offset + 16, MAX_SKINNAME);\n\n frames.push({\n width,\n height,\n originX,\n originY,\n name,\n });\n\n offset += frameSize;\n }\n\n return {\n ident,\n version,\n numFrames,\n frames,\n };\n}\n\nexport class SpriteLoader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<SpriteModel> {\n const bytes = await this.vfs.readFile(path);\n // Copy the buffer to ensure it's an ArrayBuffer and not a view\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return parseSprite(copy.buffer);\n }\n}\n","export interface FrameBlend {\n readonly frame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface AnimationSequence {\n readonly name: string;\n readonly start: number;\n readonly end: number;\n readonly fps: number;\n readonly loop?: boolean;\n}\n\nexport interface AnimationState {\n readonly sequence: AnimationSequence;\n readonly time: number;\n}\n\nexport function advanceAnimation(state: AnimationState, deltaSeconds: number): AnimationState {\n const duration = (state.sequence.end - state.sequence.start + 1) / state.sequence.fps;\n const loop = state.sequence.loop !== false;\n let time = state.time + deltaSeconds;\n\n if (loop) {\n time = ((time % duration) + duration) % duration;\n } else if (time > duration) {\n time = duration;\n }\n\n return { ...state, time: Math.max(0, Math.min(time, duration)) };\n}\n\nexport function computeFrameBlend(state: AnimationState): FrameBlend {\n const totalFrames = state.sequence.end - state.sequence.start + 1;\n const frameDuration = 1 / state.sequence.fps;\n const loop = state.sequence.loop !== false;\n const framePosition = state.time / frameDuration;\n\n if (!loop && framePosition >= totalFrames) {\n return { frame: state.sequence.end, nextFrame: state.sequence.end, lerp: 0 };\n }\n\n const normalizedPosition = loop ? framePosition % totalFrames : Math.min(framePosition, totalFrames - 1);\n const baseFrame = Math.floor(normalizedPosition);\n const frame = state.sequence.start + baseFrame;\n const nextFrame = baseFrame + 1 >= totalFrames ? (loop ? state.sequence.start : state.sequence.end) : frame + 1;\n const lerp = !loop && baseFrame >= totalFrames - 1 ? 0 : normalizedPosition - baseFrame;\n return { frame, nextFrame, lerp };\n}\n\nexport function createAnimationState(sequence: AnimationSequence): AnimationState {\n return { sequence, time: 0 };\n}\n\nexport function interpolateVec3(\n a: { x: number; y: number; z: number },\n b: { x: number; y: number; z: number },\n t: number,\n): { x: number; y: number; z: number } {\n return {\n x: a.x + (b.x - a.x) * t,\n y: a.y + (b.y - a.y) * t,\n z: a.z + (b.z - a.z) * t,\n };\n}\n","export interface WalTexture {\n readonly name: string;\n readonly width: number;\n readonly height: number;\n readonly mipmaps: readonly WalMipmap[];\n readonly animName: string;\n readonly flags: number;\n readonly contents: number;\n readonly value: number;\n}\n\nexport interface WalMipmap {\n readonly level: number;\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\nexport class WalParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WalParseError';\n }\n}\n\nexport function parseWal(buffer: ArrayBuffer): WalTexture {\n if (buffer.byteLength < 100) {\n throw new WalParseError('WAL buffer too small');\n }\n\n const view = new DataView(buffer);\n const nameBytes = new Uint8Array(buffer, 0, 32);\n const name = new TextDecoder('utf-8').decode(nameBytes).replace(/\\0.*$/, '').trim();\n const width = view.getInt32(32, true);\n const height = view.getInt32(36, true);\n const offsets = [view.getInt32(40, true), view.getInt32(44, true), view.getInt32(48, true), view.getInt32(52, true)];\n const animNameBytes = new Uint8Array(buffer, 56, 32);\n const animName = new TextDecoder('utf-8').decode(animNameBytes).replace(/\\0.*$/, '').trim();\n const flags = view.getInt32(88, true);\n const contents = view.getInt32(92, true);\n const value = view.getInt32(96, true);\n\n if (width <= 0 || height <= 0) {\n throw new WalParseError('Invalid WAL dimensions');\n }\n\n const mipmaps: WalMipmap[] = [];\n let currentWidth = width;\n let currentHeight = height;\n\n for (let level = 0; level < offsets.length; level += 1) {\n const offset = offsets[level];\n const expectedSize = Math.max(1, (currentWidth * currentHeight) | 0);\n if (offset <= 0 || offset + expectedSize > buffer.byteLength) {\n throw new WalParseError(`Invalid WAL mip offset for level ${level}`);\n }\n const data = new Uint8Array(buffer, offset, expectedSize);\n mipmaps.push({ level, width: currentWidth, height: currentHeight, data });\n currentWidth = Math.max(1, currentWidth >> 1);\n currentHeight = Math.max(1, currentHeight >> 1);\n }\n\n return { name, width, height, mipmaps, animName, flags, contents, value };\n}\n","export interface PcxImage {\n readonly width: number;\n readonly height: number;\n readonly bitsPerPixel: number;\n readonly pixels: Uint8Array;\n readonly palette: Uint8Array;\n}\n\nexport class PcxParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'PcxParseError';\n }\n}\n\nexport function parsePcx(buffer: ArrayBuffer): PcxImage {\n if (buffer.byteLength < 128) {\n throw new PcxParseError('PCX buffer too small for header');\n }\n\n const view = new DataView(buffer);\n const manufacturer = view.getUint8(0);\n const encoding = view.getUint8(2);\n const bitsPerPixel = view.getUint8(3);\n const xMin = view.getUint16(4, true);\n const yMin = view.getUint16(6, true);\n const xMax = view.getUint16(8, true);\n const yMax = view.getUint16(10, true);\n\n if (manufacturer !== 0x0a || encoding !== 1) {\n throw new PcxParseError('Unsupported PCX encoding');\n }\n if (bitsPerPixel !== 8) {\n throw new PcxParseError('Only 8bpp PCX files are supported');\n }\n\n const width = xMax - xMin + 1;\n const height = yMax - yMin + 1;\n const bytesPerLine = view.getUint16(66, true);\n\n const paletteMarkerOffset = buffer.byteLength - 769;\n if (paletteMarkerOffset < 128 || new DataView(buffer, paletteMarkerOffset, 1).getUint8(0) !== 0x0c) {\n throw new PcxParseError('Missing PCX palette');\n }\n\n const palette = new Uint8Array(buffer, paletteMarkerOffset + 1, 768);\n const encoded = new Uint8Array(buffer, 128, paletteMarkerOffset - 128);\n const pixels = new Uint8Array(width * height);\n\n let srcIndex = 0;\n let dstIndex = 0;\n\n for (let y = 0; y < height; y += 1) {\n let written = 0;\n while (written < bytesPerLine && srcIndex < encoded.length) {\n let count = 1;\n let value = encoded[srcIndex++]!;\n\n if ((value & 0xc0) === 0xc0) {\n count = value & 0x3f;\n if (srcIndex >= encoded.length) {\n throw new PcxParseError('Unexpected end of PCX RLE data');\n }\n value = encoded[srcIndex++]!;\n }\n\n for (let i = 0; i < count && written < bytesPerLine; i += 1) {\n if (written < width) {\n pixels[dstIndex++] = value;\n }\n written += 1;\n }\n }\n }\n\n return { width, height, bitsPerPixel, pixels, palette };\n}\n\nexport function pcxToRgba(image: PcxImage): Uint8Array {\n const rgba = new Uint8Array(image.width * image.height * 4);\n for (let i = 0; i < image.pixels.length; i += 1) {\n const colorIndex = image.pixels[i]!;\n const paletteIndex = colorIndex * 3;\n const rgbaIndex = i * 4;\n rgba[rgbaIndex] = image.palette[paletteIndex]!;\n rgba[rgbaIndex + 1] = image.palette[paletteIndex + 1]!;\n rgba[rgbaIndex + 2] = image.palette[paletteIndex + 2]!;\n rgba[rgbaIndex + 3] = colorIndex === 255 ? 0 : 255;\n }\n return rgba;\n}\n","import { LruCache } from './cache.js';\nimport { pcxToRgba, type PcxImage } from './pcx.js';\nimport { parseWal, type WalTexture } from './wal.js';\n\nexport interface PreparedTexture {\n readonly width: number;\n readonly height: number;\n readonly levels: readonly TextureLevel[];\n readonly source: 'pcx' | 'wal';\n}\n\nexport interface TextureLevel {\n readonly level: number;\n readonly width: number;\n readonly height: number;\n readonly rgba: Uint8Array;\n}\n\nexport interface TextureCacheOptions {\n readonly capacity?: number;\n}\n\nexport class TextureCache {\n private readonly cache: LruCache<PreparedTexture>;\n\n constructor(options: TextureCacheOptions = {}) {\n this.cache = new LruCache<PreparedTexture>(options.capacity ?? 128);\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n get(key: string): PreparedTexture | undefined {\n return this.cache.get(key.toLowerCase());\n }\n\n set(key: string, texture: PreparedTexture): void {\n this.cache.set(key.toLowerCase(), texture);\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\nexport function walToRgba(wal: WalTexture, palette: Uint8Array): PreparedTexture {\n const levels: TextureLevel[] = [];\n for (const mip of wal.mipmaps) {\n const rgba = new Uint8Array(mip.width * mip.height * 4);\n for (let i = 0; i < mip.data.length; i += 1) {\n const colorIndex = mip.data[i]!;\n const paletteIndex = colorIndex * 3;\n const outIndex = i * 4;\n rgba[outIndex] = palette[paletteIndex]!;\n rgba[outIndex + 1] = palette[paletteIndex + 1]!;\n rgba[outIndex + 2] = palette[paletteIndex + 2]!;\n rgba[outIndex + 3] = colorIndex === 255 ? 0 : 255;\n }\n levels.push({ level: mip.level, width: mip.width, height: mip.height, rgba });\n }\n\n return { width: wal.width, height: wal.height, levels, source: 'wal' };\n}\n\nexport function preparePcxTexture(pcx: PcxImage): PreparedTexture {\n const rgba = pcxToRgba(pcx);\n const level: TextureLevel = { level: 0, width: pcx.width, height: pcx.height, rgba };\n return { width: pcx.width, height: pcx.height, levels: [level], source: 'pcx' };\n}\n\nexport function parseWalTexture(buffer: ArrayBuffer, palette: Uint8Array): PreparedTexture {\n return walToRgba(parseWal(buffer), palette);\n}\n","export interface WavData {\n readonly sampleRate: number;\n readonly channels: number;\n readonly bitsPerSample: number;\n readonly samples: Float32Array;\n}\n\nexport class WavParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WavParseError';\n }\n}\n\nfunction readString(view: DataView, offset: number, length: number): string {\n return new TextDecoder('ascii').decode(new Uint8Array(view.buffer, view.byteOffset + offset, length));\n}\n\nexport function parseWav(buffer: ArrayBuffer): WavData {\n if (buffer.byteLength < 44) {\n throw new WavParseError('WAV buffer too small');\n }\n\n const view = new DataView(buffer);\n if (readString(view, 0, 4) !== 'RIFF' || readString(view, 8, 4) !== 'WAVE') {\n throw new WavParseError('Invalid WAV header');\n }\n\n let offset = 12;\n let fmtOffset = -1;\n let dataOffset = -1;\n let fmtSize = 0;\n let dataSize = 0;\n\n while (offset + 8 <= buffer.byteLength) {\n const chunkId = readString(view, offset, 4);\n const chunkSize = view.getUint32(offset + 4, true);\n const chunkDataOffset = offset + 8;\n\n if (chunkId === 'fmt ') {\n fmtOffset = chunkDataOffset;\n fmtSize = chunkSize;\n } else if (chunkId === 'data') {\n dataOffset = chunkDataOffset;\n dataSize = chunkSize;\n }\n\n offset = chunkDataOffset + chunkSize;\n }\n\n if (fmtOffset === -1 || dataOffset === -1) {\n throw new WavParseError('Missing fmt or data chunk');\n }\n\n const audioFormat = view.getUint16(fmtOffset, true);\n const channels = view.getUint16(fmtOffset + 2, true);\n const sampleRate = view.getUint32(fmtOffset + 4, true);\n const bitsPerSample = view.getUint16(fmtOffset + 14, true);\n\n if (audioFormat !== 1) {\n throw new WavParseError('Only PCM WAV is supported');\n }\n\n const bytesPerSample = bitsPerSample / 8;\n const frameCount = dataSize / (bytesPerSample * channels);\n const samples = new Float32Array(frameCount * channels);\n\n for (let frame = 0; frame < frameCount; frame += 1) {\n for (let ch = 0; ch < channels; ch += 1) {\n const sampleIndex = frame * channels + ch;\n const byteOffset = dataOffset + sampleIndex * bytesPerSample;\n let value = 0;\n if (bitsPerSample === 8) {\n value = view.getUint8(byteOffset);\n samples[sampleIndex] = (value - 128) / 128;\n } else if (bitsPerSample === 16) {\n value = view.getInt16(byteOffset, true);\n samples[sampleIndex] = value / 32768;\n } else if (bitsPerSample === 24) {\n const b0 = view.getUint8(byteOffset);\n const b1 = view.getUint8(byteOffset + 1);\n const b2 = view.getInt8(byteOffset + 2);\n value = b0 | (b1 << 8) | (b2 << 16);\n samples[sampleIndex] = value / 8388608;\n } else {\n throw new WavParseError(`Unsupported bitsPerSample: ${bitsPerSample}`);\n }\n }\n }\n\n return { sampleRate, channels, bitsPerSample, samples };\n}\n","import { OggVorbisDecoder } from '@wasm-audio-decoders/ogg-vorbis';\n\nexport interface OggAudio {\n readonly sampleRate: number;\n readonly channels: number;\n readonly bitDepth: number;\n readonly channelData: readonly Float32Array[];\n}\n\nexport class OggDecodeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OggDecodeError';\n }\n}\n\nexport async function decodeOgg(buffer: ArrayBuffer, decoder: OggVorbisDecoder = new OggVorbisDecoder()): Promise<OggAudio> {\n await decoder.ready;\n const result = await decoder.decode(new Uint8Array(buffer));\n\n const errors = (result as { errors?: { message: string }[] }).errors;\n if (errors && errors.length > 0) {\n throw new OggDecodeError(errors.map((err) => err.message).join('; '));\n }\n\n return {\n sampleRate: result.sampleRate,\n channels: result.channelData.length,\n bitDepth: result.bitDepth,\n channelData: result.channelData,\n };\n}\n","import { decodeOgg, type OggAudio } from './ogg.js';\nimport { parseWav } from './wav.js';\nimport { VirtualFileSystem } from './vfs.js';\nimport { LruCache } from './cache.js';\n\nexport type DecodedAudio = OggAudio;\n\nexport class AudioRegistryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AudioRegistryError';\n }\n}\n\nexport interface AudioRegistryOptions {\n readonly cacheSize?: number;\n}\n\nexport class AudioRegistry {\n private readonly cache: LruCache<DecodedAudio>;\n private readonly refCounts = new Map<string, number>();\n\n constructor(private readonly vfs: VirtualFileSystem, options: AudioRegistryOptions = {}) {\n this.cache = new LruCache<DecodedAudio>(options.cacheSize ?? 64);\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n async load(path: string): Promise<DecodedAudio> {\n const normalized = path.toLowerCase();\n const cached = this.cache.get(normalized);\n if (cached) {\n this.refCounts.set(normalized, (this.refCounts.get(normalized) ?? 0) + 1);\n return cached;\n }\n\n const data = await this.vfs.readFile(path);\n const arrayBuffer = data.slice().buffer;\n const audio = await this.decodeByExtension(path, arrayBuffer);\n this.cache.set(normalized, audio);\n this.refCounts.set(normalized, 1);\n return audio;\n }\n\n release(path: string): void {\n const normalized = path.toLowerCase();\n const count = this.refCounts.get(normalized) ?? 0;\n if (count <= 1) {\n this.cache.delete(normalized);\n this.refCounts.delete(normalized);\n } else {\n this.refCounts.set(normalized, count - 1);\n }\n }\n\n clearAll(): void {\n this.cache.clear();\n this.refCounts.clear();\n }\n\n private async decodeByExtension(path: string, buffer: ArrayBuffer): Promise<DecodedAudio> {\n const lower = path.toLowerCase();\n if (lower.endsWith('.wav')) {\n const wav = parseWav(buffer);\n const channels = wav.channels;\n const channelData: Float32Array[] = Array.from({ length: channels }, () => new Float32Array(wav.samples.length / channels));\n for (let i = 0; i < wav.samples.length; i += 1) {\n channelData[i % channels]![Math.floor(i / channels)] = wav.samples[i]!;\n }\n return { sampleRate: wav.sampleRate, channels, bitDepth: wav.bitsPerSample, channelData } satisfies OggAudio;\n }\n if (lower.endsWith('.ogg') || lower.endsWith('.oga')) {\n return decodeOgg(buffer);\n }\n throw new AudioRegistryError(`Unsupported audio format: ${path}`);\n }\n}\n","import { PakArchive, type PakDirectoryEntry, type PakValidationResult, normalizePath } from './pak.js';\n\nconst DEFAULT_DB_NAME = 'quake2ts-pak-indexes';\nconst DEFAULT_STORE_NAME = 'pak-indexes';\n\nexport interface StoredPakIndex extends PakValidationResult {\n readonly key: string;\n readonly name: string;\n readonly size: number;\n readonly persistedAt: number;\n}\n\nfunction getIndexedDb(): IDBFactory | undefined {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof window !== 'undefined' && 'indexedDB' in window) {\n return window.indexedDB;\n }\n if (typeof globalThis !== 'undefined' && 'indexedDB' in globalThis) {\n return (globalThis as unknown as { indexedDB?: IDBFactory }).indexedDB;\n }\n return undefined;\n}\n\nfunction openDatabase(dbName: string, storeName: string): Promise<IDBDatabase> {\n const idb = getIndexedDb();\n if (!idb) {\n return Promise.reject(new Error('IndexedDB is not available in this environment'));\n }\n\n return new Promise<IDBDatabase>((resolve, reject) => {\n const request = idb.open(dbName, 1);\n\n request.onupgradeneeded = () => {\n const { result } = request;\n if (!result.objectStoreNames.contains(storeName)) {\n result.createObjectStore(storeName, { keyPath: 'key' });\n }\n };\n\n request.onerror = () => reject(request.error ?? new Error('Unknown IndexedDB error'));\n request.onsuccess = () => resolve(request.result);\n });\n}\n\nfunction runTransaction<T>(\n db: IDBDatabase,\n storeName: string,\n mode: IDBTransactionMode,\n runner: (store: IDBObjectStore) => IDBRequest<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const transaction = db.transaction(storeName, mode);\n const store = transaction.objectStore(storeName);\n const request = runner(store);\n\n request.onsuccess = () => resolve(request.result as T);\n request.onerror = () => reject(request.error ?? new Error('IndexedDB transaction error'));\n });\n}\n\nfunction buildKey(name: string, checksum: number): string {\n return `${normalizePath(name)}:${checksum.toString(16)}`;\n}\n\nfunction cloneEntries(entries: readonly PakDirectoryEntry[]): PakDirectoryEntry[] {\n return entries.map((entry) => ({ ...entry }));\n}\n\nexport class PakIndexStore {\n constructor(\n private readonly dbName = DEFAULT_DB_NAME,\n private readonly storeName = DEFAULT_STORE_NAME,\n ) {}\n\n get isSupported(): boolean {\n return Boolean(getIndexedDb());\n }\n\n async persist(archive: PakArchive): Promise<StoredPakIndex | undefined> {\n if (!this.isSupported) {\n return undefined;\n }\n\n const validation = archive.validate();\n const record: StoredPakIndex = {\n ...validation,\n key: buildKey(archive.name, validation.checksum),\n name: archive.name,\n size: archive.size,\n persistedAt: Date.now(),\n entries: cloneEntries(validation.entries),\n };\n\n const db = await openDatabase(this.dbName, this.storeName);\n await runTransaction(db, this.storeName, 'readwrite', (store) => store.put(record));\n db.close();\n return record;\n }\n\n async find(name: string, checksum?: number): Promise<StoredPakIndex | undefined> {\n if (!this.isSupported) {\n return undefined;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const key = checksum !== undefined ? buildKey(name, checksum) : undefined;\n\n const record = await runTransaction(db, this.storeName, 'readonly', (store) => {\n if (key) {\n return store.get(key);\n }\n return store.getAll();\n });\n\n db.close();\n\n if (!record) {\n return undefined;\n }\n\n if (Array.isArray(record)) {\n const normalized = normalizePath(name);\n const matches = record.filter((candidate: StoredPakIndex) => normalizePath(candidate.name) === normalized);\n if (matches.length === 0) {\n return undefined;\n }\n return matches.sort((a, b) => b.persistedAt - a.persistedAt)[0];\n }\n\n return record as StoredPakIndex;\n }\n\n async remove(name: string, checksum?: number): Promise<boolean> {\n if (!this.isSupported) {\n return false;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const key = checksum !== undefined ? buildKey(name, checksum) : undefined;\n const result = await runTransaction(db, this.storeName, 'readwrite', (store) => {\n if (key) {\n return store.delete(key);\n }\n const prefix = `${normalizePath(name)}:`;\n return store.delete(IDBKeyRange.bound(prefix, `${prefix}￿`, false, true));\n });\n db.close();\n return typeof result === 'number' ? result > 0 : true;\n }\n\n async clear(): Promise<void> {\n if (!this.isSupported) {\n return;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n await runTransaction(db, this.storeName, 'readwrite', (store) => store.clear());\n db.close();\n }\n\n async list(): Promise<StoredPakIndex[]> {\n if (!this.isSupported) {\n return [];\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const result = await runTransaction(db, this.storeName, 'readonly', (store) => store.getAll());\n db.close();\n return (result as StoredPakIndex[]).sort((a, b) => b.persistedAt - a.persistedAt);\n }\n}\n","import { normalizePath } from './pak.js';\nimport { TextureCache, type PreparedTexture } from './texture.js';\nimport { AudioRegistry, type DecodedAudio } from './audio.js';\nimport { Md2Loader, type Md2Model } from './md2.js';\nimport { Md3Loader, type Md3Model } from './md3.js';\nimport { SpriteLoader, type SpriteModel } from './sprite.js';\nimport { VirtualFileSystem } from './vfs.js';\n\ntype AssetType = 'texture' | 'model' | 'sound' | 'sprite';\n\ninterface DependencyNode {\n readonly dependencies: Set<string>;\n loaded: boolean;\n}\n\nexport class AssetDependencyError extends Error {\n constructor(readonly missing: readonly string[], message?: string) {\n super(message ?? `Missing dependencies: ${missing.join(', ')}`);\n this.name = 'AssetDependencyError';\n }\n}\n\nexport class AssetDependencyTracker {\n private readonly nodes = new Map<string, DependencyNode>();\n\n register(assetKey: string, dependencies: readonly string[] = []): void {\n const node = this.nodes.get(assetKey) ?? { dependencies: new Set<string>(), loaded: false };\n dependencies.forEach((dependency) => node.dependencies.add(dependency));\n this.nodes.set(assetKey, node);\n dependencies.forEach((dependency) => {\n if (!this.nodes.has(dependency)) {\n this.nodes.set(dependency, { dependencies: new Set<string>(), loaded: false });\n }\n });\n }\n\n markLoaded(assetKey: string): void {\n const node = this.nodes.get(assetKey) ?? { dependencies: new Set<string>(), loaded: false };\n const missing = this.getMissingDependencies(assetKey, node);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${assetKey} is missing dependencies: ${missing.join(', ')}`);\n }\n node.loaded = true;\n this.nodes.set(assetKey, node);\n }\n\n markUnloaded(assetKey: string): void {\n const node = this.nodes.get(assetKey);\n if (node) {\n node.loaded = false;\n }\n }\n\n isLoaded(assetKey: string): boolean {\n return this.nodes.get(assetKey)?.loaded ?? false;\n }\n\n missingDependencies(assetKey: string): string[] {\n const node = this.nodes.get(assetKey);\n if (!node) {\n return [];\n }\n return this.getMissingDependencies(assetKey, node);\n }\n\n reset(): void {\n this.nodes.clear();\n }\n\n private getMissingDependencies(assetKey: string, node: DependencyNode): string[] {\n const missing: string[] = [];\n for (const dependency of node.dependencies) {\n if (!this.nodes.get(dependency)?.loaded) {\n missing.push(dependency);\n }\n }\n return missing;\n }\n}\n\nexport interface AssetManagerOptions {\n readonly textureCacheCapacity?: number;\n readonly audioCacheSize?: number;\n readonly dependencyTracker?: AssetDependencyTracker;\n}\n\nexport class AssetManager {\n readonly textures: TextureCache;\n readonly audio: AudioRegistry;\n readonly dependencyTracker: AssetDependencyTracker;\n private readonly md2: Md2Loader;\n private readonly md3: Md3Loader;\n private readonly sprite: SpriteLoader;\n\n constructor(private readonly vfs: VirtualFileSystem, options: AssetManagerOptions = {}) {\n this.textures = new TextureCache({ capacity: options.textureCacheCapacity ?? 128 });\n this.audio = new AudioRegistry(vfs, { cacheSize: options.audioCacheSize ?? 64 });\n this.dependencyTracker = options.dependencyTracker ?? new AssetDependencyTracker();\n this.md2 = new Md2Loader(vfs);\n this.md3 = new Md3Loader(vfs);\n this.sprite = new SpriteLoader(vfs);\n }\n\n isAssetLoaded(type: AssetType, path: string): boolean {\n return this.dependencyTracker.isLoaded(this.makeKey(type, path));\n }\n\n registerTexture(path: string, texture: PreparedTexture): void {\n this.textures.set(path, texture);\n const key = this.makeKey('texture', path);\n this.dependencyTracker.register(key);\n this.dependencyTracker.markLoaded(key);\n }\n\n async loadSound(path: string): Promise<DecodedAudio> {\n const audio = await this.audio.load(path);\n const key = this.makeKey('sound', path);\n this.dependencyTracker.register(key);\n this.dependencyTracker.markLoaded(key);\n return audio;\n }\n\n async loadMd2Model(path: string, textureDependencies: readonly string[] = []): Promise<Md2Model> {\n const modelKey = this.makeKey('model', path);\n const dependencyKeys = textureDependencies.map((dep) => this.makeKey('texture', dep));\n this.dependencyTracker.register(modelKey, dependencyKeys);\n const missing = this.dependencyTracker.missingDependencies(modelKey);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${modelKey} is missing dependencies: ${missing.join(', ')}`);\n }\n const model = await this.md2.load(path);\n this.dependencyTracker.markLoaded(modelKey);\n return model;\n }\n\n async loadMd3Model(path: string, textureDependencies: readonly string[] = []): Promise<Md3Model> {\n const modelKey = this.makeKey('model', path);\n const dependencyKeys = textureDependencies.map((dep) => this.makeKey('texture', dep));\n this.dependencyTracker.register(modelKey, dependencyKeys);\n const missing = this.dependencyTracker.missingDependencies(modelKey);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${modelKey} is missing dependencies: ${missing.join(', ')}`);\n }\n const model = await this.md3.load(path);\n this.dependencyTracker.markLoaded(modelKey);\n return model;\n }\n\n async loadSprite(path: string): Promise<SpriteModel> {\n const spriteKey = this.makeKey('sprite', path);\n this.dependencyTracker.register(spriteKey);\n const sprite = await this.sprite.load(path);\n this.dependencyTracker.markLoaded(spriteKey);\n return sprite;\n }\n\n resetForLevelChange(): void {\n this.textures.clear();\n this.audio.clearAll();\n this.dependencyTracker.reset();\n }\n\n private makeKey(type: AssetType, path: string): string {\n return `${type}:${normalizePath(path)}`;\n }\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 === ATTN_STATIC ? attenuation * 0.001 : attenuation * 0.0005;\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","export interface AudioParamLike {\n value: number;\n}\n\nexport interface AudioNodeLike {\n connect(destination: AudioNodeLike): void;\n}\n\nexport interface BiquadFilterNodeLike extends AudioNodeLike {\n frequency: AudioParamLike;\n Q: AudioParamLike;\n type: string;\n}\n\nexport interface GainNodeLike extends AudioNodeLike {\n gain: AudioParamLike;\n}\n\nexport interface DynamicsCompressorNodeLike extends AudioNodeLike {}\n\nexport interface AudioBufferLike {\n readonly duration: number;\n}\n\nexport interface AudioBufferSourceNodeLike extends AudioNodeLike {\n buffer: AudioBufferLike | null;\n loop: boolean;\n onended: (() => void) | null;\n start(when?: number, offset?: number, duration?: number): void;\n stop(when?: number): void;\n}\n\nexport interface PannerNodeLike extends AudioNodeLike {\n positionX: AudioParamLike;\n positionY: AudioParamLike;\n positionZ: AudioParamLike;\n refDistance?: number;\n maxDistance?: number;\n rolloffFactor?: number;\n distanceModel?: string;\n}\n\nexport interface AudioDestinationNodeLike extends AudioNodeLike {}\n\nexport interface AudioContextLike {\n readonly destination: AudioDestinationNodeLike;\n readonly currentTime: number;\n state: 'suspended' | 'running' | 'closed';\n resume(): Promise<void>;\n suspend(): Promise<void>;\n createGain(): GainNodeLike;\n createDynamicsCompressor(): DynamicsCompressorNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n createPanner?(): PannerNodeLike;\n createBiquadFilter?(): BiquadFilterNodeLike;\n decodeAudioData?(data: ArrayBuffer): Promise<AudioBufferLike>;\n}\n\nexport type AudioContextFactory = () => AudioContextLike;\n\nexport interface AudioGraph {\n context: AudioContextLike;\n master: GainNodeLike;\n compressor: DynamicsCompressorNodeLike;\n filter?: BiquadFilterNodeLike;\n}\n\nexport class AudioContextController {\n private context?: AudioContextLike;\n\n constructor(private readonly factory: AudioContextFactory) {}\n\n getContext(): AudioContextLike {\n if (!this.context) {\n this.context = this.factory();\n }\n return this.context;\n }\n\n async resume(): Promise<void> {\n const ctx = this.getContext();\n if (ctx.state === 'suspended') {\n await ctx.resume();\n }\n }\n\n getState(): AudioContextLike['state'] {\n return this.context?.state ?? 'suspended';\n }\n}\n\nexport function createAudioGraph(controller: AudioContextController): AudioGraph {\n const context = controller.getContext();\n const master = context.createGain();\n master.gain.value = 1;\n const compressor = context.createDynamicsCompressor();\n const filter = context.createBiquadFilter?.();\n if (filter) {\n filter.type = 'lowpass';\n filter.frequency.value = 20000;\n filter.Q.value = 0.707;\n master.connect(filter);\n filter.connect(compressor);\n } else {\n master.connect(compressor);\n }\n compressor.connect(context.destination);\n return { context, master, compressor, filter };\n}\n","import { ConfigStringRegistry } from '../configstrings.js';\nimport type { AudioBufferLike } from './context.js';\n\nexport class SoundRegistry {\n private readonly buffers = new Map<number, AudioBufferLike>();\n\n constructor(private readonly configStrings = new ConfigStringRegistry()) {}\n\n registerName(name: string): number {\n return this.configStrings.soundIndex(name);\n }\n\n register(name: string, buffer: AudioBufferLike): number {\n const index = this.registerName(name);\n this.buffers.set(index, buffer);\n return index;\n }\n\n find(name: string): number | undefined {\n return this.configStrings.findSoundIndex(name);\n }\n\n get(index: number): AudioBufferLike | undefined {\n return this.buffers.get(index);\n }\n\n has(index: number): boolean {\n return this.buffers.has(index);\n }\n}\n","import { normalizePath } from '../assets/pak.js';\nimport type { VirtualFileSystem } from '../assets/vfs.js';\nimport type { AudioBufferLike, AudioContextLike } from './context.js';\nimport { AudioContextController } from './context.js';\nimport { SoundRegistry } from './registry.js';\n\nexport interface SoundPrecacheOptions {\n vfs: Pick<VirtualFileSystem, 'readFile' | 'stat'>;\n registry: SoundRegistry;\n context: AudioContextController;\n decodeAudio?: (context: AudioContextLike, data: ArrayBuffer) => Promise<AudioBufferLike>;\n soundRoot?: string;\n}\n\nexport interface SoundPrecacheReport {\n loaded: string[];\n skipped: string[];\n missing: string[];\n errors: Record<string, Error>;\n}\n\nexport class SoundPrecache {\n private readonly vfs: SoundPrecacheOptions['vfs'];\n private readonly registry: SoundRegistry;\n private readonly contextController: AudioContextController;\n private readonly decodeAudio: NonNullable<SoundPrecacheOptions['decodeAudio']>;\n private readonly soundRoot: string;\n\n constructor(options: SoundPrecacheOptions) {\n this.vfs = options.vfs;\n this.registry = options.registry;\n this.contextController = options.context;\n this.soundRoot = options.soundRoot ?? 'sound/';\n this.decodeAudio =\n options.decodeAudio ??\n ((context: AudioContextLike, data: ArrayBuffer) => {\n if (!context.decodeAudioData) {\n throw new Error('decodeAudioData is not available on the provided audio context');\n }\n return context.decodeAudioData(data);\n });\n }\n\n async precache(paths: string[]): Promise<SoundPrecacheReport> {\n const unique = [...new Set(paths.map((p) => this.normalize(p)))];\n const report: SoundPrecacheReport = { loaded: [], skipped: [], missing: [], errors: {} };\n const context = this.contextController.getContext();\n\n for (const path of unique) {\n try {\n const existingIndex = this.registry.find(path);\n if (existingIndex !== undefined && this.registry.has(existingIndex)) {\n report.skipped.push(path);\n continue;\n }\n\n const stat = this.vfs.stat(path);\n if (!stat) {\n report.missing.push(path);\n continue;\n }\n\n const bytes = await this.vfs.readFile(path);\n const copy = bytes.slice().buffer;\n const buffer = await this.decodeAudio(context, copy);\n this.registry.register(path, buffer);\n report.loaded.push(path);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n report.errors[path] = err;\n }\n }\n\n return report;\n }\n\n private normalize(path: string): string {\n const normalized = normalizePath(path.replace(/^\\//, ''));\n if (normalized.startsWith(this.soundRoot)) {\n return normalized;\n }\n return normalizePath(`${this.soundRoot}${normalized}`);\n }\n}\n","import { MAX_SOUND_CHANNELS, SoundChannel } from './constants.js';\n\nconst CHANNEL_MASK = 0x07;\n\nexport const baseChannel = (entchannel: number): number => entchannel & CHANNEL_MASK;\n\nexport interface ChannelState {\n entnum: number;\n entchannel: number;\n endTimeMs: number;\n isPlayer: boolean;\n active: boolean;\n}\n\nexport interface ChannelPickContext {\n readonly nowMs: number;\n readonly playerEntity?: number;\n}\n\nexport function createInitialChannels(playerEntity?: number): ChannelState[] {\n return Array.from({ length: MAX_SOUND_CHANNELS }, () => ({\n entnum: 0,\n entchannel: SoundChannel.Auto,\n endTimeMs: 0,\n isPlayer: false,\n active: false,\n } satisfies ChannelState)).map((channel) => ({ ...channel, isPlayer: channel.entnum === playerEntity }));\n}\n\nexport function pickChannel(\n channels: ChannelState[],\n entnum: number,\n entchannel: number,\n context: ChannelPickContext,\n): number | undefined {\n if (entchannel < 0) {\n throw new Error('pickChannel: entchannel must be non-negative');\n }\n\n const normalizedEntchannel = baseChannel(entchannel);\n let firstToDie = -1;\n let lifeLeft = Number.POSITIVE_INFINITY;\n\n for (let i = 0; i < channels.length; i += 1) {\n const channel = channels[i];\n const channelBase = baseChannel(channel.entchannel);\n\n if (\n normalizedEntchannel !== SoundChannel.Auto &&\n channel.entnum === entnum &&\n channelBase === normalizedEntchannel\n ) {\n firstToDie = i;\n break;\n }\n\n if (channel.active && channel.entnum === context.playerEntity && entnum !== context.playerEntity) {\n continue;\n }\n\n const remainingLife = channel.endTimeMs - context.nowMs;\n if (firstToDie === -1 || remainingLife < lifeLeft) {\n lifeLeft = remainingLife;\n firstToDie = i;\n }\n }\n\n return firstToDie === -1 ? undefined : firstToDie;\n}\n","import { Vec3, dotVec3, lengthVec3, normalizeVec3, subtractVec3 } from '@quake2ts/shared';\nimport { SOUND_FULLVOLUME, attenuationToDistanceMultiplier } from './constants.js';\n\nexport interface ListenerState {\n origin: Vec3;\n right: Vec3;\n mono?: boolean;\n playerEntity?: number;\n}\n\nexport interface SpatializationResult {\n left: number;\n right: number;\n distanceComponent: number;\n}\n\nexport function spatializeOrigin(\n origin: Vec3,\n listener: ListenerState,\n masterVolume: number,\n attenuation: number,\n isListenerSound: boolean,\n): SpatializationResult {\n if (isListenerSound) {\n return { left: masterVolume, right: masterVolume, distanceComponent: 0 };\n }\n\n const sourceVec = subtractVec3(origin, listener.origin);\n const distance = lengthVec3(sourceVec);\n const normalized = normalizeVec3(sourceVec);\n let dist = distance - SOUND_FULLVOLUME;\n if (dist < 0) dist = 0;\n dist *= attenuationToDistanceMultiplier(attenuation);\n\n const dot = dotVec3(listener.right, normalized);\n const mono = listener.mono ?? false;\n const rscale = mono || attenuation === 0 ? 1 : 0.5 * (1 + dot);\n const lscale = mono || attenuation === 0 ? 1 : 0.5 * (1 - dot);\n\n const right = Math.max(0, Math.floor(masterVolume * (1 - dist) * rscale));\n const left = Math.max(0, Math.floor(masterVolume * (1 - dist) * lscale));\n\n return { left, right, distanceComponent: dist };\n}\n","import { ZERO_VEC3, type Vec3 } from '@quake2ts/shared';\nimport {\n ATTN_NONE,\n SOUND_FULLVOLUME,\n attenuationToDistanceMultiplier,\n calculateMaxAudibleDistance,\n SoundChannel,\n} from './constants.js';\nimport {\n AudioContextController,\n createAudioGraph,\n type AudioContextLike,\n type AudioBufferSourceNodeLike,\n type AudioGraph,\n type BiquadFilterNodeLike,\n type GainNodeLike,\n type PannerNodeLike,\n} from './context.js';\nimport { SoundRegistry } from './registry.js';\nimport { baseChannel, createInitialChannels, pickChannel, type ChannelState } from './channels.js';\nimport { spatializeOrigin, type ListenerState } from './spatialization.js';\n\nexport interface SoundRequest {\n entity: number;\n channel: number;\n soundIndex: number;\n volume: number;\n attenuation: number;\n origin?: Vec3;\n timeOffsetMs?: number;\n looping?: boolean;\n}\n\nexport interface AudioSystemOptions {\n context: AudioContextController;\n registry: SoundRegistry;\n playerEntity?: number;\n listener?: ListenerState;\n sfxVolume?: number;\n masterVolume?: number;\n resolveOcclusion?: OcclusionResolver;\n}\n\ninterface ActiveSound {\n channelIndex: number;\n entnum: number;\n entchannel: number;\n endTimeMs: number;\n source: AudioBufferSourceNodeLike;\n panner: PannerNodeLike;\n gain: GainNodeLike;\n baseGain: number;\n origin: Vec3;\n attenuation: number;\n occlusion?: OcclusionState;\n}\n\ninterface OcclusionState {\n scale: number;\n lowpassHz?: number;\n filter?: BiquadFilterNodeLike;\n}\n\nexport interface OcclusionResult {\n gainScale?: number;\n lowpassHz?: number;\n}\n\nexport type OcclusionResolver = (\n listener: ListenerState,\n source: Vec3,\n attenuation: number,\n) => OcclusionResult | undefined;\n\nexport interface AudioDiagnostics {\n activeChannels: number;\n masterVolume: number;\n sfxVolume: number;\n channels: ChannelState[];\n activeSounds: Array<{\n entnum: number;\n entchannel: number;\n channelIndex: number;\n origin: Vec3;\n gain: number;\n baseGain: number;\n attenuation: number;\n maxDistance?: number;\n distanceModel?: string;\n occlusion?: { scale: number; lowpassHz?: number };\n }>;\n}\n\nexport class AudioSystem {\n private readonly channels: ChannelState[];\n private readonly registry: SoundRegistry;\n private readonly contextController: AudioContextController;\n private readonly graph: AudioGraph;\n private readonly playerEntity?: number;\n private readonly activeSources = new Map<number, ActiveSound>();\n private readonly resolveOcclusion?: OcclusionResolver;\n private listener: ListenerState;\n private sfxVolume: number;\n private masterVolume: number;\n\n constructor(options: AudioSystemOptions) {\n this.contextController = options.context;\n this.registry = options.registry;\n this.playerEntity = options.playerEntity;\n this.channels = createInitialChannels(options.playerEntity);\n this.listener = options.listener ?? { origin: ZERO_VEC3, right: { x: 1, y: 0, z: 0 } };\n this.sfxVolume = options.sfxVolume ?? 1;\n this.masterVolume = options.masterVolume ?? 1;\n this.resolveOcclusion = options.resolveOcclusion;\n this.graph = createAudioGraph(this.contextController);\n this.graph.master.gain.value = this.masterVolume;\n }\n\n setListener(listener: ListenerState): void {\n this.listener = listener;\n }\n\n setMasterVolume(volume: number): void {\n this.masterVolume = volume;\n this.graph.master.gain.value = volume;\n }\n\n setSfxVolume(volume: number): void {\n this.sfxVolume = volume;\n }\n\n async ensureRunning(): Promise<void> {\n await this.contextController.resume();\n }\n\n play(request: SoundRequest): ActiveSound | undefined {\n const buffer = this.registry.get(request.soundIndex);\n if (!buffer) return undefined;\n\n const ctx = this.graph.context;\n const nowMs = ctx.currentTime * 1000;\n const channelIndex = pickChannel(this.channels, request.entity, request.channel, {\n nowMs,\n playerEntity: this.playerEntity,\n });\n\n if (channelIndex === undefined) return undefined;\n\n const existing = this.activeSources.get(channelIndex);\n if (existing) {\n existing.source.onended = null;\n existing.source.stop();\n this.activeSources.delete(channelIndex);\n }\n\n const source = ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = request.looping ?? false;\n\n const origin = request.origin ?? this.listener.origin;\n const gain = ctx.createGain();\n const panner = this.createPanner(ctx, request.attenuation);\n const occlusion = this.resolveOcclusion?.(this.listener, origin, request.attenuation);\n const occlusionScale = clamp01(occlusion?.gainScale ?? 1);\n const occlusionFilter = this.resolveOcclusion\n ? this.createOcclusionFilter(ctx, occlusion?.lowpassHz ?? 20000)\n : undefined;\n this.applyOriginToPanner(panner, origin);\n const isListenerSound = request.entity === this.playerEntity;\n const spatial = spatializeOrigin(origin, this.listener, request.volume, request.attenuation, isListenerSound);\n\n const attenuationScale = request.volume === 0 ? 0 : Math.max(spatial.left, spatial.right) / Math.max(1, request.volume);\n const gainValue = attenuationScale * (request.volume / 255) * this.masterVolume * this.sfxVolume;\n gain.gain.value = gainValue * occlusionScale;\n\n const startTimeSec = ctx.currentTime + (request.timeOffsetMs ?? 0) / 1000;\n const endTimeMs = (request.looping ? Number.POSITIVE_INFINITY : buffer.duration * 1000) + startTimeSec * 1000;\n\n source.connect(panner);\n if (occlusionFilter) {\n panner.connect(occlusionFilter);\n occlusionFilter.connect(gain);\n } else {\n panner.connect(gain);\n }\n gain.connect(this.graph.master);\n\n source.start(startTimeSec);\n source.onended = () => {\n this.channels[channelIndex].active = false;\n this.activeSources.delete(channelIndex);\n };\n\n const active: ActiveSound = {\n channelIndex,\n entnum: request.entity,\n entchannel: baseChannel(request.channel),\n endTimeMs,\n source,\n panner,\n gain,\n baseGain: gainValue,\n origin,\n attenuation: request.attenuation,\n occlusion: occlusionFilter\n ? { scale: occlusionScale, lowpassHz: occlusion?.lowpassHz, filter: occlusionFilter }\n : occlusion\n ? { scale: occlusionScale, lowpassHz: occlusion.lowpassHz }\n : undefined,\n };\n\n this.channels[channelIndex] = {\n entnum: request.entity,\n entchannel: baseChannel(request.channel),\n endTimeMs,\n isPlayer: request.entity === this.playerEntity,\n active: true,\n };\n\n this.activeSources.set(channelIndex, active);\n return active;\n }\n\n stop(channelIndex: number): void {\n const active = this.activeSources.get(channelIndex);\n if (!active) return;\n active.source.stop();\n this.channels[channelIndex].active = false;\n this.activeSources.delete(channelIndex);\n }\n\n stopEntitySounds(entnum: number): void {\n for (const [index, active] of [...this.activeSources.entries()]) {\n if (active.entnum !== entnum) continue;\n active.source.stop();\n this.channels[index].active = false;\n this.activeSources.delete(index);\n }\n }\n\n updateEntityPosition(entnum: number, origin: Vec3): void {\n for (const active of this.activeSources.values()) {\n if (active.entnum !== entnum) continue;\n this.applyOriginToPanner(active.panner, origin);\n active.origin = origin;\n if (this.resolveOcclusion) {\n const occlusion = this.resolveOcclusion(this.listener, origin, active.attenuation);\n this.applyOcclusion(active, occlusion);\n }\n }\n }\n\n positionedSound(origin: Vec3, soundIndex: number, volume: number, attenuation: number): ActiveSound | undefined {\n return this.play({\n entity: 0,\n channel: SoundChannel.Auto,\n soundIndex,\n volume,\n attenuation,\n origin,\n });\n }\n\n ambientSound(origin: Vec3, soundIndex: number, volume: number): ActiveSound | undefined {\n return this.play({\n entity: 0,\n channel: SoundChannel.Auto,\n soundIndex,\n volume,\n attenuation: ATTN_NONE,\n origin,\n looping: true,\n });\n }\n\n getChannelState(index: number): ChannelState | undefined {\n return this.channels[index];\n }\n\n getDiagnostics(): AudioDiagnostics {\n return {\n activeChannels: this.activeSources.size,\n masterVolume: this.masterVolume,\n sfxVolume: this.sfxVolume,\n channels: [...this.channels],\n activeSounds: [...this.activeSources.values()].map((sound) => ({\n entnum: sound.entnum,\n entchannel: sound.entchannel,\n channelIndex: sound.channelIndex,\n origin: sound.origin,\n gain: sound.gain.gain.value,\n baseGain: sound.baseGain,\n attenuation: sound.attenuation,\n maxDistance: sound.panner.maxDistance,\n distanceModel: sound.panner.distanceModel,\n occlusion: sound.occlusion ? { scale: sound.occlusion.scale, lowpassHz: sound.occlusion.lowpassHz } : undefined,\n })),\n };\n }\n\n setUnderwater(enabled: boolean, cutoffHz = 400): void {\n const filter = this.graph.filter;\n if (!filter) return;\n filter.type = 'lowpass';\n filter.Q.value = 0.707;\n filter.frequency.value = enabled ? cutoffHz : 20000;\n }\n\n private createPanner(context: AudioContextLike, attenuation: number): PannerNodeLike {\n const panner = context.createPanner\n ? context.createPanner()\n : Object.assign(context.createGain(), {\n positionX: { value: this.listener.origin.x },\n positionY: { value: this.listener.origin.y },\n positionZ: { value: this.listener.origin.z },\n } satisfies Partial<PannerNodeLike>);\n\n return this.configurePanner(panner, attenuation);\n }\n\n private configurePanner(panner: PannerNodeLike, attenuation: number): PannerNodeLike {\n const distMult = attenuationToDistanceMultiplier(attenuation);\n panner.refDistance = SOUND_FULLVOLUME;\n panner.maxDistance = calculateMaxAudibleDistance(attenuation);\n panner.rolloffFactor = distMult;\n panner.distanceModel = attenuation === 0 ? 'linear' : 'inverse';\n panner.positionX.value = this.listener.origin.x;\n panner.positionY.value = this.listener.origin.y;\n panner.positionZ.value = this.listener.origin.z;\n return panner;\n }\n\n private applyOriginToPanner(panner: PannerNodeLike, origin: Vec3): void {\n panner.positionX.value = origin.x;\n panner.positionY.value = origin.y;\n panner.positionZ.value = origin.z;\n }\n\n private createOcclusionFilter(context: AudioContextLike, cutoffHz: number): BiquadFilterNodeLike | undefined {\n if (!context.createBiquadFilter) return undefined;\n const filter = context.createBiquadFilter();\n filter.type = 'lowpass';\n filter.Q.value = 0.707;\n filter.frequency.value = clamp(cutoffHz, 10, 20000);\n return filter;\n }\n\n private applyOcclusion(active: ActiveSound, occlusion?: OcclusionResult): void {\n const scale = clamp01(occlusion?.gainScale ?? 1);\n active.gain.gain.value = active.baseGain * scale;\n if (active.occlusion?.filter) {\n const cutoff = occlusion?.lowpassHz ?? 20000;\n active.occlusion.filter.frequency.value = clamp(cutoff, 10, 20000);\n }\n if (active.occlusion) {\n active.occlusion.scale = scale;\n active.occlusion.lowpassHz = occlusion?.lowpassHz;\n } else if (occlusion) {\n active.occlusion = { scale, lowpassHz: occlusion.lowpassHz };\n }\n }\n}\n\nconst clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));\nconst clamp01 = (value: number): number => clamp(value, 0, 1);\n\n","export interface AudioElementLike {\n src: string;\n loop: boolean;\n volume: number;\n currentTime: number;\n paused: boolean;\n ended: boolean;\n play(): Promise<void>;\n pause(): void;\n load(): void;\n}\n\nexport type AudioElementFactory = () => AudioElementLike;\nexport type MusicSourceResolver = (path: string) => Promise<string>;\n\nexport interface MusicSystemOptions {\n createElement: AudioElementFactory;\n resolveSource?: MusicSourceResolver;\n volume?: number;\n}\n\nexport interface MusicState {\n readonly track?: string;\n readonly paused: boolean;\n readonly playing: boolean;\n readonly volume: number;\n}\n\nexport class MusicSystem {\n private readonly createElement: AudioElementFactory;\n private readonly resolveSource: MusicSourceResolver;\n private element?: AudioElementLike;\n private track?: string;\n private volume: number;\n\n constructor(options: MusicSystemOptions) {\n this.createElement = options.createElement;\n this.resolveSource = options.resolveSource ?? (async (path) => path);\n this.volume = options.volume ?? 1;\n }\n\n async play(track: string, { loop = true, restart = false }: { loop?: boolean; restart?: boolean } = {}): Promise<void> {\n if (this.track === track && this.element) {\n this.element.loop = loop;\n this.element.volume = this.volume;\n if (restart) {\n this.element.currentTime = 0;\n }\n if (this.element.paused || restart) {\n await this.element.play();\n }\n return;\n }\n\n const src = await this.resolveSource(track);\n const element = this.createElement();\n element.src = src;\n element.loop = loop;\n element.volume = this.volume;\n element.currentTime = 0;\n element.load();\n await element.play();\n\n this.element = element;\n this.track = track;\n }\n\n pause(): void {\n if (!this.element || this.element.paused) return;\n this.element.pause();\n }\n\n async resume(): Promise<void> {\n if (!this.element || !this.element.paused) return;\n await this.element.play();\n }\n\n stop(): void {\n if (!this.element) return;\n this.element.pause();\n this.element.currentTime = 0;\n this.element = undefined;\n this.track = undefined;\n }\n\n setVolume(volume: number): void {\n this.volume = volume;\n if (this.element) {\n this.element.volume = volume;\n }\n }\n\n getState(): MusicState {\n const playing = Boolean(this.element && !this.element.paused && !this.element.ended);\n const paused = Boolean(this.element?.paused);\n return { track: this.track, paused, playing, volume: this.volume };\n }\n}\n","import { type Vec3 } from '@quake2ts/shared';\nimport { MusicSystem } from './music.js';\nimport { SoundRegistry } from './registry.js';\nimport { AudioSystem, type SoundRequest } from './system.js';\n\nexport interface AudioApiOptions {\n registry: SoundRegistry;\n system: AudioSystem;\n music?: MusicSystem;\n}\n\nexport class AudioApi {\n private readonly registry: SoundRegistry;\n private readonly system: AudioSystem;\n private readonly music?: MusicSystem;\n\n constructor(options: AudioApiOptions) {\n this.registry = options.registry;\n this.system = options.system;\n this.music = options.music;\n }\n\n soundindex(name: string): number {\n return this.registry.registerName(name);\n }\n\n sound(entity: number, channel: number, soundindex: number, volume: number, attenuation: number, timeofs: number): void {\n this.system.play({\n entity,\n channel,\n soundIndex: soundindex,\n volume,\n attenuation,\n timeOffsetMs: timeofs,\n });\n }\n\n positioned_sound(origin: Vec3, soundindex: number, volume: number, attenuation: number): void {\n this.system.positionedSound(origin, soundindex, volume, attenuation);\n }\n\n loop_sound(entity: number, channel: number, soundindex: number, volume: number, attenuation: number): void {\n this.system.play({\n entity,\n channel,\n soundIndex: soundindex,\n volume,\n attenuation,\n looping: true,\n });\n }\n\n stop_entity_sounds(entnum: number): void {\n this.system.stopEntitySounds(entnum);\n }\n\n set_listener(listener: Parameters<AudioSystem['setListener']>[0]): void {\n this.system.setListener(listener);\n }\n\n play_music(track: string, loop = true): Promise<void> {\n if (!this.music) {\n return Promise.resolve();\n }\n return this.music.play(track, { loop });\n }\n\n pause_music(): void {\n this.music?.pause();\n }\n\n resume_music(): Promise<void> {\n return this.music?.resume() ?? Promise.resolve();\n }\n\n stop_music(): void {\n this.music?.stop();\n }\n\n set_music_volume(volume: number): void {\n this.music?.setVolume(volume);\n }\n\n play_ambient(origin: Vec3, soundindex: number, volume: number): void {\n this.system.ambientSound(origin, soundindex, volume);\n }\n\n play_channel(request: Omit<SoundRequest, 'looping'>): void {\n this.system.play({ ...request });\n }\n}\n","export interface WebGLContextInitOptions {\n /**\n * Options passed to `canvas.getContext`. Defaults to antialias enabled to match the rerelease renderer's smoothing.\n */\n readonly contextAttributes?: WebGLContextAttributes;\n /**\n * Extensions that must be present. Missing entries throw during construction so callers can fall back early.\n */\n readonly requiredExtensions?: readonly string[];\n /**\n * Extensions that will be queried if available. Missing optional extensions are ignored.\n */\n readonly optionalExtensions?: readonly string[];\n}\n\nexport interface WebGLContextState {\n readonly gl: WebGL2RenderingContext;\n readonly extensions: Map<string, unknown>;\n /**\n * Returns true once a `webglcontextlost` event has been observed.\n */\n isLost(): boolean;\n /**\n * Registers a callback that fires on context loss. Returns an unsubscribe function.\n */\n onLost(callback: () => void): () => void;\n /**\n * Registers a callback that fires on context restoration. Returns an unsubscribe function.\n */\n onRestored(callback: () => void): () => void;\n /**\n * Remove event listeners and release references.\n */\n dispose(): void;\n}\n\nfunction configureDefaultGLState(gl: WebGL2RenderingContext): void {\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n gl.enable(gl.CULL_FACE);\n gl.cullFace(gl.BACK);\n gl.enable(gl.BLEND);\n gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nfunction queryExtensions(\n gl: WebGL2RenderingContext,\n required: readonly string[],\n optional: readonly string[],\n collector: Map<string, unknown>\n): void {\n for (const name of required) {\n const ext = gl.getExtension(name);\n if (!ext) {\n throw new Error(`Missing required WebGL extension: ${name}`);\n }\n collector.set(name, ext);\n }\n\n for (const name of optional) {\n const ext = gl.getExtension(name);\n if (ext) {\n collector.set(name, ext);\n }\n }\n}\n\nexport function createWebGLContext(\n canvas: HTMLCanvasElement,\n options: WebGLContextInitOptions = {}\n): WebGLContextState {\n const { contextAttributes, requiredExtensions = [], optionalExtensions = [] } = options;\n const gl = canvas.getContext('webgl2', contextAttributes ?? { antialias: true });\n if (!gl) {\n throw new Error('WebGL2 not supported or failed to initialize');\n }\n\n configureDefaultGLState(gl);\n\n const extensions = new Map<string, unknown>();\n queryExtensions(gl, requiredExtensions, optionalExtensions, extensions);\n\n let lost = false;\n const lostCallbacks = new Set<() => void>();\n const restoreCallbacks = new Set<() => void>();\n\n const lostListener = (event: Event): void => {\n lost = true;\n event.preventDefault();\n for (const callback of lostCallbacks) {\n callback();\n }\n };\n const restoreListener = (): void => {\n lost = false;\n for (const callback of restoreCallbacks) {\n callback();\n }\n };\n\n canvas.addEventListener('webglcontextlost', lostListener);\n canvas.addEventListener('webglcontextrestored', restoreListener);\n\n return {\n gl,\n extensions,\n isLost: () => lost,\n onLost(callback: () => void) {\n lostCallbacks.add(callback);\n return () => lostCallbacks.delete(callback);\n },\n onRestored(callback: () => void) {\n restoreCallbacks.add(callback);\n return () => restoreCallbacks.delete(callback);\n },\n dispose() {\n canvas.removeEventListener('webglcontextlost', lostListener);\n canvas.removeEventListener('webglcontextrestored', restoreListener);\n lostCallbacks.clear();\n restoreCallbacks.clear();\n extensions.clear();\n },\n };\n}\n","export interface ShaderSources {\n readonly vertex: string;\n readonly fragment: string;\n}\n\nfunction compileShader(gl: WebGL2RenderingContext, type: GLenum, source: string): WebGLShader {\n const shader = gl.createShader(type);\n if (!shader) {\n throw new Error('Failed to allocate shader');\n }\n\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n const ok = gl.getShaderParameter(shader, gl.COMPILE_STATUS) as boolean;\n if (!ok) {\n const log = gl.getShaderInfoLog(shader) ?? 'Unknown shader compile failure';\n gl.deleteShader(shader);\n throw new Error(log);\n }\n\n return shader;\n}\n\nfunction linkProgram(\n gl: WebGL2RenderingContext,\n vertexShader: WebGLShader,\n fragmentShader: WebGLShader,\n attributeLocations?: Record<string, number>\n): WebGLProgram {\n const program = gl.createProgram();\n if (!program) {\n throw new Error('Failed to allocate shader program');\n }\n\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n\n if (attributeLocations) {\n for (const [name, location] of Object.entries(attributeLocations)) {\n gl.bindAttribLocation(program, location, name);\n }\n }\n\n gl.linkProgram(program);\n const ok = gl.getProgramParameter(program, gl.LINK_STATUS) as boolean;\n if (!ok) {\n const log = gl.getProgramInfoLog(program) ?? 'Unknown shader link failure';\n gl.deleteProgram(program);\n throw new Error(log);\n }\n\n return program;\n}\n\nexport class ShaderProgram {\n readonly gl: WebGL2RenderingContext;\n readonly program: WebGLProgram;\n private readonly uniformLocations = new Map<string, WebGLUniformLocation | null>();\n private readonly attributeLocations = new Map<string, number>();\n\n private constructor(gl: WebGL2RenderingContext, program: WebGLProgram) {\n this.gl = gl;\n this.program = program;\n }\n\n static create(\n gl: WebGL2RenderingContext,\n sources: ShaderSources,\n attributeLocations?: Record<string, number>\n ): ShaderProgram {\n const vertexShader = compileShader(gl, gl.VERTEX_SHADER, sources.vertex);\n const fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, sources.fragment);\n try {\n const program = linkProgram(gl, vertexShader, fragmentShader, attributeLocations);\n return new ShaderProgram(gl, program);\n } finally {\n gl.deleteShader(vertexShader);\n gl.deleteShader(fragmentShader);\n }\n }\n\n use(): void {\n this.gl.useProgram(this.program);\n }\n\n getUniformLocation(name: string): WebGLUniformLocation | null {\n if (!this.uniformLocations.has(name)) {\n const location = this.gl.getUniformLocation(this.program, name);\n this.uniformLocations.set(name, location);\n }\n\n return this.uniformLocations.get(name) ?? null;\n }\n\n getAttributeLocation(name: string): number {\n if (!this.attributeLocations.has(name)) {\n const location = this.gl.getAttribLocation(this.program, name);\n this.attributeLocations.set(name, location);\n }\n\n return this.attributeLocations.get(name) ?? -1;\n }\n\n dispose(): void {\n this.gl.deleteProgram(this.program);\n this.uniformLocations.clear();\n this.attributeLocations.clear();\n }\n}\n\nexport function createProgramFromSources(\n gl: WebGL2RenderingContext,\n sources: ShaderSources,\n attributeLocations?: Record<string, number>\n): ShaderProgram {\n return ShaderProgram.create(gl, sources, attributeLocations);\n}\n","export type BufferUsage = GLenum;\n\nexport interface VertexAttributeLayout {\n readonly index: number;\n readonly size: number;\n readonly type: GLenum;\n readonly normalized?: boolean;\n readonly stride?: number;\n readonly offset?: number;\n readonly divisor?: number;\n}\n\nexport class VertexBuffer {\n readonly gl: WebGL2RenderingContext;\n readonly buffer: WebGLBuffer;\n readonly target: GLenum;\n\n constructor(gl: WebGL2RenderingContext, usage: BufferUsage = gl.STATIC_DRAW, target?: GLenum) {\n this.gl = gl;\n this.target = target ?? gl.ARRAY_BUFFER;\n const buffer = gl.createBuffer();\n if (!buffer) {\n throw new Error('Failed to allocate buffer');\n }\n this.buffer = buffer;\n gl.bindBuffer(this.target, this.buffer);\n gl.bufferData(this.target, 0, usage);\n }\n\n bind(): void {\n this.gl.bindBuffer(this.target, this.buffer);\n }\n\n upload(data: BufferSource, usage: BufferUsage = this.gl.STATIC_DRAW): void {\n this.bind();\n this.gl.bufferData(this.target, data, usage);\n }\n\n update(data: BufferSource, offset = 0): void {\n this.bind();\n this.gl.bufferSubData(this.target, offset, data);\n }\n\n dispose(): void {\n this.gl.deleteBuffer(this.buffer);\n }\n}\n\nexport class IndexBuffer extends VertexBuffer {\n constructor(gl: WebGL2RenderingContext, usage: BufferUsage = gl.STATIC_DRAW) {\n super(gl, usage, gl.ELEMENT_ARRAY_BUFFER);\n }\n}\n\nexport class VertexArray {\n readonly gl: WebGL2RenderingContext;\n readonly vao: WebGLVertexArrayObject;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n const vao = gl.createVertexArray();\n if (!vao) {\n throw new Error('Failed to allocate vertex array object');\n }\n this.vao = vao;\n }\n\n bind(): void {\n this.gl.bindVertexArray(this.vao);\n }\n\n configureAttributes(layouts: readonly VertexAttributeLayout[], buffer?: VertexBuffer): void {\n this.bind();\n if (buffer) {\n buffer.bind();\n }\n\n for (const layout of layouts) {\n this.gl.enableVertexAttribArray(layout.index);\n this.gl.vertexAttribPointer(\n layout.index,\n layout.size,\n layout.type,\n layout.normalized ?? false,\n layout.stride ?? 0,\n layout.offset ?? 0\n );\n if (layout.divisor !== undefined) {\n this.gl.vertexAttribDivisor(layout.index, layout.divisor);\n }\n }\n }\n\n dispose(): void {\n this.gl.deleteVertexArray(this.vao);\n }\n}\n\nexport interface TextureParameters {\n readonly wrapS?: GLenum;\n readonly wrapT?: GLenum;\n readonly minFilter?: GLenum;\n readonly magFilter?: GLenum;\n}\n\nexport class Texture2D {\n readonly gl: WebGL2RenderingContext;\n readonly texture: WebGLTexture;\n readonly target: GLenum;\n\n width = 0;\n height = 0;\n\n constructor(gl: WebGL2RenderingContext, target: GLenum = gl.TEXTURE_2D) {\n this.gl = gl;\n this.target = target;\n const texture = gl.createTexture();\n if (!texture) {\n throw new Error('Failed to allocate texture');\n }\n this.texture = texture;\n }\n\n bind(unit = 0): void {\n this.gl.activeTexture(this.gl.TEXTURE0 + unit);\n this.gl.bindTexture(this.target, this.texture);\n }\n\n setParameters(params: TextureParameters): void {\n this.bind();\n if (params.wrapS !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_S, params.wrapS);\n }\n if (params.wrapT !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_T, params.wrapT);\n }\n if (params.minFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MIN_FILTER, params.minFilter);\n }\n if (params.magFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MAG_FILTER, params.magFilter);\n }\n }\n\n upload(width: number, height: number, data: TexImageSource | ArrayBufferView | null) {\n this.width = width;\n this.height = height;\n this.uploadImage(0, this.gl.RGBA, width, height, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, data);\n }\n\n uploadImage(\n level: number,\n internalFormat: GLenum,\n width: number,\n height: number,\n border: number,\n format: GLenum,\n type: GLenum,\n data: TexImageSource | ArrayBufferView | null\n ): void {\n this.bind();\n this.gl.texImage2D(this.target, level, internalFormat, width, height, border, format, type, data as any);\n }\n\n dispose(): void {\n this.gl.deleteTexture(this.texture);\n }\n}\n\nexport class TextureCubeMap {\n readonly gl: WebGL2RenderingContext;\n readonly texture: WebGLTexture;\n readonly target: GLenum;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.target = gl.TEXTURE_CUBE_MAP;\n const texture = gl.createTexture();\n if (!texture) {\n throw new Error('Failed to allocate cubemap texture');\n }\n this.texture = texture;\n }\n\n bind(unit = 0): void {\n this.gl.activeTexture(this.gl.TEXTURE0 + unit);\n this.gl.bindTexture(this.target, this.texture);\n }\n\n setParameters(params: TextureParameters): void {\n this.bind();\n if (params.wrapS !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_S, params.wrapS);\n }\n if (params.wrapT !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_T, params.wrapT);\n }\n if (params.minFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MIN_FILTER, params.minFilter);\n }\n if (params.magFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MAG_FILTER, params.magFilter);\n }\n }\n\n uploadFace(\n faceTarget: GLenum,\n level: number,\n internalFormat: GLenum,\n width: number,\n height: number,\n border: number,\n format: GLenum,\n type: GLenum,\n data: ArrayBufferView | null\n ): void {\n this.bind();\n this.gl.texImage2D(faceTarget, level, internalFormat, width, height, border, format, type, data);\n }\n\n dispose(): void {\n this.gl.deleteTexture(this.texture);\n }\n}\n\nexport class Framebuffer {\n readonly gl: WebGL2RenderingContext;\n readonly framebuffer: WebGLFramebuffer;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n const framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error('Failed to allocate framebuffer');\n }\n this.framebuffer = framebuffer;\n }\n\n bind(target: GLenum = this.gl.FRAMEBUFFER): void {\n this.gl.bindFramebuffer(target, this.framebuffer);\n }\n\n attachTexture2D(attachment: GLenum, texture: Texture2D, level = 0): void {\n this.bind();\n this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, attachment, texture.target, texture.texture, level);\n }\n\n dispose(): void {\n this.gl.deleteFramebuffer(this.framebuffer);\n }\n}\n","import { SURF_NONE, type SurfaceFlag } from '@quake2ts/shared';\nimport {\n IndexBuffer,\n Texture2D,\n VertexArray,\n VertexBuffer,\n type VertexAttributeLayout,\n} from './resources.js';\nimport { BspMap, createFaceLightmap } from '../assets/bsp.js';\n\nexport interface BspLightmapData {\n readonly width: number;\n readonly height: number;\n readonly samples: Uint8Array;\n}\n\nexport interface BspSurfaceInput {\n readonly vertices: ReadonlyArray<number> | Float32Array;\n readonly textureCoords: ReadonlyArray<number> | Float32Array;\n readonly lightmapCoords?: ReadonlyArray<number> | Float32Array;\n readonly indices?: ReadonlyArray<number> | Uint16Array | Uint32Array;\n readonly texture: string;\n readonly surfaceFlags?: SurfaceFlag;\n readonly lightmap?: BspLightmapData;\n}\n\nexport interface LightmapPlacement {\n readonly atlasIndex: number;\n readonly offset: [number, number];\n readonly scale: [number, number];\n}\n\nexport interface BspSurfaceGeometry {\n readonly vao: VertexArray;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly indexCount: number;\n readonly vertexCount: number;\n readonly texture: string;\n readonly surfaceFlags: SurfaceFlag;\n readonly lightmap?: LightmapPlacement;\n // CPU copies retained for deterministic tests and debugging.\n readonly vertexData: Float32Array;\n readonly indexData: Uint16Array;\n}\n\nexport interface LightmapAtlas {\n readonly texture: Texture2D;\n readonly width: number;\n readonly height: number;\n readonly pixels: Uint8Array;\n}\n\nexport interface BspBuildOptions {\n readonly atlasSize?: number;\n readonly lightmapPadding?: number;\n}\n\nexport interface BspGeometryBuildResult {\n readonly surfaces: readonly BspSurfaceGeometry[];\n readonly lightmaps: readonly LightmapAtlas[];\n}\n\nconst FLOAT_BYTES = 4;\nconst STRIDE = 7 * FLOAT_BYTES;\n\nexport const BSP_VERTEX_LAYOUT: readonly VertexAttributeLayout[] = [\n // Position\n { index: 0, size: 3, type: 0x1406, stride: STRIDE, offset: 0 },\n // Diffuse UV\n { index: 1, size: 2, type: 0x1406, stride: STRIDE, offset: 3 * FLOAT_BYTES },\n // Lightmap UV\n { index: 2, size: 2, type: 0x1406, stride: STRIDE, offset: 5 * FLOAT_BYTES },\n];\n\ninterface LightmapPlacementInfo {\n readonly atlasIndex: number;\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\ninterface AtlasBuilder {\n readonly width: number;\n readonly height: number;\n readonly padding: number;\n readonly data: Uint8Array;\n cursorX: number;\n cursorY: number;\n rowHeight: number;\n}\n\nfunction createAtlasBuilder(size: number, padding: number): AtlasBuilder {\n const channelCount = 4; // We upload as RGBA for compatibility.\n return {\n width: size,\n height: size,\n padding,\n data: new Uint8Array(size * size * channelCount),\n cursorX: 0,\n cursorY: 0,\n rowHeight: 0,\n };\n}\n\nfunction detectChannels(lightmap: BspLightmapData): number {\n const pixels = lightmap.width * lightmap.height;\n if (pixels === 0) {\n throw new Error('Invalid lightmap with zero area');\n }\n const channels = lightmap.samples.byteLength / pixels;\n if (!Number.isInteger(channels) || channels < 3 || channels > 4) {\n throw new Error('Unsupported lightmap channel count');\n }\n return channels;\n}\n\nfunction writeLightmapIntoAtlas(\n atlas: AtlasBuilder,\n placement: LightmapPlacementInfo,\n lightmap: BspLightmapData\n): void {\n const channels = detectChannels(lightmap);\n const stride = atlas.width * 4;\n const startX = placement.x + atlas.padding;\n const startY = placement.y + atlas.padding;\n let srcIndex = 0;\n\n for (let y = 0; y < lightmap.height; y++) {\n const destRow = (startY + y) * stride + startX * 4;\n for (let x = 0; x < lightmap.width; x++) {\n const dest = destRow + x * 4;\n atlas.data[dest] = lightmap.samples[srcIndex];\n atlas.data[dest + 1] = lightmap.samples[srcIndex + 1];\n atlas.data[dest + 2] = lightmap.samples[srcIndex + 2];\n atlas.data[dest + 3] = channels === 4 ? lightmap.samples[srcIndex + 3] : 255;\n srcIndex += channels;\n }\n }\n}\n\nfunction placeLightmap(\n builders: AtlasBuilder[],\n lightmap: BspLightmapData,\n options: Required<BspBuildOptions>\n): { placement: LightmapPlacementInfo; atlas: AtlasBuilder } {\n const paddedWidth = lightmap.width + options.lightmapPadding * 2;\n const paddedHeight = lightmap.height + options.lightmapPadding * 2;\n if (paddedWidth > options.atlasSize || paddedHeight > options.atlasSize) {\n throw new Error('Lightmap too large for atlas');\n }\n\n for (const atlas of builders) {\n if (atlas.cursorX + paddedWidth > atlas.width) {\n atlas.cursorX = 0;\n atlas.cursorY += atlas.rowHeight + options.lightmapPadding;\n atlas.rowHeight = 0;\n }\n\n if (atlas.cursorY + paddedHeight > atlas.height) {\n continue;\n }\n\n const placement: LightmapPlacementInfo = {\n atlasIndex: builders.indexOf(atlas),\n x: atlas.cursorX,\n y: atlas.cursorY,\n width: lightmap.width,\n height: lightmap.height,\n };\n\n atlas.cursorX += paddedWidth + options.lightmapPadding;\n atlas.rowHeight = Math.max(atlas.rowHeight, paddedHeight);\n return { placement, atlas };\n }\n\n const atlas = createAtlasBuilder(options.atlasSize, options.lightmapPadding);\n builders.push(atlas);\n const placement: LightmapPlacementInfo = { atlasIndex: builders.length - 1, x: 0, y: 0, width: lightmap.width, height: lightmap.height };\n atlas.cursorX = paddedWidth + options.lightmapPadding;\n atlas.rowHeight = paddedHeight;\n return { placement, atlas };\n}\n\nfunction ensureFloat32(array: ReadonlyArray<number> | Float32Array): Float32Array {\n return array instanceof Float32Array ? array : new Float32Array(array);\n}\n\nfunction ensureIndexArray(indices: ReadonlyArray<number> | Uint16Array | Uint32Array | undefined, vertexCount: number): Uint16Array {\n if (!indices) {\n const generated = new Uint16Array(vertexCount);\n for (let i = 0; i < vertexCount; i++) {\n generated[i] = i;\n }\n return generated;\n }\n\n const converted = indices instanceof Uint16Array ? indices : new Uint16Array(indices);\n return converted;\n}\n\nfunction remapLightmapCoords(\n coords: Float32Array,\n placement: LightmapPlacement,\n): Float32Array {\n const remapped = new Float32Array(coords.length);\n for (let i = 0; i < coords.length; i += 2) {\n remapped[i] = placement.offset[0] + coords[i] * placement.scale[0];\n remapped[i + 1] = placement.offset[1] + coords[i + 1] * placement.scale[1];\n }\n return remapped;\n}\n\nfunction buildVertexData(\n surface: BspSurfaceInput,\n placement: LightmapPlacement | undefined\n): Float32Array {\n const vertices = ensureFloat32(surface.vertices);\n const texCoords = ensureFloat32(surface.textureCoords);\n const lightmapCoords = placement\n ? remapLightmapCoords(ensureFloat32(surface.lightmapCoords ?? surface.textureCoords), placement)\n : ensureFloat32(surface.lightmapCoords ?? new Float32Array(texCoords.length));\n\n const vertexCount = vertices.length / 3;\n if (texCoords.length / 2 !== vertexCount) {\n throw new Error('Texture coordinates count mismatch');\n }\n if (lightmapCoords.length / 2 !== vertexCount) {\n throw new Error('Lightmap coordinates count mismatch');\n }\n\n const interleaved = new Float32Array(vertexCount * 7);\n for (let i = 0; i < vertexCount; i++) {\n const v = i * 3;\n const t = i * 2;\n const o = i * 7;\n interleaved[o] = vertices[v];\n interleaved[o + 1] = vertices[v + 1];\n interleaved[o + 2] = vertices[v + 2];\n interleaved[o + 3] = texCoords[t];\n interleaved[o + 4] = texCoords[t + 1];\n interleaved[o + 5] = lightmapCoords[t];\n interleaved[o + 6] = lightmapCoords[t + 1];\n }\n return interleaved;\n}\n\n/**\n * Converts a parsed BSP map into a set of flat surface inputs ready for rendering.\n *\n * This function handles:\n * 1. Traversing faces and their edges to build vertex lists.\n * 2. Calculating texture coordinates (UVs) from surface normals and texture info.\n * 3. Generating triangle indices (fan triangulation) for convex polygon faces.\n * 4. Extracting and calculating lightmap data and coordinates.\n *\n * @param map The parsed BSP map structure.\n * @returns An array of surface inputs suitable for consumption by `buildBspGeometry`.\n */\nexport function createBspSurfaces(map: BspMap): BspSurfaceInput[] {\n const results: BspSurfaceInput[] = [];\n\n // Iterate over all faces using index to allow efficient lookups of parallel arrays (e.g. lightMapInfo).\n for (let faceIndex = 0; faceIndex < map.faces.length; faceIndex++) {\n const face = map.faces[faceIndex];\n\n // Skip faces with invalid texture info (e.g., logic/clip brushes).\n if (face.texInfo < 0) continue;\n\n const texInfo = map.texInfo[face.texInfo];\n const vertices: number[] = [];\n const textureCoords: number[] = [];\n const lightmapCoords: number[] = [];\n\n // Retrieve vertices for this face by walking its edges.\n // BSP faces are stored as references to a global edge list.\n for (let i = 0; i < face.numEdges; i++) {\n const edgeIndex = map.surfEdges[face.firstEdge + i];\n const edge = map.edges[Math.abs(edgeIndex)];\n // A positive edge index means traversal from vertex 0 to 1.\n // A negative edge index means traversal from vertex 1 to 0.\n const vIndex = edgeIndex >= 0 ? edge.vertices[0] : edge.vertices[1];\n const vertex = map.vertices[vIndex];\n\n vertices.push(vertex[0], vertex[1], vertex[2]);\n\n // Calculate standard texture coordinates (s, t) using the texture axes.\n // s = dot(v, s_vector) + s_offset\n // t = dot(v, t_vector) + t_offset\n const s = vertex[0] * texInfo.s[0] + vertex[1] * texInfo.s[1] + vertex[2] * texInfo.s[2] + texInfo.sOffset;\n const t = vertex[0] * texInfo.t[0] + vertex[1] * texInfo.t[1] + vertex[2] * texInfo.t[2] + texInfo.tOffset;\n\n textureCoords.push(s, t);\n\n // Lightmap coordinates are tentatively set to texture coordinates.\n // If valid lightmap data exists, they will be recalculated later.\n lightmapCoords.push(s, t);\n }\n\n // Triangulate the face. BSP faces are convex polygons, so a simple triangle fan\n // originating from the first vertex (index 0) covers the surface.\n const indices: number[] = [];\n const vertexCount = vertices.length / 3;\n for (let i = 1; i < vertexCount - 1; i++) {\n indices.push(0, i, i + 1);\n }\n\n // Process lightmap data if available.\n let lightmapData: BspLightmapData | undefined;\n const lightmapInfo = map.lightMapInfo[faceIndex];\n\n if (lightmapInfo) {\n // Calculate the extents of the texture coordinates to determine lightmap dimensions.\n // Quake 2 lightmaps are 1/16th scale of the texture coordinates.\n let minS = Infinity, maxS = -Infinity, minT = Infinity, maxT = -Infinity;\n for (let k = 0; k < textureCoords.length; k+=2) {\n const s = textureCoords[k];\n const t = textureCoords[k+1];\n if (s < minS) minS = s;\n if (s > maxS) maxS = s;\n if (t < minT) minT = t;\n if (t > maxT) maxT = t;\n }\n\n // Lightmap dimensions are ceil(max/16) - floor(min/16) + 1\n const floorMinS = Math.floor(minS / 16);\n const floorMinT = Math.floor(minT / 16);\n const lmWidth = Math.ceil(maxS / 16) - floorMinS + 1;\n const lmHeight = Math.ceil(maxT / 16) - floorMinT + 1;\n\n // Extract the raw lightmap samples from the BSP lump.\n const samples = createFaceLightmap(face, map.lightMaps, lightmapInfo);\n\n if (samples) {\n // Sanity check: the extracted sample count must match the calculated dimensions.\n if (samples.length === lmWidth * lmHeight * 3) {\n lightmapData = { width: lmWidth, height: lmHeight, samples };\n\n // Recalculate lightmap UVs based on the 1/16th scale and min offset.\n // We add 0.5 to center the sample.\n for (let k = 0; k < lightmapCoords.length; k+=2) {\n lightmapCoords[k] = (textureCoords[k] / 16) - floorMinS + 0.5;\n lightmapCoords[k+1] = (textureCoords[k+1] / 16) - floorMinT + 0.5;\n }\n }\n }\n }\n\n results.push({\n vertices: new Float32Array(vertices),\n textureCoords: new Float32Array(textureCoords),\n lightmapCoords: new Float32Array(lightmapCoords),\n indices: new Uint16Array(indices),\n texture: texInfo.texture,\n surfaceFlags: texInfo.flags,\n lightmap: lightmapData\n });\n }\n\n return results;\n}\n\nexport function buildBspGeometry(\n gl: WebGL2RenderingContext,\n surfaces: readonly BspSurfaceInput[],\n options: BspBuildOptions = {}\n): BspGeometryBuildResult {\n const resolved: Required<BspBuildOptions> = {\n atlasSize: options.atlasSize ?? 1024,\n lightmapPadding: options.lightmapPadding ?? 1,\n };\n\n const atlasBuilders: AtlasBuilder[] = [];\n const placements = new Map<number, LightmapPlacement>();\n\n surfaces.forEach((surface, index) => {\n if (!surface.lightmap) {\n return;\n }\n const { placement, atlas } = placeLightmap(atlasBuilders, surface.lightmap, resolved);\n writeLightmapIntoAtlas(atlas, placement, surface.lightmap);\n placements.set(index, {\n atlasIndex: placement.atlasIndex,\n offset: [\n (placement.x + resolved.lightmapPadding) / resolved.atlasSize,\n (placement.y + resolved.lightmapPadding) / resolved.atlasSize,\n ],\n scale: [placement.width / resolved.atlasSize, placement.height / resolved.atlasSize],\n });\n });\n\n const lightmaps: LightmapAtlas[] = atlasBuilders.map((builder) => {\n const texture = new Texture2D(gl);\n texture.setParameters({\n wrapS: gl.CLAMP_TO_EDGE,\n wrapT: gl.CLAMP_TO_EDGE,\n minFilter: gl.LINEAR,\n magFilter: gl.LINEAR,\n });\n texture.uploadImage(0, gl.RGBA, builder.width, builder.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, builder.data);\n return { texture, width: builder.width, height: builder.height, pixels: builder.data };\n });\n\n const results: BspSurfaceGeometry[] = surfaces.map((surface, index) => {\n const placement = placements.get(index);\n const vertexData = buildVertexData(surface, placement);\n const indexData = ensureIndexArray(surface.indices, vertexData.length / 7);\n\n const vertexBuffer = new VertexBuffer(gl, gl.STATIC_DRAW, gl.ARRAY_BUFFER);\n vertexBuffer.upload(vertexData as unknown as BufferSource);\n\n const indexBuffer = new IndexBuffer(gl, gl.STATIC_DRAW);\n indexBuffer.upload(indexData as unknown as BufferSource);\n\n const vao = new VertexArray(gl);\n vao.configureAttributes(BSP_VERTEX_LAYOUT, vertexBuffer);\n\n return {\n vao,\n vertexBuffer,\n indexBuffer,\n indexCount: indexData.length,\n vertexCount: vertexData.length / 7,\n texture: surface.texture,\n surfaceFlags: surface.surfaceFlags ?? SURF_NONE,\n lightmap: placement,\n vertexData,\n indexData,\n };\n });\n\n return { surfaces: results, lightmaps };\n}\n","import { type Vec3 } from '@quake2ts/shared';\n\nexport interface FrustumPlane {\n readonly normal: Vec3;\n readonly distance: number;\n}\n\nfunction normalizePlane(plane: FrustumPlane): FrustumPlane {\n const { normal, distance } = plane;\n const length = Math.sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z);\n if (length === 0) {\n return plane;\n }\n const inv = 1 / length;\n return {\n normal: { x: normal.x * inv, y: normal.y * inv, z: normal.z * inv },\n distance: distance * inv,\n };\n}\n\nexport function extractFrustumPlanes(matrix: readonly number[]): readonly FrustumPlane[] {\n if (matrix.length !== 16) {\n throw new Error('View-projection matrix must contain 16 elements');\n }\n\n const m00 = matrix[0];\n const m01 = matrix[4];\n const m02 = matrix[8];\n const m03 = matrix[12];\n const m10 = matrix[1];\n const m11 = matrix[5];\n const m12 = matrix[9];\n const m13 = matrix[13];\n const m20 = matrix[2];\n const m21 = matrix[6];\n const m22 = matrix[10];\n const m23 = matrix[14];\n const m30 = matrix[3];\n const m31 = matrix[7];\n const m32 = matrix[11];\n const m33 = matrix[15];\n\n const planes: FrustumPlane[] = [\n // Left\n normalizePlane({ normal: { x: m30 + m00, y: m31 + m01, z: m32 + m02 }, distance: m33 + m03 }),\n // Right\n normalizePlane({ normal: { x: m30 - m00, y: m31 - m01, z: m32 - m02 }, distance: m33 - m03 }),\n // Bottom\n normalizePlane({ normal: { x: m30 + m10, y: m31 + m11, z: m32 + m12 }, distance: m33 + m13 }),\n // Top\n normalizePlane({ normal: { x: m30 - m10, y: m31 - m11, z: m32 - m12 }, distance: m33 - m13 }),\n // Near\n normalizePlane({ normal: { x: m30 + m20, y: m31 + m21, z: m32 + m22 }, distance: m33 + m23 }),\n // Far\n normalizePlane({ normal: { x: m30 - m20, y: m31 - m21, z: m32 - m22 }, distance: m33 - m23 }),\n ];\n\n return planes;\n}\n\nfunction planeDistance(plane: FrustumPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z + plane.distance;\n}\n\nexport function boxIntersectsFrustum(mins: Vec3, maxs: Vec3, planes: readonly FrustumPlane[]): boolean {\n for (const plane of planes) {\n // Choose the corner most likely to be outside based on the plane normal.\n const x = plane.normal.x >= 0 ? maxs.x : mins.x;\n const y = plane.normal.y >= 0 ? maxs.y : mins.y;\n const z = plane.normal.z >= 0 ? maxs.z : mins.z;\n if (planeDistance(plane, { x, y, z }) < 0) {\n return false;\n }\n }\n return true;\n}\n","import { type Vec3 } from '@quake2ts/shared';\nimport type {\n BspLeaf,\n BspMap,\n BspNode,\n BspPlane,\n BspVisibility,\n} from '../assets/bsp.js';\nimport { boxIntersectsFrustum, type FrustumPlane } from './culling.js';\n\nexport interface VisibleFace {\n readonly faceIndex: number;\n readonly leafIndex: number;\n readonly sortKey: number;\n}\n\nfunction childIsLeaf(index: number): boolean {\n return index < 0;\n}\n\nfunction childLeafIndex(index: number): number {\n return -index - 1;\n}\n\nfunction distanceToPlane(plane: BspPlane, point: Vec3): number {\n return plane.normal[0] * point.x + plane.normal[1] * point.y + plane.normal[2] * point.z - plane.dist;\n}\n\nfunction isClusterVisible(visibility: BspVisibility | undefined, fromCluster: number, testCluster: number): boolean {\n if (!visibility) {\n return true;\n }\n if (fromCluster < 0 || testCluster < 0) {\n return true;\n }\n const rowBytes = Math.ceil(visibility.numClusters / 8);\n const row = visibility.clusters[fromCluster].pvs;\n const byteIndex = Math.floor(testCluster / 8);\n const bit = 1 << (testCluster % 8);\n if (byteIndex < 0 || byteIndex >= rowBytes) {\n return false;\n }\n return (row[byteIndex] & bit) !== 0;\n}\n\nfunction leafIntersectsFrustum(leaf: BspLeaf, planes: readonly FrustumPlane[]): boolean {\n const mins = { x: leaf.mins[0], y: leaf.mins[1], z: leaf.mins[2] };\n const maxs = { x: leaf.maxs[0], y: leaf.maxs[1], z: leaf.maxs[2] };\n return boxIntersectsFrustum(mins, maxs, planes);\n}\n\nexport function findLeafForPoint(map: BspMap, point: Vec3): number {\n let nodeIndex = 0;\n while (nodeIndex >= 0) {\n const node: BspNode = map.nodes[nodeIndex];\n const plane = map.planes[node.planeIndex];\n const dist = distanceToPlane(plane, point);\n const side = dist >= 0 ? 0 : 1;\n const child = node.children[side];\n if (childIsLeaf(child)) {\n return childLeafIndex(child);\n }\n nodeIndex = child;\n }\n return -1;\n}\n\nfunction collectFacesFromLeaf(map: BspMap, leafIndex: number): number[] {\n const leaf = map.leafs[leafIndex];\n const faces: number[] = [];\n for (let i = 0; i < leaf.numLeafFaces; i += 1) {\n faces.push(map.leafLists.leafFaces[leafIndex][i]);\n }\n return faces;\n}\n\nfunction traverse(\n map: BspMap,\n nodeIndex: number,\n camera: Vec3,\n frustum: readonly FrustumPlane[],\n viewCluster: number,\n visibleFaces: VisibleFace[],\n visitedFaces: Set<number>\n): void {\n if (childIsLeaf(nodeIndex)) {\n const leafIndex = childLeafIndex(nodeIndex);\n const leaf = map.leafs[leafIndex];\n if (!isClusterVisible(map.visibility, viewCluster, leaf.cluster)) {\n return;\n }\n if (!leafIntersectsFrustum(leaf, frustum)) {\n return;\n }\n const center = {\n x: (leaf.mins[0] + leaf.maxs[0]) * 0.5,\n y: (leaf.mins[1] + leaf.maxs[1]) * 0.5,\n z: (leaf.mins[2] + leaf.maxs[2]) * 0.5,\n };\n const dx = center.x - camera.x;\n const dy = center.y - camera.y;\n const dz = center.z - camera.z;\n const leafSortKey = -(dx * dx + dy * dy + dz * dz);\n for (const faceIndex of collectFacesFromLeaf(map, leafIndex)) {\n if (visitedFaces.has(faceIndex)) {\n continue;\n }\n visitedFaces.add(faceIndex);\n visibleFaces.push({ faceIndex, leafIndex, sortKey: leafSortKey });\n }\n return;\n }\n\n const node = map.nodes[nodeIndex];\n const plane = map.planes[node.planeIndex];\n const dist = distanceToPlane(plane, camera);\n const nearChild = dist >= 0 ? node.children[0] : node.children[1];\n const farChild = dist >= 0 ? node.children[1] : node.children[0];\n\n if (boxIntersectsFrustum(\n { x: node.mins[0], y: node.mins[1], z: node.mins[2] },\n { x: node.maxs[0], y: node.maxs[1], z: node.maxs[2] },\n frustum,\n )) {\n traverse(map, nearChild, camera, frustum, viewCluster, visibleFaces, visitedFaces);\n traverse(map, farChild, camera, frustum, viewCluster, visibleFaces, visitedFaces);\n }\n}\n\nexport function gatherVisibleFaces(\n map: BspMap,\n cameraPosition: Vec3,\n frustum: readonly FrustumPlane[],\n): VisibleFace[] {\n const viewLeaf = findLeafForPoint(map, cameraPosition);\n const viewCluster = viewLeaf >= 0 ? map.leafs[viewLeaf].cluster : -1;\n const visibleFaces: VisibleFace[] = [];\n const visitedFaces = new Set<number>();\n traverse(map, 0, cameraPosition, frustum, viewCluster, visibleFaces, visitedFaces);\n return visibleFaces;\n}\n","import {\n SURF_FLOWING,\n SURF_NONE,\n SURF_SKY,\n SURF_TRANS33,\n SURF_TRANS66,\n SURF_WARP,\n type SurfaceFlag,\n} from '@quake2ts/shared';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface SurfaceRenderState {\n readonly alpha: number;\n readonly blend: boolean;\n readonly depthWrite: boolean;\n readonly warp: boolean;\n readonly flowOffset: readonly [number, number];\n readonly sky: boolean;\n}\n\nexport interface BspSurfaceBindOptions {\n readonly modelViewProjection: Float32List;\n readonly styleIndices?: readonly number[];\n readonly styleValues?: ReadonlyArray<number>;\n readonly diffuseSampler?: number;\n readonly lightmapSampler?: number;\n readonly surfaceFlags?: SurfaceFlag;\n readonly timeSeconds?: number;\n}\n\nexport const BSP_SURFACE_VERTEX_SOURCE = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_texCoord;\nlayout(location = 2) in vec2 a_lightmapCoord;\n\nuniform mat4 u_modelViewProjection;\nuniform vec2 u_texScroll;\nuniform vec2 u_lightmapScroll;\n\nout vec2 v_texCoord;\nout vec2 v_lightmapCoord;\n\nvec2 applyScroll(vec2 uv, vec2 scroll) {\n return uv + scroll;\n}\n\nvoid main() {\n v_texCoord = applyScroll(a_texCoord, u_texScroll);\n v_lightmapCoord = applyScroll(a_lightmapCoord, u_lightmapScroll);\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const BSP_SURFACE_FRAGMENT_SOURCE = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin vec2 v_lightmapCoord;\n\nuniform sampler2D u_diffuseMap;\nuniform sampler2D u_lightmapAtlas;\nuniform vec4 u_lightStyleFactors;\nuniform float u_alpha;\nuniform bool u_applyLightmap;\nuniform bool u_warp;\nuniform float u_time;\n\nout vec4 o_color;\n\nvec2 warpCoords(vec2 uv) {\n // Quake II warp applies a subtle sinusoidal offset; we mirror the rerelease scale.\n if (!u_warp) {\n return uv;\n }\n float s = uv.x + sin(uv.y * 0.125 + u_time) * 0.125;\n float t = uv.y + sin(uv.x * 0.125 + u_time) * 0.125;\n return vec2(s, t);\n}\n\nvoid main() {\n vec2 warpedTex = warpCoords(v_texCoord);\n vec4 base = texture(u_diffuseMap, warpedTex);\n\n if (u_applyLightmap) {\n vec3 light = texture(u_lightmapAtlas, warpCoords(v_lightmapCoord)).rgb;\n float styleScale = dot(u_lightStyleFactors, vec4(1.0));\n base.rgb *= light * styleScale;\n }\n\n o_color = vec4(base.rgb, base.a * u_alpha);\n}`;\n\nconst DEFAULT_STYLE_INDICES: readonly number[] = [0, 255, 255, 255];\n\nexport function resolveLightStyles(\n styleIndices: readonly number[] = DEFAULT_STYLE_INDICES,\n styleValues: ReadonlyArray<number> = []\n): Float32Array {\n const factors = new Float32Array(4);\n for (let i = 0; i < 4; i += 1) {\n const styleIndex = styleIndices[i] ?? 255;\n if (styleIndex === 255) {\n factors[i] = 0;\n continue;\n }\n const value = styleValues[styleIndex];\n factors[i] = value !== undefined ? value : 1;\n }\n return factors;\n}\n\nfunction computeFlowOffset(timeSeconds: number): readonly [number, number] {\n const cycle = (timeSeconds * 0.25) % 1;\n // Match Quake II's negative scroll direction for flowing water/conveyors.\n return [-cycle, 0];\n}\n\nexport function deriveSurfaceRenderState(\n surfaceFlags: SurfaceFlag = SURF_NONE,\n timeSeconds = 0\n): SurfaceRenderState {\n const flowing = (surfaceFlags & SURF_FLOWING) !== 0;\n const warp = (surfaceFlags & SURF_WARP) !== 0;\n const sky = (surfaceFlags & SURF_SKY) !== 0;\n const trans33 = (surfaceFlags & SURF_TRANS33) !== 0;\n const trans66 = (surfaceFlags & SURF_TRANS66) !== 0;\n\n const alpha = trans33 ? 0.33 : trans66 ? 0.66 : 1;\n const blend = trans33 || trans66;\n const depthWrite = !blend && !sky;\n const flowOffset: readonly [number, number] = flowing ? computeFlowOffset(timeSeconds) : [0, 0];\n\n return {\n alpha,\n blend,\n depthWrite,\n warp,\n flowOffset,\n sky,\n };\n}\n\nexport class BspSurfacePipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformTexScroll: WebGLUniformLocation | null;\n private readonly uniformLmScroll: WebGLUniformLocation | null;\n private readonly uniformLightStyles: WebGLUniformLocation | null;\n private readonly uniformAlpha: WebGLUniformLocation | null;\n private readonly uniformApplyLightmap: WebGLUniformLocation | null;\n private readonly uniformWarp: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n private readonly uniformLightmap: WebGLUniformLocation | null;\n private readonly uniformTime: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: BSP_SURFACE_VERTEX_SOURCE, fragment: BSP_SURFACE_FRAGMENT_SOURCE },\n { a_position: 0, a_texCoord: 1, a_lightmapCoord: 2 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformTexScroll = this.program.getUniformLocation('u_texScroll');\n this.uniformLmScroll = this.program.getUniformLocation('u_lightmapScroll');\n this.uniformLightStyles = this.program.getUniformLocation('u_lightStyleFactors');\n this.uniformAlpha = this.program.getUniformLocation('u_alpha');\n this.uniformApplyLightmap = this.program.getUniformLocation('u_applyLightmap');\n this.uniformWarp = this.program.getUniformLocation('u_warp');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n this.uniformLightmap = this.program.getUniformLocation('u_lightmapAtlas');\n this.uniformTime = this.program.getUniformLocation('u_time');\n }\n\n bind(options: BspSurfaceBindOptions): SurfaceRenderState {\n const {\n modelViewProjection,\n styleIndices = DEFAULT_STYLE_INDICES,\n styleValues = [],\n diffuseSampler = 0,\n lightmapSampler,\n surfaceFlags = SURF_NONE,\n timeSeconds = 0,\n } = options;\n\n const state = deriveSurfaceRenderState(surfaceFlags, timeSeconds);\n const styles = resolveLightStyles(styleIndices, styleValues);\n\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform2f(this.uniformTexScroll, state.flowOffset[0], state.flowOffset[1]);\n this.gl.uniform2f(this.uniformLmScroll, state.flowOffset[0], state.flowOffset[1]);\n this.gl.uniform4fv(this.uniformLightStyles, styles);\n this.gl.uniform1f(this.uniformAlpha, state.alpha);\n const applyLightmap = !state.sky && lightmapSampler !== undefined;\n this.gl.uniform1i(this.uniformApplyLightmap, applyLightmap ? 1 : 0);\n this.gl.uniform1i(this.uniformWarp, state.warp ? 1 : 0);\n this.gl.uniform1f(this.uniformTime, timeSeconds);\n this.gl.uniform1i(this.uniformDiffuse, diffuseSampler);\n this.gl.uniform1i(this.uniformLightmap, lightmapSampler ?? 0);\n\n return state;\n }\n\n dispose(): void {\n this.program.dispose();\n }\n}\n\nexport function applySurfaceState(gl: WebGL2RenderingContext, state: SurfaceRenderState): void {\n gl.depthMask(state.depthWrite);\n if (state.blend) {\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);\n } else {\n gl.disable(gl.BLEND);\n }\n}\n","import { ShaderProgram } from './shaderProgram.js';\nimport { TextureCubeMap, VertexArray, VertexBuffer, type VertexAttributeLayout } from './resources.js';\nimport type { ReadonlyMat4 } from 'gl-matrix';\n\nconst SKYBOX_POSITIONS = new Float32Array([\n // Front\n -1, -1, 1,\n 1, -1, 1,\n 1, 1, 1,\n -1, -1, 1,\n 1, 1, 1,\n -1, 1, 1,\n // Back\n -1, -1, -1,\n -1, 1, -1,\n 1, 1, -1,\n -1, -1, -1,\n 1, 1, -1,\n 1, -1, -1,\n // Left\n -1, -1, -1,\n -1, -1, 1,\n -1, 1, 1,\n -1, -1, -1,\n -1, 1, 1,\n -1, 1, -1,\n // Right\n 1, -1, -1,\n 1, 1, -1,\n 1, 1, 1,\n 1, -1, -1,\n 1, 1, 1,\n 1, -1, 1,\n // Top\n -1, 1, -1,\n -1, 1, 1,\n 1, 1, 1,\n -1, 1, -1,\n 1, 1, 1,\n 1, 1, -1,\n // Bottom\n -1, -1, -1,\n 1, -1, -1,\n 1, -1, 1,\n -1, -1, -1,\n 1, -1, 1,\n -1, -1, 1,\n]);\n\nexport const SKYBOX_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\n\nuniform mat4 u_viewProjectionNoTranslation;\nuniform vec2 u_scroll;\n\nout vec3 v_direction;\n\nvoid main() {\n vec3 dir = normalize(a_position);\n dir.xy += u_scroll;\n v_direction = dir;\n gl_Position = u_viewProjectionNoTranslation * vec4(a_position, 1.0);\n}`;\n\nexport const SKYBOX_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec3 v_direction;\nuniform samplerCube u_skybox;\n\nout vec4 o_color;\n\nvoid main() {\n o_color = texture(u_skybox, v_direction);\n}`;\n\nexport interface SkyboxBindOptions {\n readonly viewProjection: Float32List;\n readonly scroll: readonly [number, number];\n readonly textureUnit?: number;\n}\n\nexport class SkyboxPipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n readonly vao: VertexArray;\n readonly vbo: VertexBuffer;\n readonly cubemap: TextureCubeMap;\n\n private readonly uniformViewProj: WebGLUniformLocation | null;\n private readonly uniformScroll: WebGLUniformLocation | null;\n private readonly uniformSampler: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: SKYBOX_VERTEX_SHADER, fragment: SKYBOX_FRAGMENT_SHADER },\n { a_position: 0 }\n );\n\n this.vao = new VertexArray(gl);\n this.vbo = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.vbo.upload(SKYBOX_POSITIONS, gl.STATIC_DRAW);\n\n const layout: VertexAttributeLayout[] = [{ index: 0, size: 3, type: gl.FLOAT, stride: 12, offset: 0 }];\n this.vao.configureAttributes(layout, this.vbo);\n\n this.uniformViewProj = this.program.getUniformLocation('u_viewProjectionNoTranslation');\n this.uniformScroll = this.program.getUniformLocation('u_scroll');\n this.uniformSampler = this.program.getUniformLocation('u_skybox');\n\n this.cubemap = new TextureCubeMap(gl);\n this.cubemap.setParameters({\n minFilter: gl.LINEAR,\n magFilter: gl.LINEAR,\n wrapS: gl.CLAMP_TO_EDGE,\n wrapT: gl.CLAMP_TO_EDGE,\n });\n }\n\n bind(options: SkyboxBindOptions): void {\n const { viewProjection, scroll, textureUnit = 0 } = options;\n this.program.use();\n this.gl.depthMask(false);\n this.gl.uniformMatrix4fv(this.uniformViewProj, false, viewProjection);\n this.gl.uniform2f(this.uniformScroll, scroll[0], scroll[1]);\n this.gl.uniform1i(this.uniformSampler, textureUnit);\n this.cubemap.bind(textureUnit);\n this.vao.bind();\n }\n\n draw(): void {\n this.gl.drawArrays(this.gl.TRIANGLES, 0, SKYBOX_POSITIONS.length / 3);\n }\n\n dispose(): void {\n this.vbo.dispose();\n this.vao.dispose();\n this.cubemap.dispose();\n this.program.dispose();\n }\n}\n\nexport function removeViewTranslation(viewMatrix: ReadonlyMat4 | Float32Array): Float32Array {\n const noTranslation = new Float32Array(viewMatrix);\n noTranslation[12] = 0;\n noTranslation[13] = 0;\n noTranslation[14] = 0;\n return noTranslation;\n}\n\nexport function computeSkyScroll(timeSeconds: number, scrollSpeeds: readonly [number, number] = [0.01, 0.02]): [number, number] {\n const [sx, sy] = scrollSpeeds;\n return [sx * timeSeconds, sy * timeSeconds];\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { Md2Model } from '../assets/md2.js';\nimport { IndexBuffer, VertexArray, VertexBuffer } from './resources.js';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface Md2DrawVertex {\n readonly vertexIndex: number;\n readonly texCoord: readonly [number, number];\n}\n\nexport interface Md2Geometry {\n readonly vertices: readonly Md2DrawVertex[];\n readonly indices: Uint16Array;\n}\n\nexport interface Md2FrameBlend {\n readonly currentFrame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface Md2BindOptions {\n readonly modelViewProjection: Float32List;\n readonly lightDirection?: readonly [number, number, number];\n readonly ambientLight?: number;\n readonly tint?: readonly [number, number, number, number];\n readonly diffuseSampler?: number;\n}\n\nexport const MD2_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_modelViewProjection;\nuniform vec3 u_lightDir;\nuniform float u_ambient;\n\nout vec2 v_texCoord;\nout float v_light;\n\nvoid main() {\n vec3 normal = normalize(a_normal);\n float dot = max(dot(normal, normalize(u_lightDir)), 0.0);\n v_light = min(1.0, u_ambient + dot);\n v_texCoord = a_texCoord;\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const MD2_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin float v_light;\n\nuniform sampler2D u_diffuseMap;\nuniform vec4 u_tint;\n\nout vec4 o_color;\n\nvoid main() {\n vec4 albedo = texture(u_diffuseMap, v_texCoord) * u_tint;\n o_color = vec4(albedo.rgb * v_light, albedo.a);\n}`;\n\nfunction normalizeVec3(v: Vec3): Vec3 {\n const lengthSq = v.x * v.x + v.y * v.y + v.z * v.z;\n if (lengthSq <= 0) {\n return { x: 0, y: 0, z: 1 };\n }\n const inv = 1 / Math.sqrt(lengthSq);\n return { x: v.x * inv, y: v.y * inv, z: v.z * inv };\n}\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\nfunction lerpVec3(a: Vec3, b: Vec3, t: number): Vec3 {\n return {\n x: lerp(a.x, b.x, t),\n y: lerp(a.y, b.y, t),\n z: lerp(a.z, b.z, t),\n };\n}\n\nfunction normalizeUv(s: number, t: number, header: Md2Model['header']): readonly [number, number] {\n return [s / header.skinWidth, 1 - t / header.skinHeight];\n}\n\nexport function buildMd2Geometry(model: Md2Model): Md2Geometry {\n if (model.glCommands.length === 0) {\n const vertices: Md2DrawVertex[] = [];\n const indices: number[] = [];\n model.triangles.forEach((triangle) => {\n const baseIndex = vertices.length;\n for (let i = 0; i < 3; i += 1) {\n const vertexIndex = triangle.vertexIndices[i];\n const texCoordIndex = triangle.texCoordIndices[i];\n const texCoord = model.texCoords[texCoordIndex];\n vertices.push({\n vertexIndex,\n texCoord: normalizeUv(texCoord.s, texCoord.t, model.header),\n });\n }\n indices.push(baseIndex, baseIndex + 1, baseIndex + 2);\n });\n\n return { vertices, indices: new Uint16Array(indices) };\n }\n\n const vertices: Md2DrawVertex[] = [];\n const indices: number[] = [];\n\n for (const command of model.glCommands) {\n const start = vertices.length;\n vertices.push(\n ...command.vertices.map((vertex) => ({\n vertexIndex: vertex.vertexIndex,\n texCoord: [vertex.s, 1 - vertex.t] as const,\n }))\n );\n\n if (command.mode === 'strip') {\n for (let i = 0; i < command.vertices.length - 2; i += 1) {\n const even = i % 2 === 0;\n const a = start + i + (even ? 0 : 1);\n const b = start + i + (even ? 1 : 0);\n const c = start + i + 2;\n indices.push(a, b, c);\n }\n } else {\n for (let i = 1; i < command.vertices.length - 1; i += 1) {\n indices.push(start, start + i, start + i + 1);\n }\n }\n }\n\n return { vertices, indices: new Uint16Array(indices) };\n}\n\nexport function buildMd2VertexData(\n model: Md2Model,\n geometry: Md2Geometry,\n blend: Md2FrameBlend\n): Float32Array {\n const { currentFrame, nextFrame, lerp } = blend;\n const frameA = model.frames[currentFrame];\n const frameB = model.frames[nextFrame];\n\n if (!frameA || !frameB) {\n throw new Error('Requested MD2 frames are out of range');\n }\n\n const data = new Float32Array(geometry.vertices.length * 8);\n geometry.vertices.forEach((vertex, index) => {\n const vA = frameA.vertices[vertex.vertexIndex];\n const vB = frameB.vertices[vertex.vertexIndex];\n if (!vA || !vB) {\n throw new Error('MD2 vertex index out of range for frame');\n }\n\n const position = lerpVec3(vA.position, vB.position, lerp);\n const normal = normalizeVec3(lerpVec3(vA.normal, vB.normal, lerp));\n\n const base = index * 8;\n data[base] = position.x;\n data[base + 1] = position.y;\n data[base + 2] = position.z;\n data[base + 3] = normal.x;\n data[base + 4] = normal.y;\n data[base + 5] = normal.z;\n data[base + 6] = vertex.texCoord[0];\n data[base + 7] = vertex.texCoord[1];\n });\n\n return data;\n}\n\nexport class Md2MeshBuffers {\n readonly gl: WebGL2RenderingContext;\n readonly geometry: Md2Geometry;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly vertexArray: VertexArray;\n readonly indexCount: number;\n\n constructor(gl: WebGL2RenderingContext, model: Md2Model, blend: Md2FrameBlend) {\n this.gl = gl;\n this.geometry = buildMd2Geometry(model);\n this.vertexBuffer = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.indexBuffer = new IndexBuffer(gl, gl.STATIC_DRAW);\n this.vertexArray = new VertexArray(gl);\n this.indexCount = this.geometry.indices.length;\n\n this.vertexArray.configureAttributes(\n [\n { index: 0, size: 3, type: gl.FLOAT, stride: 32, offset: 0 },\n { index: 1, size: 3, type: gl.FLOAT, stride: 32, offset: 12 },\n { index: 2, size: 2, type: gl.FLOAT, stride: 32, offset: 24 },\n ],\n this.vertexBuffer\n );\n\n this.vertexArray.bind();\n this.indexBuffer.bind();\n this.indexBuffer.upload(this.geometry.indices as unknown as BufferSource, gl.STATIC_DRAW);\n this.update(model, blend);\n }\n\n update(model: Md2Model, blend: Md2FrameBlend): void {\n const data = buildMd2VertexData(model, this.geometry, blend);\n this.vertexBuffer.upload(data as unknown as BufferSource, this.gl.STATIC_DRAW);\n }\n\n bind(): void {\n this.vertexArray.bind();\n this.indexBuffer.bind();\n }\n\n dispose(): void {\n this.vertexBuffer.dispose();\n this.indexBuffer.dispose();\n this.vertexArray.dispose();\n }\n}\n\nexport class Md2Pipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformLightDir: WebGLUniformLocation | null;\n private readonly uniformAmbient: WebGLUniformLocation | null;\n private readonly uniformTint: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: MD2_VERTEX_SHADER, fragment: MD2_FRAGMENT_SHADER },\n { a_position: 0, a_normal: 1, a_texCoord: 2 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformLightDir = this.program.getUniformLocation('u_lightDir');\n this.uniformAmbient = this.program.getUniformLocation('u_ambient');\n this.uniformTint = this.program.getUniformLocation('u_tint');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n }\n\n bind(options: Md2BindOptions): void {\n const { modelViewProjection, lightDirection = [0, 0, 1], ambientLight = 0.2, tint = [1, 1, 1, 1], diffuseSampler = 0 } = options;\n const lightVec = new Float32Array(lightDirection);\n const tintVec = new Float32Array(tint);\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform3fv(this.uniformLightDir, lightVec);\n this.gl.uniform1f(this.uniformAmbient, ambientLight);\n this.gl.uniform4fv(this.uniformTint, tintVec);\n this.gl.uniform1i(this.uniformDiffuse, diffuseSampler);\n }\n\n draw(mesh: Md2MeshBuffers): void {\n mesh.bind();\n this.gl.drawElements(this.gl.TRIANGLES, mesh.indexCount, this.gl.UNSIGNED_SHORT, 0);\n }\n\n dispose(): void {\n this.program.dispose();\n }\n}\n","import { mat4, vec3 } from 'gl-matrix';\nimport { DEG2RAD } from '@quake2ts/shared';\n\nexport class Camera {\n private _position: vec3 = vec3.create();\n private _angles: vec3 = vec3.create(); // pitch, yaw, roll\n private _bobAngles: vec3 = vec3.create();\n private _bobOffset: vec3 = vec3.create();\n private _kickAngles: vec3 = vec3.create();\n private _rollAngle = 0;\n private _fov = 90;\n private _aspect = 1.0;\n private _near = 0.1;\n private _far = 1000;\n\n private _viewMatrix: mat4 = mat4.create();\n private _projectionMatrix: mat4 = mat4.create();\n private _viewProjectionMatrix: mat4 = mat4.create();\n private _dirty = true;\n\n get position(): vec3 {\n return this._position;\n }\n\n set position(value: vec3) {\n vec3.copy(this._position, value);\n this._dirty = true;\n }\n\n get angles(): vec3 {\n return this._angles;\n }\n\n set angles(value: vec3) {\n vec3.copy(this._angles, value);\n this._dirty = true;\n }\n\n get bobAngles(): vec3 {\n return this._bobAngles;\n }\n\n set bobAngles(value: vec3) {\n vec3.copy(this._bobAngles, value);\n this._dirty = true;\n }\n\n get kickAngles(): vec3 {\n return this._kickAngles;\n }\n\n set kickAngles(value: vec3) {\n vec3.copy(this._kickAngles, value);\n this._dirty = true;\n }\n\n get bobOffset(): vec3 {\n return this._bobOffset;\n }\n\n set bobOffset(value: vec3) {\n vec3.copy(this._bobOffset, value);\n this._dirty = true;\n }\n\n get rollAngle(): number {\n return this._rollAngle;\n }\n\n set rollAngle(value: number) {\n this._rollAngle = value;\n this._dirty = true;\n }\n\n get fov(): number {\n return this._fov;\n }\n\n set fov(value: number) {\n this._fov = value;\n this._dirty = true;\n }\n\n get aspect(): number {\n return this._aspect;\n }\n\n set aspect(value: number) {\n this._aspect = value;\n this._dirty = true;\n }\n\n get viewMatrix(): mat4 {\n this.updateMatrices();\n return this._viewMatrix;\n }\n\n get projectionMatrix(): mat4 {\n this.updateMatrices();\n return this._projectionMatrix;\n }\n\n get viewProjectionMatrix(): mat4 {\n this.updateMatrices();\n return this._viewProjectionMatrix;\n }\n\n getViewmodelProjectionMatrix(fov: number): mat4 {\n const projectionMatrix = mat4.create();\n mat4.perspective(\n projectionMatrix,\n fov * DEG2RAD,\n this._aspect,\n this._near,\n this._far\n );\n return projectionMatrix;\n }\n\n private updateMatrices(): void {\n if (!this._dirty) {\n return;\n }\n\n // 1. Update projection matrix\n mat4.perspective(\n this._projectionMatrix,\n this._fov * DEG2RAD,\n this._aspect,\n this._near,\n this._far\n );\n\n // 2. Create the coordinate system transformation matrix.\n // This matrix transforms vectors from Quake's coordinate system\n // (X forward, Y left, Z up) to WebGL's coordinate system (X right, Y up, Z back).\n //\n // Mapping (column vectors based on test expectations):\n // - Quake X (forward) -> WebGL -Y\n // - Quake Y (left) -> WebGL +Z\n // - Quake Z (up) -> WebGL -X\n const quakeToGl = mat4.fromValues(\n 0, -1, 0, 0, // column 0: Quake X -> WebGL (0, -1, 0)\n 0, 0, 1, 0, // column 1: Quake Y -> WebGL (0, 0, 1)\n -1, 0, 0, 0, // column 2: Quake Z -> WebGL (-1, 0, 0)\n 0, 0, 0, 1 // column 3: no translation\n );\n\n // 3. Construct the Quake rotation matrix\n const pitch = this._angles[0] + this._bobAngles[0] + this._kickAngles[0];\n const yaw = this._angles[1] + this._bobAngles[1] + this._kickAngles[1];\n const roll = this._angles[2] + this._bobAngles[2] + this._kickAngles[2] + this._rollAngle;\n\n const pitchRad = pitch * DEG2RAD;\n const yawRad = yaw * DEG2RAD;\n const rollRad = roll * DEG2RAD;\n\n const rotationQuake = mat4.create();\n mat4.identity(rotationQuake);\n\n // Rotations are applied in reverse order to the world\n // Quake's axes for rotation are: Z(yaw), Y(pitch), X(roll)\n mat4.rotateZ(rotationQuake, rotationQuake, -yawRad);\n mat4.rotateY(rotationQuake, rotationQuake, -pitchRad);\n mat4.rotateX(rotationQuake, rotationQuake, -rollRad);\n\n // 4. Combine Quake rotation with coordinate transformation\n const rotationGl = mat4.create();\n mat4.multiply(rotationGl, quakeToGl, rotationQuake);\n\n // 5. Calculate the view matrix translation\n // Apply rotation in Quake space first, then transform to GL coordinates\n const positionWithOffset = vec3.add(vec3.create(), this._position, this._bobOffset);\n const negativePosition = vec3.negate(vec3.create(), positionWithOffset);\n const rotatedPosQuake = vec3.create();\n vec3.transformMat4(rotatedPosQuake, negativePosition, rotationQuake);\n\n // Transform the rotated position from Quake coordinates to WebGL coordinates\n // using the simple coordinate swizzle (not matrix multiplication)\n const translationGl = vec3.fromValues(\n rotatedPosQuake[1] || 0, // Y in Quake -> X in WebGL (negation already applied above)\n rotatedPosQuake[2] || 0, // Z in Quake -> Y in WebGL\n rotatedPosQuake[0] || 0 // X in Quake -> Z in WebGL (negation already applied above)\n );\n\n // 6. Build the final view matrix by combining rotation and translation\n mat4.copy(this._viewMatrix, rotationGl);\n this._viewMatrix[12] = translationGl[0];\n this._viewMatrix[13] = translationGl[1];\n this._viewMatrix[14] = translationGl[2];\n\n // 7. Update the combined view-projection matrix\n mat4.multiply(\n this._viewProjectionMatrix,\n this._projectionMatrix,\n this._viewMatrix\n );\n\n this._dirty = false;\n }\n}\n","import { Mat4, Vec3, mat4FromBasis, normalizeVec3, transformPointMat4 } from '@quake2ts/shared';\nimport { Md3Model, Md3Surface } from '../assets/md3.js';\nimport { IndexBuffer, VertexArray, VertexBuffer } from './resources.js';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface Md3DrawVertex {\n readonly vertexIndex: number;\n readonly texCoord: readonly [number, number];\n}\n\nexport interface Md3SurfaceGeometry {\n readonly vertices: readonly Md3DrawVertex[];\n readonly indices: Uint16Array;\n}\n\nexport interface Md3FrameBlend {\n readonly currentFrame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface Md3DynamicLight {\n readonly origin: Vec3;\n readonly color: readonly [number, number, number];\n readonly radius: number;\n}\n\nexport interface Md3LightingOptions {\n readonly ambient?: readonly [number, number, number];\n readonly directional?: { direction: Vec3; color: readonly [number, number, number] };\n readonly dynamicLights?: readonly Md3DynamicLight[];\n readonly modelMatrix?: Mat4;\n}\n\nexport interface Md3SurfaceMaterial {\n readonly diffuseSampler?: number;\n readonly tint?: readonly [number, number, number, number];\n}\n\nexport interface Md3TagTransform {\n readonly origin: Vec3;\n readonly axis: readonly [Vec3, Vec3, Vec3];\n readonly matrix: Mat4;\n}\n\nconst DEFAULT_AMBIENT: readonly [number, number, number] = [0.2, 0.2, 0.2];\nconst DEFAULT_DIRECTION: Vec3 = { x: 0, y: 0, z: 1 };\nconst DEFAULT_DIRECTION_COLOR: readonly [number, number, number] = [0.8, 0.8, 0.8];\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\nfunction lerpVec3(a: Vec3, b: Vec3, t: number): Vec3 {\n return { x: lerp(a.x, b.x, t), y: lerp(a.y, b.y, t), z: lerp(a.z, b.z, t) };\n}\n\nfunction clamp01(v: number): number {\n if (v < 0) return 0;\n if (v > 1) return 1;\n return v;\n}\n\nexport function buildMd3SurfaceGeometry(surface: Md3Surface): Md3SurfaceGeometry {\n const vertices: Md3DrawVertex[] = [];\n const indices: number[] = [];\n\n for (const tri of surface.triangles) {\n const base = vertices.length;\n const [a, b, c] = tri.indices;\n const texA = surface.texCoords[a];\n const texB = surface.texCoords[b];\n const texC = surface.texCoords[c];\n\n if (!texA || !texB || !texC) {\n throw new Error(`Missing texCoord for triangle in surface ${surface.name}`);\n }\n\n vertices.push(\n { vertexIndex: a, texCoord: [texA.s, 1 - texA.t] },\n { vertexIndex: b, texCoord: [texB.s, 1 - texB.t] },\n { vertexIndex: c, texCoord: [texC.s, 1 - texC.t] }\n );\n\n indices.push(base, base + 1, base + 2);\n }\n\n return { vertices, indices: new Uint16Array(indices) };\n}\n\nfunction evaluateLighting(normal: Vec3, position: Vec3, lighting?: Md3LightingOptions): readonly [number, number, number] {\n const ambient = lighting?.ambient ?? DEFAULT_AMBIENT;\n const directional = lighting?.directional ?? { direction: DEFAULT_DIRECTION, color: DEFAULT_DIRECTION_COLOR };\n\n const n = normalizeVec3(normal);\n const l = normalizeVec3(directional.direction);\n const ndotl = clamp01(n.x * l.x + n.y * l.y + n.z * l.z);\n\n let r = ambient[0] + directional.color[0] * ndotl;\n let g = ambient[1] + directional.color[1] * ndotl;\n let b = ambient[2] + directional.color[2] * ndotl;\n\n if (lighting?.dynamicLights) {\n const worldPos = lighting.modelMatrix ? transformPointMat4(lighting.modelMatrix, position) : position;\n for (const light of lighting.dynamicLights) {\n const dx = worldPos.x - light.origin.x;\n const dy = worldPos.y - light.origin.y;\n const dz = worldPos.z - light.origin.z;\n const distSq = dx * dx + dy * dy + dz * dz;\n const radiusSq = light.radius * light.radius;\n if (distSq < radiusSq && radiusSq > 0) {\n const attenuation = 1 - Math.sqrt(distSq) / light.radius;\n // Compute dot product with direction to this specific dynamic light\n const dist = Math.sqrt(distSq);\n const lightDotN = dist > 0 ? clamp01(-(dx * n.x + dy * n.y + dz * n.z) / dist) : 0;\n const amount = clamp01(attenuation * lightDotN);\n r += light.color[0] * amount;\n g += light.color[1] * amount;\n b += light.color[2] * amount;\n }\n }\n }\n\n return [clamp01(r), clamp01(g), clamp01(b)];\n}\n\nexport function buildMd3VertexData(\n surface: Md3Surface,\n geometry: Md3SurfaceGeometry,\n blend: Md3FrameBlend,\n lighting?: Md3LightingOptions\n): Float32Array {\n const frameA = surface.vertices[blend.currentFrame];\n const frameB = surface.vertices[blend.nextFrame];\n\n if (!frameA || !frameB) {\n throw new Error('Requested MD3 frames are out of range');\n }\n\n const data = new Float32Array(geometry.vertices.length * 12);\n geometry.vertices.forEach((vertex, index) => {\n const vA = frameA[vertex.vertexIndex];\n const vB = frameB[vertex.vertexIndex];\n\n if (!vA || !vB) {\n throw new Error(`Vertex index ${vertex.vertexIndex} missing for frame`);\n }\n\n const position = lerpVec3(vA.position, vB.position, blend.lerp);\n const normal = normalizeVec3(lerpVec3(vA.normal, vB.normal, blend.lerp));\n const color = evaluateLighting(normal, position, lighting);\n\n const base = index * 12;\n data[base] = position.x;\n data[base + 1] = position.y;\n data[base + 2] = position.z;\n data[base + 3] = normal.x;\n data[base + 4] = normal.y;\n data[base + 5] = normal.z;\n data[base + 6] = vertex.texCoord[0];\n data[base + 7] = vertex.texCoord[1];\n data[base + 8] = color[0];\n data[base + 9] = color[1];\n data[base + 10] = color[2];\n data[base + 11] = 1;\n });\n\n return data;\n}\n\nexport function interpolateMd3Tag(model: Md3Model, blend: Md3FrameBlend, tagName: string): Md3TagTransform | null {\n const firstFrameTags = model.tags[0];\n if (!firstFrameTags) {\n return null;\n }\n\n const tagIndex = firstFrameTags.findIndex((tag) => tag.name === tagName);\n if (tagIndex === -1) {\n return null;\n }\n\n const tagA = model.tags[blend.currentFrame]?.[tagIndex];\n const tagB = model.tags[blend.nextFrame]?.[tagIndex];\n if (!tagA || !tagB) {\n throw new Error(`Tag ${tagName} is missing for one of the interpolated frames`);\n }\n\n const origin = lerpVec3(tagA.origin, tagB.origin, blend.lerp);\n const axis0 = normalizeVec3(lerpVec3(tagA.axis[0], tagB.axis[0], blend.lerp));\n const axis1 = normalizeVec3(lerpVec3(tagA.axis[1], tagB.axis[1], blend.lerp));\n const axis2 = normalizeVec3(lerpVec3(tagA.axis[2], tagB.axis[2], blend.lerp));\n\n // Re-orthogonalize to match rerelease attachment stability expectations\n const corrected0 = axis0;\n const corrected1 = normalizeVec3({\n x: axis1.x - corrected0.x * (corrected0.x * axis1.x + corrected0.y * axis1.y + corrected0.z * axis1.z),\n y: axis1.y - corrected0.y * (corrected0.x * axis1.x + corrected0.y * axis1.y + corrected0.z * axis1.z),\n z: axis1.z - corrected0.z * (corrected0.x * axis1.x + corrected0.y * axis1.y + corrected0.z * axis1.z),\n });\n const corrected2 = normalizeVec3({\n x: corrected0.y * corrected1.z - corrected0.z * corrected1.y,\n y: corrected0.z * corrected1.x - corrected0.x * corrected1.z,\n z: corrected0.x * corrected1.y - corrected0.y * corrected1.x,\n });\n\n const axis: readonly [Vec3, Vec3, Vec3] = [corrected0, corrected1, corrected2];\n return { origin, axis, matrix: mat4FromBasis(origin, axis) };\n}\n\nexport const MD3_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_color;\n\nuniform mat4 u_modelViewProjection;\n\nout vec2 v_texCoord;\nout vec4 v_color;\n\nvoid main() {\n v_texCoord = a_texCoord;\n v_color = a_color;\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const MD3_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin vec4 v_color;\n\nuniform sampler2D u_diffuseMap;\nuniform vec4 u_tint;\n\nout vec4 o_color;\n\nvoid main() {\n vec4 albedo = texture(u_diffuseMap, v_texCoord) * u_tint;\n o_color = vec4(albedo.rgb * v_color.rgb, albedo.a * v_color.a);\n}`;\n\nexport class Md3SurfaceMesh {\n readonly gl: WebGL2RenderingContext;\n readonly geometry: Md3SurfaceGeometry;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly vertexArray: VertexArray;\n readonly indexCount: number;\n\n constructor(gl: WebGL2RenderingContext, surface: Md3Surface, blend: Md3FrameBlend, lighting?: Md3LightingOptions) {\n this.gl = gl;\n this.geometry = buildMd3SurfaceGeometry(surface);\n this.vertexBuffer = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.indexBuffer = new IndexBuffer(gl, gl.STATIC_DRAW);\n this.vertexArray = new VertexArray(gl);\n this.indexCount = this.geometry.indices.length;\n\n this.vertexArray.configureAttributes(\n [\n { index: 0, size: 3, type: gl.FLOAT, stride: 48, offset: 0 },\n { index: 1, size: 3, type: gl.FLOAT, stride: 48, offset: 12 },\n { index: 2, size: 2, type: gl.FLOAT, stride: 48, offset: 24 },\n { index: 3, size: 4, type: gl.FLOAT, stride: 48, offset: 32 },\n ],\n this.vertexBuffer\n );\n\n this.vertexArray.bind();\n this.indexBuffer.bind();\n this.indexBuffer.upload(this.geometry.indices as unknown as BufferSource, gl.STATIC_DRAW);\n this.update(surface, blend, lighting);\n }\n\n update(surface: Md3Surface, blend: Md3FrameBlend, lighting?: Md3LightingOptions): void {\n const data = buildMd3VertexData(surface, this.geometry, blend, lighting);\n this.vertexBuffer.upload(data as unknown as BufferSource, this.gl.STATIC_DRAW);\n }\n\n bind(): void {\n this.vertexArray.bind();\n this.indexBuffer.bind();\n }\n\n dispose(): void {\n this.vertexBuffer.dispose();\n this.indexBuffer.dispose();\n this.vertexArray.dispose();\n }\n}\n\nexport class Md3ModelMesh {\n readonly surfaces = new Map<string, Md3SurfaceMesh>();\n readonly gl: WebGL2RenderingContext;\n readonly model: Md3Model;\n blend: Md3FrameBlend;\n lighting?: Md3LightingOptions;\n\n constructor(gl: WebGL2RenderingContext, model: Md3Model, blend: Md3FrameBlend, lighting?: Md3LightingOptions) {\n this.gl = gl;\n this.model = model;\n this.blend = blend;\n this.lighting = lighting;\n\n model.surfaces.forEach((surface) => {\n this.surfaces.set(surface.name, new Md3SurfaceMesh(gl, surface, blend, lighting));\n });\n }\n\n update(blend: Md3FrameBlend, lighting?: Md3LightingOptions): void {\n this.blend = blend;\n this.lighting = lighting ?? this.lighting;\n for (const surface of this.model.surfaces) {\n const mesh = this.surfaces.get(surface.name);\n mesh?.update(surface, blend, this.lighting);\n }\n }\n\n dispose(): void {\n for (const mesh of this.surfaces.values()) {\n mesh.dispose();\n }\n this.surfaces.clear();\n }\n}\n\nexport class Md3Pipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformTint: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: MD3_VERTEX_SHADER, fragment: MD3_FRAGMENT_SHADER },\n { a_position: 0, a_normal: 1, a_texCoord: 2, a_color: 3 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformTint = this.program.getUniformLocation('u_tint');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n }\n\n bind(modelViewProjection: Float32List, tint: readonly [number, number, number, number] = [1, 1, 1, 1], sampler = 0): void {\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform4fv(this.uniformTint, new Float32Array(tint));\n this.gl.uniform1i(this.uniformDiffuse, sampler);\n }\n\n drawSurface(mesh: Md3SurfaceMesh, material?: Md3SurfaceMaterial): void {\n const sampler = material?.diffuseSampler ?? 0;\n const tint = material?.tint ?? [1, 1, 1, 1];\n this.gl.uniform4fv(this.uniformTint, new Float32Array(tint));\n this.gl.uniform1i(this.uniformDiffuse, sampler);\n mesh.bind();\n this.gl.drawElements(this.gl.TRIANGLES, mesh.indexCount, this.gl.UNSIGNED_SHORT, 0);\n }\n\n dispose(): void {\n this.program.dispose();\n }\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { IndexBuffer, VertexArray, VertexBuffer } from './resources.js';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport type ParticleBlendMode = 'alpha' | 'additive';\n\nexport interface ParticleSpawnOptions {\n readonly position: Vec3;\n readonly velocity?: Vec3;\n readonly color?: readonly [number, number, number, number];\n readonly size?: number;\n readonly lifetime: number;\n readonly gravity?: number;\n readonly damping?: number;\n readonly bounce?: number;\n readonly blendMode?: ParticleBlendMode;\n /**\n * When true, fades alpha from 1 to 0 across the lifetime instead of remaining constant.\n */\n readonly fade?: boolean;\n}\n\nexport interface ParticleSimulationOptions {\n readonly floorZ?: number;\n}\n\ninterface ParticleMeshBatch {\n readonly blendMode: ParticleBlendMode;\n readonly start: number;\n readonly count: number;\n}\n\nexport interface ParticleMesh {\n readonly vertices: Float32Array;\n readonly indices: Uint16Array;\n readonly batches: readonly ParticleMeshBatch[];\n}\n\nconst DEFAULT_COLOR: [number, number, number, number] = [1, 1, 1, 1];\n\nexport class ParticleSystem {\n readonly maxParticles: number;\n readonly random: () => number;\n\n private readonly alive: Uint8Array;\n private readonly positionX: Float32Array;\n private readonly positionY: Float32Array;\n private readonly positionZ: Float32Array;\n private readonly velocityX: Float32Array;\n private readonly velocityY: Float32Array;\n private readonly velocityZ: Float32Array;\n private readonly colorR: Float32Array;\n private readonly colorG: Float32Array;\n private readonly colorB: Float32Array;\n private readonly colorA: Float32Array;\n private readonly size: Float32Array;\n private readonly lifetime: Float32Array;\n private readonly remaining: Float32Array;\n private readonly gravity: Float32Array;\n private readonly damping: Float32Array;\n private readonly bounce: Float32Array;\n private readonly fade: Uint8Array;\n private readonly blendMode: Uint8Array; // 0 alpha, 1 additive\n\n constructor(maxParticles: number, random: () => number = Math.random) {\n this.maxParticles = maxParticles;\n this.random = random;\n this.alive = new Uint8Array(maxParticles);\n this.positionX = new Float32Array(maxParticles);\n this.positionY = new Float32Array(maxParticles);\n this.positionZ = new Float32Array(maxParticles);\n this.velocityX = new Float32Array(maxParticles);\n this.velocityY = new Float32Array(maxParticles);\n this.velocityZ = new Float32Array(maxParticles);\n this.colorR = new Float32Array(maxParticles);\n this.colorG = new Float32Array(maxParticles);\n this.colorB = new Float32Array(maxParticles);\n this.colorA = new Float32Array(maxParticles);\n this.size = new Float32Array(maxParticles);\n this.lifetime = new Float32Array(maxParticles);\n this.remaining = new Float32Array(maxParticles);\n this.gravity = new Float32Array(maxParticles);\n this.damping = new Float32Array(maxParticles);\n this.bounce = new Float32Array(maxParticles);\n this.fade = new Uint8Array(maxParticles);\n this.blendMode = new Uint8Array(maxParticles);\n }\n\n spawn(options: ParticleSpawnOptions): number | null {\n const index = this.findFreeSlot();\n if (index === -1) {\n return null;\n }\n\n const color = options.color ?? DEFAULT_COLOR;\n const velocity = options.velocity ?? { x: 0, y: 0, z: 0 };\n\n this.alive[index] = 1;\n this.positionX[index] = options.position.x;\n this.positionY[index] = options.position.y;\n this.positionZ[index] = options.position.z;\n this.velocityX[index] = velocity.x;\n this.velocityY[index] = velocity.y;\n this.velocityZ[index] = velocity.z;\n this.colorR[index] = color[0];\n this.colorG[index] = color[1];\n this.colorB[index] = color[2];\n this.colorA[index] = color[3];\n this.size[index] = options.size ?? 2.5;\n this.lifetime[index] = options.lifetime;\n this.remaining[index] = options.lifetime;\n this.gravity[index] = options.gravity ?? 800;\n this.damping[index] = options.damping ?? 0;\n this.bounce[index] = options.bounce ?? 0.25;\n this.fade[index] = options.fade ? 1 : 0;\n this.blendMode[index] = options.blendMode === 'additive' ? 1 : 0;\n\n return index;\n }\n\n update(dt: number, options: ParticleSimulationOptions = {}): void {\n const floorZ = options.floorZ ?? -Infinity;\n for (let i = 0; i < this.maxParticles; i += 1) {\n if (!this.alive[i]) {\n continue;\n }\n\n this.remaining[i] -= dt;\n if (this.remaining[i] <= 0) {\n this.alive[i] = 0;\n continue;\n }\n\n const damping = Math.max(0, 1 - this.damping[i] * dt);\n this.velocityX[i] *= damping;\n this.velocityY[i] *= damping;\n this.velocityZ[i] = this.velocityZ[i] * damping - this.gravity[i] * dt;\n\n this.positionX[i] += this.velocityX[i] * dt;\n this.positionY[i] += this.velocityY[i] * dt;\n this.positionZ[i] += this.velocityZ[i] * dt;\n\n if (this.positionZ[i] < floorZ) {\n this.positionZ[i] = floorZ;\n this.velocityZ[i] = -this.velocityZ[i] * this.bounce[i];\n this.velocityX[i] *= 0.7;\n this.velocityY[i] *= 0.7;\n }\n }\n }\n\n killAll(): void {\n this.alive.fill(0);\n }\n\n aliveCount(): number {\n let count = 0;\n for (let i = 0; i < this.maxParticles; i += 1) {\n if (this.alive[i]) {\n count += 1;\n }\n }\n return count;\n }\n\n getState(index: number): {\n readonly alive: boolean;\n readonly position: Vec3;\n readonly velocity: Vec3;\n readonly remaining: number;\n readonly color: readonly [number, number, number, number];\n readonly size: number;\n readonly blendMode: ParticleBlendMode;\n } {\n return {\n alive: this.alive[index] === 1,\n position: {\n x: this.positionX[index],\n y: this.positionY[index],\n z: this.positionZ[index],\n },\n velocity: {\n x: this.velocityX[index],\n y: this.velocityY[index],\n z: this.velocityZ[index],\n },\n remaining: this.remaining[index],\n color: [this.colorR[index], this.colorG[index], this.colorB[index], this.colorA[index]],\n size: this.size[index],\n blendMode: this.blendMode[index] === 1 ? 'additive' : 'alpha',\n };\n }\n\n buildMesh(viewRight: Vec3, viewUp: Vec3): ParticleMesh {\n const vertices: number[] = [];\n const indices: number[] = [];\n const batches: ParticleMeshBatch[] = [];\n\n const buildBatch = (mode: ParticleBlendMode): void => {\n const startIndex = indices.length;\n let particleCount = 0;\n for (let i = 0; i < this.maxParticles; i += 1) {\n if (!this.alive[i]) {\n continue;\n }\n if ((mode === 'additive' ? 1 : 0) !== this.blendMode[i]) {\n continue;\n }\n\n particleCount += 1;\n const baseVertex = vertices.length / 9;\n const size = this.size[i] * 0.5;\n const fade = this.fade[i] ? Math.max(this.remaining[i] / this.lifetime[i], 0) : 1;\n const colorScale = this.blendMode[i] === 1 ? 1.2 : 1;\n\n const cR = this.colorR[i] * colorScale;\n const cG = this.colorG[i] * colorScale;\n const cB = this.colorB[i] * colorScale;\n const cA = this.colorA[i] * fade;\n\n const px = this.positionX[i];\n const py = this.positionY[i];\n const pz = this.positionZ[i];\n\n const rightX = viewRight.x * size;\n const rightY = viewRight.y * size;\n const rightZ = viewRight.z * size;\n const upX = viewUp.x * size;\n const upY = viewUp.y * size;\n const upZ = viewUp.z * size;\n\n const corners: readonly Vec3[] = [\n { x: px - rightX - upX, y: py - rightY - upY, z: pz - rightZ - upZ },\n { x: px + rightX - upX, y: py + rightY - upY, z: pz + rightZ - upZ },\n { x: px - rightX + upX, y: py - rightY + upY, z: pz - rightZ + upZ },\n { x: px + rightX + upX, y: py + rightY + upY, z: pz + rightZ + upZ },\n ];\n\n const uvs: readonly [number, number][] = [\n [0, 1],\n [1, 1],\n [0, 0],\n [1, 0],\n ];\n\n corners.forEach((corner, cornerIndex) => {\n vertices.push(\n corner.x,\n corner.y,\n corner.z,\n uvs[cornerIndex]?.[0] ?? 0,\n uvs[cornerIndex]?.[1] ?? 0,\n cR,\n cG,\n cB,\n cA\n );\n });\n\n indices.push(baseVertex, baseVertex + 1, baseVertex + 2, baseVertex + 2, baseVertex + 1, baseVertex + 3);\n }\n\n if (particleCount > 0) {\n batches.push({ blendMode: mode, start: startIndex, count: indices.length - startIndex });\n }\n };\n\n buildBatch('alpha');\n buildBatch('additive');\n\n return { vertices: new Float32Array(vertices), indices: new Uint16Array(indices), batches };\n }\n\n private findFreeSlot(): number {\n for (let i = 0; i < this.maxParticles; i += 1) {\n if (!this.alive[i]) {\n return i;\n }\n }\n return -1;\n }\n}\n\nexport const PARTICLE_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_uv;\nlayout(location = 2) in vec4 a_color;\n\nuniform mat4 u_viewProjection;\n\nout vec2 v_uv;\nout vec4 v_color;\n\nvoid main() {\n v_uv = a_uv;\n v_color = a_color;\n gl_Position = u_viewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const PARTICLE_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec2 v_uv;\nin vec4 v_color;\n\nout vec4 o_color;\n\nvoid main() {\n float dist = distance(v_uv, vec2(0.5));\n float alpha = v_color.a * (1.0 - smoothstep(0.35, 0.5, dist));\n o_color = vec4(v_color.rgb, alpha);\n}`;\n\nexport interface ParticleRenderOptions {\n readonly viewProjection: Float32List;\n readonly viewRight: Vec3;\n readonly viewUp: Vec3;\n}\n\nexport class ParticleRenderer {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n readonly system: ParticleSystem;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly vertexArray: VertexArray;\n\n private vertexCapacity = 0;\n private indexCapacity = 0;\n\n constructor(gl: WebGL2RenderingContext, system: ParticleSystem) {\n this.gl = gl;\n this.system = system;\n this.program = ShaderProgram.create(gl, { vertex: PARTICLE_VERTEX_SHADER, fragment: PARTICLE_FRAGMENT_SHADER });\n this.vertexBuffer = new VertexBuffer(gl, gl.DYNAMIC_DRAW);\n this.indexBuffer = new IndexBuffer(gl, gl.DYNAMIC_DRAW);\n this.vertexArray = new VertexArray(gl);\n this.vertexArray.configureAttributes(\n [\n { index: 0, size: 3, type: gl.FLOAT, stride: 36, offset: 0 },\n { index: 1, size: 2, type: gl.FLOAT, stride: 36, offset: 12 },\n { index: 2, size: 4, type: gl.FLOAT, stride: 36, offset: 20 },\n ],\n this.vertexBuffer\n );\n }\n\n render(options: ParticleRenderOptions): void {\n const mesh = this.system.buildMesh(options.viewRight, options.viewUp);\n if (mesh.indices.length === 0) {\n return;\n }\n\n const vertexData = mesh.vertices as unknown as BufferSource;\n if (mesh.vertices.byteLength > this.vertexCapacity) {\n this.vertexCapacity = mesh.vertices.byteLength;\n this.vertexBuffer.upload(vertexData, this.gl.DYNAMIC_DRAW);\n } else {\n this.vertexBuffer.update(vertexData);\n }\n\n const indexData = mesh.indices as unknown as BufferSource;\n if (mesh.indices.byteLength > this.indexCapacity) {\n this.indexCapacity = mesh.indices.byteLength;\n this.indexBuffer.upload(indexData, this.gl.DYNAMIC_DRAW);\n } else {\n this.indexBuffer.update(indexData);\n }\n\n this.gl.depthMask(false);\n this.program.use();\n const vp = this.program.getUniformLocation('u_viewProjection');\n this.gl.uniformMatrix4fv(vp, false, options.viewProjection);\n this.vertexArray.bind();\n\n for (const batch of mesh.batches) {\n if (batch.blendMode === 'additive') {\n this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE);\n } else {\n this.gl.blendFuncSeparate(\n this.gl.SRC_ALPHA,\n this.gl.ONE_MINUS_SRC_ALPHA,\n this.gl.ONE,\n this.gl.ONE_MINUS_SRC_ALPHA\n );\n }\n this.gl.drawElements(this.gl.TRIANGLES, batch.count, this.gl.UNSIGNED_SHORT, batch.start * 2);\n }\n\n this.gl.depthMask(true);\n }\n\n dispose(): void {\n this.program.dispose();\n this.vertexBuffer.dispose();\n this.indexBuffer.dispose();\n this.vertexArray.dispose();\n }\n}\n\nexport interface ParticleEffectContext {\n readonly system: ParticleSystem;\n readonly origin: Vec3;\n readonly normal?: Vec3;\n readonly direction?: Vec3;\n}\n\nexport function spawnBulletImpact(context: ParticleEffectContext): void {\n const { system, origin, normal = { x: 0, y: 0, z: 1 } } = context;\n for (let i = 0; i < 12; i += 1) {\n const speed = 200 + system.random() * 180;\n const spread = system.random() * 0.35;\n system.spawn({\n position: origin,\n velocity: {\n x: normal.x * speed + (system.random() - 0.5) * 80,\n y: normal.y * speed + (system.random() - 0.5) * 80,\n z: Math.max(normal.z * speed, 120) + spread * 80,\n },\n color: [1, 0.8, 0.4, 1],\n size: 2.5,\n lifetime: 0.45 + system.random() * 0.1,\n gravity: 600,\n damping: 2,\n bounce: 0.45,\n blendMode: 'additive',\n fade: true,\n });\n }\n\n for (let i = 0; i < 8; i += 1) {\n system.spawn({\n position: origin,\n velocity: { x: (system.random() - 0.5) * 40, y: (system.random() - 0.5) * 40, z: 80 + system.random() * 40 },\n color: [0.45, 0.45, 0.45, 0.75],\n size: 6,\n lifetime: 0.6,\n gravity: 200,\n damping: 4,\n bounce: 0.15,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n\nexport function spawnExplosion(context: ParticleEffectContext): void {\n const { system, origin } = context;\n for (let i = 0; i < 40; i += 1) {\n const theta = system.random() * Math.PI * 2;\n const phi = Math.acos(2 * system.random() - 1);\n const speed = 220 + system.random() * 260;\n const dir = {\n x: Math.sin(phi) * Math.cos(theta),\n y: Math.sin(phi) * Math.sin(theta),\n z: Math.cos(phi),\n };\n system.spawn({\n position: origin,\n velocity: { x: dir.x * speed, y: dir.y * speed, z: dir.z * speed },\n color: [1, 0.6, 0.2, 1],\n size: 5,\n lifetime: 0.9,\n gravity: 700,\n damping: 1,\n bounce: 0.35,\n blendMode: 'additive',\n fade: true,\n });\n }\n\n for (let i = 0; i < 16; i += 1) {\n system.spawn({\n position: origin,\n velocity: { x: (system.random() - 0.5) * 30, y: (system.random() - 0.5) * 30, z: 120 + system.random() * 120 },\n color: [0.25, 0.25, 0.25, 0.9],\n size: 12,\n lifetime: 1.2,\n gravity: 300,\n damping: 3,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n\nexport function spawnBlood(context: ParticleEffectContext): void {\n const { system, origin, direction = { x: 0, y: 0, z: 1 } } = context;\n for (let i = 0; i < 24; i += 1) {\n const speed = 120 + system.random() * 180;\n system.spawn({\n position: origin,\n velocity: {\n x: direction.x * speed + (system.random() - 0.5) * 70,\n y: direction.y * speed + (system.random() - 0.5) * 70,\n z: direction.z * speed + system.random() * 80,\n },\n color: [0.6, 0, 0, 0.95],\n size: 3,\n lifetime: 0.8,\n gravity: 900,\n damping: 1,\n bounce: 0.2,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n\nexport function spawnTeleportFlash(context: ParticleEffectContext): void {\n const { system, origin } = context;\n for (let i = 0; i < 30; i += 1) {\n const angle = system.random() * Math.PI * 2;\n const radius = 8 + system.random() * 8;\n system.spawn({\n position: origin,\n velocity: { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius, z: 100 + system.random() * 80 },\n color: [0.4, 0.6, 1, 0.9],\n size: 4,\n lifetime: 0.5,\n gravity: 300,\n damping: 2,\n blendMode: 'additive',\n fade: true,\n });\n }\n}\n\nexport function spawnMuzzleFlash(context: ParticleEffectContext): void {\n const { system, origin, direction = { x: 1, y: 0, z: 0 } } = context;\n for (let i = 0; i < 10; i += 1) {\n const speed = 350 + system.random() * 100;\n system.spawn({\n position: origin,\n velocity: {\n x: direction.x * speed + (system.random() - 0.5) * 30,\n y: direction.y * speed + (system.random() - 0.5) * 30,\n z: direction.z * speed + (system.random() - 0.5) * 30,\n },\n color: [1, 0.8, 0.3, 1],\n size: 3,\n lifetime: 0.25,\n gravity: 200,\n damping: 1,\n blendMode: 'additive',\n fade: true,\n });\n }\n}\n\nexport function spawnTrail(context: ParticleEffectContext): void {\n const { system, origin, direction = { x: 0, y: 0, z: 0 } } = context;\n for (let i = 0; i < 6; i += 1) {\n system.spawn({\n position: {\n x: origin.x + direction.x * i * 2,\n y: origin.y + direction.y * i * 2,\n z: origin.z + direction.z * i * 2,\n },\n velocity: { x: (system.random() - 0.5) * 15, y: (system.random() - 0.5) * 15, z: 20 + system.random() * 15 },\n color: [0.6, 0.6, 0.6, 0.8],\n size: 2.2,\n lifetime: 0.6,\n gravity: 200,\n damping: 1.5,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n","import { BinaryStream } from '@quake2ts/shared';\n\nexport interface DemoMessageBlock {\n length: number;\n data: BinaryStream;\n}\n\nexport class DemoReader {\n private buffer: ArrayBuffer;\n private view: DataView;\n private offset: number;\n\n constructor(buffer: ArrayBuffer) {\n this.buffer = buffer;\n this.view = new DataView(buffer);\n this.offset = 0;\n }\n\n /**\n * Checks if there are more blocks to read.\n */\n public hasMore(): boolean {\n return this.offset < this.buffer.byteLength;\n }\n\n /**\n * Reads the next message block from the demo file.\n * Format is [Length (4 bytes)] + [Message Block (Length bytes)].\n * Returns null if end of file or incomplete block.\n */\n public readNextBlock(): DemoMessageBlock | null {\n if (this.offset + 4 > this.buffer.byteLength) {\n // Not enough data for length\n return null;\n }\n\n // Read length (little endian)\n const length = this.view.getInt32(this.offset, true);\n this.offset += 4;\n\n if (length < 0 || length > 0x40000) { // 256k sanity check (MAX_MSGLEN is usually 1400, but demo blocks can be large)\n // Sanity check failed or negative length\n console.warn(`DemoReader: Invalid block length ${length} at offset ${this.offset - 4}`);\n return null;\n }\n\n if (this.offset + length > this.buffer.byteLength) {\n // Not enough data for the block body\n console.warn(`DemoReader: Incomplete block. Expected ${length} bytes, but only ${this.buffer.byteLength - this.offset} remain.`);\n return null;\n }\n\n // Create a view for the block data\n // Slice creates a copy, which is safer but slower.\n // For now, let's slice to ensure the BinaryStream is isolated.\n const blockData = this.buffer.slice(this.offset, this.offset + length);\n this.offset += length;\n\n return {\n length,\n data: new BinaryStream(blockData)\n };\n }\n\n /**\n * Resets the reader to the beginning.\n */\n public reset(): void {\n this.offset = 0;\n }\n\n public getOffset(): number {\n return this.offset;\n }\n}\n","import { BinaryStream } from '@quake2ts/shared';\nimport { ServerCommand } from '@quake2ts/shared';\nimport { Vec3 } from '@quake2ts/shared';\nimport { TempEntity } from '@quake2ts/shared';\n\n// Constants from Q2 source\nconst U_ORIGIN1 = (1 << 0);\nconst U_ORIGIN2 = (1 << 1);\nconst U_ANGLE2 = (1 << 2);\nconst U_ANGLE3 = (1 << 3);\nconst U_FRAME8 = (1 << 4);\nconst U_EVENT = (1 << 5);\nconst U_REMOVE = (1 << 6);\nconst U_MOREBITS1 = (1 << 7);\n\nconst U_NUMBER16 = (1 << 8);\nconst U_ORIGIN3 = (1 << 9);\nconst U_ANGLE1 = (1 << 10);\nconst U_MODEL = (1 << 11);\nconst U_RENDERFX8 = (1 << 12);\nconst U_EFFECTS8 = (1 << 14);\nconst U_MOREBITS2 = (1 << 15);\n\nconst U_SKIN8 = (1 << 16);\nconst U_FRAME16 = (1 << 17);\nconst U_RENDERFX16 = (1 << 18);\nconst U_EFFECTS16 = (1 << 19);\nconst U_MODEL2 = (1 << 20);\nconst U_MODEL3 = (1 << 21);\nconst U_MODEL4 = (1 << 22);\nconst U_MOREBITS3 = (1 << 23);\n\nconst U_OLDORIGIN = (1 << 24);\nconst U_SKIN16 = (1 << 25);\nconst U_SOUND = (1 << 26);\nconst U_SOLID = (1 << 27);\n\n// Mutable Vec3 for internal use\ninterface MutableVec3 {\n x: number;\n y: number;\n z: number;\n}\n\nexport interface EntityState {\n number: number;\n modelindex: number;\n modelindex2: number;\n modelindex3: number;\n modelindex4: number;\n frame: number;\n skinnum: number;\n effects: number;\n renderfx: number;\n origin: MutableVec3;\n old_origin: MutableVec3;\n angles: MutableVec3;\n sound: number;\n event: number;\n solid: number;\n}\n\nexport const createEmptyEntityState = (): EntityState => ({\n number: 0,\n modelindex: 0,\n modelindex2: 0,\n modelindex3: 0,\n modelindex4: 0,\n frame: 0,\n skinnum: 0,\n effects: 0,\n renderfx: 0,\n origin: { x: 0, y: 0, z: 0 },\n old_origin: { x: 0, y: 0, z: 0 },\n angles: { x: 0, y: 0, z: 0 },\n sound: 0,\n event: 0,\n solid: 0\n});\n\nexport class NetworkMessageParser {\n private stream: BinaryStream;\n\n constructor(stream: BinaryStream) {\n this.stream = stream;\n }\n\n public parseMessage(): void {\n while (this.stream.hasMore()) {\n const cmd = this.stream.readByte();\n\n if (cmd === -1) {\n break;\n }\n\n switch (cmd) {\n case ServerCommand.nop:\n break;\n case ServerCommand.disconnect:\n console.log(\"Server disconnected\");\n break;\n case ServerCommand.reconnect:\n console.log(\"Server reconnect\");\n break;\n case ServerCommand.print:\n const printId = this.stream.readByte();\n const printMsg = this.stream.readString();\n console.log(`[Server Print ${printId}]: ${printMsg}`);\n break;\n case ServerCommand.serverdata:\n this.parseServerData();\n break;\n case ServerCommand.configstring:\n this.parseConfigString();\n break;\n case ServerCommand.spawnbaseline:\n this.parseSpawnBaseline();\n break;\n case ServerCommand.centerprint:\n const centerMsg = this.stream.readString();\n console.log(`[Center Print]: ${centerMsg}`);\n break;\n case ServerCommand.download:\n this.parseDownload();\n break;\n case ServerCommand.frame:\n this.parseFrame();\n break;\n case ServerCommand.packetentities:\n this.parsePacketEntities(false);\n break;\n case ServerCommand.deltapacketentities:\n this.parsePacketEntities(true);\n break;\n case ServerCommand.stufftext:\n const text = this.stream.readString();\n console.log(`[StuffText]: ${text}`);\n break;\n case ServerCommand.layout:\n const layout = this.stream.readString();\n break;\n case ServerCommand.inventory:\n this.parseInventory();\n break;\n case ServerCommand.sound:\n this.parseSound();\n break;\n case ServerCommand.muzzleflash:\n this.parseMuzzleFlash();\n break;\n case ServerCommand.muzzleflash2:\n this.parseMuzzleFlash2();\n break;\n case ServerCommand.temp_entity:\n this.parseTempEntity();\n break;\n default:\n console.warn(`Unknown server command: ${cmd}`);\n // If we hit an unknown command, we are likely desynced as we don't know the length to skip.\n return;\n }\n }\n }\n\n private parseServerData(): void {\n const protocol = this.stream.readLong();\n const serverCount = this.stream.readLong();\n const attractLoop = this.stream.readByte();\n const gameDir = this.stream.readString();\n const playerNum = this.stream.readShort();\n const levelName = this.stream.readString();\n\n console.log(`Server Data: Protocol ${protocol}, Level ${levelName}, GameDir ${gameDir}`);\n }\n\n private parseConfigString(): void {\n const index = this.stream.readShort();\n const str = this.stream.readString();\n // In a real implementation, this would update the client's configstring table\n }\n\n private parseDownload(): void {\n const size = this.stream.readShort();\n const percent = this.stream.readByte();\n if (size > 0) {\n this.stream.readData(size);\n }\n }\n\n private parseInventory(): void {\n // MAX_ITEMS is 256 in q_shared.h usually\n // In cl_parse.c CL_ParseInventory:\n // int i;\n // for (i=0 ; i<MAX_ITEMS ; i++)\n // cl.inventory[i] = MSG_ReadShort (&net_message);\n const MAX_ITEMS = 256;\n for (let i = 0; i < MAX_ITEMS; i++) {\n this.stream.readShort();\n }\n }\n\n private parseSound(): void {\n const flags = this.stream.readByte();\n const soundNum = this.stream.readByte();\n\n if (flags & 1) { // SND_VOLUME\n this.stream.readByte();\n }\n if (flags & 2) { // SND_ATTENUATION\n this.stream.readByte();\n }\n if (flags & 16) { // SND_OFFSET\n this.stream.readByte();\n }\n if (flags & 8) { // SND_ENT\n this.stream.readShort();\n }\n if (flags & 4) { // SND_POS\n // We need a temporary object to read into\n const pos = { x: 0, y: 0, z: 0 };\n this.stream.readPos(pos);\n }\n }\n\n private parseMuzzleFlash(): void {\n const ent = this.stream.readShort();\n const weapon = this.stream.readByte();\n }\n\n private parseMuzzleFlash2(): void {\n const ent = this.stream.readShort();\n const weapon = this.stream.readByte();\n }\n\n private parseTempEntity(): void {\n const type = this.stream.readByte();\n\n // Placeholder vars\n const pos = { x: 0, y: 0, z: 0 };\n const pos2 = { x: 0, y: 0, z: 0 };\n const dir = { x: 0, y: 0, z: 0 };\n\n switch (type) {\n case TempEntity.BLOOD:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.GUNSHOT:\n case TempEntity.SPARKS:\n case TempEntity.BULLET_SPARKS:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.SCREEN_SPARKS:\n case TempEntity.SHIELD_SPARKS:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.SHOTGUN:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.SPLASH:\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // r\n break;\n\n case TempEntity.LASER_SPARKS:\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // color\n break;\n\n case TempEntity.BLUEHYPERBLASTER:\n this.stream.readPos(pos);\n this.stream.readPos(dir); // NOTE: original uses MSG_ReadPos for dir here\n break;\n\n case TempEntity.BLASTER:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.RAILTRAIL:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n break;\n\n case TempEntity.EXPLOSION2:\n case TempEntity.GRENADE_EXPLOSION:\n case TempEntity.GRENADE_EXPLOSION_WATER:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.PLASMA_EXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.EXPLOSION1:\n case TempEntity.EXPLOSION1_BIG:\n case TempEntity.ROCKET_EXPLOSION:\n case TempEntity.ROCKET_EXPLOSION_WATER:\n case TempEntity.EXPLOSION1_NP:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.BFG_EXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.BFG_BIGEXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.BFG_LASER:\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n break;\n\n case TempEntity.BUBBLETRAIL:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n break;\n\n case TempEntity.PARASITE_ATTACK:\n case TempEntity.MEDIC_CABLE_ATTACK:\n this.stream.readShort(); // ent\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n break;\n\n case TempEntity.BOSSTPORT:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.GRAPPLE_CABLE:\n this.stream.readShort(); // ent\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n this.stream.readPos(dir); // offset (reusing dir var)\n break;\n\n case TempEntity.WELDING_SPARKS:\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // color\n break;\n\n case TempEntity.GREENBLOOD:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.TUNNEL_SPARKS:\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // color\n break;\n\n case TempEntity.BLASTER2:\n case TempEntity.FLECHETTE:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.LIGHTNING:\n this.stream.readShort(); // srcEnt\n this.stream.readShort(); // destEnt\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n break;\n\n case TempEntity.DEBUGTRAIL:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n break;\n\n case TempEntity.PLAIN_EXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.FLASHLIGHT:\n this.stream.readPos(pos);\n this.stream.readShort(); // ent\n break;\n\n case TempEntity.FORCEWALL:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n this.stream.readByte(); // color\n break;\n\n case TempEntity.HEATBEAM:\n this.stream.readShort(); // ent\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n this.stream.readPos(dir); // offset\n break;\n\n case TempEntity.MONSTER_HEATBEAM:\n this.stream.readShort(); // ent\n this.stream.readPos(pos); // start\n this.stream.readPos(pos2); // end\n this.stream.readPos(dir); // offset\n break;\n\n case TempEntity.HEATBEAM_SPARKS:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.HEATBEAM_STEAM:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.STEAM:\n const steamId = this.stream.readShort();\n if (steamId !== -1) {\n this.stream.readByte(); // count\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // r\n this.stream.readShort(); // magnitude\n this.stream.readLong(); // endtime (delta?) or something\n } else {\n this.stream.readByte(); // cnt\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n this.stream.readByte(); // r\n this.stream.readShort(); // magnitude\n }\n break;\n\n case TempEntity.BUBBLETRAIL2:\n this.stream.readPos(pos);\n this.stream.readPos(pos2);\n break;\n\n case TempEntity.MOREBLOOD:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.CHAINFIST_SMOKE:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.ELECTRIC_SPARKS:\n this.stream.readPos(pos);\n this.stream.readDir(dir);\n break;\n\n case TempEntity.TRACKER_EXPLOSION:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.TELEPORT_EFFECT:\n case TempEntity.DBALL_GOAL:\n this.stream.readPos(pos);\n break;\n\n case TempEntity.WIDOWBEAMOUT:\n const wbId = this.stream.readShort();\n // Logic from CL_ParseWidow:\n // if free sustain -> reads id, pos, endtime=time+2100...\n // else -> read pos\n // BUT WE ARE PARSING, NOT SIMULATING. We must read exactly what is on the wire.\n // CL_ParseWidow logic:\n // id = MSG_ReadShort\n // if (free_sustain) { MSG_ReadPos... } else { MSG_ReadPos... }\n // It always reads a pos.\n this.stream.readPos(pos);\n break;\n\n case TempEntity.NUKEBLAST:\n // Logic from CL_ParseNuke:\n // Always reads pos.\n this.stream.readPos(pos);\n break;\n\n case TempEntity.WIDOWSPLASH:\n this.stream.readPos(pos);\n break;\n\n default:\n console.warn(`CL_ParseTEnt: bad type ${type}`);\n break;\n }\n }\n\n private parseSpawnBaseline(): void {\n const bits = this.parseEntityBits();\n // We would use this to update the baseline table\n // const entityState = createEmptyEntityState();\n // this.parseDelta(createEmptyEntityState(), entityState, bits.number, bits.bits);\n\n // For now just consume the delta\n this.parseDelta(createEmptyEntityState(), createEmptyEntityState(), bits.number, bits.bits);\n }\n\n private parseFrame(): void {\n const serverFrame = this.stream.readLong();\n const deltaFrame = this.stream.readLong();\n const surpressCount = this.stream.readByte(); // Only if protocol != 26? In cl_parse.c: if (cls.serverProtocol != 26) cl.surpressCount = MSG_ReadByte...\n // But we don't track protocol version here yet. Standard Q2 is 34. So we read it.\n\n const areaBytes = this.stream.readByte();\n this.stream.readData(areaBytes);\n\n // The frame command is followed by other commands like svc_playerinfo and svc_packetentities inside the same message block usually?\n // No, svc_frame is a command inside the loop.\n // cl_parse.c CL_ParseFrame calls CL_ParsePlayerstate etc, but those read from net_message.\n // Wait, in CL_ParseFrame, it reads area bits, THEN:\n // cmd = MSG_ReadByte\n // if (cmd != svc_playerinfo) Error\n // ...\n // cmd = MSG_ReadByte\n // if (cmd != svc_packetentities) Error\n\n // So yes, `svc_frame` implies we *expect* `svc_playerinfo` and `svc_packetentities` next.\n // But my main loop dispatch handles them as separate commands if I return?\n // No, `CL_ParseFrame` *consumes* them.\n\n // So I must consume them here.\n\n // Player Info\n const piCmd = this.stream.readByte();\n if (piCmd !== ServerCommand.playerinfo) {\n throw new Error(`Expected svc_playerinfo after svc_frame, got ${piCmd}`);\n }\n this.parsePlayerState();\n\n // Packet Entities\n const peCmd = this.stream.readByte();\n if (peCmd !== ServerCommand.packetentities && peCmd !== ServerCommand.deltapacketentities) {\n throw new Error(`Expected svc_packetentities after svc_playerinfo, got ${peCmd}`);\n }\n this.parsePacketEntities(peCmd === ServerCommand.deltapacketentities);\n }\n\n private parsePlayerState(): void {\n const flags = this.stream.readShort();\n\n // PS_M_TYPE (1<<0)\n if (flags & 1) this.stream.readByte();\n\n // PS_M_ORIGIN (1<<1)\n if (flags & 2) {\n this.stream.readShort();\n this.stream.readShort();\n this.stream.readShort();\n }\n\n // PS_M_VELOCITY (1<<2)\n if (flags & 4) {\n this.stream.readShort();\n this.stream.readShort();\n this.stream.readShort();\n }\n\n // PS_M_TIME (1<<3)\n if (flags & 8) this.stream.readByte();\n\n // PS_M_FLAGS (1<<4)\n if (flags & 16) this.stream.readByte();\n\n // PS_M_GRAVITY (1<<5)\n if (flags & 32) this.stream.readShort();\n\n // PS_M_DELTA_ANGLES (1<<6)\n if (flags & 64) {\n this.stream.readShort();\n this.stream.readShort();\n this.stream.readShort();\n }\n\n // PS_VIEWOFFSET (1<<7)\n if (flags & 128) {\n this.stream.readChar();\n this.stream.readChar();\n this.stream.readChar();\n }\n\n // PS_VIEWANGLES (1<<8)\n if (flags & 256) {\n this.stream.readAngle16();\n this.stream.readAngle16();\n this.stream.readAngle16();\n }\n\n // PS_KICKANGLES (1<<9)\n if (flags & 512) {\n this.stream.readChar();\n this.stream.readChar();\n this.stream.readChar();\n }\n\n // PS_BLEND (1<<10) (Note: skipped WEAPONINDEX/FRAME in headers, check full list order)\n // Header says:\n // #define\tPS_WEAPONINDEX\t\t(1<<12)\n // #define\tPS_WEAPONFRAME\t\t(1<<13)\n // #define\tPS_BLEND\t\t\t(1<<10)\n // #define\tPS_FOV\t\t\t\t(1<<11)\n // #define\tPS_RDFLAGS\t\t\t(1<<14)\n\n // Order in CL_ParsePlayerstate:\n // WEAPONINDEX\n if (flags & 4096) this.stream.readByte();\n\n // WEAPONFRAME\n if (flags & 8192) {\n this.stream.readByte(); // frame\n this.stream.readChar(); // offset x\n this.stream.readChar(); // offset y\n this.stream.readChar(); // offset z\n this.stream.readChar(); // angles x\n this.stream.readChar(); // angles y\n this.stream.readChar(); // angles z\n }\n\n // BLEND\n if (flags & 1024) {\n this.stream.readByte();\n this.stream.readByte();\n this.stream.readByte();\n this.stream.readByte();\n }\n\n // FOV\n if (flags & 2048) this.stream.readByte();\n\n // RDFLAGS\n if (flags & 16384) this.stream.readByte();\n\n // STATS\n const statbits = this.stream.readLong();\n for (let i = 0; i < 32; i++) {\n if (statbits & (1 << i)) {\n this.stream.readShort();\n }\n }\n }\n\n private parsePacketEntities(delta: boolean): void {\n // In CL_ParsePacketEntities\n while (true) {\n const bits = this.parseEntityBits();\n if (bits.number === 0) {\n break;\n }\n\n // Consume the delta\n this.parseDelta(createEmptyEntityState(), createEmptyEntityState(), bits.number, bits.bits);\n }\n }\n\n private parseEntityBits(): { number: number; bits: number } {\n let total = this.stream.readByte();\n if (total & U_MOREBITS1) {\n total |= (this.stream.readByte() << 8);\n }\n if (total & U_MOREBITS2) {\n total |= (this.stream.readByte() << 16);\n }\n if (total & U_MOREBITS3) {\n total |= (this.stream.readByte() << 24);\n }\n\n let number: number;\n if (total & U_NUMBER16) {\n number = this.stream.readShort();\n } else {\n number = this.stream.readByte();\n }\n\n return { number, bits: total };\n }\n\n private parseDelta(from: EntityState, to: EntityState, number: number, bits: number): void {\n // Copy 'from' to 'to'\n to.number = from.number;\n to.modelindex = from.modelindex;\n to.modelindex2 = from.modelindex2;\n to.modelindex3 = from.modelindex3;\n to.modelindex4 = from.modelindex4;\n to.frame = from.frame;\n to.skinnum = from.skinnum;\n to.effects = from.effects;\n to.renderfx = from.renderfx;\n to.origin.x = from.origin.x; to.origin.y = from.origin.y; to.origin.z = from.origin.z;\n to.old_origin.x = from.origin.x; to.old_origin.y = from.origin.y; to.old_origin.z = from.origin.z;\n to.angles.x = from.angles.x; to.angles.y = from.angles.y; to.angles.z = from.angles.z;\n to.sound = from.sound;\n to.event = from.event;\n to.solid = from.solid;\n\n to.number = number;\n\n if (bits & U_MODEL) to.modelindex = this.stream.readByte();\n if (bits & U_MODEL2) to.modelindex2 = this.stream.readByte();\n if (bits & U_MODEL3) to.modelindex3 = this.stream.readByte();\n if (bits & U_MODEL4) to.modelindex4 = this.stream.readByte();\n\n if (bits & U_FRAME8) to.frame = this.stream.readByte();\n if (bits & U_FRAME16) to.frame = this.stream.readShort();\n\n if ((bits & U_SKIN8) && (bits & U_SKIN16)) {\n to.skinnum = this.stream.readLong();\n } else if (bits & U_SKIN8) {\n to.skinnum = this.stream.readByte();\n } else if (bits & U_SKIN16) {\n to.skinnum = this.stream.readShort();\n }\n\n if ((bits & U_EFFECTS8) && (bits & U_EFFECTS16)) {\n to.effects = this.stream.readLong();\n } else if (bits & U_EFFECTS8) {\n to.effects = this.stream.readByte();\n } else if (bits & U_EFFECTS16) {\n to.effects = this.stream.readShort();\n }\n\n if ((bits & U_RENDERFX8) && (bits & U_RENDERFX16)) {\n to.renderfx = this.stream.readLong();\n } else if (bits & U_RENDERFX8) {\n to.renderfx = this.stream.readByte();\n } else if (bits & U_RENDERFX16) {\n to.renderfx = this.stream.readShort();\n }\n\n if (bits & U_ORIGIN1) to.origin.x = this.stream.readCoord();\n if (bits & U_ORIGIN2) to.origin.y = this.stream.readCoord();\n if (bits & U_ORIGIN3) to.origin.z = this.stream.readCoord();\n\n if (bits & U_ANGLE1) to.angles.x = this.stream.readAngle();\n if (bits & U_ANGLE2) to.angles.y = this.stream.readAngle();\n if (bits & U_ANGLE3) to.angles.z = this.stream.readAngle();\n\n if (bits & U_OLDORIGIN) {\n this.stream.readPos(to.old_origin);\n }\n\n if (bits & U_SOUND) to.sound = this.stream.readByte();\n\n if (bits & U_EVENT) {\n to.event = this.stream.readByte();\n } else {\n to.event = 0;\n }\n\n if (bits & U_SOLID) to.solid = this.stream.readShort();\n }\n}\n","import { DemoReader } from './demoReader.js';\nimport { NetworkMessageParser } from './parser.js';\n\nexport enum PlaybackState {\n Stopped,\n Playing,\n Paused,\n Finished\n}\n\nexport class DemoPlaybackController {\n private reader: DemoReader | null = null;\n private state: PlaybackState = PlaybackState.Stopped;\n private playbackSpeed: number = 1.0;\n\n // Timing\n private accumulatedTime: number = 0;\n private frameDuration: number = 100; // ms (10Hz default)\n\n constructor() {}\n\n public loadDemo(buffer: ArrayBuffer) {\n this.reader = new DemoReader(buffer);\n this.state = PlaybackState.Stopped;\n this.accumulatedTime = 0;\n }\n\n public play() {\n if (this.reader) {\n this.state = PlaybackState.Playing;\n }\n }\n\n public pause() {\n if (this.state === PlaybackState.Playing) {\n this.state = PlaybackState.Paused;\n }\n }\n\n public stop() {\n this.state = PlaybackState.Stopped;\n if (this.reader) {\n this.reader.reset();\n }\n this.accumulatedTime = 0;\n }\n\n public update(dt: number) {\n if (this.state !== PlaybackState.Playing || !this.reader) {\n return;\n }\n\n this.accumulatedTime += dt * 1000 * this.playbackSpeed; // Convert to ms\n\n while (this.accumulatedTime >= this.frameDuration) {\n if (!this.reader.hasMore()) {\n this.state = PlaybackState.Finished;\n return;\n }\n\n const block = this.reader.readNextBlock();\n if (!block) {\n this.state = PlaybackState.Finished;\n return;\n }\n\n const parser = new NetworkMessageParser(block.data);\n parser.parseMessage();\n this.accumulatedTime -= this.frameDuration;\n }\n }\n\n public getState(): PlaybackState {\n return this.state;\n }\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport {\n EngineHost,\n type ClientRenderer,\n type EngineHostOptions,\n type GameFrameResult,\n type GameRenderSample,\n type GameSimulation,\n} from './host.js';\nimport { ConfigStringRegistry } from './configstrings.js';\nimport { FixedTimestepLoop, type LoopCallbacks, type LoopOptions } from './loop.js';\nimport { EngineRuntime, createEngineRuntime } from './runtime.js';\n\nimport { PmoveTraceResult } from '@quake2ts/shared';\n\nexport interface TraceResult extends PmoveTraceResult {\n readonly start: Vec3;\n readonly end: Vec3;\n readonly hit?: Vec3;\n}\n\nimport { Renderer } from './render/renderer.js';\n\nexport interface EngineImports {\n trace(start: Vec3, end: Vec3): TraceResult;\n renderer?: Renderer;\n}\n\nexport interface EngineExports {\n init(): void;\n shutdown(): void;\n createMainLoop(callbacks: LoopCallbacks, options?: Partial<LoopOptions>): FixedTimestepLoop;\n}\n\nexport function createEngine(imports: EngineImports): EngineExports {\n return {\n init() {\n void imports.trace({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 });\n },\n shutdown() {\n /* no-op for bootstrap */\n },\n createMainLoop(callbacks: LoopCallbacks, options?: Partial<LoopOptions>): FixedTimestepLoop {\n return new FixedTimestepLoop(callbacks, options);\n },\n };\n}\n\nexport { FixedTimestepLoop };\nexport { ConfigStringRegistry };\nexport { Cvar, CvarRegistry } from './cvars.js';\nexport type { FixedStepContext, LoopCallbacks, LoopOptions, RenderContext } from './loop.js';\nexport { PakArchive, PakParseError, calculatePakChecksum } from './assets/pak.js';\nexport { VirtualFileSystem } from './assets/vfs.js';\nexport {\n ingestPaks,\n PakIngestionError,\n type PakIngestionOptions,\n type PakIngestionProgress,\n type PakIngestionResult,\n type PakSource,\n} from './assets/ingestion.js';\nexport { LruCache } from './assets/cache.js';\nexport { filesToPakSources, ingestPakFiles, wireDropTarget, wireFileInput } from './assets/browserIngestion.js';\nexport {\n BspLoader,\n BspParseError,\n parseBsp,\n createFaceLightmap,\n type BspMap,\n type BspHeader,\n type BspEntities,\n type BspEntity,\n type BspLump,\n type BspLumpInfo,\n type BspFace,\n type BspLeaf,\n type BspNode,\n type BspPlane,\n type BspTexInfo,\n type BspModel,\n type BspVisibility,\n type BspVisibilityCluster,\n} from './assets/bsp.js';\nexport {\n Md2Loader,\n Md2ParseError,\n groupMd2Animations,\n parseMd2,\n type Md2Animation,\n type Md2Frame,\n type Md2GlCommand,\n type Md2Model,\n} from './assets/md2.js';\nexport {\n Md3Loader,\n Md3ParseError,\n parseMd3,\n type Md3Frame,\n type Md3Model,\n type Md3Surface,\n} from './assets/md3.js';\nexport {\n SpriteLoader,\n SpriteParseError,\n parseSprite,\n type SpriteFrame,\n type SpriteModel,\n} from './assets/sprite.js';\nexport {\n advanceAnimation,\n computeFrameBlend,\n createAnimationState,\n interpolateVec3,\n type AnimationSequence,\n type AnimationState,\n type FrameBlend,\n} from './assets/animation.js';\nexport { parseWal, type WalTexture } from './assets/wal.js';\nexport { parsePcx, pcxToRgba, type PcxImage } from './assets/pcx.js';\nexport {\n parseWalTexture,\n preparePcxTexture,\n TextureCache,\n walToRgba,\n type PreparedTexture,\n type TextureLevel,\n} from './assets/texture.js';\nexport { parseWav, type WavData } from './assets/wav.js';\nexport { decodeOgg, type OggAudio } from './assets/ogg.js';\nexport { AudioRegistry, AudioRegistryError, type DecodedAudio } from './assets/audio.js';\nexport { PakIndexStore, type StoredPakIndex } from './assets/pakIndexStore.js';\nexport {\n PakValidationError,\n PakValidator,\n RERELEASE_KNOWN_PAKS,\n type KnownPakChecksum,\n type PakValidationOutcome,\n} from './assets/pakValidation.js';\nexport {\n AssetDependencyError,\n AssetDependencyTracker,\n AssetManager,\n type AssetManagerOptions,\n} from './assets/manager.js';\nexport {\n ATTN_IDLE,\n ATTN_LOOP_NONE,\n ATTN_NONE,\n ATTN_NORM,\n ATTN_STATIC,\n MAX_SOUND_CHANNELS,\n SOUND_FULLVOLUME,\n SOUND_LOOP_ATTENUATE,\n SoundChannel,\n attenuationToDistanceMultiplier,\n calculateMaxAudibleDistance,\n} from './audio/constants.js';\nexport {\n AudioContextController,\n createAudioGraph,\n type AudioBufferLike,\n type AudioContextLike,\n type AudioGraph,\n type AudioNodeLike,\n type GainNodeLike,\n type BiquadFilterNodeLike,\n type PannerNodeLike,\n} from './audio/context.js';\nexport { SoundRegistry } from './audio/registry.js';\nexport { SoundPrecache, type SoundPrecacheOptions, type SoundPrecacheReport } from './audio/precache.js';\nexport { AudioSystem, type AudioSystemOptions, type SoundRequest } from './audio/system.js';\nexport { spatializeOrigin, type ListenerState, type SpatializationResult } from './audio/spatialization.js';\nexport { createInitialChannels, pickChannel, type ChannelState } from './audio/channels.js';\nexport { MusicSystem, type MusicSystemOptions, type MusicState, type AudioElementLike } from './audio/music.js';\nexport { AudioApi, type AudioApiOptions } from './audio/api.js';\nexport {\n EngineHost,\n type ClientRenderer,\n type EngineHostOptions,\n type GameFrameResult,\n type GameRenderSample,\n type GameSimulation,\n};\nexport { EngineRuntime, createEngineRuntime };\nexport { createWebGLContext, type WebGLContextInitOptions, type WebGLContextState } from './render/context.js';\nexport { ShaderProgram, createProgramFromSources, type ShaderSources } from './render/shaderProgram.js';\nexport {\n Framebuffer,\n IndexBuffer,\n Texture2D,\n TextureCubeMap,\n VertexArray,\n VertexBuffer,\n type BufferUsage,\n type TextureParameters,\n type VertexAttributeLayout,\n} from './render/resources.js';\nexport {\n BSP_VERTEX_LAYOUT,\n createBspSurfaces,\n buildBspGeometry,\n type BspGeometryBuildResult,\n type BspLightmapData,\n type BspSurfaceGeometry,\n type BspSurfaceInput,\n type LightmapAtlas,\n type LightmapPlacement,\n} from './render/bsp.js';\nexport { extractFrustumPlanes, boxIntersectsFrustum, type FrustumPlane } from './render/culling.js';\nexport { findLeafForPoint, gatherVisibleFaces, type VisibleFace } from './render/bspTraversal.js';\nexport {\n applySurfaceState,\n BspSurfacePipeline,\n BSP_SURFACE_FRAGMENT_SOURCE,\n BSP_SURFACE_VERTEX_SOURCE,\n deriveSurfaceRenderState,\n resolveLightStyles,\n type BspSurfaceBindOptions,\n type SurfaceRenderState,\n} from './render/bspPipeline.js';\nexport {\n SKYBOX_FRAGMENT_SHADER,\n SKYBOX_VERTEX_SHADER,\n SkyboxPipeline,\n computeSkyScroll,\n removeViewTranslation,\n} from './render/skybox.js';\nexport {\n MD2_FRAGMENT_SHADER,\n MD2_VERTEX_SHADER,\n Md2MeshBuffers,\n Md2Pipeline,\n buildMd2Geometry,\n buildMd2VertexData,\n type Md2BindOptions,\n type Md2FrameBlend,\n type Md2Geometry,\n type Md2DrawVertex,\n} from './render/md2Pipeline.js';\nexport { Camera } from './render/camera.js';\nexport {\n MD3_FRAGMENT_SHADER,\n MD3_VERTEX_SHADER,\n Md3ModelMesh,\n Md3Pipeline,\n Md3SurfaceMesh,\n buildMd3SurfaceGeometry,\n buildMd3VertexData,\n interpolateMd3Tag,\n type Md3FrameBlend,\n type Md3LightingOptions,\n type Md3SurfaceMaterial,\n type Md3TagTransform,\n} from './render/md3Pipeline.js';\nexport {\n PARTICLE_FRAGMENT_SHADER,\n PARTICLE_VERTEX_SHADER,\n ParticleRenderer,\n ParticleSystem,\n spawnBlood,\n spawnBulletImpact,\n spawnExplosion,\n spawnMuzzleFlash,\n spawnTeleportFlash,\n spawnTrail,\n type ParticleBlendMode,\n type ParticleEffectContext,\n type ParticleMesh,\n type ParticleRenderOptions,\n type ParticleSimulationOptions,\n type ParticleSpawnOptions,\n} from './render/particleSystem.js';\nexport { Pic, Renderer } from './render/renderer.js';\nexport { FrameRenderStats, FrameRenderOptions } from './render/frame.js';\nexport { DemoPlaybackController, PlaybackState, DemoReader, NetworkMessageParser } from './demo/index.js';\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 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","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 /** 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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } from '../math/vec3.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 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\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 let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false;\n let startout = false;\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\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 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 if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n if (d1 > d2) {\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 const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n if (!startout) {\n trace.startsolid = true;\n if (!getout) {\n trace.allsolid = true;\n }\n trace.fraction = 0;\n return;\n }\n\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n trace.fraction = enterfrac < 0 ? 0 : 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\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 (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\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 if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n // Use absolute value of offset like original C code (full/qcommon/cmodel.c:1269-1271)\n // which uses fabs() on each component\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start);\n const endDist = planeDistanceToPoint(plane, end);\n\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 (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 // Put the crosspoint DIST_EPSILON pixels on the near side\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 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 if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\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 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\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\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 for (const entity of this.entities.values()) {\n if (entity.id === passId) 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 const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\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 for (const entity of this.entities.values()) {\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 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 PlayerSkins = Items + MAX_ITEMS,\n General = PlayerSkins + 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","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 Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n} from './types.js';\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 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 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 {\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","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 {\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 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, 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 { 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 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 jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: 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, 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, 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\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, 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 return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\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 { 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 { 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\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\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 { 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}\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}\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}\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';\n\nconst FRAMETIME = 0.025;\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 point.z += state.mins.z + 1;\n const contents = pointContents(point);\n if (contents & 0x2000000) {\n return { ...state, waterLevel: 1 };\n }\n return { ...state, waterLevel: 0 };\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 } = newState;\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: { x: 1, y: 0, z: 0 },\n right: { x: 0, y: 1, z: 0 },\n cmd,\n maxSpeed: 320,\n })\n : buildAirGroundWish({\n forward: { x: 1, y: 0, z: 0 },\n right: { x: 0, y: 1, z: 0 },\n cmd,\n maxSpeed: 320,\n });\n\n const finalVelocity = applyPmoveAccelerate({\n velocity: frictionedVelocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: onGround ? 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';\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 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 hasMore(): boolean {\n return this.offset < 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 readLong(): number {\n const value = this.view.getInt32(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 // TODO: Implement bytedirs lookup\n // For now, zero it out\n out.x = 0; out.y = 0; out.z = 0;\n }\n}\n","import {\n addVec3,\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} from '@quake2ts/shared';\nimport {\n applyPmoveAccelerate,\n applyPmoveAirAccelerate,\n applyPmoveFriction,\n} from '@quake2ts/shared';\nimport type { GameFrameResult } from '@quake2ts/engine';\n\nimport { PlayerClient } from '@quake2ts/game';\n\nexport interface PredictionState {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly viewangles: Vec3;\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly waterlevel: WaterLevel;\n readonly gravity: number;\n readonly deltaAngles?: Vec3;\n readonly client?: PlayerClient;\n readonly health: number;\n readonly armor: number;\n readonly ammo: number;\n readonly centerPrint?: string;\n readonly notify?: string;\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}\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};\n\nconst DEFAULT_GRAVITY = 800;\nconst ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\nconst MSEC_MAX = 250;\n\nexport function defaultPredictionState(): PredictionState {\n return {\n origin: ZERO_VEC3,\n velocity: ZERO_VEC3,\n viewangles: ZERO_VEC3,\n pmFlags: PmFlag.OnGround,\n pmType: PmType.Normal,\n waterlevel: WaterLevel.None,\n gravity: DEFAULT_GRAVITY,\n deltaAngles: ZERO_VEC3,\n health: 0,\n armor: 0,\n ammo: 0,\n } satisfies PredictionState;\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 } 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 return {\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 pmFlags: latest.pmFlags,\n pmType: latest.pmType,\n waterlevel: latest.waterlevel,\n gravity: latest.gravity,\n deltaAngles: latest.deltaAngles,\n client: latest.client,\n health: lerp(previous.health, latest.health, clamped),\n armor: lerp(previous.armor, latest.armor, clamped),\n ammo: lerp(previous.ammo, latest.ammo, clamped),\n centerPrint: latest.centerPrint,\n notify: latest.notify,\n } satisfies PredictionState;\n}\n\nfunction simulateCommand(\n state: PredictionState,\n cmd: UserCommand,\n settings: PredictionSettings,\n trace: PmoveTraceFn,\n): PredictionState {\n const frametime = Math.min(Math.max(cmd.msec, 0), MSEC_MAX) / 1000;\n const onGround = hasPmFlag(state.pmFlags, PmFlag.OnGround);\n const onLadder = hasPmFlag(state.pmFlags, PmFlag.OnLadder);\n\n let velocity = applyPmoveFriction({\n velocity: state.velocity,\n frametime,\n onGround,\n groundIsSlick: settings.groundIsSlick,\n onLadder,\n waterlevel: state.waterlevel,\n pmFriction: settings.pmFriction,\n pmStopSpeed: settings.pmStopSpeed,\n pmWaterFriction: settings.pmWaterFriction,\n });\n\n const { viewangles, forward, right } = clampViewAngles({\n pmFlags: state.pmFlags,\n cmdAngles: cmd.angles,\n deltaAngles: state.deltaAngles ?? ZERO_VEC3,\n });\n\n const wish =\n state.waterlevel > WaterLevel.None\n ? buildWaterWish({ forward, right, cmd, maxSpeed: settings.pmWaterSpeed })\n : buildAirGroundWish({ forward, right, cmd, maxSpeed: settings.pmMaxSpeed });\n\n if (state.waterlevel > WaterLevel.None) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: settings.pmWaterAccelerate,\n frametime,\n });\n } else if (onGround || onLadder) {\n const maxSpeed = hasPmFlag(state.pmFlags, PmFlag.Ducked) ? settings.pmDuckSpeed : settings.pmMaxSpeed;\n const clampedWish =\n wish.wishspeed > maxSpeed\n ? {\n wishdir: wish.wishdir,\n wishspeed: maxSpeed,\n }\n : wish;\n\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: clampedWish.wishdir,\n wishspeed: clampedWish.wishspeed,\n accel: settings.pmAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: settings.pmAirAccelerate,\n frametime,\n });\n velocity = { ...velocity, z: velocity.z - state.gravity * frametime };\n }\n\n const traceResult = trace(state.origin, addVec3(state.origin, scaleVec3(velocity, frametime)));\n const origin = traceResult.endpos;\n\n return {\n ...state,\n origin,\n velocity,\n viewangles,\n } satisfies PredictionState;\n}\n\nimport { PmoveTraceFn } from '@quake2ts/shared';\n\nexport class ClientPrediction {\n private readonly settings: PredictionSettings;\n private readonly trace: PmoveTraceFn;\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\n constructor(trace: PmoveTraceFn, settings: Partial<PredictionSettings> = {}) {\n this.settings = { ...DEFAULTS, ...settings } satisfies PredictionSettings;\n this.trace = trace;\n this.predicted = this.baseFrame.state ?? defaultPredictionState();\n }\n\n setAuthoritative(frame: GameFrameResult<PredictionState>): PredictionState {\n const normalized = normalizeState(frame.state);\n this.baseFrame = { ...frame, state: normalized };\n this.commands = this.commands.filter((cmd) => (cmd.serverFrame ?? Number.MAX_SAFE_INTEGER) > frame.frame);\n return this.recompute();\n }\n\n enqueueCommand(cmd: UserCommand): PredictionState {\n this.commands.push(cmd);\n return this.recompute();\n }\n\n getPredictedState(): PredictionState {\n return this.predicted;\n }\n\n private recompute(): PredictionState {\n let state = normalizeState(this.baseFrame.state);\n\n for (const cmd of this.commands) {\n state = simulateCommand(state, cmd, this.settings, this.trace);\n }\n\n this.predicted = state;\n return state;\n }\n}\n","import { ZERO_VEC3, angleVectors, clampViewAngles, dotVec3, hasPmFlag, PmFlag, type PmFlags, type Vec3 } from '@quake2ts/shared';\nimport type { PredictionState } from './prediction.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.005,\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}\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 let rollTilt = dotVec3(state.velocity, right) * this.settings.runRoll;\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\n // Apply active kick\n if (this.kick && this.kick.remainingMs > 0) {\n const ratio = Math.max(0, Math.min(1, this.kick.remainingMs / this.kick.durationMs));\n kickPitch += ratio * this.kick.pitch;\n kickRoll += ratio * this.kick.roll;\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: 0, y: 0, z: bobHeight };\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 { Pic, Renderer } from '@quake2ts/engine';\n\nexport const Draw_Number = (renderer: Renderer, x: number, y: number, value: number, pics: readonly Pic[], width: 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 renderer.drawPic(x + i * width, y, pic);\n }\n }\n};\n","export const HUD_LAYOUT = {\n // All coordinates are relative to a 640x480 screen resolution\n // and will be scaled accordingly.\n\n // Status bar numbers\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\n // Center print messages\n CENTER_PRINT_X: 320,\n CENTER_PRINT_Y: 100,\n\n // Weapon and powerup icons\n WEAPON_ICON_X: 10,\n WEAPON_ICON_Y: 450,\n POWERUP_X: 610,\n POWERUP_Y: 450,\n};\n","import { PakArchive, Pic, Renderer } from '@quake2ts/engine';\n\nlet crosshairPic: Pic | null = null;\n\nexport const Init_Crosshair = async (renderer: Renderer, pak: PakArchive) => {\n try {\n const data = pak.readFile('pics/crosshair.pcx');\n crosshairPic = await renderer.registerPic('crosshair', data.buffer as ArrayBuffer);\n } catch (e) {\n console.error('Failed to load crosshair image: pics/crosshair.pcx');\n }\n}\n\nexport const Draw_Crosshair = (renderer: Renderer, width: number, height: number) => {\n if (crosshairPic) {\n const x = (width - crosshairPic.width) / 2;\n const y = (height - crosshairPic.height) / 2;\n renderer.drawPic(x, y, crosshairPic);\n }\n};\n","import { PakArchive, Pic, Renderer } from '@quake2ts/engine';\nimport { PlayerClient, WEAPON_ITEMS, WeaponItem, PowerupId } from '@quake2ts/game';\nimport { HUD_LAYOUT } from './layout.js';\n\nconst iconPics = new Map<string, Pic>();\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\nexport const Init_Icons = async (renderer: Renderer, pak: PakArchive) => {\n for (const name of ICON_NAMES) {\n try {\n const data = pak.readFile(`pics/${name}.pcx`);\n const pic = await renderer.registerPic(name, data.buffer as ArrayBuffer);\n iconPics.set(name, pic);\n } catch (e) {\n console.error(`Failed to load HUD image: pics/${name}.pcx`);\n }\n }\n};\n\nexport const Draw_Icons = (renderer: Renderer, client: PlayerClient) => {\n if (!client) {\n return;\n }\n\n // Draw current weapon icon\n const currentWeapon = client.inventory.currentWeapon;\n if (currentWeapon) {\n const weaponDef = Object.values(WEAPON_ITEMS).find((w: WeaponItem) => w.weaponId === currentWeapon);\n if (weaponDef) {\n const iconName = `w_${weaponDef.id.substring(7)}`;\n const icon = iconPics.get(iconName);\n if (icon) {\n renderer.drawPic(HUD_LAYOUT.WEAPON_ICON_X, HUD_LAYOUT.WEAPON_ICON_Y, icon);\n }\n }\n }\n\n // Draw powerup icons\n let powerupX = HUD_LAYOUT.POWERUP_X;\n for (const [powerup, timer] of client.inventory.powerups.entries()) {\n if (timer && timer > 0) {\n const iconName = `p_${powerup}`;\n const icon = iconPics.get(iconName);\n if (icon) {\n renderer.drawPic(powerupX, HUD_LAYOUT.POWERUP_Y, icon);\n powerupX -= (icon.width + 4); // Move to the left for the next icon\n }\n }\n }\n};\n","import { PakArchive, Pic, Renderer } from '@quake2ts/engine';\nimport { PlayerState, angleVectors, dotVec3, Vec3 } from '@quake2ts/shared';\n\nconst damagePics = new Map<string, Pic>();\n\nconst DAMAGE_INDICATOR_NAMES = [\n 'd_left', 'd_right', 'd_up', 'd_down'\n];\n\nexport const Init_Damage = async (renderer: Renderer, pak: PakArchive) => {\n for (const name of DAMAGE_INDICATOR_NAMES) {\n try {\n const data = pak.readFile(`pics/${name}.pcx`);\n const pic = await renderer.registerPic(name, data.buffer as ArrayBuffer);\n damagePics.set(name, pic);\n } catch (e) {\n console.error(`Failed to load HUD image: pics/${name}.pcx`);\n }\n }\n};\n\nexport const Draw_Damage = (renderer: Renderer, ps: PlayerState) => {\n if (!ps.damageIndicators) {\n return;\n }\n\n const screenWidth = renderer.width;\n const screenHeight = renderer.height;\n\n const { forward, right, up } = angleVectors(ps.viewAngles);\n\n for (const indicator of ps.damageIndicators) {\n const { direction, strength } = indicator;\n\n const normalizedDirection = { ...direction };\n const len = Math.sqrt(normalizedDirection.x * normalizedDirection.x + normalizedDirection.y * normalizedDirection.y + normalizedDirection.z * normalizedDirection.z);\n if (len > 0) {\n normalizedDirection.x /= len;\n normalizedDirection.y /= len;\n normalizedDirection.z /= len;\n }\n\n const rightDot = dotVec3(normalizedDirection, right);\n const forwardDot = dotVec3(normalizedDirection, forward);\n\n const angle = Math.atan2(forwardDot, rightDot) * 180 / Math.PI;\n\n let pic: Pic | undefined;\n let x = 0;\n let y = 0;\n\n if (angle > -45 && angle <= 45) {\n pic = damagePics.get('d_right');\n x = screenWidth - (pic?.width || 0);\n y = (screenHeight - (pic?.height || 0)) / 2;\n } else if (angle > 45 && angle <= 135) {\n pic = damagePics.get('d_up');\n x = (screenWidth - (pic?.width || 0)) / 2;\n y = 0;\n } else if (angle > 135 || angle <= -135) {\n pic = damagePics.get('d_left');\n x = 0;\n y = (screenHeight - (pic?.height || 0)) / 2;\n } else {\n pic = damagePics.get('d_down');\n x = (screenWidth - (pic?.width || 0)) / 2;\n y = screenHeight - (pic?.height || 0);\n }\n \n if (pic) {\n renderer.drawPic(x, y, pic);\n }\n }\n};\n","import { Renderer, FrameRenderStats } from '@quake2ts/engine';\n\nexport const Draw_Diagnostics = (renderer: Renderer, stats: FrameRenderStats) => {\n const lines = [\n `FPS: ${stats.fps}`,\n `Draw Calls: ${stats.drawCalls}`,\n `Batches: ${stats.batches}`,\n `Faces Drawn: ${stats.facesDrawn}`,\n `Vertices: ${stats.vertexCount}`,\n ];\n\n let y = 10;\n for (const line of lines) {\n renderer.drawString(10, y, line);\n y += 10;\n }\n};\n","import { PakArchive, FrameRenderStats } from '@quake2ts/engine';\nimport { Pic, Renderer } from '@quake2ts/engine';\nimport { PlayerClient } from '@quake2ts/game';\nimport { PlayerState } from '@quake2ts/shared';\nimport { Draw_Number } from './hud/numbers.js';\nimport { HUD_LAYOUT } from './hud/layout.js';\nimport { Draw_Crosshair, Init_Crosshair } from './hud/crosshair.js';\nimport { Draw_Icons, Init_Icons } from './hud/icons.js';\nimport { Draw_Damage, Init_Damage } from './hud/damage.js';\nimport { Draw_Diagnostics } from './hud/diagnostics.js';\n\nconst hudNumberPics: Pic[] = [];\nlet numberWidth = 0;\n\nexport const Init_Hud = async (renderer: Renderer, pak: PakArchive) => {\n for (let i = 0; i < 10; i++) {\n try {\n const data = pak.readFile(`pics/hud/num_${i}.pcx`);\n const pic = await renderer.registerPic(`hud_num_${i}`, data.buffer as ArrayBuffer);\n hudNumberPics.push(pic);\n } catch (e) {\n console.error(`Failed to load HUD image: pics/hud/num_${i}.pcx`);\n }\n }\n if (hudNumberPics[0]) {\n numberWidth = hudNumberPics[0].width;\n }\n\n await Init_Crosshair(renderer, pak);\n await Init_Icons(renderer, pak);\n await Init_Damage(renderer, pak);\n};\n\nexport const Draw_Hud = (renderer: Renderer, ps: PlayerState, client: PlayerClient, health: number, armor: number, ammo: number, stats: FrameRenderStats) => {\n renderer.begin2D();\n\n if (ps.damageAlpha > 0) {\n renderer.drawfillRect(0, 0, renderer.width, renderer.height, [1, 0, 0, ps.damageAlpha]);\n }\n\n Draw_Number(renderer, HUD_LAYOUT.HEALTH_X, HUD_LAYOUT.HEALTH_Y, health, hudNumberPics, numberWidth);\n Draw_Number(renderer, HUD_LAYOUT.ARMOR_X, HUD_LAYOUT.ARMOR_Y, armor, hudNumberPics, numberWidth);\n Draw_Number(renderer, HUD_LAYOUT.AMMO_X, HUD_LAYOUT.AMMO_Y, ammo, hudNumberPics, numberWidth);\n Draw_Icons(renderer, client);\n Draw_Damage(renderer, ps);\n Draw_Diagnostics(renderer, stats);\n\n if (ps.centerPrint) {\n renderer.drawCenterString(renderer.height / 2 - 20, ps.centerPrint);\n }\n\n if (ps.notify) {\n renderer.drawString(8, 8, ps.notify);\n }\n\n Draw_Crosshair(renderer, renderer.width, renderer.height);\n renderer.end2D();\n};\n","export type InputCode = string;\n\nexport interface BindingEntry {\n readonly code: InputCode;\n readonly command: string;\n}\n\nconst DEFAULT_BINDINGS: readonly BindingEntry[] = [\n { code: 'KeyW', command: '+forward' },\n { code: 'ArrowUp', command: '+forward' },\n { code: 'KeyS', command: '+back' },\n { code: 'ArrowDown', command: '+back' },\n { code: 'KeyA', command: '+moveleft' },\n { code: 'KeyD', command: '+moveright' },\n { code: 'Space', command: '+jump' },\n { code: 'ControlLeft', command: '+crouch' },\n { code: 'ShiftLeft', command: '+speed' },\n { code: 'Mouse1', command: '+attack' },\n { code: 'Mouse2', command: '+use' },\n { code: 'Mouse3', command: '+zoom' },\n { code: 'ArrowLeft', command: '+left' },\n { code: 'ArrowRight', command: '+right' },\n { code: 'PageUp', command: '+lookup' },\n { code: 'PageDown', command: '+lookdown' },\n { code: 'Gamepad0-Button7', command: '+attack' },\n { code: 'Gamepad0-Button6', command: '+zoom' },\n { code: 'Gamepad0-Button0', command: '+jump' },\n { code: 'Gamepad0-Button1', command: '+crouch' },\n { code: 'Gamepad0-Button2', command: '+use' },\n { code: 'Gamepad0-Button4', command: 'prevweapon' },\n { code: 'Gamepad0-Button5', command: 'nextweapon' },\n { code: 'Digit1', command: 'weapon 1' },\n { code: 'Digit2', command: 'weapon 2' },\n { code: 'Digit3', command: 'weapon 3' },\n { code: 'Digit4', command: 'weapon 4' },\n { code: 'Digit5', command: 'weapon 5' },\n { code: 'Digit6', command: 'weapon 6' },\n { code: 'Digit7', command: 'weapon 7' },\n { code: 'Digit8', command: 'weapon 8' },\n { code: 'Digit9', command: 'weapon 9' },\n { code: 'Digit0', command: 'weapon 10' },\n];\n\nexport type BindingMap = ReadonlyMap<InputCode, string>;\n\nexport class InputBindings {\n private readonly bindings = new Map<InputCode, string>();\n\n constructor(entries: Iterable<BindingEntry> = DEFAULT_BINDINGS) {\n for (const entry of entries) {\n this.bind(entry.code, entry.command);\n }\n }\n\n bind(code: InputCode, command: string): void {\n this.bindings.set(code, command);\n }\n\n unbind(code: InputCode): void {\n this.bindings.delete(code);\n }\n\n getBinding(code: InputCode): string | undefined {\n return this.bindings.get(code);\n }\n\n entries(): BindingMap {\n return new Map(this.bindings.entries());\n }\n}\n\nexport function createDefaultBindings(): InputBindings {\n return new InputBindings();\n}\n\nexport function normalizeInputCode(code: string): InputCode {\n return code;\n}\n\nexport function normalizeCommand(command: string): string {\n return command.trim().toLowerCase();\n}\n\n","import {\n DEFAULT_FORWARD_SPEED,\n DEFAULT_MOUSE_SENSITIVITY,\n DEFAULT_PITCH_SPEED,\n DEFAULT_SIDE_SPEED,\n DEFAULT_UP_SPEED,\n DEFAULT_YAW_SPEED,\n PlayerButton,\n addViewAngles,\n mouseDeltaToViewDelta,\n type MouseDelta,\n type UserCommand,\n type Vec3,\n} from '@quake2ts/shared';\nimport { InputBindings, normalizeCommand, normalizeInputCode, type InputCode } from './bindings.js';\n\nconst MSEC_MAX = 250;\n\nexport interface GamepadLikeButton {\n readonly pressed: boolean;\n readonly value: number;\n}\n\nexport interface GamepadLike {\n readonly axes: readonly number[];\n readonly buttons: readonly GamepadLikeButton[];\n readonly index?: number;\n readonly connected?: boolean;\n}\n\ninterface ButtonState {\n readonly active: boolean;\n readonly wasPressed: boolean;\n readonly fraction: number;\n}\n\nexport interface TouchInputState {\n readonly move?: { readonly x: number; readonly y: number };\n readonly look?: { readonly x: number; readonly y: number };\n readonly buttons?: Partial<Record<InputAction, boolean>>;\n}\n\nclass KeyButton {\n private readonly activeCodes = new Set<InputCode>();\n private downTime = 0;\n private msec = 0;\n private pressed = false;\n\n press(code: InputCode, now: number): boolean {\n if (this.activeCodes.has(code)) return false;\n\n this.activeCodes.add(code);\n this.pressed = true;\n if (this.activeCodes.size === 1) {\n this.downTime = now;\n return true;\n }\n\n return false;\n }\n\n release(code: InputCode, now: number): boolean {\n if (!this.activeCodes.delete(code)) return false;\n\n if (this.activeCodes.size === 0) {\n this.msec += now - this.downTime;\n this.downTime = 0;\n return true;\n }\n\n return false;\n }\n\n sample(frameMsec: number, now: number): ButtonState {\n if (frameMsec <= 0) {\n return { active: this.activeCodes.size > 0, wasPressed: this.pressed, fraction: 0 };\n }\n\n let total = this.msec;\n\n if (this.activeCodes.size > 0) {\n total += now - this.downTime;\n this.downTime = now;\n }\n\n this.msec = 0;\n\n const fraction = Math.min(total / frameMsec, 1);\n const wasPressed = this.pressed;\n this.pressed = false;\n\n return { active: this.activeCodes.size > 0, wasPressed, fraction };\n }\n}\n\nexport interface InputControllerOptions {\n readonly forwardSpeed?: number;\n readonly sideSpeed?: number;\n readonly upSpeed?: number;\n readonly yawSpeed?: number;\n readonly pitchSpeed?: number;\n readonly sensitivity?: number;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n readonly invertMouseY?: boolean;\n readonly runByDefault?: boolean;\n readonly requirePointerLock?: boolean;\n readonly jumpAddsUpMove?: boolean;\n readonly crouchAddsDownMove?: boolean;\n readonly mouseFilter?: boolean;\n readonly getGamepads?: () => readonly (GamepadLike | null | undefined)[];\n readonly gamepadDeadZone?: number;\n readonly gamepadLookScale?: number;\n readonly invertGamepadY?: boolean;\n}\n\nexport enum InputAction {\n Forward = '+forward',\n Back = '+back',\n MoveLeft = '+moveleft',\n MoveRight = '+moveright',\n MoveUp = '+moveup',\n MoveDown = '+movedown',\n Jump = '+jump',\n Crouch = '+crouch',\n Attack = '+attack',\n Use = '+use',\n Holster = '+holster',\n TurnLeft = '+left',\n TurnRight = '+right',\n LookUp = '+lookup',\n LookDown = '+lookdown',\n SpeedModifier = '+speed',\n Zoom = '+zoom',\n}\n\nconst BUTTON_ACTIONS: Partial<Record<InputAction, PlayerButton>> = {\n [InputAction.Attack]: PlayerButton.Attack,\n [InputAction.Use]: PlayerButton.Use,\n [InputAction.Holster]: PlayerButton.Holster,\n [InputAction.Jump]: PlayerButton.Jump,\n [InputAction.Crouch]: PlayerButton.Crouch,\n};\n\nconst ACTION_LOOKUP = new Map<string, InputAction>(\n Object.values(InputAction).map((action) => [normalizeCommand(action), action]),\n);\n\nfunction commandToAction(command: string): InputAction | undefined {\n return ACTION_LOOKUP.get(normalizeCommand(command));\n}\n\nfunction nowMs(): number {\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n return performance.now();\n }\n\n return Date.now();\n}\n\nexport class InputController {\n private readonly bindings: InputBindings;\n private readonly buttons = new Map<InputAction, KeyButton>();\n private viewAngles: Vec3 = { x: 0, y: 0, z: 0 };\n private pointerLocked = false;\n private mouseDelta: MouseDelta = { deltaX: 0, deltaY: 0 };\n private previousMouseDelta: MouseDelta = { deltaX: 0, deltaY: 0 };\n private anyPressed = false;\n private commandQueue: string[] = [];\n private pendingGamepads: readonly (GamepadLike | null | undefined)[] | undefined;\n private readonly gamepadButtons = new Map<string, boolean>();\n private gamepadMove = { x: 0, y: 0 };\n private gamepadLook = { x: 0, y: 0 };\n private pendingTouchState: TouchInputState | undefined;\n private readonly touchButtons = new Map<InputAction, boolean>();\n private touchMove = { x: 0, y: 0 };\n private touchLook = { x: 0, y: 0 };\n\n private readonly forwardSpeed: number;\n private readonly sideSpeed: number;\n private readonly upSpeed: number;\n private readonly yawSpeed: number;\n private readonly pitchSpeed: number;\n private readonly sensitivity: number;\n private readonly sensitivityX?: number;\n private readonly sensitivityY?: number;\n private readonly invertMouseY: boolean;\n private readonly runByDefault: boolean;\n private readonly requirePointerLock: boolean;\n private readonly jumpAddsUpMove: boolean;\n private readonly crouchAddsDownMove: boolean;\n private readonly mouseFilter: boolean;\n private readonly getGamepads?: () => readonly (GamepadLike | null | undefined)[];\n private readonly gamepadDeadZone: number;\n private readonly gamepadLookScale: number;\n private readonly invertGamepadY: boolean;\n\n constructor(options: InputControllerOptions = {}, bindings = new InputBindings()) {\n this.bindings = bindings;\n this.forwardSpeed = options.forwardSpeed ?? DEFAULT_FORWARD_SPEED;\n this.sideSpeed = options.sideSpeed ?? DEFAULT_SIDE_SPEED;\n this.upSpeed = options.upSpeed ?? DEFAULT_UP_SPEED;\n this.yawSpeed = options.yawSpeed ?? DEFAULT_YAW_SPEED;\n this.pitchSpeed = options.pitchSpeed ?? DEFAULT_PITCH_SPEED;\n this.sensitivity = options.sensitivity ?? DEFAULT_MOUSE_SENSITIVITY;\n this.sensitivityX = options.sensitivityX;\n this.sensitivityY = options.sensitivityY;\n this.invertMouseY = options.invertMouseY ?? false;\n this.runByDefault = options.runByDefault ?? true;\n this.requirePointerLock = options.requirePointerLock ?? true;\n this.jumpAddsUpMove = options.jumpAddsUpMove ?? true;\n this.crouchAddsDownMove = options.crouchAddsDownMove ?? true;\n this.mouseFilter = options.mouseFilter ?? false;\n this.getGamepads = options.getGamepads;\n this.gamepadDeadZone = options.gamepadDeadZone ?? 0.15;\n this.gamepadLookScale = options.gamepadLookScale ?? 1;\n this.invertGamepadY = options.invertGamepadY ?? this.invertMouseY;\n }\n\n handleKeyDown(code: string, eventTimeMs: number = nowMs()): void {\n const normalized = normalizeInputCode(code);\n const binding = this.bindings.getBinding(normalized);\n if (!binding) return;\n\n this.applyCommand(binding, true, normalized, eventTimeMs);\n }\n\n handleKeyUp(code: string, eventTimeMs: number = nowMs()): void {\n const normalized = normalizeInputCode(code);\n const binding = this.bindings.getBinding(normalized);\n if (!binding) return;\n\n this.applyCommand(binding, false, normalized, eventTimeMs);\n }\n\n handleMouseButtonDown(button: number, eventTimeMs: number = nowMs()): void {\n const code = this.mouseButtonToCode(button);\n this.applyCommand(this.mouseButtonToCommand(code), true, code, eventTimeMs);\n }\n\n handleMouseButtonUp(button: number, eventTimeMs: number = nowMs()): void {\n const code = this.mouseButtonToCode(button);\n this.applyCommand(this.mouseButtonToCommand(code), false, code, eventTimeMs);\n }\n\n handleMouseMove(deltaX: number, deltaY: number): void {\n if (this.requirePointerLock && !this.pointerLocked) return;\n\n this.mouseDelta = {\n deltaX: this.mouseDelta.deltaX + deltaX,\n deltaY: this.mouseDelta.deltaY + deltaY,\n };\n }\n\n setPointerLocked(locked: boolean): void {\n this.pointerLocked = locked;\n }\n\n setGamepadState(gamepads: readonly (GamepadLike | null | undefined)[]): void {\n this.pendingGamepads = gamepads;\n }\n\n setTouchState(state: TouchInputState): void {\n this.pendingTouchState = state;\n }\n\n buildCommand(frameMsec: number, now: number = nowMs(), serverFrame?: number): UserCommand {\n this.pollGamepads(now);\n this.applyTouchState(now);\n\n const yawStep = (this.yawSpeed * frameMsec) / 1000;\n const pitchStep = (this.pitchSpeed * frameMsec) / 1000;\n\n const turnLeft = this.sample(InputAction.TurnLeft, frameMsec, now);\n const turnRight = this.sample(InputAction.TurnRight, frameMsec, now);\n const lookUp = this.sample(InputAction.LookUp, frameMsec, now);\n const lookDown = this.sample(InputAction.LookDown, frameMsec, now);\n\n let viewDelta: Vec3 = {\n x: (lookDown.fraction - lookUp.fraction) * pitchStep,\n y: (turnRight.fraction - turnLeft.fraction) * yawStep,\n z: 0,\n };\n\n if (this.gamepadLook.x !== 0 || this.gamepadLook.y !== 0) {\n const pitch = this.gamepadLook.y * (this.invertGamepadY ? -1 : 1);\n viewDelta = {\n x: viewDelta.x + pitch * pitchStep * this.gamepadLookScale,\n y: viewDelta.y + this.gamepadLook.x * yawStep * this.gamepadLookScale,\n z: 0,\n };\n }\n\n if (this.touchLook.x !== 0 || this.touchLook.y !== 0) {\n const pitch = this.touchLook.y * (this.invertMouseY ? -1 : 1);\n viewDelta = {\n x: viewDelta.x + pitch * pitchStep,\n y: viewDelta.y + this.touchLook.x * yawStep,\n z: 0,\n };\n }\n\n if (this.pointerLocked || !this.requirePointerLock) {\n const sampledDelta = this.sampleMouseDelta();\n const mouseDelta = mouseDeltaToViewDelta(sampledDelta, {\n sensitivity: this.sensitivity,\n sensitivityX: this.sensitivityX,\n sensitivityY: this.sensitivityY,\n invertY: this.invertMouseY,\n });\n viewDelta = {\n x: viewDelta.x + mouseDelta.x,\n y: viewDelta.y + mouseDelta.y,\n z: 0,\n };\n }\n\n const angles = addViewAngles(this.viewAngles, viewDelta);\n this.viewAngles = angles;\n\n const forward = this.sample(InputAction.Forward, frameMsec, now);\n const back = this.sample(InputAction.Back, frameMsec, now);\n const moveLeft = this.sample(InputAction.MoveLeft, frameMsec, now);\n const moveRight = this.sample(InputAction.MoveRight, frameMsec, now);\n const moveUp = this.sample(InputAction.MoveUp, frameMsec, now);\n const moveDown = this.sample(InputAction.MoveDown, frameMsec, now);\n const speed = this.sample(InputAction.SpeedModifier, frameMsec, now);\n const jump = this.sample(InputAction.Jump, frameMsec, now);\n const crouch = this.sample(InputAction.Crouch, frameMsec, now);\n\n const speedScale = this.runByDefault\n ? speed.active\n ? 0.5\n : 1\n : speed.active\n ? 1\n : 0.5;\n\n let forwardmove = this.forwardSpeed * (forward.fraction - back.fraction) * speedScale;\n let sidemove = this.sideSpeed * (moveRight.fraction - moveLeft.fraction) * speedScale;\n let upmove = this.upSpeed * (moveUp.fraction - moveDown.fraction);\n\n if (this.gamepadMove.x !== 0 || this.gamepadMove.y !== 0) {\n forwardmove += this.forwardSpeed * this.gamepadMove.y * speedScale;\n sidemove += this.sideSpeed * this.gamepadMove.x * speedScale;\n }\n\n if (this.touchMove.x !== 0 || this.touchMove.y !== 0) {\n forwardmove += this.forwardSpeed * this.touchMove.y * speedScale;\n sidemove += this.sideSpeed * this.touchMove.x * speedScale;\n }\n\n if (this.jumpAddsUpMove && jump.fraction > 0) {\n upmove += this.upSpeed * jump.fraction;\n }\n\n if (this.crouchAddsDownMove && crouch.fraction > 0) {\n upmove -= this.upSpeed * crouch.fraction;\n }\n\n forwardmove = this.clampMove(forwardmove, this.forwardSpeed);\n sidemove = this.clampMove(sidemove, this.sideSpeed);\n upmove = this.clampMove(upmove, this.upSpeed);\n\n let buttons = this.collectButtonBits(frameMsec, now);\n\n const msec = Math.min(Math.max(Math.round(frameMsec), 1), MSEC_MAX);\n\n if (this.anyPressed || buttons !== PlayerButton.None) {\n buttons |= PlayerButton.Any;\n }\n\n this.anyPressed = false;\n\n return {\n msec,\n buttons,\n angles: { ...this.viewAngles },\n forwardmove,\n sidemove,\n upmove,\n serverFrame,\n } satisfies UserCommand;\n }\n\n consumeConsoleCommands(): readonly string[] {\n const commands = this.commandQueue;\n this.commandQueue = [];\n return commands;\n }\n\n private pollGamepads(now: number): void {\n const gamepads = this.getGamepads?.() ?? this.pendingGamepads ?? [];\n this.pendingGamepads = undefined;\n\n this.gamepadMove = { x: 0, y: 0 };\n this.gamepadLook = { x: 0, y: 0 };\n\n const pressedThisFrame = new Set<InputCode>();\n\n for (const pad of gamepads) {\n if (!pad || pad.connected === false) continue;\n\n const index = pad.index ?? 0;\n const axes = pad.axes ?? [];\n\n this.gamepadMove = {\n x: this.mergeAnalog(this.gamepadMove.x, this.applyDeadZone(axes[0] ?? 0)),\n y: this.mergeAnalog(this.gamepadMove.y, -this.applyDeadZone(axes[1] ?? 0)),\n };\n\n this.gamepadLook = {\n x: this.mergeAnalog(this.gamepadLook.x, this.applyDeadZone(axes[2] ?? 0)),\n y: this.mergeAnalog(this.gamepadLook.y, this.applyDeadZone(axes[3] ?? 0)),\n };\n\n const buttons = pad.buttons ?? [];\n for (let i = 0; i < buttons.length; i++) {\n const button = buttons[i];\n if (!button) continue;\n\n const pressed = button.pressed || button.value > this.gamepadDeadZone;\n const code = this.gamepadButtonCode(index, i);\n if (pressed) pressedThisFrame.add(code);\n\n const wasPressed = this.gamepadButtons.get(code) ?? false;\n if (pressed !== wasPressed) {\n this.applyCommand(this.bindings.getBinding(code), pressed, code, now);\n this.gamepadButtons.set(code, pressed);\n }\n }\n }\n\n for (const [code, wasPressed] of this.gamepadButtons.entries()) {\n if (wasPressed && !pressedThisFrame.has(code)) {\n this.applyCommand(this.bindings.getBinding(code), false, code, now);\n this.gamepadButtons.set(code, false);\n }\n }\n }\n\n private applyTouchState(now: number): void {\n const state = this.pendingTouchState;\n if (!state) return;\n\n this.pendingTouchState = undefined;\n\n if (state.move) {\n this.touchMove = {\n x: this.clampAnalog(state.move.x),\n y: this.clampAnalog(state.move.y),\n };\n }\n\n if (state.look) {\n this.touchLook = {\n x: this.clampAnalog(state.look.x),\n y: this.clampAnalog(state.look.y),\n };\n }\n\n if (state.buttons) {\n for (const [action, pressed] of Object.entries(state.buttons) as Array<\n [InputAction, boolean | undefined]\n >) {\n if (pressed === undefined) continue;\n\n const wasPressed = this.touchButtons.get(action) ?? false;\n if (pressed !== wasPressed) {\n this.applyCommand(action, pressed, this.touchButtonCode(action), now);\n this.touchButtons.set(action, pressed);\n }\n }\n }\n }\n\n private applyCommand(\n command: string | undefined,\n isDown: boolean,\n code: InputCode,\n eventTimeMs: number,\n ): void {\n if (!command) return;\n\n const action = commandToAction(command);\n if (action) {\n const button = this.lookupButton(action);\n if (isDown) {\n if (button.press(code, eventTimeMs)) {\n this.commandQueue.push(action);\n }\n this.anyPressed = true;\n } else if (button.release(code, eventTimeMs)) {\n this.commandQueue.push(action.replace('+', '-'));\n }\n } else if (isDown) {\n this.commandQueue.push(command);\n }\n }\n\n private sampleMouseDelta(): MouseDelta {\n const delta = this.mouseDelta;\n this.mouseDelta = { deltaX: 0, deltaY: 0 };\n\n if (!this.mouseFilter) {\n this.previousMouseDelta = delta;\n return delta;\n }\n\n const filtered = {\n deltaX: (delta.deltaX + this.previousMouseDelta.deltaX) * 0.5,\n deltaY: (delta.deltaY + this.previousMouseDelta.deltaY) * 0.5,\n } satisfies MouseDelta;\n\n this.previousMouseDelta = delta;\n return filtered;\n }\n\n private collectButtonBits(frameMsec: number, now: number): PlayerButton {\n let buttons = PlayerButton.None;\n\n for (const [action, bit] of Object.entries(BUTTON_ACTIONS) as Array<\n [InputAction, PlayerButton]\n >) {\n const sample = this.sample(action, frameMsec, now);\n if (sample.fraction > 0 || sample.active || sample.wasPressed) {\n buttons |= bit;\n }\n }\n\n return buttons;\n }\n\n private lookupButton(action: InputAction): KeyButton {\n let button = this.buttons.get(action);\n if (!button) {\n button = new KeyButton();\n this.buttons.set(action, button);\n }\n return button;\n }\n\n private mouseButtonToCode(button: number): InputCode {\n if (button === 0) return 'Mouse1';\n if (button === 1) return 'Mouse3';\n if (button === 2) return 'Mouse2';\n return `Mouse${button + 1}`;\n }\n\n private mouseButtonToCommand(code: InputCode): string | undefined {\n return this.bindings.getBinding(code);\n }\n\n private sample(action: InputAction, frameMsec: number, now: number): ButtonState {\n const button = this.lookupButton(action);\n return button.sample(frameMsec, now);\n }\n\n private gamepadButtonCode(index: number, button: number): InputCode {\n return `Gamepad${index}-Button${button}`;\n }\n\n private touchButtonCode(action: InputAction): InputCode {\n return `Touch-${action}`;\n }\n\n private clampAnalog(value: number): number {\n return Math.max(-1, Math.min(1, value));\n }\n\n private applyDeadZone(value: number): number {\n return Math.abs(value) < this.gamepadDeadZone ? 0 : value;\n }\n\n private mergeAnalog(current: number, incoming: number): number {\n return Math.abs(incoming) > Math.abs(current) ? incoming : current;\n }\n\n private clampMove(value: number, max: number): number {\n return Math.max(-max, Math.min(max, value));\n }\n}\n\n","import type { UserCommand } from '@quake2ts/shared';\nimport { InputController, type InputControllerOptions } from './controller.js';\n\nexport interface QueuedFrameCommands {\n readonly command: UserCommand;\n readonly console: readonly string[];\n}\n\nexport class InputCommandBuffer {\n private readonly controller: InputController;\n private readonly queued: QueuedFrameCommands[] = [];\n\n constructor(options?: InputControllerOptions, controller = new InputController(options)) {\n this.controller = controller;\n }\n\n captureFrame(frameMsec: number, now?: number, serverFrame?: number): QueuedFrameCommands {\n const command = this.controller.buildCommand(frameMsec, now, serverFrame);\n const console = this.controller.consumeConsoleCommands();\n const entry: QueuedFrameCommands = { command, console };\n this.queued.push(entry);\n return entry;\n }\n\n consumeQueued(): readonly QueuedFrameCommands[] {\n const queued = [...this.queued];\n this.queued.length = 0;\n return queued;\n }\n\n getController(): InputController {\n return this.controller;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMO,IAAI,UAAU;AACd,IAAI,aAAa,OAAO,iBA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a;AAAA,UACrB,UAAU,aAAa;AAAA,UACvB,YAAY,aAAa;AAAA,UACzB,UAAU,UAAU,aAAa,SAAS,OAAO,QAAQ;AAAA,UACzD,YAAY,aAAa;AAAA,UACzB,MAAM,EAAE,GAAG,KAAK,GAAG,KAAK,GAAG,IAAI;AAAA,UAC/B,MAAM,EAAE,GAAG,IAAI,GAAG,IAAI,GAAG,GAAG;AAAA,UAC5B,aAAa;AAAA,UACb,kBAAkB,CAAC;AAAA,QACvB;AACA,iBAAS,QAAQ,OAAO,UAAU,aAAa,aAAa,QAAQ,aAAa,QAAQ,aAAa,OAAO,aAAa,MAAM,KAAK;AAAA,MACvI;AAEA,WAAK;AACL,WAAK;AAEL,aAAO;AAAA,IACT;AAAA,IACA,WAAW;AACT,oBAAc;AACd,qBAAe;AAAA,IACjB;AAAA,IACA,IAAI,aAA+B;AACjC,aAAO;AAAA,IACT;AAAA,IACA,IAAI,eAA4C;AAC9C,aAAO;AAAA,IACT;AAAA,IACA,IAAI,OAAoB;AACtB,aAAO;AAAA,IACT;AAAA,IACA,IAAI,WAAmC;AACrC,aAAO;AAAA,IACT;AAAA,IACA,IAAI,SAA6B;AAC/B,aAAO;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;","names":["len","scale","add","clone","copy","create","equals","exactEquals","fromValues","mul","multiply","rotateX","rotateY","rotateZ","round","scale","set","str","sub","subtract","create","clone","fromValues","copy","set","add","subtract","multiply","round","scale","len","angle","rotateX","rotateY","rotateZ","str","exactEquals","equals","sub","mul","ConfigStringIndex","ServerCommand","TempEntity","str","length","HEADER_SIZE","HEADER_SIZE","length","str","MAX_ITEMS","DEG_TO_RAD","len","DEG2RAD_FACTOR","RAD2DEG_FACTOR","DEG2RAD_FACTOR","angle","CONTENTS_SOLID","CONTENTS_WINDOW","CONTENTS_AUX","CONTENTS_LAVA","CONTENTS_SLIME","CONTENTS_WATER","CONTENTS_MIST","CONTENTS_NO_WATERJUMP","CONTENTS_PROJECTILECLIP","CONTENTS_AREAPORTAL","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_LIGHT","SURF_SLICK","SURF_SKY","SURF_WARP","SURF_TRANS33","SURF_TRANS66","SURF_FLOWING","SURF_NODRAW","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","WaterLevel","PmFlag","PmType","PlayerButton","scale","scale","WATERJUMP_CLEAR","clampPitch","ZERO_VEC3","lerp","len","angle","MSEC_MAX","InputAction","max","console"]}