quake2ts 0.0.577 → 0.0.580
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/packages/client/dist/browser/index.global.js +16 -16
- package/packages/client/dist/browser/index.global.js.map +1 -1
- package/packages/client/dist/cjs/index.cjs +0 -1
- package/packages/client/dist/cjs/index.cjs.map +1 -1
- package/packages/client/dist/esm/index.js +0 -1
- package/packages/client/dist/esm/index.js.map +1 -1
- package/packages/client/dist/tsconfig.tsbuildinfo +1 -1
- package/packages/engine/dist/browser/index.global.js +11 -11
- package/packages/engine/dist/browser/index.global.js.map +1 -1
- package/packages/engine/dist/cjs/index.cjs +4 -167
- package/packages/engine/dist/cjs/index.cjs.map +1 -1
- package/packages/engine/dist/esm/index.js +4 -167
- package/packages/engine/dist/esm/index.js.map +1 -1
- package/packages/engine/dist/tsconfig.tsbuildinfo +1 -1
- package/packages/engine/dist/types/assets/md2.d.ts +5 -1
- package/packages/engine/dist/types/assets/md2.d.ts.map +1 -1
- package/packages/engine/dist/types/render/renderer.d.ts +1 -0
- package/packages/engine/dist/types/render/renderer.d.ts.map +1 -1
- package/packages/game/dist/tsconfig.tsbuildinfo +1 -1
- package/packages/test-utils/dist/index.cjs +242 -147
- package/packages/test-utils/dist/index.cjs.map +1 -1
- package/packages/test-utils/dist/index.d.cts +146 -2
- package/packages/test-utils/dist/index.d.ts +146 -2
- package/packages/test-utils/dist/index.js +241 -147
- package/packages/test-utils/dist/index.js.map +1 -1
- package/packages/tools/dist/browser/index.global.js +212 -2
- package/packages/tools/dist/browser/index.global.js.map +1 -1
- package/packages/tools/dist/cjs/index.cjs +971 -2
- package/packages/tools/dist/cjs/index.cjs.map +1 -1
- package/packages/tools/dist/esm/index.js +969 -1
- package/packages/tools/dist/esm/index.js.map +1 -1
- package/packages/tools/dist/tsconfig.tsbuildinfo +1 -1
- package/packages/tools/dist/types/bspTools.d.ts +9 -0
- package/packages/tools/dist/types/bspTools.d.ts.map +1 -0
- package/packages/tools/dist/types/index.d.ts +1 -0
- package/packages/tools/dist/types/index.d.ts.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts","../../src/modelExport.ts"],"sourcesContent":["import type { Vec3 } from '@quake2ts/shared';\n\nexport interface AssetSummary {\n readonly name: string;\n readonly origin?: Vec3;\n}\n\nexport function describeAsset(name: string, origin?: Vec3): AssetSummary {\n return { name, origin };\n}\n\nexport { exportMd2ToObj, exportMd3ToGltf } from './modelExport.js';\n","import { Md2Model, Md3Model } from '@quake2ts/engine';\n\n/**\n * Export MD2 model frame to OBJ format\n * @param model Parsed MD2 model\n * @param frameIndex Frame index to export\n * @returns OBJ file contents as string\n */\nexport function exportMd2ToObj(model: Md2Model, frameIndex: number): string {\n if (frameIndex < 0 || frameIndex >= model.frames.length) {\n throw new Error(`Frame index ${frameIndex} out of bounds (0-${model.frames.length - 1})`);\n }\n\n const frame = model.frames[frameIndex];\n const lines: string[] = [];\n\n lines.push(`# Quake 2 MD2 to OBJ Export`);\n lines.push(`# Model: ${model.header.skinWidth}x${model.header.skinHeight}`);\n lines.push(`# Frame: ${frameIndex} (${frame.name})`);\n lines.push(`o ${frame.name}`);\n\n // Write vertices\n // OBJ vertices are \"v x y z\"\n // Quake uses Z-up, Y-forward? No, Quake is Z-up. OBJ is typically Y-up?\n // Actually, standard OBJ is just points. Tools usually expect Y-up.\n // Quake coords: X=Forward, Y=Left, Z=Up.\n // Blender/Standard: X=Right, Y=Up, Z=Back.\n // We usually export as-is and let the user handle rotation, or swap Y/Z.\n // The request doesn't specify coordinate conversion. I will export as-is (Quake coordinates).\n // Note: MD2 vertices are in local model space.\n for (const v of frame.vertices) {\n lines.push(`v ${v.position.x.toFixed(6)} ${v.position.y.toFixed(6)} ${v.position.z.toFixed(6)}`);\n }\n\n // Write texture coordinates\n // OBJ UVs are \"vt u v\"\n // MD2 tex coords are integers, need to normalize by skin size.\n // Also MD2 (0,0) is top-left, OBJ (0,0) is usually bottom-left.\n // So v = 1 - (t / height).\n const width = model.header.skinWidth;\n const height = model.header.skinHeight;\n for (const tc of model.texCoords) {\n const u = tc.s / width;\n const v = 1.0 - (tc.t / height);\n lines.push(`vt ${u.toFixed(6)} ${v.toFixed(6)}`);\n }\n\n // Write normals\n // MD2 stores normals in frame.vertices[i].normal\n for (const v of frame.vertices) {\n lines.push(`vn ${v.normal.x.toFixed(6)} ${v.normal.y.toFixed(6)} ${v.normal.z.toFixed(6)}`);\n }\n\n // Write faces\n // f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3\n // Indices are 1-based in OBJ.\n lines.push(`s off`); // Smoothing groups off\n for (const tri of model.triangles) {\n const v1 = tri.vertexIndices[0] + 1;\n const v2 = tri.vertexIndices[1] + 1;\n const v3 = tri.vertexIndices[2] + 1;\n\n const vt1 = tri.texCoordIndices[0] + 1;\n const vt2 = tri.texCoordIndices[1] + 1;\n const vt3 = tri.texCoordIndices[2] + 1;\n\n // Normal indices match vertex indices in MD2 (per-vertex normals)\n const vn1 = v1;\n const vn2 = v2;\n const vn3 = v3;\n\n // Reverse winding? Quake is clockwise? OpenGL is CCW.\n // MD2 is usually Clockwise winding for front face?\n // Let's stick to the order in the file.\n lines.push(`f ${v1}/${vt1}/${vn1} ${v2}/${vt2}/${vn2} ${v3}/${vt3}/${vn3}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Export MD3 model to glTF 2.0 format\n * Currently exports the first frame as a static mesh.\n * @param model Parsed MD3 model\n * @returns glTF JSON and binary buffer\n */\nexport function exportMd3ToGltf(model: Md3Model): {\n json: string\n buffer: ArrayBuffer\n} {\n // Structure for GLTF\n const gltf: any = {\n asset: {\n version: \"2.0\",\n generator: \"quake2ts-tools\"\n },\n scenes: [\n {\n nodes: [0]\n }\n ],\n nodes: [\n {\n name: model.header.name,\n mesh: 0\n }\n ],\n meshes: [\n {\n name: model.header.name,\n primitives: []\n }\n ],\n buffers: [\n {\n byteLength: 0 // To be filled\n }\n ],\n bufferViews: [],\n accessors: []\n };\n\n const binaryData: number[] = [];\n\n // Helpers to append data and create views\n const addBufferView = (data: Uint8Array, target?: number) => {\n const byteOffset = binaryData.length;\n // Align to 4 bytes\n while (binaryData.length % 4 !== 0) {\n binaryData.push(0);\n }\n const alignedOffset = binaryData.length;\n for (let i = 0; i < data.length; i++) {\n binaryData.push(data[i]);\n }\n const byteLength = data.length;\n const viewIndex = gltf.bufferViews.length;\n gltf.bufferViews.push({\n buffer: 0,\n byteOffset: alignedOffset,\n byteLength: byteLength,\n target: target\n });\n return viewIndex;\n };\n\n const addAccessor = (bufferView: number, componentType: number, count: number, type: string, min?: number[], max?: number[]) => {\n const index = gltf.accessors.length;\n const acc: any = {\n bufferView,\n componentType, // 5126=FLOAT, 5123=USHORT, 5125=UINT\n count,\n type, // \"SCALAR\", \"VEC2\", \"VEC3\"\n };\n if (min) acc.min = min;\n if (max) acc.max = max;\n gltf.accessors.push(acc);\n return index;\n };\n\n // Process surfaces\n // For each surface, export frame 0 geometry\n // MD3 has separate surfaces which map to GLTF primitives\n\n // We use frame 0\n const frameIndex = 0;\n\n for (const surface of model.surfaces) {\n // Vertices for frame 0\n const frameVerts = surface.vertices[frameIndex];\n\n // Positions (Vec3)\n const positions = new Float32Array(frameVerts.length * 3);\n const normals = new Float32Array(frameVerts.length * 3);\n const texCoords = new Float32Array(frameVerts.length * 2);\n\n let minPos = [Infinity, Infinity, Infinity];\n let maxPos = [-Infinity, -Infinity, -Infinity];\n\n for (let i = 0; i < frameVerts.length; i++) {\n const v = frameVerts[i];\n positions[i * 3] = v.position.x;\n positions[i * 3 + 1] = v.position.y;\n positions[i * 3 + 2] = v.position.z;\n\n minPos[0] = Math.min(minPos[0], v.position.x);\n minPos[1] = Math.min(minPos[1], v.position.y);\n minPos[2] = Math.min(minPos[2], v.position.z);\n maxPos[0] = Math.max(maxPos[0], v.position.x);\n maxPos[1] = Math.max(maxPos[1], v.position.y);\n maxPos[2] = Math.max(maxPos[2], v.position.z);\n\n normals[i * 3] = v.normal.x;\n normals[i * 3 + 1] = v.normal.y;\n normals[i * 3 + 2] = v.normal.z;\n\n // TexCoords (shared across frames in MD3)\n const tc = surface.texCoords[i];\n texCoords[i * 2] = tc.s;\n texCoords[i * 2 + 1] = 1.0 - tc.t; // Flip V\n }\n\n // Indices (Triangles)\n // MD3 indices are per surface\n const indices = new Uint16Array(surface.triangles.length * 3);\n for (let i = 0; i < surface.triangles.length; i++) {\n indices[i * 3] = surface.triangles[i].indices[0];\n indices[i * 3 + 1] = surface.triangles[i].indices[1];\n indices[i * 3 + 2] = surface.triangles[i].indices[2];\n }\n\n // Create BufferViews\n const posView = addBufferView(new Uint8Array(positions.buffer), 34962); // ARRAY_BUFFER\n const normView = addBufferView(new Uint8Array(normals.buffer), 34962);\n const tcView = addBufferView(new Uint8Array(texCoords.buffer), 34962);\n const idxView = addBufferView(new Uint8Array(indices.buffer), 34963); // ELEMENT_ARRAY_BUFFER\n\n // Create Accessors\n const posAcc = addAccessor(posView, 5126, frameVerts.length, \"VEC3\", minPos, maxPos);\n const normAcc = addAccessor(normView, 5126, frameVerts.length, \"VEC3\");\n const tcAcc = addAccessor(tcView, 5126, frameVerts.length, \"VEC2\");\n const idxAcc = addAccessor(idxView, 5123, indices.length, \"SCALAR\");\n\n // Add Primitive\n gltf.meshes[0].primitives.push({\n attributes: {\n POSITION: posAcc,\n NORMAL: normAcc,\n TEXCOORD_0: tcAcc\n },\n indices: idxAcc,\n material: undefined // Could add material info if needed\n });\n }\n\n // Finalize buffer\n // Pad to 4 bytes\n while (binaryData.length % 4 !== 0) {\n binaryData.push(0);\n }\n gltf.buffers[0].byteLength = binaryData.length;\n\n return {\n json: JSON.stringify(gltf, null, 2),\n buffer: new Uint8Array(binaryData).buffer\n };\n}\n"],"mappings":"+bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,mBAAAC,EAAA,oBAAAC,ICQO,SAASC,EAAeC,EAAiBC,EAA4B,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EACT,SAAU,MACZ,CAAC,CACH,CAIA,KAAOjC,EAAW,OAAS,IAAM,GAC/BA,EAAW,KAAK,CAAC,EAEnB,OAAAD,EAAK,QAAQ,CAAC,EAAE,WAAaC,EAAW,OAEjC,CACL,KAAM,KAAK,UAAUD,EAAM,KAAM,CAAC,EAClC,OAAQ,IAAI,WAAWC,CAAU,EAAE,MACrC,CACF,CD/OO,SAASkC,EAAcC,EAAcC,EAA6B,CACvE,MAAO,CAAE,KAAAD,EAAM,OAAAC,CAAO,CACxB","names":["src_exports","__export","describeAsset","exportMd2ToObj","exportMd3ToGltf","exportMd2ToObj","model","frameIndex","frame","lines","v","width","height","tc","u","tri","v1","v2","v3","vt1","vt2","vt3","vn1","vn2","vn3","exportMd3ToGltf","gltf","binaryData","addBufferView","data","target","byteOffset","alignedOffset","i","byteLength","viewIndex","addAccessor","bufferView","componentType","count","type","min","max","index","acc","surface","frameVerts","positions","normals","texCoords","minPos","maxPos","indices","posView","normView","tcView","idxView","posAcc","normAcc","tcAcc","idxAcc","describeAsset","name","origin"]}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../src/modelExport.ts","../../../shared/src/math/vec3.ts","../../../shared/src/math/angles.ts","../../../shared/src/math/anorms.ts","../../../shared/src/math/color.ts","../../../shared/src/math/random.ts","../../../shared/src/math/mat4.ts","../../../shared/src/bsp/contents.ts","../../../shared/src/bsp/spatial.ts","../../../shared/src/bsp/collision.ts","../../../shared/src/protocol/cvar.ts","../../../shared/src/protocol/configstrings.ts","../../../shared/src/replay/index.ts","../../../shared/src/replay/io.ts","../../../shared/src/protocol/contracts.ts","../../../shared/src/pmove/constants.ts","../../../shared/src/pmove/jump.ts","../../../shared/src/pmove/currents.ts","../../../shared/src/pmove/slide.ts","../../../shared/src/pmove/move.ts","../../../shared/src/pmove/water.ts","../../../shared/src/pmove/categorize.ts","../../../shared/src/pmove/dimensions.ts","../../../shared/src/pmove/duck.ts","../../../shared/src/pmove/pmove.ts","../../../shared/src/pmove/stuck.ts","../../../shared/src/pmove/fly.ts","../../../shared/src/pmove/special.ts","../../../shared/src/pmove/snap.ts","../../../shared/src/pmove/view.ts","../../../shared/src/protocol/usercmd.ts","../../../shared/src/protocol/ops.ts","../../../shared/src/protocol/tempEntity.ts","../../../shared/src/protocol/constants.ts","../../../shared/src/protocol/layout.ts","../../../shared/src/protocol/bitpack.ts","../../../shared/src/items/powerups.ts","../../../shared/src/protocol/stats.ts","../../../shared/src/protocol/writeUserCmd.ts","../../../shared/src/protocol/renderFx.ts","../../../shared/src/protocol/crc.ts","../../../shared/src/protocol/effects.ts","../../../shared/src/protocol/entityEvent.ts","../../../shared/src/protocol/entity.ts","../../../shared/src/protocol/player.ts","../../../shared/src/pmove/apply.ts","../../../shared/src/io/binaryStream.ts","../../../shared/src/io/binaryWriter.ts","../../../shared/src/io/messageBuilder.ts","../../../shared/src/net/netchan.ts","../../../shared/src/items/weapons.ts","../../../shared/src/items/ammo.ts","../../../shared/src/items/weaponInfo.ts","../../../shared/src/audio/constants.ts","../../../shared/src/inventory-helpers.ts","../../../shared/src/testing.ts","../../../engine/src/loop.ts","../../../engine/src/commands.ts","../../../shared/src/math/vec3.ts","../../../shared/src/math/angles.ts","../../../shared/src/math/anorms.ts","../../../shared/src/math/color.ts","../../../shared/src/math/random.ts","../../../shared/src/math/mat4.ts","../../../shared/src/bsp/contents.ts","../../../shared/src/bsp/spatial.ts","../../../shared/src/bsp/collision.ts","../../../shared/src/protocol/cvar.ts","../../../shared/src/protocol/configstrings.ts","../../../shared/src/replay/index.ts","../../../shared/src/replay/io.ts","../../../shared/src/protocol/contracts.ts","../../../shared/src/pmove/constants.ts","../../../shared/src/pmove/jump.ts","../../../shared/src/pmove/currents.ts","../../../shared/src/pmove/slide.ts","../../../shared/src/pmove/move.ts","../../../shared/src/pmove/water.ts","../../../shared/src/pmove/categorize.ts","../../../shared/src/pmove/dimensions.ts","../../../shared/src/pmove/duck.ts","../../../shared/src/pmove/pmove.ts","../../../shared/src/pmove/stuck.ts","../../../shared/src/pmove/fly.ts","../../../shared/src/pmove/special.ts","../../../shared/src/pmove/snap.ts","../../../shared/src/pmove/view.ts","../../../shared/src/protocol/usercmd.ts","../../../shared/src/protocol/ops.ts","../../../shared/src/protocol/tempEntity.ts","../../../shared/src/protocol/constants.ts","../../../shared/src/protocol/layout.ts","../../../shared/src/protocol/bitpack.ts","../../../shared/src/items/powerups.ts","../../../shared/src/protocol/stats.ts","../../../shared/src/protocol/writeUserCmd.ts","../../../shared/src/protocol/renderFx.ts","../../../shared/src/protocol/crc.ts","../../../shared/src/protocol/effects.ts","../../../shared/src/protocol/entityEvent.ts","../../../shared/src/protocol/entity.ts","../../../shared/src/protocol/player.ts","../../../shared/src/pmove/apply.ts","../../../shared/src/io/binaryStream.ts","../../../shared/src/io/binaryWriter.ts","../../../shared/src/io/messageBuilder.ts","../../../shared/src/net/netchan.ts","../../../shared/src/items/weapons.ts","../../../shared/src/items/ammo.ts","../../../shared/src/items/weaponInfo.ts","../../../shared/src/audio/constants.ts","../../../shared/src/inventory-helpers.ts","../../../shared/src/testing.ts","../../../engine/src/cvars.ts","../../../engine/src/host.ts","../../../engine/src/configstrings.ts","../../../engine/src/audio/api.ts","../../../engine/src/runtime.ts","../../../engine/src/assets/pak.ts","../../../engine/src/assets/streamingPak.ts","../../../engine/src/assets/pakWriter.ts","../../../engine/src/assets/resourceTracker.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/tga.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/context.ts","../../../engine/src/audio/registry.ts","../../../engine/src/audio/precache.ts","../../../engine/src/audio/channels.ts","../../../engine/src/audio/reverb.ts","../../../engine/src/audio/system.ts","../../../engine/src/audio/occlusion.ts","../../../engine/src/audio/music.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/dlight.ts","../../../engine/src/render/geometry.ts","../../../engine/src/render/bspPipeline.ts","../../../engine/src/render/skybox.ts","../../../engine/src/render/md2Pipeline.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/render/camera.ts","../../../engine/src/render/md3Pipeline.ts","../../../engine/src/render/particleSystem.ts","../../../engine/src/demo/demoReader.ts","../../../../node_modules/.pnpm/pako@2.1.0/node_modules/pako/dist/pako.esm.mjs","../../../engine/src/stream/streamingBuffer.ts","../../../engine/src/demo/parser.ts","../../../engine/src/demo/analysis.ts","../../../engine/src/demo/analyzer.ts","../../../engine/src/demo/camera.ts","../../../engine/src/demo/playback.ts","../../../engine/src/demo/recorder.ts","../../../engine/src/demo/validator.ts","../../../engine/src/demo/writer.ts","../../../engine/src/demo/demoWriter.ts","../../../engine/src/demo/delta.ts","../../../engine/src/demo/clipper.ts","../../../engine/src/assets/fileType.ts","../../../engine/src/assets/preview.ts","../../../engine/src/assets/mapStatistics.ts","../../../engine/src/assets/ent.ts","../../../engine/src/index.ts","../../src/bspTools.ts"],"sourcesContent":["import type { Vec3 } from '@quake2ts/shared';\n\nexport interface AssetSummary {\n readonly name: string;\n readonly origin?: Vec3;\n}\n\nexport function describeAsset(name: string, origin?: Vec3): AssetSummary {\n return { name, origin };\n}\n\nexport { exportMd2ToObj, exportMd3ToGltf } from './modelExport.js';\nexport { replaceBspEntities } from './bspTools.js';\n","import { Md2Model, Md3Model } from '@quake2ts/engine';\n\n/**\n * Export MD2 model frame to OBJ format\n * @param model Parsed MD2 model\n * @param frameIndex Frame index to export\n * @returns OBJ file contents as string\n */\nexport function exportMd2ToObj(model: Md2Model, frameIndex: number): string {\n if (frameIndex < 0 || frameIndex >= model.frames.length) {\n throw new Error(`Frame index ${frameIndex} out of bounds (0-${model.frames.length - 1})`);\n }\n\n const frame = model.frames[frameIndex];\n const lines: string[] = [];\n\n lines.push(`# Quake 2 MD2 to OBJ Export`);\n lines.push(`# Model: ${model.header.skinWidth}x${model.header.skinHeight}`);\n lines.push(`# Frame: ${frameIndex} (${frame.name})`);\n lines.push(`o ${frame.name}`);\n\n // Write vertices\n // OBJ vertices are \"v x y z\"\n // Quake uses Z-up, Y-forward? No, Quake is Z-up. OBJ is typically Y-up?\n // Actually, standard OBJ is just points. Tools usually expect Y-up.\n // Quake coords: X=Forward, Y=Left, Z=Up.\n // Blender/Standard: X=Right, Y=Up, Z=Back.\n // We usually export as-is and let the user handle rotation, or swap Y/Z.\n // The request doesn't specify coordinate conversion. I will export as-is (Quake coordinates).\n // Note: MD2 vertices are in local model space.\n for (const v of frame.vertices) {\n lines.push(`v ${v.position.x.toFixed(6)} ${v.position.y.toFixed(6)} ${v.position.z.toFixed(6)}`);\n }\n\n // Write texture coordinates\n // OBJ UVs are \"vt u v\"\n // MD2 tex coords are integers, need to normalize by skin size.\n // Also MD2 (0,0) is top-left, OBJ (0,0) is usually bottom-left.\n // So v = 1 - (t / height).\n const width = model.header.skinWidth;\n const height = model.header.skinHeight;\n for (const tc of model.texCoords) {\n const u = tc.s / width;\n const v = 1.0 - (tc.t / height);\n lines.push(`vt ${u.toFixed(6)} ${v.toFixed(6)}`);\n }\n\n // Write normals\n // MD2 stores normals in frame.vertices[i].normal\n for (const v of frame.vertices) {\n lines.push(`vn ${v.normal.x.toFixed(6)} ${v.normal.y.toFixed(6)} ${v.normal.z.toFixed(6)}`);\n }\n\n // Write faces\n // f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3\n // Indices are 1-based in OBJ.\n lines.push(`s off`); // Smoothing groups off\n for (const tri of model.triangles) {\n const v1 = tri.vertexIndices[0] + 1;\n const v2 = tri.vertexIndices[1] + 1;\n const v3 = tri.vertexIndices[2] + 1;\n\n const vt1 = tri.texCoordIndices[0] + 1;\n const vt2 = tri.texCoordIndices[1] + 1;\n const vt3 = tri.texCoordIndices[2] + 1;\n\n // Normal indices match vertex indices in MD2 (per-vertex normals)\n const vn1 = v1;\n const vn2 = v2;\n const vn3 = v3;\n\n // Reverse winding? Quake is clockwise? OpenGL is CCW.\n // MD2 is usually Clockwise winding for front face?\n // Let's stick to the order in the file.\n lines.push(`f ${v1}/${vt1}/${vn1} ${v2}/${vt2}/${vn2} ${v3}/${vt3}/${vn3}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Export MD3 model to glTF 2.0 format\n * Currently exports the first frame as a static mesh.\n * @param model Parsed MD3 model\n * @returns glTF JSON and binary buffer\n */\nexport function exportMd3ToGltf(model: Md3Model): {\n json: string\n buffer: ArrayBuffer\n} {\n // Structure for GLTF\n const gltf: any = {\n asset: {\n version: \"2.0\",\n generator: \"quake2ts-tools\"\n },\n scenes: [\n {\n nodes: [0]\n }\n ],\n nodes: [\n {\n name: model.header.name,\n mesh: 0\n }\n ],\n meshes: [\n {\n name: model.header.name,\n primitives: []\n }\n ],\n buffers: [\n {\n byteLength: 0 // To be filled\n }\n ],\n bufferViews: [],\n accessors: []\n };\n\n const binaryData: number[] = [];\n\n // Helpers to append data and create views\n const addBufferView = (data: Uint8Array, target?: number) => {\n const byteOffset = binaryData.length;\n // Align to 4 bytes\n while (binaryData.length % 4 !== 0) {\n binaryData.push(0);\n }\n const alignedOffset = binaryData.length;\n for (let i = 0; i < data.length; i++) {\n binaryData.push(data[i]);\n }\n const byteLength = data.length;\n const viewIndex = gltf.bufferViews.length;\n gltf.bufferViews.push({\n buffer: 0,\n byteOffset: alignedOffset,\n byteLength: byteLength,\n target: target\n });\n return viewIndex;\n };\n\n const addAccessor = (bufferView: number, componentType: number, count: number, type: string, min?: number[], max?: number[]) => {\n const index = gltf.accessors.length;\n const acc: any = {\n bufferView,\n componentType, // 5126=FLOAT, 5123=USHORT, 5125=UINT\n count,\n type, // \"SCALAR\", \"VEC2\", \"VEC3\"\n };\n if (min) acc.min = min;\n if (max) acc.max = max;\n gltf.accessors.push(acc);\n return index;\n };\n\n // Process surfaces\n // For each surface, export frame 0 geometry\n // MD3 has separate surfaces which map to GLTF primitives\n\n // We use frame 0\n const frameIndex = 0;\n\n for (const surface of model.surfaces) {\n // Vertices for frame 0\n const frameVerts = surface.vertices[frameIndex];\n\n // Positions (Vec3)\n const positions = new Float32Array(frameVerts.length * 3);\n const normals = new Float32Array(frameVerts.length * 3);\n const texCoords = new Float32Array(frameVerts.length * 2);\n\n let minPos = [Infinity, Infinity, Infinity];\n let maxPos = [-Infinity, -Infinity, -Infinity];\n\n for (let i = 0; i < frameVerts.length; i++) {\n const v = frameVerts[i];\n positions[i * 3] = v.position.x;\n positions[i * 3 + 1] = v.position.y;\n positions[i * 3 + 2] = v.position.z;\n\n minPos[0] = Math.min(minPos[0], v.position.x);\n minPos[1] = Math.min(minPos[1], v.position.y);\n minPos[2] = Math.min(minPos[2], v.position.z);\n maxPos[0] = Math.max(maxPos[0], v.position.x);\n maxPos[1] = Math.max(maxPos[1], v.position.y);\n maxPos[2] = Math.max(maxPos[2], v.position.z);\n\n normals[i * 3] = v.normal.x;\n normals[i * 3 + 1] = v.normal.y;\n normals[i * 3 + 2] = v.normal.z;\n\n // TexCoords (shared across frames in MD3)\n const tc = surface.texCoords[i];\n texCoords[i * 2] = tc.s;\n texCoords[i * 2 + 1] = 1.0 - tc.t; // Flip V\n }\n\n // Indices (Triangles)\n // MD3 indices are per surface\n const indices = new Uint16Array(surface.triangles.length * 3);\n for (let i = 0; i < surface.triangles.length; i++) {\n indices[i * 3] = surface.triangles[i].indices[0];\n indices[i * 3 + 1] = surface.triangles[i].indices[1];\n indices[i * 3 + 2] = surface.triangles[i].indices[2];\n }\n\n // Create BufferViews\n const posView = addBufferView(new Uint8Array(positions.buffer), 34962); // ARRAY_BUFFER\n const normView = addBufferView(new Uint8Array(normals.buffer), 34962);\n const tcView = addBufferView(new Uint8Array(texCoords.buffer), 34962);\n const idxView = addBufferView(new Uint8Array(indices.buffer), 34963); // ELEMENT_ARRAY_BUFFER\n\n // Create Accessors\n const posAcc = addAccessor(posView, 5126, frameVerts.length, \"VEC3\", minPos, maxPos);\n const normAcc = addAccessor(normView, 5126, frameVerts.length, \"VEC3\");\n const tcAcc = addAccessor(tcView, 5126, frameVerts.length, \"VEC2\");\n const idxAcc = addAccessor(idxView, 5123, indices.length, \"SCALAR\");\n\n // Add Primitive\n gltf.meshes[0].primitives.push({\n attributes: {\n POSITION: posAcc,\n NORMAL: normAcc,\n TEXCOORD_0: tcAcc\n },\n indices: idxAcc,\n material: undefined // Could add material info if needed\n });\n }\n\n // Finalize buffer\n // Pad to 4 bytes\n while (binaryData.length % 4 !== 0) {\n binaryData.push(0);\n }\n gltf.buffers[0].byteLength = binaryData.length;\n\n return {\n json: JSON.stringify(gltf, null, 2),\n buffer: new Uint8Array(binaryData).buffer\n };\n}\n","export interface Vec3 {\n readonly x: number;\n readonly y: number;\n readonly z: number;\n readonly [index: number]: number;\n}\n\nexport const ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\n\n// Matches STOP_EPSILON from rerelease q_vec3.h\nexport const STOP_EPSILON = 0.1;\n\nconst DEG_TO_RAD = Math.PI / 180;\n\nexport interface Bounds3 {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n}\n\nexport type Mat3Row = readonly [number, number, number];\nexport type Mat3 = readonly [Mat3Row, Mat3Row, Mat3Row];\n\nexport function copyVec3(a: Vec3): Vec3 {\n return { x: a.x, y: a.y, z: a.z };\n}\n\nexport function addVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };\n}\n\nexport function subtractVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };\n}\n\nexport function multiplyVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x * b.x, y: a.y * b.y, z: a.z * b.z };\n}\n\nexport function scaleVec3(a: Vec3, scalar: number): Vec3 {\n return { x: a.x * scalar, y: a.y * scalar, z: a.z * scalar };\n}\n\nexport function negateVec3(a: Vec3): Vec3 {\n return scaleVec3(a, -1);\n}\n\nexport function dotVec3(a: Vec3, b: Vec3): number {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\nexport function crossVec3(a: Vec3, b: Vec3): Vec3 {\n return {\n x: a.y * b.z - a.z * b.y,\n y: a.z * b.x - a.x * b.z,\n z: a.x * b.y - a.y * b.x,\n };\n}\n\nexport function lengthSquaredVec3(a: Vec3): number {\n return dotVec3(a, a);\n}\n\nexport function lengthVec3(a: Vec3): number {\n return Math.sqrt(lengthSquaredVec3(a));\n}\n\nexport function distance(a: Vec3, b: Vec3): number {\n return lengthVec3(subtractVec3(a, b));\n}\n\nexport function vec3Equals(a: Vec3, b: Vec3): boolean {\n return a.x === b.x && a.y === b.y && a.z === b.z;\n}\n\n/**\n * Returns the normalized vector. If the vector is zero-length, the\n * input is returned to mirror the rerelease q_vec3 semantics.\n */\nexport function normalizeVec3(a: Vec3): Vec3 {\n const len = lengthVec3(a);\n return len === 0 ? a : scaleVec3(a, 1 / len);\n}\n\n/**\n * Projects a point onto a plane defined by the given normal.\n * Based on ProjectPointOnPlane in the rerelease q_vec3 helpers.\n */\nexport function projectPointOnPlane(point: Vec3, normal: Vec3): Vec3 {\n const invDenom = 1 / dotVec3(normal, normal);\n const d = dotVec3(normal, point) * invDenom;\n return subtractVec3(point, scaleVec3(normal, invDenom * d));\n}\n\n/**\n * Computes a perpendicular vector to the provided direction using the\n * smallest axial component heuristic used by the rerelease.\n * Assumes the input is normalized.\n */\nexport function perpendicularVec3(src: Vec3): Vec3 {\n let pos = 0;\n let minElement = Math.abs(src.x);\n\n if (Math.abs(src.y) < minElement) {\n pos = 1;\n minElement = Math.abs(src.y);\n }\n\n if (Math.abs(src.z) < minElement) {\n pos = 2;\n }\n\n const axis = pos === 0 ? { x: 1, y: 0, z: 0 } : pos === 1 ? { x: 0, y: 1, z: 0 } : { x: 0, y: 0, z: 1 };\n return normalizeVec3(projectPointOnPlane(axis, src));\n}\n\nexport function closestPointToBox(point: Vec3, mins: Vec3, maxs: Vec3): Vec3 {\n return {\n x: point.x < mins.x ? mins.x : point.x > maxs.x ? maxs.x : point.x,\n y: point.y < mins.y ? mins.y : point.y > maxs.y ? maxs.y : point.y,\n z: point.z < mins.z ? mins.z : point.z > maxs.z ? maxs.z : point.z,\n };\n}\n\nexport function distanceBetweenBoxesSquared(aMins: Vec3, aMaxs: Vec3, bMins: Vec3, bMaxs: Vec3): number {\n let lengthSq = 0;\n\n if (aMaxs.x < bMins.x) {\n const d = aMaxs.x - bMins.x;\n lengthSq += d * d;\n } else if (aMins.x > bMaxs.x) {\n const d = aMins.x - bMaxs.x;\n lengthSq += d * d;\n }\n\n if (aMaxs.y < bMins.y) {\n const d = aMaxs.y - bMins.y;\n lengthSq += d * d;\n } else if (aMins.y > bMaxs.y) {\n const d = aMins.y - bMaxs.y;\n lengthSq += d * d;\n }\n\n if (aMaxs.z < bMins.z) {\n const d = aMaxs.z - bMins.z;\n lengthSq += d * d;\n } else if (aMins.z > bMaxs.z) {\n const d = aMins.z - bMaxs.z;\n lengthSq += d * d;\n }\n\n return lengthSq;\n}\n\nexport function createEmptyBounds3(): Bounds3 {\n return {\n mins: { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY },\n maxs: { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY },\n };\n}\n\nexport function addPointToBounds(point: Vec3, bounds: Bounds3): Bounds3 {\n return {\n mins: {\n x: Math.min(bounds.mins.x, point.x),\n y: Math.min(bounds.mins.y, point.y),\n z: Math.min(bounds.mins.z, point.z),\n },\n maxs: {\n x: Math.max(bounds.maxs.x, point.x),\n y: Math.max(bounds.maxs.y, point.y),\n z: Math.max(bounds.maxs.z, point.z),\n },\n };\n}\n\nexport function boxesIntersect(a: Bounds3, b: Bounds3): boolean {\n return (\n a.mins.x <= b.maxs.x &&\n a.maxs.x >= b.mins.x &&\n a.mins.y <= b.maxs.y &&\n a.maxs.y >= b.mins.y &&\n a.mins.z <= b.maxs.z &&\n a.maxs.z >= b.mins.z\n );\n}\n\n/**\n * Mirrors PM_ClipVelocity from `rerelease/p_move.cpp`: slide the incoming velocity off\n * a plane normal, applying an overbounce scale and zeroing tiny components so callers can\n * detect blocked axes using STOP_EPSILON.\n */\nexport function clipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n const backoff = dotVec3(inVel, normal) * overbounce;\n\n let outX = inVel.x - normal.x * backoff;\n let outY = inVel.y - normal.y * backoff;\n let outZ = inVel.z - normal.z * backoff;\n\n if (outX > -STOP_EPSILON && outX < STOP_EPSILON) {\n outX = 0;\n }\n\n if (outY > -STOP_EPSILON && outY < STOP_EPSILON) {\n outY = 0;\n }\n\n if (outZ > -STOP_EPSILON && outZ < STOP_EPSILON) {\n outZ = 0;\n }\n\n return { x: outX, y: outY, z: outZ };\n}\n\n/**\n * Slide a velocity across one or more clip planes using the same plane set resolution logic\n * seen in the inner loop of `PM_StepSlideMove_Generic` (rerelease `p_move.cpp`). When a single\n * plane is provided this devolves to PM_ClipVelocity; with two planes it projects onto the\n * crease defined by their cross product; with more planes it zeroes the velocity to avoid\n * oscillations.\n */\nexport function clipVelocityAgainstPlanes(\n velocity: Vec3,\n planes: readonly Vec3[],\n overbounce: number,\n primalVelocity?: Vec3,\n): Vec3 {\n if (planes.length === 0) {\n return velocity;\n }\n\n let working = velocity;\n\n for (let i = 0; i < planes.length; i++) {\n working = clipVelocityVec3(working, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) {\n continue;\n }\n\n if (dotVec3(working, planes[j]) < 0) {\n break;\n }\n }\n\n if (j === planes.length) {\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return working;\n }\n }\n\n if (planes.length === 2) {\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n const creaseVelocity = scaleVec3(dir, d);\n\n if (primalVelocity && dotVec3(creaseVelocity, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return creaseVelocity;\n }\n\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return ZERO_VEC3;\n}\n\n/**\n * Alias retained for ergonomics; mirrors PM_ClipVelocity semantics.\n */\nexport function slideClipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n return clipVelocityVec3(inVel, normal, overbounce);\n}\n\n/**\n * Project an offset from a point in forward/right(/up) space into world space.\n * Mirrors G_ProjectSource and G_ProjectSource2 in rerelease q_vec3.\n */\nexport function projectSourceVec3(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y,\n y: point.y + forward.y * distance.x + right.y * distance.y,\n z: point.z + forward.z * distance.x + right.z * distance.y + distance.z,\n };\n}\n\nexport function projectSourceVec3WithUp(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3, up: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y + up.x * distance.z,\n y: point.y + forward.y * distance.x + right.y * distance.y + up.y * distance.z,\n z: point.z + forward.z * distance.x + right.z * distance.y + up.z * distance.z,\n };\n}\n\n/**\n * Spherical linear interpolation between two vectors, mirroring q_vec3::slerp.\n * This is intended for direction vectors; callers should pre-normalize if needed.\n */\nexport function slerpVec3(from: Vec3, to: Vec3, t: number): Vec3 {\n const dot = dotVec3(from, to);\n let aFactor: number;\n let bFactor: number;\n\n if (Math.abs(dot) > 0.9995) {\n aFactor = 1 - t;\n bFactor = t;\n } else {\n const ang = Math.acos(dot);\n const sinOmega = Math.sin(ang);\n const sinAOmega = Math.sin((1 - t) * ang);\n const sinBOmega = Math.sin(t * ang);\n aFactor = sinAOmega / sinOmega;\n bFactor = sinBOmega / sinOmega;\n }\n\n return {\n x: from.x * aFactor + to.x * bFactor,\n y: from.y * aFactor + to.y * bFactor,\n z: from.z * aFactor + to.z * bFactor,\n };\n}\n\nexport function concatRotationMatrices(a: Mat3, b: Mat3): Mat3 {\n const row = (rowIndex: number): Mat3Row => [\n a[rowIndex][0] * b[0][0] + a[rowIndex][1] * b[1][0] + a[rowIndex][2] * b[2][0],\n a[rowIndex][0] * b[0][1] + a[rowIndex][1] * b[1][1] + a[rowIndex][2] * b[2][1],\n a[rowIndex][0] * b[0][2] + a[rowIndex][1] * b[1][2] + a[rowIndex][2] * b[2][2],\n ];\n\n const result = [row(0), row(1), row(2)] as Mat3;\n return result;\n}\n\nexport function rotatePointAroundVector(dir: Vec3, point: Vec3, degrees: number): Vec3 {\n const axisLength = lengthVec3(dir);\n if (axisLength === 0) {\n return point;\n }\n\n const vf = normalizeVec3(dir);\n const vr = perpendicularVec3(vf);\n const vup = crossVec3(vr, vf);\n\n const m: Mat3 = [\n [vr.x, vup.x, vf.x],\n [vr.y, vup.y, vf.y],\n [vr.z, vup.z, vf.z],\n ];\n\n const im: Mat3 = [\n [m[0][0], m[1][0], m[2][0]],\n [m[0][1], m[1][1], m[2][1]],\n [m[0][2], m[1][2], m[2][2]],\n ];\n\n const radians = degrees * DEG_TO_RAD;\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n const zrot: Mat3 = [\n [cos, sin, 0],\n [-sin, cos, 0],\n [0, 0, 1],\n ];\n\n const rot = concatRotationMatrices(concatRotationMatrices(m, zrot), im);\n\n return {\n x: rot[0][0] * point.x + rot[0][1] * point.y + rot[0][2] * point.z,\n y: rot[1][0] * point.x + rot[1][1] * point.y + rot[1][2] * point.z,\n z: rot[2][0] * point.x + rot[2][1] * point.y + rot[2][2] * point.z,\n };\n}\n","import { Vec3 } from './vec3.js';\n\nexport const PITCH = 0;\nexport const YAW = 1;\nexport const ROLL = 2;\n\nconst DEG2RAD_FACTOR = Math.PI / 180;\nconst RAD2DEG_FACTOR = 180 / Math.PI;\n\n// Export constants for direct use in matrix operations\nexport const DEG2RAD = DEG2RAD_FACTOR;\nexport const RAD2DEG = RAD2DEG_FACTOR;\n\nfunction axisComponent(vec: Vec3, axis: number): number {\n switch (axis) {\n case PITCH:\n return vec.x;\n case YAW:\n return vec.y;\n case ROLL:\n default:\n return vec.z;\n }\n}\n\nexport interface AngleVectorsResult {\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly up: Vec3;\n}\n\nexport function degToRad(degrees: number): number {\n return degrees * DEG2RAD_FACTOR;\n}\n\nexport function radToDeg(radians: number): number {\n return radians * RAD2DEG_FACTOR;\n}\n\nexport function lerpAngle(from: number, to: number, frac: number): number {\n let target = to;\n\n if (target - from > 180) {\n target -= 360;\n } else if (target - from < -180) {\n target += 360;\n }\n\n return from + frac * (target - from);\n}\n\nexport function angleMod(angle: number): number {\n const value = angle % 360;\n return value < 0 ? 360 + value : value;\n}\n\nexport function angleVectors(angles: Vec3): AngleVectorsResult {\n const yaw = degToRad(axisComponent(angles, YAW));\n const pitch = degToRad(axisComponent(angles, PITCH));\n const roll = degToRad(axisComponent(angles, ROLL));\n\n const sy = Math.sin(yaw);\n const cy = Math.cos(yaw);\n const sp = Math.sin(pitch);\n const cp = Math.cos(pitch);\n const sr = Math.sin(roll);\n const cr = Math.cos(roll);\n\n const forward: Vec3 = {\n x: cp * cy,\n y: cp * sy,\n z: -sp,\n };\n\n const right: Vec3 = {\n x: -sr * sp * cy - cr * -sy,\n y: -sr * sp * sy - cr * cy,\n z: -sr * cp,\n };\n\n const up: Vec3 = {\n x: cr * sp * cy - sr * -sy,\n y: cr * sp * sy - sr * cy,\n z: cr * cp,\n };\n\n return { forward, right, up };\n}\n\nexport function vectorToYaw(vec: Vec3): number {\n const pitch = axisComponent(vec, PITCH);\n const yawAxis = axisComponent(vec, YAW);\n\n if (pitch === 0) {\n if (yawAxis === 0) {\n return 0;\n }\n\n return yawAxis > 0 ? 90 : 270;\n }\n\n const yaw = radToDeg(Math.atan2(yawAxis, pitch));\n return yaw < 0 ? yaw + 360 : yaw;\n}\n\nexport function vectorToAngles(vec: Vec3): Vec3 {\n const x = vec.x;\n const y = vec.y;\n const z = vec.z;\n\n if (y === 0 && x === 0) {\n return { x: z > 0 ? -90 : -270, y: 0, z: 0 };\n }\n\n let yaw: number;\n if (x) {\n yaw = radToDeg(Math.atan2(y, x));\n } else if (y > 0) {\n yaw = 90;\n } else {\n yaw = 270;\n }\n\n if (yaw < 0) {\n yaw += 360;\n }\n\n const forward = Math.sqrt(x * x + y * y);\n let pitch = radToDeg(Math.atan2(z, forward));\n if (pitch < 0) {\n pitch += 360;\n }\n\n return { x: -pitch, y: yaw, z: 0 };\n}\n","// Extracted from full/client/anorms.h\nexport const ANORMS: [number, number, number][] = [\n [-0.525731, 0.000000, 0.850651],\n [-0.442863, 0.238856, 0.864188],\n [-0.295242, 0.000000, 0.955423],\n [-0.309017, 0.500000, 0.809017],\n [-0.162460, 0.262866, 0.951056],\n [0.000000, 0.000000, 1.000000],\n [0.000000, 0.850651, 0.525731],\n [-0.147621, 0.716567, 0.681718],\n [0.147621, 0.716567, 0.681718],\n [0.000000, 0.525731, 0.850651],\n [0.309017, 0.500000, 0.809017],\n [0.525731, 0.000000, 0.850651],\n [0.295242, 0.000000, 0.955423],\n [0.442863, 0.238856, 0.864188],\n [0.162460, 0.262866, 0.951056],\n [-0.681718, 0.147621, 0.716567],\n [-0.809017, 0.309017, 0.500000],\n [-0.587785, 0.425325, 0.688191],\n [-0.850651, 0.525731, 0.000000],\n [-0.864188, 0.442863, 0.238856],\n [-0.716567, 0.681718, 0.147621],\n [-0.688191, 0.587785, 0.425325],\n [-0.500000, 0.809017, 0.309017],\n [-0.238856, 0.864188, 0.442863],\n [-0.425325, 0.688191, 0.587785],\n [-0.716567, 0.681718, -0.147621],\n [-0.500000, 0.809017, -0.309017],\n [-0.525731, 0.850651, 0.000000],\n [0.000000, 0.850651, -0.525731],\n [-0.238856, 0.864188, -0.442863],\n [0.000000, 0.955423, -0.295242],\n [-0.262866, 0.951056, -0.162460],\n [0.000000, 1.000000, 0.000000],\n [0.000000, 0.955423, 0.295242],\n [-0.262866, 0.951056, 0.162460],\n [0.238856, 0.864188, 0.442863],\n [0.262866, 0.951056, 0.162460],\n [0.500000, 0.809017, 0.309017],\n [0.238856, 0.864188, -0.442863],\n [0.262866, 0.951056, -0.162460],\n [0.500000, 0.809017, -0.309017],\n [0.850651, 0.525731, 0.000000],\n [0.716567, 0.681718, 0.147621],\n [0.716567, 0.681718, -0.147621],\n [0.525731, 0.850651, 0.000000],\n [0.425325, 0.688191, 0.587785],\n [0.864188, 0.442863, 0.238856],\n [0.688191, 0.587785, 0.425325],\n [0.809017, 0.309017, 0.500000],\n [0.681718, 0.147621, 0.716567],\n [0.587785, 0.425325, 0.688191],\n [0.955423, 0.295242, 0.000000],\n [1.000000, 0.000000, 0.000000],\n [0.951056, 0.162460, 0.262866],\n [0.850651, -0.525731, 0.000000],\n [0.955423, -0.295242, 0.000000],\n [0.864188, -0.442863, 0.238856],\n [0.951056, -0.162460, 0.262866],\n [0.809017, -0.309017, 0.500000],\n [0.681718, -0.147621, 0.716567],\n [0.850651, 0.000000, 0.525731],\n [0.864188, 0.442863, -0.238856],\n [0.809017, 0.309017, -0.500000],\n [0.951056, 0.162460, -0.262866],\n [0.525731, 0.000000, -0.850651],\n [0.681718, 0.147621, -0.716567],\n [0.681718, -0.147621, -0.716567],\n [0.850651, 0.000000, -0.525731],\n [0.809017, -0.309017, -0.500000],\n [0.864188, -0.442863, -0.238856],\n [0.951056, -0.162460, -0.262866],\n [0.147621, 0.716567, -0.681718],\n [0.309017, 0.500000, -0.809017],\n [0.425325, 0.688191, -0.587785],\n [0.442863, 0.238856, -0.864188],\n [0.587785, 0.425325, -0.688191],\n [0.688191, 0.587785, -0.425325],\n [-0.147621, 0.716567, -0.681718],\n [-0.309017, 0.500000, -0.809017],\n [0.000000, 0.525731, -0.850651],\n [-0.525731, 0.000000, -0.850651],\n [-0.442863, 0.238856, -0.864188],\n [-0.295242, 0.000000, -0.955423],\n [-0.162460, 0.262866, -0.951056],\n [0.000000, 0.000000, -1.000000],\n [0.295242, 0.000000, -0.955423],\n [0.162460, 0.262866, -0.951056],\n [-0.442863, -0.238856, -0.864188],\n [-0.309017, -0.500000, -0.809017],\n [-0.162460, -0.262866, -0.951056],\n [0.000000, -0.850651, -0.525731],\n [-0.147621, -0.716567, -0.681718],\n [0.147621, -0.716567, -0.681718],\n [0.000000, -0.525731, -0.850651],\n [0.309017, -0.500000, -0.809017],\n [0.442863, -0.238856, -0.864188],\n [0.162460, -0.262866, -0.951056],\n [0.238856, -0.864188, -0.442863],\n [0.500000, -0.809017, -0.309017],\n [0.425325, -0.688191, -0.587785],\n [0.716567, -0.681718, -0.147621],\n [0.688191, -0.587785, -0.425325],\n [0.587785, -0.425325, -0.688191],\n [0.000000, -0.955423, -0.295242],\n [0.000000, -1.000000, 0.000000],\n [0.262866, -0.951056, -0.162460],\n [0.000000, -0.850651, 0.525731],\n [0.000000, -0.955423, 0.295242],\n [0.238856, -0.864188, 0.442863],\n [0.262866, -0.951056, 0.162460],\n [0.500000, -0.809017, 0.309017],\n [0.716567, -0.681718, 0.147621],\n [0.525731, -0.850651, 0.000000],\n [-0.238856, -0.864188, -0.442863],\n [-0.500000, -0.809017, -0.309017],\n [-0.262866, -0.951056, -0.162460],\n [-0.850651, -0.525731, 0.000000],\n [-0.716567, -0.681718, -0.147621],\n [-0.716567, -0.681718, 0.147621],\n [-0.525731, -0.850651, 0.000000],\n [-0.500000, -0.809017, 0.309017],\n [-0.238856, -0.864188, 0.442863],\n [-0.262866, -0.951056, 0.162460],\n [-0.864188, -0.442863, 0.238856],\n [-0.809017, -0.309017, 0.500000],\n [-0.688191, -0.587785, 0.425325],\n [-0.681718, -0.147621, 0.716567],\n [-0.442863, -0.238856, 0.864188],\n [-0.587785, -0.425325, 0.688191],\n [-0.309017, -0.500000, 0.809017],\n [-0.147621, -0.716567, 0.681718],\n [-0.425325, -0.688191, 0.587785],\n [-0.162460, -0.262866, 0.951056],\n [0.442863, -0.238856, 0.864188],\n [0.162460, -0.262866, 0.951056],\n [0.309017, -0.500000, 0.809017],\n [0.147621, -0.716567, 0.681718],\n [0.000000, -0.525731, 0.850651],\n [0.425325, -0.688191, 0.587785],\n [0.587785, -0.425325, 0.688191],\n [0.688191, -0.587785, 0.425325],\n [-0.955423, 0.295242, 0.000000],\n [-0.951056, 0.162460, 0.262866],\n [-1.000000, 0.000000, 0.000000],\n [-0.850651, 0.000000, 0.525731],\n [-0.955423, -0.295242, 0.000000],\n [-0.951056, -0.162460, 0.262866],\n [-0.864188, 0.442863, -0.238856],\n [-0.951056, 0.162460, -0.262866],\n [-0.809017, 0.309017, -0.500000],\n [-0.864188, -0.442863, -0.238856],\n [-0.951056, -0.162460, -0.262866],\n [-0.809017, -0.309017, -0.500000],\n [-0.681718, 0.147621, -0.716567],\n [-0.681718, -0.147621, -0.716567],\n [-0.850651, 0.000000, -0.525731],\n [-0.688191, 0.587785, -0.425325],\n [-0.587785, 0.425325, -0.688191],\n [-0.425325, 0.688191, -0.587785],\n [-0.425325, -0.688191, -0.587785],\n [-0.587785, -0.425325, -0.688191],\n [-0.688191, -0.587785, -0.425325]\n];\n","export type Color4 = [number, number, number, number];\n\n/**\n * TypeScript port of G_AddBlend from rerelease q_std.h.\n *\n * Given an incoming RGBA color and an existing blend color, computes the new\n * blended color where alpha is accumulated and RGB is mixed proportionally\n * to the previous vs. new alpha contribution.\n *\n * This function is pure and does not mutate its inputs.\n */\nexport function addBlendColor(\n r: number,\n g: number,\n b: number,\n a: number,\n current: Color4,\n): Color4 {\n if (a <= 0) {\n return current;\n }\n\n const oldR = current[0];\n const oldG = current[1];\n const oldB = current[2];\n const oldA = current[3];\n\n const a2 = oldA + (1 - oldA) * a;\n\n if (a2 <= 0) {\n return [0, 0, 0, 0];\n }\n\n const a3 = oldA / a2;\n\n const newR = oldR * a3 + r * (1 - a3);\n const newG = oldG * a3 + g * (1 - a3);\n const newB = oldB * a3 + b * (1 - a3);\n\n return [newR, newG, newB, a2];\n}\n\n","const STATE_SIZE = 624;\nconst MIDDLE_WORD = 397;\nconst MATRIX_A = 0x9908b0df;\nconst UPPER_MASK = 0x80000000;\nconst LOWER_MASK = 0x7fffffff;\nconst TWO_POW_32 = 0x100000000;\n\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\n\n/**\n * Minimal MT19937 implementation mirroring the rerelease's std::mt19937 usage in g_local.h.\n * The generator outputs deterministic unsigned 32-bit integers which drive the\n * higher-level helpers such as frandom/crandom/irandom.\n */\nexport class MersenneTwister19937 {\n private state = new Uint32Array(STATE_SIZE);\n private index = STATE_SIZE;\n\n constructor(seed = 5489) {\n this.seed(seed);\n }\n\n seed(seed: number): void {\n this.state[0] = seed >>> 0;\n for (let i = 1; i < STATE_SIZE; i++) {\n const prev = this.state[i - 1] ^ (this.state[i - 1] >>> 30);\n const next = Math.imul(prev >>> 0, 1812433253) + i;\n this.state[i] = next >>> 0;\n }\n this.index = STATE_SIZE;\n }\n\n nextUint32(): number {\n if (this.index >= STATE_SIZE) {\n this.twist();\n }\n\n let y = this.state[this.index++];\n y ^= y >>> 11;\n y ^= (y << 7) & 0x9d2c5680;\n y ^= (y << 15) & 0xefc60000;\n y ^= y >>> 18;\n return y >>> 0;\n }\n\n private twist(): void {\n for (let i = 0; i < STATE_SIZE; i++) {\n const y = (this.state[i] & UPPER_MASK) | (this.state[(i + 1) % STATE_SIZE] & LOWER_MASK);\n let next = this.state[(i + MIDDLE_WORD) % STATE_SIZE] ^ (y >>> 1);\n if ((y & 1) !== 0) {\n next ^= MATRIX_A;\n }\n this.state[i] = next >>> 0;\n }\n this.index = 0;\n }\n\n getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\n}\n\n/**\n * Deterministic helper mirroring the random helpers defined in rerelease g_local.h.\n */\nexport class RandomGenerator {\n private readonly mt: MersenneTwister19937;\n\n constructor(options: RandomGeneratorOptions = {}) {\n this.mt = new MersenneTwister19937(options.seed);\n }\n\n seed(seed: number): void {\n this.mt.seed(seed);\n }\n\n /** Uniform float in [0, 1). */\n frandom(): number {\n return this.mt.nextUint32() / TWO_POW_32;\n }\n\n /** Uniform float in [min, max). */\n frandomRange(minInclusive: number, maxExclusive: number): number {\n return minInclusive + (maxExclusive - minInclusive) * this.frandom();\n }\n\n /** Uniform float in [0, max). */\n frandomMax(maxExclusive: number): number {\n return this.frandomRange(0, maxExclusive);\n }\n\n /** Uniform float in [-1, 1). */\n crandom(): number {\n return this.frandomRange(-1, 1);\n }\n\n /** Uniform float in (-1, 1). */\n crandomOpen(): number {\n const epsilon = Number.EPSILON;\n return this.frandomRange(-1 + epsilon, 1);\n }\n\n /** Raw uint32 sample. */\n irandomUint32(): number {\n return this.mt.nextUint32();\n }\n\n /** Uniform integer in [min, max). */\n irandomRange(minInclusive: number, maxExclusive: number): number {\n if (maxExclusive - minInclusive <= 1) {\n return minInclusive;\n }\n\n const span = maxExclusive - minInclusive;\n const limit = TWO_POW_32 - (TWO_POW_32 % span);\n let sample: number;\n do {\n sample = this.mt.nextUint32();\n } while (sample >= limit);\n return minInclusive + (sample % span);\n }\n\n /** Uniform integer in [0, max). */\n irandom(maxExclusive: number): number {\n if (maxExclusive <= 0) {\n return 0;\n }\n return this.irandomRange(0, maxExclusive);\n }\n\n /** Uniform time in milliseconds [min, max). */\n randomTimeRange(minMs: number, maxMs: number): number {\n if (maxMs <= minMs) {\n return minMs;\n }\n return this.irandomRange(minMs, maxMs);\n }\n\n /** Uniform time in milliseconds [0, max). */\n randomTime(maxMs: number): number {\n return this.irandom(maxMs);\n }\n\n randomIndex<T extends { length: number }>(container: T): number {\n return this.irandom(container.length);\n }\n\n getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\n }\n}\n\nexport function createRandomGenerator(options?: RandomGeneratorOptions): RandomGenerator {\n return new RandomGenerator(options);\n}\n","import { Vec3 } from './vec3.js';\n\nexport type Mat4 = Float32Array;\n\nexport function createMat4Identity(): Mat4 {\n return new Float32Array([\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1,\n ]);\n}\n\nexport function multiplyMat4(a: Float32Array, b: Float32Array): Mat4 {\n const out = new Float32Array(16);\n for (let row = 0; row < 4; row += 1) {\n for (let col = 0; col < 4; col += 1) {\n out[col * 4 + row] =\n a[0 * 4 + row] * b[col * 4 + 0] +\n a[1 * 4 + row] * b[col * 4 + 1] +\n a[2 * 4 + row] * b[col * 4 + 2] +\n a[3 * 4 + row] * b[col * 4 + 3];\n }\n }\n return out;\n}\n\nexport function transformPointMat4(mat: Float32Array, point: Vec3): Vec3 {\n const x = point.x;\n const y = point.y;\n const z = point.z;\n return {\n x: mat[0] * x + mat[4] * y + mat[8] * z + mat[12],\n y: mat[1] * x + mat[5] * y + mat[9] * z + mat[13],\n z: mat[2] * x + mat[6] * y + mat[10] * z + mat[14],\n };\n}\n\nexport function mat4FromBasis(origin: Vec3, axis: readonly [Vec3, Vec3, Vec3]): Mat4 {\n const out = createMat4Identity();\n out[0] = axis[0].x;\n out[1] = axis[0].y;\n out[2] = axis[0].z;\n\n out[4] = axis[1].x;\n out[5] = axis[1].y;\n out[6] = axis[1].z;\n\n out[8] = axis[2].x;\n out[9] = axis[2].y;\n out[10] = axis[2].z;\n\n out[12] = origin.x;\n out[13] = origin.y;\n out[14] = origin.z;\n\n return out;\n}\n","/**\n * Bitflag constants mirroring the Quake II rerelease `contents_t` and\n * `surfflags_t` enumerations from `game.h`. The helpers here operate purely on\n * numeric bitmasks so both the authoritative game simulation and the client can\n * share the same semantic checks.\n */\nexport type ContentsFlag = number;\nexport type SurfaceFlag = number;\n\nexport const CONTENTS_NONE: ContentsFlag = 0;\nexport const CONTENTS_SOLID: ContentsFlag = 1 << 0;\nexport const CONTENTS_WINDOW: ContentsFlag = 1 << 1;\nexport const CONTENTS_AUX: ContentsFlag = 1 << 2;\nexport const CONTENTS_LAVA: ContentsFlag = 1 << 3;\nexport const CONTENTS_SLIME: ContentsFlag = 1 << 4;\nexport const CONTENTS_WATER: ContentsFlag = 1 << 5;\nexport const CONTENTS_MIST: ContentsFlag = 1 << 6;\nexport const CONTENTS_TRIGGER: ContentsFlag = 0x40000000;\nexport const CONTENTS_NO_WATERJUMP: ContentsFlag = 1 << 13;\nexport const CONTENTS_PROJECTILECLIP: ContentsFlag = 1 << 14;\nexport const CONTENTS_AREAPORTAL: ContentsFlag = 1 << 15;\nexport const CONTENTS_PLAYERCLIP: ContentsFlag = 1 << 16;\nexport const CONTENTS_MONSTERCLIP: ContentsFlag = 1 << 17;\nexport const CONTENTS_CURRENT_0: ContentsFlag = 1 << 18;\nexport const CONTENTS_CURRENT_90: ContentsFlag = 1 << 19;\nexport const CONTENTS_CURRENT_180: ContentsFlag = 1 << 20;\nexport const CONTENTS_CURRENT_270: ContentsFlag = 1 << 21;\nexport const CONTENTS_CURRENT_UP: ContentsFlag = 1 << 22;\nexport const CONTENTS_CURRENT_DOWN: ContentsFlag = 1 << 23;\nexport const CONTENTS_ORIGIN: ContentsFlag = 1 << 24;\nexport const CONTENTS_MONSTER: ContentsFlag = 1 << 25;\nexport const CONTENTS_DEADMONSTER: ContentsFlag = 1 << 26;\nexport const CONTENTS_DETAIL: ContentsFlag = 1 << 27;\nexport const CONTENTS_TRANSLUCENT: ContentsFlag = 1 << 28;\nexport const CONTENTS_LADDER: ContentsFlag = 1 << 29;\nexport const CONTENTS_PLAYER: ContentsFlag = 1 << 30;\nexport const CONTENTS_PROJECTILE: ContentsFlag = 1 << 31;\n\nexport const LAST_VISIBLE_CONTENTS: ContentsFlag = CONTENTS_MIST;\n\nexport const SURF_NONE: SurfaceFlag = 0;\nexport const SURF_LIGHT: SurfaceFlag = 1 << 0;\nexport const SURF_SLICK: SurfaceFlag = 1 << 1;\nexport const SURF_SKY: SurfaceFlag = 1 << 2;\nexport const SURF_WARP: SurfaceFlag = 1 << 3;\nexport const SURF_TRANS33: SurfaceFlag = 1 << 4;\nexport const SURF_TRANS66: SurfaceFlag = 1 << 5;\nexport const SURF_FLOWING: SurfaceFlag = 1 << 6;\nexport const SURF_NODRAW: SurfaceFlag = 1 << 7;\nexport const SURF_ALPHATEST: SurfaceFlag = 1 << 25;\nexport const SURF_N64_UV: SurfaceFlag = 1 << 28;\nexport const SURF_N64_SCROLL_X: SurfaceFlag = 1 << 29;\nexport const SURF_N64_SCROLL_Y: SurfaceFlag = 1 << 30;\nexport const SURF_N64_SCROLL_FLIP: SurfaceFlag = 1 << 31;\n\nexport const MASK_ALL: ContentsFlag = 0xffffffff;\nexport const MASK_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_PLAYERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_DEADSOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_MONSTERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_WATER: ContentsFlag = CONTENTS_WATER | CONTENTS_LAVA | CONTENTS_SLIME;\nexport const MASK_OPAQUE: ContentsFlag = CONTENTS_SOLID | CONTENTS_SLIME | CONTENTS_LAVA;\nexport const MASK_SHOT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_PLAYER | CONTENTS_WINDOW | CONTENTS_DEADMONSTER;\nexport const MASK_CURRENT: ContentsFlag =\n CONTENTS_CURRENT_0 |\n CONTENTS_CURRENT_90 |\n CONTENTS_CURRENT_180 |\n CONTENTS_CURRENT_270 |\n CONTENTS_CURRENT_UP |\n CONTENTS_CURRENT_DOWN;\nexport const MASK_BLOCK_SIGHT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_LADDER_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_WALK_NAV_SOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTERCLIP;\nexport const MASK_PROJECTILE: ContentsFlag = MASK_SHOT | CONTENTS_PROJECTILECLIP;\n\nexport function hasAllContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) === flags;\n}\n\nexport function hasAnyContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) !== 0;\n}\n\nexport function addContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask | flags;\n}\n\nexport function removeContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask & ~flags;\n}\n\nexport function hasSurfaceFlags(surface: SurfaceFlag, flags: SurfaceFlag): boolean {\n return (surface & flags) === flags;\n}\n\nexport function combineSurfaceFlags(...flags: SurfaceFlag[]): SurfaceFlag {\n let mask = SURF_NONE;\n for (const flag of flags) {\n mask |= flag;\n }\n return mask;\n}\n","import type { Vec3 } from '../math/vec3.js';\n\nexport const AREA_DEPTH = 4;\nexport const WORLD_SIZE = 8192; // Standard Q2 world extent\n\nexport interface SpatialNode {\n axis: number; // 0=X, 1=Y, -1=Leaf\n dist: number;\n children: [SpatialNode, SpatialNode] | null;\n items: Set<number>;\n}\n\nexport function createSpatialTree(\n depth = 0,\n mins: Vec3 = { x: -WORLD_SIZE, y: -WORLD_SIZE, z: -WORLD_SIZE },\n maxs: Vec3 = { x: WORLD_SIZE, y: WORLD_SIZE, z: WORLD_SIZE }\n): SpatialNode {\n if (depth >= AREA_DEPTH) {\n return {\n axis: -1,\n dist: 0,\n children: null,\n items: new Set(),\n };\n }\n\n const axis = depth % 2; // Alternates X (0) and Y (1)\n const dist = 0.5 * (axis === 0 ? mins.x + maxs.x : mins.y + maxs.y);\n\n const mins1 = { ...mins };\n const maxs1 = { ...maxs };\n const mins2 = { ...mins };\n const maxs2 = { ...maxs };\n\n if (axis === 0) {\n maxs1.x = dist;\n mins2.x = dist;\n } else {\n maxs1.y = dist;\n mins2.y = dist;\n }\n\n const child1 = createSpatialTree(depth + 1, mins1, maxs1);\n const child2 = createSpatialTree(depth + 1, mins2, maxs2);\n\n return {\n axis,\n dist,\n children: [child1, child2],\n items: new Set(),\n };\n}\n\nexport function linkEntityToSpatialTree(\n node: SpatialNode,\n id: number,\n absmin: Vec3,\n absmax: Vec3\n): SpatialNode {\n let current = node;\n\n while (current.axis !== -1 && current.children) {\n const axis = current.axis;\n const dist = current.dist;\n\n const min = axis === 0 ? absmin.x : absmin.y;\n const max = axis === 0 ? absmax.x : absmax.y;\n\n if (min > dist) {\n current = current.children[1];\n } else if (max < dist) {\n current = current.children[0];\n } else {\n break; // Straddles the plane, resides in this node\n }\n }\n\n current.items.add(id);\n return current;\n}\n\nexport function querySpatialTree(\n node: SpatialNode,\n absmin: Vec3,\n absmax: Vec3,\n results: Set<number>\n): void {\n // Add all items in the current node (because if we are here, we overlap this node's space\n // and straddling items definitely overlap us or are at least in the parent region)\n // Actually, strictly speaking, items in this node straddle the split plane.\n // Since we are traversing down, we are within the node's volume.\n // The items in this node are those that couldn't be pushed further down.\n // So we must check them.\n\n // NOTE: This collects candidates. Precise collision check still needed.\n for (const id of node.items) {\n results.add(id);\n }\n\n if (node.axis === -1 || !node.children) {\n return;\n }\n\n const axis = node.axis;\n const dist = node.dist;\n\n const min = axis === 0 ? absmin.x : absmin.y;\n const max = axis === 0 ? absmax.x : absmax.y;\n\n if (max > dist) {\n querySpatialTree(node.children[1], absmin, absmax, results);\n }\n if (min < dist) {\n querySpatialTree(node.children[0], absmin, absmax, results);\n }\n}\n","import { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } from '../math/vec3.js';\nimport { createSpatialTree, linkEntityToSpatialTree, querySpatialTree, SpatialNode } from './spatial.js';\n\nexport interface CollisionPlane {\n normal: Vec3;\n dist: number;\n type: number;\n signbits: number;\n}\n\nexport interface CollisionBrushSide {\n plane: CollisionPlane;\n surfaceFlags: number;\n}\n\nexport interface CollisionBrush {\n contents: number;\n sides: CollisionBrushSide[];\n checkcount?: number;\n}\n\nexport interface CollisionLeaf {\n contents: number;\n cluster: number;\n area: number;\n firstLeafBrush: number;\n numLeafBrushes: number;\n}\n\nexport interface CollisionNode {\n plane: CollisionPlane;\n children: [number, number];\n}\n\nexport interface CollisionBmodel {\n mins: Vec3;\n maxs: Vec3;\n origin: Vec3;\n headnode: number;\n}\n\nexport interface CollisionModel {\n planes: CollisionPlane[];\n nodes: CollisionNode[];\n leaves: CollisionLeaf[];\n brushes: CollisionBrush[];\n leafBrushes: number[];\n bmodels: CollisionBmodel[];\n visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\n}\n\nexport interface CollisionLumpData {\n planes: Array<{ normal: Vec3; dist: number; type: number }>;\n nodes: Array<{ planenum: number; children: [number, number] }>;\n leaves: Array<{ contents: number; cluster: number; area: number; firstLeafBrush: number; numLeafBrushes: number }>;\n brushes: Array<{ firstSide: number; numSides: number; contents: number }>;\n brushSides: Array<{ planenum: number; surfaceFlags: number }>;\n leafBrushes: number[];\n bmodels: Array<{ mins: Vec3; maxs: Vec3; origin: Vec3; headnode: number }>;\n visibility?: CollisionVisibility;\n}\n\nexport interface TraceResult {\n fraction: number;\n plane: CollisionPlane | null;\n contents: number;\n surfaceFlags: number;\n startsolid: boolean;\n allsolid: boolean;\n}\n\nexport interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\n contents?: number;\n surfaceFlags?: number;\n startsolid: boolean;\n allsolid: boolean;\n}\n\nexport enum PlaneSide {\n FRONT = 1,\n BACK = 2,\n CROSS = 3,\n}\n\nexport interface TraceDebugInfo {\n nodesTraversed: number;\n leafsReached: number;\n brushesTested: number;\n}\n\nexport let traceDebugInfo: TraceDebugInfo | null = null;\n\nexport function enableTraceDebug(): void {\n traceDebugInfo = { nodesTraversed: 0, leafsReached: 0, brushesTested: 0 };\n // console.log('DEBUG: Trace debug enabled');\n}\n\nexport function disableTraceDebug(): void {\n traceDebugInfo = null;\n}\n\nexport const DIST_EPSILON = 0.03125;\n\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\n\nexport function buildCollisionModel(lumps: CollisionLumpData): CollisionModel {\n const planes: CollisionPlane[] = lumps.planes.map((plane) => ({\n ...plane,\n signbits: computePlaneSignBits(plane.normal),\n }));\n\n const nodes: CollisionNode[] = lumps.nodes.map((node) => ({\n plane: planes[node.planenum],\n children: node.children,\n }));\n\n const brushes: CollisionBrush[] = lumps.brushes.map((brush) => {\n const sides = lumps.brushSides.slice(brush.firstSide, brush.firstSide + brush.numSides).map((side) => ({\n plane: planes[side.planenum],\n surfaceFlags: side.surfaceFlags,\n }));\n\n return {\n contents: brush.contents,\n sides,\n checkcount: 0,\n };\n });\n\n const leaves: CollisionLeaf[] = lumps.leaves.map((leaf) => ({\n contents: leaf.contents,\n cluster: leaf.cluster,\n area: leaf.area,\n firstLeafBrush: leaf.firstLeafBrush,\n numLeafBrushes: leaf.numLeafBrushes,\n }));\n\n const bmodels: CollisionBmodel[] = lumps.bmodels.map((model) => ({\n mins: model.mins,\n maxs: model.maxs,\n origin: model.origin,\n headnode: model.headnode,\n }));\n\n return {\n planes,\n nodes,\n leaves,\n brushes,\n leafBrushes: lumps.leafBrushes,\n bmodels,\n visibility: lumps.visibility,\n };\n}\n\nexport function computePlaneSignBits(normal: Vec3): number {\n let bits = 0;\n if (normal.x < 0) bits |= 1;\n if (normal.y < 0) bits |= 2;\n if (normal.z < 0) bits |= 4;\n return bits;\n}\n\nexport function planeDistanceToPoint(plane: CollisionPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z - plane.dist;\n}\n\nexport function pointOnPlaneSide(plane: CollisionPlane, point: Vec3, epsilon = 0): PlaneSide.FRONT | PlaneSide.BACK | PlaneSide.CROSS {\n const dist = planeDistanceToPoint(plane, point);\n if (dist > epsilon) {\n return PlaneSide.FRONT;\n }\n if (dist < -epsilon) {\n return PlaneSide.BACK;\n }\n return PlaneSide.CROSS;\n}\n\nexport function boxOnPlaneSide(mins: Vec3, maxs: Vec3, plane: CollisionPlane, epsilon = 0): PlaneSide {\n let dist1: number;\n let dist2: number;\n\n switch (plane.signbits) {\n case 0:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 1:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 2:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 3:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 4:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 5:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 6:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n default:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n }\n\n let sides = 0;\n if (dist1 - plane.dist >= -epsilon) sides = PlaneSide.FRONT;\n if (dist2 - plane.dist <= epsilon) sides |= PlaneSide.BACK;\n return sides as PlaneSide;\n}\n\nexport function pointInsideBrush(point: Vec3, brush: CollisionBrush, epsilon = DIST_EPSILON): boolean {\n for (const side of brush.sides) {\n const dist = planeDistanceToPoint(side.plane, point);\n if (dist > epsilon) {\n return false;\n }\n }\n return true;\n}\n\nexport interface BoxBrushTestResult {\n startsolid: boolean;\n allsolid: boolean;\n contents: number;\n}\n\nexport function testBoxInBrush(origin: Vec3, mins: Vec3, maxs: Vec3, brush: CollisionBrush): BoxBrushTestResult {\n for (const side of brush.sides) {\n const offset = side.plane.normal.x * (side.plane.normal.x < 0 ? maxs.x : mins.x) +\n side.plane.normal.y * (side.plane.normal.y < 0 ? maxs.y : mins.y) +\n side.plane.normal.z * (side.plane.normal.z < 0 ? maxs.z : mins.z);\n\n const dist = side.plane.dist - offset;\n const d1 = origin.x * side.plane.normal.x + origin.y * side.plane.normal.y + origin.z * side.plane.normal.z - dist;\n\n if (d1 > 0) {\n return { startsolid: false, allsolid: false, contents: 0 };\n }\n }\n\n return { startsolid: true, allsolid: true, contents: brush.contents };\n}\n\nexport interface ClipBoxParams {\n start: Vec3;\n end: Vec3;\n mins: Vec3;\n maxs: Vec3;\n brush: CollisionBrush;\n trace: TraceResult;\n}\n\n/**\n * Clips a movement box against a brush using the Liang-Barsky algorithm.\n *\n * This function determines if and where the swept box (from start to end) intersects the brush.\n * It works by clipping the movement line segment against the infinite planes defined by the brush sides.\n *\n * Algorithm Overview (Liang-Barsky):\n * The movement is treated as a parameterized line P(t) = Start + t * (End - Start), for t in [0, 1].\n * We maintain an interval [enterfrac, leavefrac] (initially [-1, 1]) representing the portion of the\n * line that is potentially inside the brush.\n * For each plane:\n * 1. We determine the distance of Start (d1) and End (d2) from the plane.\n * - For box traces, planes are expanded by the box extents, effectively treating the box as a point.\n * 2. If both points are in front (outside), the line is outside the brush.\n * 3. If the line crosses the plane:\n * - If entering (d1 > d2), we update `enterfrac` (max of entry times).\n * - If leaving (d1 < d2), we update `leavefrac` (min of exit times).\n * 4. If at any point enterfrac > leavefrac, the line misses the brush.\n *\n * @see CM_ClipBoxToBrush in qcommon/cm_trace.c:145-220\n *\n * @param params ClipBoxParams containing start/end vectors, box mins/maxs, target brush, and trace result to update.\n */\nexport function clipBoxToBrush({ start, end, mins, maxs, brush, trace }: ClipBoxParams): void {\n if (brush.sides.length === 0) return;\n\n const isPoint = mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n\n // enterfrac: The fraction of movement where the box FIRST fully enters the brush volume (intersection start).\n // leavefrac: The fraction of movement where the box STARTS to leave the brush volume (intersection end).\n // Initialized to -1 and 1 to cover the full potential range + buffers.\n let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false; // True if the end point is outside at least one plane (not trapped in brush)\n let startout = false; // True if the start point is outside at least one plane (not starting stuck)\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\n\n // Expand the plane by the box extents to perform a point-plane test.\n // This reduces the AABB sweep vs convex brush problem to a line segment vs expanded planes problem.\n if (!isPoint) {\n const ofsX = plane.normal.x < 0 ? maxs.x : mins.x;\n const ofsY = plane.normal.y < 0 ? maxs.y : mins.y;\n const ofsZ = plane.normal.z < 0 ? maxs.z : mins.z;\n dist -= plane.normal.x * ofsX + plane.normal.y * ofsY + plane.normal.z * ofsZ;\n }\n\n // d1: Distance of start point from the (expanded) plane. Positive = in front (outside).\n // d2: Distance of end point from the (expanded) plane.\n const d1 = start.x * plane.normal.x + start.y * plane.normal.y + start.z * plane.normal.z - dist;\n const d2 = end.x * plane.normal.x + end.y * plane.normal.y + end.z * plane.normal.z - dist;\n\n if (d2 > 0) getout = true;\n if (d1 > 0) startout = true;\n\n // Case 1: Entirely outside this plane.\n // Since brushes are convex intersections of half-spaces (defined by planes pointing OUT),\n // being in front of ANY plane means being outside the brush.\n // The d2 >= d1 check handles the case where the line is parallel or moving away from the plane.\n if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n // Case 2: Entirely inside this plane (back side).\n // Does not restrict the entry/exit interval further than other planes might.\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n // Case 3: Line intersects the plane.\n // d1 > d2 means we are moving from Front (outside) to Back (inside) -> Entering.\n if (d1 > d2) {\n // Calculate intersection fraction f.\n // DIST_EPSILON is subtracted to ensure we stop slightly *before* the plane,\n // preventing the object from getting stuck in the next frame due to float precision.\n const f = (d1 - DIST_EPSILON) / (d1 - d2);\n if (f > enterfrac) {\n enterfrac = f;\n clipplane = plane;\n leadside = side;\n }\n } else {\n // Moving from Back (inside) to Front (outside) -> Leaving.\n // DIST_EPSILON is added to push the exit point slightly further out (or in depending on perspective),\n // effectively narrowing the \"inside\" interval.\n const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n // If we never started outside any plane, we started inside the brush.\n if (!startout) {\n trace.startsolid = true;\n // If we also never got out of any plane (meaning we stayed behind all planes),\n // then the entire movement is inside the brush (allsolid).\n if (!getout) {\n trace.allsolid = true;\n }\n trace.fraction = 0;\n return;\n }\n\n // If the entry fraction is less than the exit fraction, we have a valid intersection interval.\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n if (enterfrac < 0) enterfrac = 0;\n trace.fraction = enterfrac;\n trace.plane = clipplane;\n trace.contents = brush.contents;\n trace.surfaceFlags = leadside?.surfaceFlags ?? 0;\n }\n}\n\nexport function createDefaultTrace(): TraceResult {\n return {\n fraction: 1,\n plane: null,\n contents: 0,\n surfaceFlags: 0,\n startsolid: false,\n allsolid: false,\n };\n}\n\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\n/**\n * Recursively checks a hull sweep against a BSP tree.\n * Implements a Liang-Barsky like clipping algorithm against the BSP planes.\n *\n * Based on CM_RecursiveHullCheck in qcommon/cm_trace.c.\n */\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n // If we've already hit something earlier in the trace than where we are starting this check,\n // we can stop.\n if (trace.fraction <= startFraction) {\n return;\n }\n\n // If we reached a leaf, check the brushes in it.\n if (nodeIndex < 0) {\n if (traceDebugInfo) {\n traceDebugInfo.leafsReached++;\n }\n\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n // Optimization: Avoid checking the same brush multiple times in a single trace.\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n if (traceDebugInfo) {\n traceDebugInfo.brushesTested++;\n }\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n if (traceDebugInfo) {\n traceDebugInfo.nodesTraversed++;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n\n // Calculate the distance from the plane to the box's nearest corner.\n // This effectively expands the plane by the box extents.\n // Use absolute value of offset like original C code (full/qcommon/cmodel.c:1269-1271).\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start);\n const endDist = planeDistanceToPoint(plane, end);\n\n // If both start and end points are in front of the plane (including offset),\n // we only need to check the front child.\n if (startDist >= offset && endDist >= offset) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n // If both start and end points are behind the plane (including offset),\n // we only need to check the back child.\n if (startDist < -offset && endDist < -offset) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n // The segment straddles the plane. We need to split the segment and recurse down both sides.\n // Put the crosspoint DIST_EPSILON pixels on the near side to avoid precision issues.\n // See full/qcommon/cmodel.c:1293-1313 (CM_RecursiveHullCheck)\n // fraction1 (frac) is used for \"move up to node\" - the near-side recursion\n // fraction2 (frac2) is used for \"go past the node\" - the far-side recursion\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1, fraction2;\n\n if (startDist < endDist) {\n side = 1;\n fraction2 = (startDist + offset + DIST_EPSILON) * idist;\n fraction1 = (startDist - offset + DIST_EPSILON) * idist;\n } else {\n side = 0;\n fraction2 = (startDist - offset - DIST_EPSILON) * idist;\n fraction1 = (startDist + offset + DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n // Recurse down the near side\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n // Optimisation: if we hit something closer than the split point, we don't need to check the far side\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n // Recurse down the far side\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n if (traceDebugInfo) {\n traceDebugInfo.leafsReached++;\n }\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): boolean {\n return !(\n a.mins.x > b.maxs.x ||\n a.maxs.x < b.mins.x ||\n a.mins.y > b.maxs.y ||\n a.maxs.y < b.mins.y ||\n a.mins.z > b.maxs.z ||\n a.maxs.z < b.mins.z\n );\n}\n\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n private readonly entityNodes = new Map<number, SpatialNode>();\n private readonly rootNode = createSpatialTree();\n\n link(entity: CollisionEntityLink): void {\n const state = makeEntityState(entity);\n this.entities.set(entity.id, state);\n\n // Update spatial index\n const existingNode = this.entityNodes.get(entity.id);\n if (existingNode) {\n existingNode.items.delete(entity.id);\n }\n\n const newNode = linkEntityToSpatialTree(\n this.rootNode,\n entity.id,\n state.bounds.mins,\n state.bounds.maxs\n );\n this.entityNodes.set(entity.id, newNode);\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n\n const node = this.entityNodes.get(entityId);\n if (node) {\n node.items.delete(entityId);\n this.entityNodes.delete(entityId);\n }\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n // Determine query bounds for spatial lookup\n const traceAbsMin = {\n x: Math.min(params.start.x, params.end.x) + mins.x,\n y: Math.min(params.start.y, params.end.y) + mins.y,\n z: Math.min(params.start.z, params.end.z) + mins.z,\n };\n const traceAbsMax = {\n x: Math.max(params.start.x, params.end.x) + maxs.x,\n y: Math.max(params.start.y, params.end.y) + maxs.y,\n z: Math.max(params.start.z, params.end.z) + maxs.z,\n };\n\n const candidates = new Set<number>();\n querySpatialTree(this.rootNode, traceAbsMin, traceAbsMax, candidates);\n\n for (const entityId of candidates) {\n if (entityId === passId) continue;\n\n const entity = this.entities.get(entityId);\n if (!entity) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n if (trace.startsolid || trace.allsolid || trace.fraction < bestTrace.fraction) {\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n const candidates = new Set<number>();\n querySpatialTree(this.rootNode, queryBounds.mins, queryBounds.maxs, candidates);\n\n for (const entityId of candidates) {\n const entity = this.entities.get(entityId);\n if (!entity) continue;\n\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\n }\n}\n","export const enum CvarFlags {\n None = 0,\n Archive = 1 << 0,\n UserInfo = 1 << 1,\n ServerInfo = 1 << 2,\n Latch = 1 << 3,\n Cheat = 1 << 4,\n}\n\nexport interface CvarDefinition {\n readonly name: string;\n readonly defaultValue: string;\n readonly description?: string;\n readonly flags?: CvarFlags;\n}\n","// Mirrors the Quake II rerelease configstring/index layout from `game.h`.\n// These constants intentionally track the numeric values used in the C++\n// game and client modules so the TypeScript engine/game/client layers can\n// share deterministic indices for precaches and HUD parsing.\n\nexport const MAX_STRING_CHARS = 1024;\nexport const MAX_STRING_TOKENS = 80;\nexport const MAX_TOKEN_CHARS = 512;\n\nexport const MAX_QPATH = 64;\nexport const MAX_OSPATH = 128;\n\nexport const MAX_CLIENTS = 256;\nexport const MAX_EDICTS = 8192;\nexport const MAX_LIGHTSTYLES = 256;\nexport const MAX_MODELS = 8192;\nexport const MAX_SOUNDS = 2048;\nexport const MAX_IMAGES = 512;\nexport const MAX_ITEMS = 256;\nexport const MAX_GENERAL = MAX_CLIENTS * 2;\nexport const MAX_SHADOW_LIGHTS = 256;\nexport const MAX_WHEEL_ITEMS = 32;\n\nexport const CS_MAX_STRING_LENGTH = 96;\nexport const CS_MAX_STRING_LENGTH_OLD = 64;\n\n// Enum-style numeric constants that mirror the C++ `configstrings` enum. Only\n// the explicitly numbered entries are re-stated here; everything else follows\n// sequentially to keep the arithmetic (e.g., CS_SOUNDS = CS_MODELS +\n// MAX_MODELS) intact.\nexport enum ConfigStringIndex {\n Name = 0,\n CdTrack = 1,\n Sky = 2,\n SkyAxis = 3,\n SkyRotate = 4,\n StatusBar = 5,\n\n // Matching bg_local.h:55-76\n HealthBarName = 55,\n CONFIG_N64_PHYSICS = 56,\n CONFIG_CTF_TEAMS = 57,\n CONFIG_COOP_RESPAWN_STRING = 58,\n Story = 54, // Arbitrarily placed in the gap for now\n\n AirAccel = 59,\n MaxClients = 60,\n MapChecksum = 61,\n\n Models = 62,\n Sounds = Models + MAX_MODELS,\n Images = Sounds + MAX_SOUNDS,\n Lights = Images + MAX_IMAGES,\n ShadowLights = Lights + MAX_LIGHTSTYLES,\n Items = ShadowLights + MAX_SHADOW_LIGHTS,\n Players = Items + MAX_ITEMS, // CS_PLAYERS (contains userinfo with name, skin, etc.)\n PlayerSkins = Players, // Alias for legacy code compatibility\n General = Players + MAX_CLIENTS,\n WheelWeapons = General + MAX_GENERAL,\n WheelAmmo = WheelWeapons + MAX_WHEEL_ITEMS,\n WheelPowerups = WheelAmmo + MAX_WHEEL_ITEMS,\n CdLoopCount = WheelPowerups + MAX_WHEEL_ITEMS,\n GameStyle = CdLoopCount + 1,\n MaxConfigStrings = GameStyle + 1,\n}\n\n// Mirror the C++ MAX_CONFIGSTRINGS value for consumers that prefer a standalone constant.\nexport const MAX_CONFIGSTRINGS = ConfigStringIndex.MaxConfigStrings;\n\n/**\n * Returns the maximum string length permitted for the given configstring index,\n * mirroring the `CS_SIZE` helper in the rerelease. Statusbar and general ranges\n * can legally occupy multiple 96-character slots; everything else is capped at\n * `CS_MAX_STRING_LENGTH`.\n */\nexport function configStringSize(index: number): number {\n if (index >= ConfigStringIndex.StatusBar && index < ConfigStringIndex.AirAccel) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.AirAccel - index);\n }\n\n if (index >= ConfigStringIndex.General && index < ConfigStringIndex.WheelWeapons) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.MaxConfigStrings - index);\n }\n\n return CS_MAX_STRING_LENGTH;\n}\n\n// Legacy constants\nexport const CS_NAME = ConfigStringIndex.Name;\nexport const CS_CDTRACK = ConfigStringIndex.CdTrack;\nexport const CS_SKY = ConfigStringIndex.Sky;\nexport const CS_SKYAXIS = ConfigStringIndex.SkyAxis;\nexport const CS_SKYROTATE = ConfigStringIndex.SkyRotate;\nexport const CS_STATUSBAR = ConfigStringIndex.StatusBar;\nexport const CS_AIRACCEL = ConfigStringIndex.AirAccel;\nexport const CS_MAXCLIENTS = ConfigStringIndex.MaxClients;\nexport const CS_MAPCHECKSUM = ConfigStringIndex.MapChecksum;\nexport const CS_MODELS = ConfigStringIndex.Models;\nexport const CS_SOUNDS = ConfigStringIndex.Sounds;\nexport const CS_IMAGES = ConfigStringIndex.Images;\nexport const CS_LIGHTS = ConfigStringIndex.Lights;\nexport const CS_ITEMS = ConfigStringIndex.Items;\nexport const CS_PLAYERS = ConfigStringIndex.Players;\nexport const CS_GENERAL = ConfigStringIndex.General;\n","export * from './schema.js';\nexport * from './io.js';\n","import { ReplaySession, ReplayFrame } from './schema.js';\nimport { UserCommand } from '../protocol/usercmd.js';\n\nexport function serializeReplay(session: ReplaySession): string {\n return JSON.stringify(session, null, 2);\n}\n\nexport function deserializeReplay(json: string): ReplaySession {\n const session = JSON.parse(json);\n\n // Validate structure lightly\n if (!session.metadata || !Array.isArray(session.frames)) {\n throw new Error('Invalid replay format: missing metadata or frames');\n }\n\n return session as ReplaySession;\n}\n\nexport function createReplaySession(map: string, seed?: number): ReplaySession {\n return {\n metadata: {\n map,\n date: new Date().toISOString(),\n version: '1.0',\n seed\n },\n frames: []\n };\n}\n\nexport function addReplayFrame(session: ReplaySession, cmd: UserCommand, serverFrame: number, startTime: number) {\n session.frames.push({\n serverFrame,\n cmd,\n timestamp: Date.now() - startTime\n });\n}\n","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\n","/**\n * Mirrors the Quake II rerelease `water_level_t` enumeration from `game.h`\n * (lines 443-449). These numeric values are relied upon throughout the\n * movement code when checking how submerged a player is, so we keep the same\n * ordering to make future porting work straightforward.\n */\nexport enum WaterLevel {\n None = 0,\n Feet = 1,\n Waist = 2,\n Under = 3,\n}\n\n/**\n * Utility that matches the common rerelease checks that treat any level at or\n * above the `WATER_WAIST` constant as \"significantly submerged\" for friction\n * and current calculations.\n */\nexport function isAtLeastWaistDeep(level: WaterLevel): boolean {\n return level >= WaterLevel.Waist;\n}\n\n/**\n * Returns true when the player is considered underwater (the `WATER_UNDER`\n * case in the rerelease). This mirrors the places in `p_move.cpp` that gate\n * effects such as breath timers and screen warping.\n */\nexport function isUnderwater(level: WaterLevel): boolean {\n return level === WaterLevel.Under;\n}\n\n/**\n * Matches the Quake II rerelease `pmflags_t` bit layout from `game.h` so the\n * shared helpers can manipulate the same flag words as the authoritative game\n * and the client prediction layer.\n */\nexport const enum PmFlag {\n Ducked = 1 << 0,\n JumpHeld = 1 << 1,\n OnGround = 1 << 2,\n TimeWaterJump = 1 << 3,\n TimeLand = 1 << 4,\n TimeTeleport = 1 << 5,\n NoPositionalPrediction = 1 << 6,\n OnLadder = 1 << 7,\n NoAngularPrediction = 1 << 8,\n IgnorePlayerCollision = 1 << 9,\n TimeTrick = 1 << 10,\n}\n\nexport type PmFlags = number;\n\nexport function hasPmFlag(flags: PmFlags, flag: PmFlag): boolean {\n return (flags & flag) !== 0;\n}\n\nexport function addPmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags | flag;\n}\n\nexport function removePmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags & ~flag;\n}\n\n/**\n * Player movement types mirrored from the rerelease `pmtype_t` enumeration.\n * The exact numeric values matter when syncing pmove state across the network\n * so we keep the same order as the C++ definition.\n */\nexport enum PmType {\n Normal = 0,\n Grapple = 1,\n NoClip = 2,\n Spectator = 3,\n Dead = 4,\n Gib = 5,\n Freeze = 6,\n}\n\n/**\n * Bitmask constants for the `buttons` field on the Quake II player command\n * structure. These mirror the rerelease `BUTTON_*` definitions so logic such as\n * jump/crouch checks can be shared between the server and client.\n */\nexport const enum PlayerButton {\n None = 0,\n Attack = 1 << 0,\n Use = 1 << 1,\n Holster = 1 << 2,\n Jump = 1 << 3,\n Crouch = 1 << 4,\n Attack2 = 1 << 5,\n Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel, type PmFlags, PmFlag, PmType, PlayerButton, addPmFlag, removePmFlag } from './constants.js';\n\nconst DEFAULT_JUMP_HEIGHT = 270;\n\nexport interface CheckJumpParams {\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly origin: Vec3;\n readonly jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly origin: Vec3;\n readonly jumpSound: boolean;\n readonly jumped: boolean;\n}\n\nfunction hasButton(buttons: number, button: PlayerButton): boolean {\n return (buttons & button) !== 0;\n}\n\n/**\n * Pure translation of the rerelease `PM_CheckJump` helper from `p_move.cpp`.\n * The function takes in the minimal pmove state that the original C++ logic\n * touches and returns the updated flag/origin/velocity tuple so callers can\n * apply the same semantics on both the server and client.\n */\nexport function checkJump(params: CheckJumpParams): CheckJumpResult {\n const { pmFlags, pmType, buttons, waterlevel, onGround, velocity, origin, jumpHeight = DEFAULT_JUMP_HEIGHT } = params;\n\n // PM_CheckJump immediately bails while the landing timer is active.\n if (pmFlags & PmFlag.TimeLand) {\n return { pmFlags, onGround, velocity, origin, jumpSound: false, jumped: false };\n }\n\n const holdingJump = hasButton(buttons, PlayerButton.Jump);\n let nextFlags = pmFlags;\n let nextOnGround = onGround;\n let jumpSound = false;\n let jumped = false;\n let nextVelocity = velocity;\n let nextOrigin = origin;\n\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n nextFlags = addPmFlag(nextFlags, PmFlag.JumpHeld);\n nextFlags = removePmFlag(nextFlags, PmFlag.OnGround);\n nextOnGround = false;\n jumpSound = true;\n jumped = true;\n\n const z = velocity.z + jumpHeight;\n const finalZ = z < jumpHeight ? jumpHeight : z;\n nextVelocity = { ...velocity, z: finalZ };\n\n // Unstuck from ground: pm->s.origin[2] += 1;\n nextOrigin = { ...origin, z: origin.z + 1 };\n\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\n}\n","import type { ContentsFlag } from '../bsp/contents.js';\nimport {\n CONTENTS_CURRENT_0,\n CONTENTS_CURRENT_180,\n CONTENTS_CURRENT_270,\n CONTENTS_CURRENT_90,\n CONTENTS_CURRENT_DOWN,\n CONTENTS_CURRENT_UP,\n CONTENTS_LADDER,\n MASK_CURRENT,\n} from '../bsp/contents.js';\nimport { addVec3, crossVec3, normalizeVec3, scaleVec3, ZERO_VEC3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, WaterLevel, isAtLeastWaistDeep } from './constants.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nexport interface WaterCurrentParams {\n readonly watertype: ContentsFlag;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly waterSpeed: number;\n}\n\nexport interface GroundCurrentParams {\n readonly groundContents: ContentsFlag;\n readonly scale?: number;\n}\n\nexport interface AddCurrentsParams {\n readonly wishVelocity: Vec3;\n readonly onLadder: boolean;\n readonly onGround: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n readonly groundContents: ContentsFlag;\n readonly cmd: PmoveCmd;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly waterSpeed: number;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace?: PmoveTraceFn;\n}\n\nconst DEFAULT_GROUND_CURRENT_SCALE = 100;\nconst DEFAULT_FORWARD_LADDER_CLAMP = 200;\nconst DEFAULT_SIDE_LADDER_CLAMP = 150;\nconst LADDER_HORIZONTAL_CAP = 25;\nconst LADDER_ASCEND_PITCH_THRESHOLD = 15;\nconst LADDER_TRACE_DISTANCE = 1;\nconst UP_VECTOR: Vec3 = { x: 0, y: 0, z: 1 };\n\nconst DEFAULT_TRACE: PmoveTraceFn = (_, end) => ({\n fraction: 1,\n endpos: end,\n allsolid: false,\n startsolid: false,\n});\n\n/**\n * Mirrors the rerelease pattern in `p_move.cpp` (lines 730-765) that turns the\n * directional CONTENTS_CURRENT_* flags into a unit-ish direction vector.\n */\nexport function currentVectorFromContents(contents: ContentsFlag): Vec3 {\n let x = 0;\n let y = 0;\n let z = 0;\n\n if (contents & CONTENTS_CURRENT_0) {\n x += 1;\n }\n if (contents & CONTENTS_CURRENT_90) {\n y += 1;\n }\n if (contents & CONTENTS_CURRENT_180) {\n x -= 1;\n }\n if (contents & CONTENTS_CURRENT_270) {\n y -= 1;\n }\n if (contents & CONTENTS_CURRENT_UP) {\n z += 1;\n }\n if (contents & CONTENTS_CURRENT_DOWN) {\n z -= 1;\n }\n\n if (x === 0 && y === 0 && z === 0) {\n return ZERO_VEC3;\n }\n\n return { x, y, z };\n}\n\n/**\n * Computes the velocity contribution from water currents using the same rules\n * as `PM_WaterMove`: the CONTENTS_CURRENT_* bits are turned into a direction\n * vector, scaled by `pm_waterspeed`, and halved when the player only has their\n * feet submerged while standing on solid ground.\n */\nexport function waterCurrentVelocity(params: WaterCurrentParams): Vec3 {\n const { watertype, waterlevel, onGround, waterSpeed } = params;\n\n if ((watertype & MASK_CURRENT) === 0) {\n return ZERO_VEC3;\n }\n\n const direction = currentVectorFromContents(watertype);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n let scale = waterSpeed;\n if (waterlevel === WaterLevel.Feet && onGround) {\n scale *= 0.5;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Computes the conveyor-style velocity that should be applied while touching a\n * ground plane that carries CONTENTS_CURRENT_* bits. The rerelease multiplies\n * the direction vector by 100 units per second, so we expose the same default\n * while allowing callers to override the scalar for tests.\n */\nexport function groundCurrentVelocity(params: GroundCurrentParams): Vec3 {\n const { groundContents, scale = DEFAULT_GROUND_CURRENT_SCALE } = params;\n\n const direction = currentVectorFromContents(groundContents);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Pure mirror of PM_AddCurrents from rerelease `p_move.cpp`: handles ladder\n * specific motion tweaks, water currents, and conveyor-style ground currents\n * before pmove acceleration is applied.\n */\nexport function applyPmoveAddCurrents(params: AddCurrentsParams): Vec3 {\n const {\n wishVelocity,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed,\n ladderMod,\n waterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace = DEFAULT_TRACE,\n } = params;\n\n let adjusted = wishVelocity;\n\n if (onLadder) {\n adjusted = applyLadderAdjustments({\n wishVelocity: adjusted,\n cmd,\n waterlevel,\n viewPitch,\n maxSpeed,\n ladderMod,\n onGround,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n }\n\n const waterVelocity = waterCurrentVelocity({ watertype, waterlevel, onGround, waterSpeed });\n if (waterVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, waterVelocity);\n }\n\n if (onGround) {\n const groundVelocity = groundCurrentVelocity({ groundContents });\n if (groundVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, groundVelocity);\n }\n }\n\n return adjusted;\n}\n\ninterface LadderAdjustParams {\n readonly wishVelocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly onGround: boolean;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nfunction applyLadderAdjustments(params: LadderAdjustParams): Vec3 {\n const { wishVelocity, cmd, waterlevel, viewPitch, maxSpeed, ladderMod, onGround, forward, origin, mins, maxs, trace } = params;\n const buttons = cmd.buttons ?? 0;\n let adjusted = { ...wishVelocity };\n\n if ((buttons & (PlayerButton.Jump | PlayerButton.Crouch)) !== 0) {\n const ladderSpeed = isAtLeastWaistDeep(waterlevel) ? maxSpeed : DEFAULT_FORWARD_LADDER_CLAMP;\n adjusted = {\n ...adjusted,\n z: buttons & PlayerButton.Jump ? ladderSpeed : -ladderSpeed,\n };\n } else if (cmd.forwardmove) {\n const clamped = clamp(cmd.forwardmove, -DEFAULT_FORWARD_LADDER_CLAMP, DEFAULT_FORWARD_LADDER_CLAMP);\n if (cmd.forwardmove > 0) {\n const climb = viewPitch < LADDER_ASCEND_PITCH_THRESHOLD ? clamped : -clamped;\n adjusted = { ...adjusted, z: climb };\n } else {\n if (!onGround) {\n adjusted = { ...adjusted, x: 0, y: 0 };\n }\n adjusted = { ...adjusted, z: clamped };\n }\n } else {\n adjusted = { ...adjusted, z: 0 };\n }\n\n if (!onGround) {\n if (cmd.sidemove) {\n let sideSpeed = clamp(cmd.sidemove, -DEFAULT_SIDE_LADDER_CLAMP, DEFAULT_SIDE_LADDER_CLAMP);\n if (waterlevel < WaterLevel.Waist) {\n sideSpeed *= ladderMod;\n }\n\n const flatForward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n if (flatForward.x !== 0 || flatForward.y !== 0) {\n const spot = addVec3(origin, scaleVec3(flatForward, LADDER_TRACE_DISTANCE));\n const tr = trace(origin, spot, mins, maxs);\n if (\n tr.fraction !== 1 &&\n !tr.allsolid &&\n tr.contents !== undefined &&\n (tr.contents & CONTENTS_LADDER) !== 0 &&\n tr.planeNormal\n ) {\n const right = crossVec3(tr.planeNormal, UP_VECTOR);\n adjusted = { ...adjusted, x: 0, y: 0 };\n adjusted = addVec3(adjusted, scaleVec3(right, -sideSpeed));\n }\n }\n } else {\n adjusted = {\n ...adjusted,\n x: clampHorizontal(adjusted.x),\n y: clampHorizontal(adjusted.y),\n };\n }\n }\n\n return adjusted;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction clampHorizontal(value: number): number {\n if (value < -LADDER_HORIZONTAL_CAP) {\n return -LADDER_HORIZONTAL_CAP;\n }\n if (value > LADDER_HORIZONTAL_CAP) {\n return LADDER_HORIZONTAL_CAP;\n }\n return value;\n}\n","import { addVec3, ZERO_VEC3, clipVelocityVec3, crossVec3, dotVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst DEFAULT_MAX_CLIP_PLANES = 5;\nconst DEFAULT_MAX_BUMPS = 4;\nconst DEFAULT_STEP_SIZE = 18;\nconst MIN_STEP_NORMAL = 0.7;\n\nexport const SLIDEMOVE_BLOCKED_FLOOR = 1;\nexport const SLIDEMOVE_BLOCKED_WALL = 2;\n\nexport interface SlideMoveResult {\n readonly velocity: Vec3;\n readonly planes: readonly Vec3[];\n readonly stopped: boolean;\n}\n\nexport interface SlideMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly overbounce: number;\n readonly trace: PmoveTraceFn;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n /**\n * Mirrors the pm->s.pm_time check in PM_StepSlideMove_Generic: if true, the\n * returned velocity is reset to the primal velocity after collision\n * resolution so time-based effects (like knockbacks) don't dampen.\n */\n readonly hasTime?: boolean;\n}\n\nexport interface SlideMoveOutcome extends SlideMoveResult {\n readonly origin: Vec3;\n readonly blocked: number;\n}\n\nexport interface StepSlideMoveParams extends SlideMoveParams {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly stepSize?: number;\n}\n\nexport interface StepSlideMoveOutcome extends SlideMoveOutcome {\n readonly stepped: boolean;\n readonly stepHeight: number;\n readonly stepNormal?: Vec3;\n}\n\n/**\n * Resolves a sequence of collision planes against a primal velocity using the same\n * plane iteration logic seen in PM_StepSlideMove_Generic (rerelease p_move.cpp).\n * The incoming planes should be ordered as they were encountered during traces;\n * the function will accumulate them, clip the velocity to be parallel to all planes,\n * and return zero velocity when three planes form an unresolvable corner or when\n * the adjusted velocity would oppose the primal direction.\n */\nexport function resolveSlideMove(\n initialVelocity: Vec3,\n planesEncountered: readonly Vec3[],\n overbounce: number,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n primalVelocity: Vec3 = initialVelocity,\n): SlideMoveResult {\n if (planesEncountered.length === 0) {\n return { velocity: initialVelocity, planes: [], stopped: false };\n }\n\n const planes: Vec3[] = [];\n let velocity: Vec3 = initialVelocity;\n\n for (const plane of planesEncountered) {\n if (planes.length >= maxClipPlanes) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n // Skip near-duplicate planes to mirror the epsilon guard in PM_StepSlideMove_Generic.\n const duplicate = planes.find((existing) => dotVec3(existing, plane) > 0.99);\n if (duplicate) {\n continue;\n }\n\n planes.push(plane);\n\n let clipped: Vec3 | undefined;\n let i = 0;\n for (; i < planes.length; i++) {\n const candidate = clipVelocityVec3(velocity, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) continue;\n if (dotVec3(candidate, planes[j]) < 0) break;\n }\n\n if (j === planes.length) {\n clipped = candidate;\n break;\n }\n }\n\n if (clipped) {\n velocity = clipped;\n } else {\n if (planes.length !== 2) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n velocity = scaleVec3(dir, d);\n }\n\n // If velocity reversed relative to the primal direction, stop to avoid oscillations.\n if (dotVec3(velocity, primalVelocity) <= 0) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n }\n\n const stopped = velocity.x === 0 && velocity.y === 0 && velocity.z === 0;\n return { velocity, planes, stopped };\n}\n\n/**\n * Pure mirror of PM_SlideMoveGeneric from rerelease `p_move.cpp` (minus gravity/step handling).\n * Uses a caller-provided trace to collect collision planes, accumulates them through\n * `resolveSlideMove`, and returns the resulting origin/velocity/blocking state.\n */\nexport function slideMove(params: SlideMoveParams): SlideMoveOutcome {\n const {\n origin: initialOrigin,\n velocity: initialVelocity,\n frametime,\n overbounce,\n trace,\n maxBumps = DEFAULT_MAX_BUMPS,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n mins,\n maxs,\n hasTime = false,\n } = params;\n\n let origin = initialOrigin;\n let velocity = initialVelocity;\n const planes: Vec3[] = [];\n const primalVelocity = initialVelocity;\n let timeLeft = frametime;\n let blocked = 0;\n\n for (let bump = 0; bump < maxBumps; bump++) {\n if (velocity.x === 0 && velocity.y === 0 && velocity.z === 0) {\n break;\n }\n\n const end = addVec3(origin, scaleVec3(velocity, timeLeft));\n const tr = trace(origin, end, mins, maxs);\n\n if (tr.allsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.startsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.fraction > 0) {\n origin = tr.endpos;\n }\n\n if (tr.fraction === 1) {\n break;\n }\n\n if (!tr.planeNormal) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.planeNormal.z > 0.7) {\n blocked |= SLIDEMOVE_BLOCKED_FLOOR;\n }\n if (tr.planeNormal.z === 0) {\n blocked |= SLIDEMOVE_BLOCKED_WALL;\n }\n\n planes.push(tr.planeNormal);\n timeLeft -= timeLeft * tr.fraction;\n\n const resolved = resolveSlideMove(velocity, planes, overbounce, maxClipPlanes, primalVelocity);\n velocity = resolved.velocity;\n planes.splice(0, planes.length, ...resolved.planes);\n\n if (primalVelocity.z > 0 && velocity.z < 0) {\n velocity = { ...velocity, z: 0 };\n }\n\n if (resolved.stopped) {\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: true, blocked };\n }\n }\n\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: velocityOut.x === 0 && velocityOut.y === 0 && velocityOut.z === 0, blocked };\n}\n\n/**\n * Mirrors PM_StepSlideMove (rerelease p_move.cpp) in a pure form: attempts a\n * regular slide move, then retries from a stepped-up position when the first\n * attempt was blocked. The function compares planar distance traveled and the\n * steepness of the landing plane to decide whether to keep the step.\n */\nexport function stepSlideMove(params: StepSlideMoveParams): StepSlideMoveOutcome {\n const { mins, maxs, stepSize = DEFAULT_STEP_SIZE, ...rest } = params;\n\n const startOrigin = params.origin;\n const startVelocity = params.velocity;\n\n const downResult = slideMove({ ...rest, mins, maxs });\n\n const upTarget = addVec3(startOrigin, { x: 0, y: 0, z: stepSize });\n const upTrace = rest.trace(startOrigin, upTarget, mins, maxs);\n if (upTrace.allsolid) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const actualStep = upTrace.endpos.z - startOrigin.z;\n const steppedResult = slideMove({ ...rest, origin: upTrace.endpos, velocity: startVelocity, mins, maxs });\n\n const pushDownTarget = addVec3(steppedResult.origin, { x: 0, y: 0, z: -actualStep });\n const downTrace = rest.trace(steppedResult.origin, pushDownTarget, mins, maxs);\n\n let steppedOrigin = steppedResult.origin;\n let stepNormal = downTrace.planeNormal;\n\n if (!downTrace.allsolid) {\n steppedOrigin = downTrace.endpos;\n }\n\n const planarDistanceSquared = (a: Vec3, b: Vec3) => (a.x - b.x) ** 2 + (a.y - b.y) ** 2;\n const downDist = planarDistanceSquared(downResult.origin, startOrigin);\n const upDist = planarDistanceSquared(steppedOrigin, startOrigin);\n\n if (downDist > upDist || (stepNormal && stepNormal.z < MIN_STEP_NORMAL)) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const steppedVelocity = { ...steppedResult.velocity, z: downResult.velocity.z };\n const steppedBlocked = steppedResult.blocked;\n const stopped = steppedVelocity.x === 0 && steppedVelocity.y === 0 && steppedVelocity.z === 0;\n\n return {\n origin: steppedOrigin,\n velocity: steppedVelocity,\n planes: steppedResult.planes,\n blocked: steppedBlocked,\n stopped,\n stepped: true,\n stepHeight: actualStep,\n stepNormal,\n };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport { applyPmoveAccelerate, applyPmoveAirAccelerate } from './pmove.js';\nimport { applyPmoveAddCurrents } from './currents.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n PlayerButton,\n WaterLevel,\n hasPmFlag,\n} from './constants.js';\n\ninterface BaseMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly hasTime?: boolean;\n}\n\nexport interface AirMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly gravity: number;\n readonly pmType: PmType;\n readonly pmAccelerate: number;\n readonly pmAirAccelerate?: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly onLadder: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly groundContents: number;\n readonly viewPitch: number;\n readonly ladderMod: number;\n readonly pmWaterSpeed: number;\n}\n\nexport interface WaterMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly pmWaterAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly onLadder: boolean;\n readonly watertype: number;\n readonly groundContents: number;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly ladderMod: number;\n}\n\nexport interface WalkMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly gravity: number;\n readonly pmType: PmType;\n readonly pmAccelerate: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly onLadder: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly groundContents: number;\n readonly viewPitch: number;\n readonly ladderMod: number;\n readonly pmWaterSpeed: number;\n}\n\nconst DEFAULT_AIR_ACCELERATE = 1;\nconst WATER_DRIFT_SPEED = 60;\nconst DEFAULT_STEP_OVERBOUNCE = 1.01;\n\nexport function applyPmoveAirMove(params: AirMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n gravity,\n pmType,\n pmAccelerate,\n pmAirAccelerate = DEFAULT_AIR_ACCELERATE,\n pmMaxSpeed,\n pmDuckSpeed,\n onLadder,\n waterlevel,\n watertype,\n groundContents,\n viewPitch,\n ladderMod,\n pmWaterSpeed,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildPlanarWishVelocity(forward, right, cmd);\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n const maxSpeed = ducked ? pmDuckSpeed : pmMaxSpeed;\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n if (onLadder) {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (Math.abs(wishvel.z) < Number.EPSILON) {\n velocity = dampVerticalVelocity(velocity, gravity, frametime);\n }\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (onGround) {\n velocity = { ...velocity, z: 0 };\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (gravity > 0) {\n velocity = { ...velocity, z: 0 };\n } else {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n if (velocity.x === 0 && velocity.y === 0) {\n return {\n origin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: true,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (pmAirAccelerate > 0) {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir,\n wishspeed,\n accel: pmAirAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: DEFAULT_AIR_ACCELERATE, frametime });\n }\n\n if (pmType !== PmType.Grapple) {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nexport function applyPmoveWaterMove(params: WaterMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n pmMaxSpeed,\n pmDuckSpeed,\n pmWaterAccelerate,\n pmWaterSpeed,\n onLadder,\n watertype,\n groundContents,\n waterlevel,\n viewPitch,\n ladderMod,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildFullWishVelocity(forward, right, cmd);\n\n if (isIdleInWater(cmd, onGround)) {\n wishvel = { ...wishvel, z: wishvel.z - WATER_DRIFT_SPEED };\n } else {\n if (hasButton(cmd, PlayerButton.Crouch)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: -pmWaterSpeed * 0.5 });\n } else if (hasButton(cmd, PlayerButton.Jump)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: pmWaterSpeed * 0.5 });\n }\n }\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmMaxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n wishspeed *= 0.5;\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n if (ducked && wishspeed > pmDuckSpeed) {\n const scale = pmDuckSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmDuckSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmWaterAccelerate, frametime });\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nexport function applyPmoveWalkMove(params: WalkMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n gravity,\n pmAccelerate,\n pmMaxSpeed,\n pmDuckSpeed,\n onLadder,\n waterlevel,\n watertype,\n groundContents,\n viewPitch,\n ladderMod,\n pmWaterSpeed,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildPlanarWishVelocity(forward, right, cmd);\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n const maxSpeed = ducked ? pmDuckSpeed : pmMaxSpeed;\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n // Ground friction handled by caller (applyPmoveFriction)\n\n velocity = { ...velocity, z: 0 };\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n\n if (gravity > 0) {\n velocity = { ...velocity, z: 0 };\n } else {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n if (velocity.x === 0 && velocity.y === 0) {\n return {\n origin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: true,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nfunction buildPlanarWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n}\n\nfunction buildFullWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: forward.z * cmd.forwardmove + right.z * cmd.sidemove,\n } satisfies Vec3;\n}\n\nfunction hasButton(cmd: PmoveCmd, button: PlayerButton): boolean {\n return (cmd.buttons ?? 0) & button ? true : false;\n}\n\nfunction isIdleInWater(cmd: PmoveCmd, onGround: boolean): boolean {\n const noMove = cmd.forwardmove === 0 && cmd.sidemove === 0;\n const noButtons = (cmd.buttons ?? 0) & (PlayerButton.Jump | PlayerButton.Crouch) ? false : true;\n return noMove && noButtons && !onGround;\n}\n\nfunction dampVerticalVelocity(velocity: Vec3, gravity: number, frametime: number): Vec3 {\n let z = velocity.z;\n const delta = gravity * frametime;\n if (z > 0) {\n z -= delta;\n if (z < 0) {\n z = 0;\n }\n } else {\n z += delta;\n if (z > 0) {\n z = 0;\n }\n }\n return { ...velocity, z };\n}\n\ninterface StepParams extends BaseMoveParams {\n readonly velocity: Vec3;\n}\n\nfunction runStepSlideMove(params: StepParams): StepSlideMoveOutcome {\n const { origin, velocity, frametime, mins, maxs, trace, overbounce = DEFAULT_STEP_OVERBOUNCE, stepSize, maxBumps, maxClipPlanes, hasTime } = params;\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n","import { MASK_WATER, CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel } from './constants.js';\nimport type { PmovePointContentsFn } from './types.js';\n\nexport interface WaterLevelParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly viewheight: number;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface WaterLevelResult {\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n}\n\n/**\n * Mirrors the rerelease `PM_GetWaterLevel` helper: probes the player's feet,\n * waist, and viewheight to determine how submerged they are and returns both\n * the enum level plus the contents bits encountered at the lowest sample.\n */\nexport function getWaterLevel(params: WaterLevelParams): WaterLevelResult {\n const { origin, mins, viewheight, pointContents } = params;\n\n const sample2 = viewheight - mins.z;\n const sample1 = sample2 / 2;\n\n const point: Vec3 = {\n x: origin.x,\n y: origin.y,\n z: origin.z + mins.z + 1,\n };\n\n let contents = pointContents(point);\n if ((contents & MASK_WATER) === 0) {\n return { waterlevel: WaterLevel.None, watertype: CONTENTS_NONE };\n }\n\n const watertype = contents;\n let waterlevel = WaterLevel.Feet;\n\n let point2: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample1 };\n contents = pointContents(point2);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Waist;\n\n let point3: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample2 };\n contents = pointContents(point3);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Under;\n }\n }\n\n return { waterlevel, watertype };\n}\n","import { CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport { addVec3, clipVelocityVec3, type Vec3 } from '../math/vec3.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport { getWaterLevel } from './water.js';\nimport type { PmovePointContentsFn, PmoveTraceFn, PmoveTraceResult } from './types.js';\n\nconst GROUND_PROBE_DISTANCE = 0.25;\nconst LADDER_BYPASS_VELOCITY = 180;\nconst TRICK_VELOCITY_THRESHOLD = 100;\nconst SLANTED_NORMAL_THRESHOLD = 0.7;\nconst TRICK_NORMAL_THRESHOLD = 0.9;\nconst TRICK_PM_TIME = 64;\nconst LAND_PM_TIME = 128;\nconst IMPACT_CLIP_OVERBOUNCE = 1.01;\n\nconst WATERJUMP_CLEAR =\n PmFlag.TimeWaterJump | PmFlag.TimeLand | PmFlag.TimeTeleport | PmFlag.TimeTrick;\n\nexport interface CategorizePositionParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly n64Physics: boolean;\n readonly velocity: Vec3;\n readonly startVelocity: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface CategorizePositionResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly onGround: boolean;\n readonly groundTrace?: PmoveTraceResult;\n readonly groundContents: ContentsFlag;\n readonly waterlevel: number;\n readonly watertype: ContentsFlag;\n readonly impactDelta?: number;\n}\n\n/**\n * Pure mirror of PM_CatagorizePosition from `rerelease/p_move.cpp`: traces a quarter-unit\n * below the player bounds to determine whether they stand on solid ground, updates timers\n * and pmflags accordingly, records the latest ground plane data, and recalculates waterlevel\n * by probing feet/waist/viewheight samples.\n */\nexport function categorizePosition(params: CategorizePositionParams): CategorizePositionResult {\n const {\n pmType,\n n64Physics,\n velocity,\n startVelocity,\n origin,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n } = params;\n\n let pmFlags = params.pmFlags;\n let pmTime = params.pmTime;\n let impactDelta: number | undefined;\n let onGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n let groundTrace: PmoveTraceResult | undefined;\n let groundContents: ContentsFlag = CONTENTS_NONE;\n\n const forceAirborne = velocity.z > LADDER_BYPASS_VELOCITY || pmType === PmType.Grapple;\n\n if (forceAirborne) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n const end: Vec3 = { x: origin.x, y: origin.y, z: origin.z - GROUND_PROBE_DISTANCE };\n const traceResult = trace(origin, end, mins, maxs);\n groundTrace = traceResult;\n groundContents = traceResult.contents ?? CONTENTS_NONE;\n\n const planeNormal = traceResult.planeNormal;\n\n let slantedGround =\n traceResult.fraction < 1 && !!planeNormal && planeNormal.z < SLANTED_NORMAL_THRESHOLD;\n\n if (slantedGround && planeNormal) {\n const slantEnd = addVec3(origin, planeNormal);\n const slantTrace = trace(origin, slantEnd, mins, maxs);\n if (slantTrace.fraction < 1 && !slantTrace.startsolid) {\n slantedGround = false;\n }\n }\n\n if (\n traceResult.fraction === 1 ||\n !planeNormal ||\n (slantedGround && !traceResult.startsolid)\n ) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n onGround = true;\n\n if (hasPmFlag(pmFlags, PmFlag.TimeWaterJump)) {\n pmFlags &= ~WATERJUMP_CLEAR;\n pmTime = 0;\n }\n\n const wasOnGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround) {\n if (\n !n64Physics &&\n velocity.z >= TRICK_VELOCITY_THRESHOLD &&\n planeNormal.z >= TRICK_NORMAL_THRESHOLD &&\n !hasPmFlag(pmFlags, PmFlag.Ducked)\n ) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeTrick);\n pmTime = TRICK_PM_TIME;\n }\n\n const clipped = clipVelocityVec3(velocity, planeNormal, IMPACT_CLIP_OVERBOUNCE);\n impactDelta = startVelocity.z - clipped.z;\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround && (n64Physics || hasPmFlag(pmFlags, PmFlag.Ducked))) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeLand);\n pmTime = LAND_PM_TIME;\n }\n }\n }\n\n const { waterlevel, watertype } = getWaterLevel({\n origin,\n mins,\n viewheight,\n pointContents,\n });\n\n return {\n pmFlags,\n pmTime,\n onGround: hasPmFlag(pmFlags, PmFlag.OnGround),\n groundTrace,\n groundContents,\n waterlevel,\n watertype,\n impactDelta,\n };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { PmFlag, type PmFlags, PmType } from './constants.js';\n\nexport interface PlayerDimensions {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n}\n\nfunction createVec3(x: number, y: number, z: number): Vec3 {\n return { x, y, z } satisfies Vec3;\n}\n\n/**\n * Pure mirror of PM_SetDimensions from rerelease `p_move.cpp`.\n * Computes the mins/maxs/viewheight triplet for a player based on\n * their movement type and ducked flag without mutating inputs.\n */\nexport function computePlayerDimensions(pmType: PmType, pmFlags: PmFlags): PlayerDimensions {\n const minsBase = createVec3(-16, -16, 0);\n const maxsBase = createVec3(16, 16, 16);\n\n if (pmType === PmType.Gib) {\n return {\n mins: minsBase,\n maxs: maxsBase,\n viewheight: 8,\n } satisfies PlayerDimensions;\n }\n\n const ducked = pmType === PmType.Dead || (pmFlags & PmFlag.Ducked) !== 0;\n const mins = createVec3(minsBase.x, minsBase.y, -24);\n const maxs = createVec3(maxsBase.x, maxsBase.y, ducked ? 4 : 32);\n\n return {\n mins,\n maxs,\n viewheight: ducked ? -2 : 22,\n } satisfies PlayerDimensions;\n}\n","import { MASK_SOLID, MASK_WATER, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport {\n PlayerButton,\n PmFlag,\n type PmFlags,\n PmType,\n WaterLevel,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport type { PmoveTraceResult } from './types.js';\nimport { computePlayerDimensions, type PlayerDimensions } from './dimensions.js';\n\nconst CROUCH_MAX_Z = 4;\nconst STAND_MAX_Z = 32;\nconst ABOVE_WATER_OFFSET = 8;\n\nexport interface DuckTraceParams {\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly mask: ContentsFlag;\n}\n\nexport type DuckTraceFn = (params: DuckTraceParams) => PmoveTraceResult;\n\nexport interface CheckDuckParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly hasGroundEntity: boolean;\n readonly onLadder: boolean;\n readonly n64Physics: boolean;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: DuckTraceFn;\n}\n\nexport interface CheckDuckResult extends PlayerDimensions {\n readonly pmFlags: PmFlags;\n readonly ducked: boolean;\n readonly changed: boolean;\n}\n\n/**\n * Pure port of PM_CheckDuck from rerelease `p_move.cpp`. Updates the PMF_DUCKED flag\n * based on crouch input, obstruction traces, and special cases (dead bodies) without\n * mutating the provided mins/maxs. Returns the updated flag word plus the dimensions\n * computed from PM_SetDimensions so callers can update collision bounds atomically.\n */\nexport function checkDuckState(params: CheckDuckParams): CheckDuckResult {\n const { pmType } = params;\n\n if (pmType === PmType.Gib) {\n const dims = computePlayerDimensions(pmType, params.pmFlags);\n return { pmFlags: params.pmFlags, ducked: hasPmFlag(params.pmFlags, PmFlag.Ducked), changed: false, ...dims };\n }\n\n let flags = params.pmFlags;\n let changed = false;\n\n if (pmType === PmType.Dead) {\n if (!hasPmFlag(flags, PmFlag.Ducked)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (shouldDuck(params)) {\n if (!hasPmFlag(flags, PmFlag.Ducked) && !isDuckBlocked(params)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (hasPmFlag(flags, PmFlag.Ducked) && !isStandBlocked(params)) {\n flags = removePmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n\n const dims = computePlayerDimensions(pmType, flags);\n const ducked = pmType === PmType.Dead || hasPmFlag(flags, PmFlag.Ducked);\n\n return { pmFlags: flags, ducked, changed, ...dims };\n}\n\nfunction shouldDuck(params: CheckDuckParams): boolean {\n if ((params.buttons & PlayerButton.Crouch) === 0) {\n return false;\n }\n if (params.onLadder || params.n64Physics) {\n return false;\n }\n if (params.hasGroundEntity) {\n return true;\n }\n if (params.waterlevel <= WaterLevel.Feet && !isAboveWater(params)) {\n return true;\n }\n return false;\n}\n\nfunction isDuckBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, CROUCH_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isStandBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, STAND_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isAboveWater(params: CheckDuckParams): boolean {\n const below: Vec3 = { x: params.origin.x, y: params.origin.y, z: params.origin.z - ABOVE_WATER_OFFSET };\n\n const solidTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_SOLID,\n });\n\n if (solidTrace.fraction < 1) {\n return false;\n }\n\n const waterTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_WATER,\n });\n\n return waterTrace.fraction < 1;\n}\n\nfunction withZ(vec: Vec3, z: number): Vec3 {\n return { x: vec.x, y: vec.y, z };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport { angleVectors } from '../math/angles.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n PmoveState,\n PmoveImports,\n PmoveTraceResult\n} from './types.js';\nimport { PlayerButton, PmFlag, PmType, addPmFlag, removePmFlag } from './constants.js';\nimport { checkJump } from './jump.js';\nimport { applyPmoveAirMove, applyPmoveWaterMove, applyPmoveWalkMove } from './move.js';\nimport { categorizePosition } from './categorize.js';\nimport { checkDuckState, DuckTraceParams } from './duck.js';\n// import { updateViewOffsets } from './view.js';\n\nconst FRAMETIME = 0.025; // Define FRAMETIME here or import if available in constants? Using local definition for now as per previous context.\n\n/**\n * Pure version of PM_Friction from rerelease p_move.cpp.\n * Handles ground and water friction and returns a new velocity.\n */\nexport function applyPmoveFriction(params: PmoveFrictionParams): Vec3 {\n const {\n velocity,\n frametime,\n onGround,\n groundIsSlick,\n onLadder,\n waterlevel,\n pmFriction,\n pmStopSpeed,\n pmWaterFriction,\n } = params;\n\n const speed = lengthVec3(velocity);\n\n // Matches the \"if (speed < 1)\" early-out: clears X/Y but preserves Z.\n if (speed < 1) {\n return { x: 0, y: 0, z: velocity.z };\n }\n\n let drop = 0;\n\n // Ground friction (or ladder)\n if ((onGround && !groundIsSlick) || onLadder) {\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const friction = pmFriction;\n drop += control * friction * frametime;\n }\n\n // Water friction (only when not on ladder)\n if (waterlevel > 0 && !onLadder) {\n drop += speed * pmWaterFriction * waterlevel * frametime;\n }\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n const scale = newspeed / speed;\n return scaleVec3(velocity, scale);\n}\n\n/**\n * Pure version of PM_Accelerate from rerelease p_move.cpp.\n * Returns a new velocity with wishdir/wishspeed acceleration applied.\n */\nexport function applyPmoveAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspeed - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * frametime * wishspeed;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Mirrors PM_AirAccelerate in rerelease `p_move.cpp` (lines ~612-636): wishspeed is clamped\n * to 30 for the addspeed calculation but the acceleration magnitude still uses the full wishspeed.\n */\nexport function applyPmoveAirAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const wishspd = Math.min(wishspeed, 30);\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspd - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * wishspeed * frametime;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Pure mirror of PM_CmdScale from rerelease `p_move.cpp`. Computes the scalar applied to\n * the command directional inputs so that the resulting wish velocity caps at `maxSpeed`\n * regardless of the directional mix.\n */\nexport function pmoveCmdScale(cmd: PmoveCmd, maxSpeed: number): number {\n const forward = Math.abs(cmd.forwardmove);\n const side = Math.abs(cmd.sidemove);\n const up = Math.abs(cmd.upmove);\n\n const max = Math.max(forward, side, up);\n if (max === 0) {\n return 0;\n }\n\n const total = Math.sqrt(cmd.forwardmove * cmd.forwardmove + cmd.sidemove * cmd.sidemove + cmd.upmove * cmd.upmove);\n return (maxSpeed * max) / (127 * total);\n}\n\n/**\n * Computes wishdir/wishspeed for ground/air movement as done in PM_AirMove and\n * PM_GroundMove. Z is forced to zero and wishspeed is clamped to maxSpeed, matching\n * the rerelease p_move.cpp helpers before they call PM_Accelerate/PM_AirAccelerate.\n */\nexport function buildAirGroundWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n\n/**\n * Computes the wishdir/wishspeed mix for water movement, matching PM_WaterMove in\n * rerelease p_move.cpp: includes the upward bias when no strong upmove is requested,\n * clamps wishspeed to maxSpeed, and halves the returned wishspeed before acceleration.\n */\nexport function buildWaterWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n // Use full 3D components for water movement\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: forward.z * cmd.forwardmove + right.z * cmd.sidemove,\n } satisfies Vec3;\n\n if (cmd.upmove > 10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else if (cmd.upmove < -10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else if (Math.abs(cmd.forwardmove) < 10 && Math.abs(cmd.sidemove) < 10) {\n // Standard drift down when no vertical input AND no significant horizontal input\n // Matches Quake 2 rerelease behavior (sinking slowly)\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: -60 });\n } else {\n // When moving horizontally but not vertically, drift slightly up\n // This matches the \"else { wishvel[2] += 10 }\" logic in PM_WaterMove\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: 10 });\n }\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n wishspeed *= 0.5;\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n\n/**\n * Runs the full player movement simulation for a single frame.\n */\nexport function runPmove(state: PmoveState, imports: PmoveImports): PmoveState {\n if (state.pmType === PmType.Dead) {\n return state;\n }\n\n let nextState = { ...state };\n\n // Categorize Position\n const catResult = categorizePosition({\n pmType: nextState.pmType,\n pmFlags: nextState.pmFlags,\n pmTime: 0,\n n64Physics: false,\n velocity: nextState.velocity,\n startVelocity: nextState.velocity,\n origin: nextState.origin,\n mins: nextState.mins,\n maxs: nextState.maxs,\n viewheight: nextState.viewHeight,\n trace: imports.trace,\n pointContents: imports.pointcontents\n });\n\n // Merge result back to state\n nextState.pmFlags = catResult.pmFlags;\n nextState.waterlevel = catResult.waterlevel;\n nextState.watertype = catResult.watertype;\n\n // Check Ducking (Before Jump)\n const duckResult = checkDuckState({\n pmType: nextState.pmType,\n pmFlags: nextState.pmFlags,\n buttons: nextState.cmd.buttons,\n waterlevel: nextState.waterlevel,\n hasGroundEntity: (nextState.pmFlags & PmFlag.OnGround) !== 0,\n onLadder: false,\n n64Physics: false,\n origin: nextState.origin,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: (params: DuckTraceParams): PmoveTraceResult => {\n // Adapter from DuckTraceFn (obj) to PmoveTraceFn (args)\n return imports.trace(params.start, params.end, params.mins, params.maxs);\n }\n });\n\n nextState.pmFlags = duckResult.pmFlags;\n nextState.mins = duckResult.mins;\n nextState.maxs = duckResult.maxs;\n nextState.viewHeight = duckResult.viewheight;\n\n // Check Jump\n const jumpResult = checkJump({\n pmFlags: nextState.pmFlags,\n pmType: nextState.pmType,\n buttons: nextState.cmd.buttons,\n waterlevel: nextState.waterlevel,\n onGround: (nextState.pmFlags & PmFlag.OnGround) !== 0,\n velocity: nextState.velocity,\n origin: nextState.origin\n });\n\n nextState.pmFlags = jumpResult.pmFlags;\n nextState.velocity = jumpResult.velocity;\n nextState.origin = jumpResult.origin;\n\n if (jumpResult.onGround !== ((nextState.pmFlags & PmFlag.OnGround) !== 0)) {\n if (jumpResult.onGround) {\n nextState.pmFlags = addPmFlag(nextState.pmFlags, PmFlag.OnGround);\n } else {\n nextState.pmFlags = removePmFlag(nextState.pmFlags, PmFlag.OnGround);\n }\n }\n\n // Frictional movement\n const onGround = (nextState.pmFlags & PmFlag.OnGround) !== 0;\n\n // Apply friction\n const velocityBeforeFriction = nextState.velocity;\n nextState.velocity = applyPmoveFriction({\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n onGround,\n groundIsSlick: false,\n onLadder: false, // Defaulting to false for now as ladder logic is complex\n waterlevel: nextState.waterlevel,\n pmFriction: 6, // Default\n pmStopSpeed: 100, // Default\n pmWaterFriction: 1 // Default\n });\n\n // Calculate view vectors from angles\n const { forward, right } = angleVectors(nextState.viewAngles);\n\n if (nextState.pmType === PmType.NoClip) {\n // PM_NoclipMove\n // Simplified noclip\n const wishvel = {\n x: forward.x * nextState.cmd.forwardmove + right.x * nextState.cmd.sidemove,\n y: forward.y * nextState.cmd.forwardmove + right.y * nextState.cmd.sidemove,\n z: nextState.cmd.upmove\n };\n const scale = FRAMETIME; // Just move by velocity\n // Actually we need to apply velocity based on input\n // But sticking to just what's needed for jumping/movement:\n nextState.velocity = wishvel; // Simple override for noclip\n nextState.origin = {\n x: nextState.origin.x + wishvel.x * scale,\n y: nextState.origin.y + wishvel.y * scale,\n z: nextState.origin.z + wishvel.z * scale\n };\n\n } else if (nextState.waterlevel >= 2) {\n const outcome = applyPmoveWaterMove({\n origin: nextState.origin,\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: imports.trace,\n cmd: nextState.cmd,\n forward,\n right,\n pmFlags: nextState.pmFlags,\n onGround,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n pmWaterAccelerate: 4,\n pmWaterSpeed: 400,\n onLadder: false,\n watertype: nextState.watertype,\n groundContents: 0, // Should be passed in?\n waterlevel: nextState.waterlevel,\n viewPitch: nextState.viewAngles.x,\n ladderMod: 1,\n stepSize: 18 // Added stepSize for consistency, though water move might not use it heavily\n });\n nextState.origin = outcome.origin;\n nextState.velocity = outcome.velocity;\n\n } else if ((nextState.pmFlags & PmFlag.OnGround) === 0) {\n const outcome = applyPmoveAirMove({\n origin: nextState.origin,\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: imports.trace,\n cmd: nextState.cmd,\n forward,\n right,\n pmFlags: nextState.pmFlags,\n onGround,\n gravity: nextState.gravity,\n pmType: nextState.pmType,\n pmAccelerate: 10,\n pmAirAccelerate: 1,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n onLadder: false,\n waterlevel: nextState.waterlevel,\n watertype: nextState.watertype,\n groundContents: 0,\n viewPitch: nextState.viewAngles.x,\n ladderMod: 1,\n pmWaterSpeed: 400,\n stepSize: 18 // Added stepSize\n });\n nextState.origin = outcome.origin;\n nextState.velocity = outcome.velocity;\n\n } else {\n const outcome = applyPmoveWalkMove({\n origin: nextState.origin,\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: imports.trace,\n cmd: nextState.cmd,\n forward,\n right,\n pmFlags: nextState.pmFlags,\n onGround,\n gravity: nextState.gravity,\n pmType: nextState.pmType,\n pmAccelerate: 10,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n onLadder: false,\n waterlevel: nextState.waterlevel,\n watertype: nextState.watertype,\n groundContents: 0,\n viewPitch: nextState.viewAngles.x,\n ladderMod: 1,\n pmWaterSpeed: 400,\n stepSize: 18 // Added stepSize\n });\n nextState.origin = outcome.origin;\n nextState.velocity = outcome.velocity;\n }\n\n // Categorize Position again at end of frame\n const catResultEnd = categorizePosition({\n pmType: nextState.pmType,\n pmFlags: nextState.pmFlags,\n pmTime: 0,\n n64Physics: false,\n velocity: nextState.velocity,\n startVelocity: nextState.velocity,\n origin: nextState.origin,\n mins: nextState.mins,\n maxs: nextState.maxs,\n viewheight: nextState.viewHeight,\n trace: imports.trace,\n pointContents: imports.pointcontents\n });\n\n nextState.pmFlags = catResultEnd.pmFlags;\n nextState.waterlevel = catResultEnd.waterlevel;\n nextState.watertype = catResultEnd.watertype;\n\n // Update view offsets (bobbing, etc)\n // nextState = updateViewOffsets(nextState);\n\n return nextState;\n}\n","import {\n addVec3,\n lengthSquaredVec3,\n scaleVec3,\n subtractVec3,\n type Vec3,\n} from '../math/vec3.js';\nimport type { PmoveTraceResult } from './types.js';\n\nconst AXES = ['x', 'y', 'z'] as const;\ntype Axis = (typeof AXES)[number];\n\ntype AxisTuple = readonly [number, number, number];\ntype SideBoundCode = -1 | 0 | 1;\n\ninterface SideCheck {\n readonly normal: AxisTuple;\n readonly mins: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n readonly maxs: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n}\n\nconst SIDE_CHECKS: readonly SideCheck[] = [\n { normal: [0, 0, 1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [0, 0, -1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [-1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [0, 1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n { normal: [0, -1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n];\n\nexport interface FixStuckParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: FixStuckTraceFn;\n}\n\nexport type FixStuckResult = 'good-position' | 'fixed' | 'no-good-position';\n\nexport interface FixStuckOutcome {\n readonly result: FixStuckResult;\n readonly origin: Vec3;\n}\n\nexport type FixStuckTraceFn = (\n start: Vec3,\n mins: Vec3,\n maxs: Vec3,\n end: Vec3,\n) => PmoveTraceResult;\n\ninterface CandidatePosition {\n readonly distance: number;\n readonly origin: Vec3;\n}\n\nconst ZERO_VEC: Vec3 = { x: 0, y: 0, z: 0 };\n\ntype MutableVec3 = { x: number; y: number; z: number };\n\nfunction cloneMutable(vec: Vec3): MutableVec3 {\n return { x: vec.x, y: vec.y, z: vec.z };\n}\n\nfunction tupleToVec3(tuple: AxisTuple): Vec3 {\n return { x: tuple[0], y: tuple[1], z: tuple[2] };\n}\n\nfunction adjustAxis(vec: MutableVec3, axis: Axis, delta: number): void {\n if (delta === 0) return;\n switch (axis) {\n case 'x':\n vec.x += delta;\n break;\n case 'y':\n vec.y += delta;\n break;\n case 'z':\n vec.z += delta;\n break;\n }\n}\n\nfunction setAxis(vec: MutableVec3, axis: Axis, value: number): void {\n switch (axis) {\n case 'x':\n vec.x = value;\n break;\n case 'y':\n vec.y = value;\n break;\n case 'z':\n vec.z = value;\n break;\n }\n}\n\nfunction axisValue(vec: Vec3, axis: Axis): number {\n switch (axis) {\n case 'x':\n return vec.x;\n case 'y':\n return vec.y;\n case 'z':\n default:\n return vec.z;\n }\n}\n\nfunction boundValue(code: SideBoundCode, axis: Axis, mins: Vec3, maxs: Vec3): number {\n if (code === -1) {\n return axisValue(mins, axis);\n }\n if (code === 1) {\n return axisValue(maxs, axis);\n }\n return 0;\n}\n\nfunction applySideOffset(base: Vec3, side: SideCheck, mins: Vec3, maxs: Vec3): MutableVec3 {\n const result = cloneMutable(base);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n const normal = side.normal[i];\n if (normal < 0) {\n adjustAxis(result, axis, axisValue(mins, axis));\n } else if (normal > 0) {\n adjustAxis(result, axis, axisValue(maxs, axis));\n }\n }\n return result;\n}\n\nfunction buildSideBounds(side: SideCheck, mins: Vec3, maxs: Vec3): { mins: MutableVec3; maxs: MutableVec3 } {\n const localMins = cloneMutable(ZERO_VEC);\n const localMaxs = cloneMutable(ZERO_VEC);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n setAxis(localMins, axis, boundValue(side.mins[i], axis, mins, maxs));\n setAxis(localMaxs, axis, boundValue(side.maxs[i], axis, mins, maxs));\n }\n return { mins: localMins, maxs: localMaxs };\n}\n\nfunction addEpsilon(\n source: MutableVec3,\n axis: Axis | undefined,\n direction: number,\n): MutableVec3 {\n if (!axis || direction === 0) {\n return source;\n }\n const clone = cloneMutable(source);\n adjustAxis(clone, axis, direction);\n return clone;\n}\n\nfunction addEpsilonImmutable(vec: Vec3, axis: Axis | undefined, direction: number): Vec3 {\n if (!axis || direction === 0) {\n return vec;\n }\n switch (axis) {\n case 'x':\n return { ...vec, x: vec.x + direction };\n case 'y':\n return { ...vec, y: vec.y + direction };\n case 'z':\n default:\n return { ...vec, z: vec.z + direction };\n }\n}\n\n/**\n * TypeScript port of G_FixStuckObject_Generic from rerelease p_move.cpp. Attempts to\n * nudge a stuck bounding box out of solid space by probing the faces of the box and\n * moving towards the opposite side, keeping the smallest successful displacement.\n */\nexport function fixStuckObjectGeneric(params: FixStuckParams): FixStuckOutcome {\n const { origin, mins, maxs, trace } = params;\n\n const initial = trace(origin, mins, maxs, origin);\n if (!initial.startsolid) {\n return { result: 'good-position', origin: { ...origin } };\n }\n\n const candidates: CandidatePosition[] = [];\n\n for (let i = 0; i < SIDE_CHECKS.length; i++) {\n const side = SIDE_CHECKS[i];\n const { mins: localMins, maxs: localMaxs } = buildSideBounds(side, mins, maxs);\n\n let start = applySideOffset(origin, side, mins, maxs);\n let tr = trace(start, localMins, localMaxs, start);\n\n let epsilonAxis: Axis | undefined;\n let epsilonDir = 0;\n\n if (tr.startsolid) {\n for (let axisIndex = 0; axisIndex < AXES.length; axisIndex++) {\n if (side.normal[axisIndex] !== 0) {\n continue;\n }\n const axis = AXES[axisIndex];\n let epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, 1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = 1;\n break;\n }\n epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, -1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = -1;\n break;\n }\n }\n }\n\n if (tr.startsolid) {\n continue;\n }\n\n const otherSide = SIDE_CHECKS[i ^ 1];\n let oppositeStart = applySideOffset(origin, otherSide, mins, maxs);\n oppositeStart = addEpsilon(oppositeStart, epsilonAxis, epsilonDir);\n\n tr = trace(start, localMins, localMaxs, oppositeStart);\n if (tr.startsolid) {\n continue;\n }\n\n const normal = tupleToVec3(side.normal);\n const end = addVec3(tr.endpos ?? oppositeStart, scaleVec3(normal, 0.125));\n const delta = subtractVec3(end, oppositeStart);\n let newOrigin = addVec3(origin, delta);\n newOrigin = addEpsilonImmutable(newOrigin, epsilonAxis, epsilonDir);\n\n const validation = trace(newOrigin, mins, maxs, newOrigin);\n if (validation.startsolid) {\n continue;\n }\n\n candidates.push({ origin: newOrigin, distance: lengthSquaredVec3(delta) });\n }\n\n if (candidates.length === 0) {\n return { result: 'no-good-position', origin: { ...origin } };\n }\n\n candidates.sort((a, b) => a.distance - b.distance);\n return { result: 'fixed', origin: { ...candidates[0].origin } };\n}\n","import { addVec3, lengthVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from './constants.js';\nimport { applyPmoveAccelerate } from './pmove.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nconst FLY_FRICTION_MULTIPLIER = 1.5;\nconst BUTTON_VERTICAL_SCALE = 0.5;\nconst DEFAULT_OVERBOUNCE = 1.01;\n\nexport interface FlyMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly frametime: number;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly pmMaxSpeed: number;\n readonly pmAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly doclip: boolean;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly trace?: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport type FlyMoveResult = StepSlideMoveOutcome;\n\n/**\n * Pure translation of PM_FlyMove from rerelease `p_move.cpp`: applies the\n * spectator/noclip friction and acceleration rules, then either advances the\n * origin freely or resolves movement through `stepSlideMove` when clipping is\n * requested. This keeps the spectator and noclip physics deterministic between\n * the client and server.\n */\nexport function applyPmoveFlyMove(params: FlyMoveParams): FlyMoveResult {\n const {\n origin,\n cmd,\n frametime,\n pmFriction,\n pmStopSpeed,\n pmMaxSpeed,\n pmAccelerate,\n pmWaterSpeed,\n doclip,\n forward,\n right,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n let velocity = applyFlyFriction({ velocity: params.velocity, pmFriction, pmStopSpeed, frametime });\n\n const wishdirVelocity = buildFlyWishVelocity({\n cmd,\n forward,\n right,\n pmMaxSpeed,\n pmWaterSpeed,\n });\n\n if (wishdirVelocity.wishspeed > 0) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wishdirVelocity.wishdir,\n wishspeed: wishdirVelocity.accelSpeed,\n accel: pmAccelerate,\n frametime,\n });\n }\n\n if (!doclip) {\n const originDelta = scaleVec3(velocity, frametime);\n const nextOrigin = addVec3(origin, originDelta);\n return {\n origin: nextOrigin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: velocity.x === 0 && velocity.y === 0 && velocity.z === 0,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n if (!trace || !mins || !maxs) {\n throw new Error('applyPmoveFlyMove: doclip=true requires trace/mins/maxs');\n }\n\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n overbounce,\n trace,\n mins,\n maxs,\n stepSize,\n maxBumps,\n maxClipPlanes,\n });\n}\n\ninterface FlyFrictionParams {\n readonly velocity: Vec3;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly frametime: number;\n}\n\nfunction applyFlyFriction(params: FlyFrictionParams): Vec3 {\n const { velocity, pmFriction, pmStopSpeed, frametime } = params;\n const speed = lengthVec3(velocity);\n\n if (speed < 1) {\n return { x: 0, y: 0, z: 0 };\n }\n\n const friction = pmFriction * FLY_FRICTION_MULTIPLIER;\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const drop = control * friction * frametime;\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n return scaleVec3(velocity, newspeed / speed);\n}\n\ninterface FlyWishVelocityParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmMaxSpeed: number;\n readonly pmWaterSpeed: number;\n}\n\ninterface FlyWishVelocityResult {\n readonly wishdir: Vec3;\n readonly wishspeed: number;\n readonly accelSpeed: number;\n}\n\nfunction buildFlyWishVelocity(params: FlyWishVelocityParams): FlyWishVelocityResult {\n const { cmd, forward, right, pmMaxSpeed, pmWaterSpeed } = params;\n\n const forwardNorm = normalizeVec3(forward);\n const rightNorm = normalizeVec3(right);\n\n const wishvel = {\n x: forwardNorm.x * cmd.forwardmove + rightNorm.x * cmd.sidemove,\n y: forwardNorm.y * cmd.forwardmove + rightNorm.y * cmd.sidemove,\n z: forwardNorm.z * cmd.forwardmove + rightNorm.z * cmd.sidemove,\n } satisfies Vec3;\n\n let adjusted = wishvel;\n const buttons = cmd.buttons ?? 0;\n\n if (buttons & PlayerButton.Jump) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n if (buttons & PlayerButton.Crouch) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: -pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n let wishspeed = lengthVec3(adjusted);\n let wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n adjusted = scaleVec3(adjusted, scale);\n wishspeed = pmMaxSpeed;\n wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n }\n\n const accelSpeed = wishspeed * 2;\n\n return { wishdir, wishspeed, accelSpeed };\n}\n","import { CONTENTS_LADDER, CONTENTS_NONE, CONTENTS_NO_WATERJUMP } from '../bsp/contents.js';\nimport { addVec3, lengthSquaredVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, PmFlag, type PmFlags, addPmFlag, removePmFlag, WaterLevel } from './constants.js';\nimport { stepSlideMove } from './slide.js';\nimport type { PmoveCmd, PmovePointContentsFn, PmoveTraceFn } from './types.js';\nimport { getWaterLevel } from './water.js';\n\nconst LADDER_TRACE_DISTANCE = 1;\nconst WATERJUMP_FORWARD_CHECK = 40;\nconst WATERJUMP_FORWARD_SPEED = 50;\nconst WATERJUMP_UPWARD_SPEED = 350;\nconst WATERJUMP_PM_TIME = 2048;\nconst WATERJUMP_SIM_STEP = 0.1;\nconst WATERJUMP_BASE_GRAVITY = 800;\nconst WATERJUMP_MAX_STEPS = 50;\nconst GROUND_NORMAL_THRESHOLD = 0.7;\nconst WATERJUMP_STEP_TOLERANCE = 18;\nconst DEFAULT_OVERBOUNCE = 1.01;\nconst WATERJUMP_DOWN_PROBE = 2;\n\nexport interface SpecialMovementParams {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly gravity: number;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n readonly onGround: boolean;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport interface SpecialMovementResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly velocity: Vec3;\n readonly performedWaterJump: boolean;\n}\n\n/**\n * Mirrors the ladder detection and water-jump probing logic from\n * `PM_CheckSpecialMovement` in `rerelease/p_move.cpp`. The helper clears and\n * re-adds the ladder flag based on nearby CONTENTS_LADDER brushes, then\n * simulates a potential water jump by firing the same 40-unit probe and\n * step-slide loop the C++ uses before committing to the upward velocity.\n */\nexport function checkSpecialMovement(params: SpecialMovementParams): SpecialMovementResult {\n const {\n pmFlags: initialFlags,\n pmTime: initialPmTime,\n waterlevel,\n watertype,\n gravity,\n cmd,\n forward,\n origin,\n velocity: initialVelocity,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n onGround,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize = WATERJUMP_STEP_TOLERANCE,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n if (initialPmTime > 0) {\n return { pmFlags: initialFlags, pmTime: initialPmTime, velocity: initialVelocity, performedWaterJump: false };\n }\n\n let pmFlags = removePmFlag(initialFlags, PmFlag.OnLadder);\n let pmTime = initialPmTime;\n let velocity = initialVelocity;\n\n const flatforward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n const hasForward = lengthSquaredVec3(flatforward) > 0;\n\n if (waterlevel < WaterLevel.Waist && hasForward) {\n const ladderEnd = addVec3(origin, scaleVec3(flatforward, LADDER_TRACE_DISTANCE));\n const ladderTrace = trace(origin, ladderEnd, mins, maxs);\n const contents = ladderTrace.contents ?? CONTENTS_NONE;\n\n if (ladderTrace.fraction < 1 && (contents & CONTENTS_LADDER) !== 0) {\n pmFlags = addPmFlag(pmFlags, PmFlag.OnLadder);\n }\n }\n\n if (gravity === 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (((cmd.buttons ?? 0) & PlayerButton.Jump) === 0 && cmd.forwardmove <= 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (waterlevel !== WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if ((watertype & CONTENTS_NO_WATERJUMP) !== 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (!hasForward) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const forwardCheckEnd = addVec3(origin, scaleVec3(flatforward, WATERJUMP_FORWARD_CHECK));\n const forwardTrace = trace(origin, forwardCheckEnd, mins, maxs);\n\n if (\n forwardTrace.fraction === 1 ||\n !forwardTrace.planeNormal ||\n forwardTrace.planeNormal.z >= GROUND_NORMAL_THRESHOLD\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n let simVelocity: Vec3 = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n };\n\n let simOrigin = origin;\n let hasTime = true;\n const stepCount = computeWaterJumpSteps(gravity);\n\n for (let i = 0; i < stepCount; i++) {\n simVelocity = { x: simVelocity.x, y: simVelocity.y, z: simVelocity.z - gravity * WATERJUMP_SIM_STEP };\n if (simVelocity.z < 0) {\n hasTime = false;\n }\n\n const move = stepSlideMove({\n origin: simOrigin,\n velocity: simVelocity,\n frametime: WATERJUMP_SIM_STEP,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n simOrigin = move.origin;\n simVelocity = move.velocity;\n }\n\n const downEnd = addVec3(simOrigin, { x: 0, y: 0, z: -WATERJUMP_DOWN_PROBE });\n const downTrace = trace(simOrigin, downEnd, mins, maxs);\n\n if (\n downTrace.fraction === 1 ||\n !downTrace.planeNormal ||\n downTrace.planeNormal.z < GROUND_NORMAL_THRESHOLD ||\n downTrace.endpos.z < origin.z\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (onGround && Math.abs(origin.z - downTrace.endpos.z) <= stepSize) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const landingWater = getWaterLevel({ origin: downTrace.endpos, mins, viewheight, pointContents });\n if (landingWater.waterlevel >= WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeWaterJump);\n pmTime = WATERJUMP_PM_TIME;\n velocity = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n } satisfies Vec3;\n\n return { pmFlags, pmTime, velocity, performedWaterJump: true };\n}\n\nfunction computeWaterJumpSteps(gravity: number): number {\n if (gravity === 0) {\n return 0;\n }\n\n const scaled = Math.floor(10 * (WATERJUMP_BASE_GRAVITY / gravity));\n if (scaled <= 0) {\n return 0;\n }\n return Math.min(WATERJUMP_MAX_STEPS, scaled);\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { fixStuckObjectGeneric } from './stuck.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst SNAP_OFFSETS = [0, -1, 1] as const;\n\nexport interface GoodPositionParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nexport function goodPosition(params: GoodPositionParams): boolean {\n const { origin, mins, maxs, trace } = params;\n const result = trace(origin, origin, mins, maxs);\n return result.allsolid ? false : true;\n}\n\nexport type SnapResolution = 'unchanged' | 'fixed' | 'reverted';\n\nexport interface SnapPositionParams extends GoodPositionParams {\n readonly velocity: Vec3;\n readonly previousOrigin: Vec3;\n}\n\nexport interface SnapPositionResult {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly resolution: SnapResolution;\n}\n\n/**\n * Pure translation of PM_SnapPosition from rerelease `p_move.cpp`.\n * Attempts to keep the caller's origin in a valid location by first\n * checking the current origin against collision traces, then falling\n * back to the shared `fixStuckObjectGeneric` helper before finally\n * reverting to the provided previous origin when no fix is possible.\n */\nexport function snapPosition(params: SnapPositionParams): SnapPositionResult {\n const { origin, velocity, mins, maxs, previousOrigin, trace } = params;\n\n if (goodPosition({ origin, mins, maxs, trace })) {\n return { origin: { ...origin }, velocity: { ...velocity }, resolution: 'unchanged' };\n }\n\n const fix = fixStuckObjectGeneric({\n origin,\n mins,\n maxs,\n trace: (start, localMins, localMaxs, end) => trace(start, end, localMins, localMaxs),\n });\n\n if (fix.result === 'fixed' || fix.result === 'good-position') {\n return { origin: fix.origin, velocity: { ...velocity }, resolution: 'fixed' };\n }\n\n return { origin: { ...previousOrigin }, velocity: { ...velocity }, resolution: 'reverted' };\n}\n\nexport interface InitialSnapPositionParams extends GoodPositionParams {}\n\nexport interface InitialSnapPositionResult {\n readonly origin: Vec3;\n readonly snapped: boolean;\n}\n\n/**\n * Pure translation of PM_InitialSnapPosition from rerelease `p_move.cpp`.\n * Tries a 3x3x3 grid of +/-1 unit offsets around the base origin to find\n * a valid collision-free spot, mirroring the search order of the C++ code.\n */\nexport function initialSnapPosition(params: InitialSnapPositionParams): InitialSnapPositionResult {\n const { origin, mins, maxs, trace } = params;\n\n for (const oz of SNAP_OFFSETS) {\n for (const oy of SNAP_OFFSETS) {\n for (const ox of SNAP_OFFSETS) {\n const candidate = { x: origin.x + ox, y: origin.y + oy, z: origin.z + oz } satisfies Vec3;\n if (goodPosition({ origin: candidate, mins, maxs, trace })) {\n const snapped = ox !== 0 || oy !== 0 || oz !== 0;\n return { origin: candidate, snapped };\n }\n }\n }\n }\n\n return { origin: { ...origin }, snapped: false };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { angleVectors, type AngleVectorsResult } from '../math/angles.js';\nimport { PmFlag, type PmFlags } from './constants.js';\n\nexport interface ClampViewAnglesParams {\n readonly pmFlags: PmFlags;\n readonly cmdAngles: Vec3;\n readonly deltaAngles: Vec3;\n}\n\nexport interface ClampViewAnglesResult extends AngleVectorsResult {\n readonly viewangles: Vec3;\n}\n\nfunction addAngles(cmdAngles: Vec3, deltaAngles: Vec3): Vec3 {\n return {\n x: cmdAngles.x + deltaAngles.x,\n y: cmdAngles.y + deltaAngles.y,\n z: cmdAngles.z + deltaAngles.z,\n } satisfies Vec3;\n}\n\nfunction clampPitch(pitch: number): number {\n if (pitch > 89 && pitch < 180) {\n return 89;\n }\n if (pitch < 271 && pitch >= 180) {\n return 271;\n }\n return pitch;\n}\n\n/**\n * Pure translation of `PM_ClampAngles` from `rerelease/p_move.cpp`. The helper\n * fuses the latest command angles with the stored delta, applies the teleport\n * pitch/roll reset, enforces the ±90° pitch window, and returns the resulting\n * axis vectors that the C version stored in `pml.forward/right/up`.\n */\nexport function clampViewAngles(params: ClampViewAnglesParams): ClampViewAnglesResult {\n const { pmFlags, cmdAngles, deltaAngles } = params;\n\n let viewangles: Vec3;\n\n if ((pmFlags & PmFlag.TimeTeleport) !== 0) {\n viewangles = {\n x: 0,\n y: cmdAngles.y + deltaAngles.y,\n z: 0,\n } satisfies Vec3;\n } else {\n viewangles = addAngles(cmdAngles, deltaAngles);\n viewangles = { ...viewangles, x: clampPitch(viewangles.x) };\n }\n\n const vectors = angleVectors(viewangles);\n return { viewangles, ...vectors };\n}\n","import { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n readonly sequence: number;\n readonly lightlevel: number;\n readonly impulse: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\n}\n","\nexport enum ServerCommand {\n bad = 0,\n\n // these ops are known to the game dll\n muzzleflash = 1,\n muzzleflash2 = 2,\n temp_entity = 3,\n layout = 4,\n inventory = 5,\n\n // the rest are private to the client and server\n nop = 6,\n disconnect = 7,\n reconnect = 8,\n sound = 9, // <see code>\n print = 10, // [byte] id [string] null terminated string\n stufftext = 11, // [string] stuffed into client's console buffer, should be \\n terminated\n serverdata = 12, // [long] protocol ...\n configstring = 13, // [short] [string]\n spawnbaseline = 14,\n centerprint = 15, // [string] to put in center of the screen\n download = 16, // [short] size [size bytes]\n playerinfo = 17, // variable\n packetentities = 18, // [...]\n deltapacketentities = 19, // [...]\n frame = 20,\n splitclient = 21,\n configblast = 22,\n spawnbaselineblast = 23,\n level_restart = 24,\n damage = 25,\n locprint = 26,\n fog = 27,\n waitingforplayers = 28,\n bot_chat = 29,\n poi = 30,\n help_path = 31,\n muzzleflash3 = 32,\n achievement = 33\n}\n\nexport enum ClientCommand {\n bad = 0,\n nop = 1,\n move = 2, // [[usercmd_t]\n userinfo = 3, // [[userinfo string]\n stringcmd = 4 // [string] message\n}\n","\n// Temp entity constants from Quake 2\nexport enum TempEntity {\n GUNSHOT = 0,\n BLOOD = 1,\n BLASTER = 2,\n RAILTRAIL = 3,\n SHOTGUN = 4,\n EXPLOSION1 = 5,\n EXPLOSION2 = 6,\n ROCKET_EXPLOSION = 7,\n GRENADE_EXPLOSION = 8,\n SPARKS = 9,\n SPLASH = 10,\n BUBBLETRAIL = 11,\n SCREEN_SPARKS = 12,\n SHIELD_SPARKS = 13,\n BULLET_SPARKS = 14,\n LASER_SPARKS = 15,\n PARASITE_ATTACK = 16,\n ROCKET_EXPLOSION_WATER = 17,\n GRENADE_EXPLOSION_WATER = 18,\n MEDIC_CABLE_ATTACK = 19,\n BFG_EXPLOSION = 20,\n BFG_BIGEXPLOSION = 21,\n BOSSTPORT = 22,\n BFG_LASER = 23,\n GRAPPLE_CABLE = 24,\n WELDING_SPARKS = 25,\n GREENBLOOD = 26,\n BLUEHYPERBLASTER = 27,\n PLASMA_EXPLOSION = 28,\n TUNNEL_SPARKS = 29,\n // ROGUE\n BLASTER2 = 30,\n RAILTRAIL2 = 31,\n FLAME = 32,\n LIGHTNING = 33,\n DEBUGTRAIL = 34,\n PLAIN_EXPLOSION = 35,\n FLASHLIGHT = 36,\n FORCEWALL = 37,\n HEATBEAM = 38,\n MONSTER_HEATBEAM = 39,\n STEAM = 40,\n BUBBLETRAIL2 = 41,\n MOREBLOOD = 42,\n HEATBEAM_SPARKS = 43,\n HEATBEAM_STEAM = 44,\n CHAINFIST_SMOKE = 45,\n ELECTRIC_SPARKS = 46,\n TRACKER_EXPLOSION = 47,\n TELEPORT_EFFECT = 48,\n DBALL_GOAL = 49,\n WIDOWBEAMOUT = 50,\n NUKEBLAST = 51,\n WIDOWSPLASH = 52,\n EXPLOSION1_BIG = 53,\n EXPLOSION1_NP = 54,\n FLECHETTE = 55,\n BLUEHYPERBLASTER_KEX = 56,\n BFG_ZAP = 57,\n BERSERK_SLAM = 58,\n GRAPPLE_CABLE_2 = 59,\n POWER_SPLASH = 60,\n LIGHTNING_BEAM = 61,\n EXPLOSION1_NL = 62,\n EXPLOSION2_NL = 63\n}\n","\nexport const MAX_CHALLENGES = 1024;\nexport const MAX_PACKET_ENTITIES = 256; // Standard Q2 value\nexport const UPDATE_BACKUP = 16;\nexport const CMD_BACKUP = 64;\nexport const MAX_INFO_STRING = 512;\nexport const MAX_MSGLEN = 1400; // MTU safe limit\n\n// Muzzle Flash Constants\nexport const MZ_BLASTER = 0;\nexport const MZ_MACHINEGUN = 1;\nexport const MZ_SHOTGUN = 2;\nexport const MZ_CHAINGUN1 = 3;\nexport const MZ_CHAINGUN2 = 4;\nexport const MZ_CHAINGUN3 = 5;\nexport const MZ_RAILGUN = 6;\nexport const MZ_ROCKET = 7;\nexport const MZ_GRENADE = 8;\nexport const MZ_LOGIN = 9;\nexport const MZ_LOGOUT = 10;\nexport const MZ_SSHOTGUN = 11;\nexport const MZ_BFG = 12;\nexport const MZ_HYPERBLASTER = 13;\n\n// Xatrix / Rogue Extensions\nexport const MZ_IONRIPPER = 16;\nexport const MZ_BLUEHYPERBLASTER = 17;\nexport const MZ_PHALANX = 18;\nexport const MZ_BFG2 = 19;\nexport const MZ_PHALANX2 = 20;\nexport const MZ_ETF_RIFLE = 30;\nexport const MZ_PROX = 31;\nexport const MZ_ETF_RIFLE_2 = 32;\nexport const MZ_HEATBEAM = 33;\nexport const MZ_BLASTER2 = 34;\nexport const MZ_TRACKER = 35;\nexport const MZ_NUKE1 = 36;\nexport const MZ_NUKE2 = 37;\nexport const MZ_NUKE4 = 38;\nexport const MZ_NUKE8 = 39;\n","// Matching rerelease/game.h:1584-1593\nexport enum LayoutFlags {\n LAYOUTS_LAYOUT = 1,\n LAYOUTS_INVENTORY = 2,\n LAYOUTS_HIDE_HUD = 4,\n LAYOUTS_INTERMISSION = 8,\n LAYOUTS_HELP = 16,\n LAYOUTS_HIDE_CROSSHAIR = 32\n}\n","\n/**\n * Helper to force a number into a signed 16-bit integer range (-32768 to 32767).\n * This mimics the behavior of casting to `short` in C++.\n */\nfunction toSigned16(val: number): number {\n return (val << 16) >> 16;\n}\n\n/**\n * Reads a 16-bit integer (unsigned) from the stats array at the given byte offset.\n * Mimics reading `*(uint16_t*)((uint8_t*)stats + byteOffset)` in Little Endian.\n */\nfunction readUint16LE(stats: number[], startIndex: number, byteOffset: number): number {\n // Determine which element(s) of the array we are accessing\n // stats is int16[], so each element is 2 bytes.\n // absolute byte offset from stats[startIndex]\n const elementIndex = Math.floor(byteOffset / 2);\n const isOdd = (byteOffset % 2) !== 0;\n\n // Access the array at the calculated index relative to startIndex\n const index = startIndex + elementIndex;\n\n // Read the primary element\n const val0 = stats[index] || 0; // Handle potentially undefined/uninitialized slots as 0\n\n if (!isOdd) {\n // Aligned access: just return the element as uint16\n return val0 & 0xFFFF;\n } else {\n // Unaligned access: High byte of val0 + Low byte of val1\n const val1 = stats[index + 1] || 0;\n\n // Low byte of result comes from High byte of val0\n const low = (val0 >>> 8) & 0xFF;\n // High byte of result comes from Low byte of val1\n const high = val1 & 0xFF;\n\n return (high << 8) | low;\n }\n}\n\n/**\n * Writes a 16-bit integer to the stats array at the given byte offset.\n * Mimics writing `*(uint16_t*)((uint8_t*)stats + byteOffset) = value` in Little Endian.\n */\nfunction writeUint16LE(stats: number[], startIndex: number, byteOffset: number, value: number): void {\n const elementIndex = Math.floor(byteOffset / 2);\n const isOdd = (byteOffset % 2) !== 0;\n const index = startIndex + elementIndex;\n\n // Ensure array has values at these indices to avoid NaN math\n if (stats[index] === undefined) stats[index] = 0;\n\n if (!isOdd) {\n // Aligned access: overwrite the element\n stats[index] = toSigned16(value);\n } else {\n // Unaligned access\n if (stats[index + 1] === undefined) stats[index + 1] = 0;\n\n const val0 = stats[index];\n const val1 = stats[index + 1];\n\n // We want to write `value` (which is Low byte `L_v` and High byte `H_v`)\n // into the bytes at `byteOffset` and `byteOffset + 1`.\n\n // Byte at `byteOffset` corresponds to High byte of `stats[index]`.\n // It should become `value & 0xFF` (L_v).\n // So `stats[index]` becomes `(Old_Low) | (L_v << 8)`.\n const newHigh0 = value & 0xFF;\n const newVal0 = (val0 & 0xFF) | (newHigh0 << 8);\n stats[index] = toSigned16(newVal0);\n\n // Byte at `byteOffset + 1` corresponds to Low byte of `stats[index+1]`.\n // It should become `(value >> 8) & 0xFF` (H_v).\n // So `stats[index+1]` becomes `(H_v) | (Old_High << 8)`.\n const newLow1 = (value >>> 8) & 0xFF;\n const newVal1 = newLow1 | (val1 & 0xFF00);\n stats[index + 1] = toSigned16(newVal1);\n }\n}\n\n/**\n * Packs a value into the stats array using a specific bit width.\n * Equivalent to C++ `set_compressed_integer`.\n *\n * @param stats The stats array (number[] representing int16s)\n * @param startIndex The index in the stats array where the packed region begins (e.g. STAT_AMMO_INFO_START)\n * @param id The ID of the item to set (0-based index within the packed region)\n * @param count The value to set\n * @param bitsPerValue Number of bits per item (e.g. 9 for ammo, 2 for powerups)\n */\nexport function setCompressedInteger(\n stats: number[],\n startIndex: number,\n id: number,\n count: number,\n bitsPerValue: number\n): void {\n const bitOffset = bitsPerValue * id;\n const byteOffset = Math.floor(bitOffset / 8);\n const bitShift = bitOffset % 8;\n const mask = ((1 << bitsPerValue) - 1) << bitShift;\n\n // Read the 16-bit word at the target byte address\n let base = readUint16LE(stats, startIndex, byteOffset);\n\n // Apply the mask and value\n // Note: (count << bitShift) might overflow 16 bits if we aren't careful,\n // but the mask will handle the high bits.\n // However, in JS, bitwise ops are 32-bit.\n // We need to ensure we only write back 16 bits.\n\n const valueToWrite = (base & ~mask) | ((count << bitShift) & mask);\n\n // Write the modified 16-bit word back\n writeUint16LE(stats, startIndex, byteOffset, valueToWrite & 0xFFFF);\n}\n\n/**\n * Unpacks a value from the stats array.\n * Equivalent to C++ `get_compressed_integer`.\n */\nexport function getCompressedInteger(\n stats: number[],\n startIndex: number,\n id: number,\n bitsPerValue: number\n): number {\n const bitOffset = bitsPerValue * id;\n const byteOffset = Math.floor(bitOffset / 8);\n const bitShift = bitOffset % 8;\n const mask = ((1 << bitsPerValue) - 1) << bitShift;\n\n const base = readUint16LE(stats, startIndex, byteOffset);\n\n return (base & mask) >>> bitShift;\n}\n","/**\n * Powerup identifiers shared across game and cgame.\n * Reference: rerelease/g_items.cpp, game/src/inventory/playerInventory.ts\n */\n\nexport enum PowerupId {\n QuadDamage = 'quad',\n Invulnerability = 'invulnerability',\n EnviroSuit = 'enviro_suit',\n Rebreather = 'rebreather',\n Silencer = 'silencer',\n // New additions for demo playback and extended support\n PowerScreen = 'power_screen',\n PowerShield = 'power_shield',\n QuadFire = 'quad_fire',\n Invisibility = 'invisibility',\n Bandolier = 'bandolier',\n AmmoPack = 'ammo_pack',\n IRGoggles = 'ir_goggles',\n DoubleDamage = 'double_damage',\n SphereVengeance = 'sphere_vengeance',\n SphereHunter = 'sphere_hunter',\n SphereDefender = 'sphere_defender',\n Doppelganger = 'doppelganger',\n TagToken = 'tag_token',\n TechResistance = 'tech_resistance',\n TechStrength = 'tech_strength',\n TechHaste = 'tech_haste',\n TechRegeneration = 'tech_regeneration',\n Flashlight = 'flashlight',\n Compass = 'compass',\n}\n","import { setCompressedInteger, getCompressedInteger } from './bitpack.js';\nimport { PowerupId } from '../items/powerups.js';\n\n// Matching rerelease/bg_local.h:196-262\nexport enum PlayerStat {\n STAT_HEALTH_ICON = 0,\n STAT_HEALTH,\n STAT_AMMO_ICON,\n STAT_AMMO,\n STAT_ARMOR_ICON,\n STAT_ARMOR,\n STAT_SELECTED_ICON,\n STAT_PICKUP_ICON,\n STAT_PICKUP_STRING,\n STAT_TIMER_ICON,\n STAT_TIMER,\n STAT_HELPICON,\n STAT_SELECTED_ITEM,\n STAT_LAYOUTS,\n STAT_FRAGS,\n STAT_FLASHES,\n STAT_CHASE,\n STAT_SPECTATOR,\n\n // CTF Stats (Rerelease/KEX)\n STAT_CTF_TEAM1_PIC = 18,\n STAT_CTF_TEAM1_CAPS = 19,\n STAT_CTF_TEAM2_PIC = 20,\n STAT_CTF_TEAM2_CAPS = 21,\n STAT_CTF_FLAG_PIC = 22,\n STAT_CTF_JOINED_TEAM1_PIC = 23,\n STAT_CTF_JOINED_TEAM2_PIC = 24,\n STAT_CTF_TEAM1_HEADER = 25,\n STAT_CTF_TEAM2_HEADER = 26,\n STAT_CTF_TECH = 27,\n STAT_CTF_ID_VIEW = 28,\n STAT_CTF_MATCH = 29,\n STAT_CTF_ID_VIEW_COLOR = 30,\n STAT_CTF_TEAMINFO = 31,\n\n // Rerelease additions\n STAT_WEAPONS_OWNED_1 = 32,\n STAT_WEAPONS_OWNED_2 = 33,\n\n // Ammo counts (start index)\n STAT_AMMO_INFO_START = 34,\n // Calculated below, but enum needs literal or constant if we want to use it as type.\n // However, for TS Enum, we can just define start.\n\n // Powerups start after Ammo.\n // AMMO_MAX=12, 9 bits each -> 108 bits -> 7 int16s.\n // 34 + 7 = 41.\n STAT_POWERUP_INFO_START = 41,\n\n // Keys and other KEX stats (Start after Powerups)\n // POWERUP_MAX=23, 2 bits each -> 46 bits -> 3 int16s.\n // 41 + 3 = 44.\n STAT_KEY_A = 44,\n STAT_KEY_B = 45,\n STAT_KEY_C = 46,\n\n STAT_ACTIVE_WHEEL_WEAPON = 47,\n STAT_COOP_RESPAWN = 48,\n STAT_LIVES = 49,\n STAT_HIT_MARKER = 50,\n STAT_SELECTED_ITEM_NAME = 51,\n STAT_HEALTH_BARS = 52,\n STAT_ACTIVE_WEAPON = 53,\n\n STAT_LAST\n}\n\n// Constants for bit packing logic\nexport const AMMO_MAX = 12;\nexport const NUM_BITS_FOR_AMMO = 9;\nexport const NUM_AMMO_STATS = Math.ceil((AMMO_MAX * NUM_BITS_FOR_AMMO) / 16); // 7\n\nexport const POWERUP_MAX = 23; // Adjusted to include TechRegeneration (index 22)\nexport const NUM_BITS_FOR_POWERUP = 2;\nexport const NUM_POWERUP_STATS = Math.ceil((POWERUP_MAX * NUM_BITS_FOR_POWERUP) / 16); // 3\n\n// Powerup ID mapping from string to C++ integer index (powerup_t in bg_local.h)\nconst POWERUP_STAT_MAP: Partial<Record<PowerupId, number>> = {\n [PowerupId.PowerScreen]: 0,\n [PowerupId.PowerShield]: 1,\n // 2 is POWERUP_AM_BOMB (not in PowerupId?)\n [PowerupId.QuadDamage]: 3,\n [PowerupId.QuadFire]: 4,\n [PowerupId.Invulnerability]: 5,\n [PowerupId.Invisibility]: 6,\n [PowerupId.Silencer]: 7,\n [PowerupId.Rebreather]: 8,\n [PowerupId.EnviroSuit]: 9,\n [PowerupId.Bandolier]: 10, // Placeholder/Map mismatch handling?\n [PowerupId.AmmoPack]: 10, // Original reused indices or had gaps?\n [PowerupId.IRGoggles]: 11,\n [PowerupId.DoubleDamage]: 12,\n [PowerupId.SphereVengeance]: 13,\n [PowerupId.SphereHunter]: 14,\n [PowerupId.SphereDefender]: 15,\n [PowerupId.Doppelganger]: 16,\n [PowerupId.Flashlight]: 17,\n [PowerupId.Compass]: 18,\n [PowerupId.TechResistance]: 19,\n [PowerupId.TechStrength]: 20,\n [PowerupId.TechHaste]: 21,\n [PowerupId.TechRegeneration]: 22,\n // Add missing mappings to avoid runtime lookups failing for new types\n [PowerupId.TagToken]: -1,\n};\n\n// 9 bits for ammo count\nexport function G_SetAmmoStat(stats: number[], ammoId: number, count: number): void {\n if (ammoId < 0 || ammoId >= AMMO_MAX) return;\n\n // Clamp count to 9 bits (0-511)\n let val = count;\n if (val > 511) val = 511;\n if (val < 0) val = 0;\n\n setCompressedInteger(stats, PlayerStat.STAT_AMMO_INFO_START, ammoId, val, NUM_BITS_FOR_AMMO);\n}\n\nexport function G_GetAmmoStat(stats: number[], ammoId: number): number {\n if (ammoId < 0 || ammoId >= AMMO_MAX) return 0;\n return getCompressedInteger(stats, PlayerStat.STAT_AMMO_INFO_START, ammoId, NUM_BITS_FOR_AMMO);\n}\n\n// 2 bits for powerup active/inactive state\nexport function G_SetPowerupStat(stats: number[], powerupId: PowerupId | number, val: number): void {\n let index: number | undefined;\n\n if (typeof powerupId === 'number') {\n index = powerupId;\n } else {\n index = POWERUP_STAT_MAP[powerupId];\n }\n\n if (index === undefined || index < 0 || index >= POWERUP_MAX) return;\n\n // Clamp value to 2 bits (0-3)\n let safeVal = val;\n if (safeVal > 3) safeVal = 3;\n if (safeVal < 0) safeVal = 0;\n\n setCompressedInteger(stats, PlayerStat.STAT_POWERUP_INFO_START, index, safeVal, NUM_BITS_FOR_POWERUP);\n}\n\nexport function G_GetPowerupStat(stats: number[], powerupId: PowerupId | number): number {\n let index: number | undefined;\n\n if (typeof powerupId === 'number') {\n index = powerupId;\n } else {\n index = POWERUP_STAT_MAP[powerupId];\n }\n\n if (index === undefined || index < 0 || index >= POWERUP_MAX) return 0;\n\n return getCompressedInteger(stats, PlayerStat.STAT_POWERUP_INFO_START, index, NUM_BITS_FOR_POWERUP);\n}\n","import { BinaryWriter } from '../io/binaryWriter.js';\nimport { UserCommand } from './usercmd.js';\n\nexport function writeUserCommand(writer: BinaryWriter, cmd: UserCommand): void {\n // msec (byte)\n writer.writeByte(cmd.msec);\n\n // buttons (byte)\n writer.writeByte(cmd.buttons);\n\n // angles (short * 3) - Scaled 360 -> 65536\n writer.writeAngle16(cmd.angles.x);\n writer.writeAngle16(cmd.angles.y);\n writer.writeAngle16(cmd.angles.z);\n\n // forwardmove (short)\n writer.writeShort(cmd.forwardmove);\n\n // sidemove (short)\n writer.writeShort(cmd.sidemove);\n\n // upmove (short)\n writer.writeShort(cmd.upmove);\n\n // impulse (byte)\n writer.writeByte(0); // TODO: Impulse in UserCommand\n\n // lightlevel (byte)\n writer.writeByte(0); // TODO: Lightlevel\n}\n","export enum RenderFx {\n MinLight = 1,\n ViewerModel = 2,\n WeaponModel = 4,\n FullBright = 8,\n DepthHack = 16,\n Translucent = 32,\n FrameLerp = 64,\n Beam = 128,\n CustomLight = 256,\n Glow = 512,\n ShellRed = 1024,\n ShellGreen = 2048,\n ShellBlue = 4096,\n IrVisible = 32768,\n ShellDouble = 65536,\n ShellHalfDam = 131072,\n MinLightPlus = 262144,\n ExtraLight = 524288,\n BeamLightning = 1048576,\n Flashlight = 2097152, // 1 << 21\n}\n","// Quake 2 CRC implementation\n// Ported from qcommon/crc.c\n\nconst crc_table: number[] = [\n 0x00, 0x91, 0xe3, 0x72, 0x07, 0x96, 0xe4, 0x75, 0x0e, 0x9f, 0xed, 0x7c, 0x09, 0x98, 0xea, 0x7b,\n 0x1c, 0x8d, 0xff, 0x6e, 0x1b, 0x8a, 0xf8, 0x69, 0x12, 0x83, 0xf1, 0x60, 0x15, 0x84, 0xf6, 0x67,\n 0x38, 0xa9, 0xdb, 0x4a, 0x3f, 0xae, 0xdc, 0x4d, 0x36, 0xa7, 0xd5, 0x44, 0x31, 0xa0, 0xd2, 0x43,\n 0x24, 0xb5, 0xc7, 0x56, 0x23, 0xb2, 0xc0, 0x51, 0x2a, 0xbb, 0xc9, 0x58, 0x2d, 0xbc, 0xce, 0x5f,\n 0x70, 0xe1, 0x93, 0x02, 0x77, 0xe6, 0x94, 0x05, 0x7e, 0xef, 0x9d, 0x0c, 0x79, 0xe8, 0x9a, 0x0b,\n 0x6c, 0xfd, 0x8f, 0x1e, 0x6b, 0xfa, 0x88, 0x19, 0x62, 0xf3, 0x81, 0x10, 0x65, 0xf4, 0x86, 0x17,\n 0x48, 0xd9, 0xab, 0x3a, 0x4f, 0xde, 0xac, 0x3d, 0x46, 0xd7, 0xa5, 0x34, 0x41, 0xd0, 0xa2, 0x33,\n 0x54, 0xc5, 0xb7, 0x26, 0x53, 0xc2, 0xb0, 0x21, 0x5a, 0xcb, 0xb9, 0x28, 0x5d, 0xcc, 0xbe, 0x2f,\n 0xe0, 0x71, 0x03, 0x92, 0xe7, 0x76, 0x04, 0x95, 0xee, 0x7f, 0x0d, 0x9c, 0xe9, 0x78, 0x0a, 0x9b,\n 0xfc, 0x6d, 0x1f, 0x8e, 0xfb, 0x6a, 0x18, 0x89, 0xf2, 0x63, 0x11, 0x80, 0xf5, 0x64, 0x16, 0x87,\n 0xd8, 0x49, 0x3b, 0xaa, 0xdf, 0x4e, 0x3c, 0xad, 0xd6, 0x47, 0x35, 0xa4, 0xd1, 0x40, 0x32, 0xa3,\n 0xc4, 0x55, 0x27, 0xb6, 0xc3, 0x52, 0x20, 0xb1, 0xca, 0x5b, 0x29, 0xb8, 0xcd, 0x5c, 0x2e, 0xbf,\n 0x90, 0x01, 0x73, 0xe2, 0x97, 0x06, 0x74, 0xe5, 0x9e, 0x0f, 0x7d, 0xec, 0x99, 0x08, 0x7a, 0xeb,\n 0x8c, 0x1d, 0x6f, 0xfe, 0x8b, 0x1a, 0x68, 0xf9, 0x82, 0x13, 0x61, 0xf0, 0x85, 0x14, 0x66, 0xf7,\n 0xa8, 0x39, 0x4b, 0xda, 0xaf, 0x3e, 0x4c, 0xdd, 0xa6, 0x37, 0x45, 0xd4, 0xa1, 0x30, 0x42, 0xd3,\n 0xb4, 0x25, 0x56, 0xc7, 0xb3, 0x22, 0x50, 0xc1, 0xba, 0x2b, 0x59, 0xc8, 0xbd, 0x2c, 0x5e, 0xcf\n];\n\n/**\n * Calculates 8-bit CRC for the given data\n */\nexport function crc8(data: Uint8Array): number {\n let crc = 0;\n for (let i = 0; i < data.length; i++) {\n crc = crc_table[(crc ^ data[i]) & 0xff];\n }\n return crc;\n}\n","// Source: game.h (Quake 2)\nexport enum EntityEffects {\n Rotate = 0x00000004,\n Gib = 0x00000008,\n RotateScript = 0x00000010,\n Blaster = 0x00000020,\n Rocket = 0x00000040,\n Grenade = 0x00000080,\n HyperBlaster = 0x00000100,\n Bfg = 0x00000200,\n ColorShell = 0x00000400,\n Powerscreen = 0x00000800,\n Anim01 = 0x00001000,\n Anim23 = 0x00002000,\n AnimAll = 0x00004000,\n AnimAllFast = 0x00008000,\n Quad = 0x00010000,\n Pent = 0x00020000,\n Explosion = 0x00040000,\n Teleport = 0x00080000,\n Flag1 = 0x00100000,\n Flag2 = 0x00200000,\n Boomerang = 0x00400000,\n Greengibs = 0x00800000,\n Bluehyperblaster = 0x01000000,\n Spinning = 0x02000000,\n Plasma = 0x04000000,\n Trap = 0x08000000,\n Tracker = 0x10000000,\n Double = 0x20000000,\n Sphinx = 0x40000000,\n TagTrail = 0x80000000,\n}\n","export enum EntityEvent {\n None = 0,\n ItemRespawn = 1,\n Footstep = 2,\n FallShort = 3,\n Fall = 4,\n FallFar = 5,\n PlayerTeleport = 6,\n OtherTeleport = 7,\n\n // [Paril-KEX]\n OtherFootstep = 8,\n LadderStep = 9,\n}\n","import { BinaryWriter } from '../io/index.js';\nimport { EntityState } from './entityState.js';\n\n// Constants matching packages/engine/src/demo/parser.ts\nexport const U_ORIGIN1 = (1 << 0);\nexport const U_ORIGIN2 = (1 << 1);\nexport const U_ANGLE2 = (1 << 2);\nexport const U_ANGLE3 = (1 << 3);\nexport const U_FRAME8 = (1 << 4);\nexport const U_EVENT = (1 << 5);\nexport const U_REMOVE = (1 << 6);\nexport const U_MOREBITS1 = (1 << 7);\n\nexport const U_NUMBER16 = (1 << 8);\nexport const U_ORIGIN3 = (1 << 9);\nexport const U_ANGLE1 = (1 << 10);\nexport const U_MODEL = (1 << 11);\nexport const U_RENDERFX8 = (1 << 12);\nexport const U_ALPHA = (1 << 13); // Rerelease: Alpha\nexport const U_EFFECTS8 = (1 << 14);\nexport const U_MOREBITS2 = (1 << 15);\n\nexport const U_SKIN8 = (1 << 16);\nexport const U_FRAME16 = (1 << 17);\nexport const U_RENDERFX16 = (1 << 18);\nexport const U_EFFECTS16 = (1 << 19);\nexport const U_MODEL2 = (1 << 20); // Rerelease\nexport const U_MODEL3 = (1 << 21); // Rerelease\nexport const U_MODEL4 = (1 << 22); // Rerelease\nexport const U_MOREBITS3 = (1 << 23);\n\nexport const U_OLDORIGIN = (1 << 24);\nexport const U_SKIN16 = (1 << 25);\nexport const U_SOUND = (1 << 26);\nexport const U_SOLID = (1 << 27);\nexport const U_SCALE = (1 << 28); // Rerelease\nexport const U_INSTANCE_BITS = (1 << 29); // Rerelease\nexport const U_LOOP_VOLUME = (1 << 30); // Rerelease\nexport const U_MOREBITS4 = 0x80000000 | 0; // Bit 31 (sign bit)\n\n// Rerelease Extension Bits (Byte 5 - High Bits)\nexport const U_LOOP_ATTENUATION_HIGH = (1 << 0);\nexport const U_OWNER_HIGH = (1 << 1);\nexport const U_OLD_FRAME_HIGH = (1 << 2);\n\n\n// A null state for new entities, used as a baseline for comparison.\nconst NULL_STATE: EntityState = {\n number: 0,\n origin: { x: 0, y: 0, z: 0 },\n angles: { x: 0, y: 0, z: 0 },\n modelIndex: 0,\n frame: 0,\n skinNum: 0,\n effects: 0,\n renderfx: 0,\n solid: 0,\n sound: 0,\n event: 0,\n alpha: 0,\n scale: 0,\n instanceBits: 0,\n loopVolume: 0,\n loopAttenuation: 0,\n owner: 0,\n oldFrame: 0,\n modelIndex2: 0,\n modelIndex3: 0,\n modelIndex4: 0\n};\n\n/**\n * Writes the remove bit for an entity.\n */\nexport function writeRemoveEntity(\n number: number,\n writer: BinaryWriter\n): void {\n let bits = U_REMOVE;\n\n if (number >= 256) {\n bits |= U_NUMBER16;\n }\n\n // Determine needed bytes for header (U_NUMBER16 is in bits 8-15)\n if (bits & 0xFF00) {\n bits |= U_MOREBITS1;\n }\n\n // Write Header\n writer.writeByte(bits & 0xFF);\n if (bits & U_MOREBITS1) {\n writer.writeByte((bits >> 8) & 0xFF);\n }\n\n // Write Number\n if (bits & U_NUMBER16) {\n writer.writeShort(number);\n } else {\n writer.writeByte(number);\n }\n}\n\n/**\n * Writes the delta between two entity states to a binary writer.\n */\nexport function writeDeltaEntity(\n from: EntityState,\n to: EntityState,\n writer: BinaryWriter,\n force: boolean,\n newEntity: boolean\n): void {\n let bits = 0;\n let bitsHigh = 0;\n\n // If this is a new entity, use a null baseline\n if (newEntity) {\n from = NULL_STATE;\n }\n\n // --- Compare fields and build the bitmask ---\n if (to.modelIndex !== from.modelIndex || force) {\n bits |= U_MODEL;\n }\n if (to.modelIndex2 !== from.modelIndex2 || force) {\n bits |= U_MODEL2;\n }\n if (to.modelIndex3 !== from.modelIndex3 || force) {\n bits |= U_MODEL3;\n }\n if (to.modelIndex4 !== from.modelIndex4 || force) {\n bits |= U_MODEL4;\n }\n\n if (to.origin.x !== from.origin.x || force) {\n bits |= U_ORIGIN1;\n }\n if (to.origin.y !== from.origin.y || force) {\n bits |= U_ORIGIN2;\n }\n if (to.origin.z !== from.origin.z || force) {\n bits |= U_ORIGIN3;\n }\n if (to.angles.x !== from.angles.x || force) {\n bits |= U_ANGLE1;\n }\n if (to.angles.y !== from.angles.y || force) {\n bits |= U_ANGLE2;\n }\n if (to.angles.z !== from.angles.z || force) {\n bits |= U_ANGLE3;\n }\n\n if (to.frame !== from.frame || force) {\n if (to.frame >= 256) bits |= U_FRAME16;\n else bits |= U_FRAME8;\n }\n\n if (to.skinNum !== from.skinNum || force) {\n if (to.skinNum >= 256) bits |= U_SKIN16;\n else bits |= U_SKIN8;\n }\n\n if (to.effects !== from.effects || force) {\n if (to.effects >= 256) bits |= U_EFFECTS16;\n else bits |= U_EFFECTS8;\n }\n\n if (to.renderfx !== from.renderfx || force) {\n if (to.renderfx >= 256) bits |= U_RENDERFX16;\n else bits |= U_RENDERFX8;\n }\n\n if (to.solid !== from.solid || force) {\n bits |= U_SOLID;\n }\n if (to.sound !== from.sound || force) {\n bits |= U_SOUND;\n }\n if (to.event !== from.event || force) {\n bits |= U_EVENT;\n }\n\n // Rerelease Fields\n if ((to.alpha !== from.alpha || force) && to.alpha !== undefined) {\n bits |= U_ALPHA;\n }\n if ((to.scale !== from.scale || force) && to.scale !== undefined) {\n bits |= U_SCALE;\n }\n if ((to.instanceBits !== from.instanceBits || force) && to.instanceBits !== undefined) {\n bits |= U_INSTANCE_BITS;\n }\n if ((to.loopVolume !== from.loopVolume || force) && to.loopVolume !== undefined) {\n bits |= U_LOOP_VOLUME;\n }\n\n // High Bits Fields\n if ((to.loopAttenuation !== from.loopAttenuation || force) && to.loopAttenuation !== undefined) {\n bitsHigh |= U_LOOP_ATTENUATION_HIGH;\n }\n if ((to.owner !== from.owner || force) && to.owner !== undefined) {\n bitsHigh |= U_OWNER_HIGH;\n }\n if ((to.oldFrame !== from.oldFrame || force) && to.oldFrame !== undefined) {\n bitsHigh |= U_OLD_FRAME_HIGH;\n }\n\n\n // Handle entity number\n if (to.number >= 256) {\n bits |= U_NUMBER16;\n }\n\n // Determine needed bytes for header\n\n // If we have high bits, we set U_MOREBITS4 on the 4th byte\n if (bitsHigh > 0) {\n bits |= U_MOREBITS4;\n }\n\n // Now calculate cascading flags\n if (bits & 0xFF000000) { // e.g. U_MOREBITS4 (bit 31) is here\n bits |= U_MOREBITS3;\n }\n if (bits & 0xFFFF0000) { // e.g. U_MOREBITS3 (bit 23) is here\n bits |= U_MOREBITS2;\n }\n if (bits & 0xFFFFFF00) { // e.g. U_MOREBITS2 (bit 15) is here\n bits |= U_MOREBITS1;\n }\n\n // Write Header\n writer.writeByte(bits & 0xFF);\n\n if (bits & U_MOREBITS1) {\n writer.writeByte((bits >> 8) & 0xFF);\n }\n if (bits & U_MOREBITS2) {\n writer.writeByte((bits >> 16) & 0xFF);\n }\n if (bits & U_MOREBITS3) {\n writer.writeByte((bits >> 24) & 0xFF);\n }\n if (bits & U_MOREBITS4) {\n writer.writeByte(bitsHigh & 0xFF);\n }\n\n // Write Number\n if (bits & U_NUMBER16) {\n writer.writeShort(to.number);\n } else {\n writer.writeByte(to.number);\n }\n\n // Write Fields in Order (matching NetworkMessageParser.parseDelta)\n if (bits & U_MODEL) writer.writeByte(to.modelIndex);\n if (bits & U_MODEL2) writer.writeByte(to.modelIndex2 ?? 0);\n if (bits & U_MODEL3) writer.writeByte(to.modelIndex3 ?? 0);\n if (bits & U_MODEL4) writer.writeByte(to.modelIndex4 ?? 0);\n\n if (bits & U_FRAME8) writer.writeByte(to.frame);\n if (bits & U_FRAME16) writer.writeShort(to.frame);\n\n if (bits & U_SKIN8) writer.writeByte(to.skinNum);\n if (bits & U_SKIN16) writer.writeShort(to.skinNum);\n\n if (bits & U_EFFECTS8) writer.writeByte(to.effects);\n if (bits & U_EFFECTS16) writer.writeShort(to.effects);\n\n if (bits & U_RENDERFX8) writer.writeByte(to.renderfx);\n if (bits & U_RENDERFX16) writer.writeShort(to.renderfx);\n\n if (bits & U_ORIGIN1) writer.writeCoord(to.origin.x);\n if (bits & U_ORIGIN2) writer.writeCoord(to.origin.y);\n if (bits & U_ORIGIN3) writer.writeCoord(to.origin.z);\n\n if (bits & U_ANGLE1) writer.writeAngle(to.angles.x);\n if (bits & U_ANGLE2) writer.writeAngle(to.angles.y);\n if (bits & U_ANGLE3) writer.writeAngle(to.angles.z);\n\n if (bits & U_OLDORIGIN) {\n // Not implemented in EntityState usually, skip or zero\n // writer.writePos(to.old_origin);\n }\n\n if (bits & U_SOUND) writer.writeByte(to.sound ?? 0);\n\n if (bits & U_EVENT) writer.writeByte(to.event ?? 0);\n\n if (bits & U_SOLID) writer.writeShort(to.solid);\n\n // Rerelease Fields Writing\n if (bits & U_ALPHA) writer.writeByte(Math.floor((to.alpha ?? 0) * 255));\n if (bits & U_SCALE) writer.writeFloat(to.scale ?? 0);\n if (bits & U_INSTANCE_BITS) writer.writeLong(to.instanceBits ?? 0);\n if (bits & U_LOOP_VOLUME) writer.writeByte(Math.floor((to.loopVolume ?? 0) * 255));\n\n // High bits fields\n if (bitsHigh & U_LOOP_ATTENUATION_HIGH) writer.writeByte(Math.floor((to.loopAttenuation ?? 0) * 255));\n if (bitsHigh & U_OWNER_HIGH) writer.writeShort(to.owner ?? 0);\n if (bitsHigh & U_OLD_FRAME_HIGH) writer.writeShort(to.oldFrame ?? 0);\n}\n","import { BinaryWriter, Vec3 } from '../index.js';\n\nexport interface ProtocolPlayerState {\n pm_type: number;\n origin: Vec3;\n velocity: Vec3;\n pm_time: number;\n pm_flags: number;\n gravity: number;\n delta_angles: Vec3;\n viewoffset: Vec3;\n viewangles: Vec3;\n kick_angles: Vec3;\n gun_index: number;\n gun_frame: number;\n gun_offset: Vec3;\n gun_angles: Vec3;\n blend: number[]; // [r,g,b,a]\n fov: number;\n rdflags: number;\n stats: number[];\n\n // Optional / Extension fields if needed\n gunskin?: number;\n gunrate?: number;\n damage_blend?: number[];\n team_id?: number;\n}\n\n// Bitflags matching demo/parser.ts\nconst PS_M_TYPE = (1 << 0);\nconst PS_M_ORIGIN = (1 << 1);\nconst PS_M_VELOCITY = (1 << 2);\nconst PS_M_TIME = (1 << 3);\nconst PS_M_FLAGS = (1 << 4);\nconst PS_M_GRAVITY = (1 << 5);\nconst PS_M_DELTA_ANGLES = (1 << 6);\nconst PS_VIEWOFFSET = (1 << 7);\nconst PS_VIEWANGLES = (1 << 8);\nconst PS_KICKANGLES = (1 << 9);\nconst PS_BLEND = (1 << 10);\nconst PS_FOV = (1 << 11);\nconst PS_WEAPONINDEX = (1 << 12);\nconst PS_WEAPONFRAME = (1 << 13);\nconst PS_RDFLAGS = (1 << 14);\n\nexport function writePlayerState(writer: BinaryWriter, ps: ProtocolPlayerState): void {\n // Determine mask\n let mask = 0;\n\n if (ps.pm_type !== 0) mask |= PS_M_TYPE;\n if (ps.origin.x !== 0 || ps.origin.y !== 0 || ps.origin.z !== 0) mask |= PS_M_ORIGIN;\n if (ps.velocity.x !== 0 || ps.velocity.y !== 0 || ps.velocity.z !== 0) mask |= PS_M_VELOCITY;\n if (ps.pm_time !== 0) mask |= PS_M_TIME;\n if (ps.pm_flags !== 0) mask |= PS_M_FLAGS;\n if (ps.gravity !== 0) mask |= PS_M_GRAVITY;\n if (ps.delta_angles.x !== 0 || ps.delta_angles.y !== 0 || ps.delta_angles.z !== 0) mask |= PS_M_DELTA_ANGLES;\n if (ps.viewoffset.x !== 0 || ps.viewoffset.y !== 0 || ps.viewoffset.z !== 0) mask |= PS_VIEWOFFSET;\n if (ps.viewangles.x !== 0 || ps.viewangles.y !== 0 || ps.viewangles.z !== 0) mask |= PS_VIEWANGLES;\n if (ps.kick_angles.x !== 0 || ps.kick_angles.y !== 0 || ps.kick_angles.z !== 0) mask |= PS_KICKANGLES;\n if (ps.gun_index !== 0) mask |= PS_WEAPONINDEX;\n\n // Weapon frame includes offset/angles\n if (ps.gun_frame !== 0 ||\n ps.gun_offset.x !== 0 || ps.gun_offset.y !== 0 || ps.gun_offset.z !== 0 ||\n ps.gun_angles.x !== 0 || ps.gun_angles.y !== 0 || ps.gun_angles.z !== 0) {\n mask |= PS_WEAPONFRAME;\n }\n\n if (ps.blend && (ps.blend[0] !== 0 || ps.blend[1] !== 0 || ps.blend[2] !== 0 || ps.blend[3] !== 0)) {\n mask |= PS_BLEND;\n }\n\n if (ps.fov !== 0) mask |= PS_FOV;\n if (ps.rdflags !== 0) mask |= PS_RDFLAGS;\n\n // Stats mask calculation\n let statsMask = 0;\n // Only support first 32 stats for now\n for (let i = 0; i < 32; i++) {\n if (ps.stats[i] && ps.stats[i] !== 0) {\n statsMask |= (1 << i);\n }\n }\n\n // Write header\n writer.writeShort(mask);\n\n // Write fields\n if (mask & PS_M_TYPE) writer.writeByte(ps.pm_type);\n\n if (mask & PS_M_ORIGIN) {\n writer.writeShort(Math.round(ps.origin.x * 8));\n writer.writeShort(Math.round(ps.origin.y * 8));\n writer.writeShort(Math.round(ps.origin.z * 8));\n }\n\n if (mask & PS_M_VELOCITY) {\n writer.writeShort(Math.round(ps.velocity.x * 8));\n writer.writeShort(Math.round(ps.velocity.y * 8));\n writer.writeShort(Math.round(ps.velocity.z * 8));\n }\n\n if (mask & PS_M_TIME) writer.writeByte(ps.pm_time);\n if (mask & PS_M_FLAGS) writer.writeByte(ps.pm_flags);\n if (mask & PS_M_GRAVITY) writer.writeShort(ps.gravity);\n\n if (mask & PS_M_DELTA_ANGLES) {\n writer.writeShort(Math.round(ps.delta_angles.x * (32768 / 180)));\n writer.writeShort(Math.round(ps.delta_angles.y * (32768 / 180)));\n writer.writeShort(Math.round(ps.delta_angles.z * (32768 / 180)));\n }\n\n if (mask & PS_VIEWOFFSET) {\n writer.writeChar(Math.round(ps.viewoffset.x * 4));\n writer.writeChar(Math.round(ps.viewoffset.y * 4));\n writer.writeChar(Math.round(ps.viewoffset.z * 4));\n }\n\n if (mask & PS_VIEWANGLES) {\n writer.writeAngle16(ps.viewangles.x);\n writer.writeAngle16(ps.viewangles.y);\n writer.writeAngle16(ps.viewangles.z);\n }\n\n if (mask & PS_KICKANGLES) {\n writer.writeChar(Math.round(ps.kick_angles.x * 4));\n writer.writeChar(Math.round(ps.kick_angles.y * 4));\n writer.writeChar(Math.round(ps.kick_angles.z * 4));\n }\n\n if (mask & PS_WEAPONINDEX) writer.writeByte(ps.gun_index);\n\n if (mask & PS_WEAPONFRAME) {\n writer.writeByte(ps.gun_frame);\n writer.writeChar(Math.round(ps.gun_offset.x * 4));\n writer.writeChar(Math.round(ps.gun_offset.y * 4));\n writer.writeChar(Math.round(ps.gun_offset.z * 4));\n writer.writeChar(Math.round(ps.gun_angles.x * 4));\n writer.writeChar(Math.round(ps.gun_angles.y * 4));\n writer.writeChar(Math.round(ps.gun_angles.z * 4));\n }\n\n if (mask & PS_BLEND) {\n writer.writeByte(Math.round(ps.blend[0]));\n writer.writeByte(Math.round(ps.blend[1]));\n writer.writeByte(Math.round(ps.blend[2]));\n writer.writeByte(Math.round(ps.blend[3]));\n }\n\n if (mask & PS_FOV) writer.writeByte(ps.fov);\n if (mask & PS_RDFLAGS) writer.writeByte(ps.rdflags);\n\n // Write Stats\n writer.writeLong(statsMask);\n for (let i = 0; i < 32; i++) {\n if (statsMask & (1 << i)) {\n writer.writeShort(ps.stats[i]);\n }\n }\n}\n","\nimport { PmoveCmd, PmoveTraceFn } from './types.js';\nimport { Vec3 } from '../math/vec3.js';\n\nimport { applyPmoveAccelerate, applyPmoveFriction, buildAirGroundWish, buildWaterWish } from './pmove.js';\nimport { PlayerState } from '../protocol/player-state.js';\nimport { angleVectors } from '../math/angles.js';\nimport { MASK_WATER } from '../bsp/contents.js';\n\nconst FRAMETIME = 0.025;\n\n// Local definition to avoid dependency issues if constants.ts is missing\n// Matches packages/shared/src/pmove/constants.ts\nconst WaterLevel = {\n None: 0,\n Feet: 1,\n Waist: 2,\n Under: 3,\n} as const;\n\nconst categorizePosition = (state: PlayerState, trace: PmoveTraceFn): PlayerState => {\n const point = { ...state.origin };\n point.z -= 0.25;\n const traceResult = trace(state.origin, point);\n\n return {\n ...state,\n onGround: traceResult.fraction < 1,\n };\n};\n\nconst checkWater = (state: PlayerState, pointContents: (point: Vec3) => number): PlayerState => {\n const point = { ...state.origin };\n const { mins, maxs } = state;\n\n // Default to feet\n point.z = state.origin.z + mins.z + 1;\n\n const feetContents = pointContents(point);\n\n if (!(feetContents & MASK_WATER)) {\n return { ...state, waterLevel: WaterLevel.None, watertype: 0 };\n }\n\n let waterLevel: number = WaterLevel.Feet;\n let watertype = feetContents;\n\n // Check waist\n const waist = state.origin.z + (mins.z + maxs.z) * 0.5;\n point.z = waist;\n const waistContents = pointContents(point);\n\n if (waistContents & MASK_WATER) {\n waterLevel = WaterLevel.Waist;\n watertype = waistContents;\n\n // Check head (eyes)\n // Standard Quake 2 viewheight is 22. maxs.z is typically 32.\n // So eyes are roughly at origin.z + 22.\n // We'll use origin.z + 22 to check if eyes are underwater.\n // If viewheight was available in PlayerState, we'd use that.\n const head = state.origin.z + 22;\n point.z = head;\n const headContents = pointContents(point);\n\n if (headContents & MASK_WATER) {\n waterLevel = WaterLevel.Under;\n watertype = headContents;\n }\n }\n\n return { ...state, waterLevel, watertype };\n};\n\n\nexport const applyPmove = (\n state: PlayerState,\n cmd: PmoveCmd,\n trace: PmoveTraceFn,\n pointContents: (point: Vec3) => number\n): PlayerState => {\n let newState = { ...state };\n newState = categorizePosition(newState, trace);\n newState = checkWater(newState, pointContents);\n\n const { origin, velocity, onGround, waterLevel, viewAngles } = newState;\n\n // Calculate forward and right vectors from view angles\n // For water movement, use full view angles including pitch\n // For ground/air movement, reduce pitch influence by dividing by 3\n // See: rerelease/p_move.cpp lines 1538, 1686-1691, 800, 858\n const adjustedAngles = waterLevel >= 2\n ? viewAngles\n : {\n // For ground/air movement, reduce pitch influence (rerelease/p_move.cpp:1689)\n x: viewAngles.x > 180 ? (viewAngles.x - 360) / 3 : viewAngles.x / 3,\n y: viewAngles.y,\n z: viewAngles.z,\n };\n\n const { forward, right } = angleVectors(adjustedAngles);\n\n // Apply friction BEFORE acceleration to match original Quake 2 rerelease behavior\n // See: rerelease/src/game/player/pmove.c lines 1678 (PM_Friction) then 1693 (PM_AirMove->PM_Accelerate)\n const frictionedVelocity = applyPmoveFriction({\n velocity,\n frametime: FRAMETIME,\n onGround,\n groundIsSlick: false,\n onLadder: false,\n waterlevel: waterLevel,\n pmFriction: 6,\n pmStopSpeed: 100,\n pmWaterFriction: 1,\n });\n\n const wish = waterLevel >= 2\n ? buildWaterWish({\n forward,\n right,\n cmd,\n maxSpeed: 320,\n })\n : buildAirGroundWish({\n forward,\n right,\n cmd,\n maxSpeed: 320,\n });\n\n const finalVelocity = applyPmoveAccelerate({\n velocity: frictionedVelocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n // Water movement uses ground acceleration (10), not air acceleration (1)\n accel: (onGround || waterLevel >= 2) ? 10 : 1,\n frametime: FRAMETIME,\n });\n\n const traceResult = trace(origin, {\n x: origin.x + finalVelocity.x * FRAMETIME,\n y: origin.y + finalVelocity.y * FRAMETIME,\n z: origin.z + finalVelocity.z * FRAMETIME,\n });\n\n return {\n ...newState,\n origin: traceResult.endpos,\n velocity: finalVelocity,\n };\n};\n","import { Vec3 } from '../math/vec3.js';\nimport { ANORMS } from '../math/anorms.js';\n\nexport class BinaryStream {\n private view: DataView;\n private offset: number;\n private length: number;\n\n constructor(buffer: ArrayBuffer | Uint8Array) {\n if (buffer instanceof Uint8Array) {\n this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n } else {\n this.view = new DataView(buffer);\n }\n this.offset = 0;\n this.length = this.view.byteLength;\n }\n\n public getPosition(): number {\n return this.offset;\n }\n\n public getReadPosition(): number {\n return this.offset;\n }\n\n public getLength(): number {\n return this.length;\n }\n\n public getRemaining(): number {\n return this.length - this.offset;\n }\n\n public seek(position: number): void {\n if (position < 0 || position > this.length) {\n throw new Error(`Seek out of bounds: ${position} (length: ${this.length})`);\n }\n this.offset = position;\n }\n\n public setReadPosition(position: number): void {\n this.seek(position);\n }\n\n public hasMore(): boolean {\n return this.offset < this.length;\n }\n\n public hasBytes(count: number): boolean {\n return this.offset + count <= this.length;\n }\n\n public readChar(): number {\n const value = this.view.getInt8(this.offset);\n this.offset += 1;\n return value;\n }\n\n public readByte(): number {\n const value = this.view.getUint8(this.offset);\n this.offset += 1;\n return value;\n }\n\n public readShort(): number {\n const value = this.view.getInt16(this.offset, true);\n this.offset += 2;\n return value;\n }\n\n public readUShort(): number {\n const value = this.view.getUint16(this.offset, true);\n this.offset += 2;\n return value;\n }\n\n public readLong(): number {\n const value = this.view.getInt32(this.offset, true);\n this.offset += 4;\n return value;\n }\n\n public readULong(): number {\n const value = this.view.getUint32(this.offset, true);\n this.offset += 4;\n return value;\n }\n\n public readFloat(): number {\n const value = this.view.getFloat32(this.offset, true);\n this.offset += 4;\n return value;\n }\n\n public readString(): string {\n let str = '';\n while (this.offset < this.length) {\n const charCode = this.readChar();\n if (charCode === -1 || charCode === 0) {\n break;\n }\n str += String.fromCharCode(charCode);\n }\n return str;\n }\n\n public readStringLine(): string {\n let str = '';\n while (this.offset < this.length) {\n const charCode = this.readChar();\n if (charCode === -1 || charCode === 0 || charCode === 10) { // 10 is \\n\n break;\n }\n str += String.fromCharCode(charCode);\n }\n return str;\n }\n\n public readCoord(): number {\n return this.readShort() * (1.0 / 8.0);\n }\n\n public readAngle(): number {\n return this.readChar() * (360.0 / 256.0);\n }\n\n public readAngle16(): number {\n return (this.readShort() * 360.0) / 65536.0;\n }\n\n public readData(length: number): Uint8Array {\n if (this.offset + length > this.length) {\n throw new Error(`Read out of bounds: ${this.offset + length} (length: ${this.length})`);\n }\n const data = new Uint8Array(this.view.buffer, this.view.byteOffset + this.offset, length);\n this.offset += length;\n // Return a copy to avoid side effects if the original buffer is modified or reused\n return new Uint8Array(data);\n }\n\n public readPos(out: { x: number, y: number, z: number }): void {\n out.x = this.readCoord();\n out.y = this.readCoord();\n out.z = this.readCoord();\n }\n\n public readDir(out: { x: number, y: number, z: number }): void {\n const b = this.readByte();\n if (b >= 162) { // NUMVERTEXNORMALS\n out.x = 0; out.y = 0; out.z = 0;\n return;\n }\n const norm = ANORMS[b];\n out.x = norm[0];\n out.y = norm[1];\n out.z = norm[2];\n }\n}\n","import { ANORMS } from '../math/anorms.js';\nimport { Vec3 } from '../math/vec3.js';\n\nexport class BinaryWriter {\n private buffer: Uint8Array;\n private view: DataView;\n private offset: number;\n private readonly fixed: boolean;\n\n constructor(sizeOrBuffer: number | Uint8Array = 1400) {\n if (typeof sizeOrBuffer === 'number') {\n this.buffer = new Uint8Array(sizeOrBuffer);\n this.fixed = false;\n } else {\n this.buffer = sizeOrBuffer;\n this.fixed = true;\n }\n this.view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n this.offset = 0;\n }\n\n private ensureSpace(bytes: number) {\n if (this.offset + bytes > this.buffer.byteLength) {\n if (this.fixed) {\n throw new Error(`Buffer overflow: capacity ${this.buffer.byteLength}, needed ${this.offset + bytes}`);\n }\n // Expand buffer (double size)\n const newSize = Math.max(this.buffer.byteLength * 2, this.offset + bytes);\n const newBuffer = new Uint8Array(newSize);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n this.view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n }\n }\n\n public writeByte(value: number): void {\n this.ensureSpace(1);\n this.view.setUint8(this.offset, value);\n this.offset += 1;\n }\n\n public writeBytes(data: Uint8Array): void {\n this.ensureSpace(data.byteLength);\n this.buffer.set(data, this.offset);\n this.offset += data.byteLength;\n }\n\n public writeChar(value: number): void {\n this.ensureSpace(1);\n this.view.setInt8(this.offset, value);\n this.offset += 1;\n }\n\n public writeShort(value: number): void {\n this.ensureSpace(2);\n // Use setUint16 to allow writing 0xFFFF as a valid pattern even if it represents -1\n // But value might be negative (-1). setUint16(-1) wraps to 65535.\n // So setInt16 is fine if value is in range.\n // If value is 65535 (from bit manipulation), setInt16 might throw?\n // Let's safe cast.\n this.view.setInt16(this.offset, value, true);\n this.offset += 2;\n }\n\n public writeLong(value: number): void {\n this.ensureSpace(4);\n this.view.setInt32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeFloat(value: number): void {\n this.ensureSpace(4);\n this.view.setFloat32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeString(value: string): void {\n // UTF-8 encoding of string + null terminator\n // We iterate manually to match readString behavior (ASCII/Latin1 mostly)\n // and avoid TextEncoder overhead if simple\n const len = value.length;\n this.ensureSpace(len + 1);\n for (let i = 0; i < len; i++) {\n this.view.setUint8(this.offset + i, value.charCodeAt(i));\n }\n this.view.setUint8(this.offset + len, 0);\n this.offset += len + 1;\n }\n\n public writeCoord(value: number): void {\n this.writeShort(Math.trunc(value * 8));\n }\n\n public writeAngle(value: number): void {\n this.writeByte(Math.trunc(value * 256.0 / 360.0) & 255);\n }\n\n public writeAngle16(value: number): void {\n this.writeShort(Math.trunc(value * 65536.0 / 360.0) & 65535);\n }\n\n public writePos(pos: Vec3): void {\n this.writeCoord(pos.x);\n this.writeCoord(pos.y);\n this.writeCoord(pos.z);\n }\n\n public writeDir(dir: Vec3): void {\n // Find closest normal\n let maxDot = -1.0;\n let bestIndex = 0;\n\n // Check for zero vector\n if (dir.x === 0 && dir.y === 0 && dir.z === 0) {\n this.writeByte(0);\n return;\n }\n\n for (let i = 0; i < ANORMS.length; i++) {\n const norm = ANORMS[i];\n const dot = dir.x * norm[0] + dir.y * norm[1] + dir.z * norm[2];\n if (dot > maxDot) {\n maxDot = dot;\n bestIndex = i;\n }\n }\n\n this.writeByte(bestIndex);\n }\n\n public getData(): Uint8Array {\n return this.buffer.slice(0, this.offset);\n }\n\n public getBuffer(): Uint8Array {\n return this.buffer;\n }\n\n public getOffset(): number {\n return this.offset;\n }\n\n public reset(): void {\n this.offset = 0;\n }\n}\n","import { ANORMS } from '../math/anorms.js';\n\nexport class NetworkMessageBuilder {\n private buffer: Uint8Array;\n private view: DataView;\n private offset: number;\n\n constructor(initialSize: number = 1024) {\n this.buffer = new Uint8Array(initialSize);\n this.view = new DataView(this.buffer.buffer);\n this.offset = 0;\n }\n\n private ensureCapacity(needed: number): void {\n if (this.offset + needed > this.buffer.length) {\n const newSize = Math.max(this.buffer.length * 2, this.offset + needed);\n const newBuffer = new Uint8Array(newSize);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n this.view = new DataView(this.buffer.buffer);\n }\n }\n\n public getData(): Uint8Array {\n return this.buffer.slice(0, this.offset);\n }\n\n public writeByte(value: number): void {\n this.ensureCapacity(1);\n this.view.setUint8(this.offset, value);\n this.offset += 1;\n }\n\n public writeChar(value: number): void {\n this.ensureCapacity(1);\n this.view.setInt8(this.offset, value);\n this.offset += 1;\n }\n\n public writeShort(value: number): void {\n this.ensureCapacity(2);\n this.view.setInt16(this.offset, value, true);\n this.offset += 2;\n }\n\n public writeUShort(value: number): void {\n this.ensureCapacity(2);\n this.view.setUint16(this.offset, value, true);\n this.offset += 2;\n }\n\n public writeLong(value: number): void {\n this.ensureCapacity(4);\n this.view.setInt32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeFloat(value: number): void {\n this.ensureCapacity(4);\n this.view.setFloat32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeString(value: string): void {\n const len = value.length + 1; // +1 for null terminator\n this.ensureCapacity(len);\n for (let i = 0; i < value.length; i++) {\n this.view.setUint8(this.offset + i, value.charCodeAt(i));\n }\n this.view.setUint8(this.offset + value.length, 0);\n this.offset += len;\n }\n\n public writeData(data: Uint8Array): void {\n this.ensureCapacity(data.length);\n this.buffer.set(data, this.offset);\n this.offset += data.length;\n }\n\n public writeCoord(value: number): void {\n this.writeShort(Math.round(value * 8.0));\n }\n\n public writeAngle(value: number): void {\n this.writeByte(Math.round(value * 256.0 / 360.0) & 255);\n }\n\n public writeAngle16(value: number): void {\n this.writeShort(Math.round(value * 65536.0 / 360.0));\n }\n\n public writeDir(x: number, y: number, z: number): void {\n // Find closest normal from ANORMS\n // Simple brute force or use lookup if needed.\n // For now, let's just use 0 if implementation is complex to find best match.\n // Or unimplemented for now?\n // \"WriteDir\" in Q2 usually means writing a byte index into ANORMS.\n\n let best = 0;\n let bestDot = -999999;\n\n const len = Math.sqrt(x*x + y*y + z*z);\n if (len > 0) {\n x /= len; y /= len; z /= len;\n\n for (let i=0; i<162; i++) {\n const dot = x*ANORMS[i][0] + y*ANORMS[i][1] + z*ANORMS[i][2];\n if (dot > bestDot) {\n bestDot = dot;\n best = i;\n }\n }\n }\n\n this.writeByte(best);\n }\n}\n","import { BinaryWriter } from '../io/binaryWriter.js';\n\nexport interface NetAddress {\n type: string;\n port: number;\n}\n\n/**\n * NetChan handles reliable message delivery over an unreliable channel (UDP/WebSocket).\n * Fragmentation support is planned but not fully implemented.\n *\n * Ported from qcommon/net_chan.c\n */\nexport class NetChan {\n // Constants from net_chan.c\n static readonly MAX_MSGLEN = 1400;\n static readonly FRAGMENT_SIZE = 1024;\n static readonly PACKET_HEADER = 10; // sequence(4) + ack(4) + qport(2)\n static readonly HEADER_OVERHEAD = NetChan.PACKET_HEADER + 2; // +2 for reliable length prefix\n\n // Increase internal reliable buffer to support large messages (fragmentation)\n // Quake 2 uses MAX_MSGLEN for the reliable buffer, limiting single messages to ~1400 bytes.\n // We expand this to allow larger messages (e.g. snapshots, downloads) which are then fragmented.\n static readonly MAX_RELIABLE_BUFFER = 0x40000; // 256KB\n\n // Public state\n qport = 0; // qport value to distinguish multiple clients from same IP\n\n // Sequencing\n incomingSequence = 0;\n outgoingSequence = 0;\n incomingAcknowledged = 0;\n\n // Reliable messaging\n incomingReliableAcknowledged = false; // single bit\n incomingReliableSequence = 0; // last reliable message sequence received\n outgoingReliableSequence = 0; // reliable message sequence number to send\n reliableMessage: BinaryWriter;\n reliableLength = 0;\n\n // Fragmentation State (Sending)\n fragmentSendOffset = 0;\n\n // Fragmentation State (Receiving)\n fragmentBuffer: Uint8Array | null = null;\n fragmentLength = 0;\n fragmentReceived = 0;\n\n // Timing\n lastReceived = 0;\n lastSent = 0;\n\n remoteAddress: NetAddress | null = null;\n\n constructor() {\n // Initialize buffers\n this.reliableMessage = new BinaryWriter(NetChan.MAX_RELIABLE_BUFFER);\n\n // Set initial timestamps\n const now = Date.now();\n this.lastReceived = now;\n this.lastSent = now;\n\n // Random qport by default (can be overridden)\n // Ensure we use global Math.random which is usually seeded or random enough for basic collision avoidance\n this.qport = Math.floor(Math.random() * 65536);\n }\n\n /**\n * Setup the netchan with specific settings\n */\n setup(qport: number, address: NetAddress | null = null): void {\n this.qport = qport;\n this.remoteAddress = address;\n this.reset();\n }\n\n /**\n * Reset the netchan state\n */\n reset(): void {\n this.incomingSequence = 0;\n this.outgoingSequence = 0;\n this.incomingAcknowledged = 0;\n this.incomingReliableAcknowledged = false;\n this.incomingReliableSequence = 0;\n this.outgoingReliableSequence = 0;\n this.reliableLength = 0;\n this.reliableMessage.reset();\n\n this.fragmentSendOffset = 0;\n this.fragmentBuffer = null;\n this.fragmentLength = 0;\n this.fragmentReceived = 0;\n\n this.lastReceived = Date.now();\n this.lastSent = Date.now();\n }\n\n /**\n * Transmits a packet containing reliable and unreliable data\n */\n transmit(unreliableData?: Uint8Array): Uint8Array {\n this.outgoingSequence++;\n this.lastSent = Date.now();\n\n // Determine how much reliable data to send in this packet\n let sendReliableLength = 0;\n let isFragment = false;\n let fragmentStart = 0;\n\n if (this.reliableLength > 0) {\n // Check if we need to fragment\n if (this.reliableLength > NetChan.FRAGMENT_SIZE) {\n // We are in fragment mode\n isFragment = true;\n\n // If we have finished sending all fragments but still haven't received ACK,\n // we must loop back to the beginning to retransmit.\n if (this.fragmentSendOffset >= this.reliableLength) {\n this.fragmentSendOffset = 0;\n }\n\n // Calculate chunk size\n const remaining = this.reliableLength - this.fragmentSendOffset;\n sendReliableLength = remaining;\n if (sendReliableLength > NetChan.FRAGMENT_SIZE) {\n sendReliableLength = NetChan.FRAGMENT_SIZE;\n }\n\n fragmentStart = this.fragmentSendOffset;\n\n // Advance offset for the next packet\n this.fragmentSendOffset += sendReliableLength;\n } else {\n // Fits in one packet\n sendReliableLength = this.reliableLength;\n }\n }\n\n // Calculate total size\n // Header + Reliable + Unreliable\n const headerSize = NetChan.PACKET_HEADER;\n const reliableHeaderSize = sendReliableLength > 0 ? 2 + (isFragment ? 8 : 0) : 0; // +2 length, +8 fragment info\n\n let unreliableSize = unreliableData ? unreliableData.length : 0;\n\n // Check for overflow\n if (headerSize + reliableHeaderSize + sendReliableLength + unreliableSize > NetChan.MAX_MSGLEN) {\n unreliableSize = NetChan.MAX_MSGLEN - headerSize - reliableHeaderSize - sendReliableLength;\n // We truncate unreliable data if it doesn't fit with reliable data\n if (unreliableSize < 0) unreliableSize = 0;\n }\n\n const buffer = new ArrayBuffer(headerSize + reliableHeaderSize + sendReliableLength + unreliableSize);\n const view = new DataView(buffer);\n const result = new Uint8Array(buffer);\n\n // Write Header\n // Sequence\n let sequence = this.outgoingSequence;\n\n // Set reliable bit if we are sending reliable data\n if (sendReliableLength > 0) {\n sequence |= 0x80000000;\n // Also set the reliable sequence bit (0/1 toggle) at bit 30\n if ((this.outgoingReliableSequence & 1) !== 0) {\n sequence |= 0x40000000;\n }\n }\n\n view.setUint32(0, sequence, true);\n\n // Acknowledge\n // Set reliable ack bit at bit 31\n let ack = this.incomingSequence;\n if ((this.incomingReliableSequence & 1) !== 0) {\n ack |= 0x80000000;\n }\n view.setUint32(4, ack, true);\n\n view.setUint16(8, this.qport, true);\n\n // Copy Reliable Data\n let offset = headerSize;\n if (sendReliableLength > 0) {\n // Write length of reliable data (2 bytes)\n // Extension: If length has high bit (0x8000), it's a fragment.\n let lengthField = sendReliableLength;\n if (isFragment) {\n lengthField |= 0x8000;\n }\n\n view.setUint16(offset, lengthField, true);\n offset += 2;\n\n if (isFragment) {\n // Write fragment info: 4 bytes start offset, 4 bytes total length\n view.setUint32(offset, fragmentStart, true);\n offset += 4;\n view.setUint32(offset, this.reliableLength, true);\n offset += 4;\n }\n\n // Copy data\n const reliableBuffer = this.reliableMessage.getBuffer();\n const reliableBytes = reliableBuffer.subarray(fragmentStart, fragmentStart + sendReliableLength);\n result.set(reliableBytes, offset);\n offset += sendReliableLength;\n }\n\n // Copy Unreliable Data\n if (unreliableData && unreliableSize > 0) {\n const chunk = unreliableData.slice(0, unreliableSize);\n result.set(chunk, offset);\n }\n\n return result;\n }\n\n /**\n * Processes a received packet\n * Returns the payload data (reliable + unreliable) to be processed, or null if discarded\n */\n process(packet: Uint8Array): Uint8Array | null {\n if (packet.length < NetChan.PACKET_HEADER) {\n return null;\n }\n\n this.lastReceived = Date.now();\n\n const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);\n const sequence = view.getUint32(0, true);\n const ack = view.getUint32(4, true);\n const qport = view.getUint16(8, true);\n\n if (this.qport !== qport) {\n return null;\n }\n\n // Check for duplicate or out of order\n const seqNumberClean = sequence & ~(0x80000000 | 0x40000000); // Mask out flags\n\n // Handle wrapping using signed difference\n if (((seqNumberClean - this.incomingSequence) | 0) <= 0) {\n return null;\n }\n\n // Update incoming sequence\n this.incomingSequence = seqNumberClean;\n\n // Handle reliable acknowledgment\n const ackNumber = ack & ~0x80000000;\n const ackReliable = (ack & 0x80000000) !== 0;\n\n if (ackNumber > this.incomingAcknowledged) {\n this.incomingAcknowledged = ackNumber;\n }\n\n // Check if our reliable message was acknowledged\n // If the receiver has toggled their reliable bit, it means they got the WHOLE message\n if (this.reliableLength > 0) {\n const receivedAckBit = ackReliable ? 1 : 0;\n const currentReliableBit = this.outgoingReliableSequence & 1;\n\n if (receivedAckBit !== currentReliableBit) {\n // Acked!\n this.reliableLength = 0;\n this.reliableMessage.reset();\n this.outgoingReliableSequence ^= 1;\n this.fragmentSendOffset = 0; // Reset fragment offset\n }\n }\n\n // Handle incoming reliable data\n const hasReliableData = (sequence & 0x80000000) !== 0;\n const reliableSeqBit = (sequence & 0x40000000) !== 0 ? 1 : 0;\n\n let payloadOffset = NetChan.PACKET_HEADER;\n let reliableData: Uint8Array | null = null;\n\n if (hasReliableData) {\n if (payloadOffset + 2 > packet.byteLength) return null; // Malformed\n\n let reliableLen = view.getUint16(payloadOffset, true);\n payloadOffset += 2;\n\n const isFragment = (reliableLen & 0x8000) !== 0;\n reliableLen &= 0x7FFF;\n\n // Check if this is the expected reliable sequence\n const expectedBit = this.incomingReliableSequence & 1;\n\n if (reliableSeqBit === expectedBit) {\n // It's the sequence we are waiting for\n\n if (isFragment) {\n // Read fragment info\n if (payloadOffset + 8 > packet.byteLength) return null;\n const fragStart = view.getUint32(payloadOffset, true);\n payloadOffset += 4;\n const fragTotal = view.getUint32(payloadOffset, true);\n payloadOffset += 4;\n\n // Validate fragTotal against MAX_RELIABLE_BUFFER\n if (fragTotal > NetChan.MAX_RELIABLE_BUFFER) {\n console.warn(`NetChan: received invalid fragment total ${fragTotal} > ${NetChan.MAX_RELIABLE_BUFFER}`);\n return null;\n }\n\n // Initialize fragment buffer if needed\n if (!this.fragmentBuffer || this.fragmentBuffer.length !== fragTotal) {\n this.fragmentBuffer = new Uint8Array(fragTotal);\n this.fragmentLength = fragTotal;\n this.fragmentReceived = 0;\n }\n\n // Check for valid fragment offset\n if (payloadOffset + reliableLen > packet.byteLength) return null;\n const data = packet.subarray(payloadOffset, payloadOffset + reliableLen);\n\n // Only accept if it matches our expected offset (enforce in-order delivery for simplicity)\n // or check if we haven't received this part yet.\n // Since we use a simple 'fragmentReceived' counter, we effectively expect in-order delivery\n // of streams if we just use append logic.\n // BUT UDP can reorder.\n // To be robust, we should enforce strict ordering: fragStart must equal fragmentReceived.\n // If we miss a chunk, we ignore subsequent chunks until the missing one arrives (via retransmit loop).\n\n if (fragStart === this.fragmentReceived && fragStart + reliableLen <= fragTotal) {\n this.fragmentBuffer.set(data, fragStart);\n this.fragmentReceived += reliableLen;\n\n // Check if complete\n if (this.fragmentReceived >= fragTotal) {\n reliableData = this.fragmentBuffer;\n this.incomingReliableSequence++;\n this.fragmentBuffer = null;\n this.fragmentLength = 0;\n this.fragmentReceived = 0;\n }\n }\n\n } else {\n // Not a fragment (standard)\n this.incomingReliableSequence++;\n if (payloadOffset + reliableLen > packet.byteLength) return null;\n reliableData = packet.slice(payloadOffset, payloadOffset + reliableLen);\n }\n }\n\n // Advance past reliable data regardless\n payloadOffset += reliableLen;\n }\n\n // Get unreliable data\n const unreliableData = packet.slice(payloadOffset);\n\n // Combine if we have reliable data\n if (reliableData && reliableData.length > 0) {\n const totalLen = reliableData.length + unreliableData.length;\n const result = new Uint8Array(totalLen);\n result.set(reliableData, 0);\n result.set(unreliableData, reliableData.length);\n return result;\n }\n\n if (unreliableData) {\n return unreliableData;\n }\n\n return new Uint8Array(0);\n }\n\n /**\n * Checks if reliable message buffer is empty and ready for new data\n */\n canSendReliable(): boolean {\n return this.reliableLength === 0;\n }\n\n /**\n * Writes a byte to the reliable message buffer\n */\n writeReliableByte(value: number): void {\n if (this.reliableLength + 1 > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeByte(value);\n this.reliableLength++;\n }\n\n /**\n * Writes a short to the reliable message buffer\n */\n writeReliableShort(value: number): void {\n if (this.reliableLength + 2 > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeShort(value);\n this.reliableLength += 2;\n }\n\n /**\n * Writes a long to the reliable message buffer\n */\n writeReliableLong(value: number): void {\n if (this.reliableLength + 4 > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeLong(value);\n this.reliableLength += 4;\n }\n\n /**\n * Writes a string to the reliable message buffer\n */\n writeReliableString(value: string): void {\n const len = value.length + 1; // +1 for null terminator\n if (this.reliableLength + len > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeString(value);\n this.reliableLength += len;\n }\n\n /**\n * Returns the current reliable data buffer\n */\n getReliableData(): Uint8Array {\n if (this.reliableLength === 0) {\n return new Uint8Array(0);\n }\n const buffer = this.reliableMessage.getBuffer();\n return buffer.subarray(0, this.reliableLength);\n }\n\n /**\n * Checks if we need to send a keepalive packet\n */\n needsKeepalive(currentTime: number): boolean {\n return (currentTime - this.lastSent) > 1000;\n }\n\n /**\n * Checks if the connection has timed out\n */\n isTimedOut(currentTime: number, timeoutMs: number = 30000): boolean {\n return (currentTime - this.lastReceived) > timeoutMs;\n }\n}\n","/**\n * Weapon identifiers shared across game and cgame.\n * Reference: rerelease/g_items.cpp, game/src/inventory/playerInventory.ts\n */\n\nexport enum WeaponId {\n Blaster = 'blaster',\n Shotgun = 'shotgun',\n SuperShotgun = 'supershotgun', // Matched to assets (w_supershotgun, weapon_supershotgun)\n Machinegun = 'machinegun',\n Chaingun = 'chaingun',\n HandGrenade = 'grenades', // Matched to assets (w_grenades, weapon_grenades)\n GrenadeLauncher = 'grenadelauncher', // Matched to assets (w_grenadelauncher)\n RocketLauncher = 'rocketlauncher', // Matched to assets (w_rocketlauncher)\n HyperBlaster = 'hyperblaster',\n Railgun = 'railgun',\n BFG10K = 'bfg10k',\n // New additions for demo playback and extended support\n Grapple = 'grapple',\n ChainFist = 'chainfist',\n EtfRifle = 'etf_rifle', // Confirm asset?\n ProxLauncher = 'prox_launcher', // Confirm asset?\n IonRipper = 'ionripper',\n PlasmaBeam = 'plasmabeam',\n Phalanx = 'phalanx',\n Disruptor = 'disruptor',\n Trap = 'trap',\n}\n","/**\n * Ammo type identifiers shared across game and cgame.\n * Reference: rerelease/g_items.cpp, game/src/inventory/ammo.ts\n */\n\nexport enum AmmoType {\n Bullets = 0,\n Shells,\n Rockets,\n Grenades,\n Cells,\n Slugs,\n // RAFAEL\n MagSlugs,\n Trap,\n // RAFAEL\n // ROGUE\n Flechettes,\n Tesla,\n Disruptor, // Was missing or named differently?\n Prox,\n // ROGUE\n // Custom or Extras?\n Nuke,\n Rounds,\n}\n\nexport const AMMO_TYPE_COUNT = Object.keys(AmmoType).length / 2;\n\n/**\n * Item classnames for ammo pickups.\n * Used for spawning and identifying ammo items.\n */\nexport enum AmmoItemId {\n Shells = 'ammo_shells',\n Bullets = 'ammo_bullets',\n Rockets = 'ammo_rockets',\n Grenades = 'ammo_grenades',\n Cells = 'ammo_cells',\n Slugs = 'ammo_slugs',\n MagSlugs = 'ammo_magslug',\n Flechettes = 'ammo_flechettes',\n Disruptor = 'ammo_disruptor',\n Tesla = 'ammo_tesla',\n Trap = 'ammo_trap',\n Prox = 'ammo_prox',\n}\n","import { WeaponId } from './weapons.js';\nimport { AmmoType } from './ammo.js';\n\n// Order matches Q2 original weapon wheel index order for bitmask generation\n// Used by both Game (for STAT_WEAPONS_OWNED calculation) and CGame (for weapon wheel UI)\nexport const WEAPON_WHEEL_ORDER: WeaponId[] = [\n WeaponId.Blaster,\n WeaponId.Shotgun,\n WeaponId.SuperShotgun,\n WeaponId.Machinegun,\n WeaponId.Chaingun,\n WeaponId.GrenadeLauncher,\n WeaponId.RocketLauncher,\n WeaponId.HandGrenade,\n WeaponId.HyperBlaster,\n WeaponId.Railgun,\n WeaponId.BFG10K\n];\n\n// Mapping of weapon to its ammo type\n// Used by CGame to lookup ammo counts for weapon wheel\nexport const WEAPON_AMMO_MAP: Record<WeaponId, AmmoType | null> = {\n [WeaponId.Blaster]: null,\n [WeaponId.Shotgun]: AmmoType.Shells,\n [WeaponId.SuperShotgun]: AmmoType.Shells,\n [WeaponId.Machinegun]: AmmoType.Bullets,\n [WeaponId.Chaingun]: AmmoType.Bullets,\n [WeaponId.HandGrenade]: AmmoType.Grenades,\n [WeaponId.GrenadeLauncher]: AmmoType.Grenades,\n [WeaponId.RocketLauncher]: AmmoType.Rockets,\n [WeaponId.HyperBlaster]: AmmoType.Cells,\n [WeaponId.Railgun]: AmmoType.Slugs,\n [WeaponId.BFG10K]: AmmoType.Cells,\n\n // Extensions / Rogue / Xatrix\n [WeaponId.Grapple]: null,\n [WeaponId.ChainFist]: null,\n [WeaponId.EtfRifle]: AmmoType.Flechettes,\n [WeaponId.ProxLauncher]: AmmoType.Prox,\n [WeaponId.IonRipper]: AmmoType.Cells,\n [WeaponId.PlasmaBeam]: AmmoType.Cells,\n [WeaponId.Phalanx]: AmmoType.MagSlugs,\n [WeaponId.Disruptor]: AmmoType.Disruptor,\n [WeaponId.Trap]: AmmoType.Trap,\n};\n","export const MAX_SOUND_CHANNELS = 32;\n\n// Sound channel identifiers and flags from the rerelease game headers.\nexport enum SoundChannel {\n Auto = 0,\n Weapon = 1,\n Voice = 2,\n Item = 3,\n Body = 4,\n Aux = 5,\n Footstep = 6,\n Aux3 = 7,\n\n NoPhsAdd = 1 << 3,\n Reliable = 1 << 4,\n ForcePos = 1 << 5,\n}\n\nexport const ATTN_LOOP_NONE = -1;\nexport const ATTN_NONE = 0;\nexport const ATTN_NORM = 1;\nexport const ATTN_IDLE = 2;\nexport const ATTN_STATIC = 3;\n\nexport const SOUND_FULLVOLUME = 80;\nexport const SOUND_LOOP_ATTENUATE = 0.003;\n\nexport function attenuationToDistanceMultiplier(attenuation: number): number {\n return attenuation * 0.001;\n}\n\nexport function calculateMaxAudibleDistance(attenuation: number): number {\n const distMult = attenuationToDistanceMultiplier(attenuation);\n return distMult <= 0 ? Number.POSITIVE_INFINITY : SOUND_FULLVOLUME + 1 / distMult;\n}\n","import { PlayerState } from './protocol/index.js';\nimport { AmmoItemId, AmmoType, WeaponId } from './items/index.js';\nimport { G_GetAmmoStat } from './protocol/stats.js';\nimport { WEAPON_AMMO_MAP } from './items/index.js';\nimport { ConfigStringIndex } from './protocol/configstrings.js';\n\n// Blaster uses no ammo in standard Q2.\n// We handle mapping `AmmoItemId` (string) to `AmmoType` (enum).\nexport const AMMO_ITEM_MAP: Record<AmmoItemId, AmmoType> = {\n [AmmoItemId.Shells]: AmmoType.Shells,\n [AmmoItemId.Bullets]: AmmoType.Bullets,\n [AmmoItemId.Rockets]: AmmoType.Rockets,\n [AmmoItemId.Grenades]: AmmoType.Grenades,\n [AmmoItemId.Cells]: AmmoType.Cells,\n [AmmoItemId.Slugs]: AmmoType.Slugs,\n [AmmoItemId.MagSlugs]: AmmoType.MagSlugs,\n [AmmoItemId.Flechettes]: AmmoType.Flechettes,\n [AmmoItemId.Disruptor]: AmmoType.Disruptor,\n [AmmoItemId.Tesla]: AmmoType.Tesla,\n [AmmoItemId.Trap]: AmmoType.Trap,\n [AmmoItemId.Prox]: AmmoType.Prox,\n};\n\n/**\n * Retrieves the ammo count for a given item (Weapon or Ammo).\n * @param playerState The current player state.\n * @param item The item identifier (WeaponId or AmmoItemId).\n * @returns The ammo count, or 0 if not found/applicable. Returns -1 for infinite ammo (e.g. Blaster).\n */\nexport function getAmmoCount(playerState: PlayerState, item: WeaponId | AmmoItemId): number {\n let ammoType: AmmoType | null | undefined;\n\n // Check if it's an Ammo Item ID\n if (Object.values(AmmoItemId).includes(item as AmmoItemId)) {\n ammoType = AMMO_ITEM_MAP[item as AmmoItemId];\n }\n // Check if it's a Weapon ID\n else if (Object.values(WeaponId).includes(item as WeaponId)) {\n ammoType = WEAPON_AMMO_MAP[item as WeaponId];\n\n // Existing map has null for Blaster, Grapple, etc.\n if (ammoType === null) {\n return -1;\n }\n }\n\n if (ammoType === undefined || ammoType === null) {\n return 0;\n }\n\n return G_GetAmmoStat(playerState.stats, ammoType);\n}\n\n/**\n * Resolves the icon path for a given stat index (e.g. STAT_SELECTED_ICON).\n * @param statIndex The index in the stats array to read (e.g. PlayerStat.STAT_SELECTED_ICON).\n * @param playerState The player state containing the stats.\n * @param configStrings The array of configuration strings (from client state).\n * @returns The path to the icon image, or undefined if invalid.\n */\nexport function getIconPath(\n statIndex: number,\n playerState: PlayerState,\n configStrings: string[]\n): string | undefined {\n const iconIndex = playerState.stats[statIndex];\n\n // 0 usually means no icon or null\n if (iconIndex === undefined || iconIndex <= 0) {\n return undefined;\n }\n\n // The value in the stat is the index into the Config Strings relative to ConfigStringIndex.Images.\n const configIndex = ConfigStringIndex.Images + iconIndex;\n\n if (configIndex < 0 || configIndex >= configStrings.length) {\n return undefined;\n }\n\n return configStrings[configIndex];\n}\n","import type { PmoveTraceFn, PmoveTraceResult } from './pmove/types.js';\nimport type { Vec3 } from './math/vec3.js';\nimport { CONTENTS_LADDER } from './bsp/contents.js';\n\nexport const intersects = (end: Vec3, maxs: Vec3, mins: Vec3, boxMins: Vec3, boxMaxs: Vec3): boolean => {\n return (\n end.x + maxs.x > boxMins.x &&\n end.x + mins.x < boxMaxs.x &&\n end.y + maxs.y > boxMins.y &&\n end.y + mins.y < boxMaxs.y &&\n end.z + maxs.z > boxMins.z &&\n end.z + mins.z < boxMaxs.z\n );\n};\n\nexport const stairTrace: PmoveTraceFn = (start: Vec3, end: Vec3, mins?: Vec3, maxs?: Vec3): PmoveTraceResult => {\n // Default bbox if not provided\n const useMins = mins ?? { x: -16, y: -16, z: -24 };\n const useMaxs = maxs ?? { x: 16, y: 16, z: 32 };\n\n // Step: x from 0 forward, z from 0 to 8\n const STEP_HEIGHT = 8;\n const STEP_X_START = 0;\n\n const isHorizontal = Math.abs(end.z - start.z) < 1;\n const isMovingDown = end.z < start.z;\n\n // Check if trying to go below the floor\n const endMinZ = end.z + useMins.z;\n const startMinZ = start.z + useMins.z;\n const endMaxX = end.x + useMaxs.x;\n\n // If moving horizontally, check if we'd hit the vertical face of the step\n // The step only blocks if the player's origin is below the step height\n if (isHorizontal && end.z < STEP_HEIGHT && endMaxX > STEP_X_START) {\n // Check if we're crossing into the step area\n const startMaxX = start.x + useMaxs.x;\n if (startMaxX <= STEP_X_START) {\n // We're moving from before the step to past it, block\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: -1, y: 0, z: 0 },\n contents: 1,\n };\n }\n }\n\n // If moving down and over the step area, land on the step surface\n if (isMovingDown && end.x >= STEP_X_START) {\n // The step surface is at z=STEP_HEIGHT in world space\n // The player's bbox bottom reaches this plane when origin.z + mins.z = STEP_HEIGHT\n // So the player's origin should be at z = STEP_HEIGHT - mins.z\n const landZ = STEP_HEIGHT - useMins.z;\n\n // Check if we'd pass through the step surface\n // We cross the plane if start is above it and end would be below it\n if (startMinZ > STEP_HEIGHT && endMinZ < STEP_HEIGHT) {\n // Calculate the fraction along the ray where we intersect the plane\n // The bbox bottom is at: start.z + useMins.z + t * (end.z - start.z + 0) = STEP_HEIGHT\n // Solving for t: t = (STEP_HEIGHT - (start.z + useMins.z)) / ((end.z + useMins.z) - (start.z + useMins.z))\n const fraction = (STEP_HEIGHT - startMinZ) / (endMinZ - startMinZ);\n\n // Clamp to valid range [0, 1]\n const clampedFraction = Math.max(0, Math.min(1, fraction));\n\n // Calculate the endpos along the ray at this fraction\n const finalX = start.x + clampedFraction * (end.x - start.x);\n const finalY = start.y + clampedFraction * (end.y - start.y);\n const finalZ = start.z + clampedFraction * (end.z - start.z);\n\n return {\n allsolid: false,\n startsolid: false,\n fraction: clampedFraction,\n endpos: { x: finalX, y: finalY, z: finalZ },\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n }\n\n // If moving down and would go below floor level, block at floor\n if (isMovingDown && endMinZ < 0) {\n // Floor is at z=0, so player origin should be at z = -mins.z when landing\n const landZ = -useMins.z;\n\n // Only apply if we're crossing the floor plane\n if (startMinZ >= 0) {\n // Calculate fraction where bbox bottom hits z=0\n const fraction = (0 - startMinZ) / (endMinZ - startMinZ);\n const clampedFraction = Math.max(0, Math.min(1, fraction));\n\n const finalX = start.x + clampedFraction * (end.x - start.x);\n const finalY = start.y + clampedFraction * (end.y - start.y);\n const finalZ = start.z + clampedFraction * (end.z - start.z);\n\n return {\n allsolid: false,\n startsolid: false,\n fraction: clampedFraction,\n endpos: { x: finalX, y: finalY, z: finalZ },\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n\n // Already below floor, block immediately\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n\n // Free movement\n return {\n allsolid: false,\n startsolid: false,\n fraction: 1.0,\n endpos: end,\n contents: 0,\n };\n};\n\nexport const ladderTrace: PmoveTraceFn = (start: Vec3, end: Vec3, mins?: Vec3, maxs?: Vec3): PmoveTraceResult => {\n // Default bbox if not provided\n const useMins = mins ?? { x: -16, y: -16, z: -24 };\n const useMaxs = maxs ?? { x: 16, y: 16, z: 32 };\n\n // Define the ladder volume (x=0 to x=8, y=-16 to y=16, z=0 to z=100)\n const LADDER_X_MIN = 0;\n const LADDER_X_MAX = 8;\n const LADDER_Y_MIN = -16;\n const LADDER_Y_MAX = 16;\n const LADDER_Z_MIN = 0;\n const LADDER_Z_MAX = 100;\n\n // Check if end position is within the ladder volume\n const endInLadder =\n end.x + useMins.x < LADDER_X_MAX &&\n end.x + useMaxs.x > LADDER_X_MIN &&\n end.y + useMins.y < LADDER_Y_MAX &&\n end.y + useMaxs.y > LADDER_Y_MIN &&\n end.z + useMins.z < LADDER_Z_MAX &&\n end.z + useMaxs.z > LADDER_Z_MIN;\n\n // If moving into the ladder from outside (moving forward into it)\n const movingIntoLadder = start.x < LADDER_X_MIN && end.x >= LADDER_X_MIN;\n\n // If moving horizontally into the ladder front face, block with ladder surface\n if (movingIntoLadder && Math.abs(end.z - start.z) < 0.1) {\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: -1, y: 0, z: 0 },\n contents: CONTENTS_LADDER,\n };\n }\n\n // If we're in the ladder volume, return success but with CONTENTS_LADDER\n // This allows the player to detect they're on a ladder without blocking movement\n if (endInLadder) {\n return {\n allsolid: false,\n startsolid: false,\n fraction: 1.0,\n endpos: end,\n contents: CONTENTS_LADDER,\n };\n }\n\n // Floor at z=0\n if (end.z + useMins.z <= 0) {\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n\n // No collision - free movement\n return {\n allsolid: false,\n startsolid: false,\n fraction: 1.0,\n endpos: end,\n contents: 0,\n };\n};\n","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","\nexport type CommandCallback = (args: string[]) => void;\nexport type AutocompleteProvider = () => string[];\n\nexport class Command {\n readonly name: string;\n readonly description?: string;\n readonly callback: CommandCallback;\n\n constructor(name: string, callback: CommandCallback, description?: string) {\n this.name = name;\n this.callback = callback;\n this.description = description;\n }\n\n execute(args: string[]): void {\n this.callback(args);\n }\n}\n\nexport class CommandRegistry {\n private readonly commands = new Map<string, Command>();\n private readonly history: string[] = [];\n private readonly historyLimit = 64;\n private readonly autocompleteProviders: AutocompleteProvider[] = [];\n public onConsoleOutput?: (message: string) => void;\n\n register(name: string, callback: CommandCallback, description?: string): Command {\n const command = new Command(name, callback, description);\n this.commands.set(name, command);\n return command;\n }\n\n registerCommand(name: string, callback: CommandCallback): void {\n this.register(name, callback);\n }\n\n registerAutocompleteProvider(provider: AutocompleteProvider): void {\n this.autocompleteProviders.push(provider);\n }\n\n get(name: string): Command | undefined {\n return this.commands.get(name);\n }\n\n execute(commandString: string): boolean {\n const trimmed = commandString.trim();\n if (trimmed.length === 0) {\n return false;\n }\n\n // Add to history if not duplicate of last\n if (this.history.length === 0 || this.history[this.history.length - 1] !== trimmed) {\n this.history.push(trimmed);\n if (this.history.length > this.historyLimit) {\n this.history.shift();\n }\n }\n\n const parts = this.tokenize(commandString);\n if (parts.length === 0) {\n return false;\n }\n\n const name = parts[0];\n const args = parts.slice(1);\n\n const command = this.get(name);\n if (command) {\n command.execute(args);\n return true;\n }\n\n this.onConsoleOutput?.(`Unknown command \"${name}\"`);\n return false;\n }\n\n executeCommand(cmd: string): void {\n this.execute(cmd);\n }\n\n getHistory(): string[] {\n return [...this.history];\n }\n\n getSuggestions(prefix: string): string[] {\n const suggestions = new Set<string>();\n\n // Command suggestions\n for (const name of this.commands.keys()) {\n if (name.startsWith(prefix)) {\n suggestions.add(name);\n }\n }\n\n // Provider suggestions (e.g. cvars)\n for (const provider of this.autocompleteProviders) {\n const providerSuggestions = provider();\n for (const suggestion of providerSuggestions) {\n if (suggestion.startsWith(prefix)) {\n suggestions.add(suggestion);\n }\n }\n }\n\n return Array.from(suggestions).sort();\n }\n\n private tokenize(text: string): string[] {\n const args: string[] = [];\n let currentArg = '';\n let inQuote = false;\n\n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === '\"') {\n inQuote = !inQuote;\n } else if (char === ' ' && !inQuote) {\n if (currentArg.length > 0) {\n args.push(currentArg);\n currentArg = '';\n }\n } else {\n currentArg += char;\n }\n }\n if (currentArg.length > 0) {\n args.push(currentArg);\n }\n\n return args;\n }\n\n list(): Command[] {\n return [...this.commands.values()].sort((a, b) => a.name.localeCompare(b.name));\n }\n}\n","export interface Vec3 {\n readonly x: number;\n readonly y: number;\n readonly z: number;\n readonly [index: number]: number;\n}\n\nexport const ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\n\n// Matches STOP_EPSILON from rerelease q_vec3.h\nexport const STOP_EPSILON = 0.1;\n\nconst DEG_TO_RAD = Math.PI / 180;\n\nexport interface Bounds3 {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n}\n\nexport type Mat3Row = readonly [number, number, number];\nexport type Mat3 = readonly [Mat3Row, Mat3Row, Mat3Row];\n\nexport function copyVec3(a: Vec3): Vec3 {\n return { x: a.x, y: a.y, z: a.z };\n}\n\nexport function addVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };\n}\n\nexport function subtractVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };\n}\n\nexport function multiplyVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x * b.x, y: a.y * b.y, z: a.z * b.z };\n}\n\nexport function scaleVec3(a: Vec3, scalar: number): Vec3 {\n return { x: a.x * scalar, y: a.y * scalar, z: a.z * scalar };\n}\n\nexport function negateVec3(a: Vec3): Vec3 {\n return scaleVec3(a, -1);\n}\n\nexport function dotVec3(a: Vec3, b: Vec3): number {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\nexport function crossVec3(a: Vec3, b: Vec3): Vec3 {\n return {\n x: a.y * b.z - a.z * b.y,\n y: a.z * b.x - a.x * b.z,\n z: a.x * b.y - a.y * b.x,\n };\n}\n\nexport function lengthSquaredVec3(a: Vec3): number {\n return dotVec3(a, a);\n}\n\nexport function lengthVec3(a: Vec3): number {\n return Math.sqrt(lengthSquaredVec3(a));\n}\n\nexport function distance(a: Vec3, b: Vec3): number {\n return lengthVec3(subtractVec3(a, b));\n}\n\nexport function vec3Equals(a: Vec3, b: Vec3): boolean {\n return a.x === b.x && a.y === b.y && a.z === b.z;\n}\n\n/**\n * Returns the normalized vector. If the vector is zero-length, the\n * input is returned to mirror the rerelease q_vec3 semantics.\n */\nexport function normalizeVec3(a: Vec3): Vec3 {\n const len = lengthVec3(a);\n return len === 0 ? a : scaleVec3(a, 1 / len);\n}\n\n/**\n * Projects a point onto a plane defined by the given normal.\n * Based on ProjectPointOnPlane in the rerelease q_vec3 helpers.\n */\nexport function projectPointOnPlane(point: Vec3, normal: Vec3): Vec3 {\n const invDenom = 1 / dotVec3(normal, normal);\n const d = dotVec3(normal, point) * invDenom;\n return subtractVec3(point, scaleVec3(normal, invDenom * d));\n}\n\n/**\n * Computes a perpendicular vector to the provided direction using the\n * smallest axial component heuristic used by the rerelease.\n * Assumes the input is normalized.\n */\nexport function perpendicularVec3(src: Vec3): Vec3 {\n let pos = 0;\n let minElement = Math.abs(src.x);\n\n if (Math.abs(src.y) < minElement) {\n pos = 1;\n minElement = Math.abs(src.y);\n }\n\n if (Math.abs(src.z) < minElement) {\n pos = 2;\n }\n\n const axis = pos === 0 ? { x: 1, y: 0, z: 0 } : pos === 1 ? { x: 0, y: 1, z: 0 } : { x: 0, y: 0, z: 1 };\n return normalizeVec3(projectPointOnPlane(axis, src));\n}\n\nexport function closestPointToBox(point: Vec3, mins: Vec3, maxs: Vec3): Vec3 {\n return {\n x: point.x < mins.x ? mins.x : point.x > maxs.x ? maxs.x : point.x,\n y: point.y < mins.y ? mins.y : point.y > maxs.y ? maxs.y : point.y,\n z: point.z < mins.z ? mins.z : point.z > maxs.z ? maxs.z : point.z,\n };\n}\n\nexport function distanceBetweenBoxesSquared(aMins: Vec3, aMaxs: Vec3, bMins: Vec3, bMaxs: Vec3): number {\n let lengthSq = 0;\n\n if (aMaxs.x < bMins.x) {\n const d = aMaxs.x - bMins.x;\n lengthSq += d * d;\n } else if (aMins.x > bMaxs.x) {\n const d = aMins.x - bMaxs.x;\n lengthSq += d * d;\n }\n\n if (aMaxs.y < bMins.y) {\n const d = aMaxs.y - bMins.y;\n lengthSq += d * d;\n } else if (aMins.y > bMaxs.y) {\n const d = aMins.y - bMaxs.y;\n lengthSq += d * d;\n }\n\n if (aMaxs.z < bMins.z) {\n const d = aMaxs.z - bMins.z;\n lengthSq += d * d;\n } else if (aMins.z > bMaxs.z) {\n const d = aMins.z - bMaxs.z;\n lengthSq += d * d;\n }\n\n return lengthSq;\n}\n\nexport function createEmptyBounds3(): Bounds3 {\n return {\n mins: { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY },\n maxs: { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY },\n };\n}\n\nexport function addPointToBounds(point: Vec3, bounds: Bounds3): Bounds3 {\n return {\n mins: {\n x: Math.min(bounds.mins.x, point.x),\n y: Math.min(bounds.mins.y, point.y),\n z: Math.min(bounds.mins.z, point.z),\n },\n maxs: {\n x: Math.max(bounds.maxs.x, point.x),\n y: Math.max(bounds.maxs.y, point.y),\n z: Math.max(bounds.maxs.z, point.z),\n },\n };\n}\n\nexport function boxesIntersect(a: Bounds3, b: Bounds3): boolean {\n return (\n a.mins.x <= b.maxs.x &&\n a.maxs.x >= b.mins.x &&\n a.mins.y <= b.maxs.y &&\n a.maxs.y >= b.mins.y &&\n a.mins.z <= b.maxs.z &&\n a.maxs.z >= b.mins.z\n );\n}\n\n/**\n * Mirrors PM_ClipVelocity from `rerelease/p_move.cpp`: slide the incoming velocity off\n * a plane normal, applying an overbounce scale and zeroing tiny components so callers can\n * detect blocked axes using STOP_EPSILON.\n */\nexport function clipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n const backoff = dotVec3(inVel, normal) * overbounce;\n\n let outX = inVel.x - normal.x * backoff;\n let outY = inVel.y - normal.y * backoff;\n let outZ = inVel.z - normal.z * backoff;\n\n if (outX > -STOP_EPSILON && outX < STOP_EPSILON) {\n outX = 0;\n }\n\n if (outY > -STOP_EPSILON && outY < STOP_EPSILON) {\n outY = 0;\n }\n\n if (outZ > -STOP_EPSILON && outZ < STOP_EPSILON) {\n outZ = 0;\n }\n\n return { x: outX, y: outY, z: outZ };\n}\n\n/**\n * Slide a velocity across one or more clip planes using the same plane set resolution logic\n * seen in the inner loop of `PM_StepSlideMove_Generic` (rerelease `p_move.cpp`). When a single\n * plane is provided this devolves to PM_ClipVelocity; with two planes it projects onto the\n * crease defined by their cross product; with more planes it zeroes the velocity to avoid\n * oscillations.\n */\nexport function clipVelocityAgainstPlanes(\n velocity: Vec3,\n planes: readonly Vec3[],\n overbounce: number,\n primalVelocity?: Vec3,\n): Vec3 {\n if (planes.length === 0) {\n return velocity;\n }\n\n let working = velocity;\n\n for (let i = 0; i < planes.length; i++) {\n working = clipVelocityVec3(working, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) {\n continue;\n }\n\n if (dotVec3(working, planes[j]) < 0) {\n break;\n }\n }\n\n if (j === planes.length) {\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return working;\n }\n }\n\n if (planes.length === 2) {\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n const creaseVelocity = scaleVec3(dir, d);\n\n if (primalVelocity && dotVec3(creaseVelocity, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return creaseVelocity;\n }\n\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return ZERO_VEC3;\n}\n\n/**\n * Alias retained for ergonomics; mirrors PM_ClipVelocity semantics.\n */\nexport function slideClipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n return clipVelocityVec3(inVel, normal, overbounce);\n}\n\n/**\n * Project an offset from a point in forward/right(/up) space into world space.\n * Mirrors G_ProjectSource and G_ProjectSource2 in rerelease q_vec3.\n */\nexport function projectSourceVec3(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y,\n y: point.y + forward.y * distance.x + right.y * distance.y,\n z: point.z + forward.z * distance.x + right.z * distance.y + distance.z,\n };\n}\n\nexport function projectSourceVec3WithUp(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3, up: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y + up.x * distance.z,\n y: point.y + forward.y * distance.x + right.y * distance.y + up.y * distance.z,\n z: point.z + forward.z * distance.x + right.z * distance.y + up.z * distance.z,\n };\n}\n\n/**\n * Spherical linear interpolation between two vectors, mirroring q_vec3::slerp.\n * This is intended for direction vectors; callers should pre-normalize if needed.\n */\nexport function slerpVec3(from: Vec3, to: Vec3, t: number): Vec3 {\n const dot = dotVec3(from, to);\n let aFactor: number;\n let bFactor: number;\n\n if (Math.abs(dot) > 0.9995) {\n aFactor = 1 - t;\n bFactor = t;\n } else {\n const ang = Math.acos(dot);\n const sinOmega = Math.sin(ang);\n const sinAOmega = Math.sin((1 - t) * ang);\n const sinBOmega = Math.sin(t * ang);\n aFactor = sinAOmega / sinOmega;\n bFactor = sinBOmega / sinOmega;\n }\n\n return {\n x: from.x * aFactor + to.x * bFactor,\n y: from.y * aFactor + to.y * bFactor,\n z: from.z * aFactor + to.z * bFactor,\n };\n}\n\nexport function concatRotationMatrices(a: Mat3, b: Mat3): Mat3 {\n const row = (rowIndex: number): Mat3Row => [\n a[rowIndex][0] * b[0][0] + a[rowIndex][1] * b[1][0] + a[rowIndex][2] * b[2][0],\n a[rowIndex][0] * b[0][1] + a[rowIndex][1] * b[1][1] + a[rowIndex][2] * b[2][1],\n a[rowIndex][0] * b[0][2] + a[rowIndex][1] * b[1][2] + a[rowIndex][2] * b[2][2],\n ];\n\n const result = [row(0), row(1), row(2)] as Mat3;\n return result;\n}\n\nexport function rotatePointAroundVector(dir: Vec3, point: Vec3, degrees: number): Vec3 {\n const axisLength = lengthVec3(dir);\n if (axisLength === 0) {\n return point;\n }\n\n const vf = normalizeVec3(dir);\n const vr = perpendicularVec3(vf);\n const vup = crossVec3(vr, vf);\n\n const m: Mat3 = [\n [vr.x, vup.x, vf.x],\n [vr.y, vup.y, vf.y],\n [vr.z, vup.z, vf.z],\n ];\n\n const im: Mat3 = [\n [m[0][0], m[1][0], m[2][0]],\n [m[0][1], m[1][1], m[2][1]],\n [m[0][2], m[1][2], m[2][2]],\n ];\n\n const radians = degrees * DEG_TO_RAD;\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n const zrot: Mat3 = [\n [cos, sin, 0],\n [-sin, cos, 0],\n [0, 0, 1],\n ];\n\n const rot = concatRotationMatrices(concatRotationMatrices(m, zrot), im);\n\n return {\n x: rot[0][0] * point.x + rot[0][1] * point.y + rot[0][2] * point.z,\n y: rot[1][0] * point.x + rot[1][1] * point.y + rot[1][2] * point.z,\n z: rot[2][0] * point.x + rot[2][1] * point.y + rot[2][2] * point.z,\n };\n}\n","import { Vec3 } from './vec3.js';\n\nexport const PITCH = 0;\nexport const YAW = 1;\nexport const ROLL = 2;\n\nconst DEG2RAD_FACTOR = Math.PI / 180;\nconst RAD2DEG_FACTOR = 180 / Math.PI;\n\n// Export constants for direct use in matrix operations\nexport const DEG2RAD = DEG2RAD_FACTOR;\nexport const RAD2DEG = RAD2DEG_FACTOR;\n\nfunction axisComponent(vec: Vec3, axis: number): number {\n switch (axis) {\n case PITCH:\n return vec.x;\n case YAW:\n return vec.y;\n case ROLL:\n default:\n return vec.z;\n }\n}\n\nexport interface AngleVectorsResult {\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly up: Vec3;\n}\n\nexport function degToRad(degrees: number): number {\n return degrees * DEG2RAD_FACTOR;\n}\n\nexport function radToDeg(radians: number): number {\n return radians * RAD2DEG_FACTOR;\n}\n\nexport function lerpAngle(from: number, to: number, frac: number): number {\n let target = to;\n\n if (target - from > 180) {\n target -= 360;\n } else if (target - from < -180) {\n target += 360;\n }\n\n return from + frac * (target - from);\n}\n\nexport function angleMod(angle: number): number {\n const value = angle % 360;\n return value < 0 ? 360 + value : value;\n}\n\nexport function angleVectors(angles: Vec3): AngleVectorsResult {\n const yaw = degToRad(axisComponent(angles, YAW));\n const pitch = degToRad(axisComponent(angles, PITCH));\n const roll = degToRad(axisComponent(angles, ROLL));\n\n const sy = Math.sin(yaw);\n const cy = Math.cos(yaw);\n const sp = Math.sin(pitch);\n const cp = Math.cos(pitch);\n const sr = Math.sin(roll);\n const cr = Math.cos(roll);\n\n const forward: Vec3 = {\n x: cp * cy,\n y: cp * sy,\n z: -sp,\n };\n\n const right: Vec3 = {\n x: -sr * sp * cy - cr * -sy,\n y: -sr * sp * sy - cr * cy,\n z: -sr * cp,\n };\n\n const up: Vec3 = {\n x: cr * sp * cy - sr * -sy,\n y: cr * sp * sy - sr * cy,\n z: cr * cp,\n };\n\n return { forward, right, up };\n}\n\nexport function vectorToYaw(vec: Vec3): number {\n const pitch = axisComponent(vec, PITCH);\n const yawAxis = axisComponent(vec, YAW);\n\n if (pitch === 0) {\n if (yawAxis === 0) {\n return 0;\n }\n\n return yawAxis > 0 ? 90 : 270;\n }\n\n const yaw = radToDeg(Math.atan2(yawAxis, pitch));\n return yaw < 0 ? yaw + 360 : yaw;\n}\n\nexport function vectorToAngles(vec: Vec3): Vec3 {\n const x = vec.x;\n const y = vec.y;\n const z = vec.z;\n\n if (y === 0 && x === 0) {\n return { x: z > 0 ? -90 : -270, y: 0, z: 0 };\n }\n\n let yaw: number;\n if (x) {\n yaw = radToDeg(Math.atan2(y, x));\n } else if (y > 0) {\n yaw = 90;\n } else {\n yaw = 270;\n }\n\n if (yaw < 0) {\n yaw += 360;\n }\n\n const forward = Math.sqrt(x * x + y * y);\n let pitch = radToDeg(Math.atan2(z, forward));\n if (pitch < 0) {\n pitch += 360;\n }\n\n return { x: -pitch, y: yaw, z: 0 };\n}\n","// Extracted from full/client/anorms.h\nexport const ANORMS: [number, number, number][] = [\n [-0.525731, 0.000000, 0.850651],\n [-0.442863, 0.238856, 0.864188],\n [-0.295242, 0.000000, 0.955423],\n [-0.309017, 0.500000, 0.809017],\n [-0.162460, 0.262866, 0.951056],\n [0.000000, 0.000000, 1.000000],\n [0.000000, 0.850651, 0.525731],\n [-0.147621, 0.716567, 0.681718],\n [0.147621, 0.716567, 0.681718],\n [0.000000, 0.525731, 0.850651],\n [0.309017, 0.500000, 0.809017],\n [0.525731, 0.000000, 0.850651],\n [0.295242, 0.000000, 0.955423],\n [0.442863, 0.238856, 0.864188],\n [0.162460, 0.262866, 0.951056],\n [-0.681718, 0.147621, 0.716567],\n [-0.809017, 0.309017, 0.500000],\n [-0.587785, 0.425325, 0.688191],\n [-0.850651, 0.525731, 0.000000],\n [-0.864188, 0.442863, 0.238856],\n [-0.716567, 0.681718, 0.147621],\n [-0.688191, 0.587785, 0.425325],\n [-0.500000, 0.809017, 0.309017],\n [-0.238856, 0.864188, 0.442863],\n [-0.425325, 0.688191, 0.587785],\n [-0.716567, 0.681718, -0.147621],\n [-0.500000, 0.809017, -0.309017],\n [-0.525731, 0.850651, 0.000000],\n [0.000000, 0.850651, -0.525731],\n [-0.238856, 0.864188, -0.442863],\n [0.000000, 0.955423, -0.295242],\n [-0.262866, 0.951056, -0.162460],\n [0.000000, 1.000000, 0.000000],\n [0.000000, 0.955423, 0.295242],\n [-0.262866, 0.951056, 0.162460],\n [0.238856, 0.864188, 0.442863],\n [0.262866, 0.951056, 0.162460],\n [0.500000, 0.809017, 0.309017],\n [0.238856, 0.864188, -0.442863],\n [0.262866, 0.951056, -0.162460],\n [0.500000, 0.809017, -0.309017],\n [0.850651, 0.525731, 0.000000],\n [0.716567, 0.681718, 0.147621],\n [0.716567, 0.681718, -0.147621],\n [0.525731, 0.850651, 0.000000],\n [0.425325, 0.688191, 0.587785],\n [0.864188, 0.442863, 0.238856],\n [0.688191, 0.587785, 0.425325],\n [0.809017, 0.309017, 0.500000],\n [0.681718, 0.147621, 0.716567],\n [0.587785, 0.425325, 0.688191],\n [0.955423, 0.295242, 0.000000],\n [1.000000, 0.000000, 0.000000],\n [0.951056, 0.162460, 0.262866],\n [0.850651, -0.525731, 0.000000],\n [0.955423, -0.295242, 0.000000],\n [0.864188, -0.442863, 0.238856],\n [0.951056, -0.162460, 0.262866],\n [0.809017, -0.309017, 0.500000],\n [0.681718, -0.147621, 0.716567],\n [0.850651, 0.000000, 0.525731],\n [0.864188, 0.442863, -0.238856],\n [0.809017, 0.309017, -0.500000],\n [0.951056, 0.162460, -0.262866],\n [0.525731, 0.000000, -0.850651],\n [0.681718, 0.147621, -0.716567],\n [0.681718, -0.147621, -0.716567],\n [0.850651, 0.000000, -0.525731],\n [0.809017, -0.309017, -0.500000],\n [0.864188, -0.442863, -0.238856],\n [0.951056, -0.162460, -0.262866],\n [0.147621, 0.716567, -0.681718],\n [0.309017, 0.500000, -0.809017],\n [0.425325, 0.688191, -0.587785],\n [0.442863, 0.238856, -0.864188],\n [0.587785, 0.425325, -0.688191],\n [0.688191, 0.587785, -0.425325],\n [-0.147621, 0.716567, -0.681718],\n [-0.309017, 0.500000, -0.809017],\n [0.000000, 0.525731, -0.850651],\n [-0.525731, 0.000000, -0.850651],\n [-0.442863, 0.238856, -0.864188],\n [-0.295242, 0.000000, -0.955423],\n [-0.162460, 0.262866, -0.951056],\n [0.000000, 0.000000, -1.000000],\n [0.295242, 0.000000, -0.955423],\n [0.162460, 0.262866, -0.951056],\n [-0.442863, -0.238856, -0.864188],\n [-0.309017, -0.500000, -0.809017],\n [-0.162460, -0.262866, -0.951056],\n [0.000000, -0.850651, -0.525731],\n [-0.147621, -0.716567, -0.681718],\n [0.147621, -0.716567, -0.681718],\n [0.000000, -0.525731, -0.850651],\n [0.309017, -0.500000, -0.809017],\n [0.442863, -0.238856, -0.864188],\n [0.162460, -0.262866, -0.951056],\n [0.238856, -0.864188, -0.442863],\n [0.500000, -0.809017, -0.309017],\n [0.425325, -0.688191, -0.587785],\n [0.716567, -0.681718, -0.147621],\n [0.688191, -0.587785, -0.425325],\n [0.587785, -0.425325, -0.688191],\n [0.000000, -0.955423, -0.295242],\n [0.000000, -1.000000, 0.000000],\n [0.262866, -0.951056, -0.162460],\n [0.000000, -0.850651, 0.525731],\n [0.000000, -0.955423, 0.295242],\n [0.238856, -0.864188, 0.442863],\n [0.262866, -0.951056, 0.162460],\n [0.500000, -0.809017, 0.309017],\n [0.716567, -0.681718, 0.147621],\n [0.525731, -0.850651, 0.000000],\n [-0.238856, -0.864188, -0.442863],\n [-0.500000, -0.809017, -0.309017],\n [-0.262866, -0.951056, -0.162460],\n [-0.850651, -0.525731, 0.000000],\n [-0.716567, -0.681718, -0.147621],\n [-0.716567, -0.681718, 0.147621],\n [-0.525731, -0.850651, 0.000000],\n [-0.500000, -0.809017, 0.309017],\n [-0.238856, -0.864188, 0.442863],\n [-0.262866, -0.951056, 0.162460],\n [-0.864188, -0.442863, 0.238856],\n [-0.809017, -0.309017, 0.500000],\n [-0.688191, -0.587785, 0.425325],\n [-0.681718, -0.147621, 0.716567],\n [-0.442863, -0.238856, 0.864188],\n [-0.587785, -0.425325, 0.688191],\n [-0.309017, -0.500000, 0.809017],\n [-0.147621, -0.716567, 0.681718],\n [-0.425325, -0.688191, 0.587785],\n [-0.162460, -0.262866, 0.951056],\n [0.442863, -0.238856, 0.864188],\n [0.162460, -0.262866, 0.951056],\n [0.309017, -0.500000, 0.809017],\n [0.147621, -0.716567, 0.681718],\n [0.000000, -0.525731, 0.850651],\n [0.425325, -0.688191, 0.587785],\n [0.587785, -0.425325, 0.688191],\n [0.688191, -0.587785, 0.425325],\n [-0.955423, 0.295242, 0.000000],\n [-0.951056, 0.162460, 0.262866],\n [-1.000000, 0.000000, 0.000000],\n [-0.850651, 0.000000, 0.525731],\n [-0.955423, -0.295242, 0.000000],\n [-0.951056, -0.162460, 0.262866],\n [-0.864188, 0.442863, -0.238856],\n [-0.951056, 0.162460, -0.262866],\n [-0.809017, 0.309017, -0.500000],\n [-0.864188, -0.442863, -0.238856],\n [-0.951056, -0.162460, -0.262866],\n [-0.809017, -0.309017, -0.500000],\n [-0.681718, 0.147621, -0.716567],\n [-0.681718, -0.147621, -0.716567],\n [-0.850651, 0.000000, -0.525731],\n [-0.688191, 0.587785, -0.425325],\n [-0.587785, 0.425325, -0.688191],\n [-0.425325, 0.688191, -0.587785],\n [-0.425325, -0.688191, -0.587785],\n [-0.587785, -0.425325, -0.688191],\n [-0.688191, -0.587785, -0.425325]\n];\n","export type Color4 = [number, number, number, number];\n\n/**\n * TypeScript port of G_AddBlend from rerelease q_std.h.\n *\n * Given an incoming RGBA color and an existing blend color, computes the new\n * blended color where alpha is accumulated and RGB is mixed proportionally\n * to the previous vs. new alpha contribution.\n *\n * This function is pure and does not mutate its inputs.\n */\nexport function addBlendColor(\n r: number,\n g: number,\n b: number,\n a: number,\n current: Color4,\n): Color4 {\n if (a <= 0) {\n return current;\n }\n\n const oldR = current[0];\n const oldG = current[1];\n const oldB = current[2];\n const oldA = current[3];\n\n const a2 = oldA + (1 - oldA) * a;\n\n if (a2 <= 0) {\n return [0, 0, 0, 0];\n }\n\n const a3 = oldA / a2;\n\n const newR = oldR * a3 + r * (1 - a3);\n const newG = oldG * a3 + g * (1 - a3);\n const newB = oldB * a3 + b * (1 - a3);\n\n return [newR, newG, newB, a2];\n}\n\n","const STATE_SIZE = 624;\nconst MIDDLE_WORD = 397;\nconst MATRIX_A = 0x9908b0df;\nconst UPPER_MASK = 0x80000000;\nconst LOWER_MASK = 0x7fffffff;\nconst TWO_POW_32 = 0x100000000;\n\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\n\n/**\n * Minimal MT19937 implementation mirroring the rerelease's std::mt19937 usage in g_local.h.\n * The generator outputs deterministic unsigned 32-bit integers which drive the\n * higher-level helpers such as frandom/crandom/irandom.\n */\nexport class MersenneTwister19937 {\n private state = new Uint32Array(STATE_SIZE);\n private index = STATE_SIZE;\n\n constructor(seed = 5489) {\n this.seed(seed);\n }\n\n seed(seed: number): void {\n this.state[0] = seed >>> 0;\n for (let i = 1; i < STATE_SIZE; i++) {\n const prev = this.state[i - 1] ^ (this.state[i - 1] >>> 30);\n const next = Math.imul(prev >>> 0, 1812433253) + i;\n this.state[i] = next >>> 0;\n }\n this.index = STATE_SIZE;\n }\n\n nextUint32(): number {\n if (this.index >= STATE_SIZE) {\n this.twist();\n }\n\n let y = this.state[this.index++];\n y ^= y >>> 11;\n y ^= (y << 7) & 0x9d2c5680;\n y ^= (y << 15) & 0xefc60000;\n y ^= y >>> 18;\n return y >>> 0;\n }\n\n private twist(): void {\n for (let i = 0; i < STATE_SIZE; i++) {\n const y = (this.state[i] & UPPER_MASK) | (this.state[(i + 1) % STATE_SIZE] & LOWER_MASK);\n let next = this.state[(i + MIDDLE_WORD) % STATE_SIZE] ^ (y >>> 1);\n if ((y & 1) !== 0) {\n next ^= MATRIX_A;\n }\n this.state[i] = next >>> 0;\n }\n this.index = 0;\n }\n\n getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\n}\n\n/**\n * Deterministic helper mirroring the random helpers defined in rerelease g_local.h.\n */\nexport class RandomGenerator {\n private readonly mt: MersenneTwister19937;\n\n constructor(options: RandomGeneratorOptions = {}) {\n this.mt = new MersenneTwister19937(options.seed);\n }\n\n seed(seed: number): void {\n this.mt.seed(seed);\n }\n\n /** Uniform float in [0, 1). */\n frandom(): number {\n return this.mt.nextUint32() / TWO_POW_32;\n }\n\n /** Uniform float in [min, max). */\n frandomRange(minInclusive: number, maxExclusive: number): number {\n return minInclusive + (maxExclusive - minInclusive) * this.frandom();\n }\n\n /** Uniform float in [0, max). */\n frandomMax(maxExclusive: number): number {\n return this.frandomRange(0, maxExclusive);\n }\n\n /** Uniform float in [-1, 1). */\n crandom(): number {\n return this.frandomRange(-1, 1);\n }\n\n /** Uniform float in (-1, 1). */\n crandomOpen(): number {\n const epsilon = Number.EPSILON;\n return this.frandomRange(-1 + epsilon, 1);\n }\n\n /** Raw uint32 sample. */\n irandomUint32(): number {\n return this.mt.nextUint32();\n }\n\n /** Uniform integer in [min, max). */\n irandomRange(minInclusive: number, maxExclusive: number): number {\n if (maxExclusive - minInclusive <= 1) {\n return minInclusive;\n }\n\n const span = maxExclusive - minInclusive;\n const limit = TWO_POW_32 - (TWO_POW_32 % span);\n let sample: number;\n do {\n sample = this.mt.nextUint32();\n } while (sample >= limit);\n return minInclusive + (sample % span);\n }\n\n /** Uniform integer in [0, max). */\n irandom(maxExclusive: number): number {\n if (maxExclusive <= 0) {\n return 0;\n }\n return this.irandomRange(0, maxExclusive);\n }\n\n /** Uniform time in milliseconds [min, max). */\n randomTimeRange(minMs: number, maxMs: number): number {\n if (maxMs <= minMs) {\n return minMs;\n }\n return this.irandomRange(minMs, maxMs);\n }\n\n /** Uniform time in milliseconds [0, max). */\n randomTime(maxMs: number): number {\n return this.irandom(maxMs);\n }\n\n randomIndex<T extends { length: number }>(container: T): number {\n return this.irandom(container.length);\n }\n\n getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\n }\n}\n\nexport function createRandomGenerator(options?: RandomGeneratorOptions): RandomGenerator {\n return new RandomGenerator(options);\n}\n","import { Vec3 } from './vec3.js';\n\nexport type Mat4 = Float32Array;\n\nexport function createMat4Identity(): Mat4 {\n return new Float32Array([\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1,\n ]);\n}\n\nexport function multiplyMat4(a: Float32Array, b: Float32Array): Mat4 {\n const out = new Float32Array(16);\n for (let row = 0; row < 4; row += 1) {\n for (let col = 0; col < 4; col += 1) {\n out[col * 4 + row] =\n a[0 * 4 + row] * b[col * 4 + 0] +\n a[1 * 4 + row] * b[col * 4 + 1] +\n a[2 * 4 + row] * b[col * 4 + 2] +\n a[3 * 4 + row] * b[col * 4 + 3];\n }\n }\n return out;\n}\n\nexport function transformPointMat4(mat: Float32Array, point: Vec3): Vec3 {\n const x = point.x;\n const y = point.y;\n const z = point.z;\n return {\n x: mat[0] * x + mat[4] * y + mat[8] * z + mat[12],\n y: mat[1] * x + mat[5] * y + mat[9] * z + mat[13],\n z: mat[2] * x + mat[6] * y + mat[10] * z + mat[14],\n };\n}\n\nexport function mat4FromBasis(origin: Vec3, axis: readonly [Vec3, Vec3, Vec3]): Mat4 {\n const out = createMat4Identity();\n out[0] = axis[0].x;\n out[1] = axis[0].y;\n out[2] = axis[0].z;\n\n out[4] = axis[1].x;\n out[5] = axis[1].y;\n out[6] = axis[1].z;\n\n out[8] = axis[2].x;\n out[9] = axis[2].y;\n out[10] = axis[2].z;\n\n out[12] = origin.x;\n out[13] = origin.y;\n out[14] = origin.z;\n\n return out;\n}\n","/**\n * Bitflag constants mirroring the Quake II rerelease `contents_t` and\n * `surfflags_t` enumerations from `game.h`. The helpers here operate purely on\n * numeric bitmasks so both the authoritative game simulation and the client can\n * share the same semantic checks.\n */\nexport type ContentsFlag = number;\nexport type SurfaceFlag = number;\n\nexport const CONTENTS_NONE: ContentsFlag = 0;\nexport const CONTENTS_SOLID: ContentsFlag = 1 << 0;\nexport const CONTENTS_WINDOW: ContentsFlag = 1 << 1;\nexport const CONTENTS_AUX: ContentsFlag = 1 << 2;\nexport const CONTENTS_LAVA: ContentsFlag = 1 << 3;\nexport const CONTENTS_SLIME: ContentsFlag = 1 << 4;\nexport const CONTENTS_WATER: ContentsFlag = 1 << 5;\nexport const CONTENTS_MIST: ContentsFlag = 1 << 6;\nexport const CONTENTS_TRIGGER: ContentsFlag = 0x40000000;\nexport const CONTENTS_NO_WATERJUMP: ContentsFlag = 1 << 13;\nexport const CONTENTS_PROJECTILECLIP: ContentsFlag = 1 << 14;\nexport const CONTENTS_AREAPORTAL: ContentsFlag = 1 << 15;\nexport const CONTENTS_PLAYERCLIP: ContentsFlag = 1 << 16;\nexport const CONTENTS_MONSTERCLIP: ContentsFlag = 1 << 17;\nexport const CONTENTS_CURRENT_0: ContentsFlag = 1 << 18;\nexport const CONTENTS_CURRENT_90: ContentsFlag = 1 << 19;\nexport const CONTENTS_CURRENT_180: ContentsFlag = 1 << 20;\nexport const CONTENTS_CURRENT_270: ContentsFlag = 1 << 21;\nexport const CONTENTS_CURRENT_UP: ContentsFlag = 1 << 22;\nexport const CONTENTS_CURRENT_DOWN: ContentsFlag = 1 << 23;\nexport const CONTENTS_ORIGIN: ContentsFlag = 1 << 24;\nexport const CONTENTS_MONSTER: ContentsFlag = 1 << 25;\nexport const CONTENTS_DEADMONSTER: ContentsFlag = 1 << 26;\nexport const CONTENTS_DETAIL: ContentsFlag = 1 << 27;\nexport const CONTENTS_TRANSLUCENT: ContentsFlag = 1 << 28;\nexport const CONTENTS_LADDER: ContentsFlag = 1 << 29;\nexport const CONTENTS_PLAYER: ContentsFlag = 1 << 30;\nexport const CONTENTS_PROJECTILE: ContentsFlag = 1 << 31;\n\nexport const LAST_VISIBLE_CONTENTS: ContentsFlag = CONTENTS_MIST;\n\nexport const SURF_NONE: SurfaceFlag = 0;\nexport const SURF_LIGHT: SurfaceFlag = 1 << 0;\nexport const SURF_SLICK: SurfaceFlag = 1 << 1;\nexport const SURF_SKY: SurfaceFlag = 1 << 2;\nexport const SURF_WARP: SurfaceFlag = 1 << 3;\nexport const SURF_TRANS33: SurfaceFlag = 1 << 4;\nexport const SURF_TRANS66: SurfaceFlag = 1 << 5;\nexport const SURF_FLOWING: SurfaceFlag = 1 << 6;\nexport const SURF_NODRAW: SurfaceFlag = 1 << 7;\nexport const SURF_ALPHATEST: SurfaceFlag = 1 << 25;\nexport const SURF_N64_UV: SurfaceFlag = 1 << 28;\nexport const SURF_N64_SCROLL_X: SurfaceFlag = 1 << 29;\nexport const SURF_N64_SCROLL_Y: SurfaceFlag = 1 << 30;\nexport const SURF_N64_SCROLL_FLIP: SurfaceFlag = 1 << 31;\n\nexport const MASK_ALL: ContentsFlag = 0xffffffff;\nexport const MASK_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_PLAYERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_DEADSOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_MONSTERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_WATER: ContentsFlag = CONTENTS_WATER | CONTENTS_LAVA | CONTENTS_SLIME;\nexport const MASK_OPAQUE: ContentsFlag = CONTENTS_SOLID | CONTENTS_SLIME | CONTENTS_LAVA;\nexport const MASK_SHOT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_PLAYER | CONTENTS_WINDOW | CONTENTS_DEADMONSTER;\nexport const MASK_CURRENT: ContentsFlag =\n CONTENTS_CURRENT_0 |\n CONTENTS_CURRENT_90 |\n CONTENTS_CURRENT_180 |\n CONTENTS_CURRENT_270 |\n CONTENTS_CURRENT_UP |\n CONTENTS_CURRENT_DOWN;\nexport const MASK_BLOCK_SIGHT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_LADDER_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_WALK_NAV_SOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTERCLIP;\nexport const MASK_PROJECTILE: ContentsFlag = MASK_SHOT | CONTENTS_PROJECTILECLIP;\n\nexport function hasAllContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) === flags;\n}\n\nexport function hasAnyContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) !== 0;\n}\n\nexport function addContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask | flags;\n}\n\nexport function removeContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask & ~flags;\n}\n\nexport function hasSurfaceFlags(surface: SurfaceFlag, flags: SurfaceFlag): boolean {\n return (surface & flags) === flags;\n}\n\nexport function combineSurfaceFlags(...flags: SurfaceFlag[]): SurfaceFlag {\n let mask = SURF_NONE;\n for (const flag of flags) {\n mask |= flag;\n }\n return mask;\n}\n","import type { Vec3 } from '../math/vec3.js';\n\nexport const AREA_DEPTH = 4;\nexport const WORLD_SIZE = 8192; // Standard Q2 world extent\n\nexport interface SpatialNode {\n axis: number; // 0=X, 1=Y, -1=Leaf\n dist: number;\n children: [SpatialNode, SpatialNode] | null;\n items: Set<number>;\n}\n\nexport function createSpatialTree(\n depth = 0,\n mins: Vec3 = { x: -WORLD_SIZE, y: -WORLD_SIZE, z: -WORLD_SIZE },\n maxs: Vec3 = { x: WORLD_SIZE, y: WORLD_SIZE, z: WORLD_SIZE }\n): SpatialNode {\n if (depth >= AREA_DEPTH) {\n return {\n axis: -1,\n dist: 0,\n children: null,\n items: new Set(),\n };\n }\n\n const axis = depth % 2; // Alternates X (0) and Y (1)\n const dist = 0.5 * (axis === 0 ? mins.x + maxs.x : mins.y + maxs.y);\n\n const mins1 = { ...mins };\n const maxs1 = { ...maxs };\n const mins2 = { ...mins };\n const maxs2 = { ...maxs };\n\n if (axis === 0) {\n maxs1.x = dist;\n mins2.x = dist;\n } else {\n maxs1.y = dist;\n mins2.y = dist;\n }\n\n const child1 = createSpatialTree(depth + 1, mins1, maxs1);\n const child2 = createSpatialTree(depth + 1, mins2, maxs2);\n\n return {\n axis,\n dist,\n children: [child1, child2],\n items: new Set(),\n };\n}\n\nexport function linkEntityToSpatialTree(\n node: SpatialNode,\n id: number,\n absmin: Vec3,\n absmax: Vec3\n): SpatialNode {\n let current = node;\n\n while (current.axis !== -1 && current.children) {\n const axis = current.axis;\n const dist = current.dist;\n\n const min = axis === 0 ? absmin.x : absmin.y;\n const max = axis === 0 ? absmax.x : absmax.y;\n\n if (min > dist) {\n current = current.children[1];\n } else if (max < dist) {\n current = current.children[0];\n } else {\n break; // Straddles the plane, resides in this node\n }\n }\n\n current.items.add(id);\n return current;\n}\n\nexport function querySpatialTree(\n node: SpatialNode,\n absmin: Vec3,\n absmax: Vec3,\n results: Set<number>\n): void {\n // Add all items in the current node (because if we are here, we overlap this node's space\n // and straddling items definitely overlap us or are at least in the parent region)\n // Actually, strictly speaking, items in this node straddle the split plane.\n // Since we are traversing down, we are within the node's volume.\n // The items in this node are those that couldn't be pushed further down.\n // So we must check them.\n\n // NOTE: This collects candidates. Precise collision check still needed.\n for (const id of node.items) {\n results.add(id);\n }\n\n if (node.axis === -1 || !node.children) {\n return;\n }\n\n const axis = node.axis;\n const dist = node.dist;\n\n const min = axis === 0 ? absmin.x : absmin.y;\n const max = axis === 0 ? absmax.x : absmax.y;\n\n if (max > dist) {\n querySpatialTree(node.children[1], absmin, absmax, results);\n }\n if (min < dist) {\n querySpatialTree(node.children[0], absmin, absmax, results);\n }\n}\n","import { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } from '../math/vec3.js';\nimport { createSpatialTree, linkEntityToSpatialTree, querySpatialTree, SpatialNode } from './spatial.js';\n\nexport interface CollisionPlane {\n normal: Vec3;\n dist: number;\n type: number;\n signbits: number;\n}\n\nexport interface CollisionBrushSide {\n plane: CollisionPlane;\n surfaceFlags: number;\n}\n\nexport interface CollisionBrush {\n contents: number;\n sides: CollisionBrushSide[];\n checkcount?: number;\n}\n\nexport interface CollisionLeaf {\n contents: number;\n cluster: number;\n area: number;\n firstLeafBrush: number;\n numLeafBrushes: number;\n}\n\nexport interface CollisionNode {\n plane: CollisionPlane;\n children: [number, number];\n}\n\nexport interface CollisionBmodel {\n mins: Vec3;\n maxs: Vec3;\n origin: Vec3;\n headnode: number;\n}\n\nexport interface CollisionModel {\n planes: CollisionPlane[];\n nodes: CollisionNode[];\n leaves: CollisionLeaf[];\n brushes: CollisionBrush[];\n leafBrushes: number[];\n bmodels: CollisionBmodel[];\n visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\n}\n\nexport interface CollisionLumpData {\n planes: Array<{ normal: Vec3; dist: number; type: number }>;\n nodes: Array<{ planenum: number; children: [number, number] }>;\n leaves: Array<{ contents: number; cluster: number; area: number; firstLeafBrush: number; numLeafBrushes: number }>;\n brushes: Array<{ firstSide: number; numSides: number; contents: number }>;\n brushSides: Array<{ planenum: number; surfaceFlags: number }>;\n leafBrushes: number[];\n bmodels: Array<{ mins: Vec3; maxs: Vec3; origin: Vec3; headnode: number }>;\n visibility?: CollisionVisibility;\n}\n\nexport interface TraceResult {\n fraction: number;\n plane: CollisionPlane | null;\n contents: number;\n surfaceFlags: number;\n startsolid: boolean;\n allsolid: boolean;\n}\n\nexport interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\n contents?: number;\n surfaceFlags?: number;\n startsolid: boolean;\n allsolid: boolean;\n}\n\nexport enum PlaneSide {\n FRONT = 1,\n BACK = 2,\n CROSS = 3,\n}\n\nexport interface TraceDebugInfo {\n nodesTraversed: number;\n leafsReached: number;\n brushesTested: number;\n}\n\nexport let traceDebugInfo: TraceDebugInfo | null = null;\n\nexport function enableTraceDebug(): void {\n traceDebugInfo = { nodesTraversed: 0, leafsReached: 0, brushesTested: 0 };\n // console.log('DEBUG: Trace debug enabled');\n}\n\nexport function disableTraceDebug(): void {\n traceDebugInfo = null;\n}\n\nexport const DIST_EPSILON = 0.03125;\n\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\n\nexport function buildCollisionModel(lumps: CollisionLumpData): CollisionModel {\n const planes: CollisionPlane[] = lumps.planes.map((plane) => ({\n ...plane,\n signbits: computePlaneSignBits(plane.normal),\n }));\n\n const nodes: CollisionNode[] = lumps.nodes.map((node) => ({\n plane: planes[node.planenum],\n children: node.children,\n }));\n\n const brushes: CollisionBrush[] = lumps.brushes.map((brush) => {\n const sides = lumps.brushSides.slice(brush.firstSide, brush.firstSide + brush.numSides).map((side) => ({\n plane: planes[side.planenum],\n surfaceFlags: side.surfaceFlags,\n }));\n\n return {\n contents: brush.contents,\n sides,\n checkcount: 0,\n };\n });\n\n const leaves: CollisionLeaf[] = lumps.leaves.map((leaf) => ({\n contents: leaf.contents,\n cluster: leaf.cluster,\n area: leaf.area,\n firstLeafBrush: leaf.firstLeafBrush,\n numLeafBrushes: leaf.numLeafBrushes,\n }));\n\n const bmodels: CollisionBmodel[] = lumps.bmodels.map((model) => ({\n mins: model.mins,\n maxs: model.maxs,\n origin: model.origin,\n headnode: model.headnode,\n }));\n\n return {\n planes,\n nodes,\n leaves,\n brushes,\n leafBrushes: lumps.leafBrushes,\n bmodels,\n visibility: lumps.visibility,\n };\n}\n\nexport function computePlaneSignBits(normal: Vec3): number {\n let bits = 0;\n if (normal.x < 0) bits |= 1;\n if (normal.y < 0) bits |= 2;\n if (normal.z < 0) bits |= 4;\n return bits;\n}\n\nexport function planeDistanceToPoint(plane: CollisionPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z - plane.dist;\n}\n\nexport function pointOnPlaneSide(plane: CollisionPlane, point: Vec3, epsilon = 0): PlaneSide.FRONT | PlaneSide.BACK | PlaneSide.CROSS {\n const dist = planeDistanceToPoint(plane, point);\n if (dist > epsilon) {\n return PlaneSide.FRONT;\n }\n if (dist < -epsilon) {\n return PlaneSide.BACK;\n }\n return PlaneSide.CROSS;\n}\n\nexport function boxOnPlaneSide(mins: Vec3, maxs: Vec3, plane: CollisionPlane, epsilon = 0): PlaneSide {\n let dist1: number;\n let dist2: number;\n\n switch (plane.signbits) {\n case 0:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 1:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 2:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 3:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 4:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 5:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 6:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n default:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n }\n\n let sides = 0;\n if (dist1 - plane.dist >= -epsilon) sides = PlaneSide.FRONT;\n if (dist2 - plane.dist <= epsilon) sides |= PlaneSide.BACK;\n return sides as PlaneSide;\n}\n\nexport function pointInsideBrush(point: Vec3, brush: CollisionBrush, epsilon = DIST_EPSILON): boolean {\n for (const side of brush.sides) {\n const dist = planeDistanceToPoint(side.plane, point);\n if (dist > epsilon) {\n return false;\n }\n }\n return true;\n}\n\nexport interface BoxBrushTestResult {\n startsolid: boolean;\n allsolid: boolean;\n contents: number;\n}\n\nexport function testBoxInBrush(origin: Vec3, mins: Vec3, maxs: Vec3, brush: CollisionBrush): BoxBrushTestResult {\n for (const side of brush.sides) {\n const offset = side.plane.normal.x * (side.plane.normal.x < 0 ? maxs.x : mins.x) +\n side.plane.normal.y * (side.plane.normal.y < 0 ? maxs.y : mins.y) +\n side.plane.normal.z * (side.plane.normal.z < 0 ? maxs.z : mins.z);\n\n const dist = side.plane.dist - offset;\n const d1 = origin.x * side.plane.normal.x + origin.y * side.plane.normal.y + origin.z * side.plane.normal.z - dist;\n\n if (d1 > 0) {\n return { startsolid: false, allsolid: false, contents: 0 };\n }\n }\n\n return { startsolid: true, allsolid: true, contents: brush.contents };\n}\n\nexport interface ClipBoxParams {\n start: Vec3;\n end: Vec3;\n mins: Vec3;\n maxs: Vec3;\n brush: CollisionBrush;\n trace: TraceResult;\n}\n\n/**\n * Clips a movement box against a brush using the Liang-Barsky algorithm.\n *\n * This function determines if and where the swept box (from start to end) intersects the brush.\n * It works by clipping the movement line segment against the infinite planes defined by the brush sides.\n *\n * Algorithm Overview (Liang-Barsky):\n * The movement is treated as a parameterized line P(t) = Start + t * (End - Start), for t in [0, 1].\n * We maintain an interval [enterfrac, leavefrac] (initially [-1, 1]) representing the portion of the\n * line that is potentially inside the brush.\n * For each plane:\n * 1. We determine the distance of Start (d1) and End (d2) from the plane.\n * - For box traces, planes are expanded by the box extents, effectively treating the box as a point.\n * 2. If both points are in front (outside), the line is outside the brush.\n * 3. If the line crosses the plane:\n * - If entering (d1 > d2), we update `enterfrac` (max of entry times).\n * - If leaving (d1 < d2), we update `leavefrac` (min of exit times).\n * 4. If at any point enterfrac > leavefrac, the line misses the brush.\n *\n * @see CM_ClipBoxToBrush in qcommon/cm_trace.c:145-220\n *\n * @param params ClipBoxParams containing start/end vectors, box mins/maxs, target brush, and trace result to update.\n */\nexport function clipBoxToBrush({ start, end, mins, maxs, brush, trace }: ClipBoxParams): void {\n if (brush.sides.length === 0) return;\n\n const isPoint = mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n\n // enterfrac: The fraction of movement where the box FIRST fully enters the brush volume (intersection start).\n // leavefrac: The fraction of movement where the box STARTS to leave the brush volume (intersection end).\n // Initialized to -1 and 1 to cover the full potential range + buffers.\n let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false; // True if the end point is outside at least one plane (not trapped in brush)\n let startout = false; // True if the start point is outside at least one plane (not starting stuck)\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\n\n // Expand the plane by the box extents to perform a point-plane test.\n // This reduces the AABB sweep vs convex brush problem to a line segment vs expanded planes problem.\n if (!isPoint) {\n const ofsX = plane.normal.x < 0 ? maxs.x : mins.x;\n const ofsY = plane.normal.y < 0 ? maxs.y : mins.y;\n const ofsZ = plane.normal.z < 0 ? maxs.z : mins.z;\n dist -= plane.normal.x * ofsX + plane.normal.y * ofsY + plane.normal.z * ofsZ;\n }\n\n // d1: Distance of start point from the (expanded) plane. Positive = in front (outside).\n // d2: Distance of end point from the (expanded) plane.\n const d1 = start.x * plane.normal.x + start.y * plane.normal.y + start.z * plane.normal.z - dist;\n const d2 = end.x * plane.normal.x + end.y * plane.normal.y + end.z * plane.normal.z - dist;\n\n if (d2 > 0) getout = true;\n if (d1 > 0) startout = true;\n\n // Case 1: Entirely outside this plane.\n // Since brushes are convex intersections of half-spaces (defined by planes pointing OUT),\n // being in front of ANY plane means being outside the brush.\n // The d2 >= d1 check handles the case where the line is parallel or moving away from the plane.\n if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n // Case 2: Entirely inside this plane (back side).\n // Does not restrict the entry/exit interval further than other planes might.\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n // Case 3: Line intersects the plane.\n // d1 > d2 means we are moving from Front (outside) to Back (inside) -> Entering.\n if (d1 > d2) {\n // Calculate intersection fraction f.\n // DIST_EPSILON is subtracted to ensure we stop slightly *before* the plane,\n // preventing the object from getting stuck in the next frame due to float precision.\n const f = (d1 - DIST_EPSILON) / (d1 - d2);\n if (f > enterfrac) {\n enterfrac = f;\n clipplane = plane;\n leadside = side;\n }\n } else {\n // Moving from Back (inside) to Front (outside) -> Leaving.\n // DIST_EPSILON is added to push the exit point slightly further out (or in depending on perspective),\n // effectively narrowing the \"inside\" interval.\n const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n // If we never started outside any plane, we started inside the brush.\n if (!startout) {\n trace.startsolid = true;\n // If we also never got out of any plane (meaning we stayed behind all planes),\n // then the entire movement is inside the brush (allsolid).\n if (!getout) {\n trace.allsolid = true;\n }\n trace.fraction = 0;\n return;\n }\n\n // If the entry fraction is less than the exit fraction, we have a valid intersection interval.\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n if (enterfrac < 0) enterfrac = 0;\n trace.fraction = enterfrac;\n trace.plane = clipplane;\n trace.contents = brush.contents;\n trace.surfaceFlags = leadside?.surfaceFlags ?? 0;\n }\n}\n\nexport function createDefaultTrace(): TraceResult {\n return {\n fraction: 1,\n plane: null,\n contents: 0,\n surfaceFlags: 0,\n startsolid: false,\n allsolid: false,\n };\n}\n\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\n/**\n * Recursively checks a hull sweep against a BSP tree.\n * Implements a Liang-Barsky like clipping algorithm against the BSP planes.\n *\n * Based on CM_RecursiveHullCheck in qcommon/cm_trace.c.\n */\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n // If we've already hit something earlier in the trace than where we are starting this check,\n // we can stop.\n if (trace.fraction <= startFraction) {\n return;\n }\n\n // If we reached a leaf, check the brushes in it.\n if (nodeIndex < 0) {\n if (traceDebugInfo) {\n traceDebugInfo.leafsReached++;\n }\n\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n // Optimization: Avoid checking the same brush multiple times in a single trace.\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n if (traceDebugInfo) {\n traceDebugInfo.brushesTested++;\n }\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n if (traceDebugInfo) {\n traceDebugInfo.nodesTraversed++;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n\n // Calculate the distance from the plane to the box's nearest corner.\n // This effectively expands the plane by the box extents.\n // Use absolute value of offset like original C code (full/qcommon/cmodel.c:1269-1271).\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start);\n const endDist = planeDistanceToPoint(plane, end);\n\n // If both start and end points are in front of the plane (including offset),\n // we only need to check the front child.\n if (startDist >= offset && endDist >= offset) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n // If both start and end points are behind the plane (including offset),\n // we only need to check the back child.\n if (startDist < -offset && endDist < -offset) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n // The segment straddles the plane. We need to split the segment and recurse down both sides.\n // Put the crosspoint DIST_EPSILON pixels on the near side to avoid precision issues.\n // See full/qcommon/cmodel.c:1293-1313 (CM_RecursiveHullCheck)\n // fraction1 (frac) is used for \"move up to node\" - the near-side recursion\n // fraction2 (frac2) is used for \"go past the node\" - the far-side recursion\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1, fraction2;\n\n if (startDist < endDist) {\n side = 1;\n fraction2 = (startDist + offset + DIST_EPSILON) * idist;\n fraction1 = (startDist - offset + DIST_EPSILON) * idist;\n } else {\n side = 0;\n fraction2 = (startDist - offset - DIST_EPSILON) * idist;\n fraction1 = (startDist + offset + DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n // Recurse down the near side\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n // Optimisation: if we hit something closer than the split point, we don't need to check the far side\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n // Recurse down the far side\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n if (traceDebugInfo) {\n traceDebugInfo.leafsReached++;\n }\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): boolean {\n return !(\n a.mins.x > b.maxs.x ||\n a.maxs.x < b.mins.x ||\n a.mins.y > b.maxs.y ||\n a.maxs.y < b.mins.y ||\n a.mins.z > b.maxs.z ||\n a.maxs.z < b.mins.z\n );\n}\n\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n private readonly entityNodes = new Map<number, SpatialNode>();\n private readonly rootNode = createSpatialTree();\n\n link(entity: CollisionEntityLink): void {\n const state = makeEntityState(entity);\n this.entities.set(entity.id, state);\n\n // Update spatial index\n const existingNode = this.entityNodes.get(entity.id);\n if (existingNode) {\n existingNode.items.delete(entity.id);\n }\n\n const newNode = linkEntityToSpatialTree(\n this.rootNode,\n entity.id,\n state.bounds.mins,\n state.bounds.maxs\n );\n this.entityNodes.set(entity.id, newNode);\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n\n const node = this.entityNodes.get(entityId);\n if (node) {\n node.items.delete(entityId);\n this.entityNodes.delete(entityId);\n }\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n // Determine query bounds for spatial lookup\n const traceAbsMin = {\n x: Math.min(params.start.x, params.end.x) + mins.x,\n y: Math.min(params.start.y, params.end.y) + mins.y,\n z: Math.min(params.start.z, params.end.z) + mins.z,\n };\n const traceAbsMax = {\n x: Math.max(params.start.x, params.end.x) + maxs.x,\n y: Math.max(params.start.y, params.end.y) + maxs.y,\n z: Math.max(params.start.z, params.end.z) + maxs.z,\n };\n\n const candidates = new Set<number>();\n querySpatialTree(this.rootNode, traceAbsMin, traceAbsMax, candidates);\n\n for (const entityId of candidates) {\n if (entityId === passId) continue;\n\n const entity = this.entities.get(entityId);\n if (!entity) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n if (trace.startsolid || trace.allsolid || trace.fraction < bestTrace.fraction) {\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n const candidates = new Set<number>();\n querySpatialTree(this.rootNode, queryBounds.mins, queryBounds.maxs, candidates);\n\n for (const entityId of candidates) {\n const entity = this.entities.get(entityId);\n if (!entity) continue;\n\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\n }\n}\n","export const enum CvarFlags {\n None = 0,\n Archive = 1 << 0,\n UserInfo = 1 << 1,\n ServerInfo = 1 << 2,\n Latch = 1 << 3,\n Cheat = 1 << 4,\n}\n\nexport interface CvarDefinition {\n readonly name: string;\n readonly defaultValue: string;\n readonly description?: string;\n readonly flags?: CvarFlags;\n}\n","// Mirrors the Quake II rerelease configstring/index layout from `game.h`.\n// These constants intentionally track the numeric values used in the C++\n// game and client modules so the TypeScript engine/game/client layers can\n// share deterministic indices for precaches and HUD parsing.\n\nexport const MAX_STRING_CHARS = 1024;\nexport const MAX_STRING_TOKENS = 80;\nexport const MAX_TOKEN_CHARS = 512;\n\nexport const MAX_QPATH = 64;\nexport const MAX_OSPATH = 128;\n\nexport const MAX_CLIENTS = 256;\nexport const MAX_EDICTS = 8192;\nexport const MAX_LIGHTSTYLES = 256;\nexport const MAX_MODELS = 8192;\nexport const MAX_SOUNDS = 2048;\nexport const MAX_IMAGES = 512;\nexport const MAX_ITEMS = 256;\nexport const MAX_GENERAL = MAX_CLIENTS * 2;\nexport const MAX_SHADOW_LIGHTS = 256;\nexport const MAX_WHEEL_ITEMS = 32;\n\nexport const CS_MAX_STRING_LENGTH = 96;\nexport const CS_MAX_STRING_LENGTH_OLD = 64;\n\n// Enum-style numeric constants that mirror the C++ `configstrings` enum. Only\n// the explicitly numbered entries are re-stated here; everything else follows\n// sequentially to keep the arithmetic (e.g., CS_SOUNDS = CS_MODELS +\n// MAX_MODELS) intact.\nexport enum ConfigStringIndex {\n Name = 0,\n CdTrack = 1,\n Sky = 2,\n SkyAxis = 3,\n SkyRotate = 4,\n StatusBar = 5,\n\n // Matching bg_local.h:55-76\n HealthBarName = 55,\n CONFIG_N64_PHYSICS = 56,\n CONFIG_CTF_TEAMS = 57,\n CONFIG_COOP_RESPAWN_STRING = 58,\n Story = 54, // Arbitrarily placed in the gap for now\n\n AirAccel = 59,\n MaxClients = 60,\n MapChecksum = 61,\n\n Models = 62,\n Sounds = Models + MAX_MODELS,\n Images = Sounds + MAX_SOUNDS,\n Lights = Images + MAX_IMAGES,\n ShadowLights = Lights + MAX_LIGHTSTYLES,\n Items = ShadowLights + MAX_SHADOW_LIGHTS,\n Players = Items + MAX_ITEMS, // CS_PLAYERS (contains userinfo with name, skin, etc.)\n PlayerSkins = Players, // Alias for legacy code compatibility\n General = Players + MAX_CLIENTS,\n WheelWeapons = General + MAX_GENERAL,\n WheelAmmo = WheelWeapons + MAX_WHEEL_ITEMS,\n WheelPowerups = WheelAmmo + MAX_WHEEL_ITEMS,\n CdLoopCount = WheelPowerups + MAX_WHEEL_ITEMS,\n GameStyle = CdLoopCount + 1,\n MaxConfigStrings = GameStyle + 1,\n}\n\n// Mirror the C++ MAX_CONFIGSTRINGS value for consumers that prefer a standalone constant.\nexport const MAX_CONFIGSTRINGS = ConfigStringIndex.MaxConfigStrings;\n\n/**\n * Returns the maximum string length permitted for the given configstring index,\n * mirroring the `CS_SIZE` helper in the rerelease. Statusbar and general ranges\n * can legally occupy multiple 96-character slots; everything else is capped at\n * `CS_MAX_STRING_LENGTH`.\n */\nexport function configStringSize(index: number): number {\n if (index >= ConfigStringIndex.StatusBar && index < ConfigStringIndex.AirAccel) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.AirAccel - index);\n }\n\n if (index >= ConfigStringIndex.General && index < ConfigStringIndex.WheelWeapons) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.MaxConfigStrings - index);\n }\n\n return CS_MAX_STRING_LENGTH;\n}\n\n// Legacy constants\nexport const CS_NAME = ConfigStringIndex.Name;\nexport const CS_CDTRACK = ConfigStringIndex.CdTrack;\nexport const CS_SKY = ConfigStringIndex.Sky;\nexport const CS_SKYAXIS = ConfigStringIndex.SkyAxis;\nexport const CS_SKYROTATE = ConfigStringIndex.SkyRotate;\nexport const CS_STATUSBAR = ConfigStringIndex.StatusBar;\nexport const CS_AIRACCEL = ConfigStringIndex.AirAccel;\nexport const CS_MAXCLIENTS = ConfigStringIndex.MaxClients;\nexport const CS_MAPCHECKSUM = ConfigStringIndex.MapChecksum;\nexport const CS_MODELS = ConfigStringIndex.Models;\nexport const CS_SOUNDS = ConfigStringIndex.Sounds;\nexport const CS_IMAGES = ConfigStringIndex.Images;\nexport const CS_LIGHTS = ConfigStringIndex.Lights;\nexport const CS_ITEMS = ConfigStringIndex.Items;\nexport const CS_PLAYERS = ConfigStringIndex.Players;\nexport const CS_GENERAL = ConfigStringIndex.General;\n","export * from './schema.js';\nexport * from './io.js';\n","import { ReplaySession, ReplayFrame } from './schema.js';\nimport { UserCommand } from '../protocol/usercmd.js';\n\nexport function serializeReplay(session: ReplaySession): string {\n return JSON.stringify(session, null, 2);\n}\n\nexport function deserializeReplay(json: string): ReplaySession {\n const session = JSON.parse(json);\n\n // Validate structure lightly\n if (!session.metadata || !Array.isArray(session.frames)) {\n throw new Error('Invalid replay format: missing metadata or frames');\n }\n\n return session as ReplaySession;\n}\n\nexport function createReplaySession(map: string, seed?: number): ReplaySession {\n return {\n metadata: {\n map,\n date: new Date().toISOString(),\n version: '1.0',\n seed\n },\n frames: []\n };\n}\n\nexport function addReplayFrame(session: ReplaySession, cmd: UserCommand, serverFrame: number, startTime: number) {\n session.frames.push({\n serverFrame,\n cmd,\n timestamp: Date.now() - startTime\n });\n}\n","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\n","/**\n * Mirrors the Quake II rerelease `water_level_t` enumeration from `game.h`\n * (lines 443-449). These numeric values are relied upon throughout the\n * movement code when checking how submerged a player is, so we keep the same\n * ordering to make future porting work straightforward.\n */\nexport enum WaterLevel {\n None = 0,\n Feet = 1,\n Waist = 2,\n Under = 3,\n}\n\n/**\n * Utility that matches the common rerelease checks that treat any level at or\n * above the `WATER_WAIST` constant as \"significantly submerged\" for friction\n * and current calculations.\n */\nexport function isAtLeastWaistDeep(level: WaterLevel): boolean {\n return level >= WaterLevel.Waist;\n}\n\n/**\n * Returns true when the player is considered underwater (the `WATER_UNDER`\n * case in the rerelease). This mirrors the places in `p_move.cpp` that gate\n * effects such as breath timers and screen warping.\n */\nexport function isUnderwater(level: WaterLevel): boolean {\n return level === WaterLevel.Under;\n}\n\n/**\n * Matches the Quake II rerelease `pmflags_t` bit layout from `game.h` so the\n * shared helpers can manipulate the same flag words as the authoritative game\n * and the client prediction layer.\n */\nexport const enum PmFlag {\n Ducked = 1 << 0,\n JumpHeld = 1 << 1,\n OnGround = 1 << 2,\n TimeWaterJump = 1 << 3,\n TimeLand = 1 << 4,\n TimeTeleport = 1 << 5,\n NoPositionalPrediction = 1 << 6,\n OnLadder = 1 << 7,\n NoAngularPrediction = 1 << 8,\n IgnorePlayerCollision = 1 << 9,\n TimeTrick = 1 << 10,\n}\n\nexport type PmFlags = number;\n\nexport function hasPmFlag(flags: PmFlags, flag: PmFlag): boolean {\n return (flags & flag) !== 0;\n}\n\nexport function addPmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags | flag;\n}\n\nexport function removePmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags & ~flag;\n}\n\n/**\n * Player movement types mirrored from the rerelease `pmtype_t` enumeration.\n * The exact numeric values matter when syncing pmove state across the network\n * so we keep the same order as the C++ definition.\n */\nexport enum PmType {\n Normal = 0,\n Grapple = 1,\n NoClip = 2,\n Spectator = 3,\n Dead = 4,\n Gib = 5,\n Freeze = 6,\n}\n\n/**\n * Bitmask constants for the `buttons` field on the Quake II player command\n * structure. These mirror the rerelease `BUTTON_*` definitions so logic such as\n * jump/crouch checks can be shared between the server and client.\n */\nexport const enum PlayerButton {\n None = 0,\n Attack = 1 << 0,\n Use = 1 << 1,\n Holster = 1 << 2,\n Jump = 1 << 3,\n Crouch = 1 << 4,\n Attack2 = 1 << 5,\n Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel, type PmFlags, PmFlag, PmType, PlayerButton, addPmFlag, removePmFlag } from './constants.js';\n\nconst DEFAULT_JUMP_HEIGHT = 270;\n\nexport interface CheckJumpParams {\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly origin: Vec3;\n readonly jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly origin: Vec3;\n readonly jumpSound: boolean;\n readonly jumped: boolean;\n}\n\nfunction hasButton(buttons: number, button: PlayerButton): boolean {\n return (buttons & button) !== 0;\n}\n\n/**\n * Pure translation of the rerelease `PM_CheckJump` helper from `p_move.cpp`.\n * The function takes in the minimal pmove state that the original C++ logic\n * touches and returns the updated flag/origin/velocity tuple so callers can\n * apply the same semantics on both the server and client.\n */\nexport function checkJump(params: CheckJumpParams): CheckJumpResult {\n const { pmFlags, pmType, buttons, waterlevel, onGround, velocity, origin, jumpHeight = DEFAULT_JUMP_HEIGHT } = params;\n\n // PM_CheckJump immediately bails while the landing timer is active.\n if (pmFlags & PmFlag.TimeLand) {\n return { pmFlags, onGround, velocity, origin, jumpSound: false, jumped: false };\n }\n\n const holdingJump = hasButton(buttons, PlayerButton.Jump);\n let nextFlags = pmFlags;\n let nextOnGround = onGround;\n let jumpSound = false;\n let jumped = false;\n let nextVelocity = velocity;\n let nextOrigin = origin;\n\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n }\n\n nextFlags = addPmFlag(nextFlags, PmFlag.JumpHeld);\n nextFlags = removePmFlag(nextFlags, PmFlag.OnGround);\n nextOnGround = false;\n jumpSound = true;\n jumped = true;\n\n const z = velocity.z + jumpHeight;\n const finalZ = z < jumpHeight ? jumpHeight : z;\n nextVelocity = { ...velocity, z: finalZ };\n\n // Unstuck from ground: pm->s.origin[2] += 1;\n nextOrigin = { ...origin, z: origin.z + 1 };\n\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, origin: nextOrigin, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\n}\n","import type { ContentsFlag } from '../bsp/contents.js';\nimport {\n CONTENTS_CURRENT_0,\n CONTENTS_CURRENT_180,\n CONTENTS_CURRENT_270,\n CONTENTS_CURRENT_90,\n CONTENTS_CURRENT_DOWN,\n CONTENTS_CURRENT_UP,\n CONTENTS_LADDER,\n MASK_CURRENT,\n} from '../bsp/contents.js';\nimport { addVec3, crossVec3, normalizeVec3, scaleVec3, ZERO_VEC3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, WaterLevel, isAtLeastWaistDeep } from './constants.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nexport interface WaterCurrentParams {\n readonly watertype: ContentsFlag;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly waterSpeed: number;\n}\n\nexport interface GroundCurrentParams {\n readonly groundContents: ContentsFlag;\n readonly scale?: number;\n}\n\nexport interface AddCurrentsParams {\n readonly wishVelocity: Vec3;\n readonly onLadder: boolean;\n readonly onGround: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n readonly groundContents: ContentsFlag;\n readonly cmd: PmoveCmd;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly waterSpeed: number;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace?: PmoveTraceFn;\n}\n\nconst DEFAULT_GROUND_CURRENT_SCALE = 100;\nconst DEFAULT_FORWARD_LADDER_CLAMP = 200;\nconst DEFAULT_SIDE_LADDER_CLAMP = 150;\nconst LADDER_HORIZONTAL_CAP = 25;\nconst LADDER_ASCEND_PITCH_THRESHOLD = 15;\nconst LADDER_TRACE_DISTANCE = 1;\nconst UP_VECTOR: Vec3 = { x: 0, y: 0, z: 1 };\n\nconst DEFAULT_TRACE: PmoveTraceFn = (_, end) => ({\n fraction: 1,\n endpos: end,\n allsolid: false,\n startsolid: false,\n});\n\n/**\n * Mirrors the rerelease pattern in `p_move.cpp` (lines 730-765) that turns the\n * directional CONTENTS_CURRENT_* flags into a unit-ish direction vector.\n */\nexport function currentVectorFromContents(contents: ContentsFlag): Vec3 {\n let x = 0;\n let y = 0;\n let z = 0;\n\n if (contents & CONTENTS_CURRENT_0) {\n x += 1;\n }\n if (contents & CONTENTS_CURRENT_90) {\n y += 1;\n }\n if (contents & CONTENTS_CURRENT_180) {\n x -= 1;\n }\n if (contents & CONTENTS_CURRENT_270) {\n y -= 1;\n }\n if (contents & CONTENTS_CURRENT_UP) {\n z += 1;\n }\n if (contents & CONTENTS_CURRENT_DOWN) {\n z -= 1;\n }\n\n if (x === 0 && y === 0 && z === 0) {\n return ZERO_VEC3;\n }\n\n return { x, y, z };\n}\n\n/**\n * Computes the velocity contribution from water currents using the same rules\n * as `PM_WaterMove`: the CONTENTS_CURRENT_* bits are turned into a direction\n * vector, scaled by `pm_waterspeed`, and halved when the player only has their\n * feet submerged while standing on solid ground.\n */\nexport function waterCurrentVelocity(params: WaterCurrentParams): Vec3 {\n const { watertype, waterlevel, onGround, waterSpeed } = params;\n\n if ((watertype & MASK_CURRENT) === 0) {\n return ZERO_VEC3;\n }\n\n const direction = currentVectorFromContents(watertype);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n let scale = waterSpeed;\n if (waterlevel === WaterLevel.Feet && onGround) {\n scale *= 0.5;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Computes the conveyor-style velocity that should be applied while touching a\n * ground plane that carries CONTENTS_CURRENT_* bits. The rerelease multiplies\n * the direction vector by 100 units per second, so we expose the same default\n * while allowing callers to override the scalar for tests.\n */\nexport function groundCurrentVelocity(params: GroundCurrentParams): Vec3 {\n const { groundContents, scale = DEFAULT_GROUND_CURRENT_SCALE } = params;\n\n const direction = currentVectorFromContents(groundContents);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Pure mirror of PM_AddCurrents from rerelease `p_move.cpp`: handles ladder\n * specific motion tweaks, water currents, and conveyor-style ground currents\n * before pmove acceleration is applied.\n */\nexport function applyPmoveAddCurrents(params: AddCurrentsParams): Vec3 {\n const {\n wishVelocity,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed,\n ladderMod,\n waterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace = DEFAULT_TRACE,\n } = params;\n\n let adjusted = wishVelocity;\n\n if (onLadder) {\n adjusted = applyLadderAdjustments({\n wishVelocity: adjusted,\n cmd,\n waterlevel,\n viewPitch,\n maxSpeed,\n ladderMod,\n onGround,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n }\n\n const waterVelocity = waterCurrentVelocity({ watertype, waterlevel, onGround, waterSpeed });\n if (waterVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, waterVelocity);\n }\n\n if (onGround) {\n const groundVelocity = groundCurrentVelocity({ groundContents });\n if (groundVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, groundVelocity);\n }\n }\n\n return adjusted;\n}\n\ninterface LadderAdjustParams {\n readonly wishVelocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly onGround: boolean;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nfunction applyLadderAdjustments(params: LadderAdjustParams): Vec3 {\n const { wishVelocity, cmd, waterlevel, viewPitch, maxSpeed, ladderMod, onGround, forward, origin, mins, maxs, trace } = params;\n const buttons = cmd.buttons ?? 0;\n let adjusted = { ...wishVelocity };\n\n if ((buttons & (PlayerButton.Jump | PlayerButton.Crouch)) !== 0) {\n const ladderSpeed = isAtLeastWaistDeep(waterlevel) ? maxSpeed : DEFAULT_FORWARD_LADDER_CLAMP;\n adjusted = {\n ...adjusted,\n z: buttons & PlayerButton.Jump ? ladderSpeed : -ladderSpeed,\n };\n } else if (cmd.forwardmove) {\n const clamped = clamp(cmd.forwardmove, -DEFAULT_FORWARD_LADDER_CLAMP, DEFAULT_FORWARD_LADDER_CLAMP);\n if (cmd.forwardmove > 0) {\n const climb = viewPitch < LADDER_ASCEND_PITCH_THRESHOLD ? clamped : -clamped;\n adjusted = { ...adjusted, z: climb };\n } else {\n if (!onGround) {\n adjusted = { ...adjusted, x: 0, y: 0 };\n }\n adjusted = { ...adjusted, z: clamped };\n }\n } else {\n adjusted = { ...adjusted, z: 0 };\n }\n\n if (!onGround) {\n if (cmd.sidemove) {\n let sideSpeed = clamp(cmd.sidemove, -DEFAULT_SIDE_LADDER_CLAMP, DEFAULT_SIDE_LADDER_CLAMP);\n if (waterlevel < WaterLevel.Waist) {\n sideSpeed *= ladderMod;\n }\n\n const flatForward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n if (flatForward.x !== 0 || flatForward.y !== 0) {\n const spot = addVec3(origin, scaleVec3(flatForward, LADDER_TRACE_DISTANCE));\n const tr = trace(origin, spot, mins, maxs);\n if (\n tr.fraction !== 1 &&\n !tr.allsolid &&\n tr.contents !== undefined &&\n (tr.contents & CONTENTS_LADDER) !== 0 &&\n tr.planeNormal\n ) {\n const right = crossVec3(tr.planeNormal, UP_VECTOR);\n adjusted = { ...adjusted, x: 0, y: 0 };\n adjusted = addVec3(adjusted, scaleVec3(right, -sideSpeed));\n }\n }\n } else {\n adjusted = {\n ...adjusted,\n x: clampHorizontal(adjusted.x),\n y: clampHorizontal(adjusted.y),\n };\n }\n }\n\n return adjusted;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction clampHorizontal(value: number): number {\n if (value < -LADDER_HORIZONTAL_CAP) {\n return -LADDER_HORIZONTAL_CAP;\n }\n if (value > LADDER_HORIZONTAL_CAP) {\n return LADDER_HORIZONTAL_CAP;\n }\n return value;\n}\n","import { addVec3, ZERO_VEC3, clipVelocityVec3, crossVec3, dotVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst DEFAULT_MAX_CLIP_PLANES = 5;\nconst DEFAULT_MAX_BUMPS = 4;\nconst DEFAULT_STEP_SIZE = 18;\nconst MIN_STEP_NORMAL = 0.7;\n\nexport const SLIDEMOVE_BLOCKED_FLOOR = 1;\nexport const SLIDEMOVE_BLOCKED_WALL = 2;\n\nexport interface SlideMoveResult {\n readonly velocity: Vec3;\n readonly planes: readonly Vec3[];\n readonly stopped: boolean;\n}\n\nexport interface SlideMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly overbounce: number;\n readonly trace: PmoveTraceFn;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n /**\n * Mirrors the pm->s.pm_time check in PM_StepSlideMove_Generic: if true, the\n * returned velocity is reset to the primal velocity after collision\n * resolution so time-based effects (like knockbacks) don't dampen.\n */\n readonly hasTime?: boolean;\n}\n\nexport interface SlideMoveOutcome extends SlideMoveResult {\n readonly origin: Vec3;\n readonly blocked: number;\n}\n\nexport interface StepSlideMoveParams extends SlideMoveParams {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly stepSize?: number;\n}\n\nexport interface StepSlideMoveOutcome extends SlideMoveOutcome {\n readonly stepped: boolean;\n readonly stepHeight: number;\n readonly stepNormal?: Vec3;\n}\n\n/**\n * Resolves a sequence of collision planes against a primal velocity using the same\n * plane iteration logic seen in PM_StepSlideMove_Generic (rerelease p_move.cpp).\n * The incoming planes should be ordered as they were encountered during traces;\n * the function will accumulate them, clip the velocity to be parallel to all planes,\n * and return zero velocity when three planes form an unresolvable corner or when\n * the adjusted velocity would oppose the primal direction.\n */\nexport function resolveSlideMove(\n initialVelocity: Vec3,\n planesEncountered: readonly Vec3[],\n overbounce: number,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n primalVelocity: Vec3 = initialVelocity,\n): SlideMoveResult {\n if (planesEncountered.length === 0) {\n return { velocity: initialVelocity, planes: [], stopped: false };\n }\n\n const planes: Vec3[] = [];\n let velocity: Vec3 = initialVelocity;\n\n for (const plane of planesEncountered) {\n if (planes.length >= maxClipPlanes) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n // Skip near-duplicate planes to mirror the epsilon guard in PM_StepSlideMove_Generic.\n const duplicate = planes.find((existing) => dotVec3(existing, plane) > 0.99);\n if (duplicate) {\n continue;\n }\n\n planes.push(plane);\n\n let clipped: Vec3 | undefined;\n let i = 0;\n for (; i < planes.length; i++) {\n const candidate = clipVelocityVec3(velocity, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) continue;\n if (dotVec3(candidate, planes[j]) < 0) break;\n }\n\n if (j === planes.length) {\n clipped = candidate;\n break;\n }\n }\n\n if (clipped) {\n velocity = clipped;\n } else {\n if (planes.length !== 2) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n velocity = scaleVec3(dir, d);\n }\n\n // If velocity reversed relative to the primal direction, stop to avoid oscillations.\n if (dotVec3(velocity, primalVelocity) <= 0) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n }\n\n const stopped = velocity.x === 0 && velocity.y === 0 && velocity.z === 0;\n return { velocity, planes, stopped };\n}\n\n/**\n * Pure mirror of PM_SlideMoveGeneric from rerelease `p_move.cpp` (minus gravity/step handling).\n * Uses a caller-provided trace to collect collision planes, accumulates them through\n * `resolveSlideMove`, and returns the resulting origin/velocity/blocking state.\n */\nexport function slideMove(params: SlideMoveParams): SlideMoveOutcome {\n const {\n origin: initialOrigin,\n velocity: initialVelocity,\n frametime,\n overbounce,\n trace,\n maxBumps = DEFAULT_MAX_BUMPS,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n mins,\n maxs,\n hasTime = false,\n } = params;\n\n let origin = initialOrigin;\n let velocity = initialVelocity;\n const planes: Vec3[] = [];\n const primalVelocity = initialVelocity;\n let timeLeft = frametime;\n let blocked = 0;\n\n for (let bump = 0; bump < maxBumps; bump++) {\n if (velocity.x === 0 && velocity.y === 0 && velocity.z === 0) {\n break;\n }\n\n const end = addVec3(origin, scaleVec3(velocity, timeLeft));\n const tr = trace(origin, end, mins, maxs);\n\n if (tr.allsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.startsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.fraction > 0) {\n origin = tr.endpos;\n }\n\n if (tr.fraction === 1) {\n break;\n }\n\n if (!tr.planeNormal) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.planeNormal.z > 0.7) {\n blocked |= SLIDEMOVE_BLOCKED_FLOOR;\n }\n if (tr.planeNormal.z === 0) {\n blocked |= SLIDEMOVE_BLOCKED_WALL;\n }\n\n planes.push(tr.planeNormal);\n timeLeft -= timeLeft * tr.fraction;\n\n const resolved = resolveSlideMove(velocity, planes, overbounce, maxClipPlanes, primalVelocity);\n velocity = resolved.velocity;\n planes.splice(0, planes.length, ...resolved.planes);\n\n if (primalVelocity.z > 0 && velocity.z < 0) {\n velocity = { ...velocity, z: 0 };\n }\n\n if (resolved.stopped) {\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: true, blocked };\n }\n }\n\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: velocityOut.x === 0 && velocityOut.y === 0 && velocityOut.z === 0, blocked };\n}\n\n/**\n * Mirrors PM_StepSlideMove (rerelease p_move.cpp) in a pure form: attempts a\n * regular slide move, then retries from a stepped-up position when the first\n * attempt was blocked. The function compares planar distance traveled and the\n * steepness of the landing plane to decide whether to keep the step.\n */\nexport function stepSlideMove(params: StepSlideMoveParams): StepSlideMoveOutcome {\n const { mins, maxs, stepSize = DEFAULT_STEP_SIZE, ...rest } = params;\n\n const startOrigin = params.origin;\n const startVelocity = params.velocity;\n\n const downResult = slideMove({ ...rest, mins, maxs });\n\n const upTarget = addVec3(startOrigin, { x: 0, y: 0, z: stepSize });\n const upTrace = rest.trace(startOrigin, upTarget, mins, maxs);\n if (upTrace.allsolid) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const actualStep = upTrace.endpos.z - startOrigin.z;\n const steppedResult = slideMove({ ...rest, origin: upTrace.endpos, velocity: startVelocity, mins, maxs });\n\n const pushDownTarget = addVec3(steppedResult.origin, { x: 0, y: 0, z: -actualStep });\n const downTrace = rest.trace(steppedResult.origin, pushDownTarget, mins, maxs);\n\n let steppedOrigin = steppedResult.origin;\n let stepNormal = downTrace.planeNormal;\n\n if (!downTrace.allsolid) {\n steppedOrigin = downTrace.endpos;\n }\n\n const planarDistanceSquared = (a: Vec3, b: Vec3) => (a.x - b.x) ** 2 + (a.y - b.y) ** 2;\n const downDist = planarDistanceSquared(downResult.origin, startOrigin);\n const upDist = planarDistanceSquared(steppedOrigin, startOrigin);\n\n if (downDist > upDist || (stepNormal && stepNormal.z < MIN_STEP_NORMAL)) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const steppedVelocity = { ...steppedResult.velocity, z: downResult.velocity.z };\n const steppedBlocked = steppedResult.blocked;\n const stopped = steppedVelocity.x === 0 && steppedVelocity.y === 0 && steppedVelocity.z === 0;\n\n return {\n origin: steppedOrigin,\n velocity: steppedVelocity,\n planes: steppedResult.planes,\n blocked: steppedBlocked,\n stopped,\n stepped: true,\n stepHeight: actualStep,\n stepNormal,\n };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport { applyPmoveAccelerate, applyPmoveAirAccelerate } from './pmove.js';\nimport { applyPmoveAddCurrents } from './currents.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n PlayerButton,\n WaterLevel,\n hasPmFlag,\n} from './constants.js';\n\ninterface BaseMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly hasTime?: boolean;\n}\n\nexport interface AirMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly gravity: number;\n readonly pmType: PmType;\n readonly pmAccelerate: number;\n readonly pmAirAccelerate?: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly onLadder: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly groundContents: number;\n readonly viewPitch: number;\n readonly ladderMod: number;\n readonly pmWaterSpeed: number;\n}\n\nexport interface WaterMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly pmWaterAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly onLadder: boolean;\n readonly watertype: number;\n readonly groundContents: number;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly ladderMod: number;\n}\n\nexport interface WalkMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly gravity: number;\n readonly pmType: PmType;\n readonly pmAccelerate: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly onLadder: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly groundContents: number;\n readonly viewPitch: number;\n readonly ladderMod: number;\n readonly pmWaterSpeed: number;\n}\n\nconst DEFAULT_AIR_ACCELERATE = 1;\nconst WATER_DRIFT_SPEED = 60;\nconst DEFAULT_STEP_OVERBOUNCE = 1.01;\n\nexport function applyPmoveAirMove(params: AirMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n gravity,\n pmType,\n pmAccelerate,\n pmAirAccelerate = DEFAULT_AIR_ACCELERATE,\n pmMaxSpeed,\n pmDuckSpeed,\n onLadder,\n waterlevel,\n watertype,\n groundContents,\n viewPitch,\n ladderMod,\n pmWaterSpeed,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildPlanarWishVelocity(forward, right, cmd);\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n const maxSpeed = ducked ? pmDuckSpeed : pmMaxSpeed;\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n if (onLadder) {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (Math.abs(wishvel.z) < Number.EPSILON) {\n velocity = dampVerticalVelocity(velocity, gravity, frametime);\n }\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (onGround) {\n velocity = { ...velocity, z: 0 };\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (gravity > 0) {\n velocity = { ...velocity, z: 0 };\n } else {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n if (velocity.x === 0 && velocity.y === 0) {\n return {\n origin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: true,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (pmAirAccelerate > 0) {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir,\n wishspeed,\n accel: pmAirAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: DEFAULT_AIR_ACCELERATE, frametime });\n }\n\n if (pmType !== PmType.Grapple) {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nexport function applyPmoveWaterMove(params: WaterMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n pmMaxSpeed,\n pmDuckSpeed,\n pmWaterAccelerate,\n pmWaterSpeed,\n onLadder,\n watertype,\n groundContents,\n waterlevel,\n viewPitch,\n ladderMod,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildFullWishVelocity(forward, right, cmd);\n\n if (isIdleInWater(cmd, onGround)) {\n wishvel = { ...wishvel, z: wishvel.z - WATER_DRIFT_SPEED };\n } else {\n if (hasButton(cmd, PlayerButton.Crouch)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: -pmWaterSpeed * 0.5 });\n } else if (hasButton(cmd, PlayerButton.Jump)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: pmWaterSpeed * 0.5 });\n }\n }\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmMaxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n wishspeed *= 0.5;\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n if (ducked && wishspeed > pmDuckSpeed) {\n const scale = pmDuckSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmDuckSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmWaterAccelerate, frametime });\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nexport function applyPmoveWalkMove(params: WalkMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n gravity,\n pmAccelerate,\n pmMaxSpeed,\n pmDuckSpeed,\n onLadder,\n waterlevel,\n watertype,\n groundContents,\n viewPitch,\n ladderMod,\n pmWaterSpeed,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildPlanarWishVelocity(forward, right, cmd);\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n const maxSpeed = ducked ? pmDuckSpeed : pmMaxSpeed;\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n // Ground friction handled by caller (applyPmoveFriction)\n\n velocity = { ...velocity, z: 0 };\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n\n if (gravity > 0) {\n velocity = { ...velocity, z: 0 };\n } else {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n if (velocity.x === 0 && velocity.y === 0) {\n return {\n origin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: true,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nfunction buildPlanarWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n}\n\nfunction buildFullWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: forward.z * cmd.forwardmove + right.z * cmd.sidemove,\n } satisfies Vec3;\n}\n\nfunction hasButton(cmd: PmoveCmd, button: PlayerButton): boolean {\n return (cmd.buttons ?? 0) & button ? true : false;\n}\n\nfunction isIdleInWater(cmd: PmoveCmd, onGround: boolean): boolean {\n const noMove = cmd.forwardmove === 0 && cmd.sidemove === 0;\n const noButtons = (cmd.buttons ?? 0) & (PlayerButton.Jump | PlayerButton.Crouch) ? false : true;\n return noMove && noButtons && !onGround;\n}\n\nfunction dampVerticalVelocity(velocity: Vec3, gravity: number, frametime: number): Vec3 {\n let z = velocity.z;\n const delta = gravity * frametime;\n if (z > 0) {\n z -= delta;\n if (z < 0) {\n z = 0;\n }\n } else {\n z += delta;\n if (z > 0) {\n z = 0;\n }\n }\n return { ...velocity, z };\n}\n\ninterface StepParams extends BaseMoveParams {\n readonly velocity: Vec3;\n}\n\nfunction runStepSlideMove(params: StepParams): StepSlideMoveOutcome {\n const { origin, velocity, frametime, mins, maxs, trace, overbounce = DEFAULT_STEP_OVERBOUNCE, stepSize, maxBumps, maxClipPlanes, hasTime } = params;\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n","import { MASK_WATER, CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel } from './constants.js';\nimport type { PmovePointContentsFn } from './types.js';\n\nexport interface WaterLevelParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly viewheight: number;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface WaterLevelResult {\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n}\n\n/**\n * Mirrors the rerelease `PM_GetWaterLevel` helper: probes the player's feet,\n * waist, and viewheight to determine how submerged they are and returns both\n * the enum level plus the contents bits encountered at the lowest sample.\n */\nexport function getWaterLevel(params: WaterLevelParams): WaterLevelResult {\n const { origin, mins, viewheight, pointContents } = params;\n\n const sample2 = viewheight - mins.z;\n const sample1 = sample2 / 2;\n\n const point: Vec3 = {\n x: origin.x,\n y: origin.y,\n z: origin.z + mins.z + 1,\n };\n\n let contents = pointContents(point);\n if ((contents & MASK_WATER) === 0) {\n return { waterlevel: WaterLevel.None, watertype: CONTENTS_NONE };\n }\n\n const watertype = contents;\n let waterlevel = WaterLevel.Feet;\n\n let point2: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample1 };\n contents = pointContents(point2);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Waist;\n\n let point3: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample2 };\n contents = pointContents(point3);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Under;\n }\n }\n\n return { waterlevel, watertype };\n}\n","import { CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport { addVec3, clipVelocityVec3, type Vec3 } from '../math/vec3.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport { getWaterLevel } from './water.js';\nimport type { PmovePointContentsFn, PmoveTraceFn, PmoveTraceResult } from './types.js';\n\nconst GROUND_PROBE_DISTANCE = 0.25;\nconst LADDER_BYPASS_VELOCITY = 180;\nconst TRICK_VELOCITY_THRESHOLD = 100;\nconst SLANTED_NORMAL_THRESHOLD = 0.7;\nconst TRICK_NORMAL_THRESHOLD = 0.9;\nconst TRICK_PM_TIME = 64;\nconst LAND_PM_TIME = 128;\nconst IMPACT_CLIP_OVERBOUNCE = 1.01;\n\nconst WATERJUMP_CLEAR =\n PmFlag.TimeWaterJump | PmFlag.TimeLand | PmFlag.TimeTeleport | PmFlag.TimeTrick;\n\nexport interface CategorizePositionParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly n64Physics: boolean;\n readonly velocity: Vec3;\n readonly startVelocity: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface CategorizePositionResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly onGround: boolean;\n readonly groundTrace?: PmoveTraceResult;\n readonly groundContents: ContentsFlag;\n readonly waterlevel: number;\n readonly watertype: ContentsFlag;\n readonly impactDelta?: number;\n}\n\n/**\n * Pure mirror of PM_CatagorizePosition from `rerelease/p_move.cpp`: traces a quarter-unit\n * below the player bounds to determine whether they stand on solid ground, updates timers\n * and pmflags accordingly, records the latest ground plane data, and recalculates waterlevel\n * by probing feet/waist/viewheight samples.\n */\nexport function categorizePosition(params: CategorizePositionParams): CategorizePositionResult {\n const {\n pmType,\n n64Physics,\n velocity,\n startVelocity,\n origin,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n } = params;\n\n let pmFlags = params.pmFlags;\n let pmTime = params.pmTime;\n let impactDelta: number | undefined;\n let onGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n let groundTrace: PmoveTraceResult | undefined;\n let groundContents: ContentsFlag = CONTENTS_NONE;\n\n const forceAirborne = velocity.z > LADDER_BYPASS_VELOCITY || pmType === PmType.Grapple;\n\n if (forceAirborne) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n const end: Vec3 = { x: origin.x, y: origin.y, z: origin.z - GROUND_PROBE_DISTANCE };\n const traceResult = trace(origin, end, mins, maxs);\n groundTrace = traceResult;\n groundContents = traceResult.contents ?? CONTENTS_NONE;\n\n const planeNormal = traceResult.planeNormal;\n\n let slantedGround =\n traceResult.fraction < 1 && !!planeNormal && planeNormal.z < SLANTED_NORMAL_THRESHOLD;\n\n if (slantedGround && planeNormal) {\n const slantEnd = addVec3(origin, planeNormal);\n const slantTrace = trace(origin, slantEnd, mins, maxs);\n if (slantTrace.fraction < 1 && !slantTrace.startsolid) {\n slantedGround = false;\n }\n }\n\n if (\n traceResult.fraction === 1 ||\n !planeNormal ||\n (slantedGround && !traceResult.startsolid)\n ) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n onGround = true;\n\n if (hasPmFlag(pmFlags, PmFlag.TimeWaterJump)) {\n pmFlags &= ~WATERJUMP_CLEAR;\n pmTime = 0;\n }\n\n const wasOnGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround) {\n if (\n !n64Physics &&\n velocity.z >= TRICK_VELOCITY_THRESHOLD &&\n planeNormal.z >= TRICK_NORMAL_THRESHOLD &&\n !hasPmFlag(pmFlags, PmFlag.Ducked)\n ) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeTrick);\n pmTime = TRICK_PM_TIME;\n }\n\n const clipped = clipVelocityVec3(velocity, planeNormal, IMPACT_CLIP_OVERBOUNCE);\n impactDelta = startVelocity.z - clipped.z;\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround && (n64Physics || hasPmFlag(pmFlags, PmFlag.Ducked))) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeLand);\n pmTime = LAND_PM_TIME;\n }\n }\n }\n\n const { waterlevel, watertype } = getWaterLevel({\n origin,\n mins,\n viewheight,\n pointContents,\n });\n\n return {\n pmFlags,\n pmTime,\n onGround: hasPmFlag(pmFlags, PmFlag.OnGround),\n groundTrace,\n groundContents,\n waterlevel,\n watertype,\n impactDelta,\n };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { PmFlag, type PmFlags, PmType } from './constants.js';\n\nexport interface PlayerDimensions {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n}\n\nfunction createVec3(x: number, y: number, z: number): Vec3 {\n return { x, y, z } satisfies Vec3;\n}\n\n/**\n * Pure mirror of PM_SetDimensions from rerelease `p_move.cpp`.\n * Computes the mins/maxs/viewheight triplet for a player based on\n * their movement type and ducked flag without mutating inputs.\n */\nexport function computePlayerDimensions(pmType: PmType, pmFlags: PmFlags): PlayerDimensions {\n const minsBase = createVec3(-16, -16, 0);\n const maxsBase = createVec3(16, 16, 16);\n\n if (pmType === PmType.Gib) {\n return {\n mins: minsBase,\n maxs: maxsBase,\n viewheight: 8,\n } satisfies PlayerDimensions;\n }\n\n const ducked = pmType === PmType.Dead || (pmFlags & PmFlag.Ducked) !== 0;\n const mins = createVec3(minsBase.x, minsBase.y, -24);\n const maxs = createVec3(maxsBase.x, maxsBase.y, ducked ? 4 : 32);\n\n return {\n mins,\n maxs,\n viewheight: ducked ? -2 : 22,\n } satisfies PlayerDimensions;\n}\n","import { MASK_SOLID, MASK_WATER, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport {\n PlayerButton,\n PmFlag,\n type PmFlags,\n PmType,\n WaterLevel,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport type { PmoveTraceResult } from './types.js';\nimport { computePlayerDimensions, type PlayerDimensions } from './dimensions.js';\n\nconst CROUCH_MAX_Z = 4;\nconst STAND_MAX_Z = 32;\nconst ABOVE_WATER_OFFSET = 8;\n\nexport interface DuckTraceParams {\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly mask: ContentsFlag;\n}\n\nexport type DuckTraceFn = (params: DuckTraceParams) => PmoveTraceResult;\n\nexport interface CheckDuckParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly hasGroundEntity: boolean;\n readonly onLadder: boolean;\n readonly n64Physics: boolean;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: DuckTraceFn;\n}\n\nexport interface CheckDuckResult extends PlayerDimensions {\n readonly pmFlags: PmFlags;\n readonly ducked: boolean;\n readonly changed: boolean;\n}\n\n/**\n * Pure port of PM_CheckDuck from rerelease `p_move.cpp`. Updates the PMF_DUCKED flag\n * based on crouch input, obstruction traces, and special cases (dead bodies) without\n * mutating the provided mins/maxs. Returns the updated flag word plus the dimensions\n * computed from PM_SetDimensions so callers can update collision bounds atomically.\n */\nexport function checkDuckState(params: CheckDuckParams): CheckDuckResult {\n const { pmType } = params;\n\n if (pmType === PmType.Gib) {\n const dims = computePlayerDimensions(pmType, params.pmFlags);\n return { pmFlags: params.pmFlags, ducked: hasPmFlag(params.pmFlags, PmFlag.Ducked), changed: false, ...dims };\n }\n\n let flags = params.pmFlags;\n let changed = false;\n\n if (pmType === PmType.Dead) {\n if (!hasPmFlag(flags, PmFlag.Ducked)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (shouldDuck(params)) {\n if (!hasPmFlag(flags, PmFlag.Ducked) && !isDuckBlocked(params)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (hasPmFlag(flags, PmFlag.Ducked) && !isStandBlocked(params)) {\n flags = removePmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n\n const dims = computePlayerDimensions(pmType, flags);\n const ducked = pmType === PmType.Dead || hasPmFlag(flags, PmFlag.Ducked);\n\n return { pmFlags: flags, ducked, changed, ...dims };\n}\n\nfunction shouldDuck(params: CheckDuckParams): boolean {\n if ((params.buttons & PlayerButton.Crouch) === 0) {\n return false;\n }\n if (params.onLadder || params.n64Physics) {\n return false;\n }\n if (params.hasGroundEntity) {\n return true;\n }\n if (params.waterlevel <= WaterLevel.Feet && !isAboveWater(params)) {\n return true;\n }\n return false;\n}\n\nfunction isDuckBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, CROUCH_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isStandBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, STAND_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isAboveWater(params: CheckDuckParams): boolean {\n const below: Vec3 = { x: params.origin.x, y: params.origin.y, z: params.origin.z - ABOVE_WATER_OFFSET };\n\n const solidTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_SOLID,\n });\n\n if (solidTrace.fraction < 1) {\n return false;\n }\n\n const waterTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_WATER,\n });\n\n return waterTrace.fraction < 1;\n}\n\nfunction withZ(vec: Vec3, z: number): Vec3 {\n return { x: vec.x, y: vec.y, z };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport { angleVectors } from '../math/angles.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n PmoveState,\n PmoveImports,\n PmoveTraceResult\n} from './types.js';\nimport { PlayerButton, PmFlag, PmType, addPmFlag, removePmFlag } from './constants.js';\nimport { checkJump } from './jump.js';\nimport { applyPmoveAirMove, applyPmoveWaterMove, applyPmoveWalkMove } from './move.js';\nimport { categorizePosition } from './categorize.js';\nimport { checkDuckState, DuckTraceParams } from './duck.js';\n// import { updateViewOffsets } from './view.js';\n\nconst FRAMETIME = 0.025; // Define FRAMETIME here or import if available in constants? Using local definition for now as per previous context.\n\n/**\n * Pure version of PM_Friction from rerelease p_move.cpp.\n * Handles ground and water friction and returns a new velocity.\n */\nexport function applyPmoveFriction(params: PmoveFrictionParams): Vec3 {\n const {\n velocity,\n frametime,\n onGround,\n groundIsSlick,\n onLadder,\n waterlevel,\n pmFriction,\n pmStopSpeed,\n pmWaterFriction,\n } = params;\n\n const speed = lengthVec3(velocity);\n\n // Matches the \"if (speed < 1)\" early-out: clears X/Y but preserves Z.\n if (speed < 1) {\n return { x: 0, y: 0, z: velocity.z };\n }\n\n let drop = 0;\n\n // Ground friction (or ladder)\n if ((onGround && !groundIsSlick) || onLadder) {\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const friction = pmFriction;\n drop += control * friction * frametime;\n }\n\n // Water friction (only when not on ladder)\n if (waterlevel > 0 && !onLadder) {\n drop += speed * pmWaterFriction * waterlevel * frametime;\n }\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n const scale = newspeed / speed;\n return scaleVec3(velocity, scale);\n}\n\n/**\n * Pure version of PM_Accelerate from rerelease p_move.cpp.\n * Returns a new velocity with wishdir/wishspeed acceleration applied.\n */\nexport function applyPmoveAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspeed - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * frametime * wishspeed;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Mirrors PM_AirAccelerate in rerelease `p_move.cpp` (lines ~612-636): wishspeed is clamped\n * to 30 for the addspeed calculation but the acceleration magnitude still uses the full wishspeed.\n */\nexport function applyPmoveAirAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const wishspd = Math.min(wishspeed, 30);\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspd - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * wishspeed * frametime;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Pure mirror of PM_CmdScale from rerelease `p_move.cpp`. Computes the scalar applied to\n * the command directional inputs so that the resulting wish velocity caps at `maxSpeed`\n * regardless of the directional mix.\n */\nexport function pmoveCmdScale(cmd: PmoveCmd, maxSpeed: number): number {\n const forward = Math.abs(cmd.forwardmove);\n const side = Math.abs(cmd.sidemove);\n const up = Math.abs(cmd.upmove);\n\n const max = Math.max(forward, side, up);\n if (max === 0) {\n return 0;\n }\n\n const total = Math.sqrt(cmd.forwardmove * cmd.forwardmove + cmd.sidemove * cmd.sidemove + cmd.upmove * cmd.upmove);\n return (maxSpeed * max) / (127 * total);\n}\n\n/**\n * Computes wishdir/wishspeed for ground/air movement as done in PM_AirMove and\n * PM_GroundMove. Z is forced to zero and wishspeed is clamped to maxSpeed, matching\n * the rerelease p_move.cpp helpers before they call PM_Accelerate/PM_AirAccelerate.\n */\nexport function buildAirGroundWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n\n/**\n * Computes the wishdir/wishspeed mix for water movement, matching PM_WaterMove in\n * rerelease p_move.cpp: includes the upward bias when no strong upmove is requested,\n * clamps wishspeed to maxSpeed, and halves the returned wishspeed before acceleration.\n */\nexport function buildWaterWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n // Use full 3D components for water movement\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: forward.z * cmd.forwardmove + right.z * cmd.sidemove,\n } satisfies Vec3;\n\n if (cmd.upmove > 10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else if (cmd.upmove < -10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else if (Math.abs(cmd.forwardmove) < 10 && Math.abs(cmd.sidemove) < 10) {\n // Standard drift down when no vertical input AND no significant horizontal input\n // Matches Quake 2 rerelease behavior (sinking slowly)\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: -60 });\n } else {\n // When moving horizontally but not vertically, drift slightly up\n // This matches the \"else { wishvel[2] += 10 }\" logic in PM_WaterMove\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: 10 });\n }\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n wishspeed *= 0.5;\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n\n/**\n * Runs the full player movement simulation for a single frame.\n */\nexport function runPmove(state: PmoveState, imports: PmoveImports): PmoveState {\n if (state.pmType === PmType.Dead) {\n return state;\n }\n\n let nextState = { ...state };\n\n // Categorize Position\n const catResult = categorizePosition({\n pmType: nextState.pmType,\n pmFlags: nextState.pmFlags,\n pmTime: 0,\n n64Physics: false,\n velocity: nextState.velocity,\n startVelocity: nextState.velocity,\n origin: nextState.origin,\n mins: nextState.mins,\n maxs: nextState.maxs,\n viewheight: nextState.viewHeight,\n trace: imports.trace,\n pointContents: imports.pointcontents\n });\n\n // Merge result back to state\n nextState.pmFlags = catResult.pmFlags;\n nextState.waterlevel = catResult.waterlevel;\n nextState.watertype = catResult.watertype;\n\n // Check Ducking (Before Jump)\n const duckResult = checkDuckState({\n pmType: nextState.pmType,\n pmFlags: nextState.pmFlags,\n buttons: nextState.cmd.buttons,\n waterlevel: nextState.waterlevel,\n hasGroundEntity: (nextState.pmFlags & PmFlag.OnGround) !== 0,\n onLadder: false,\n n64Physics: false,\n origin: nextState.origin,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: (params: DuckTraceParams): PmoveTraceResult => {\n // Adapter from DuckTraceFn (obj) to PmoveTraceFn (args)\n return imports.trace(params.start, params.end, params.mins, params.maxs);\n }\n });\n\n nextState.pmFlags = duckResult.pmFlags;\n nextState.mins = duckResult.mins;\n nextState.maxs = duckResult.maxs;\n nextState.viewHeight = duckResult.viewheight;\n\n // Check Jump\n const jumpResult = checkJump({\n pmFlags: nextState.pmFlags,\n pmType: nextState.pmType,\n buttons: nextState.cmd.buttons,\n waterlevel: nextState.waterlevel,\n onGround: (nextState.pmFlags & PmFlag.OnGround) !== 0,\n velocity: nextState.velocity,\n origin: nextState.origin\n });\n\n nextState.pmFlags = jumpResult.pmFlags;\n nextState.velocity = jumpResult.velocity;\n nextState.origin = jumpResult.origin;\n\n if (jumpResult.onGround !== ((nextState.pmFlags & PmFlag.OnGround) !== 0)) {\n if (jumpResult.onGround) {\n nextState.pmFlags = addPmFlag(nextState.pmFlags, PmFlag.OnGround);\n } else {\n nextState.pmFlags = removePmFlag(nextState.pmFlags, PmFlag.OnGround);\n }\n }\n\n // Frictional movement\n const onGround = (nextState.pmFlags & PmFlag.OnGround) !== 0;\n\n // Apply friction\n const velocityBeforeFriction = nextState.velocity;\n nextState.velocity = applyPmoveFriction({\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n onGround,\n groundIsSlick: false,\n onLadder: false, // Defaulting to false for now as ladder logic is complex\n waterlevel: nextState.waterlevel,\n pmFriction: 6, // Default\n pmStopSpeed: 100, // Default\n pmWaterFriction: 1 // Default\n });\n\n // Calculate view vectors from angles\n const { forward, right } = angleVectors(nextState.viewAngles);\n\n if (nextState.pmType === PmType.NoClip) {\n // PM_NoclipMove\n // Simplified noclip\n const wishvel = {\n x: forward.x * nextState.cmd.forwardmove + right.x * nextState.cmd.sidemove,\n y: forward.y * nextState.cmd.forwardmove + right.y * nextState.cmd.sidemove,\n z: nextState.cmd.upmove\n };\n const scale = FRAMETIME; // Just move by velocity\n // Actually we need to apply velocity based on input\n // But sticking to just what's needed for jumping/movement:\n nextState.velocity = wishvel; // Simple override for noclip\n nextState.origin = {\n x: nextState.origin.x + wishvel.x * scale,\n y: nextState.origin.y + wishvel.y * scale,\n z: nextState.origin.z + wishvel.z * scale\n };\n\n } else if (nextState.waterlevel >= 2) {\n const outcome = applyPmoveWaterMove({\n origin: nextState.origin,\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: imports.trace,\n cmd: nextState.cmd,\n forward,\n right,\n pmFlags: nextState.pmFlags,\n onGround,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n pmWaterAccelerate: 4,\n pmWaterSpeed: 400,\n onLadder: false,\n watertype: nextState.watertype,\n groundContents: 0, // Should be passed in?\n waterlevel: nextState.waterlevel,\n viewPitch: nextState.viewAngles.x,\n ladderMod: 1,\n stepSize: 18 // Added stepSize for consistency, though water move might not use it heavily\n });\n nextState.origin = outcome.origin;\n nextState.velocity = outcome.velocity;\n\n } else if ((nextState.pmFlags & PmFlag.OnGround) === 0) {\n const outcome = applyPmoveAirMove({\n origin: nextState.origin,\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: imports.trace,\n cmd: nextState.cmd,\n forward,\n right,\n pmFlags: nextState.pmFlags,\n onGround,\n gravity: nextState.gravity,\n pmType: nextState.pmType,\n pmAccelerate: 10,\n pmAirAccelerate: 1,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n onLadder: false,\n waterlevel: nextState.waterlevel,\n watertype: nextState.watertype,\n groundContents: 0,\n viewPitch: nextState.viewAngles.x,\n ladderMod: 1,\n pmWaterSpeed: 400,\n stepSize: 18 // Added stepSize\n });\n nextState.origin = outcome.origin;\n nextState.velocity = outcome.velocity;\n\n } else {\n const outcome = applyPmoveWalkMove({\n origin: nextState.origin,\n velocity: nextState.velocity,\n frametime: FRAMETIME,\n mins: nextState.mins,\n maxs: nextState.maxs,\n trace: imports.trace,\n cmd: nextState.cmd,\n forward,\n right,\n pmFlags: nextState.pmFlags,\n onGround,\n gravity: nextState.gravity,\n pmType: nextState.pmType,\n pmAccelerate: 10,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n onLadder: false,\n waterlevel: nextState.waterlevel,\n watertype: nextState.watertype,\n groundContents: 0,\n viewPitch: nextState.viewAngles.x,\n ladderMod: 1,\n pmWaterSpeed: 400,\n stepSize: 18 // Added stepSize\n });\n nextState.origin = outcome.origin;\n nextState.velocity = outcome.velocity;\n }\n\n // Categorize Position again at end of frame\n const catResultEnd = categorizePosition({\n pmType: nextState.pmType,\n pmFlags: nextState.pmFlags,\n pmTime: 0,\n n64Physics: false,\n velocity: nextState.velocity,\n startVelocity: nextState.velocity,\n origin: nextState.origin,\n mins: nextState.mins,\n maxs: nextState.maxs,\n viewheight: nextState.viewHeight,\n trace: imports.trace,\n pointContents: imports.pointcontents\n });\n\n nextState.pmFlags = catResultEnd.pmFlags;\n nextState.waterlevel = catResultEnd.waterlevel;\n nextState.watertype = catResultEnd.watertype;\n\n // Update view offsets (bobbing, etc)\n // nextState = updateViewOffsets(nextState);\n\n return nextState;\n}\n","import {\n addVec3,\n lengthSquaredVec3,\n scaleVec3,\n subtractVec3,\n type Vec3,\n} from '../math/vec3.js';\nimport type { PmoveTraceResult } from './types.js';\n\nconst AXES = ['x', 'y', 'z'] as const;\ntype Axis = (typeof AXES)[number];\n\ntype AxisTuple = readonly [number, number, number];\ntype SideBoundCode = -1 | 0 | 1;\n\ninterface SideCheck {\n readonly normal: AxisTuple;\n readonly mins: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n readonly maxs: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n}\n\nconst SIDE_CHECKS: readonly SideCheck[] = [\n { normal: [0, 0, 1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [0, 0, -1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [-1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [0, 1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n { normal: [0, -1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n];\n\nexport interface FixStuckParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: FixStuckTraceFn;\n}\n\nexport type FixStuckResult = 'good-position' | 'fixed' | 'no-good-position';\n\nexport interface FixStuckOutcome {\n readonly result: FixStuckResult;\n readonly origin: Vec3;\n}\n\nexport type FixStuckTraceFn = (\n start: Vec3,\n mins: Vec3,\n maxs: Vec3,\n end: Vec3,\n) => PmoveTraceResult;\n\ninterface CandidatePosition {\n readonly distance: number;\n readonly origin: Vec3;\n}\n\nconst ZERO_VEC: Vec3 = { x: 0, y: 0, z: 0 };\n\ntype MutableVec3 = { x: number; y: number; z: number };\n\nfunction cloneMutable(vec: Vec3): MutableVec3 {\n return { x: vec.x, y: vec.y, z: vec.z };\n}\n\nfunction tupleToVec3(tuple: AxisTuple): Vec3 {\n return { x: tuple[0], y: tuple[1], z: tuple[2] };\n}\n\nfunction adjustAxis(vec: MutableVec3, axis: Axis, delta: number): void {\n if (delta === 0) return;\n switch (axis) {\n case 'x':\n vec.x += delta;\n break;\n case 'y':\n vec.y += delta;\n break;\n case 'z':\n vec.z += delta;\n break;\n }\n}\n\nfunction setAxis(vec: MutableVec3, axis: Axis, value: number): void {\n switch (axis) {\n case 'x':\n vec.x = value;\n break;\n case 'y':\n vec.y = value;\n break;\n case 'z':\n vec.z = value;\n break;\n }\n}\n\nfunction axisValue(vec: Vec3, axis: Axis): number {\n switch (axis) {\n case 'x':\n return vec.x;\n case 'y':\n return vec.y;\n case 'z':\n default:\n return vec.z;\n }\n}\n\nfunction boundValue(code: SideBoundCode, axis: Axis, mins: Vec3, maxs: Vec3): number {\n if (code === -1) {\n return axisValue(mins, axis);\n }\n if (code === 1) {\n return axisValue(maxs, axis);\n }\n return 0;\n}\n\nfunction applySideOffset(base: Vec3, side: SideCheck, mins: Vec3, maxs: Vec3): MutableVec3 {\n const result = cloneMutable(base);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n const normal = side.normal[i];\n if (normal < 0) {\n adjustAxis(result, axis, axisValue(mins, axis));\n } else if (normal > 0) {\n adjustAxis(result, axis, axisValue(maxs, axis));\n }\n }\n return result;\n}\n\nfunction buildSideBounds(side: SideCheck, mins: Vec3, maxs: Vec3): { mins: MutableVec3; maxs: MutableVec3 } {\n const localMins = cloneMutable(ZERO_VEC);\n const localMaxs = cloneMutable(ZERO_VEC);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n setAxis(localMins, axis, boundValue(side.mins[i], axis, mins, maxs));\n setAxis(localMaxs, axis, boundValue(side.maxs[i], axis, mins, maxs));\n }\n return { mins: localMins, maxs: localMaxs };\n}\n\nfunction addEpsilon(\n source: MutableVec3,\n axis: Axis | undefined,\n direction: number,\n): MutableVec3 {\n if (!axis || direction === 0) {\n return source;\n }\n const clone = cloneMutable(source);\n adjustAxis(clone, axis, direction);\n return clone;\n}\n\nfunction addEpsilonImmutable(vec: Vec3, axis: Axis | undefined, direction: number): Vec3 {\n if (!axis || direction === 0) {\n return vec;\n }\n switch (axis) {\n case 'x':\n return { ...vec, x: vec.x + direction };\n case 'y':\n return { ...vec, y: vec.y + direction };\n case 'z':\n default:\n return { ...vec, z: vec.z + direction };\n }\n}\n\n/**\n * TypeScript port of G_FixStuckObject_Generic from rerelease p_move.cpp. Attempts to\n * nudge a stuck bounding box out of solid space by probing the faces of the box and\n * moving towards the opposite side, keeping the smallest successful displacement.\n */\nexport function fixStuckObjectGeneric(params: FixStuckParams): FixStuckOutcome {\n const { origin, mins, maxs, trace } = params;\n\n const initial = trace(origin, mins, maxs, origin);\n if (!initial.startsolid) {\n return { result: 'good-position', origin: { ...origin } };\n }\n\n const candidates: CandidatePosition[] = [];\n\n for (let i = 0; i < SIDE_CHECKS.length; i++) {\n const side = SIDE_CHECKS[i];\n const { mins: localMins, maxs: localMaxs } = buildSideBounds(side, mins, maxs);\n\n let start = applySideOffset(origin, side, mins, maxs);\n let tr = trace(start, localMins, localMaxs, start);\n\n let epsilonAxis: Axis | undefined;\n let epsilonDir = 0;\n\n if (tr.startsolid) {\n for (let axisIndex = 0; axisIndex < AXES.length; axisIndex++) {\n if (side.normal[axisIndex] !== 0) {\n continue;\n }\n const axis = AXES[axisIndex];\n let epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, 1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = 1;\n break;\n }\n epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, -1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = -1;\n break;\n }\n }\n }\n\n if (tr.startsolid) {\n continue;\n }\n\n const otherSide = SIDE_CHECKS[i ^ 1];\n let oppositeStart = applySideOffset(origin, otherSide, mins, maxs);\n oppositeStart = addEpsilon(oppositeStart, epsilonAxis, epsilonDir);\n\n tr = trace(start, localMins, localMaxs, oppositeStart);\n if (tr.startsolid) {\n continue;\n }\n\n const normal = tupleToVec3(side.normal);\n const end = addVec3(tr.endpos ?? oppositeStart, scaleVec3(normal, 0.125));\n const delta = subtractVec3(end, oppositeStart);\n let newOrigin = addVec3(origin, delta);\n newOrigin = addEpsilonImmutable(newOrigin, epsilonAxis, epsilonDir);\n\n const validation = trace(newOrigin, mins, maxs, newOrigin);\n if (validation.startsolid) {\n continue;\n }\n\n candidates.push({ origin: newOrigin, distance: lengthSquaredVec3(delta) });\n }\n\n if (candidates.length === 0) {\n return { result: 'no-good-position', origin: { ...origin } };\n }\n\n candidates.sort((a, b) => a.distance - b.distance);\n return { result: 'fixed', origin: { ...candidates[0].origin } };\n}\n","import { addVec3, lengthVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from './constants.js';\nimport { applyPmoveAccelerate } from './pmove.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nconst FLY_FRICTION_MULTIPLIER = 1.5;\nconst BUTTON_VERTICAL_SCALE = 0.5;\nconst DEFAULT_OVERBOUNCE = 1.01;\n\nexport interface FlyMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly frametime: number;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly pmMaxSpeed: number;\n readonly pmAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly doclip: boolean;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly trace?: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport type FlyMoveResult = StepSlideMoveOutcome;\n\n/**\n * Pure translation of PM_FlyMove from rerelease `p_move.cpp`: applies the\n * spectator/noclip friction and acceleration rules, then either advances the\n * origin freely or resolves movement through `stepSlideMove` when clipping is\n * requested. This keeps the spectator and noclip physics deterministic between\n * the client and server.\n */\nexport function applyPmoveFlyMove(params: FlyMoveParams): FlyMoveResult {\n const {\n origin,\n cmd,\n frametime,\n pmFriction,\n pmStopSpeed,\n pmMaxSpeed,\n pmAccelerate,\n pmWaterSpeed,\n doclip,\n forward,\n right,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n let velocity = applyFlyFriction({ velocity: params.velocity, pmFriction, pmStopSpeed, frametime });\n\n const wishdirVelocity = buildFlyWishVelocity({\n cmd,\n forward,\n right,\n pmMaxSpeed,\n pmWaterSpeed,\n });\n\n if (wishdirVelocity.wishspeed > 0) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wishdirVelocity.wishdir,\n wishspeed: wishdirVelocity.accelSpeed,\n accel: pmAccelerate,\n frametime,\n });\n }\n\n if (!doclip) {\n const originDelta = scaleVec3(velocity, frametime);\n const nextOrigin = addVec3(origin, originDelta);\n return {\n origin: nextOrigin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: velocity.x === 0 && velocity.y === 0 && velocity.z === 0,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n if (!trace || !mins || !maxs) {\n throw new Error('applyPmoveFlyMove: doclip=true requires trace/mins/maxs');\n }\n\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n overbounce,\n trace,\n mins,\n maxs,\n stepSize,\n maxBumps,\n maxClipPlanes,\n });\n}\n\ninterface FlyFrictionParams {\n readonly velocity: Vec3;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly frametime: number;\n}\n\nfunction applyFlyFriction(params: FlyFrictionParams): Vec3 {\n const { velocity, pmFriction, pmStopSpeed, frametime } = params;\n const speed = lengthVec3(velocity);\n\n if (speed < 1) {\n return { x: 0, y: 0, z: 0 };\n }\n\n const friction = pmFriction * FLY_FRICTION_MULTIPLIER;\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const drop = control * friction * frametime;\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n return scaleVec3(velocity, newspeed / speed);\n}\n\ninterface FlyWishVelocityParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmMaxSpeed: number;\n readonly pmWaterSpeed: number;\n}\n\ninterface FlyWishVelocityResult {\n readonly wishdir: Vec3;\n readonly wishspeed: number;\n readonly accelSpeed: number;\n}\n\nfunction buildFlyWishVelocity(params: FlyWishVelocityParams): FlyWishVelocityResult {\n const { cmd, forward, right, pmMaxSpeed, pmWaterSpeed } = params;\n\n const forwardNorm = normalizeVec3(forward);\n const rightNorm = normalizeVec3(right);\n\n const wishvel = {\n x: forwardNorm.x * cmd.forwardmove + rightNorm.x * cmd.sidemove,\n y: forwardNorm.y * cmd.forwardmove + rightNorm.y * cmd.sidemove,\n z: forwardNorm.z * cmd.forwardmove + rightNorm.z * cmd.sidemove,\n } satisfies Vec3;\n\n let adjusted = wishvel;\n const buttons = cmd.buttons ?? 0;\n\n if (buttons & PlayerButton.Jump) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n if (buttons & PlayerButton.Crouch) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: -pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n let wishspeed = lengthVec3(adjusted);\n let wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n adjusted = scaleVec3(adjusted, scale);\n wishspeed = pmMaxSpeed;\n wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n }\n\n const accelSpeed = wishspeed * 2;\n\n return { wishdir, wishspeed, accelSpeed };\n}\n","import { CONTENTS_LADDER, CONTENTS_NONE, CONTENTS_NO_WATERJUMP } from '../bsp/contents.js';\nimport { addVec3, lengthSquaredVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, PmFlag, type PmFlags, addPmFlag, removePmFlag, WaterLevel } from './constants.js';\nimport { stepSlideMove } from './slide.js';\nimport type { PmoveCmd, PmovePointContentsFn, PmoveTraceFn } from './types.js';\nimport { getWaterLevel } from './water.js';\n\nconst LADDER_TRACE_DISTANCE = 1;\nconst WATERJUMP_FORWARD_CHECK = 40;\nconst WATERJUMP_FORWARD_SPEED = 50;\nconst WATERJUMP_UPWARD_SPEED = 350;\nconst WATERJUMP_PM_TIME = 2048;\nconst WATERJUMP_SIM_STEP = 0.1;\nconst WATERJUMP_BASE_GRAVITY = 800;\nconst WATERJUMP_MAX_STEPS = 50;\nconst GROUND_NORMAL_THRESHOLD = 0.7;\nconst WATERJUMP_STEP_TOLERANCE = 18;\nconst DEFAULT_OVERBOUNCE = 1.01;\nconst WATERJUMP_DOWN_PROBE = 2;\n\nexport interface SpecialMovementParams {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly gravity: number;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n readonly onGround: boolean;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport interface SpecialMovementResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly velocity: Vec3;\n readonly performedWaterJump: boolean;\n}\n\n/**\n * Mirrors the ladder detection and water-jump probing logic from\n * `PM_CheckSpecialMovement` in `rerelease/p_move.cpp`. The helper clears and\n * re-adds the ladder flag based on nearby CONTENTS_LADDER brushes, then\n * simulates a potential water jump by firing the same 40-unit probe and\n * step-slide loop the C++ uses before committing to the upward velocity.\n */\nexport function checkSpecialMovement(params: SpecialMovementParams): SpecialMovementResult {\n const {\n pmFlags: initialFlags,\n pmTime: initialPmTime,\n waterlevel,\n watertype,\n gravity,\n cmd,\n forward,\n origin,\n velocity: initialVelocity,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n onGround,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize = WATERJUMP_STEP_TOLERANCE,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n if (initialPmTime > 0) {\n return { pmFlags: initialFlags, pmTime: initialPmTime, velocity: initialVelocity, performedWaterJump: false };\n }\n\n let pmFlags = removePmFlag(initialFlags, PmFlag.OnLadder);\n let pmTime = initialPmTime;\n let velocity = initialVelocity;\n\n const flatforward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n const hasForward = lengthSquaredVec3(flatforward) > 0;\n\n if (waterlevel < WaterLevel.Waist && hasForward) {\n const ladderEnd = addVec3(origin, scaleVec3(flatforward, LADDER_TRACE_DISTANCE));\n const ladderTrace = trace(origin, ladderEnd, mins, maxs);\n const contents = ladderTrace.contents ?? CONTENTS_NONE;\n\n if (ladderTrace.fraction < 1 && (contents & CONTENTS_LADDER) !== 0) {\n pmFlags = addPmFlag(pmFlags, PmFlag.OnLadder);\n }\n }\n\n if (gravity === 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (((cmd.buttons ?? 0) & PlayerButton.Jump) === 0 && cmd.forwardmove <= 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (waterlevel !== WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if ((watertype & CONTENTS_NO_WATERJUMP) !== 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (!hasForward) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const forwardCheckEnd = addVec3(origin, scaleVec3(flatforward, WATERJUMP_FORWARD_CHECK));\n const forwardTrace = trace(origin, forwardCheckEnd, mins, maxs);\n\n if (\n forwardTrace.fraction === 1 ||\n !forwardTrace.planeNormal ||\n forwardTrace.planeNormal.z >= GROUND_NORMAL_THRESHOLD\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n let simVelocity: Vec3 = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n };\n\n let simOrigin = origin;\n let hasTime = true;\n const stepCount = computeWaterJumpSteps(gravity);\n\n for (let i = 0; i < stepCount; i++) {\n simVelocity = { x: simVelocity.x, y: simVelocity.y, z: simVelocity.z - gravity * WATERJUMP_SIM_STEP };\n if (simVelocity.z < 0) {\n hasTime = false;\n }\n\n const move = stepSlideMove({\n origin: simOrigin,\n velocity: simVelocity,\n frametime: WATERJUMP_SIM_STEP,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n simOrigin = move.origin;\n simVelocity = move.velocity;\n }\n\n const downEnd = addVec3(simOrigin, { x: 0, y: 0, z: -WATERJUMP_DOWN_PROBE });\n const downTrace = trace(simOrigin, downEnd, mins, maxs);\n\n if (\n downTrace.fraction === 1 ||\n !downTrace.planeNormal ||\n downTrace.planeNormal.z < GROUND_NORMAL_THRESHOLD ||\n downTrace.endpos.z < origin.z\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (onGround && Math.abs(origin.z - downTrace.endpos.z) <= stepSize) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const landingWater = getWaterLevel({ origin: downTrace.endpos, mins, viewheight, pointContents });\n if (landingWater.waterlevel >= WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeWaterJump);\n pmTime = WATERJUMP_PM_TIME;\n velocity = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n } satisfies Vec3;\n\n return { pmFlags, pmTime, velocity, performedWaterJump: true };\n}\n\nfunction computeWaterJumpSteps(gravity: number): number {\n if (gravity === 0) {\n return 0;\n }\n\n const scaled = Math.floor(10 * (WATERJUMP_BASE_GRAVITY / gravity));\n if (scaled <= 0) {\n return 0;\n }\n return Math.min(WATERJUMP_MAX_STEPS, scaled);\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { fixStuckObjectGeneric } from './stuck.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst SNAP_OFFSETS = [0, -1, 1] as const;\n\nexport interface GoodPositionParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nexport function goodPosition(params: GoodPositionParams): boolean {\n const { origin, mins, maxs, trace } = params;\n const result = trace(origin, origin, mins, maxs);\n return result.allsolid ? false : true;\n}\n\nexport type SnapResolution = 'unchanged' | 'fixed' | 'reverted';\n\nexport interface SnapPositionParams extends GoodPositionParams {\n readonly velocity: Vec3;\n readonly previousOrigin: Vec3;\n}\n\nexport interface SnapPositionResult {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly resolution: SnapResolution;\n}\n\n/**\n * Pure translation of PM_SnapPosition from rerelease `p_move.cpp`.\n * Attempts to keep the caller's origin in a valid location by first\n * checking the current origin against collision traces, then falling\n * back to the shared `fixStuckObjectGeneric` helper before finally\n * reverting to the provided previous origin when no fix is possible.\n */\nexport function snapPosition(params: SnapPositionParams): SnapPositionResult {\n const { origin, velocity, mins, maxs, previousOrigin, trace } = params;\n\n if (goodPosition({ origin, mins, maxs, trace })) {\n return { origin: { ...origin }, velocity: { ...velocity }, resolution: 'unchanged' };\n }\n\n const fix = fixStuckObjectGeneric({\n origin,\n mins,\n maxs,\n trace: (start, localMins, localMaxs, end) => trace(start, end, localMins, localMaxs),\n });\n\n if (fix.result === 'fixed' || fix.result === 'good-position') {\n return { origin: fix.origin, velocity: { ...velocity }, resolution: 'fixed' };\n }\n\n return { origin: { ...previousOrigin }, velocity: { ...velocity }, resolution: 'reverted' };\n}\n\nexport interface InitialSnapPositionParams extends GoodPositionParams {}\n\nexport interface InitialSnapPositionResult {\n readonly origin: Vec3;\n readonly snapped: boolean;\n}\n\n/**\n * Pure translation of PM_InitialSnapPosition from rerelease `p_move.cpp`.\n * Tries a 3x3x3 grid of +/-1 unit offsets around the base origin to find\n * a valid collision-free spot, mirroring the search order of the C++ code.\n */\nexport function initialSnapPosition(params: InitialSnapPositionParams): InitialSnapPositionResult {\n const { origin, mins, maxs, trace } = params;\n\n for (const oz of SNAP_OFFSETS) {\n for (const oy of SNAP_OFFSETS) {\n for (const ox of SNAP_OFFSETS) {\n const candidate = { x: origin.x + ox, y: origin.y + oy, z: origin.z + oz } satisfies Vec3;\n if (goodPosition({ origin: candidate, mins, maxs, trace })) {\n const snapped = ox !== 0 || oy !== 0 || oz !== 0;\n return { origin: candidate, snapped };\n }\n }\n }\n }\n\n return { origin: { ...origin }, snapped: false };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { angleVectors, type AngleVectorsResult } from '../math/angles.js';\nimport { PmFlag, type PmFlags } from './constants.js';\n\nexport interface ClampViewAnglesParams {\n readonly pmFlags: PmFlags;\n readonly cmdAngles: Vec3;\n readonly deltaAngles: Vec3;\n}\n\nexport interface ClampViewAnglesResult extends AngleVectorsResult {\n readonly viewangles: Vec3;\n}\n\nfunction addAngles(cmdAngles: Vec3, deltaAngles: Vec3): Vec3 {\n return {\n x: cmdAngles.x + deltaAngles.x,\n y: cmdAngles.y + deltaAngles.y,\n z: cmdAngles.z + deltaAngles.z,\n } satisfies Vec3;\n}\n\nfunction clampPitch(pitch: number): number {\n if (pitch > 89 && pitch < 180) {\n return 89;\n }\n if (pitch < 271 && pitch >= 180) {\n return 271;\n }\n return pitch;\n}\n\n/**\n * Pure translation of `PM_ClampAngles` from `rerelease/p_move.cpp`. The helper\n * fuses the latest command angles with the stored delta, applies the teleport\n * pitch/roll reset, enforces the ±90° pitch window, and returns the resulting\n * axis vectors that the C version stored in `pml.forward/right/up`.\n */\nexport function clampViewAngles(params: ClampViewAnglesParams): ClampViewAnglesResult {\n const { pmFlags, cmdAngles, deltaAngles } = params;\n\n let viewangles: Vec3;\n\n if ((pmFlags & PmFlag.TimeTeleport) !== 0) {\n viewangles = {\n x: 0,\n y: cmdAngles.y + deltaAngles.y,\n z: 0,\n } satisfies Vec3;\n } else {\n viewangles = addAngles(cmdAngles, deltaAngles);\n viewangles = { ...viewangles, x: clampPitch(viewangles.x) };\n }\n\n const vectors = angleVectors(viewangles);\n return { viewangles, ...vectors };\n}\n","import { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n readonly sequence: number;\n readonly lightlevel: number;\n readonly impulse: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\n}\n","\nexport enum ServerCommand {\n bad = 0,\n\n // these ops are known to the game dll\n muzzleflash = 1,\n muzzleflash2 = 2,\n temp_entity = 3,\n layout = 4,\n inventory = 5,\n\n // the rest are private to the client and server\n nop = 6,\n disconnect = 7,\n reconnect = 8,\n sound = 9, // <see code>\n print = 10, // [byte] id [string] null terminated string\n stufftext = 11, // [string] stuffed into client's console buffer, should be \\n terminated\n serverdata = 12, // [long] protocol ...\n configstring = 13, // [short] [string]\n spawnbaseline = 14,\n centerprint = 15, // [string] to put in center of the screen\n download = 16, // [short] size [size bytes]\n playerinfo = 17, // variable\n packetentities = 18, // [...]\n deltapacketentities = 19, // [...]\n frame = 20,\n splitclient = 21,\n configblast = 22,\n spawnbaselineblast = 23,\n level_restart = 24,\n damage = 25,\n locprint = 26,\n fog = 27,\n waitingforplayers = 28,\n bot_chat = 29,\n poi = 30,\n help_path = 31,\n muzzleflash3 = 32,\n achievement = 33\n}\n\nexport enum ClientCommand {\n bad = 0,\n nop = 1,\n move = 2, // [[usercmd_t]\n userinfo = 3, // [[userinfo string]\n stringcmd = 4 // [string] message\n}\n","\n// Temp entity constants from Quake 2\nexport enum TempEntity {\n GUNSHOT = 0,\n BLOOD = 1,\n BLASTER = 2,\n RAILTRAIL = 3,\n SHOTGUN = 4,\n EXPLOSION1 = 5,\n EXPLOSION2 = 6,\n ROCKET_EXPLOSION = 7,\n GRENADE_EXPLOSION = 8,\n SPARKS = 9,\n SPLASH = 10,\n BUBBLETRAIL = 11,\n SCREEN_SPARKS = 12,\n SHIELD_SPARKS = 13,\n BULLET_SPARKS = 14,\n LASER_SPARKS = 15,\n PARASITE_ATTACK = 16,\n ROCKET_EXPLOSION_WATER = 17,\n GRENADE_EXPLOSION_WATER = 18,\n MEDIC_CABLE_ATTACK = 19,\n BFG_EXPLOSION = 20,\n BFG_BIGEXPLOSION = 21,\n BOSSTPORT = 22,\n BFG_LASER = 23,\n GRAPPLE_CABLE = 24,\n WELDING_SPARKS = 25,\n GREENBLOOD = 26,\n BLUEHYPERBLASTER = 27,\n PLASMA_EXPLOSION = 28,\n TUNNEL_SPARKS = 29,\n // ROGUE\n BLASTER2 = 30,\n RAILTRAIL2 = 31,\n FLAME = 32,\n LIGHTNING = 33,\n DEBUGTRAIL = 34,\n PLAIN_EXPLOSION = 35,\n FLASHLIGHT = 36,\n FORCEWALL = 37,\n HEATBEAM = 38,\n MONSTER_HEATBEAM = 39,\n STEAM = 40,\n BUBBLETRAIL2 = 41,\n MOREBLOOD = 42,\n HEATBEAM_SPARKS = 43,\n HEATBEAM_STEAM = 44,\n CHAINFIST_SMOKE = 45,\n ELECTRIC_SPARKS = 46,\n TRACKER_EXPLOSION = 47,\n TELEPORT_EFFECT = 48,\n DBALL_GOAL = 49,\n WIDOWBEAMOUT = 50,\n NUKEBLAST = 51,\n WIDOWSPLASH = 52,\n EXPLOSION1_BIG = 53,\n EXPLOSION1_NP = 54,\n FLECHETTE = 55,\n BLUEHYPERBLASTER_KEX = 56,\n BFG_ZAP = 57,\n BERSERK_SLAM = 58,\n GRAPPLE_CABLE_2 = 59,\n POWER_SPLASH = 60,\n LIGHTNING_BEAM = 61,\n EXPLOSION1_NL = 62,\n EXPLOSION2_NL = 63\n}\n","\nexport const MAX_CHALLENGES = 1024;\nexport const MAX_PACKET_ENTITIES = 256; // Standard Q2 value\nexport const UPDATE_BACKUP = 16;\nexport const CMD_BACKUP = 64;\nexport const MAX_INFO_STRING = 512;\nexport const MAX_MSGLEN = 1400; // MTU safe limit\n\n// Muzzle Flash Constants\nexport const MZ_BLASTER = 0;\nexport const MZ_MACHINEGUN = 1;\nexport const MZ_SHOTGUN = 2;\nexport const MZ_CHAINGUN1 = 3;\nexport const MZ_CHAINGUN2 = 4;\nexport const MZ_CHAINGUN3 = 5;\nexport const MZ_RAILGUN = 6;\nexport const MZ_ROCKET = 7;\nexport const MZ_GRENADE = 8;\nexport const MZ_LOGIN = 9;\nexport const MZ_LOGOUT = 10;\nexport const MZ_SSHOTGUN = 11;\nexport const MZ_BFG = 12;\nexport const MZ_HYPERBLASTER = 13;\n\n// Xatrix / Rogue Extensions\nexport const MZ_IONRIPPER = 16;\nexport const MZ_BLUEHYPERBLASTER = 17;\nexport const MZ_PHALANX = 18;\nexport const MZ_BFG2 = 19;\nexport const MZ_PHALANX2 = 20;\nexport const MZ_ETF_RIFLE = 30;\nexport const MZ_PROX = 31;\nexport const MZ_ETF_RIFLE_2 = 32;\nexport const MZ_HEATBEAM = 33;\nexport const MZ_BLASTER2 = 34;\nexport const MZ_TRACKER = 35;\nexport const MZ_NUKE1 = 36;\nexport const MZ_NUKE2 = 37;\nexport const MZ_NUKE4 = 38;\nexport const MZ_NUKE8 = 39;\n","// Matching rerelease/game.h:1584-1593\nexport enum LayoutFlags {\n LAYOUTS_LAYOUT = 1,\n LAYOUTS_INVENTORY = 2,\n LAYOUTS_HIDE_HUD = 4,\n LAYOUTS_INTERMISSION = 8,\n LAYOUTS_HELP = 16,\n LAYOUTS_HIDE_CROSSHAIR = 32\n}\n","\n/**\n * Helper to force a number into a signed 16-bit integer range (-32768 to 32767).\n * This mimics the behavior of casting to `short` in C++.\n */\nfunction toSigned16(val: number): number {\n return (val << 16) >> 16;\n}\n\n/**\n * Reads a 16-bit integer (unsigned) from the stats array at the given byte offset.\n * Mimics reading `*(uint16_t*)((uint8_t*)stats + byteOffset)` in Little Endian.\n */\nfunction readUint16LE(stats: number[], startIndex: number, byteOffset: number): number {\n // Determine which element(s) of the array we are accessing\n // stats is int16[], so each element is 2 bytes.\n // absolute byte offset from stats[startIndex]\n const elementIndex = Math.floor(byteOffset / 2);\n const isOdd = (byteOffset % 2) !== 0;\n\n // Access the array at the calculated index relative to startIndex\n const index = startIndex + elementIndex;\n\n // Read the primary element\n const val0 = stats[index] || 0; // Handle potentially undefined/uninitialized slots as 0\n\n if (!isOdd) {\n // Aligned access: just return the element as uint16\n return val0 & 0xFFFF;\n } else {\n // Unaligned access: High byte of val0 + Low byte of val1\n const val1 = stats[index + 1] || 0;\n\n // Low byte of result comes from High byte of val0\n const low = (val0 >>> 8) & 0xFF;\n // High byte of result comes from Low byte of val1\n const high = val1 & 0xFF;\n\n return (high << 8) | low;\n }\n}\n\n/**\n * Writes a 16-bit integer to the stats array at the given byte offset.\n * Mimics writing `*(uint16_t*)((uint8_t*)stats + byteOffset) = value` in Little Endian.\n */\nfunction writeUint16LE(stats: number[], startIndex: number, byteOffset: number, value: number): void {\n const elementIndex = Math.floor(byteOffset / 2);\n const isOdd = (byteOffset % 2) !== 0;\n const index = startIndex + elementIndex;\n\n // Ensure array has values at these indices to avoid NaN math\n if (stats[index] === undefined) stats[index] = 0;\n\n if (!isOdd) {\n // Aligned access: overwrite the element\n stats[index] = toSigned16(value);\n } else {\n // Unaligned access\n if (stats[index + 1] === undefined) stats[index + 1] = 0;\n\n const val0 = stats[index];\n const val1 = stats[index + 1];\n\n // We want to write `value` (which is Low byte `L_v` and High byte `H_v`)\n // into the bytes at `byteOffset` and `byteOffset + 1`.\n\n // Byte at `byteOffset` corresponds to High byte of `stats[index]`.\n // It should become `value & 0xFF` (L_v).\n // So `stats[index]` becomes `(Old_Low) | (L_v << 8)`.\n const newHigh0 = value & 0xFF;\n const newVal0 = (val0 & 0xFF) | (newHigh0 << 8);\n stats[index] = toSigned16(newVal0);\n\n // Byte at `byteOffset + 1` corresponds to Low byte of `stats[index+1]`.\n // It should become `(value >> 8) & 0xFF` (H_v).\n // So `stats[index+1]` becomes `(H_v) | (Old_High << 8)`.\n const newLow1 = (value >>> 8) & 0xFF;\n const newVal1 = newLow1 | (val1 & 0xFF00);\n stats[index + 1] = toSigned16(newVal1);\n }\n}\n\n/**\n * Packs a value into the stats array using a specific bit width.\n * Equivalent to C++ `set_compressed_integer`.\n *\n * @param stats The stats array (number[] representing int16s)\n * @param startIndex The index in the stats array where the packed region begins (e.g. STAT_AMMO_INFO_START)\n * @param id The ID of the item to set (0-based index within the packed region)\n * @param count The value to set\n * @param bitsPerValue Number of bits per item (e.g. 9 for ammo, 2 for powerups)\n */\nexport function setCompressedInteger(\n stats: number[],\n startIndex: number,\n id: number,\n count: number,\n bitsPerValue: number\n): void {\n const bitOffset = bitsPerValue * id;\n const byteOffset = Math.floor(bitOffset / 8);\n const bitShift = bitOffset % 8;\n const mask = ((1 << bitsPerValue) - 1) << bitShift;\n\n // Read the 16-bit word at the target byte address\n let base = readUint16LE(stats, startIndex, byteOffset);\n\n // Apply the mask and value\n // Note: (count << bitShift) might overflow 16 bits if we aren't careful,\n // but the mask will handle the high bits.\n // However, in JS, bitwise ops are 32-bit.\n // We need to ensure we only write back 16 bits.\n\n const valueToWrite = (base & ~mask) | ((count << bitShift) & mask);\n\n // Write the modified 16-bit word back\n writeUint16LE(stats, startIndex, byteOffset, valueToWrite & 0xFFFF);\n}\n\n/**\n * Unpacks a value from the stats array.\n * Equivalent to C++ `get_compressed_integer`.\n */\nexport function getCompressedInteger(\n stats: number[],\n startIndex: number,\n id: number,\n bitsPerValue: number\n): number {\n const bitOffset = bitsPerValue * id;\n const byteOffset = Math.floor(bitOffset / 8);\n const bitShift = bitOffset % 8;\n const mask = ((1 << bitsPerValue) - 1) << bitShift;\n\n const base = readUint16LE(stats, startIndex, byteOffset);\n\n return (base & mask) >>> bitShift;\n}\n","/**\n * Powerup identifiers shared across game and cgame.\n * Reference: rerelease/g_items.cpp, game/src/inventory/playerInventory.ts\n */\n\nexport enum PowerupId {\n QuadDamage = 'quad',\n Invulnerability = 'invulnerability',\n EnviroSuit = 'enviro_suit',\n Rebreather = 'rebreather',\n Silencer = 'silencer',\n // New additions for demo playback and extended support\n PowerScreen = 'power_screen',\n PowerShield = 'power_shield',\n QuadFire = 'quad_fire',\n Invisibility = 'invisibility',\n Bandolier = 'bandolier',\n AmmoPack = 'ammo_pack',\n IRGoggles = 'ir_goggles',\n DoubleDamage = 'double_damage',\n SphereVengeance = 'sphere_vengeance',\n SphereHunter = 'sphere_hunter',\n SphereDefender = 'sphere_defender',\n Doppelganger = 'doppelganger',\n TagToken = 'tag_token',\n TechResistance = 'tech_resistance',\n TechStrength = 'tech_strength',\n TechHaste = 'tech_haste',\n TechRegeneration = 'tech_regeneration',\n Flashlight = 'flashlight',\n Compass = 'compass',\n}\n","import { setCompressedInteger, getCompressedInteger } from './bitpack.js';\nimport { PowerupId } from '../items/powerups.js';\n\n// Matching rerelease/bg_local.h:196-262\nexport enum PlayerStat {\n STAT_HEALTH_ICON = 0,\n STAT_HEALTH,\n STAT_AMMO_ICON,\n STAT_AMMO,\n STAT_ARMOR_ICON,\n STAT_ARMOR,\n STAT_SELECTED_ICON,\n STAT_PICKUP_ICON,\n STAT_PICKUP_STRING,\n STAT_TIMER_ICON,\n STAT_TIMER,\n STAT_HELPICON,\n STAT_SELECTED_ITEM,\n STAT_LAYOUTS,\n STAT_FRAGS,\n STAT_FLASHES,\n STAT_CHASE,\n STAT_SPECTATOR,\n\n // CTF Stats (Rerelease/KEX)\n STAT_CTF_TEAM1_PIC = 18,\n STAT_CTF_TEAM1_CAPS = 19,\n STAT_CTF_TEAM2_PIC = 20,\n STAT_CTF_TEAM2_CAPS = 21,\n STAT_CTF_FLAG_PIC = 22,\n STAT_CTF_JOINED_TEAM1_PIC = 23,\n STAT_CTF_JOINED_TEAM2_PIC = 24,\n STAT_CTF_TEAM1_HEADER = 25,\n STAT_CTF_TEAM2_HEADER = 26,\n STAT_CTF_TECH = 27,\n STAT_CTF_ID_VIEW = 28,\n STAT_CTF_MATCH = 29,\n STAT_CTF_ID_VIEW_COLOR = 30,\n STAT_CTF_TEAMINFO = 31,\n\n // Rerelease additions\n STAT_WEAPONS_OWNED_1 = 32,\n STAT_WEAPONS_OWNED_2 = 33,\n\n // Ammo counts (start index)\n STAT_AMMO_INFO_START = 34,\n // Calculated below, but enum needs literal or constant if we want to use it as type.\n // However, for TS Enum, we can just define start.\n\n // Powerups start after Ammo.\n // AMMO_MAX=12, 9 bits each -> 108 bits -> 7 int16s.\n // 34 + 7 = 41.\n STAT_POWERUP_INFO_START = 41,\n\n // Keys and other KEX stats (Start after Powerups)\n // POWERUP_MAX=23, 2 bits each -> 46 bits -> 3 int16s.\n // 41 + 3 = 44.\n STAT_KEY_A = 44,\n STAT_KEY_B = 45,\n STAT_KEY_C = 46,\n\n STAT_ACTIVE_WHEEL_WEAPON = 47,\n STAT_COOP_RESPAWN = 48,\n STAT_LIVES = 49,\n STAT_HIT_MARKER = 50,\n STAT_SELECTED_ITEM_NAME = 51,\n STAT_HEALTH_BARS = 52,\n STAT_ACTIVE_WEAPON = 53,\n\n STAT_LAST\n}\n\n// Constants for bit packing logic\nexport const AMMO_MAX = 12;\nexport const NUM_BITS_FOR_AMMO = 9;\nexport const NUM_AMMO_STATS = Math.ceil((AMMO_MAX * NUM_BITS_FOR_AMMO) / 16); // 7\n\nexport const POWERUP_MAX = 23; // Adjusted to include TechRegeneration (index 22)\nexport const NUM_BITS_FOR_POWERUP = 2;\nexport const NUM_POWERUP_STATS = Math.ceil((POWERUP_MAX * NUM_BITS_FOR_POWERUP) / 16); // 3\n\n// Powerup ID mapping from string to C++ integer index (powerup_t in bg_local.h)\nconst POWERUP_STAT_MAP: Partial<Record<PowerupId, number>> = {\n [PowerupId.PowerScreen]: 0,\n [PowerupId.PowerShield]: 1,\n // 2 is POWERUP_AM_BOMB (not in PowerupId?)\n [PowerupId.QuadDamage]: 3,\n [PowerupId.QuadFire]: 4,\n [PowerupId.Invulnerability]: 5,\n [PowerupId.Invisibility]: 6,\n [PowerupId.Silencer]: 7,\n [PowerupId.Rebreather]: 8,\n [PowerupId.EnviroSuit]: 9,\n [PowerupId.Bandolier]: 10, // Placeholder/Map mismatch handling?\n [PowerupId.AmmoPack]: 10, // Original reused indices or had gaps?\n [PowerupId.IRGoggles]: 11,\n [PowerupId.DoubleDamage]: 12,\n [PowerupId.SphereVengeance]: 13,\n [PowerupId.SphereHunter]: 14,\n [PowerupId.SphereDefender]: 15,\n [PowerupId.Doppelganger]: 16,\n [PowerupId.Flashlight]: 17,\n [PowerupId.Compass]: 18,\n [PowerupId.TechResistance]: 19,\n [PowerupId.TechStrength]: 20,\n [PowerupId.TechHaste]: 21,\n [PowerupId.TechRegeneration]: 22,\n // Add missing mappings to avoid runtime lookups failing for new types\n [PowerupId.TagToken]: -1,\n};\n\n// 9 bits for ammo count\nexport function G_SetAmmoStat(stats: number[], ammoId: number, count: number): void {\n if (ammoId < 0 || ammoId >= AMMO_MAX) return;\n\n // Clamp count to 9 bits (0-511)\n let val = count;\n if (val > 511) val = 511;\n if (val < 0) val = 0;\n\n setCompressedInteger(stats, PlayerStat.STAT_AMMO_INFO_START, ammoId, val, NUM_BITS_FOR_AMMO);\n}\n\nexport function G_GetAmmoStat(stats: number[], ammoId: number): number {\n if (ammoId < 0 || ammoId >= AMMO_MAX) return 0;\n return getCompressedInteger(stats, PlayerStat.STAT_AMMO_INFO_START, ammoId, NUM_BITS_FOR_AMMO);\n}\n\n// 2 bits for powerup active/inactive state\nexport function G_SetPowerupStat(stats: number[], powerupId: PowerupId | number, val: number): void {\n let index: number | undefined;\n\n if (typeof powerupId === 'number') {\n index = powerupId;\n } else {\n index = POWERUP_STAT_MAP[powerupId];\n }\n\n if (index === undefined || index < 0 || index >= POWERUP_MAX) return;\n\n // Clamp value to 2 bits (0-3)\n let safeVal = val;\n if (safeVal > 3) safeVal = 3;\n if (safeVal < 0) safeVal = 0;\n\n setCompressedInteger(stats, PlayerStat.STAT_POWERUP_INFO_START, index, safeVal, NUM_BITS_FOR_POWERUP);\n}\n\nexport function G_GetPowerupStat(stats: number[], powerupId: PowerupId | number): number {\n let index: number | undefined;\n\n if (typeof powerupId === 'number') {\n index = powerupId;\n } else {\n index = POWERUP_STAT_MAP[powerupId];\n }\n\n if (index === undefined || index < 0 || index >= POWERUP_MAX) return 0;\n\n return getCompressedInteger(stats, PlayerStat.STAT_POWERUP_INFO_START, index, NUM_BITS_FOR_POWERUP);\n}\n","import { BinaryWriter } from '../io/binaryWriter.js';\nimport { UserCommand } from './usercmd.js';\n\nexport function writeUserCommand(writer: BinaryWriter, cmd: UserCommand): void {\n // msec (byte)\n writer.writeByte(cmd.msec);\n\n // buttons (byte)\n writer.writeByte(cmd.buttons);\n\n // angles (short * 3) - Scaled 360 -> 65536\n writer.writeAngle16(cmd.angles.x);\n writer.writeAngle16(cmd.angles.y);\n writer.writeAngle16(cmd.angles.z);\n\n // forwardmove (short)\n writer.writeShort(cmd.forwardmove);\n\n // sidemove (short)\n writer.writeShort(cmd.sidemove);\n\n // upmove (short)\n writer.writeShort(cmd.upmove);\n\n // impulse (byte)\n writer.writeByte(0); // TODO: Impulse in UserCommand\n\n // lightlevel (byte)\n writer.writeByte(0); // TODO: Lightlevel\n}\n","export enum RenderFx {\n MinLight = 1,\n ViewerModel = 2,\n WeaponModel = 4,\n FullBright = 8,\n DepthHack = 16,\n Translucent = 32,\n FrameLerp = 64,\n Beam = 128,\n CustomLight = 256,\n Glow = 512,\n ShellRed = 1024,\n ShellGreen = 2048,\n ShellBlue = 4096,\n IrVisible = 32768,\n ShellDouble = 65536,\n ShellHalfDam = 131072,\n MinLightPlus = 262144,\n ExtraLight = 524288,\n BeamLightning = 1048576,\n Flashlight = 2097152, // 1 << 21\n}\n","// Quake 2 CRC implementation\n// Ported from qcommon/crc.c\n\nconst crc_table: number[] = [\n 0x00, 0x91, 0xe3, 0x72, 0x07, 0x96, 0xe4, 0x75, 0x0e, 0x9f, 0xed, 0x7c, 0x09, 0x98, 0xea, 0x7b,\n 0x1c, 0x8d, 0xff, 0x6e, 0x1b, 0x8a, 0xf8, 0x69, 0x12, 0x83, 0xf1, 0x60, 0x15, 0x84, 0xf6, 0x67,\n 0x38, 0xa9, 0xdb, 0x4a, 0x3f, 0xae, 0xdc, 0x4d, 0x36, 0xa7, 0xd5, 0x44, 0x31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, 0x39, 0x4b, 0xda, 0xaf, 0x3e, 0x4c, 0xdd, 0xa6, 0x37, 0x45, 0xd4, 0xa1, 0x30, 0x42, 0xd3,\n 0xb4, 0x25, 0x56, 0xc7, 0xb3, 0x22, 0x50, 0xc1, 0xba, 0x2b, 0x59, 0xc8, 0xbd, 0x2c, 0x5e, 0xcf\n];\n\n/**\n * Calculates 8-bit CRC for the given data\n */\nexport function crc8(data: Uint8Array): number {\n let crc = 0;\n for (let i = 0; i < data.length; i++) {\n crc = crc_table[(crc ^ data[i]) & 0xff];\n }\n return crc;\n}\n","// Source: game.h (Quake 2)\nexport enum EntityEffects {\n Rotate = 0x00000004,\n Gib = 0x00000008,\n RotateScript = 0x00000010,\n Blaster = 0x00000020,\n Rocket = 0x00000040,\n Grenade = 0x00000080,\n HyperBlaster = 0x00000100,\n Bfg = 0x00000200,\n ColorShell = 0x00000400,\n Powerscreen = 0x00000800,\n Anim01 = 0x00001000,\n Anim23 = 0x00002000,\n AnimAll = 0x00004000,\n AnimAllFast = 0x00008000,\n Quad = 0x00010000,\n Pent = 0x00020000,\n Explosion = 0x00040000,\n Teleport = 0x00080000,\n Flag1 = 0x00100000,\n Flag2 = 0x00200000,\n Boomerang = 0x00400000,\n Greengibs = 0x00800000,\n Bluehyperblaster = 0x01000000,\n Spinning = 0x02000000,\n Plasma = 0x04000000,\n Trap = 0x08000000,\n Tracker = 0x10000000,\n Double = 0x20000000,\n Sphinx = 0x40000000,\n TagTrail = 0x80000000,\n}\n","export enum EntityEvent {\n None = 0,\n ItemRespawn = 1,\n Footstep = 2,\n FallShort = 3,\n Fall = 4,\n FallFar = 5,\n PlayerTeleport = 6,\n OtherTeleport = 7,\n\n // [Paril-KEX]\n OtherFootstep = 8,\n LadderStep = 9,\n}\n","import { BinaryWriter } from '../io/index.js';\nimport { EntityState } from './entityState.js';\n\n// Constants matching packages/engine/src/demo/parser.ts\nexport const U_ORIGIN1 = (1 << 0);\nexport const U_ORIGIN2 = (1 << 1);\nexport const U_ANGLE2 = (1 << 2);\nexport const U_ANGLE3 = (1 << 3);\nexport const U_FRAME8 = (1 << 4);\nexport const U_EVENT = (1 << 5);\nexport const U_REMOVE = (1 << 6);\nexport const U_MOREBITS1 = (1 << 7);\n\nexport const U_NUMBER16 = (1 << 8);\nexport const U_ORIGIN3 = (1 << 9);\nexport const U_ANGLE1 = (1 << 10);\nexport const U_MODEL = (1 << 11);\nexport const U_RENDERFX8 = (1 << 12);\nexport const U_ALPHA = (1 << 13); // Rerelease: Alpha\nexport const U_EFFECTS8 = (1 << 14);\nexport const U_MOREBITS2 = (1 << 15);\n\nexport const U_SKIN8 = (1 << 16);\nexport const U_FRAME16 = (1 << 17);\nexport const U_RENDERFX16 = (1 << 18);\nexport const U_EFFECTS16 = (1 << 19);\nexport const U_MODEL2 = (1 << 20); // Rerelease\nexport const U_MODEL3 = (1 << 21); // Rerelease\nexport const U_MODEL4 = (1 << 22); // Rerelease\nexport const U_MOREBITS3 = (1 << 23);\n\nexport const U_OLDORIGIN = (1 << 24);\nexport const U_SKIN16 = (1 << 25);\nexport const U_SOUND = (1 << 26);\nexport const U_SOLID = (1 << 27);\nexport const U_SCALE = (1 << 28); // Rerelease\nexport const U_INSTANCE_BITS = (1 << 29); // Rerelease\nexport const U_LOOP_VOLUME = (1 << 30); // Rerelease\nexport const U_MOREBITS4 = 0x80000000 | 0; // Bit 31 (sign bit)\n\n// Rerelease Extension Bits (Byte 5 - High Bits)\nexport const U_LOOP_ATTENUATION_HIGH = (1 << 0);\nexport const U_OWNER_HIGH = (1 << 1);\nexport const U_OLD_FRAME_HIGH = (1 << 2);\n\n\n// A null state for new entities, used as a baseline for comparison.\nconst NULL_STATE: EntityState = {\n number: 0,\n origin: { x: 0, y: 0, z: 0 },\n angles: { x: 0, y: 0, z: 0 },\n modelIndex: 0,\n frame: 0,\n skinNum: 0,\n effects: 0,\n renderfx: 0,\n solid: 0,\n sound: 0,\n event: 0,\n alpha: 0,\n scale: 0,\n instanceBits: 0,\n loopVolume: 0,\n loopAttenuation: 0,\n owner: 0,\n oldFrame: 0,\n modelIndex2: 0,\n modelIndex3: 0,\n modelIndex4: 0\n};\n\n/**\n * Writes the remove bit for an entity.\n */\nexport function writeRemoveEntity(\n number: number,\n writer: BinaryWriter\n): void {\n let bits = U_REMOVE;\n\n if (number >= 256) {\n bits |= U_NUMBER16;\n }\n\n // Determine needed bytes for header (U_NUMBER16 is in bits 8-15)\n if (bits & 0xFF00) {\n bits |= U_MOREBITS1;\n }\n\n // Write Header\n writer.writeByte(bits & 0xFF);\n if (bits & U_MOREBITS1) {\n writer.writeByte((bits >> 8) & 0xFF);\n }\n\n // Write Number\n if (bits & U_NUMBER16) {\n writer.writeShort(number);\n } else {\n writer.writeByte(number);\n }\n}\n\n/**\n * Writes the delta between two entity states to a binary writer.\n */\nexport function writeDeltaEntity(\n from: EntityState,\n to: EntityState,\n writer: BinaryWriter,\n force: boolean,\n newEntity: boolean\n): void {\n let bits = 0;\n let bitsHigh = 0;\n\n // If this is a new entity, use a null baseline\n if (newEntity) {\n from = NULL_STATE;\n }\n\n // --- Compare fields and build the bitmask ---\n if (to.modelIndex !== from.modelIndex || force) {\n bits |= U_MODEL;\n }\n if (to.modelIndex2 !== from.modelIndex2 || force) {\n bits |= U_MODEL2;\n }\n if (to.modelIndex3 !== from.modelIndex3 || force) {\n bits |= U_MODEL3;\n }\n if (to.modelIndex4 !== from.modelIndex4 || force) {\n bits |= U_MODEL4;\n }\n\n if (to.origin.x !== from.origin.x || force) {\n bits |= U_ORIGIN1;\n }\n if (to.origin.y !== from.origin.y || force) {\n bits |= U_ORIGIN2;\n }\n if (to.origin.z !== from.origin.z || force) {\n bits |= U_ORIGIN3;\n }\n if (to.angles.x !== from.angles.x || force) {\n bits |= U_ANGLE1;\n }\n if (to.angles.y !== from.angles.y || force) {\n bits |= U_ANGLE2;\n }\n if (to.angles.z !== from.angles.z || force) {\n bits |= U_ANGLE3;\n }\n\n if (to.frame !== from.frame || force) {\n if (to.frame >= 256) bits |= U_FRAME16;\n else bits |= U_FRAME8;\n }\n\n if (to.skinNum !== from.skinNum || force) {\n if (to.skinNum >= 256) bits |= U_SKIN16;\n else bits |= U_SKIN8;\n }\n\n if (to.effects !== from.effects || force) {\n if (to.effects >= 256) bits |= U_EFFECTS16;\n else bits |= U_EFFECTS8;\n }\n\n if (to.renderfx !== from.renderfx || force) {\n if (to.renderfx >= 256) bits |= U_RENDERFX16;\n else bits |= U_RENDERFX8;\n }\n\n if (to.solid !== from.solid || force) {\n bits |= U_SOLID;\n }\n if (to.sound !== from.sound || force) {\n bits |= U_SOUND;\n }\n if (to.event !== from.event || force) {\n bits |= U_EVENT;\n }\n\n // Rerelease Fields\n if ((to.alpha !== from.alpha || force) && to.alpha !== undefined) {\n bits |= U_ALPHA;\n }\n if ((to.scale !== from.scale || force) && to.scale !== undefined) {\n bits |= U_SCALE;\n }\n if ((to.instanceBits !== from.instanceBits || force) && to.instanceBits !== undefined) {\n bits |= U_INSTANCE_BITS;\n }\n if ((to.loopVolume !== from.loopVolume || force) && to.loopVolume !== undefined) {\n bits |= U_LOOP_VOLUME;\n }\n\n // High Bits Fields\n if ((to.loopAttenuation !== from.loopAttenuation || force) && to.loopAttenuation !== undefined) {\n bitsHigh |= U_LOOP_ATTENUATION_HIGH;\n }\n if ((to.owner !== from.owner || force) && to.owner !== undefined) {\n bitsHigh |= U_OWNER_HIGH;\n }\n if ((to.oldFrame !== from.oldFrame || force) && to.oldFrame !== undefined) {\n bitsHigh |= U_OLD_FRAME_HIGH;\n }\n\n\n // Handle entity number\n if (to.number >= 256) {\n bits |= U_NUMBER16;\n }\n\n // Determine needed bytes for header\n\n // If we have high bits, we set U_MOREBITS4 on the 4th byte\n if (bitsHigh > 0) {\n bits |= U_MOREBITS4;\n }\n\n // Now calculate cascading flags\n if (bits & 0xFF000000) { // e.g. U_MOREBITS4 (bit 31) is here\n bits |= U_MOREBITS3;\n }\n if (bits & 0xFFFF0000) { // e.g. U_MOREBITS3 (bit 23) is here\n bits |= U_MOREBITS2;\n }\n if (bits & 0xFFFFFF00) { // e.g. U_MOREBITS2 (bit 15) is here\n bits |= U_MOREBITS1;\n }\n\n // Write Header\n writer.writeByte(bits & 0xFF);\n\n if (bits & U_MOREBITS1) {\n writer.writeByte((bits >> 8) & 0xFF);\n }\n if (bits & U_MOREBITS2) {\n writer.writeByte((bits >> 16) & 0xFF);\n }\n if (bits & U_MOREBITS3) {\n writer.writeByte((bits >> 24) & 0xFF);\n }\n if (bits & U_MOREBITS4) {\n writer.writeByte(bitsHigh & 0xFF);\n }\n\n // Write Number\n if (bits & U_NUMBER16) {\n writer.writeShort(to.number);\n } else {\n writer.writeByte(to.number);\n }\n\n // Write Fields in Order (matching NetworkMessageParser.parseDelta)\n if (bits & U_MODEL) writer.writeByte(to.modelIndex);\n if (bits & U_MODEL2) writer.writeByte(to.modelIndex2 ?? 0);\n if (bits & U_MODEL3) writer.writeByte(to.modelIndex3 ?? 0);\n if (bits & U_MODEL4) writer.writeByte(to.modelIndex4 ?? 0);\n\n if (bits & U_FRAME8) writer.writeByte(to.frame);\n if (bits & U_FRAME16) writer.writeShort(to.frame);\n\n if (bits & U_SKIN8) writer.writeByte(to.skinNum);\n if (bits & U_SKIN16) writer.writeShort(to.skinNum);\n\n if (bits & U_EFFECTS8) writer.writeByte(to.effects);\n if (bits & U_EFFECTS16) writer.writeShort(to.effects);\n\n if (bits & U_RENDERFX8) writer.writeByte(to.renderfx);\n if (bits & U_RENDERFX16) writer.writeShort(to.renderfx);\n\n if (bits & U_ORIGIN1) writer.writeCoord(to.origin.x);\n if (bits & U_ORIGIN2) writer.writeCoord(to.origin.y);\n if (bits & U_ORIGIN3) writer.writeCoord(to.origin.z);\n\n if (bits & U_ANGLE1) writer.writeAngle(to.angles.x);\n if (bits & U_ANGLE2) writer.writeAngle(to.angles.y);\n if (bits & U_ANGLE3) writer.writeAngle(to.angles.z);\n\n if (bits & U_OLDORIGIN) {\n // Not implemented in EntityState usually, skip or zero\n // writer.writePos(to.old_origin);\n }\n\n if (bits & U_SOUND) writer.writeByte(to.sound ?? 0);\n\n if (bits & U_EVENT) writer.writeByte(to.event ?? 0);\n\n if (bits & U_SOLID) writer.writeShort(to.solid);\n\n // Rerelease Fields Writing\n if (bits & U_ALPHA) writer.writeByte(Math.floor((to.alpha ?? 0) * 255));\n if (bits & U_SCALE) writer.writeFloat(to.scale ?? 0);\n if (bits & U_INSTANCE_BITS) writer.writeLong(to.instanceBits ?? 0);\n if (bits & U_LOOP_VOLUME) writer.writeByte(Math.floor((to.loopVolume ?? 0) * 255));\n\n // High bits fields\n if (bitsHigh & U_LOOP_ATTENUATION_HIGH) writer.writeByte(Math.floor((to.loopAttenuation ?? 0) * 255));\n if (bitsHigh & U_OWNER_HIGH) writer.writeShort(to.owner ?? 0);\n if (bitsHigh & U_OLD_FRAME_HIGH) writer.writeShort(to.oldFrame ?? 0);\n}\n","import { BinaryWriter, Vec3 } from '../index.js';\n\nexport interface ProtocolPlayerState {\n pm_type: number;\n origin: Vec3;\n velocity: Vec3;\n pm_time: number;\n pm_flags: number;\n gravity: number;\n delta_angles: Vec3;\n viewoffset: Vec3;\n viewangles: Vec3;\n kick_angles: Vec3;\n gun_index: number;\n gun_frame: number;\n gun_offset: Vec3;\n gun_angles: Vec3;\n blend: number[]; // [r,g,b,a]\n fov: number;\n rdflags: number;\n stats: number[];\n\n // Optional / Extension fields if needed\n gunskin?: number;\n gunrate?: number;\n damage_blend?: number[];\n team_id?: number;\n}\n\n// Bitflags matching demo/parser.ts\nconst PS_M_TYPE = (1 << 0);\nconst PS_M_ORIGIN = (1 << 1);\nconst PS_M_VELOCITY = (1 << 2);\nconst PS_M_TIME = (1 << 3);\nconst PS_M_FLAGS = (1 << 4);\nconst PS_M_GRAVITY = (1 << 5);\nconst PS_M_DELTA_ANGLES = (1 << 6);\nconst PS_VIEWOFFSET = (1 << 7);\nconst PS_VIEWANGLES = (1 << 8);\nconst PS_KICKANGLES = (1 << 9);\nconst PS_BLEND = (1 << 10);\nconst PS_FOV = (1 << 11);\nconst PS_WEAPONINDEX = (1 << 12);\nconst PS_WEAPONFRAME = (1 << 13);\nconst PS_RDFLAGS = (1 << 14);\n\nexport function writePlayerState(writer: BinaryWriter, ps: ProtocolPlayerState): void {\n // Determine mask\n let mask = 0;\n\n if (ps.pm_type !== 0) mask |= PS_M_TYPE;\n if (ps.origin.x !== 0 || ps.origin.y !== 0 || ps.origin.z !== 0) mask |= PS_M_ORIGIN;\n if (ps.velocity.x !== 0 || ps.velocity.y !== 0 || ps.velocity.z !== 0) mask |= PS_M_VELOCITY;\n if (ps.pm_time !== 0) mask |= PS_M_TIME;\n if (ps.pm_flags !== 0) mask |= PS_M_FLAGS;\n if (ps.gravity !== 0) mask |= PS_M_GRAVITY;\n if (ps.delta_angles.x !== 0 || ps.delta_angles.y !== 0 || ps.delta_angles.z !== 0) mask |= PS_M_DELTA_ANGLES;\n if (ps.viewoffset.x !== 0 || ps.viewoffset.y !== 0 || ps.viewoffset.z !== 0) mask |= PS_VIEWOFFSET;\n if (ps.viewangles.x !== 0 || ps.viewangles.y !== 0 || ps.viewangles.z !== 0) mask |= PS_VIEWANGLES;\n if (ps.kick_angles.x !== 0 || ps.kick_angles.y !== 0 || ps.kick_angles.z !== 0) mask |= PS_KICKANGLES;\n if (ps.gun_index !== 0) mask |= PS_WEAPONINDEX;\n\n // Weapon frame includes offset/angles\n if (ps.gun_frame !== 0 ||\n ps.gun_offset.x !== 0 || ps.gun_offset.y !== 0 || ps.gun_offset.z !== 0 ||\n ps.gun_angles.x !== 0 || ps.gun_angles.y !== 0 || ps.gun_angles.z !== 0) {\n mask |= PS_WEAPONFRAME;\n }\n\n if (ps.blend && (ps.blend[0] !== 0 || ps.blend[1] !== 0 || ps.blend[2] !== 0 || ps.blend[3] !== 0)) {\n mask |= PS_BLEND;\n }\n\n if (ps.fov !== 0) mask |= PS_FOV;\n if (ps.rdflags !== 0) mask |= PS_RDFLAGS;\n\n // Stats mask calculation\n let statsMask = 0;\n // Only support first 32 stats for now\n for (let i = 0; i < 32; i++) {\n if (ps.stats[i] && ps.stats[i] !== 0) {\n statsMask |= (1 << i);\n }\n }\n\n // Write header\n writer.writeShort(mask);\n\n // Write fields\n if (mask & PS_M_TYPE) writer.writeByte(ps.pm_type);\n\n if (mask & PS_M_ORIGIN) {\n writer.writeShort(Math.round(ps.origin.x * 8));\n writer.writeShort(Math.round(ps.origin.y * 8));\n writer.writeShort(Math.round(ps.origin.z * 8));\n }\n\n if (mask & PS_M_VELOCITY) {\n writer.writeShort(Math.round(ps.velocity.x * 8));\n writer.writeShort(Math.round(ps.velocity.y * 8));\n writer.writeShort(Math.round(ps.velocity.z * 8));\n }\n\n if (mask & PS_M_TIME) writer.writeByte(ps.pm_time);\n if (mask & PS_M_FLAGS) writer.writeByte(ps.pm_flags);\n if (mask & PS_M_GRAVITY) writer.writeShort(ps.gravity);\n\n if (mask & PS_M_DELTA_ANGLES) {\n writer.writeShort(Math.round(ps.delta_angles.x * (32768 / 180)));\n writer.writeShort(Math.round(ps.delta_angles.y * (32768 / 180)));\n writer.writeShort(Math.round(ps.delta_angles.z * (32768 / 180)));\n }\n\n if (mask & PS_VIEWOFFSET) {\n writer.writeChar(Math.round(ps.viewoffset.x * 4));\n writer.writeChar(Math.round(ps.viewoffset.y * 4));\n writer.writeChar(Math.round(ps.viewoffset.z * 4));\n }\n\n if (mask & PS_VIEWANGLES) {\n writer.writeAngle16(ps.viewangles.x);\n writer.writeAngle16(ps.viewangles.y);\n writer.writeAngle16(ps.viewangles.z);\n }\n\n if (mask & PS_KICKANGLES) {\n writer.writeChar(Math.round(ps.kick_angles.x * 4));\n writer.writeChar(Math.round(ps.kick_angles.y * 4));\n writer.writeChar(Math.round(ps.kick_angles.z * 4));\n }\n\n if (mask & PS_WEAPONINDEX) writer.writeByte(ps.gun_index);\n\n if (mask & PS_WEAPONFRAME) {\n writer.writeByte(ps.gun_frame);\n writer.writeChar(Math.round(ps.gun_offset.x * 4));\n writer.writeChar(Math.round(ps.gun_offset.y * 4));\n writer.writeChar(Math.round(ps.gun_offset.z * 4));\n writer.writeChar(Math.round(ps.gun_angles.x * 4));\n writer.writeChar(Math.round(ps.gun_angles.y * 4));\n writer.writeChar(Math.round(ps.gun_angles.z * 4));\n }\n\n if (mask & PS_BLEND) {\n writer.writeByte(Math.round(ps.blend[0]));\n writer.writeByte(Math.round(ps.blend[1]));\n writer.writeByte(Math.round(ps.blend[2]));\n writer.writeByte(Math.round(ps.blend[3]));\n }\n\n if (mask & PS_FOV) writer.writeByte(ps.fov);\n if (mask & PS_RDFLAGS) writer.writeByte(ps.rdflags);\n\n // Write Stats\n writer.writeLong(statsMask);\n for (let i = 0; i < 32; i++) {\n if (statsMask & (1 << i)) {\n writer.writeShort(ps.stats[i]);\n }\n }\n}\n","\nimport { PmoveCmd, PmoveTraceFn } from './types.js';\nimport { Vec3 } from '../math/vec3.js';\n\nimport { applyPmoveAccelerate, applyPmoveFriction, buildAirGroundWish, buildWaterWish } from './pmove.js';\nimport { PlayerState } from '../protocol/player-state.js';\nimport { angleVectors } from '../math/angles.js';\nimport { MASK_WATER } from '../bsp/contents.js';\n\nconst FRAMETIME = 0.025;\n\n// Local definition to avoid dependency issues if constants.ts is missing\n// Matches packages/shared/src/pmove/constants.ts\nconst WaterLevel = {\n None: 0,\n Feet: 1,\n Waist: 2,\n Under: 3,\n} as const;\n\nconst categorizePosition = (state: PlayerState, trace: PmoveTraceFn): PlayerState => {\n const point = { ...state.origin };\n point.z -= 0.25;\n const traceResult = trace(state.origin, point);\n\n return {\n ...state,\n onGround: traceResult.fraction < 1,\n };\n};\n\nconst checkWater = (state: PlayerState, pointContents: (point: Vec3) => number): PlayerState => {\n const point = { ...state.origin };\n const { mins, maxs } = state;\n\n // Default to feet\n point.z = state.origin.z + mins.z + 1;\n\n const feetContents = pointContents(point);\n\n if (!(feetContents & MASK_WATER)) {\n return { ...state, waterLevel: WaterLevel.None, watertype: 0 };\n }\n\n let waterLevel: number = WaterLevel.Feet;\n let watertype = feetContents;\n\n // Check waist\n const waist = state.origin.z + (mins.z + maxs.z) * 0.5;\n point.z = waist;\n const waistContents = pointContents(point);\n\n if (waistContents & MASK_WATER) {\n waterLevel = WaterLevel.Waist;\n watertype = waistContents;\n\n // Check head (eyes)\n // Standard Quake 2 viewheight is 22. maxs.z is typically 32.\n // So eyes are roughly at origin.z + 22.\n // We'll use origin.z + 22 to check if eyes are underwater.\n // If viewheight was available in PlayerState, we'd use that.\n const head = state.origin.z + 22;\n point.z = head;\n const headContents = pointContents(point);\n\n if (headContents & MASK_WATER) {\n waterLevel = WaterLevel.Under;\n watertype = headContents;\n }\n }\n\n return { ...state, waterLevel, watertype };\n};\n\n\nexport const applyPmove = (\n state: PlayerState,\n cmd: PmoveCmd,\n trace: PmoveTraceFn,\n pointContents: (point: Vec3) => number\n): PlayerState => {\n let newState = { ...state };\n newState = categorizePosition(newState, trace);\n newState = checkWater(newState, pointContents);\n\n const { origin, velocity, onGround, waterLevel, viewAngles } = newState;\n\n // Calculate forward and right vectors from view angles\n // For water movement, use full view angles including pitch\n // For ground/air movement, reduce pitch influence by dividing by 3\n // See: rerelease/p_move.cpp lines 1538, 1686-1691, 800, 858\n const adjustedAngles = waterLevel >= 2\n ? viewAngles\n : {\n // For ground/air movement, reduce pitch influence (rerelease/p_move.cpp:1689)\n x: viewAngles.x > 180 ? (viewAngles.x - 360) / 3 : viewAngles.x / 3,\n y: viewAngles.y,\n z: viewAngles.z,\n };\n\n const { forward, right } = angleVectors(adjustedAngles);\n\n // Apply friction BEFORE acceleration to match original Quake 2 rerelease behavior\n // See: rerelease/src/game/player/pmove.c lines 1678 (PM_Friction) then 1693 (PM_AirMove->PM_Accelerate)\n const frictionedVelocity = applyPmoveFriction({\n velocity,\n frametime: FRAMETIME,\n onGround,\n groundIsSlick: false,\n onLadder: false,\n waterlevel: waterLevel,\n pmFriction: 6,\n pmStopSpeed: 100,\n pmWaterFriction: 1,\n });\n\n const wish = waterLevel >= 2\n ? buildWaterWish({\n forward,\n right,\n cmd,\n maxSpeed: 320,\n })\n : buildAirGroundWish({\n forward,\n right,\n cmd,\n maxSpeed: 320,\n });\n\n const finalVelocity = applyPmoveAccelerate({\n velocity: frictionedVelocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n // Water movement uses ground acceleration (10), not air acceleration (1)\n accel: (onGround || waterLevel >= 2) ? 10 : 1,\n frametime: FRAMETIME,\n });\n\n const traceResult = trace(origin, {\n x: origin.x + finalVelocity.x * FRAMETIME,\n y: origin.y + finalVelocity.y * FRAMETIME,\n z: origin.z + finalVelocity.z * FRAMETIME,\n });\n\n return {\n ...newState,\n origin: traceResult.endpos,\n velocity: finalVelocity,\n };\n};\n","import { Vec3 } from '../math/vec3.js';\nimport { ANORMS } from '../math/anorms.js';\n\nexport class BinaryStream {\n private view: DataView;\n private offset: number;\n private length: number;\n\n constructor(buffer: ArrayBuffer | Uint8Array) {\n if (buffer instanceof Uint8Array) {\n this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n } else {\n this.view = new DataView(buffer);\n }\n this.offset = 0;\n this.length = this.view.byteLength;\n }\n\n public getPosition(): number {\n return this.offset;\n }\n\n public getReadPosition(): number {\n return this.offset;\n }\n\n public getLength(): number {\n return this.length;\n }\n\n public getRemaining(): number {\n return this.length - this.offset;\n }\n\n public seek(position: number): void {\n if (position < 0 || position > this.length) {\n throw new Error(`Seek out of bounds: ${position} (length: ${this.length})`);\n }\n this.offset = position;\n }\n\n public setReadPosition(position: number): void {\n this.seek(position);\n }\n\n public hasMore(): boolean {\n return this.offset < this.length;\n }\n\n public hasBytes(count: number): boolean {\n return this.offset + count <= this.length;\n }\n\n public readChar(): number {\n const value = this.view.getInt8(this.offset);\n this.offset += 1;\n return value;\n }\n\n public readByte(): number {\n const value = this.view.getUint8(this.offset);\n this.offset += 1;\n return value;\n }\n\n public readShort(): number {\n const value = this.view.getInt16(this.offset, true);\n this.offset += 2;\n return value;\n }\n\n public readUShort(): number {\n const value = this.view.getUint16(this.offset, true);\n this.offset += 2;\n return value;\n }\n\n public readLong(): number {\n const value = this.view.getInt32(this.offset, true);\n this.offset += 4;\n return value;\n }\n\n public readULong(): number {\n const value = this.view.getUint32(this.offset, true);\n this.offset += 4;\n return value;\n }\n\n public readFloat(): number {\n const value = this.view.getFloat32(this.offset, true);\n this.offset += 4;\n return value;\n }\n\n public readString(): string {\n let str = '';\n while (this.offset < this.length) {\n const charCode = this.readChar();\n if (charCode === -1 || charCode === 0) {\n break;\n }\n str += String.fromCharCode(charCode);\n }\n return str;\n }\n\n public readStringLine(): string {\n let str = '';\n while (this.offset < this.length) {\n const charCode = this.readChar();\n if (charCode === -1 || charCode === 0 || charCode === 10) { // 10 is \\n\n break;\n }\n str += String.fromCharCode(charCode);\n }\n return str;\n }\n\n public readCoord(): number {\n return this.readShort() * (1.0 / 8.0);\n }\n\n public readAngle(): number {\n return this.readChar() * (360.0 / 256.0);\n }\n\n public readAngle16(): number {\n return (this.readShort() * 360.0) / 65536.0;\n }\n\n public readData(length: number): Uint8Array {\n if (this.offset + length > this.length) {\n throw new Error(`Read out of bounds: ${this.offset + length} (length: ${this.length})`);\n }\n const data = new Uint8Array(this.view.buffer, this.view.byteOffset + this.offset, length);\n this.offset += length;\n // Return a copy to avoid side effects if the original buffer is modified or reused\n return new Uint8Array(data);\n }\n\n public readPos(out: { x: number, y: number, z: number }): void {\n out.x = this.readCoord();\n out.y = this.readCoord();\n out.z = this.readCoord();\n }\n\n public readDir(out: { x: number, y: number, z: number }): void {\n const b = this.readByte();\n if (b >= 162) { // NUMVERTEXNORMALS\n out.x = 0; out.y = 0; out.z = 0;\n return;\n }\n const norm = ANORMS[b];\n out.x = norm[0];\n out.y = norm[1];\n out.z = norm[2];\n }\n}\n","import { ANORMS } from '../math/anorms.js';\nimport { Vec3 } from '../math/vec3.js';\n\nexport class BinaryWriter {\n private buffer: Uint8Array;\n private view: DataView;\n private offset: number;\n private readonly fixed: boolean;\n\n constructor(sizeOrBuffer: number | Uint8Array = 1400) {\n if (typeof sizeOrBuffer === 'number') {\n this.buffer = new Uint8Array(sizeOrBuffer);\n this.fixed = false;\n } else {\n this.buffer = sizeOrBuffer;\n this.fixed = true;\n }\n this.view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n this.offset = 0;\n }\n\n private ensureSpace(bytes: number) {\n if (this.offset + bytes > this.buffer.byteLength) {\n if (this.fixed) {\n throw new Error(`Buffer overflow: capacity ${this.buffer.byteLength}, needed ${this.offset + bytes}`);\n }\n // Expand buffer (double size)\n const newSize = Math.max(this.buffer.byteLength * 2, this.offset + bytes);\n const newBuffer = new Uint8Array(newSize);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n this.view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n }\n }\n\n public writeByte(value: number): void {\n this.ensureSpace(1);\n this.view.setUint8(this.offset, value);\n this.offset += 1;\n }\n\n public writeBytes(data: Uint8Array): void {\n this.ensureSpace(data.byteLength);\n this.buffer.set(data, this.offset);\n this.offset += data.byteLength;\n }\n\n public writeChar(value: number): void {\n this.ensureSpace(1);\n this.view.setInt8(this.offset, value);\n this.offset += 1;\n }\n\n public writeShort(value: number): void {\n this.ensureSpace(2);\n // Use setUint16 to allow writing 0xFFFF as a valid pattern even if it represents -1\n // But value might be negative (-1). setUint16(-1) wraps to 65535.\n // So setInt16 is fine if value is in range.\n // If value is 65535 (from bit manipulation), setInt16 might throw?\n // Let's safe cast.\n this.view.setInt16(this.offset, value, true);\n this.offset += 2;\n }\n\n public writeLong(value: number): void {\n this.ensureSpace(4);\n this.view.setInt32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeFloat(value: number): void {\n this.ensureSpace(4);\n this.view.setFloat32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeString(value: string): void {\n // UTF-8 encoding of string + null terminator\n // We iterate manually to match readString behavior (ASCII/Latin1 mostly)\n // and avoid TextEncoder overhead if simple\n const len = value.length;\n this.ensureSpace(len + 1);\n for (let i = 0; i < len; i++) {\n this.view.setUint8(this.offset + i, value.charCodeAt(i));\n }\n this.view.setUint8(this.offset + len, 0);\n this.offset += len + 1;\n }\n\n public writeCoord(value: number): void {\n this.writeShort(Math.trunc(value * 8));\n }\n\n public writeAngle(value: number): void {\n this.writeByte(Math.trunc(value * 256.0 / 360.0) & 255);\n }\n\n public writeAngle16(value: number): void {\n this.writeShort(Math.trunc(value * 65536.0 / 360.0) & 65535);\n }\n\n public writePos(pos: Vec3): void {\n this.writeCoord(pos.x);\n this.writeCoord(pos.y);\n this.writeCoord(pos.z);\n }\n\n public writeDir(dir: Vec3): void {\n // Find closest normal\n let maxDot = -1.0;\n let bestIndex = 0;\n\n // Check for zero vector\n if (dir.x === 0 && dir.y === 0 && dir.z === 0) {\n this.writeByte(0);\n return;\n }\n\n for (let i = 0; i < ANORMS.length; i++) {\n const norm = ANORMS[i];\n const dot = dir.x * norm[0] + dir.y * norm[1] + dir.z * norm[2];\n if (dot > maxDot) {\n maxDot = dot;\n bestIndex = i;\n }\n }\n\n this.writeByte(bestIndex);\n }\n\n public getData(): Uint8Array {\n return this.buffer.slice(0, this.offset);\n }\n\n public getBuffer(): Uint8Array {\n return this.buffer;\n }\n\n public getOffset(): number {\n return this.offset;\n }\n\n public reset(): void {\n this.offset = 0;\n }\n}\n","import { ANORMS } from '../math/anorms.js';\n\nexport class NetworkMessageBuilder {\n private buffer: Uint8Array;\n private view: DataView;\n private offset: number;\n\n constructor(initialSize: number = 1024) {\n this.buffer = new Uint8Array(initialSize);\n this.view = new DataView(this.buffer.buffer);\n this.offset = 0;\n }\n\n private ensureCapacity(needed: number): void {\n if (this.offset + needed > this.buffer.length) {\n const newSize = Math.max(this.buffer.length * 2, this.offset + needed);\n const newBuffer = new Uint8Array(newSize);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n this.view = new DataView(this.buffer.buffer);\n }\n }\n\n public getData(): Uint8Array {\n return this.buffer.slice(0, this.offset);\n }\n\n public writeByte(value: number): void {\n this.ensureCapacity(1);\n this.view.setUint8(this.offset, value);\n this.offset += 1;\n }\n\n public writeChar(value: number): void {\n this.ensureCapacity(1);\n this.view.setInt8(this.offset, value);\n this.offset += 1;\n }\n\n public writeShort(value: number): void {\n this.ensureCapacity(2);\n this.view.setInt16(this.offset, value, true);\n this.offset += 2;\n }\n\n public writeUShort(value: number): void {\n this.ensureCapacity(2);\n this.view.setUint16(this.offset, value, true);\n this.offset += 2;\n }\n\n public writeLong(value: number): void {\n this.ensureCapacity(4);\n this.view.setInt32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeFloat(value: number): void {\n this.ensureCapacity(4);\n this.view.setFloat32(this.offset, value, true);\n this.offset += 4;\n }\n\n public writeString(value: string): void {\n const len = value.length + 1; // +1 for null terminator\n this.ensureCapacity(len);\n for (let i = 0; i < value.length; i++) {\n this.view.setUint8(this.offset + i, value.charCodeAt(i));\n }\n this.view.setUint8(this.offset + value.length, 0);\n this.offset += len;\n }\n\n public writeData(data: Uint8Array): void {\n this.ensureCapacity(data.length);\n this.buffer.set(data, this.offset);\n this.offset += data.length;\n }\n\n public writeCoord(value: number): void {\n this.writeShort(Math.round(value * 8.0));\n }\n\n public writeAngle(value: number): void {\n this.writeByte(Math.round(value * 256.0 / 360.0) & 255);\n }\n\n public writeAngle16(value: number): void {\n this.writeShort(Math.round(value * 65536.0 / 360.0));\n }\n\n public writeDir(x: number, y: number, z: number): void {\n // Find closest normal from ANORMS\n // Simple brute force or use lookup if needed.\n // For now, let's just use 0 if implementation is complex to find best match.\n // Or unimplemented for now?\n // \"WriteDir\" in Q2 usually means writing a byte index into ANORMS.\n\n let best = 0;\n let bestDot = -999999;\n\n const len = Math.sqrt(x*x + y*y + z*z);\n if (len > 0) {\n x /= len; y /= len; z /= len;\n\n for (let i=0; i<162; i++) {\n const dot = x*ANORMS[i][0] + y*ANORMS[i][1] + z*ANORMS[i][2];\n if (dot > bestDot) {\n bestDot = dot;\n best = i;\n }\n }\n }\n\n this.writeByte(best);\n }\n}\n","import { BinaryWriter } from '../io/binaryWriter.js';\n\nexport interface NetAddress {\n type: string;\n port: number;\n}\n\n/**\n * NetChan handles reliable message delivery over an unreliable channel (UDP/WebSocket).\n * Fragmentation support is planned but not fully implemented.\n *\n * Ported from qcommon/net_chan.c\n */\nexport class NetChan {\n // Constants from net_chan.c\n static readonly MAX_MSGLEN = 1400;\n static readonly FRAGMENT_SIZE = 1024;\n static readonly PACKET_HEADER = 10; // sequence(4) + ack(4) + qport(2)\n static readonly HEADER_OVERHEAD = NetChan.PACKET_HEADER + 2; // +2 for reliable length prefix\n\n // Increase internal reliable buffer to support large messages (fragmentation)\n // Quake 2 uses MAX_MSGLEN for the reliable buffer, limiting single messages to ~1400 bytes.\n // We expand this to allow larger messages (e.g. snapshots, downloads) which are then fragmented.\n static readonly MAX_RELIABLE_BUFFER = 0x40000; // 256KB\n\n // Public state\n qport = 0; // qport value to distinguish multiple clients from same IP\n\n // Sequencing\n incomingSequence = 0;\n outgoingSequence = 0;\n incomingAcknowledged = 0;\n\n // Reliable messaging\n incomingReliableAcknowledged = false; // single bit\n incomingReliableSequence = 0; // last reliable message sequence received\n outgoingReliableSequence = 0; // reliable message sequence number to send\n reliableMessage: BinaryWriter;\n reliableLength = 0;\n\n // Fragmentation State (Sending)\n fragmentSendOffset = 0;\n\n // Fragmentation State (Receiving)\n fragmentBuffer: Uint8Array | null = null;\n fragmentLength = 0;\n fragmentReceived = 0;\n\n // Timing\n lastReceived = 0;\n lastSent = 0;\n\n remoteAddress: NetAddress | null = null;\n\n constructor() {\n // Initialize buffers\n this.reliableMessage = new BinaryWriter(NetChan.MAX_RELIABLE_BUFFER);\n\n // Set initial timestamps\n const now = Date.now();\n this.lastReceived = now;\n this.lastSent = now;\n\n // Random qport by default (can be overridden)\n // Ensure we use global Math.random which is usually seeded or random enough for basic collision avoidance\n this.qport = Math.floor(Math.random() * 65536);\n }\n\n /**\n * Setup the netchan with specific settings\n */\n setup(qport: number, address: NetAddress | null = null): void {\n this.qport = qport;\n this.remoteAddress = address;\n this.reset();\n }\n\n /**\n * Reset the netchan state\n */\n reset(): void {\n this.incomingSequence = 0;\n this.outgoingSequence = 0;\n this.incomingAcknowledged = 0;\n this.incomingReliableAcknowledged = false;\n this.incomingReliableSequence = 0;\n this.outgoingReliableSequence = 0;\n this.reliableLength = 0;\n this.reliableMessage.reset();\n\n this.fragmentSendOffset = 0;\n this.fragmentBuffer = null;\n this.fragmentLength = 0;\n this.fragmentReceived = 0;\n\n this.lastReceived = Date.now();\n this.lastSent = Date.now();\n }\n\n /**\n * Transmits a packet containing reliable and unreliable data\n */\n transmit(unreliableData?: Uint8Array): Uint8Array {\n this.outgoingSequence++;\n this.lastSent = Date.now();\n\n // Determine how much reliable data to send in this packet\n let sendReliableLength = 0;\n let isFragment = false;\n let fragmentStart = 0;\n\n if (this.reliableLength > 0) {\n // Check if we need to fragment\n if (this.reliableLength > NetChan.FRAGMENT_SIZE) {\n // We are in fragment mode\n isFragment = true;\n\n // If we have finished sending all fragments but still haven't received ACK,\n // we must loop back to the beginning to retransmit.\n if (this.fragmentSendOffset >= this.reliableLength) {\n this.fragmentSendOffset = 0;\n }\n\n // Calculate chunk size\n const remaining = this.reliableLength - this.fragmentSendOffset;\n sendReliableLength = remaining;\n if (sendReliableLength > NetChan.FRAGMENT_SIZE) {\n sendReliableLength = NetChan.FRAGMENT_SIZE;\n }\n\n fragmentStart = this.fragmentSendOffset;\n\n // Advance offset for the next packet\n this.fragmentSendOffset += sendReliableLength;\n } else {\n // Fits in one packet\n sendReliableLength = this.reliableLength;\n }\n }\n\n // Calculate total size\n // Header + Reliable + Unreliable\n const headerSize = NetChan.PACKET_HEADER;\n const reliableHeaderSize = sendReliableLength > 0 ? 2 + (isFragment ? 8 : 0) : 0; // +2 length, +8 fragment info\n\n let unreliableSize = unreliableData ? unreliableData.length : 0;\n\n // Check for overflow\n if (headerSize + reliableHeaderSize + sendReliableLength + unreliableSize > NetChan.MAX_MSGLEN) {\n unreliableSize = NetChan.MAX_MSGLEN - headerSize - reliableHeaderSize - sendReliableLength;\n // We truncate unreliable data if it doesn't fit with reliable data\n if (unreliableSize < 0) unreliableSize = 0;\n }\n\n const buffer = new ArrayBuffer(headerSize + reliableHeaderSize + sendReliableLength + unreliableSize);\n const view = new DataView(buffer);\n const result = new Uint8Array(buffer);\n\n // Write Header\n // Sequence\n let sequence = this.outgoingSequence;\n\n // Set reliable bit if we are sending reliable data\n if (sendReliableLength > 0) {\n sequence |= 0x80000000;\n // Also set the reliable sequence bit (0/1 toggle) at bit 30\n if ((this.outgoingReliableSequence & 1) !== 0) {\n sequence |= 0x40000000;\n }\n }\n\n view.setUint32(0, sequence, true);\n\n // Acknowledge\n // Set reliable ack bit at bit 31\n let ack = this.incomingSequence;\n if ((this.incomingReliableSequence & 1) !== 0) {\n ack |= 0x80000000;\n }\n view.setUint32(4, ack, true);\n\n view.setUint16(8, this.qport, true);\n\n // Copy Reliable Data\n let offset = headerSize;\n if (sendReliableLength > 0) {\n // Write length of reliable data (2 bytes)\n // Extension: If length has high bit (0x8000), it's a fragment.\n let lengthField = sendReliableLength;\n if (isFragment) {\n lengthField |= 0x8000;\n }\n\n view.setUint16(offset, lengthField, true);\n offset += 2;\n\n if (isFragment) {\n // Write fragment info: 4 bytes start offset, 4 bytes total length\n view.setUint32(offset, fragmentStart, true);\n offset += 4;\n view.setUint32(offset, this.reliableLength, true);\n offset += 4;\n }\n\n // Copy data\n const reliableBuffer = this.reliableMessage.getBuffer();\n const reliableBytes = reliableBuffer.subarray(fragmentStart, fragmentStart + sendReliableLength);\n result.set(reliableBytes, offset);\n offset += sendReliableLength;\n }\n\n // Copy Unreliable Data\n if (unreliableData && unreliableSize > 0) {\n const chunk = unreliableData.slice(0, unreliableSize);\n result.set(chunk, offset);\n }\n\n return result;\n }\n\n /**\n * Processes a received packet\n * Returns the payload data (reliable + unreliable) to be processed, or null if discarded\n */\n process(packet: Uint8Array): Uint8Array | null {\n if (packet.length < NetChan.PACKET_HEADER) {\n return null;\n }\n\n this.lastReceived = Date.now();\n\n const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);\n const sequence = view.getUint32(0, true);\n const ack = view.getUint32(4, true);\n const qport = view.getUint16(8, true);\n\n if (this.qport !== qport) {\n return null;\n }\n\n // Check for duplicate or out of order\n const seqNumberClean = sequence & ~(0x80000000 | 0x40000000); // Mask out flags\n\n // Handle wrapping using signed difference\n if (((seqNumberClean - this.incomingSequence) | 0) <= 0) {\n return null;\n }\n\n // Update incoming sequence\n this.incomingSequence = seqNumberClean;\n\n // Handle reliable acknowledgment\n const ackNumber = ack & ~0x80000000;\n const ackReliable = (ack & 0x80000000) !== 0;\n\n if (ackNumber > this.incomingAcknowledged) {\n this.incomingAcknowledged = ackNumber;\n }\n\n // Check if our reliable message was acknowledged\n // If the receiver has toggled their reliable bit, it means they got the WHOLE message\n if (this.reliableLength > 0) {\n const receivedAckBit = ackReliable ? 1 : 0;\n const currentReliableBit = this.outgoingReliableSequence & 1;\n\n if (receivedAckBit !== currentReliableBit) {\n // Acked!\n this.reliableLength = 0;\n this.reliableMessage.reset();\n this.outgoingReliableSequence ^= 1;\n this.fragmentSendOffset = 0; // Reset fragment offset\n }\n }\n\n // Handle incoming reliable data\n const hasReliableData = (sequence & 0x80000000) !== 0;\n const reliableSeqBit = (sequence & 0x40000000) !== 0 ? 1 : 0;\n\n let payloadOffset = NetChan.PACKET_HEADER;\n let reliableData: Uint8Array | null = null;\n\n if (hasReliableData) {\n if (payloadOffset + 2 > packet.byteLength) return null; // Malformed\n\n let reliableLen = view.getUint16(payloadOffset, true);\n payloadOffset += 2;\n\n const isFragment = (reliableLen & 0x8000) !== 0;\n reliableLen &= 0x7FFF;\n\n // Check if this is the expected reliable sequence\n const expectedBit = this.incomingReliableSequence & 1;\n\n if (reliableSeqBit === expectedBit) {\n // It's the sequence we are waiting for\n\n if (isFragment) {\n // Read fragment info\n if (payloadOffset + 8 > packet.byteLength) return null;\n const fragStart = view.getUint32(payloadOffset, true);\n payloadOffset += 4;\n const fragTotal = view.getUint32(payloadOffset, true);\n payloadOffset += 4;\n\n // Validate fragTotal against MAX_RELIABLE_BUFFER\n if (fragTotal > NetChan.MAX_RELIABLE_BUFFER) {\n console.warn(`NetChan: received invalid fragment total ${fragTotal} > ${NetChan.MAX_RELIABLE_BUFFER}`);\n return null;\n }\n\n // Initialize fragment buffer if needed\n if (!this.fragmentBuffer || this.fragmentBuffer.length !== fragTotal) {\n this.fragmentBuffer = new Uint8Array(fragTotal);\n this.fragmentLength = fragTotal;\n this.fragmentReceived = 0;\n }\n\n // Check for valid fragment offset\n if (payloadOffset + reliableLen > packet.byteLength) return null;\n const data = packet.subarray(payloadOffset, payloadOffset + reliableLen);\n\n // Only accept if it matches our expected offset (enforce in-order delivery for simplicity)\n // or check if we haven't received this part yet.\n // Since we use a simple 'fragmentReceived' counter, we effectively expect in-order delivery\n // of streams if we just use append logic.\n // BUT UDP can reorder.\n // To be robust, we should enforce strict ordering: fragStart must equal fragmentReceived.\n // If we miss a chunk, we ignore subsequent chunks until the missing one arrives (via retransmit loop).\n\n if (fragStart === this.fragmentReceived && fragStart + reliableLen <= fragTotal) {\n this.fragmentBuffer.set(data, fragStart);\n this.fragmentReceived += reliableLen;\n\n // Check if complete\n if (this.fragmentReceived >= fragTotal) {\n reliableData = this.fragmentBuffer;\n this.incomingReliableSequence++;\n this.fragmentBuffer = null;\n this.fragmentLength = 0;\n this.fragmentReceived = 0;\n }\n }\n\n } else {\n // Not a fragment (standard)\n this.incomingReliableSequence++;\n if (payloadOffset + reliableLen > packet.byteLength) return null;\n reliableData = packet.slice(payloadOffset, payloadOffset + reliableLen);\n }\n }\n\n // Advance past reliable data regardless\n payloadOffset += reliableLen;\n }\n\n // Get unreliable data\n const unreliableData = packet.slice(payloadOffset);\n\n // Combine if we have reliable data\n if (reliableData && reliableData.length > 0) {\n const totalLen = reliableData.length + unreliableData.length;\n const result = new Uint8Array(totalLen);\n result.set(reliableData, 0);\n result.set(unreliableData, reliableData.length);\n return result;\n }\n\n if (unreliableData) {\n return unreliableData;\n }\n\n return new Uint8Array(0);\n }\n\n /**\n * Checks if reliable message buffer is empty and ready for new data\n */\n canSendReliable(): boolean {\n return this.reliableLength === 0;\n }\n\n /**\n * Writes a byte to the reliable message buffer\n */\n writeReliableByte(value: number): void {\n if (this.reliableLength + 1 > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeByte(value);\n this.reliableLength++;\n }\n\n /**\n * Writes a short to the reliable message buffer\n */\n writeReliableShort(value: number): void {\n if (this.reliableLength + 2 > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeShort(value);\n this.reliableLength += 2;\n }\n\n /**\n * Writes a long to the reliable message buffer\n */\n writeReliableLong(value: number): void {\n if (this.reliableLength + 4 > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeLong(value);\n this.reliableLength += 4;\n }\n\n /**\n * Writes a string to the reliable message buffer\n */\n writeReliableString(value: string): void {\n const len = value.length + 1; // +1 for null terminator\n if (this.reliableLength + len > NetChan.MAX_RELIABLE_BUFFER) {\n throw new Error('NetChan reliable buffer overflow');\n }\n this.reliableMessage.writeString(value);\n this.reliableLength += len;\n }\n\n /**\n * Returns the current reliable data buffer\n */\n getReliableData(): Uint8Array {\n if (this.reliableLength === 0) {\n return new Uint8Array(0);\n }\n const buffer = this.reliableMessage.getBuffer();\n return buffer.subarray(0, this.reliableLength);\n }\n\n /**\n * Checks if we need to send a keepalive packet\n */\n needsKeepalive(currentTime: number): boolean {\n return (currentTime - this.lastSent) > 1000;\n }\n\n /**\n * Checks if the connection has timed out\n */\n isTimedOut(currentTime: number, timeoutMs: number = 30000): boolean {\n return (currentTime - this.lastReceived) > timeoutMs;\n }\n}\n","/**\n * Weapon identifiers shared across game and cgame.\n * Reference: rerelease/g_items.cpp, game/src/inventory/playerInventory.ts\n */\n\nexport enum WeaponId {\n Blaster = 'blaster',\n Shotgun = 'shotgun',\n SuperShotgun = 'supershotgun', // Matched to assets (w_supershotgun, weapon_supershotgun)\n Machinegun = 'machinegun',\n Chaingun = 'chaingun',\n HandGrenade = 'grenades', // Matched to assets (w_grenades, weapon_grenades)\n GrenadeLauncher = 'grenadelauncher', // Matched to assets (w_grenadelauncher)\n RocketLauncher = 'rocketlauncher', // Matched to assets (w_rocketlauncher)\n HyperBlaster = 'hyperblaster',\n Railgun = 'railgun',\n BFG10K = 'bfg10k',\n // New additions for demo playback and extended support\n Grapple = 'grapple',\n ChainFist = 'chainfist',\n EtfRifle = 'etf_rifle', // Confirm asset?\n ProxLauncher = 'prox_launcher', // Confirm asset?\n IonRipper = 'ionripper',\n PlasmaBeam = 'plasmabeam',\n Phalanx = 'phalanx',\n Disruptor = 'disruptor',\n Trap = 'trap',\n}\n","/**\n * Ammo type identifiers shared across game and cgame.\n * Reference: rerelease/g_items.cpp, game/src/inventory/ammo.ts\n */\n\nexport enum AmmoType {\n Bullets = 0,\n Shells,\n Rockets,\n Grenades,\n Cells,\n Slugs,\n // RAFAEL\n MagSlugs,\n Trap,\n // RAFAEL\n // ROGUE\n Flechettes,\n Tesla,\n Disruptor, // Was missing or named differently?\n Prox,\n // ROGUE\n // Custom or Extras?\n Nuke,\n Rounds,\n}\n\nexport const AMMO_TYPE_COUNT = Object.keys(AmmoType).length / 2;\n\n/**\n * Item classnames for ammo pickups.\n * Used for spawning and identifying ammo items.\n */\nexport enum AmmoItemId {\n Shells = 'ammo_shells',\n Bullets = 'ammo_bullets',\n Rockets = 'ammo_rockets',\n Grenades = 'ammo_grenades',\n Cells = 'ammo_cells',\n Slugs = 'ammo_slugs',\n MagSlugs = 'ammo_magslug',\n Flechettes = 'ammo_flechettes',\n Disruptor = 'ammo_disruptor',\n Tesla = 'ammo_tesla',\n Trap = 'ammo_trap',\n Prox = 'ammo_prox',\n}\n","import { WeaponId } from './weapons.js';\nimport { AmmoType } from './ammo.js';\n\n// Order matches Q2 original weapon wheel index order for bitmask generation\n// Used by both Game (for STAT_WEAPONS_OWNED calculation) and CGame (for weapon wheel UI)\nexport const WEAPON_WHEEL_ORDER: WeaponId[] = [\n WeaponId.Blaster,\n WeaponId.Shotgun,\n WeaponId.SuperShotgun,\n WeaponId.Machinegun,\n WeaponId.Chaingun,\n WeaponId.GrenadeLauncher,\n WeaponId.RocketLauncher,\n WeaponId.HandGrenade,\n WeaponId.HyperBlaster,\n WeaponId.Railgun,\n WeaponId.BFG10K\n];\n\n// Mapping of weapon to its ammo type\n// Used by CGame to lookup ammo counts for weapon wheel\nexport const WEAPON_AMMO_MAP: Record<WeaponId, AmmoType | null> = {\n [WeaponId.Blaster]: null,\n [WeaponId.Shotgun]: AmmoType.Shells,\n [WeaponId.SuperShotgun]: AmmoType.Shells,\n [WeaponId.Machinegun]: AmmoType.Bullets,\n [WeaponId.Chaingun]: AmmoType.Bullets,\n [WeaponId.HandGrenade]: AmmoType.Grenades,\n [WeaponId.GrenadeLauncher]: AmmoType.Grenades,\n [WeaponId.RocketLauncher]: AmmoType.Rockets,\n [WeaponId.HyperBlaster]: AmmoType.Cells,\n [WeaponId.Railgun]: AmmoType.Slugs,\n [WeaponId.BFG10K]: AmmoType.Cells,\n\n // Extensions / Rogue / Xatrix\n [WeaponId.Grapple]: null,\n [WeaponId.ChainFist]: null,\n [WeaponId.EtfRifle]: AmmoType.Flechettes,\n [WeaponId.ProxLauncher]: AmmoType.Prox,\n [WeaponId.IonRipper]: AmmoType.Cells,\n [WeaponId.PlasmaBeam]: AmmoType.Cells,\n [WeaponId.Phalanx]: AmmoType.MagSlugs,\n [WeaponId.Disruptor]: AmmoType.Disruptor,\n [WeaponId.Trap]: AmmoType.Trap,\n};\n","export const MAX_SOUND_CHANNELS = 32;\n\n// Sound channel identifiers and flags from the rerelease game headers.\nexport enum SoundChannel {\n Auto = 0,\n Weapon = 1,\n Voice = 2,\n Item = 3,\n Body = 4,\n Aux = 5,\n Footstep = 6,\n Aux3 = 7,\n\n NoPhsAdd = 1 << 3,\n Reliable = 1 << 4,\n ForcePos = 1 << 5,\n}\n\nexport const ATTN_LOOP_NONE = -1;\nexport const ATTN_NONE = 0;\nexport const ATTN_NORM = 1;\nexport const ATTN_IDLE = 2;\nexport const ATTN_STATIC = 3;\n\nexport const SOUND_FULLVOLUME = 80;\nexport const SOUND_LOOP_ATTENUATE = 0.003;\n\nexport function attenuationToDistanceMultiplier(attenuation: number): number {\n return attenuation * 0.001;\n}\n\nexport function calculateMaxAudibleDistance(attenuation: number): number {\n const distMult = attenuationToDistanceMultiplier(attenuation);\n return distMult <= 0 ? Number.POSITIVE_INFINITY : SOUND_FULLVOLUME + 1 / distMult;\n}\n","import { PlayerState } from './protocol/index.js';\nimport { AmmoItemId, AmmoType, WeaponId } from './items/index.js';\nimport { G_GetAmmoStat } from './protocol/stats.js';\nimport { WEAPON_AMMO_MAP } from './items/index.js';\nimport { ConfigStringIndex } from './protocol/configstrings.js';\n\n// Blaster uses no ammo in standard Q2.\n// We handle mapping `AmmoItemId` (string) to `AmmoType` (enum).\nexport const AMMO_ITEM_MAP: Record<AmmoItemId, AmmoType> = {\n [AmmoItemId.Shells]: AmmoType.Shells,\n [AmmoItemId.Bullets]: AmmoType.Bullets,\n [AmmoItemId.Rockets]: AmmoType.Rockets,\n [AmmoItemId.Grenades]: AmmoType.Grenades,\n [AmmoItemId.Cells]: AmmoType.Cells,\n [AmmoItemId.Slugs]: AmmoType.Slugs,\n [AmmoItemId.MagSlugs]: AmmoType.MagSlugs,\n [AmmoItemId.Flechettes]: AmmoType.Flechettes,\n [AmmoItemId.Disruptor]: AmmoType.Disruptor,\n [AmmoItemId.Tesla]: AmmoType.Tesla,\n [AmmoItemId.Trap]: AmmoType.Trap,\n [AmmoItemId.Prox]: AmmoType.Prox,\n};\n\n/**\n * Retrieves the ammo count for a given item (Weapon or Ammo).\n * @param playerState The current player state.\n * @param item The item identifier (WeaponId or AmmoItemId).\n * @returns The ammo count, or 0 if not found/applicable. Returns -1 for infinite ammo (e.g. Blaster).\n */\nexport function getAmmoCount(playerState: PlayerState, item: WeaponId | AmmoItemId): number {\n let ammoType: AmmoType | null | undefined;\n\n // Check if it's an Ammo Item ID\n if (Object.values(AmmoItemId).includes(item as AmmoItemId)) {\n ammoType = AMMO_ITEM_MAP[item as AmmoItemId];\n }\n // Check if it's a Weapon ID\n else if (Object.values(WeaponId).includes(item as WeaponId)) {\n ammoType = WEAPON_AMMO_MAP[item as WeaponId];\n\n // Existing map has null for Blaster, Grapple, etc.\n if (ammoType === null) {\n return -1;\n }\n }\n\n if (ammoType === undefined || ammoType === null) {\n return 0;\n }\n\n return G_GetAmmoStat(playerState.stats, ammoType);\n}\n\n/**\n * Resolves the icon path for a given stat index (e.g. STAT_SELECTED_ICON).\n * @param statIndex The index in the stats array to read (e.g. PlayerStat.STAT_SELECTED_ICON).\n * @param playerState The player state containing the stats.\n * @param configStrings The array of configuration strings (from client state).\n * @returns The path to the icon image, or undefined if invalid.\n */\nexport function getIconPath(\n statIndex: number,\n playerState: PlayerState,\n configStrings: string[]\n): string | undefined {\n const iconIndex = playerState.stats[statIndex];\n\n // 0 usually means no icon or null\n if (iconIndex === undefined || iconIndex <= 0) {\n return undefined;\n }\n\n // The value in the stat is the index into the Config Strings relative to ConfigStringIndex.Images.\n const configIndex = ConfigStringIndex.Images + iconIndex;\n\n if (configIndex < 0 || configIndex >= configStrings.length) {\n return undefined;\n }\n\n return configStrings[configIndex];\n}\n","import type { PmoveTraceFn, PmoveTraceResult } from './pmove/types.js';\nimport type { Vec3 } from './math/vec3.js';\nimport { CONTENTS_LADDER } from './bsp/contents.js';\n\nexport const intersects = (end: Vec3, maxs: Vec3, mins: Vec3, boxMins: Vec3, boxMaxs: Vec3): boolean => {\n return (\n end.x + maxs.x > boxMins.x &&\n end.x + mins.x < boxMaxs.x &&\n end.y + maxs.y > boxMins.y &&\n end.y + mins.y < boxMaxs.y &&\n end.z + maxs.z > boxMins.z &&\n end.z + mins.z < boxMaxs.z\n );\n};\n\nexport const stairTrace: PmoveTraceFn = (start: Vec3, end: Vec3, mins?: Vec3, maxs?: Vec3): PmoveTraceResult => {\n // Default bbox if not provided\n const useMins = mins ?? { x: -16, y: -16, z: -24 };\n const useMaxs = maxs ?? { x: 16, y: 16, z: 32 };\n\n // Step: x from 0 forward, z from 0 to 8\n const STEP_HEIGHT = 8;\n const STEP_X_START = 0;\n\n const isHorizontal = Math.abs(end.z - start.z) < 1;\n const isMovingDown = end.z < start.z;\n\n // Check if trying to go below the floor\n const endMinZ = end.z + useMins.z;\n const startMinZ = start.z + useMins.z;\n const endMaxX = end.x + useMaxs.x;\n\n // If moving horizontally, check if we'd hit the vertical face of the step\n // The step only blocks if the player's origin is below the step height\n if (isHorizontal && end.z < STEP_HEIGHT && endMaxX > STEP_X_START) {\n // Check if we're crossing into the step area\n const startMaxX = start.x + useMaxs.x;\n if (startMaxX <= STEP_X_START) {\n // We're moving from before the step to past it, block\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: -1, y: 0, z: 0 },\n contents: 1,\n };\n }\n }\n\n // If moving down and over the step area, land on the step surface\n if (isMovingDown && end.x >= STEP_X_START) {\n // The step surface is at z=STEP_HEIGHT in world space\n // The player's bbox bottom reaches this plane when origin.z + mins.z = STEP_HEIGHT\n // So the player's origin should be at z = STEP_HEIGHT - mins.z\n const landZ = STEP_HEIGHT - useMins.z;\n\n // Check if we'd pass through the step surface\n // We cross the plane if start is above it and end would be below it\n if (startMinZ > STEP_HEIGHT && endMinZ < STEP_HEIGHT) {\n // Calculate the fraction along the ray where we intersect the plane\n // The bbox bottom is at: start.z + useMins.z + t * (end.z - start.z + 0) = STEP_HEIGHT\n // Solving for t: t = (STEP_HEIGHT - (start.z + useMins.z)) / ((end.z + useMins.z) - (start.z + useMins.z))\n const fraction = (STEP_HEIGHT - startMinZ) / (endMinZ - startMinZ);\n\n // Clamp to valid range [0, 1]\n const clampedFraction = Math.max(0, Math.min(1, fraction));\n\n // Calculate the endpos along the ray at this fraction\n const finalX = start.x + clampedFraction * (end.x - start.x);\n const finalY = start.y + clampedFraction * (end.y - start.y);\n const finalZ = start.z + clampedFraction * (end.z - start.z);\n\n return {\n allsolid: false,\n startsolid: false,\n fraction: clampedFraction,\n endpos: { x: finalX, y: finalY, z: finalZ },\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n }\n\n // If moving down and would go below floor level, block at floor\n if (isMovingDown && endMinZ < 0) {\n // Floor is at z=0, so player origin should be at z = -mins.z when landing\n const landZ = -useMins.z;\n\n // Only apply if we're crossing the floor plane\n if (startMinZ >= 0) {\n // Calculate fraction where bbox bottom hits z=0\n const fraction = (0 - startMinZ) / (endMinZ - startMinZ);\n const clampedFraction = Math.max(0, Math.min(1, fraction));\n\n const finalX = start.x + clampedFraction * (end.x - start.x);\n const finalY = start.y + clampedFraction * (end.y - start.y);\n const finalZ = start.z + clampedFraction * (end.z - start.z);\n\n return {\n allsolid: false,\n startsolid: false,\n fraction: clampedFraction,\n endpos: { x: finalX, y: finalY, z: finalZ },\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n\n // Already below floor, block immediately\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n\n // Free movement\n return {\n allsolid: false,\n startsolid: false,\n fraction: 1.0,\n endpos: end,\n contents: 0,\n };\n};\n\nexport const ladderTrace: PmoveTraceFn = (start: Vec3, end: Vec3, mins?: Vec3, maxs?: Vec3): PmoveTraceResult => {\n // Default bbox if not provided\n const useMins = mins ?? { x: -16, y: -16, z: -24 };\n const useMaxs = maxs ?? { x: 16, y: 16, z: 32 };\n\n // Define the ladder volume (x=0 to x=8, y=-16 to y=16, z=0 to z=100)\n const LADDER_X_MIN = 0;\n const LADDER_X_MAX = 8;\n const LADDER_Y_MIN = -16;\n const LADDER_Y_MAX = 16;\n const LADDER_Z_MIN = 0;\n const LADDER_Z_MAX = 100;\n\n // Check if end position is within the ladder volume\n const endInLadder =\n end.x + useMins.x < LADDER_X_MAX &&\n end.x + useMaxs.x > LADDER_X_MIN &&\n end.y + useMins.y < LADDER_Y_MAX &&\n end.y + useMaxs.y > LADDER_Y_MIN &&\n end.z + useMins.z < LADDER_Z_MAX &&\n end.z + useMaxs.z > LADDER_Z_MIN;\n\n // If moving into the ladder from outside (moving forward into it)\n const movingIntoLadder = start.x < LADDER_X_MIN && end.x >= LADDER_X_MIN;\n\n // If moving horizontally into the ladder front face, block with ladder surface\n if (movingIntoLadder && Math.abs(end.z - start.z) < 0.1) {\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: -1, y: 0, z: 0 },\n contents: CONTENTS_LADDER,\n };\n }\n\n // If we're in the ladder volume, return success but with CONTENTS_LADDER\n // This allows the player to detect they're on a ladder without blocking movement\n if (endInLadder) {\n return {\n allsolid: false,\n startsolid: false,\n fraction: 1.0,\n endpos: end,\n contents: CONTENTS_LADDER,\n };\n }\n\n // Floor at z=0\n if (end.z + useMins.z <= 0) {\n return {\n allsolid: false,\n startsolid: false,\n fraction: 0,\n endpos: start,\n planeNormal: { x: 0, y: 0, z: 1 },\n contents: 1,\n };\n }\n\n // No collision - free movement\n return {\n allsolid: false,\n startsolid: false,\n fraction: 1.0,\n endpos: end,\n contents: 0,\n };\n};\n","import { 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 getString(): string {\n return this.string;\n }\n\n get number(): number {\n return Number(this._value);\n }\n\n getFloat(): number {\n return this.number;\n }\n\n get integer(): number {\n return Math.trunc(this.number);\n }\n\n getInt(): number {\n return this.integer;\n }\n\n get boolean(): boolean {\n return Boolean(this.integer);\n }\n\n getBoolean(): boolean {\n return this.boolean;\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 interface CvarInfo {\n name: string;\n value: string;\n defaultValue: string;\n flags: CvarFlags;\n description?: string;\n}\n\nexport class CvarRegistry {\n private readonly cvars = new Map<string, Cvar>();\n public onCvarChange?: (name: string, value: string) => void;\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 // Wrap the onChange handler to also trigger the registry's onCvarChange\n const originalOnChange = def.onChange;\n const wrappedOnChange: CvarChangeHandler = (cvar, prev) => {\n originalOnChange?.(cvar, prev);\n this.onCvarChange?.(cvar.name, cvar.string);\n };\n\n const cvar = new Cvar({ ...def, onChange: wrappedOnChange });\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 getCvar(name: string): Cvar | undefined {\n return this.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 setCvar(name: string, value: string): void {\n this.setValue(name, value);\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 listCvars(): CvarInfo[] {\n return this.list().map(cvar => ({\n name: cvar.name,\n value: cvar.string,\n defaultValue: cvar.defaultValue,\n flags: cvar.flags,\n description: cvar.description\n }));\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';\nimport { CommandRegistry } from './commands.js';\nimport { CvarRegistry } from './cvars.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 paused_ = false;\n private latestCommand?: UserCommand;\n readonly commands = new CommandRegistry();\n readonly cvars = new CvarRegistry();\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 // Wire up cvar autocomplete provider\n this.commands.registerAutocompleteProvider(() => {\n return this.cvars.list().map(cvar => cvar.name);\n });\n }\n\n start(): void {\n if (this.started) return;\n\n try {\n this.latestFrame = this.game.init(this.startTimeMs) ?? this.latestFrame;\n this.client?.init(this.latestFrame);\n } catch (error) {\n this.game.shutdown();\n this.client?.shutdown();\n throw error;\n }\n\n this.started = true;\n this.paused_ = false;\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 this.paused_ = false;\n }\n\n setPaused(paused: boolean): void {\n this.paused_ = paused;\n if (paused) {\n this.loop.stop();\n } else if (this.started) {\n this.loop.start();\n }\n }\n\n get paused(): boolean {\n return this.paused_;\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","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 getName(index: number): string | undefined {\n return this.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 Vec3 } from '@quake2ts/shared';\nimport { MusicSystem } from './music.js';\nimport { SoundRegistry } from './registry.js';\nimport { AudioSystem, type SoundRequest, type ActiveSound } from './system.js';\n\nexport interface SubtitleClient {\n showSubtitle(text: string, soundName: string): void;\n}\n\nexport interface AudioApiOptions {\n registry: SoundRegistry;\n system: AudioSystem;\n music?: MusicSystem;\n client?: SubtitleClient;\n}\n\nexport class AudioApi {\n private readonly registry: SoundRegistry;\n private readonly system: AudioSystem;\n private readonly music?: MusicSystem;\n private readonly client?: SubtitleClient;\n\n constructor(options: AudioApiOptions) {\n this.registry = options.registry;\n this.system = options.system;\n this.music = options.music;\n this.client = options.client;\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 this.triggerSubtitle(soundindex);\n }\n\n positioned_sound(origin: Vec3, soundindex: number, volume: number, attenuation: number): void {\n this.system.positionedSound(origin, soundindex, volume, attenuation);\n this.triggerSubtitle(soundindex);\n }\n\n loop_sound(entity: number, channel: number, soundindex: number, volume: number, attenuation: number): ActiveSound | undefined {\n const active = this.system.play({\n entity,\n channel,\n soundIndex: soundindex,\n volume,\n attenuation,\n looping: true,\n });\n this.triggerSubtitle(soundindex);\n return active;\n }\n\n stop_entity_sounds(entnum: number): void {\n this.system.stopEntitySounds(entnum);\n }\n\n setPlaybackRate(rate: number): void {\n this.system.setPlaybackRate(rate);\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 play_track(trackNum: number, loop = true): Promise<void> {\n if (!this.music) {\n return Promise.resolve();\n }\n return this.music.playTrack(trackNum);\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 this.triggerSubtitle(soundindex);\n }\n\n play_channel(request: Omit<SoundRequest, 'looping'>): void {\n this.system.play({ ...request });\n this.triggerSubtitle(request.soundIndex);\n }\n\n private triggerSubtitle(soundIndex: number) {\n if (!this.client) return;\n\n const soundName = this.registry.getName(soundIndex);\n if (!soundName) return;\n\n // Simple heuristic for now: if a sound has a subtitle, it's probably dialogue.\n // We can make this more robust later with a dedicated subtitle data file.\n const dialogueMatch = soundName.match(/\\[(.*?)\\]/);\n if (dialogueMatch) {\n this.client.showSubtitle(dialogueMatch[1], soundName);\n }\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\nimport { AudioApi, AudioApiOptions, SubtitleClient } from './audio/api.js';\n\nexport function createEngineRuntime<FrameState = unknown>(\n engine: EngineExports,\n game: GameSimulation<FrameState>,\n client: ClientRenderer<FrameState> & SubtitleClient,\n audioOptions: AudioApiOptions,\n options?: EngineHostOptions,\n): { runtime: EngineRuntime<FrameState>, audio: AudioApi } {\n const audio = new AudioApi({ ...audioOptions, client });\n const host = new EngineHost(game, client, options);\n const runtime = new EngineRuntime(engine, host);\n return { runtime, audio };\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","\nimport { PakDirectoryEntry, PakParseError } from './pak.js';\n\nconst PAK_MAGIC = 'PACK';\nconst HEADER_SIZE = 12;\nconst DIRECTORY_ENTRY_SIZE = 64;\n\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/').replace(/^\\/+/, '').toLowerCase();\n}\n\n/**\n * Read PAK file in chunks, streaming file contents on demand.\n * Uses the Blob interface which is supported by File in browsers.\n */\nexport class StreamingPakArchive {\n private entries: Map<string, PakDirectoryEntry> | null = null;\n\n constructor(private readonly source: Blob) {}\n\n /**\n * Read directory asynchronously.\n * Caches the result so subsequent calls are fast.\n */\n async readDirectory(): Promise<PakDirectoryEntry[]> {\n if (this.entries) {\n return Array.from(this.entries.values());\n }\n\n // Read header (12 bytes)\n const headerBuffer = await this.readChunk(0, HEADER_SIZE);\n const headerView = new DataView(headerBuffer);\n\n const magic = String.fromCharCode(\n headerView.getUint8(0),\n headerView.getUint8(1),\n headerView.getUint8(2),\n headerView.getUint8(3),\n );\n\n if (magic !== PAK_MAGIC) {\n throw new PakParseError(`Invalid PAK header magic: ${magic}`);\n }\n\n const dirOffset = headerView.getInt32(4, true);\n const dirLength = headerView.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 // Read directory\n // Note: If directory is huge, this might be a large read, but it's metadata only.\n // 64 bytes per file. 10,000 files = 640KB. Very fast.\n const dirBuffer = await this.readChunk(dirOffset, dirLength);\n const dirView = new DataView(dirBuffer);\n const entryCount = dirLength / DIRECTORY_ENTRY_SIZE;\n\n const entries = new Map<string, PakDirectoryEntry>();\n\n for (let i = 0; i < entryCount; i++) {\n const offset = i * DIRECTORY_ENTRY_SIZE;\n const rawName = this.readCString(dirView, offset, 56);\n const normalized = normalizePath(rawName);\n\n const fileOffset = dirView.getInt32(offset + 56, true);\n const fileLength = dirView.getInt32(offset + 60, true);\n\n // We cannot easily validate file bounds against total size without knowing total size,\n // but source.size is available on Blob.\n if (fileOffset < 0 || fileLength < 0 || fileOffset + fileLength > this.source.size) {\n // Log warning or throw? Throwing might be safer.\n // throw new PakParseError(`Invalid entry bounds for ${rawName}`);\n }\n\n if (normalized) {\n entries.set(normalized, { name: normalized, offset: fileOffset, length: fileLength });\n }\n }\n\n this.entries = entries;\n return Array.from(entries.values());\n }\n\n /**\n * Stream file contents on demand.\n * Returns a ReadableStream of Uint8Array.\n */\n async readFile(path: string): Promise<ReadableStream<Uint8Array>> {\n const entry = await this.getEntry(path);\n if (!entry) {\n throw new PakParseError(`File not found in PAK: ${path}`);\n }\n\n const blob = this.source.slice(entry.offset, entry.offset + entry.length);\n\n // In browser, blob.stream() returns ReadableStream<Uint8Array>.\n // In Node (older versions), it might differ, but recent Node supports standard Blob.\n return blob.stream() as ReadableStream<Uint8Array>;\n }\n\n /**\n * Get file as a Blob without loading entire file into memory.\n */\n async getFileBlob(path: string): Promise<Blob> {\n const entry = await this.getEntry(path);\n if (!entry) {\n throw new PakParseError(`File not found in PAK: ${path}`);\n }\n return this.source.slice(entry.offset, entry.offset + entry.length);\n }\n\n private async getEntry(path: string): Promise<PakDirectoryEntry | undefined> {\n if (!this.entries) {\n await this.readDirectory();\n }\n return this.entries!.get(normalizePath(path));\n }\n\n private async readChunk(offset: number, length: number): Promise<ArrayBuffer> {\n const slice = this.source.slice(offset, offset + length);\n if ('arrayBuffer' in slice) {\n return await slice.arrayBuffer();\n } else {\n // Fallback for older environments or JSDOM blobs if needed\n return new Response(slice).arrayBuffer();\n }\n }\n\n private 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}\n","import { normalizePath } from './pak.js';\n\nconst PAK_MAGIC = 'PACK';\nconst HEADER_SIZE = 12;\nconst DIRECTORY_ENTRY_SIZE = 64;\n\n/**\n * Utility class for creating Quake 2 PAK archives.\n */\nexport class PakWriter {\n private entries = new Map<string, Uint8Array>();\n\n /**\n * Adds a file to the archive.\n * @param path The file path (will be normalized to lowercase, forward slashes).\n * @param data The file content.\n */\n addFile(path: string, data: Uint8Array): void {\n const normalized = normalizePath(path);\n if (normalized.length > 56) {\n throw new Error(`Path too long: '${normalized}' (max 56 chars)`);\n }\n this.entries.set(normalized, data);\n }\n\n /**\n * Removes a file from the archive.\n * @param path The file path.\n * @returns True if the file existed and was removed.\n */\n removeFile(path: string): boolean {\n return this.entries.delete(normalizePath(path));\n }\n\n /**\n * Serializes the current entries into a PAK archive buffer.\n */\n build(): Uint8Array {\n // Calculate sizes\n let fileDataSize = 0;\n for (const data of this.entries.values()) {\n fileDataSize += data.byteLength;\n }\n\n const directorySize = this.entries.size * DIRECTORY_ENTRY_SIZE;\n const totalSize = HEADER_SIZE + fileDataSize + directorySize;\n\n const buffer = new Uint8Array(totalSize);\n const view = new DataView(buffer.buffer);\n\n // Write Header\n view.setUint8(0, 'P'.charCodeAt(0));\n view.setUint8(1, 'A'.charCodeAt(0));\n view.setUint8(2, 'C'.charCodeAt(0));\n view.setUint8(3, 'K'.charCodeAt(0));\n\n // Directory Offset (files come first, then directory)\n const dirOffset = HEADER_SIZE + fileDataSize;\n view.setInt32(4, dirOffset, true);\n view.setInt32(8, directorySize, true);\n\n // Write Files\n let currentOffset = HEADER_SIZE;\n const fileOffsets = new Map<string, number>();\n\n // We sort keys to ensure deterministic output for testing, though not strictly required by format\n const sortedKeys = Array.from(this.entries.keys()).sort();\n\n for (const name of sortedKeys) {\n const data = this.entries.get(name)!;\n fileOffsets.set(name, currentOffset);\n buffer.set(data, currentOffset);\n currentOffset += data.byteLength;\n }\n\n // Write Directory\n let dirEntryOffset = dirOffset;\n const encoder = new TextEncoder();\n\n for (const name of sortedKeys) {\n const data = this.entries.get(name)!;\n\n // Name (56 bytes)\n const nameBytes = encoder.encode(name);\n if (nameBytes.length > 56) {\n // Should have been caught by addFile, but check again for safety\n throw new Error(`Path too long after encoding: ${name}`);\n }\n\n for (let i = 0; i < 56; i++) {\n if (i < nameBytes.length) {\n view.setUint8(dirEntryOffset + i, nameBytes[i]);\n } else {\n view.setUint8(dirEntryOffset + i, 0); // Padding\n }\n }\n\n // Offset\n view.setInt32(dirEntryOffset + 56, fileOffsets.get(name)!, true);\n\n // Length\n view.setInt32(dirEntryOffset + 60, data.byteLength, true);\n\n dirEntryOffset += DIRECTORY_ENTRY_SIZE;\n }\n\n return buffer;\n }\n\n /**\n * Static helper to build a PAK from a map of entries.\n */\n static buildFromEntries(entries: Map<string, Uint8Array>): Uint8Array {\n const writer = new PakWriter();\n for (const [path, data] of entries) {\n writer.addFile(path, data);\n }\n return writer.build();\n }\n}\n","export enum ResourceType {\n Texture = 'texture',\n Sound = 'sound',\n Model = 'model',\n Map = 'map',\n Sprite = 'sprite',\n ConfigString = 'configString'\n}\n\nexport interface ResourceLoadEntry {\n type: ResourceType;\n path: string;\n timestamp: number;\n frame: number;\n size?: number;\n pakSource?: string;\n}\n\nexport interface ResourceLoadLog {\n byFrame: Map<number, ResourceLoadEntry[]>;\n byTime: Map<number, ResourceLoadEntry[]>;\n uniqueResources: Map<string, ResourceLoadEntry>;\n}\n\nexport class ResourceLoadTracker {\n private tracking = false;\n private entries: ResourceLoadEntry[] = [];\n private currentFrame = 0;\n private currentTime = 0;\n\n startTracking(): void {\n this.tracking = true;\n this.entries = [];\n }\n\n stopTracking(): ResourceLoadLog {\n this.tracking = false;\n\n const log: ResourceLoadLog = {\n byFrame: new Map(),\n byTime: new Map(),\n uniqueResources: new Map()\n };\n\n for (const entry of this.entries) {\n // By Frame\n if (!log.byFrame.has(entry.frame)) {\n log.byFrame.set(entry.frame, []);\n }\n log.byFrame.get(entry.frame)!.push(entry);\n\n // By Time\n if (!log.byTime.has(entry.timestamp)) {\n log.byTime.set(entry.timestamp, []);\n }\n log.byTime.get(entry.timestamp)!.push(entry);\n\n // Unique\n const key = `${entry.type}:${entry.path}`;\n if (!log.uniqueResources.has(key)) {\n log.uniqueResources.set(key, entry);\n }\n }\n\n return log;\n }\n\n recordLoad(type: ResourceType, path: string, size?: number, pakSource?: string): void {\n if (!this.tracking) return;\n\n this.entries.push({\n type,\n path,\n timestamp: this.currentTime,\n frame: this.currentFrame,\n size,\n pakSource\n });\n }\n\n setCurrentFrame(frame: number): void {\n this.currentFrame = frame;\n }\n\n setCurrentTime(time: number): void {\n this.currentTime = time;\n }\n}\n","import { PakArchive, PakDirectoryEntry, normalizePath } from './pak.js';\n\ntype VfsSource = { archive: PakArchive; entry: PakDirectoryEntry; priority: number };\n\nexport interface VirtualFileHandle {\n readonly path: string;\n readonly size: number;\n readonly sourcePak: string;\n}\n\nexport interface FileMetadata extends VirtualFileHandle {\n readonly offset: number;\n}\n\nexport interface FileInfo extends VirtualFileHandle {}\n\nexport interface DirectoryNode {\n readonly name: string;\n readonly path: string;\n readonly files: FileInfo[];\n readonly directories: DirectoryNode[];\n}\n\nexport interface PakInfo {\n readonly filename: string;\n readonly entryCount: number;\n readonly totalSize: number;\n readonly priority?: number;\n}\n\nexport interface DirectoryListing {\n readonly files: VirtualFileHandle[];\n readonly directories: string[];\n}\n\ninterface MountedPak {\n pak: PakArchive;\n priority: number;\n}\n\nexport class VirtualFileSystem {\n private readonly mounts: MountedPak[] = [];\n // files maps path -> list of sources, sorted by priority (high to low)\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, priority: number = 0): void {\n // Remove if already mounted to update priority\n const existingIndex = this.mounts.findIndex(m => m.pak === archive);\n if (existingIndex !== -1) {\n this.mounts.splice(existingIndex, 1);\n }\n\n this.mounts.push({ pak: archive, priority });\n this.mounts.sort((a, b) => b.priority - a.priority); // Sort high priority first\n\n // Index files\n for (const entry of archive.listEntries()) {\n const key = normalizePath(entry.name);\n const source: VfsSource = { archive, entry, priority };\n\n if (!this.files.has(key)) {\n this.files.set(key, []);\n }\n const sources = this.files.get(key)!;\n\n // Remove existing entry for this archive if any\n const idx = sources.findIndex(s => s.archive === archive);\n if (idx !== -1) {\n sources.splice(idx, 1);\n }\n\n // Use unshift to prepend so that for equal priority, the last mounted one comes first\n sources.unshift(source);\n // Sort sources by priority descending (stable sort preserves insertion order for equal priority)\n sources.sort((a, b) => b.priority - a.priority);\n }\n }\n\n setPriority(archive: PakArchive, priority: number): void {\n this.mountPak(archive, priority);\n }\n\n getPaks(): MountedPak[] {\n // Return a copy, sorted by priority ascending to match likely test expectations or intuitive order (base -> mod)\n // Actually, if we want \"getPaks\" to represent the load order (usually base first), then ascending priority makes sense.\n return [...this.mounts].sort((a, b) => a.priority - b.priority);\n }\n\n get mountedPaks(): readonly PakArchive[] {\n return this.mounts.map(m => m.pak);\n }\n\n hasFile(path: string): boolean {\n return this.files.has(normalizePath(path));\n }\n\n private getSource(path: string): VfsSource | undefined {\n const sources = this.files.get(normalizePath(path));\n if (!sources || sources.length === 0) return undefined;\n // Sources are sorted by priority desc, so first one is the winner\n return sources[0];\n }\n\n stat(path: string): VirtualFileHandle | undefined {\n const source = this.getSource(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 getFileMetadata(path: string): FileMetadata | undefined {\n const source = this.getSource(path);\n if (!source) {\n return undefined;\n }\n return {\n path: source.entry.name,\n size: source.entry.length,\n sourcePak: source.archive.name,\n offset: source.entry.offset,\n };\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n const source = this.getSource(path);\n if (!source) {\n throw new Error(`File not found in VFS: ${path}`);\n }\n return source.archive.readFile(path);\n }\n\n async readBinaryFile(path: string): Promise<Uint8Array> {\n return this.readFile(path);\n }\n\n streamFile(path: string, chunkSize = 1024 * 1024): ReadableStream<Uint8Array> {\n const source = this.getSource(path);\n if (!source) {\n throw new Error(`File not found in VFS: ${path}`);\n }\n\n const { archive } = source;\n // Note: PakArchive currently reads full file. Streaming would require PakArchive to support streaming.\n // For now, we simulate streaming from the full buffer or if PakArchive supports range requests.\n // Assuming PakArchive.readFile returns full buffer.\n const fullData = archive.readFile(path); // This is likely sync or returns Uint8Array directly based on existing code.\n\n // Wait, `archive.readFile` might be async?\n // Looking at previous `readFile` implementation, it returns `Uint8Array`.\n // So we just wrap it.\n\n let offset = 0;\n const totalSize = fullData.length;\n\n return new ReadableStream({\n pull(controller) {\n if (offset >= totalSize) {\n controller.close();\n return;\n }\n\n const end = Math.min(offset + chunkSize, totalSize);\n const chunk = fullData.slice(offset, end);\n offset = end;\n controller.enqueue(chunk);\n }\n });\n }\n\n async readTextFile(path: string): Promise<string> {\n const data = await this.readFile(path);\n return new TextDecoder('utf-8').decode(data);\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 [path, sources] of this.files) {\n const source = sources[0]; // Winner\n // Check if file is in directory\n // path is normalized\n\n // If dir is empty, we look for anything not starting with /.\n // But normalizePath removes leading /.\n\n if (dir) {\n if (!source.entry.name.startsWith(prefix)) {\n continue;\n }\n }\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 async listDirectory(path: string): Promise<FileInfo[]> {\n const listing = this.list(path);\n return listing.files;\n }\n\n findByExtension(extension: string): VirtualFileHandle[] {\n const normalizedExt = extension.startsWith('.') ? extension.toLowerCase() : `.${extension.toLowerCase()}`;\n const results: VirtualFileHandle[] = [];\n for (const [path, sources] of this.files) {\n const source = sources[0];\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 listByExtension(extensions: string[]): FileInfo[] {\n const normalizedExts = new Set(\n extensions.map((ext) => (ext.startsWith('.') ? ext.toLowerCase() : `.${ext.toLowerCase()}`)),\n );\n const results: FileInfo[] = [];\n for (const [path, sources] of this.files) {\n const source = sources[0];\n const name = source.entry.name.toLowerCase();\n for (const ext of normalizedExts) {\n if (name.endsWith(ext)) {\n results.push({\n path: source.entry.name,\n size: source.entry.length,\n sourcePak: source.archive.name,\n });\n break;\n }\n }\n }\n return results.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n searchFiles(pattern: RegExp): FileInfo[] {\n const results: FileInfo[] = [];\n for (const [path, sources] of this.files) {\n const source = sources[0];\n if (pattern.test(source.entry.name)) {\n results.push({\n path: source.entry.name,\n size: source.entry.length,\n sourcePak: source.archive.name,\n });\n }\n }\n return results.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n getPakInfo(): PakInfo[] {\n return this.mounts.map((m) => ({\n filename: m.pak.name,\n entryCount: m.pak.listEntries().length,\n totalSize: m.pak.size,\n priority: m.priority\n }));\n }\n\n getDirectoryTree(): DirectoryNode {\n const root: DirectoryNode = {\n name: '',\n path: '',\n files: [],\n directories: [],\n };\n\n const nodeMap = new Map<string, DirectoryNode>();\n nodeMap.set('', root);\n\n // Get all files and sort them to ensure consistent tree\n const allFiles = Array.from(this.files.values())\n .map((sources) => {\n const s = sources[0];\n return {\n path: s.entry.name,\n size: s.entry.length,\n sourcePak: s.archive.name,\n };\n })\n .sort((a, b) => a.path.localeCompare(b.path));\n\n for (const file of allFiles) {\n const parts = file.path.split('/');\n const fileName = parts.pop()!;\n let currentPath = '';\n let currentNode = root;\n\n for (const part of parts) {\n const parentPath = currentPath;\n currentPath = currentPath ? `${currentPath}/${part}` : part;\n\n let nextNode = nodeMap.get(currentPath);\n if (!nextNode) {\n nextNode = {\n name: part,\n path: currentPath,\n files: [],\n directories: [],\n };\n currentNode.directories.push(nextNode);\n nodeMap.set(currentPath, nextNode);\n }\n currentNode = nextNode;\n }\n\n currentNode.files.push(file);\n }\n\n return root;\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 private currentMemoryUsage = 0;\n\n constructor(\n private readonly capacity: number,\n private readonly maxMemory: number = Infinity,\n private readonly sizeCalculator: (value: T) => number = () => 0\n ) {\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 get memoryUsage(): number {\n return this.currentMemoryUsage;\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 // Refresh item position (delete and re-add)\n this.map.delete(key);\n this.map.set(key, value);\n return value;\n }\n\n set(key: string, value: T): void {\n const itemSize = this.sizeCalculator(value);\n\n // If item exists, remove it first (updating memory)\n if (this.map.has(key)) {\n this.delete(key);\n }\n\n this.map.set(key, value);\n this.currentMemoryUsage += itemSize;\n\n this.evict();\n }\n\n delete(key: string): boolean {\n const value = this.map.get(key);\n if (value !== undefined) {\n this.currentMemoryUsage -= this.sizeCalculator(value);\n return this.map.delete(key);\n }\n return false;\n }\n\n clear(): void {\n this.map.clear();\n this.currentMemoryUsage = 0;\n }\n\n entries(): CacheEntry<T>[] {\n return Array.from(this.map.entries()).reverse().map(([key, value]) => ({ key, value }));\n }\n\n private evict(): void {\n // Evict based on capacity\n while (this.map.size > this.capacity) {\n const oldestKey = this.map.keys().next();\n if (!oldestKey.done) {\n this.delete(oldestKey.value);\n } else {\n break;\n }\n }\n\n // Evict based on memory\n while (this.currentMemoryUsage > this.maxMemory && this.map.size > 0) {\n const oldestKey = this.map.keys().next();\n if (!oldestKey.done) {\n this.delete(oldestKey.value);\n } else {\n break;\n }\n }\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 * Returns a sorted array of unique entity classnames present in the map.\n */\n getUniqueClassnames(): string[];\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 /**\n * Finds the closest brush-based entity that intersects with the given ray.\n * @param ray An object defining the origin and direction of the ray.\n * @returns An object containing the intersected entity, its model, and the\n * distance from the ray's origin, or null if no intersection occurs.\n */\n pickEntity(ray: { origin: Vec3; direction: Vec3 }): {\n entity: BspEntity;\n model: BspModel;\n distance: number;\n } | null;\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 const map: BspMap = {\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 pickEntity(ray) {\n let closest: { entity: BspEntity; model: BspModel; distance: number } | null = null;\n let minDistance = Infinity;\n\n for (const entity of entities.entities) {\n const modelKey = entity.properties['model'];\n if (!modelKey || !modelKey.startsWith('*')) {\n continue;\n }\n\n const modelIndex = parseInt(modelKey.substring(1), 10);\n if (isNaN(modelIndex) || modelIndex < 0 || modelIndex >= models.length) {\n continue;\n }\n\n const model = models[modelIndex];\n const dist = intersectRayAabb(ray.origin, ray.direction, model.mins, model.maxs);\n\n if (dist !== null && dist < minDistance) {\n minDistance = dist;\n closest = { entity, model, distance: dist };\n }\n }\n\n return closest;\n },\n };\n\n return map;\n}\n\nfunction intersectRayAabb(origin: Vec3, direction: Vec3, mins: Vec3, maxs: Vec3): number | null {\n let tmin = 0;\n let tmax = Infinity;\n\n for (let i = 0; i < 3; i++) {\n if (Math.abs(direction[i]) < 1e-8) {\n if (origin[i] < mins[i] || origin[i] > maxs[i]) {\n return null;\n }\n } else {\n const invD = 1.0 / direction[i];\n let t0 = (mins[i] - origin[i]) * invD;\n let t1 = (maxs[i] - origin[i]) * invD;\n if (t0 > t1) {\n const temp = t0;\n t0 = t1;\n t1 = temp;\n }\n tmin = Math.max(tmin, t0);\n tmax = Math.min(tmax, t1);\n if (tmin > tmax) {\n return null;\n }\n }\n }\n\n return tmin;\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 {\n raw,\n entities,\n worldspawn,\n getUniqueClassnames() {\n const classnames = new Set<string>();\n for (const entity of entities) {\n if (entity.classname) {\n classnames.add(entity.classname);\n }\n }\n return Array.from(classnames).sort();\n },\n };\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 = 28;\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 = 4;\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 { ANORMS as MD2_NORMALS } from '@quake2ts/shared';\nimport { Vec3 } from '@quake2ts/shared';\nimport { VirtualFileSystem } from './vfs.js';\n\nconst MD2_MAGIC = 844121161; // 'IDP2'\nconst MD2_VERSION = 8;\nconst HEADER_SIZE = 68;\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 readonly magic: 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 readonly minBounds: Vec3;\n readonly maxBounds: Vec3;\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 * Multiple LOD versions of model (high, medium, low poly)\n */\n readonly lods?: Md2Model[];\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 private readonly cache = new Map<string, Md2Model>();\n\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<Md2Model> {\n if (this.cache.has(path)) {\n return this.cache.get(path)!;\n }\n const bytes = await this.vfs.readFile(path);\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n const model = parseMd2(copy.buffer);\n this.cache.set(path, model);\n return model;\n }\n\n get(path: string): Md2Model | undefined {\n return this.cache.get(path);\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 magic: ident\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 let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n\n for (let v = 0; v < header.numVertices; v += 1) {\n const offset = 40 + v * 4;\n const x = view.getUint8(offset) * scale.x + translate.x;\n const y = view.getUint8(offset + 1) * scale.y + translate.y;\n const z = view.getUint8(offset + 2) * scale.z + translate.z;\n\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (z < minZ) minZ = z;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n if (z > maxZ) maxZ = z;\n\n const position: Vec3 = { x, y, z };\n const normalIndex = view.getUint8(offset + 3);\n const normalArr = MD2_NORMALS[normalIndex] as unknown as [number, number, number];\n if (!normalArr) {\n throw new Md2ParseError(`Invalid normal index ${normalIndex} in frame ${name}`);\n }\n const normal: Vec3 = { x: normalArr[0], y: normalArr[1], z: normalArr[2] };\n vertices.push({ position, normalIndex, normal });\n }\n\n frames.push({\n name,\n vertices,\n minBounds: { x: minX, y: minY, z: minZ },\n maxBounds: { x: maxX, y: maxY, z: maxZ },\n });\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 readonly magic?: number; // Compatibility shim\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 magic: ident\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 private readonly cache = new Map<string, Md3Model>();\n\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<Md3Model> {\n if (this.cache.has(path)) {\n return this.cache.get(path)!;\n }\n const data = await this.vfs.readFile(path);\n const model = parseMd3(data.slice().buffer);\n this.cache.set(path, model);\n return model;\n }\n\n get(path: string): Md3Model | undefined {\n return this.cache.get(path);\n }\n}\n","import { VirtualFileSystem } from './vfs.js';\n\nconst IDSPRITEHEADER = 0x32534449; // 'IDS2' (Little Endian)\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 frame0: number;\n readonly frame1: 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 { frame0: state.sequence.end, frame1: 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 frame0 = state.sequence.start + baseFrame;\n const frame1 = baseFrame + 1 >= totalFrames ? (loop ? state.sequence.start : state.sequence.end) : frame0 + 1;\n const lerp = !loop && baseFrame >= totalFrames - 1 ? 0 : normalizedPosition - baseFrame;\n return { frame0, frame1, 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","export interface TgaImage {\n readonly width: number;\n readonly height: number;\n readonly bitsPerPixel: number;\n readonly pixels: Uint8Array;\n}\n\nexport class TgaParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TgaParseError';\n }\n}\n\n/**\n * Parses a TGA image buffer into raw RGBA pixels.\n * Based on original Quake 2 TGA loading in ref_gl/gl_image.c (LoadTGA)\n */\nexport function parseTga(buffer: ArrayBuffer): TgaImage {\n const view = new DataView(buffer);\n\n if (buffer.byteLength < 18) {\n throw new TgaParseError('Buffer too small for TGA header');\n }\n\n // Header parsing\n // See ref_gl/gl_image.c: LoadTGA\n const idLength = view.getUint8(0);\n const colorMapType = view.getUint8(1);\n const imageType = view.getUint8(2);\n\n // Image spec (starts at offset 8)\n // 8-9: x origin (ignored)\n // 10-11: y origin (ignored)\n const width = view.getUint16(12, true);\n const height = view.getUint16(14, true);\n const pixelDepth = view.getUint8(16);\n const imageDescriptor = view.getUint8(17);\n\n // Validation\n if (imageType !== 2 && imageType !== 10 && imageType !== 3 && imageType !== 11) {\n throw new TgaParseError(`Unsupported TGA image type: ${imageType} (only RGB/Grayscale supported)`);\n }\n\n if (pixelDepth !== 24 && pixelDepth !== 32 && pixelDepth !== 8) {\n throw new TgaParseError(`Unsupported pixel depth: ${pixelDepth} (only 8, 24, 32 bpp supported)`);\n }\n\n const isRle = imageType >= 9;\n const isGrayscale = imageType === 3 || imageType === 11;\n const bytesPerPixel = pixelDepth / 8;\n\n let offset = 18 + idLength;\n\n // Skip color map if present\n if (colorMapType === 1) {\n const colorMapLength = view.getUint16(5, true);\n const colorMapEntrySize = view.getUint8(7);\n offset += colorMapLength * (colorMapEntrySize / 8);\n }\n\n const pixelCount = width * height;\n const pixels = new Uint8Array(pixelCount * 4); // Always output RGBA\n\n // Pre-calculate origin bit for vertical flip\n // Bit 5 of descriptor: 0 = origin at bottom-left, 1 = top-left\n const originTopLeft = (imageDescriptor & 0x20) !== 0;\n\n // We decode into a flat RGBA buffer. If origin is bottom-left, we'll need to flip later\n // or write in reverse order. For simplicity, let's decode to a temp buffer then flip if needed.\n // Actually, standard TGA is typically bottom-left (OpenGL style), but Quake textures might vary.\n // Let's decode linearly first.\n\n let currentPixel = 0;\n const rawData = new Uint8Array(buffer);\n\n // Helper to read a pixel color\n const readPixel = (outIndex: number) => {\n if (isGrayscale) {\n const gray = rawData[offset++];\n pixels[outIndex] = gray;\n pixels[outIndex + 1] = gray;\n pixels[outIndex + 2] = gray;\n pixels[outIndex + 3] = 255;\n } else {\n const b = rawData[offset++];\n const g = rawData[offset++];\n const r = rawData[offset++];\n const a = pixelDepth === 32 ? rawData[offset++] : 255;\n\n pixels[outIndex] = r;\n pixels[outIndex + 1] = g;\n pixels[outIndex + 2] = b;\n pixels[outIndex + 3] = a;\n }\n };\n\n if (!isRle) {\n // Uncompressed - standard pixel reading\n for (let i = 0; i < pixelCount; i++) {\n if (offset >= buffer.byteLength) {\n throw new TgaParseError('Unexpected end of TGA data');\n }\n readPixel(i * 4);\n }\n } else {\n // RLE Compressed\n // See ref_gl/gl_image.c: LoadTGA (RLE handling section)\n let pixelsRead = 0;\n while (pixelsRead < pixelCount) {\n if (offset >= buffer.byteLength) {\n throw new TgaParseError('Unexpected end of TGA RLE data');\n }\n\n const packetHeader = rawData[offset++];\n const count = (packetHeader & 0x7f) + 1;\n const isRlePacket = (packetHeader & 0x80) !== 0;\n\n if (pixelsRead + count > pixelCount) {\n throw new TgaParseError('TGA RLE packet exceeds image bounds');\n }\n\n if (isRlePacket) {\n // Run-length packet: read one pixel value and repeat it\n const r = isGrayscale ? rawData[offset] : rawData[offset + 2];\n const g = isGrayscale ? rawData[offset] : rawData[offset + 1];\n const b = isGrayscale ? rawData[offset] : rawData[offset];\n const a = isGrayscale ? 255 : (pixelDepth === 32 ? rawData[offset + 3] : 255);\n offset += bytesPerPixel;\n\n for (let i = 0; i < count; i++) {\n const idx = (pixelsRead + i) * 4;\n pixels[idx] = r;\n pixels[idx + 1] = g;\n pixels[idx + 2] = b;\n pixels[idx + 3] = a;\n }\n } else {\n // Raw packet: read 'count' pixels directly\n for (let i = 0; i < count; i++) {\n readPixel((pixelsRead + i) * 4);\n }\n }\n pixelsRead += count;\n }\n }\n\n // Handle flipping if origin is bottom-left (standard TGA) to match top-left usage usually expected\n // Actually, Quake 2 textures (WAL) are top-left.\n // If the TGA descriptor says bottom-left (bit 5 == 0), we need to flip Y to get top-left.\n if (!originTopLeft) {\n const stride = width * 4;\n const tempRow = new Uint8Array(stride);\n for (let y = 0; y < height / 2; y++) {\n const topRowIdx = y * stride;\n const bottomRowIdx = (height - 1 - y) * stride;\n\n // Swap rows\n tempRow.set(pixels.subarray(topRowIdx, topRowIdx + stride));\n pixels.set(pixels.subarray(bottomRowIdx, bottomRowIdx + stride), topRowIdx);\n pixels.set(tempRow, bottomRowIdx);\n }\n }\n\n return {\n width,\n height,\n bitsPerPixel: 32, // We normalized to RGBA\n pixels\n };\n}\n","import { LruCache } from './cache.js';\nimport { pcxToRgba, type PcxImage } from './pcx.js';\nimport { parseWal, type WalTexture } from './wal.js';\nimport { TgaImage } from './tga.js';\n\nexport interface PreparedTexture {\n readonly width: number;\n readonly height: number;\n readonly levels: readonly TextureLevel[];\n readonly source: 'pcx' | 'wal' | 'tga';\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 readonly maxMemory?: number;\n}\n\nfunction calculateTextureSize(texture: PreparedTexture): number {\n let size = 0;\n for (const level of texture.levels) {\n size += level.rgba.byteLength;\n }\n return size;\n}\n\nexport class TextureCache {\n private readonly cache: LruCache<PreparedTexture>;\n\n constructor(options: TextureCacheOptions = {}) {\n this.cache = new LruCache<PreparedTexture>(\n options.capacity ?? 128,\n options.maxMemory ?? 256 * 1024 * 1024, // Default 256MB\n calculateTextureSize\n );\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n get memoryUsage(): number {\n return this.cache.memoryUsage;\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 prepareTgaTexture(tga: TgaImage): PreparedTexture {\n const level: TextureLevel = { level: 0, width: tga.width, height: tga.height, rgba: tga.pixels };\n return { width: tga.width, height: tga.height, levels: [level], source: 'tga' };\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, parseWalTexture, preparePcxTexture, prepareTgaTexture } 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, VirtualFileHandle } from './vfs.js';\nimport { parsePcx } from './pcx.js';\nimport { parseTga } from './tga.js';\nimport { BspLoader, type BspMap } from './bsp.js';\nimport { ResourceLoadTracker, ResourceType } from './resourceTracker.js';\n\nexport type AssetType = 'texture' | 'model' | 'sound' | 'sprite' | 'map';\n\nexport interface MemoryUsage {\n textures: number;\n audio: number;\n heapTotal?: number;\n heapUsed?: number;\n}\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\ninterface AssetTask {\n path: string;\n type: AssetType;\n priority: number;\n resolve: (value: any) => void;\n reject: (err: any) => void;\n}\n\nexport interface AssetManagerOptions {\n readonly textureCacheCapacity?: number;\n readonly textureMemoryLimit?: number;\n readonly audioCacheSize?: number;\n readonly dependencyTracker?: AssetDependencyTracker;\n readonly resourceTracker?: ResourceLoadTracker;\n readonly maxConcurrentLoads?: number;\n}\n\nexport class AssetManager {\n readonly textures: TextureCache;\n readonly audio: AudioRegistry;\n readonly dependencyTracker: AssetDependencyTracker;\n readonly resourceTracker?: ResourceLoadTracker;\n private readonly md2: Md2Loader;\n private readonly md3: Md3Loader;\n private readonly sprite: SpriteLoader;\n private readonly bsp: BspLoader;\n private palette: Uint8Array;\n private readonly maps = new Map<string, BspMap>();\n\n private readonly loadQueue: AssetTask[] = [];\n private activeLoads = 0;\n private readonly maxConcurrentLoads: number;\n\n constructor(private readonly vfs: VirtualFileSystem, options: AssetManagerOptions = {}) {\n this.textures = new TextureCache({\n capacity: options.textureCacheCapacity ?? 128,\n maxMemory: options.textureMemoryLimit\n });\n this.audio = new AudioRegistry(vfs, { cacheSize: options.audioCacheSize ?? 64 });\n this.dependencyTracker = options.dependencyTracker ?? new AssetDependencyTracker();\n this.resourceTracker = options.resourceTracker;\n this.md2 = new Md2Loader(vfs);\n this.md3 = new Md3Loader(vfs);\n this.sprite = new SpriteLoader(vfs);\n this.bsp = new BspLoader(vfs);\n this.maxConcurrentLoads = options.maxConcurrentLoads ?? 4;\n\n // Default grayscale palette until loaded\n this.palette = new Uint8Array(768);\n for (let i = 0; i < 256; i++) {\n this.palette[i*3] = i;\n this.palette[i*3+1] = i;\n this.palette[i*3+2] = i;\n }\n }\n\n /**\n * Loads the global palette (pics/colormap.pcx) if available.\n * This is required for loading WAL textures.\n */\n async loadPalette(path: string = 'pics/colormap.pcx'): Promise<void> {\n try {\n const buffer = await this.vfs.readFile(path);\n // buffer from vfs.readFile returns ArrayBuffer | SharedArrayBuffer\n // parsePcx expects ArrayBuffer.\n const pcx = parsePcx(buffer as unknown as ArrayBuffer);\n if (pcx.palette) {\n this.palette = pcx.palette;\n }\n } catch (e) {\n console.warn(`Failed to load palette from ${path}:`, e);\n }\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 loadTexture(path: string): Promise<PreparedTexture> {\n if (this.resourceTracker) {\n const stats = this.vfs.stat(path);\n this.resourceTracker.recordLoad(ResourceType.Texture, path, stats?.size, stats?.sourcePak);\n }\n const cached = this.textures.get(path);\n if (cached) return cached;\n\n const buffer = await this.vfs.readFile(path);\n const ext = path.split('.').pop()?.toLowerCase();\n\n let texture: PreparedTexture;\n\n if (ext === 'wal') {\n texture = parseWalTexture(buffer as unknown as ArrayBuffer, this.palette);\n } else if (ext === 'pcx') {\n texture = preparePcxTexture(parsePcx(buffer as unknown as ArrayBuffer));\n } else if (ext === 'tga') {\n texture = prepareTgaTexture(parseTga(buffer as unknown as ArrayBuffer));\n } else {\n throw new Error(`Unsupported texture format for loadTexture: ${ext}`);\n }\n\n this.registerTexture(path, texture);\n return texture;\n }\n\n async loadSound(path: string): Promise<DecodedAudio> {\n if (this.resourceTracker) {\n const stats = this.vfs.stat(path);\n this.resourceTracker.recordLoad(ResourceType.Sound, path, stats?.size, stats?.sourcePak);\n }\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 if (this.resourceTracker) {\n const stats = this.vfs.stat(path);\n this.resourceTracker.recordLoad(ResourceType.Model, path, stats?.size, stats?.sourcePak);\n }\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 getMd2Model(path: string): Md2Model | undefined {\n if (this.resourceTracker) {\n const stats = this.vfs.stat(path);\n this.resourceTracker.recordLoad(ResourceType.Model, path, stats?.size, stats?.sourcePak);\n }\n return this.md2.get(path);\n }\n\n async loadMd3Model(path: string, textureDependencies: readonly string[] = []): Promise<Md3Model> {\n if (this.resourceTracker) {\n const stats = this.vfs.stat(path);\n this.resourceTracker.recordLoad(ResourceType.Model, path, stats?.size, stats?.sourcePak);\n }\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 getMd3Model(path: string): Md3Model | undefined {\n if (this.resourceTracker) {\n const stats = this.vfs.stat(path);\n this.resourceTracker.recordLoad(ResourceType.Model, path, stats?.size, stats?.sourcePak);\n }\n return this.md3.get(path);\n }\n\n async loadSprite(path: string): Promise<SpriteModel> {\n if (this.resourceTracker) {\n const stats = this.vfs.stat(path);\n this.resourceTracker.recordLoad(ResourceType.Sprite, path, stats?.size, stats?.sourcePak);\n }\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 async loadMap(path: string): Promise<BspMap> {\n if (this.resourceTracker) {\n const stats = this.vfs.stat(path);\n this.resourceTracker.recordLoad(ResourceType.Map, path, stats?.size, stats?.sourcePak);\n }\n const mapKey = this.makeKey('map', path);\n if (this.maps.has(path)) {\n return this.maps.get(path)!;\n }\n this.dependencyTracker.register(mapKey);\n const map = await this.bsp.load(path);\n this.maps.set(path, map);\n this.dependencyTracker.markLoaded(mapKey);\n return map;\n }\n\n getMap(path: string): BspMap | undefined {\n return this.maps.get(path);\n }\n\n listFiles(extension: string): VirtualFileHandle[] {\n return this.vfs.findByExtension(extension);\n }\n\n resetForLevelChange(): void {\n this.textures.clear();\n this.audio.clearAll();\n this.dependencyTracker.reset();\n this.maps.clear();\n this.loadQueue.length = 0; // Clear pending loads\n }\n\n getMemoryUsage(): MemoryUsage {\n let heapTotal = 0;\n let heapUsed = 0;\n if (typeof process !== 'undefined' && process.memoryUsage) {\n const mem = process.memoryUsage();\n heapTotal = mem.heapTotal;\n heapUsed = mem.heapUsed;\n }\n\n // Audio memory estimation is tricky as it depends on decoded buffers.\n // AudioRegistry tracks loaded sounds, but we might need to query it.\n // Assuming basic tracking for now.\n\n return {\n textures: this.textures.memoryUsage,\n audio: 0, // Placeholder\n heapTotal,\n heapUsed\n };\n }\n\n clearCache(type: AssetType): void {\n switch (type) {\n case 'texture':\n this.textures.clear();\n break;\n case 'sound':\n this.audio.clearAll();\n break;\n case 'map':\n this.maps.clear();\n break;\n // Models are currently handled by internal loaders (Md2Loader etc.)\n // which wrap LruCache internally or similar?\n // Looking at imports, Md2Loader is from ./md2.js. It likely has a cache.\n // If we want to clear models, we need to expose clear on Md2Loader.\n }\n }\n\n /**\n * Preload a list of assets with low priority.\n */\n async preloadAssets(paths: string[]): Promise<void> {\n const promises = paths.map(path => {\n const type = this.detectAssetType(path);\n if (type) {\n return this.queueLoad(path, type, 0); // Low priority 0\n }\n return Promise.resolve();\n });\n await Promise.all(promises);\n }\n\n /**\n * Queue an asset for loading.\n * @param path The path to the asset.\n * @param type The type of asset.\n * @param priority Higher priority assets are loaded first. Default 1 (High).\n */\n queueLoad<T>(path: string, type: AssetType, priority: number = 1): Promise<T> {\n // If already loaded, return immediately\n if (type === 'texture' && this.textures.get(path)) {\n return Promise.resolve(this.textures.get(path) as unknown as T);\n }\n // Add similar checks for other types if possible\n\n return new Promise<T>((resolve, reject) => {\n this.loadQueue.push({\n path,\n type,\n priority,\n resolve,\n reject\n });\n this.loadQueue.sort((a, b) => b.priority - a.priority);\n this.processQueue();\n });\n }\n\n private async processQueue() {\n if (this.activeLoads >= this.maxConcurrentLoads || this.loadQueue.length === 0) {\n return;\n }\n\n const task = this.loadQueue.shift()!;\n this.activeLoads++;\n\n try {\n let result;\n switch (task.type) {\n case 'texture':\n result = await this.loadTexture(task.path);\n break;\n case 'sound':\n result = await this.loadSound(task.path);\n break;\n case 'model':\n // Heuristic: MD2 vs MD3\n if (task.path.endsWith('.md2')) {\n result = await this.loadMd2Model(task.path);\n } else if (task.path.endsWith('.md3')) {\n result = await this.loadMd3Model(task.path);\n }\n break;\n case 'sprite':\n result = await this.loadSprite(task.path);\n break;\n case 'map':\n result = await this.loadMap(task.path);\n break;\n default:\n throw new Error(`Unknown asset type ${task.type}`);\n }\n task.resolve(result);\n } catch (err) {\n task.reject(err);\n } finally {\n this.activeLoads--;\n this.processQueue();\n }\n }\n\n private detectAssetType(path: string): AssetType | null {\n const ext = path.split('.').pop()?.toLowerCase();\n if (!ext) return null;\n if (['wal', 'pcx', 'tga', 'png', 'jpg'].includes(ext)) return 'texture';\n if (['wav', 'ogg'].includes(ext)) return 'sound';\n if (['md2', 'md3'].includes(ext)) return 'model';\n if (['sp2'].includes(ext)) return 'sprite';\n if (['bsp'].includes(ext)) return 'map';\n return null;\n }\n\n private makeKey(type: AssetType, path: string): string {\n return `${type}:${normalizePath(path)}`;\n }\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 ConvolverNodeLike extends AudioNodeLike {\n buffer: AudioBufferLike | null;\n normalize: boolean;\n}\n\nexport interface AudioBufferLike {\n readonly duration: number;\n}\n\nexport interface AudioBufferSourceNodeLike extends AudioNodeLike {\n buffer: AudioBufferLike | null;\n loop: boolean;\n playbackRate: AudioParamLike;\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 createConvolver?(): ConvolverNodeLike;\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 reverb?: ReverbNode;\n}\n\nexport interface ReverbNode {\n convolver: ConvolverNodeLike;\n input: GainNodeLike; // Send to reverb\n output: GainNodeLike; // Return from reverb\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\n // Create reverb nodes if supported\n let reverb: ReverbNode | undefined;\n if (context.createConvolver && context.createGain) {\n const convolver = context.createConvolver();\n const input = context.createGain();\n const output = context.createGain();\n\n input.connect(convolver);\n convolver.connect(output);\n // Connect reverb output to master (will be routed through filter/compressor below)\n\n reverb = { convolver, input, output };\n }\n\n // Routing\n // Master -> Filter (optional) -> Compressor -> Destination\n\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\n // Connect reverb output to filter so it gets low-passed underwater too\n if (reverb) {\n reverb.output.connect(filter);\n }\n } else {\n master.connect(compressor);\n if (reverb) {\n reverb.output.connect(compressor);\n }\n }\n\n compressor.connect(context.destination);\n\n return { context, master, compressor, filter, reverb };\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 getName(index: number): string | undefined {\n return this.configStrings.getName(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 type { AudioBufferLike, ReverbNode } from './context.js';\n\nexport interface ReverbPreset {\n name: string;\n buffer: AudioBufferLike;\n gain?: number; // Output gain adjustment for this specific IR\n}\n\nexport class ReverbSystem {\n private activePreset: ReverbPreset | null = null;\n private readonly node: ReverbNode;\n private enabled = true;\n\n constructor(node: ReverbNode) {\n this.node = node;\n // Default levels\n this.node.input.gain.value = 0.5; // Default send level\n this.node.output.gain.value = 1.0; // Default return level\n }\n\n setPreset(preset: ReverbPreset | null) {\n this.activePreset = preset;\n if (this.node.convolver.buffer !== (preset?.buffer ?? null)) {\n this.node.convolver.buffer = preset?.buffer ?? null;\n }\n\n // Adjust output gain based on preset\n if (preset && preset.gain !== undefined) {\n this.node.output.gain.value = preset.gain;\n } else {\n this.node.output.gain.value = 1.0;\n }\n }\n\n setEnabled(enabled: boolean) {\n this.enabled = enabled;\n if (!enabled) {\n this.node.input.gain.value = 0;\n } else {\n this.node.input.gain.value = 0.5; // Restore default\n }\n }\n\n getOutputNode() {\n return this.node.output;\n }\n\n getInputNode() {\n return this.node.input;\n }\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 type AudioNodeLike,\n} from './context.js';\nimport { SoundRegistry } from './registry.js';\nimport { baseChannel, createInitialChannels, pickChannel, type ChannelState } from './channels.js';\nimport { ReverbSystem, type ReverbPreset } from './reverb.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\nexport interface 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 interface ListenerState {\n origin: Vec3;\n right: Vec3;\n mono?: boolean;\n playerEntity?: 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 private playbackRate: number = 1.0;\n\n public readonly reverb: ReverbSystem | undefined;\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 if (this.graph.reverb) {\n this.reverb = new ReverbSystem(this.graph.reverb);\n }\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 setPlaybackRate(rate: number): void {\n this.playbackRate = rate;\n // Iterate active sources and update rate\n for (const active of this.activeSources.values()) {\n if (active.source.playbackRate) {\n active.source.playbackRate.value = rate;\n }\n // Apply muting if rate is not 1.0 (to avoid pitch shift artifacts)\n this.updateSourceGain(active);\n }\n }\n\n async ensureRunning(): Promise<void> {\n await this.contextController.resume();\n }\n\n setReverbPreset(preset: ReverbPreset | null): void {\n this.reverb?.setPreset(preset);\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 if (source.playbackRate) {\n source.playbackRate.value = this.playbackRate;\n }\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\n // Gain logic: only apply base volume, master, sfx.\n // Panner handles distance attenuation and spatialization.\n const baseVolume = request.volume / 255;\n const gainValue = baseVolume * this.sfxVolume; // masterVolume is on graph.master\n\n // Mute if playback rate is not 1.0 (if desired, though usually we might want pitch shift)\n const playbackRateMute = Math.abs(this.playbackRate - 1.0) < 0.001 ? 1 : 0;\n\n gain.gain.value = gainValue * occlusionScale * playbackRateMute;\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\n let finalNode: AudioNodeLike = panner;\n\n if (occlusionFilter) {\n panner.connect(occlusionFilter);\n occlusionFilter.connect(gain);\n finalNode = gain;\n } else {\n panner.connect(gain);\n finalNode = gain;\n }\n\n gain.connect(this.graph.master);\n\n // Send to reverb\n if (this.reverb) {\n gain.connect(this.reverb.getInputNode());\n }\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 = 'linear'; // Use linear for everything to match Quake 2\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\n // For ATTN_NONE (0), we might want no attenuation.\n // If attenuation is 0, distMult is 0. rolloffFactor 0 means no distance attenuation.\n // So linear model with rolloff 0 is correct.\n\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 updateSourceGain(active: ActiveSound) {\n // Re-calculate effective gain based on baseGain, occlusion, and playback rate\n const occlusionScale = active.occlusion?.scale ?? 1;\n const playbackRateMute = Math.abs(this.playbackRate - 1.0) < 0.001 ? 1 : 0;\n active.gain.gain.value = active.baseGain * occlusionScale * playbackRateMute;\n }\n\n private applyOcclusion(active: ActiveSound, occlusion?: OcclusionResult): void {\n const scale = clamp01(occlusion?.gainScale ?? 1);\n const playbackRateMute = Math.abs(this.playbackRate - 1.0) < 0.001 ? 1 : 0;\n active.gain.gain.value = active.baseGain * scale * playbackRateMute;\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","import type { OcclusionResolver, OcclusionResult, ListenerState } from './system.js';\nimport { lengthVec3, subtractVec3, type Vec3 } from '@quake2ts/shared';\nimport { calculateMaxAudibleDistance } from './constants.js';\n\n// Type definition for the engine's trace function\nexport type TraceFn = (start: Vec3, end: Vec3, mins: Vec3 | undefined, maxs: Vec3 | undefined) => {\n fraction: number;\n allsolid?: boolean;\n startsolid?: boolean;\n contents?: number;\n};\n\nexport class AudioOcclusion {\n constructor(private readonly trace: TraceFn) {}\n\n resolve: OcclusionResolver = (listener: ListenerState, source: Vec3, attenuation: number): OcclusionResult | undefined => {\n const dist = lengthVec3(subtractVec3(source, listener.origin));\n const maxDist = calculateMaxAudibleDistance(attenuation);\n\n // Distance-based low-pass\n // Even without occlusion, air absorbs high frequencies over distance.\n // We'll map distance 0..maxDist to 20000..1000 Hz.\n // This is a simple linear roll-off.\n\n // Clamp distance\n const clampedDist = Math.min(dist, maxDist);\n const distanceFactor = clampedDist / Math.max(1, maxDist); // 0 (close) to 1 (far)\n\n // Logarithmic feel? Or linear? Linear is fine for now.\n // 20kHz at 0, 2kHz at max distance\n const distanceCutoff = 20000 * (1 - distanceFactor * 0.9);\n\n // Trace from listener to source\n const tr = this.trace(listener.origin, source, undefined, undefined);\n\n let gainScale = 1.0;\n let occlusionCutoff = 20000;\n\n if (tr.fraction < 1.0) {\n // Obstructed\n gainScale = 0.3;\n occlusionCutoff = 400;\n }\n\n // Combine cutoffs (take minimum)\n const finalCutoff = Math.min(distanceCutoff, occlusionCutoff);\n\n // Only return result if we are modifying the sound\n if (gainScale < 1.0 || finalCutoff < 20000) {\n return {\n gainScale,\n lowpassHz: finalCutoff\n };\n }\n\n return undefined;\n };\n}\n\nexport function createOcclusionResolver(trace: TraceFn): OcclusionResolver {\n const occlusion = new AudioOcclusion(trace);\n return occlusion.resolve;\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 crossfadeDuration?: number; // Seconds, default 1.0\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 readonly crossfadeDuration: number;\n\n private currentElement?: AudioElementLike;\n private fadingElement?: AudioElementLike;\n\n private track?: string;\n private volume: number;\n\n private fadeInterval?: any; // Timer handle\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 this.crossfadeDuration = options.crossfadeDuration ?? 1.0;\n }\n\n async playTrack(trackNum: number): Promise<void> {\n // Standard Quake 2 track mapping: track 2 -> music/track02.ogg\n // Tracks 0 and 1 are usually data tracks on the CD and skipped.\n const trackName = `music/track${trackNum.toString().padStart(2, '0')}.ogg`;\n return this.play(trackName);\n }\n\n async play(track: string, { loop = true, restart = false }: { loop?: boolean; restart?: boolean } = {}): Promise<void> {\n // If requesting the same track\n if (this.track === track && this.currentElement) {\n // If we were fading it out, cancel that and fade back in?\n // For simplicity, if it's the same track and playing, just ensure parameters.\n this.currentElement.loop = loop;\n\n this.cancelFade();\n\n // Handle edge case where this track was being faded out\n if (this.fadingElement) {\n this.fadingElement.pause();\n this.fadingElement = undefined;\n }\n\n this.currentElement.volume = this.volume;\n\n if (restart) {\n this.currentElement.currentTime = 0;\n }\n if (this.currentElement.paused || restart) {\n await this.currentElement.play();\n }\n return;\n }\n\n const src = await this.resolveSource(track);\n\n // Stop any pending fade\n this.cancelFade();\n\n // If there is already a fading element (from a previous quick switch), stop it immediately\n if (this.fadingElement) {\n this.fadingElement.pause();\n this.fadingElement = undefined;\n }\n\n // Move current to fading\n if (this.currentElement) {\n this.fadingElement = this.currentElement;\n this.currentElement = undefined;\n }\n\n // Create new element\n const element = this.createElement();\n element.src = src;\n element.loop = loop;\n element.volume = 0; // Start at 0 for fade in\n element.currentTime = 0;\n element.load();\n\n try {\n await element.play();\n } catch (e) {\n console.warn(`MusicSystem: Failed to play ${track}`, e);\n // If fail, ensure cleanup\n if (this.fadingElement) {\n // Maybe restore old one? Or just stop.\n // For now, simple fail logic\n }\n }\n\n this.currentElement = element;\n this.track = track;\n\n this.startCrossfade();\n }\n\n pause(): void {\n this.cancelFade();\n if (this.currentElement && !this.currentElement.paused) {\n this.currentElement.pause();\n }\n if (this.fadingElement) {\n this.fadingElement.pause();\n this.fadingElement = undefined;\n }\n }\n\n async resume(): Promise<void> {\n if (!this.currentElement || !this.currentElement.paused) return;\n await this.currentElement.play();\n this.currentElement.volume = this.volume; // Ensure volume\n }\n\n stop(): void {\n this.cancelFade();\n if (this.currentElement) {\n this.currentElement.pause();\n this.currentElement.currentTime = 0;\n this.currentElement = undefined;\n }\n if (this.fadingElement) {\n this.fadingElement.pause();\n this.fadingElement = undefined;\n }\n this.track = undefined;\n }\n\n setVolume(volume: number): void {\n this.volume = volume;\n if (this.currentElement && !this.fadeInterval) {\n this.currentElement.volume = volume;\n }\n }\n\n getState(): MusicState {\n const playing = Boolean(this.currentElement && !this.currentElement.paused && !this.currentElement.ended);\n const paused = Boolean(this.currentElement?.paused);\n return { track: this.track, paused, playing, volume: this.volume };\n }\n\n private startCrossfade() {\n const stepTime = 50; // ms\n const steps = (this.crossfadeDuration * 1000) / stepTime;\n const volStep = this.volume / steps;\n\n let currentVol = 0;\n let fadingVol = this.fadingElement ? this.fadingElement.volume : 0;\n\n const tick = () => {\n let active = false;\n\n // Fade In Current\n if (this.currentElement) {\n currentVol = Math.min(this.volume, currentVol + volStep);\n this.currentElement.volume = currentVol;\n if (currentVol < this.volume) active = true;\n }\n\n // Fade Out Old\n if (this.fadingElement) {\n fadingVol = Math.max(0, fadingVol - volStep);\n this.fadingElement.volume = fadingVol;\n if (fadingVol > 0) {\n active = true;\n } else {\n // Done fading out\n this.fadingElement.pause();\n this.fadingElement = undefined;\n }\n }\n\n if (!active) {\n this.cancelFade();\n }\n };\n\n // Execute first tick immediately to avoid latency\n tick();\n\n // If still active (more steps needed), schedule interval\n if (this.currentElement && this.currentElement.volume < this.volume || this.fadingElement) {\n this.fadeInterval = setInterval(tick, stepTime);\n }\n }\n\n private cancelFade() {\n if (this.fadeInterval) {\n clearInterval(this.fadeInterval);\n this.fadeInterval = undefined;\n }\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 readonly sourceSize: number;\n\n private constructor(gl: WebGL2RenderingContext, program: WebGLProgram, sourceSize: number) {\n this.gl = gl;\n this.program = program;\n this.sourceSize = sourceSize;\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 const sourceSize = sources.vertex.length + sources.fragment.length;\n return new ShaderProgram(gl, program, sourceSize);\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 readonly faceIndex: number;\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 readonly hiddenClassnames?: Set<string>;\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 faceIndex,\n });\n }\n\n return results;\n}\n\nexport function buildBspGeometry(\n gl: WebGL2RenderingContext,\n surfaces: readonly BspSurfaceInput[],\n map?: BspMap,\n options: BspBuildOptions = {}\n): BspGeometryBuildResult {\n // Filter surfaces based on hidden classnames\n let filteredSurfaces = surfaces;\n if (map && options.hiddenClassnames && options.hiddenClassnames.size > 0) {\n const hiddenFaces = new Set<number>();\n for (const entity of map.entities.entities) {\n if (entity.classname && options.hiddenClassnames.has(entity.classname)) {\n const modelProp = entity.properties['model'];\n if (modelProp && modelProp.startsWith('*')) {\n const modelIndex = parseInt(modelProp.substring(1), 10);\n if (!isNaN(modelIndex) && modelIndex >= 0 && modelIndex < map.models.length) {\n const model = map.models[modelIndex];\n for (let i = 0; i < model.numFaces; i++) {\n hiddenFaces.add(model.firstFace + i);\n }\n }\n }\n }\n }\n if (hiddenFaces.size > 0) {\n filteredSurfaces = surfaces.filter((s) => !hiddenFaces.has(s.faceIndex));\n }\n }\n\n const resolved: Required<BspBuildOptions> = {\n atlasSize: options.atlasSize ?? 1024,\n lightmapPadding: options.lightmapPadding ?? 1,\n hiddenClassnames: options.hiddenClassnames ?? new Set(),\n };\n\n const atlasBuilders: AtlasBuilder[] = [];\n const placements = new Map<number, LightmapPlacement>();\n\n filteredSurfaces.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[] = filteredSurfaces.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, type Mat4 } 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: ArrayLike<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\nexport function transformAabb(mins: Vec3, maxs: Vec3, transform: Mat4): { mins: Vec3; maxs: Vec3 } {\n // Center and extents\n const cx = (mins.x + maxs.x) * 0.5;\n const cy = (mins.y + maxs.y) * 0.5;\n const cz = (mins.z + maxs.z) * 0.5;\n const ex = (maxs.x - mins.x) * 0.5;\n const ey = (maxs.y - mins.y) * 0.5;\n const ez = (maxs.z - mins.z) * 0.5;\n\n // Transform center\n const m = transform;\n const tcx = m[0] * cx + m[4] * cy + m[8] * cz + m[12];\n const tcy = m[1] * cx + m[5] * cy + m[9] * cz + m[13];\n const tcz = m[2] * cx + m[6] * cy + m[10] * cz + m[14];\n\n // Transform extents (absolute sum)\n const tex =\n Math.abs(m[0]) * ex + Math.abs(m[4]) * ey + Math.abs(m[8]) * ez;\n const tey =\n Math.abs(m[1]) * ex + Math.abs(m[5]) * ey + Math.abs(m[9]) * ez;\n const tez =\n Math.abs(m[2]) * ex + Math.abs(m[6]) * ey + Math.abs(m[10]) * ez;\n\n return {\n mins: { x: tcx - tex, y: tcy - tey, z: tcz - tez },\n maxs: { x: tcx + tex, y: tcy + tey, z: tcz + tez },\n };\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\nexport function 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 { Vec3 } from '@quake2ts/shared';\n\nexport interface DLight {\n /** The unique ID of the entity that owns this light (optional). */\n readonly key?: number;\n\n /** World position of the light. */\n readonly origin: Vec3;\n\n /** RGB color of the light (0-1 range). */\n readonly color: Vec3;\n\n /** Intensity/Radius of the light. */\n intensity: number;\n\n /** Minimum lighting value to add (usually 0). */\n readonly minLight?: number;\n\n /** Time when the light should be removed (seconds). */\n die: number;\n\n /** Rate of change for intensity (units per second). Default 0. */\n readonly radiusSpeed?: number;\n}\n\nexport const MAX_DLIGHTS = 32;\n\n/**\n * Manages a pool of dynamic lights.\n */\nexport class DynamicLightManager {\n private lights: DLight[] = [];\n\n /**\n * Adds a dynamic light or updates an existing one with the same key.\n */\n addLight(dlight: DLight, time: number): void {\n if (dlight.key !== undefined) {\n // Update existing light with same key\n const index = this.lights.findIndex(l => l.key === dlight.key);\n if (index !== -1) {\n this.lights[index] = dlight;\n return;\n }\n }\n\n // Add new light\n this.lights.push(dlight);\n }\n\n /**\n * Clears all lights (e.g., map change).\n */\n clear(): void {\n this.lights = [];\n }\n\n /**\n * Updates the list of active lights, removing expired ones and animating properties.\n * @param time Current game time in seconds.\n * @param dt Delta time in seconds.\n */\n update(time: number, dt: number = 0): void {\n // Filter dead lights\n this.lights = this.lights.filter(l => l.die > time);\n\n // Animate lights\n if (dt > 0) {\n for (const light of this.lights) {\n if (light.radiusSpeed !== undefined && light.radiusSpeed !== 0) {\n light.intensity += light.radiusSpeed * dt;\n if (light.intensity < 0) light.intensity = 0;\n }\n }\n }\n }\n\n /**\n * Returns the current list of active lights.\n */\n getActiveLights(): readonly DLight[] {\n return this.lights;\n }\n}\n","export function generateWireframeIndices(indices: Uint16Array | Uint32Array): Uint16Array | Uint32Array {\n const lineIndices: number[] = [];\n // Assumes TRIANGLES primitive\n for (let i = 0; i < indices.length; i += 3) {\n const a = indices[i];\n const b = indices[i + 1];\n const c = indices[i + 2];\n lineIndices.push(a, b, b, c, c, a);\n }\n\n // Preserve original type if possible, default to Uint16Array\n if (indices instanceof Uint32Array || Math.max(...lineIndices) > 65535) {\n return new Uint32Array(lineIndices);\n }\n return new Uint16Array(lineIndices);\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';\nimport { DLight, MAX_DLIGHTS } from './dlight.js';\nimport { RenderModeConfig } from './frame.js';\nimport { BspSurfaceGeometry } from './bsp.js';\nimport { IndexBuffer } from './resources.js';\nimport { generateWireframeIndices } from './geometry.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 styleLayers?: readonly number[];\n readonly diffuseSampler?: number;\n readonly lightmapSampler?: number;\n readonly refractionSampler?: number; // New: Refraction map sampler\n readonly surfaceFlags?: SurfaceFlag;\n readonly timeSeconds?: number;\n readonly texScroll?: readonly [number, number];\n readonly alpha?: number;\n readonly warp?: boolean;\n readonly dlights?: readonly DLight[];\n readonly renderMode?: RenderModeConfig;\n readonly lightmapOnly?: boolean;\n // New lighting controls\n readonly brightness?: number;\n readonly gamma?: number;\n readonly fullbright?: boolean;\n readonly ambient?: 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;\nlayout(location = 3) in float a_lightmapStep;\n\nuniform mat4 u_modelViewProjection;\nuniform vec2 u_texScroll;\nuniform vec2 u_lightmapScroll;\nuniform float u_time;\nuniform bool u_warp;\n\nout vec2 v_texCoord;\nout vec2 v_lightmapCoord;\nout float v_lightmapStep;\nout vec3 v_position;\nout vec4 v_screenPos; // For refraction\n\n// Match gl_warp.c TURBSCALE\nconst float TURBSCALE = (256.0 / (2.0 * 3.14159));\n\nvec2 applyScroll(vec2 uv, vec2 scroll) {\n return uv + scroll;\n}\n\nvoid main() {\n vec3 pos = a_position;\n vec2 tex = a_texCoord;\n vec2 lm = a_lightmapCoord;\n\n // Vertex Warping (match gl_warp.c)\n\n if (u_warp) {\n // Simple sine wave distortion\n float amp = 0.125;\n\n // Let's just use sin directly.\n float s = tex.x + sin((tex.y * 0.125 + u_time) * 1.0) * amp;\n float t = tex.y + sin((tex.x * 0.125 + u_time) * 1.0) * amp;\n\n tex = vec2(s, t);\n }\n\n v_texCoord = applyScroll(tex, u_texScroll);\n v_lightmapCoord = applyScroll(lm, u_lightmapScroll);\n v_lightmapStep = a_lightmapStep;\n v_position = pos;\n gl_Position = u_modelViewProjection * vec4(pos, 1.0);\n v_screenPos = gl_Position;\n}`;\n\nexport const BSP_SURFACE_FRAGMENT_SOURCE = `#version 300 es\nprecision highp float;\n\nstruct DLight {\n vec3 position;\n vec3 color;\n float intensity;\n};\n\nconst int MAX_DLIGHTS = ${MAX_DLIGHTS};\n\nin vec2 v_texCoord;\nin vec2 v_lightmapCoord;\nin float v_lightmapStep;\nin vec3 v_position;\nin vec4 v_screenPos;\n\nuniform sampler2D u_diffuseMap;\nuniform sampler2D u_lightmapAtlas;\nuniform sampler2D u_refractionMap; // New: Refraction map\nuniform vec4 u_lightStyleFactors;\nuniform vec4 u_styleLayerMapping; // 0, 1, 2... or -1 if invalid\nuniform float u_alpha;\nuniform bool u_applyLightmap;\nuniform bool u_warp;\nuniform bool u_lightmapOnly;\nuniform bool u_hasRefraction; // New: Flag to enable refraction\nuniform float u_time;\n\nuniform int u_renderMode; // 0: Textured, 1: Solid, 2: Solid Faceted\nuniform vec4 u_solidColor;\n\nuniform int u_numDlights;\nuniform DLight u_dlights[MAX_DLIGHTS];\n\n// Lighting controls\nuniform float u_brightness;\nuniform float u_gamma;\nuniform bool u_fullbright;\nuniform float u_ambient;\n\nout vec4 o_color;\n\nvoid main() {\n vec4 finalColor;\n\n if (u_renderMode == 0) {\n // TEXTURED MODE\n vec4 base = vec4(1.0);\n if (!u_lightmapOnly) {\n base = texture(u_diffuseMap, v_texCoord);\n }\n\n // Refraction Logic\n if (u_warp && u_hasRefraction) {\n vec2 ndc = (v_screenPos.xy / v_screenPos.w) * 0.5 + 0.5;\n\n // Calculate distortion based on texture coordinates time\n // Simple turbulent distortion\n float distortionStrength = 0.05;\n vec2 distortion = vec2(\n sin(v_texCoord.y * 10.0 + u_time * 2.0),\n cos(v_texCoord.x * 10.0 + u_time * 2.0)\n ) * distortionStrength;\n\n vec3 refractColor = texture(u_refractionMap, ndc + distortion).rgb;\n\n // Blend base texture with refraction\n // Quake 2 water usually is quite opaque but let's try a blend\n // Or just tint the refraction\n\n // If it's water (warp), we usually want some transparency + refraction\n // Let's mix refraction into the base color\n base.rgb = mix(base.rgb, refractColor, 0.4);\n base.a = 0.7; // Ensure some alpha for water\n }\n\n vec3 totalLight = vec3(1.0);\n\n if (u_applyLightmap && !u_fullbright) {\n // Multi-style lightmap accumulation\n vec3 light = vec3(0.0);\n bool hasLight = false;\n\n // Loop unrolled-ish\n for (int i = 0; i < 4; i++) {\n float layer = u_styleLayerMapping[i];\n float factor = u_lightStyleFactors[i];\n\n if (layer >= -0.5) { // Valid layer (check >= 0 approx)\n // Offset V by layer * step\n // Since we packed vertically\n vec2 offset = vec2(0.0, layer * v_lightmapStep);\n light += texture(u_lightmapAtlas, v_lightmapCoord + offset).rgb * factor;\n hasLight = true;\n }\n }\n\n if (!hasLight) light = vec3(1.0);\n\n totalLight = light;\n\n // Add dynamic lights\n for (int i = 0; i < MAX_DLIGHTS; i++) {\n if (i >= u_numDlights) break;\n DLight dlight = u_dlights[i];\n\n float dist = distance(v_position, dlight.position);\n // Quake 2 dlight formula\n if (dist < dlight.intensity) {\n float contribution = (dlight.intensity - dist) * (1.0 / 255.0);\n totalLight += dlight.color * contribution;\n }\n }\n } else if (u_fullbright) {\n totalLight = vec3(1.0);\n }\n\n // Apply ambient minimum\n totalLight = max(totalLight, vec3(u_ambient));\n\n // Apply brightness\n totalLight *= u_brightness;\n\n base.rgb *= totalLight;\n\n // Gamma correction\n if (u_gamma != 1.0) {\n base.rgb = pow(base.rgb, vec3(1.0 / u_gamma));\n }\n\n finalColor = vec4(base.rgb, base.a * u_alpha);\n } else {\n // SOLID / WIREFRAME / FACETED\n vec3 color = u_solidColor.rgb;\n if (u_renderMode == 2) {\n // FACETED: simple lighting based on face normal\n vec3 fdx = dFdx(v_position);\n vec3 fdy = dFdy(v_position);\n vec3 faceNormal = normalize(cross(fdx, fdy));\n\n // Simple directional light from \"camera\" or fixed\n vec3 lightDir = normalize(vec3(0.5, 0.5, 1.0));\n float diff = max(dot(faceNormal, lightDir), 0.2); // Ambient 0.2\n color *= diff;\n }\n finalColor = vec4(color, u_solidColor.a * u_alpha);\n }\n\n o_color = finalColor;\n}`;\n\nconst DEFAULT_STYLE_INDICES: readonly number[] = [0, 255, 255, 255];\nconst DEFAULT_STYLE_LAYERS: readonly number[] = [0, -1, -1, -1];\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 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 || warp; // Enable blend for warp (water)\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\n// Extend BspSurfaceGeometry to include wireframe index buffer\ndeclare module './bsp.js' {\n interface BspSurfaceGeometry {\n wireframeIndexBuffer?: IndexBuffer;\n wireframeIndexCount?: number;\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 uniformStyleLayerMapping: WebGLUniformLocation | null;\n private readonly uniformAlpha: WebGLUniformLocation | null;\n private readonly uniformApplyLightmap: WebGLUniformLocation | null;\n private readonly uniformWarp: WebGLUniformLocation | null;\n private readonly uniformLightmapOnly: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n private readonly uniformLightmap: WebGLUniformLocation | null;\n private readonly uniformRefraction: WebGLUniformLocation | null; // New\n private readonly uniformHasRefraction: WebGLUniformLocation | null; // New\n private readonly uniformTime: WebGLUniformLocation | null;\n\n private readonly uniformRenderMode: WebGLUniformLocation | null;\n private readonly uniformSolidColor: WebGLUniformLocation | null;\n\n private readonly uniformNumDlights: WebGLUniformLocation | null;\n private readonly uniformDlights: { pos: WebGLUniformLocation | null, color: WebGLUniformLocation | null, intensity: WebGLUniformLocation | null }[] = [];\n\n // Lighting controls uniforms\n private readonly uniformBrightness: WebGLUniformLocation | null;\n private readonly uniformGamma: WebGLUniformLocation | null;\n private readonly uniformFullbright: WebGLUniformLocation | null;\n private readonly uniformAmbient: 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, a_lightmapStep: 3 }\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.uniformStyleLayerMapping = this.program.getUniformLocation('u_styleLayerMapping');\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.uniformLightmapOnly = this.program.getUniformLocation('u_lightmapOnly');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n this.uniformLightmap = this.program.getUniformLocation('u_lightmapAtlas');\n this.uniformRefraction = this.program.getUniformLocation('u_refractionMap');\n this.uniformHasRefraction = this.program.getUniformLocation('u_hasRefraction');\n this.uniformTime = this.program.getUniformLocation('u_time');\n\n this.uniformRenderMode = this.program.getUniformLocation('u_renderMode');\n this.uniformSolidColor = this.program.getUniformLocation('u_solidColor');\n\n this.uniformNumDlights = this.program.getUniformLocation('u_numDlights');\n for (let i = 0; i < MAX_DLIGHTS; i++) {\n this.uniformDlights.push({\n pos: this.program.getUniformLocation(`u_dlights[${i}].position`),\n color: this.program.getUniformLocation(`u_dlights[${i}].color`),\n intensity: this.program.getUniformLocation(`u_dlights[${i}].intensity`),\n });\n }\n\n this.uniformBrightness = this.program.getUniformLocation('u_brightness');\n this.uniformGamma = this.program.getUniformLocation('u_gamma');\n this.uniformFullbright = this.program.getUniformLocation('u_fullbright');\n this.uniformAmbient = this.program.getUniformLocation('u_ambient');\n }\n\n get shaderSize(): number {\n return this.program.sourceSize;\n }\n\n bind(options: BspSurfaceBindOptions): SurfaceRenderState {\n const {\n modelViewProjection,\n styleIndices = DEFAULT_STYLE_INDICES,\n styleLayers = DEFAULT_STYLE_LAYERS,\n styleValues = [],\n diffuseSampler = 0,\n lightmapSampler,\n refractionSampler,\n surfaceFlags = SURF_NONE,\n timeSeconds = 0,\n texScroll,\n alpha,\n warp,\n dlights = [],\n renderMode,\n lightmapOnly,\n brightness = 1.0,\n gamma = 1.0,\n fullbright = false,\n ambient = 0.0\n } = options;\n\n const state = deriveSurfaceRenderState(surfaceFlags, timeSeconds);\n const styles = resolveLightStyles(styleIndices, styleValues);\n\n const finalScrollX = texScroll ? texScroll[0] : state.flowOffset[0];\n const finalScrollY = texScroll ? texScroll[1] : state.flowOffset[1];\n const finalAlpha = alpha !== undefined ? alpha : state.alpha;\n const finalWarp = warp !== undefined ? warp : state.warp;\n\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform2f(this.uniformTexScroll, finalScrollX, finalScrollY);\n this.gl.uniform2f(this.uniformLmScroll, state.flowOffset[0], state.flowOffset[1]);\n this.gl.uniform4fv(this.uniformLightStyles, styles);\n this.gl.uniform4fv(this.uniformStyleLayerMapping, styleLayers as number[]);\n this.gl.uniform1f(this.uniformAlpha, finalAlpha);\n const applyLightmap = !state.sky && lightmapSampler !== undefined && !finalWarp; // Warp surfaces have no lightmaps\n this.gl.uniform1i(this.uniformApplyLightmap, applyLightmap ? 1 : 0);\n this.gl.uniform1i(this.uniformWarp, finalWarp ? 1 : 0);\n this.gl.uniform1i(this.uniformLightmapOnly, lightmapOnly ? 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 // Bind Refraction\n if (refractionSampler !== undefined && finalWarp) {\n this.gl.uniform1i(this.uniformRefraction, refractionSampler);\n this.gl.uniform1i(this.uniformHasRefraction, 1);\n } else {\n this.gl.uniform1i(this.uniformHasRefraction, 0);\n }\n\n // Render Mode Logic\n let modeInt = 0; // Textured\n let color = [1, 1, 1, 1];\n\n if (renderMode) {\n if (renderMode.mode === 'solid' || renderMode.mode === 'wireframe') {\n modeInt = 1; // Solid\n } else if (renderMode.mode === 'solid-faceted') {\n modeInt = 2; // Faceted\n }\n\n if (renderMode.color) {\n color = [...renderMode.color];\n } else if (renderMode.generateRandomColor) {\n color = [1, 1, 1, 1];\n }\n }\n\n this.gl.uniform1i(this.uniformRenderMode, modeInt);\n this.gl.uniform4f(this.uniformSolidColor, color[0], color[1], color[2], color[3]);\n\n // Bind Dlights\n const numDlights = Math.min(dlights.length, MAX_DLIGHTS);\n this.gl.uniform1i(this.uniformNumDlights, numDlights);\n for (let i = 0; i < numDlights; i++) {\n const light = dlights[i];\n this.gl.uniform3f(this.uniformDlights[i].pos, light.origin.x, light.origin.y, light.origin.z);\n this.gl.uniform3f(this.uniformDlights[i].color, light.color.x, light.color.y, light.color.z);\n this.gl.uniform1f(this.uniformDlights[i].intensity, light.intensity);\n }\n\n // Bind Lighting controls\n this.gl.uniform1f(this.uniformBrightness, brightness);\n this.gl.uniform1f(this.uniformGamma, gamma);\n this.gl.uniform1i(this.uniformFullbright, fullbright ? 1 : 0);\n this.gl.uniform1f(this.uniformAmbient, ambient);\n\n return state;\n }\n\n draw(geometry: BspSurfaceGeometry, renderMode?: RenderModeConfig): void {\n geometry.vao.bind();\n\n if (renderMode && renderMode.mode === 'wireframe') {\n // Lazy init wireframe buffer\n if (!geometry.wireframeIndexBuffer) {\n // We need to cast back to mutable because we are augmenting the object at runtime\n const mutableGeometry = geometry as any;\n mutableGeometry.wireframeIndexBuffer = new IndexBuffer(this.gl, this.gl.STATIC_DRAW);\n const wireIndices = generateWireframeIndices(geometry.indexData);\n mutableGeometry.wireframeIndexBuffer.upload(wireIndices as unknown as BufferSource);\n mutableGeometry.wireframeIndexCount = wireIndices.length;\n }\n\n geometry.wireframeIndexBuffer!.bind();\n this.gl.drawElements(this.gl.LINES, geometry.wireframeIndexCount!, this.gl.UNSIGNED_SHORT, 0);\n } else {\n geometry.indexBuffer.bind();\n this.gl.drawElements(this.gl.TRIANGLES, geometry.indexCount, this.gl.UNSIGNED_SHORT, 0);\n }\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 get shaderSize(): number {\n return this.program.sourceSize;\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';\nimport { DLight, MAX_DLIGHTS } from './dlight.js';\nimport { generateWireframeIndices } from './geometry.js';\nimport { RenderModeConfig } from './frame.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 frame0: number;\n readonly frame1: 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 readonly dlights?: readonly DLight[];\n readonly modelMatrix?: Float32List; // Needed for dlight world position calculation\n readonly renderMode?: RenderModeConfig;\n // Lighting controls\n readonly brightness?: number;\n readonly gamma?: number;\n readonly fullbright?: boolean;\n readonly ambient?: 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\nstruct DLight {\n vec3 position;\n vec3 color;\n float intensity;\n};\n\nconst int MAX_DLIGHTS = ${MAX_DLIGHTS};\n\nuniform mat4 u_modelViewProjection;\nuniform mat4 u_modelMatrix;\nuniform vec3 u_lightDir;\nuniform float u_ambient;\n\nuniform int u_numDlights;\nuniform DLight u_dlights[MAX_DLIGHTS];\n\nout vec2 v_texCoord;\nout vec3 v_lightColor;\nout vec3 v_position; // For faceted shading\n\nvoid main() {\n vec3 normal = normalize(a_normal);\n\n // Directional Light (simple Lambert)\n float dotL = max(dot(normal, normalize(u_lightDir)), 0.0);\n vec3 lightAcc = vec3(min(1.0, u_ambient + dotL)); // White light assumed for directional/ambient\n\n // Dynamic Lights\n vec4 worldPos = u_modelMatrix * vec4(a_position, 1.0);\n\n for (int i = 0; i < MAX_DLIGHTS; i++) {\n if (i >= u_numDlights) break;\n DLight dlight = u_dlights[i];\n\n float dist = distance(worldPos.xyz, dlight.position);\n if (dist < dlight.intensity) {\n float intensity = (dlight.intensity - dist) / dlight.intensity;\n lightAcc += dlight.color * intensity;\n }\n }\n\n v_lightColor = lightAcc;\n v_texCoord = a_texCoord;\n v_position = worldPos.xyz;\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 vec3 v_lightColor;\nin vec3 v_position;\n\nuniform sampler2D u_diffuseMap;\nuniform vec4 u_tint;\n\nuniform int u_renderMode; // 0: Textured, 1: Solid, 2: Solid Faceted\nuniform vec4 u_solidColor;\n\n// Lighting controls\nuniform float u_brightness;\nuniform float u_gamma;\nuniform bool u_fullbright;\nuniform float u_globalAmbient;\n\nout vec4 o_color;\n\nvoid main() {\n vec4 finalColor;\n\n if (u_renderMode == 0) {\n vec4 albedo = texture(u_diffuseMap, v_texCoord) * u_tint;\n\n vec3 light = v_lightColor;\n\n if (u_fullbright) {\n light = vec3(1.0);\n }\n\n // Apply global ambient min\n light = max(light, vec3(u_globalAmbient));\n\n light *= u_brightness;\n\n vec3 rgb = albedo.rgb * light;\n\n if (u_gamma != 1.0) {\n rgb = pow(rgb, vec3(1.0 / u_gamma));\n }\n\n finalColor = vec4(rgb, albedo.a);\n } else {\n vec3 color = u_solidColor.rgb;\n if (u_renderMode == 2) {\n // FACETED\n vec3 fdx = dFdx(v_position);\n vec3 fdy = dFdy(v_position);\n vec3 faceNormal = normalize(cross(fdx, fdy));\n vec3 lightDir = normalize(vec3(0.5, 0.5, 1.0));\n float diff = max(dot(faceNormal, lightDir), 0.2);\n color *= diff;\n }\n finalColor = vec4(color, u_solidColor.a * u_tint.a);\n }\n\n o_color = finalColor;\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 { frame0, frame1, lerp } = blend;\n const frameA = model.frames[frame0];\n const frameB = model.frames[frame1];\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 wireframeIndexBuffer?: IndexBuffer;\n wireframeIndexCount?: 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 this.wireframeIndexBuffer?.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 uniformModelMatrix: 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 private readonly uniformRenderMode: WebGLUniformLocation | null;\n private readonly uniformSolidColor: WebGLUniformLocation | null;\n\n private readonly uniformNumDlights: WebGLUniformLocation | null;\n private readonly uniformDlights: { pos: WebGLUniformLocation | null, color: WebGLUniformLocation | null, intensity: WebGLUniformLocation | null }[] = [];\n\n // Lighting controls\n private readonly uniformBrightness: WebGLUniformLocation | null;\n private readonly uniformGamma: WebGLUniformLocation | null;\n private readonly uniformFullbright: WebGLUniformLocation | null;\n private readonly uniformGlobalAmbient: 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.uniformModelMatrix = this.program.getUniformLocation('u_modelMatrix');\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 this.uniformRenderMode = this.program.getUniformLocation('u_renderMode');\n this.uniformSolidColor = this.program.getUniformLocation('u_solidColor');\n\n this.uniformNumDlights = this.program.getUniformLocation('u_numDlights');\n for (let i = 0; i < MAX_DLIGHTS; i++) {\n this.uniformDlights.push({\n pos: this.program.getUniformLocation(`u_dlights[${i}].position`),\n color: this.program.getUniformLocation(`u_dlights[${i}].color`),\n intensity: this.program.getUniformLocation(`u_dlights[${i}].intensity`),\n });\n }\n\n this.uniformBrightness = this.program.getUniformLocation('u_brightness');\n this.uniformGamma = this.program.getUniformLocation('u_gamma');\n this.uniformFullbright = this.program.getUniformLocation('u_fullbright');\n this.uniformGlobalAmbient = this.program.getUniformLocation('u_globalAmbient');\n }\n\n get shaderSize(): number {\n return this.program.sourceSize;\n }\n\n bind(options: Md2BindOptions): void {\n const {\n modelViewProjection,\n modelMatrix,\n lightDirection = [0, 0, 1],\n ambientLight = 0.2,\n tint = [1, 1, 1, 1],\n diffuseSampler = 0,\n dlights = [],\n renderMode,\n brightness = 1.0,\n gamma = 1.0,\n fullbright = false,\n ambient = 0.0\n } = 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 if (modelMatrix) {\n this.gl.uniformMatrix4fv(this.uniformModelMatrix, false, modelMatrix);\n } else {\n this.gl.uniformMatrix4fv(this.uniformModelMatrix, false, new Float32Array([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]));\n }\n\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 // Render Mode\n let modeInt = 0;\n let color = [1, 1, 1, 1];\n if (renderMode) {\n if (renderMode.mode === 'solid' || renderMode.mode === 'wireframe') modeInt = 1;\n else if (renderMode.mode === 'solid-faceted') modeInt = 2;\n\n if (renderMode.color) {\n color = [...renderMode.color];\n } else if (renderMode.generateRandomColor) {\n // Will be handled by caller passing specific color, or white here\n }\n }\n this.gl.uniform1i(this.uniformRenderMode, modeInt);\n this.gl.uniform4f(this.uniformSolidColor, color[0], color[1], color[2], color[3]);\n\n\n // Bind Dlights\n const numDlights = Math.min(dlights.length, MAX_DLIGHTS);\n this.gl.uniform1i(this.uniformNumDlights, numDlights);\n for (let i = 0; i < numDlights; i++) {\n const light = dlights[i];\n this.gl.uniform3f(this.uniformDlights[i].pos, light.origin.x, light.origin.y, light.origin.z);\n this.gl.uniform3f(this.uniformDlights[i].color, light.color.x, light.color.y, light.color.z);\n this.gl.uniform1f(this.uniformDlights[i].intensity, light.intensity);\n }\n\n // Lighting controls\n this.gl.uniform1f(this.uniformBrightness, brightness);\n this.gl.uniform1f(this.uniformGamma, gamma);\n this.gl.uniform1i(this.uniformFullbright, fullbright ? 1 : 0);\n this.gl.uniform1f(this.uniformGlobalAmbient, ambient);\n }\n\n draw(mesh: Md2MeshBuffers, renderMode?: RenderModeConfig): void {\n mesh.vertexArray.bind();\n\n if (renderMode && renderMode.mode === 'wireframe') {\n if (!mesh.wireframeIndexBuffer) {\n mesh.wireframeIndexBuffer = new IndexBuffer(this.gl, this.gl.STATIC_DRAW);\n const wireIndices = generateWireframeIndices(mesh.geometry.indices);\n mesh.wireframeIndexBuffer.upload(wireIndices as unknown as BufferSource);\n mesh.wireframeIndexCount = wireIndices.length;\n }\n mesh.wireframeIndexBuffer.bind();\n this.gl.drawElements(this.gl.LINES, mesh.wireframeIndexCount!, this.gl.UNSIGNED_SHORT, 0);\n } else {\n mesh.indexBuffer.bind();\n this.gl.drawElements(this.gl.TRIANGLES, mesh.indexCount, this.gl.UNSIGNED_SHORT, 0);\n }\n }\n\n dispose(): void {\n this.program.dispose();\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}();","import { mat4, vec3 } from 'gl-matrix';\nimport { DEG2RAD, RAD2DEG } from '@quake2ts/shared';\n\nexport interface CameraState {\n position: vec3;\n angles: vec3;\n}\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 // Event callback\n public onCameraMove?: (camera: CameraState) => void;\n\n get position(): vec3 {\n return this._position;\n }\n\n set position(value: vec3) {\n if (!vec3.equals(this._position, value)) {\n vec3.copy(this._position, value);\n this._dirty = true;\n this.triggerMoveEvent();\n }\n }\n\n get angles(): vec3 {\n return this._angles;\n }\n\n set angles(value: vec3) {\n if (!vec3.equals(this._angles, value)) {\n vec3.copy(this._angles, value);\n this._dirty = true;\n this.triggerMoveEvent();\n }\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 // API Methods\n setPosition(x: number, y: number, z: number): void {\n const newPos = vec3.fromValues(x, y, z);\n if (!vec3.equals(this._position, newPos)) {\n vec3.copy(this._position, newPos);\n this._dirty = true;\n this.triggerMoveEvent();\n }\n }\n\n setRotation(pitch: number, yaw: number, roll: number): void {\n const newAngles = vec3.fromValues(pitch, yaw, roll);\n if (!vec3.equals(this._angles, newAngles)) {\n vec3.copy(this._angles, newAngles);\n this._dirty = true;\n this.triggerMoveEvent();\n }\n }\n\n setFov(fov: number): void {\n this.fov = fov;\n }\n\n setAspectRatio(aspect: number): void {\n this.aspect = aspect;\n }\n\n lookAt(target: vec3): void {\n // Calculate vector from camera to target\n const direction = vec3.create();\n vec3.subtract(direction, target, this._position);\n\n // Normalize? Not strictly necessary for angle calc but good practice\n const len = vec3.length(direction);\n if (len < 0.001) return; // Too close\n\n // Calculate Yaw (around Z axis in Quake coords)\n // Quake: X forward, Y left\n // Math.atan2(y, x) gives angle from X axis.\n // Quake angles: 0 is East (X+), 90 is North (Y+)? No, Quake yaw 0 is East (X+).\n // Let's verify standard Quake angles.\n // X+ is 0 yaw. Y+ is 90 yaw.\n const yaw = Math.atan2(direction[1], direction[0]) * RAD2DEG;\n\n // Calculate Pitch (up/down)\n // Z is up.\n // Pitch is angle from XY plane. Positive is Up? In Quake usually Positive is Down (looking down).\n // Wait, let's check standard Quake 2 pitch.\n // Positive pitch is usually looking DOWN. Negative is UP.\n // But let's check `angleVectors` usage in memory if possible.\n // Usually: pitch, yaw, roll.\n // hypot(x,y) is horizontal distance.\n const hyp = Math.hypot(direction[0], direction[1]);\n const pitch = -Math.atan2(direction[2], hyp) * RAD2DEG;\n\n this.setRotation(pitch, yaw, 0);\n }\n\n private triggerMoveEvent() {\n if (this.onCameraMove) {\n this.onCameraMove({\n position: vec3.clone(this._position),\n angles: vec3.clone(this._angles)\n });\n }\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 screenToWorldRay(\n screenX: number,\n screenY: number\n ): { origin: vec3; direction: vec3 } {\n // 1. Calculate Normalized Device Coordinates (NDC)\n // screenX, screenY are in [0, 1] range\n // NDC: [-1, 1]\n const ndcX = (screenX * 2) - 1;\n const ndcY = 1 - (screenY * 2); // Flip Y because screen Y is down, NDC Y is up\n\n // 2. Create ray in clip space\n // Z = -1 for near plane, Z = 1 for far plane\n const clipStart = vec3.fromValues(ndcX, ndcY, -1);\n const clipEnd = vec3.fromValues(ndcX, ndcY, 1);\n\n // 3. Inverse View-Projection Matrix\n const invViewProj = mat4.create();\n mat4.invert(invViewProj, this.viewProjectionMatrix);\n\n // 4. Transform to World Space\n const worldStart = vec3.create();\n const worldEnd = vec3.create();\n\n vec3.transformMat4(worldStart, clipStart, invViewProj);\n vec3.transformMat4(worldEnd, clipEnd, invViewProj);\n\n // 5. Construct Ray\n // The start point is the camera position (or near plane intersection)\n // But for picking, we usually want the ray from the camera origin.\n // However, unprojecting ndcX, ndcY, -1 gives point on near plane.\n\n // Direction is normalized vector from start to end\n const direction = vec3.create();\n vec3.subtract(direction, worldEnd, worldStart);\n vec3.normalize(direction, direction);\n\n // The previous test expectation was failing because of coordinate space confusion.\n // If the test expects +X forward, and we get -0, 0, 0, it means the ray is pointing somewhere else.\n // Let's debug the coordinate transform.\n // Quake X (Forward) -> GL -Z.\n // NDC (0, 0, -1) -> Near Plane Center.\n // Inverse ViewProj should map NDC (0,0,-1) to World Position + Forward * NearDist.\n\n // If we are at 0,0,0 looking +X.\n // Quake +X is GL -Z.\n // So forward in GL is -Z.\n // NDC 0,0 is center.\n // Unprojecting should give direction -Z in GL space.\n // But we are transforming back to World Space (Quake space).\n // So GL -Z should map back to Quake +X.\n\n return {\n origin: vec3.clone(this._position),\n direction,\n };\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 -Z <-- FIXED from -Y to -Z\n // - Quake Y (left) -> WebGL -X <-- FIXED from +Z to -X\n // - Quake Z (up) -> WebGL +Y <-- FIXED from -X to +Y\n //\n // Let's re-verify the standard mapping.\n // Quake: X Forward, Y Left, Z Up.\n // GL: -Z Forward, X Right, Y Up.\n //\n // So:\n // Quake X (Forward) -> GL -Z\n // Quake Y (Left) -> GL -X (Since GL X is Right, Left is -X)\n // Quake Z (Up) -> GL Y\n\n const quakeToGl = mat4.fromValues(\n 0, 0, -1, 0, // column 0: Quake X -> WebGL -Z\n -1, 0, 0, 0, // column 1: Quake Y -> WebGL -X\n 0, 1, 0, 0, // column 2: Quake Z -> WebGL Y\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 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 const translationGl = vec3.fromValues(\n rotatedPosQuake[1] ? -rotatedPosQuake[1] : 0, // Y in Quake -> -X in WebGL\n rotatedPosQuake[2] || 0, // Z in Quake -> Y in WebGL\n rotatedPosQuake[0] ? -rotatedPosQuake[0] : 0 // X in Quake -> -Z in WebGL\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';\nimport { RenderModeConfig } from './frame.js';\nimport { generateWireframeIndices } from './geometry.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 frame0: number;\n readonly frame1: 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 readonly renderMode?: RenderModeConfig;\n readonly brightness?: number;\n readonly gamma?: number;\n readonly fullbright?: boolean;\n readonly globalAmbient?: 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.frame0];\n const frameB = surface.vertices[blend.frame1];\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.frame0]?.[tagIndex];\n const tagB = model.tags[blend.frame1]?.[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;\nout vec3 v_position;\n\nvoid main() {\n v_texCoord = a_texCoord;\n v_color = a_color;\n v_position = a_position; // Model space, assuming single mesh pass\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;\nin vec3 v_position;\n\nuniform sampler2D u_diffuseMap;\nuniform vec4 u_tint;\n\nuniform int u_renderMode; // 0: Textured, 1: Solid, 2: Solid Faceted\nuniform vec4 u_solidColor;\n\n// Lighting controls\nuniform float u_brightness;\nuniform float u_gamma;\nuniform bool u_fullbright;\nuniform float u_globalAmbient;\n\nout vec4 o_color;\n\nvoid main() {\n vec4 finalColor;\n\n if (u_renderMode == 0) {\n vec4 albedo = texture(u_diffuseMap, v_texCoord) * u_tint;\n\n vec3 light = v_color.rgb;\n if (u_fullbright) {\n light = vec3(1.0);\n }\n light = max(light, vec3(u_globalAmbient));\n light *= u_brightness;\n\n vec3 rgb = albedo.rgb * light;\n\n if (u_gamma != 1.0) {\n rgb = pow(rgb, vec3(1.0 / u_gamma));\n }\n\n finalColor = vec4(rgb, albedo.a * v_color.a);\n } else {\n vec3 color = u_solidColor.rgb;\n if (u_renderMode == 2) {\n // FACETED\n vec3 fdx = dFdx(v_position);\n vec3 fdy = dFdy(v_position);\n vec3 faceNormal = normalize(cross(fdx, fdy));\n vec3 lightDir = normalize(vec3(0.5, 0.5, 1.0));\n float diff = max(dot(faceNormal, lightDir), 0.2);\n color *= diff;\n }\n finalColor = vec4(color, u_solidColor.a * u_tint.a);\n }\n\n o_color = finalColor;\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 wireframeIndexBuffer?: IndexBuffer;\n wireframeIndexCount?: 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 this.wireframeIndexBuffer?.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 private readonly uniformRenderMode: WebGLUniformLocation | null;\n private readonly uniformSolidColor: WebGLUniformLocation | null;\n\n // Lighting controls\n private readonly uniformBrightness: WebGLUniformLocation | null;\n private readonly uniformGamma: WebGLUniformLocation | null;\n private readonly uniformFullbright: WebGLUniformLocation | null;\n private readonly uniformGlobalAmbient: 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 this.uniformRenderMode = this.program.getUniformLocation('u_renderMode');\n this.uniformSolidColor = this.program.getUniformLocation('u_solidColor');\n\n this.uniformBrightness = this.program.getUniformLocation('u_brightness');\n this.uniformGamma = this.program.getUniformLocation('u_gamma');\n this.uniformFullbright = this.program.getUniformLocation('u_fullbright');\n this.uniformGlobalAmbient = this.program.getUniformLocation('u_globalAmbient');\n }\n\n get shaderSize(): number {\n return this.program.sourceSize;\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 // Default mode for simple bind\n this.gl.uniform1i(this.uniformRenderMode, 0);\n this.gl.uniform4f(this.uniformSolidColor, 1, 1, 1, 1);\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 const renderMode = material?.renderMode;\n\n // Lighting controls from material (which propagates from pipeline bind if structure allows,\n // but here we are in draw call. We need access to the lighting state set in bind?\n // The problem is Md3Pipeline doesn't have a comprehensive 'bind' method that takes everything.\n // It has bind(mvp) and drawSurface(mesh, material).\n // The caller (renderer.ts) iterates surfaces and calls drawSurface.\n // So we should probably update drawSurface or bind to accept lighting params.\n // Or add a separate setLighting method.\n // For now, let's pass them via material if possible, or assume they were set globally.\n // But drawSurface sets uniforms...\n // Actually, bind() sets MVP and resets some state.\n // We should probably pass lighting to bind() or add setLightingState.\n // Let's modify bind() signature to be more comprehensive or add a separate method.\n // Since we are modifying Md3Pipeline class, let's update `bind` to take lighting options.\n\n // However, drawSurface also sets uniforms.\n // Wait, the uniforms I added (brightness etc) are on the program.\n // If I set them in `bind`, they persist until `use` is called again or another program is used.\n // Since drawSurface assumes program is used, it should be fine.\n\n const brightness = material?.brightness ?? 1.0;\n const gamma = material?.gamma ?? 1.0;\n const fullbright = material?.fullbright ?? false;\n const globalAmbient = material?.globalAmbient ?? 0.0;\n\n this.gl.uniform4fv(this.uniformTint, new Float32Array(tint));\n this.gl.uniform1i(this.uniformDiffuse, sampler);\n\n // Render Mode\n let modeInt = 0;\n let color = [1, 1, 1, 1];\n if (renderMode) {\n if (renderMode.mode === 'solid' || renderMode.mode === 'wireframe') modeInt = 1;\n else if (renderMode.mode === 'solid-faceted') modeInt = 2;\n\n if (renderMode.color) {\n color = [...renderMode.color];\n }\n }\n this.gl.uniform1i(this.uniformRenderMode, modeInt);\n this.gl.uniform4f(this.uniformSolidColor, color[0], color[1], color[2], color[3]);\n\n this.gl.uniform1f(this.uniformBrightness, brightness);\n this.gl.uniform1f(this.uniformGamma, gamma);\n this.gl.uniform1i(this.uniformFullbright, fullbright ? 1 : 0);\n this.gl.uniform1f(this.uniformGlobalAmbient, globalAmbient);\n\n mesh.vertexArray.bind();\n\n if (renderMode && renderMode.mode === 'wireframe') {\n if (!mesh.wireframeIndexBuffer) {\n mesh.wireframeIndexBuffer = new IndexBuffer(this.gl, this.gl.STATIC_DRAW);\n const wireIndices = generateWireframeIndices(mesh.geometry.indices);\n mesh.wireframeIndexBuffer.upload(wireIndices as unknown as BufferSource);\n mesh.wireframeIndexCount = wireIndices.length;\n }\n mesh.wireframeIndexBuffer.bind();\n this.gl.drawElements(this.gl.LINES, mesh.wireframeIndexCount!, this.gl.UNSIGNED_SHORT, 0);\n } else {\n mesh.indexBuffer.bind();\n this.gl.drawElements(this.gl.TRIANGLES, mesh.indexCount, this.gl.UNSIGNED_SHORT, 0);\n }\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';\nimport { RandomGenerator } from '@quake2ts/shared';\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 rng: RandomGenerator;\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, rng: RandomGenerator) {\n this.maxParticles = maxParticles;\n this.rng = rng;\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 get shaderSize(): number {\n return this.program.sourceSize;\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.rng.frandom() * 180;\n const spread = system.rng.frandom() * 0.35;\n system.spawn({\n position: origin,\n velocity: {\n x: normal.x * speed + (system.rng.frandom() - 0.5) * 80,\n y: normal.y * speed + (system.rng.frandom() - 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.rng.frandom() * 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.rng.frandom() - 0.5) * 40, y: (system.rng.frandom() - 0.5) * 40, z: 80 + system.rng.frandom() * 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.rng.frandom() * Math.PI * 2;\n const phi = Math.acos(2 * system.rng.frandom() - 1);\n const speed = 220 + system.rng.frandom() * 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.rng.frandom() - 0.5) * 30, y: (system.rng.frandom() - 0.5) * 30, z: 120 + system.rng.frandom() * 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.rng.frandom() * 180;\n system.spawn({\n position: origin,\n velocity: {\n x: direction.x * speed + (system.rng.frandom() - 0.5) * 70,\n y: direction.y * speed + (system.rng.frandom() - 0.5) * 70,\n z: direction.z * speed + system.rng.frandom() * 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.rng.frandom() * Math.PI * 2;\n const radius = 8 + system.rng.frandom() * 8;\n system.spawn({\n position: origin,\n velocity: { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius, z: 100 + system.rng.frandom() * 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.rng.frandom() * 100;\n system.spawn({\n position: origin,\n velocity: {\n x: direction.x * speed + (system.rng.frandom() - 0.5) * 30,\n y: direction.y * speed + (system.rng.frandom() - 0.5) * 30,\n z: direction.z * speed + (system.rng.frandom() - 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.rng.frandom() - 0.5) * 15, y: (system.rng.frandom() - 0.5) * 15, z: 20 + system.rng.frandom() * 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\nexport function spawnSplash(context: ParticleEffectContext): void {\n const { system, origin, normal = { x: 0, y: 0, z: 1 } } = context;\n for (let i = 0; i < 30; i += 1) {\n const speed = 100 + system.rng.frandom() * 150;\n system.spawn({\n position: origin,\n velocity: {\n x: normal.x * speed + (system.rng.frandom() - 0.5) * 80,\n y: normal.y * speed + (system.rng.frandom() - 0.5) * 80,\n z: 100 + system.rng.frandom() * 120,\n },\n color: [0.5, 0.6, 0.8, 0.5],\n size: 3,\n lifetime: 0.5 + system.rng.frandom() * 0.3,\n gravity: 800,\n damping: 1.5,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n\nexport function spawnSteam(context: ParticleEffectContext): void {\n const { system, origin } = context;\n for (let i = 0; i < 8; i += 1) {\n system.spawn({\n position: {\n x: origin.x + (system.rng.frandom() - 0.5) * 10,\n y: origin.y + (system.rng.frandom() - 0.5) * 10,\n z: origin.z + (system.rng.frandom() - 0.5) * 10,\n },\n velocity: {\n x: (system.rng.frandom() - 0.5) * 20,\n y: (system.rng.frandom() - 0.5) * 20,\n z: 40 + system.rng.frandom() * 20,\n },\n color: [0.8, 0.8, 0.8, 0.3],\n size: 5 + system.rng.frandom() * 4,\n lifetime: 1.5 + system.rng.frandom() * 0.5,\n gravity: -50, // Negative gravity for rising steam\n damping: 0.5,\n blendMode: 'alpha',\n fade: true,\n });\n }\n}\n\n// ============================================================================\n// New Particle Helpers for Weapon Impacts & Effects\n// ============================================================================\n\nexport interface RailTrailContext {\n readonly system: ParticleSystem;\n readonly start: Vec3;\n readonly end: Vec3;\n}\n\nexport function spawnRailTrail(context: RailTrailContext): void {\n const { system, start, end } = context;\n const dx = end.x - start.x;\n const dy = end.y - start.y;\n const dz = end.z - start.z;\n const dist = Math.sqrt(dx * dx + dy * dy + dz * dz);\n\n if (dist < 1) return;\n\n // Normalize direction\n const dir = { x: dx / dist, y: dy / dist, z: dz / dist };\n\n // Core trail particles\n const step = 8; // Density\n for (let d = 0; d < dist; d += step) {\n const x = start.x + dir.x * d;\n const y = start.y + dir.y * d;\n const z = start.z + dir.z * d;\n\n // Spiral effect\n // d acts as \"time\" or distance along axis\n // We want a spiral around the axis.\n // For simplicity, let's just do a glowing core + some random jitter for now.\n // A true spiral requires constructing perpendicular vectors.\n\n // Inner blue core\n system.spawn({\n position: { x, y, z },\n velocity: { x: 0, y: 0, z: 0 }, // Static\n color: [0.4, 0.4, 1, 0.8],\n size: 2,\n lifetime: 0.6,\n blendMode: 'additive',\n fade: true\n });\n\n // Outer spiral/jitter\n const radius = 3;\n const theta = d * 0.5; // Twist\n // This is not a true spiral around the vector, but simple jitter around point\n // To do true spiral, we need basis vectors.\n // For now, simple jitter is \"good enough\" for Quake 2 feel usually.\n // Or we can try to improve visuals later.\n system.spawn({\n position: {\n x: x + (system.rng.frandom() - 0.5) * 6,\n y: y + (system.rng.frandom() - 0.5) * 6,\n z: z + (system.rng.frandom() - 0.5) * 6\n },\n velocity: {\n x: (system.rng.frandom() - 0.5) * 10,\n y: (system.rng.frandom() - 0.5) * 10,\n z: (system.rng.frandom() - 0.5) * 10\n },\n color: [0.1, 0.1, 0.8, 0.6],\n size: 3,\n lifetime: 0.8 + system.rng.frandom() * 0.2,\n blendMode: 'additive',\n fade: true\n });\n }\n}\n\nexport interface SparksContext extends ParticleEffectContext {\n readonly count?: number;\n readonly color?: readonly [number, number, number, number];\n}\n\nexport function spawnSparks(context: SparksContext): void {\n const { system, origin, normal = { x: 0, y: 0, z: 1 }, count = 12, color = [1, 0.9, 0.2, 1] } = context;\n\n for (let i = 0; i < count; i++) {\n const speed = 100 + system.rng.frandom() * 200;\n const spread = 0.5;\n\n system.spawn({\n position: origin,\n velocity: {\n x: normal.x * speed + (system.rng.frandom() - 0.5) * 100 * spread,\n y: normal.y * speed + (system.rng.frandom() - 0.5) * 100 * spread,\n z: normal.z * speed + (system.rng.frandom() - 0.5) * 100 * spread\n },\n color: color,\n size: 1.5,\n lifetime: 0.3 + system.rng.frandom() * 0.2,\n gravity: 800,\n bounce: 0.5,\n damping: 1,\n blendMode: 'additive',\n fade: true\n });\n }\n}\n\nexport interface BlasterImpactContext extends ParticleEffectContext {\n readonly color?: readonly [number, number, number, number];\n}\n\nexport function spawnBlasterImpact(context: BlasterImpactContext): void {\n const { system, origin, normal = { x: 0, y: 0, z: 1 }, color = [1, 0.8, 0.0, 1] } = context;\n\n // Flash\n system.spawn({\n position: origin,\n velocity: { x: 0, y: 0, z: 0 },\n color: color,\n size: 8,\n lifetime: 0.2,\n blendMode: 'additive',\n fade: true\n });\n\n // Sparks\n for (let i = 0; i < 8; i++) {\n const speed = 150 + system.rng.frandom() * 150;\n system.spawn({\n position: origin,\n velocity: {\n x: normal.x * speed + (system.rng.frandom() - 0.5) * 120,\n y: normal.y * speed + (system.rng.frandom() - 0.5) * 120,\n z: normal.z * speed + (system.rng.frandom() - 0.5) * 120\n },\n color: color,\n size: 2,\n lifetime: 0.4 + system.rng.frandom() * 0.2,\n gravity: 400,\n blendMode: 'additive',\n fade: true\n });\n }\n}\n\nexport function spawnBfgExplosion(context: ParticleEffectContext): void {\n const { system, origin } = context;\n\n // Core Flash\n system.spawn({\n position: origin,\n velocity: { x: 0, y: 0, z: 0 },\n color: [0.2, 1.0, 0.2, 1], // Green\n size: 30,\n lifetime: 0.5,\n blendMode: 'additive',\n fade: true\n });\n\n // Radiating green rays/particles\n for (let i = 0; i < 60; i++) {\n const theta = system.rng.frandom() * Math.PI * 2;\n const phi = Math.acos(2 * system.rng.frandom() - 1);\n const speed = 300 + system.rng.frandom() * 400;\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\n system.spawn({\n position: origin,\n velocity: { x: dir.x * speed, y: dir.y * speed, z: dir.z * speed },\n color: [0.2, 1.0, 0.2, 0.8],\n size: 4,\n lifetime: 1.0,\n gravity: 100, // Low gravity\n damping: 1,\n blendMode: 'additive',\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 private messageOffsets: number[] = [];\n private currentBlock: DemoMessageBlock | null = null;\n\n constructor(buffer: ArrayBuffer) {\n this.buffer = buffer;\n this.view = new DataView(buffer);\n this.offset = 0;\n this.scan();\n }\n\n /**\n * Scans the buffer to build an index of message offsets.\n */\n private scan(): void {\n let scanOffset = 0;\n this.messageOffsets = [];\n\n while (scanOffset + 4 <= this.buffer.byteLength) {\n const length = this.view.getInt32(scanOffset, true);\n\n if (length === -1) {\n // EOF\n break;\n }\n\n if (length < 0 || length > 0x200000) {\n // Sanity check failed, stop scanning\n console.warn(`DemoReader: Invalid block length ${length} at offset ${scanOffset} during scan`);\n break;\n }\n\n if (scanOffset + 4 + length > this.buffer.byteLength) {\n // Incomplete block, stop scanning\n console.warn(`DemoReader: Incomplete block at offset ${scanOffset} during scan`);\n break;\n }\n\n this.messageOffsets.push(scanOffset);\n scanOffset += 4 + length;\n }\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 return null;\n }\n\n const length = this.view.getInt32(this.offset, true);\n\n if (length === -1) {\n // Explicit EOF block\n return null;\n }\n\n // We already validated this in scan(), but let's keep it safe\n if (length < 0 || this.offset + 4 + length > this.buffer.byteLength) {\n return null;\n }\n\n this.offset += 4; // Skip length\n\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 * Advances to the next block and stores it in `currentBlock`.\n * Returns true if a block was read, false otherwise.\n * Compatible with `getBlock()` usage.\n */\n public nextBlock(): boolean {\n const block = this.readNextBlock();\n if (block) {\n this.currentBlock = block;\n return true;\n }\n this.currentBlock = null;\n return false;\n }\n\n /**\n * Returns the current block read by `nextBlock()`.\n */\n public getBlock(): DemoMessageBlock {\n if (!this.currentBlock) {\n throw new Error(\"No current block. Call nextBlock() first.\");\n }\n return this.currentBlock;\n }\n\n /**\n * Reads all remaining blocks and concatenates them into a single buffer.\n * Useful for converting discrete blocks into a continuous stream.\n */\n public readAllBlocksToBuffer(): ArrayBuffer {\n // First pass: Calculate total size\n let totalLength = 0;\n const currentOffset = this.offset;\n const blockInfos: { offset: number, length: number }[] = [];\n\n // Scan ahead without modifying this.offset yet\n let tempOffset = this.offset;\n while (tempOffset + 4 <= this.buffer.byteLength) {\n const length = this.view.getInt32(tempOffset, true);\n if (length === -1) break;\n if (length < 0 || tempOffset + 4 + length > this.buffer.byteLength) {\n break;\n }\n blockInfos.push({ offset: tempOffset + 4, length });\n totalLength += length;\n tempOffset += 4 + length;\n }\n\n // Allocate result buffer\n const result = new Uint8Array(totalLength);\n let resultOffset = 0;\n\n // Copy data\n const srcBytes = new Uint8Array(this.buffer);\n for (const info of blockInfos) {\n result.set(srcBytes.subarray(info.offset, info.offset + info.length), resultOffset);\n resultOffset += info.length;\n }\n\n // Update reader state\n this.offset = tempOffset;\n\n return result.buffer;\n }\n\n /**\n * Resets the reader to the beginning.\n */\n public reset(): void {\n this.offset = 0;\n this.currentBlock = null;\n }\n\n /**\n * Seeks to a specific message index.\n * Returns true if successful, false if index is out of bounds.\n */\n public seekToMessage(index: number): boolean {\n if (index < 0 || index >= this.messageOffsets.length) {\n return false;\n }\n this.offset = this.messageOffsets[index];\n this.currentBlock = null;\n return true;\n }\n\n /**\n * Returns the total number of messages in the demo.\n */\n public getMessageCount(): number {\n return this.messageOffsets.length;\n }\n\n public getOffset(): number {\n return this.offset;\n }\n\n public getProgress(): { current: number; total: number; percent: number } {\n const current = this.offset;\n const total = this.buffer.byteLength;\n return {\n current,\n total,\n percent: total > 0 ? (current / total) * 100 : 0\n };\n }\n}\n","\n/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED$1 = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN$1 = 2;\n\n/*============================================================================*/\n\n\nfunction zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES$1 = 30;\n/* number of distance codes */\n\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\n\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES$1 + 2) * 2);\nzero$1(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES$1 * 2);\nzero$1(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero$1(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);\nzero$1(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES$1);\nzero$1(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES$1);\nzero$1(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Tracev((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Tracev((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) => {\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n\n const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS$1; bits++) {\n code = (code + bl_count[bits - 1]) << 1;\n next_code[bits] = code;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n // \"inconsistent bit counts\");\n //Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n for (n = 0; n <= max_code; n++) {\n let len = tree[n * 2 + 1]/*.Len*/;\n if (len === 0) { continue; }\n /* Now reverse the bits */\n tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);\n\n //Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n }\n};\n\n\n/* ===========================================================================\n * Initialize the various 'constant' tables.\n */\nconst tr_static_init = () => {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES$1 - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES$1; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES$1 + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES$1; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.sym_next = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) => {\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let sx = 0; /* running index in sym_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.sym_next !== 0) {\n do {\n dist = s.pending_buf[s.sym_buf + sx++] & 0xff;\n dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;\n lc = s.pending_buf[s.sym_buf + sx++];\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and sym_buf is ok: */\n //Assert(s->pending < s->lit_bufsize + sx, \"pendingBuf overflow\");\n\n } while (sx < s.sym_next);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE$1;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) => {\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"block list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"allow list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* block_mask is the bit mask of block-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let block_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"block-listed\") bytes. */\n for (n = 0; n <= 31; n++, block_mask >>>= 1) {\n if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"allow-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS$1; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"block-listed\" or \"allow-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init$1 = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n bi_windup(s); /* align on byte boundary */\n put_short(s, stored_len);\n put_short(s, ~stored_len);\n if (stored_len) {\n s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);\n }\n s.pending += stored_len;\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align$1 = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and write out the encoded block.\n */\nconst _tr_flush_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN$1) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->sym_next / 3));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block$1(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally$1 = (s, dist, lc) => {\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n\n s.pending_buf[s.sym_buf + s.sym_next++] = dist;\n s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;\n s.pending_buf[s.sym_buf + s.sym_next++] = lc;\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n return (s.sym_next === s.sym_end);\n};\n\nvar _tr_init_1 = _tr_init$1;\nvar _tr_stored_block_1 = _tr_stored_block$1;\nvar _tr_flush_block_1 = _tr_flush_block$1;\nvar _tr_tally_1 = _tr_tally$1;\nvar _tr_align_1 = _tr_align$1;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants$2 = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_UNKNOWN,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants$2;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42; /* zlib header -> BUSY_STATE */\n//#ifdef GZIP\nconst GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */\n//#endif\nconst EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */\nconst NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */\nconst COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */\nconst HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */\nconst BUSY_STATE = 113; /* deflate -> FINISH_STATE */\nconst FINISH_STATE = 666; /* stream complete */\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) * 2) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n/* ===========================================================================\n * Slide the hash table when sliding the window down (could be avoided with 32\n * bit values at the expense of memory usage). We slide even when level == 0 to\n * keep the hash table consistent if we switch back to level > 0 later.\n */\nconst slide_hash = (s) => {\n let n, m;\n let p;\n let wsize = s.w_size;\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= wsize ? m - wsize : 0);\n } while (--n);\n n = wsize;\n//#ifndef FASTEST\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= wsize ? m - wsize : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n//#endif\n};\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output, except for\n * some deflate_stored() output, goes through this function so some\n * applications may wish to modify it to avoid allocating a large\n * strm->next_out buffer and copying into it. (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let n, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n slide_hash(s);\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n *\n * In case deflateParams() is used to later switch to a non-zero compression\n * level, s->matches (otherwise unused when storing) keeps track of the number\n * of hash table slides to perform. If s->matches is 1, then one hash table\n * slide will be done when switching. If s->matches is 2, the maximum value\n * allowed here, then the hash table will be cleared, since two or more slides\n * is the same as a clear.\n *\n * deflate_stored() is written to minimize the number of times an input byte is\n * copied. It is most efficient with large input and output buffers, which\n * maximizes the opportunites to have a single copy from next_in to next_out.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Smallest worthy block size when not flushing or finishing. By default\n * this is 32K. This can be as small as 507 bytes for memLevel == 1. For\n * large input and output buffers, the stored block size will be larger.\n */\n let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;\n\n /* Copy as many min_block or larger stored blocks directly to next_out as\n * possible. If flushing, copy the remaining available input to next_out as\n * stored blocks, if there is enough space.\n */\n let len, left, have, last = 0;\n let used = s.strm.avail_in;\n do {\n /* Set len to the maximum size block that we can copy directly with the\n * available input data and output space. Set left to how much of that\n * would be copied from what's left in the window.\n */\n len = 65535/* MAX_STORED */; /* maximum deflate stored block length */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n if (s.strm.avail_out < have) { /* need room for header */\n break;\n }\n /* maximum stored block length that will fit in avail_out: */\n have = s.strm.avail_out - have;\n left = s.strstart - s.block_start; /* bytes left in window */\n if (len > left + s.strm.avail_in) {\n len = left + s.strm.avail_in; /* limit len to the input */\n }\n if (len > have) {\n len = have; /* limit len to the output */\n }\n\n /* If the stored block would be less than min_block in length, or if\n * unable to copy all of the available input when flushing, then try\n * copying to the window and the pending buffer instead. Also don't\n * write an empty block when flushing -- deflate() does that.\n */\n if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) ||\n flush === Z_NO_FLUSH$2 ||\n len !== left + s.strm.avail_in)) {\n break;\n }\n\n /* Make a dummy stored block in pending to get the header bytes,\n * including any pending bits. This also updates the debugging counts.\n */\n last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;\n _tr_stored_block(s, 0, 0, last);\n\n /* Replace the lengths in the dummy stored block with len. */\n s.pending_buf[s.pending - 4] = len;\n s.pending_buf[s.pending - 3] = len >> 8;\n s.pending_buf[s.pending - 2] = ~len;\n s.pending_buf[s.pending - 1] = ~len >> 8;\n\n /* Write the stored block header bytes. */\n flush_pending(s.strm);\n\n//#ifdef ZLIB_DEBUG\n// /* Update debugging counts for the data about to be copied. */\n// s->compressed_len += len << 3;\n// s->bits_sent += len << 3;\n//#endif\n\n /* Copy uncompressed bytes from the window to next_out. */\n if (left) {\n if (left > len) {\n left = len;\n }\n //zmemcpy(s->strm->next_out, s->window + s->block_start, left);\n s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);\n s.strm.next_out += left;\n s.strm.avail_out -= left;\n s.strm.total_out += left;\n s.block_start += left;\n len -= left;\n }\n\n /* Copy uncompressed bytes directly from next_in to next_out, updating\n * the check value.\n */\n if (len) {\n read_buf(s.strm, s.strm.output, s.strm.next_out, len);\n s.strm.next_out += len;\n s.strm.avail_out -= len;\n s.strm.total_out += len;\n }\n } while (last === 0);\n\n /* Update the sliding window with the last s->w_size bytes of the copied\n * data, or append all of the copied data to the existing window if less\n * than s->w_size bytes were copied. Also update the number of bytes to\n * insert in the hash tables, in the event that deflateParams() switches to\n * a non-zero compression level.\n */\n used -= s.strm.avail_in; /* number of input bytes directly copied */\n if (used) {\n /* If any input was used, then no unused input remains in the window,\n * therefore s->block_start == s->strstart.\n */\n if (used >= s.w_size) { /* supplant the previous history */\n s.matches = 2; /* clear hash */\n //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);\n s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);\n s.strstart = s.w_size;\n s.insert = s.strstart;\n }\n else {\n if (s.window_size - s.strstart <= used) {\n /* Slide the window down. */\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);\n s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);\n s.strstart += used;\n s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;\n }\n s.block_start = s.strstart;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* If the last block was written to next_out, then done. */\n if (last) {\n return BS_FINISH_DONE;\n }\n\n /* If flushing and all input has been consumed, then done. */\n if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 &&\n s.strm.avail_in === 0 && s.strstart === s.block_start) {\n return BS_BLOCK_DONE;\n }\n\n /* Fill the window with any remaining input. */\n have = s.window_size - s.strstart;\n if (s.strm.avail_in > have && s.block_start >= s.w_size) {\n /* Slide the window down. */\n s.block_start -= s.w_size;\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n have += s.w_size; /* more space now */\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n if (have > s.strm.avail_in) {\n have = s.strm.avail_in;\n }\n if (have) {\n read_buf(s.strm, s.window, s.strstart, have);\n s.strstart += have;\n s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* There was not enough avail_out to write a complete worthy or flushed\n * stored block to next_out. Write a stored block to pending instead, if we\n * have enough input for a worthy block, or if flushing and there is enough\n * room for the remaining input as a stored block in the pending buffer.\n */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n /* maximum stored block length that will fit in pending: */\n have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;\n min_block = have > s.w_size ? s.w_size : have;\n left = s.strstart - s.block_start;\n if (left >= min_block ||\n ((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 &&\n s.strm.avail_in === 0 && left <= have)) {\n len = left > have ? have : left;\n last = flush === Z_FINISH$3 && s.strm.avail_in === 0 &&\n len === left ? 1 : 0;\n _tr_stored_block(s, s.block_start, len, last);\n s.block_start += len;\n flush_pending(s.strm);\n }\n\n /* We've done all we can with the available input and output. */\n return last ? BS_FINISH_STARTED : BS_NEED_MORE;\n};\n\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED$2; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.sym_buf = 0; /* buffer for distances and literals/lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.sym_next = 0; /* running index in sym_buf */\n this.sym_end = 0; /* symbol table full when sym_next reaches this */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\n/* =========================================================================\n * Check for a valid deflate stream state. Return 0 if ok, 1 if not.\n */\nconst deflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const s = strm.state;\n if (!s || s.strm !== strm || (s.status !== INIT_STATE &&\n//#ifdef GZIP\n s.status !== GZIP_STATE &&\n//#endif\n s.status !== EXTRA_STATE &&\n s.status !== NAME_STATE &&\n s.status !== COMMENT_STATE &&\n s.status !== HCRC_STATE &&\n s.status !== BUSY_STATE &&\n s.status !== FINISH_STATE)) {\n return 1;\n }\n return 0;\n};\n\n\nconst deflateResetKeep = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status =\n//#ifdef GZIP\n s.wrap === 2 ? GZIP_STATE :\n//#endif\n s.wrap ? INIT_STATE : BUSY_STATE;\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = -2;\n _tr_init(s);\n return Z_OK$3;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK$3) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (deflateStateCheck(strm) || strm.state.wrap !== 2) {\n return Z_STREAM_ERROR$2;\n }\n strm.state.gzhead = head;\n return Z_OK$3;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR$2;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION$1) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n s.status = INIT_STATE; /* to pass state test in deflateReset() */\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n /* We overlay pending_buf and sym_buf. This works since the average size\n * for length/distance pairs over any compressed block is assured to be 31\n * bits or less.\n *\n * Analysis: The longest fixed codes are a length code of 8 bits plus 5\n * extra bits, for lengths 131 to 257. The longest fixed distance codes are\n * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest\n * possible fixed-codes length/distance pair is then 31 bits total.\n *\n * sym_buf starts one-fourth of the way into pending_buf. So there are\n * three bytes in sym_buf for every four bytes in pending_buf. Each symbol\n * in sym_buf is three bytes -- two for the distance and one for the\n * literal/length. As each symbol is consumed, the pointer to the next\n * sym_buf value to read moves forward three bytes. From that symbol, up to\n * 31 bits are written to pending_buf. The closest the written pending_buf\n * bits gets to the next sym_buf symbol to read is just before the last\n * code is written. At that time, 31*(n-2) bits have been written, just\n * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at\n * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1\n * symbols are written.) The closest the writing gets to what is unread is\n * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and\n * can range from 128 to 32768.\n *\n * Therefore, at a minimum, there are 142 bits of space between what is\n * written and what is read in the overlain buffers, so the symbols cannot\n * be overwritten by the compressed data. That space is actually 139 bits,\n * due to the three-bit fixed-code block header.\n *\n * That covers the case where either Z_FIXED is specified, forcing fixed\n * codes, or when the use of fixed codes is chosen, because that choice\n * results in a smaller compressed block than dynamic codes. That latter\n * condition then assures that the above analysis also covers all dynamic\n * blocks. A dynamic-code block will only be chosen to be emitted if it has\n * fewer bits than a fixed-code block would for the same set of symbols.\n * Therefore its average symbol length is assured to be less than 31. So\n * the compressed data for a dynamic block also cannot overwrite the\n * symbols from which it is being constructed.\n */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->sym_buf = s->pending_buf + s->lit_bufsize;\n s.sym_buf = s.lit_bufsize;\n\n //s->sym_end = (s->lit_bufsize - 1) * 3;\n s.sym_end = (s.lit_bufsize - 1) * 3;\n /* We avoid equality with lit_bufsize*3 because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);\n};\n\n\n/* ========================================================================= */\nconst deflate$2 = (strm, flush) => {\n\n if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (strm.avail_in !== 0 && !strm.input) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH$3)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);\n }\n\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK$3;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH$3) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* Write the header */\n if (s.status === INIT_STATE && s.wrap === 0) {\n s.status = BUSY_STATE;\n }\n if (s.status === INIT_STATE) {\n /* zlib header */\n let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#ifdef GZIP\n if (s.status === GZIP_STATE) {\n /* gzip header */\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;\n while (s.pending + left > s.pending_buf_size) {\n let copy = s.pending_buf_size - s.pending;\n // zmemcpy(s.pending_buf + s.pending,\n // s.gzhead.extra + s.gzindex, copy);\n s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);\n s.pending = s.pending_buf_size;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex += copy;\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n left -= copy;\n }\n // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility\n // TypedArray.slice and TypedArray.from don't exist in IE10-IE11\n let gzhead_extra = new Uint8Array(s.gzhead.extra);\n // zmemcpy(s->pending_buf + s->pending,\n // s->gzhead->extra + s->gzindex, left);\n s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);\n s.pending += left;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = NAME_STATE;\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = COMMENT_STATE;\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n }\n s.status = HCRC_STATE;\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n }\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#endif\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {\n let bstate = s.level === 0 ? deflate_stored(s, flush) :\n s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush);\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK$3;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align(s);\n }\n else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH$1) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK$3;\n }\n }\n }\n\n if (flush !== Z_FINISH$3) { return Z_OK$3; }\n if (s.wrap <= 0) { return Z_STREAM_END$3; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const status = strm.state.status;\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR$2;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK$3;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2$1 = deflate$2;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateGetDictionary = deflateGetDictionary;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1$2 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2$1,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {\n return new TextEncoder().encode(str);\n }\n\n let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n const len = max || buf.length;\n\n if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {\n return new TextDecoder().decode(buf.subarray(0, max));\n }\n\n let i, out;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate$1(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1$2.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1$2.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1$2.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1$2.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$2) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1$2.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$2;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$2) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate$1(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip$1(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_2 = deflate$1;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar constants$1 = constants$2;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD$1 = 16209; /* got a data error -- remain here until reset */\nconst TYPE$1 = 16191; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE$1;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n// let shoextra; /* extra bits table to use */\n let match; /* use base and extra for symbol >= match */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES$1 || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES$1) {\n base = extra = work; /* dummy value--not used */\n match = 20;\n\n } else if (type === LENS$1) {\n base = lbase;\n extra = lext;\n match = 257;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n match = 0;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] + 1 < match) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] >= match) {\n here_op = extra[work[sym] - match];\n here_val = base[work[sym] - match];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,\n Z_DEFLATED\n} = constants$2;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 16180; /* i: waiting for magic header */\nconst FLAGS = 16181; /* i: waiting for method and flags (gzip) */\nconst TIME = 16182; /* i: waiting for modification time (gzip) */\nconst OS = 16183; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 16184; /* i: waiting for extra length (gzip) */\nconst EXTRA = 16185; /* i: waiting for extra bytes (gzip) */\nconst NAME = 16186; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 16187; /* i: waiting for end of comment (gzip) */\nconst HCRC = 16188; /* i: waiting for header crc (gzip) */\nconst DICTID = 16189; /* i: waiting for dictionary check value */\nconst DICT = 16190; /* waiting for inflateSetDictionary() call */\nconst TYPE = 16191; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 16192; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 16193; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 16194; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16195; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 16196; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 16197; /* i: waiting for code length code lengths */\nconst CODELENS = 16198; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 16199; /* i: same as LEN below, but only first time in */\nconst LEN = 16200; /* i: waiting for length/lit/eob code */\nconst LENEXT = 16201; /* i: waiting for length extra bits */\nconst DIST = 16202; /* i: waiting for distance code */\nconst DISTEXT = 16203; /* i: waiting for distance extra bits */\nconst MATCH = 16204; /* o: waiting for output space to copy string */\nconst LIT = 16205; /* o: waiting for output space to write literal */\nconst CHECK = 16206; /* i: waiting for 32-bit check value */\nconst LENGTH = 16207; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 16208; /* finished check, done -- remain here until reset */\nconst BAD = 16209; /* got a data error -- remain here until reset */\nconst MEM = 16210; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 16211; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip,\n bit 2 true to validate check value */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib), or\n -1 if raw or no header yet */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const state = strm.state;\n if (!state || state.strm !== strm ||\n state.mode < HEAD || state.mode > SYNC) {\n return 1;\n }\n return 0;\n};\n\n\nconst inflateResetKeep = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.flags = -1;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$1;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 5;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.strm = strm;\n state.window = null/*Z_NULL*/;\n state.mode = HEAD; /* to pass state test in inflateReset2() */\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$1) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate$2 = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (inflateStateCheck(strm) || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$1;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n if (state.wbits === 0) {\n state.wbits = 15;\n }\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n if (len > 15 || len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n state.flags = 0; /* indicate zlib header */\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT$1;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check =\n /*UPDATE_CHECK(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$1;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR$1;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH$1))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (inflateStateCheck(strm)) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$1;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$1;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR$1;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$1;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2$1 = inflate$2;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCodesUsed = inflateCodesUsed;\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\nmodule.exports.inflateValidate = inflateValidate;\n*/\n\nvar inflate_1$2 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2$1,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate$1(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1$2.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1$2.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;\n\n // Convert data if needed\n if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1$2.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT && dictionary) {\n status = inflate_1$2.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK) {\n status = inflate_1$2.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR) {\n // Replace code with more verbose\n status = Z_NEED_DICT;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1$2.inflateReset(strm);\n status = inflate_1$2.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR:\n case Z_DATA_ERROR:\n case Z_NEED_DICT:\n case Z_MEM_ERROR:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END) {\n status = inflate_1$2.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err) {\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate$1(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1$1 = Inflate$1;\nvar inflate_2 = inflate$1;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip$1 = inflate$1;\nvar constants = constants$2;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1$1,\n\tinflate: inflate_2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip$1,\n\tconstants: constants\n};\n\nconst { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;\n\nconst { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;\n\n\n\nvar Deflate_1 = Deflate;\nvar deflate_1 = deflate;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar Inflate_1 = Inflate;\nvar inflate_1 = inflate;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip_1 = ungzip;\nvar constants_1 = constants$2;\n\nvar pako = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tInflate: Inflate_1,\n\tinflate: inflate_1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nexport { Deflate_1 as Deflate, Inflate_1 as Inflate, constants_1 as constants, pako as default, deflate_1 as deflate, deflateRaw_1 as deflateRaw, gzip_1 as gzip, inflate_1 as inflate, inflateRaw_1 as inflateRaw, ungzip_1 as ungzip };\n","/**\n * StreamingBuffer - Continuous buffer for network message parsing\n *\n * Matches vanilla Quake 2's net_message buffer architecture from:\n * - /home/user/quake2/full/qcommon/msg.c (MSG_Read* functions)\n * - /home/user/quake2/full/client/cl_main.c:1798-1799 (buffer initialization)\n *\n * Maintains a continuous stream buffer that can be incrementally filled with\n * data from demo blocks or network packets, while preserving read position\n * for stateful parsing.\n */\nexport class StreamingBuffer {\n private buffer: Uint8Array;\n private readOffset: number;\n private writeOffset: number;\n private static readonly INITIAL_SIZE = 64 * 1024; // 64KB initial buffer\n private static readonly MAX_STRING_LENGTH = 2048; // From vanilla Q2\n\n constructor(initialCapacity: number = StreamingBuffer.INITIAL_SIZE) {\n this.buffer = new Uint8Array(initialCapacity);\n this.readOffset = 0;\n this.writeOffset = 0;\n }\n\n /**\n * Append new data to the buffer (for demos: append blocks; for network: append packets)\n * Grows buffer if needed to accommodate new data.\n */\n append(data: ArrayBuffer | Uint8Array): void {\n const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);\n const requiredSize = this.writeOffset + bytes.length;\n\n // Grow buffer if needed\n if (requiredSize > this.buffer.length) {\n this.grow(requiredSize);\n }\n\n // Append data at write position\n this.buffer.set(bytes, this.writeOffset);\n this.writeOffset += bytes.length;\n }\n\n /**\n * Check if we have N bytes available from current read position\n */\n hasBytes(count: number): boolean {\n return (this.writeOffset - this.readOffset) >= count;\n }\n\n /**\n * Get number of bytes available for reading\n */\n available(): number {\n return this.writeOffset - this.readOffset;\n }\n\n /**\n * Read one byte and advance position\n * Reference: MSG_ReadByte() in /home/user/quake2/full/qcommon/msg.c\n */\n readByte(): number {\n if (!this.hasBytes(1)) {\n throw new Error('Buffer underflow');\n }\n return this.buffer[this.readOffset++];\n }\n\n /**\n * Read 2-byte short (little-endian) and advance position\n * Reference: MSG_ReadShort() in /home/user/quake2/full/qcommon/msg.c\n */\n readShort(): number {\n if (!this.hasBytes(2)) {\n throw new Error('Buffer underflow');\n }\n const value = this.buffer[this.readOffset] |\n (this.buffer[this.readOffset + 1] << 8);\n this.readOffset += 2;\n // Handle sign extension for signed shorts\n return value > 0x7FFF ? value - 0x10000 : value;\n }\n\n /**\n * Read 4-byte long (little-endian) and advance position\n * Reference: MSG_ReadLong() in /home/user/quake2/full/qcommon/msg.c\n */\n readLong(): number {\n if (!this.hasBytes(4)) {\n throw new Error('Buffer underflow');\n }\n const value = this.buffer[this.readOffset] |\n (this.buffer[this.readOffset + 1] << 8) |\n (this.buffer[this.readOffset + 2] << 16) |\n (this.buffer[this.readOffset + 3] << 24);\n this.readOffset += 4;\n // JavaScript bitwise operations return signed 32-bit integers\n return value;\n }\n\n /**\n * Read 4-byte float (little-endian) and advance position\n */\n readFloat(): number {\n if (!this.hasBytes(4)) {\n throw new Error('Buffer underflow');\n }\n const view = new DataView(this.buffer.buffer, this.buffer.byteOffset + this.readOffset, 4);\n const val = view.getFloat32(0, true); // Little endian\n this.readOffset += 4;\n return val;\n }\n\n /**\n * Read null-terminated string and advance position\n * Reference: MSG_ReadString() in /home/user/quake2/full/qcommon/msg.c\n */\n readString(): string {\n const maxLength = Math.min(\n StreamingBuffer.MAX_STRING_LENGTH,\n this.writeOffset - this.readOffset\n );\n\n let length = 0;\n // Find null terminator\n while (length < maxLength && this.buffer[this.readOffset + length] !== 0) {\n length++;\n }\n\n if (length >= maxLength) {\n // Check if we hit end of buffer or max string length\n if (this.writeOffset - this.readOffset <= maxLength) {\n throw new Error('Buffer underflow');\n }\n throw new Error('String exceeds max length');\n }\n\n // Read string bytes (excluding null terminator)\n const bytes = this.buffer.slice(this.readOffset, this.readOffset + length);\n this.readOffset += length + 1; // +1 to skip null terminator\n\n // Convert to string (ASCII/Latin-1 encoding like vanilla Q2)\n return new TextDecoder('latin1').decode(bytes);\n }\n\n /**\n * Read raw bytes without advancing position (peek)\n */\n peekBytes(count: number): Uint8Array {\n if (!this.hasBytes(count)) {\n throw new Error('Buffer underflow');\n }\n return this.buffer.slice(this.readOffset, this.readOffset + count);\n }\n\n /**\n * Read raw bytes and advance position\n */\n readBytes(count: number): Uint8Array {\n if (!this.hasBytes(count)) {\n throw new Error('Buffer underflow');\n }\n const bytes = this.buffer.slice(this.readOffset, this.readOffset + count);\n this.readOffset += count;\n return bytes;\n }\n\n /**\n * Alias for readBytes to match tests\n */\n readData(count: number): Uint8Array {\n return this.readBytes(count);\n }\n\n /**\n * Get current read position (for debugging/state tracking)\n */\n getReadPosition(): number {\n return this.readOffset;\n }\n\n /**\n * Get current write position (for debugging/state tracking)\n */\n getWritePosition(): number {\n return this.writeOffset;\n }\n\n /**\n * Set read position (use with caution - mainly for testing)\n */\n setReadPosition(position: number): void {\n if (position < 0 || position > this.writeOffset) {\n throw new Error('Invalid read position');\n }\n this.readOffset = position;\n }\n\n /**\n * Grow buffer to accommodate more data\n * Doubles current size or grows to required size, whichever is larger\n */\n private grow(requiredSize?: number): void {\n const newSize = requiredSize\n ? Math.max(requiredSize, this.buffer.length * 2)\n : this.buffer.length * 2;\n\n const newBuffer = new Uint8Array(newSize);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n\n /**\n * Compact buffer - remove consumed data to free memory\n * Copies unread data to beginning of buffer and resets offsets\n *\n * Call this periodically when processing large streams to prevent\n * unbounded memory growth.\n */\n compact(): void {\n if (this.readOffset === 0) {\n // Nothing to compact\n return;\n }\n\n const unreadBytes = this.writeOffset - this.readOffset;\n\n if (unreadBytes === 0) {\n // All data consumed, just reset offsets\n this.readOffset = 0;\n this.writeOffset = 0;\n return;\n }\n\n // Copy unread data to beginning of buffer\n this.buffer.copyWithin(0, this.readOffset, this.writeOffset);\n\n // Reset offsets\n this.readOffset = 0;\n this.writeOffset = unreadBytes;\n }\n\n /**\n * Get total buffer capacity\n */\n getCapacity(): number {\n return this.buffer.length;\n }\n\n /**\n * Reset buffer to initial state (clear all data)\n */\n reset(): void {\n this.readOffset = 0;\n this.writeOffset = 0;\n }\n}\n","\n// Rerelease Protocol Impl\nimport { BinaryStream, Vec3, ServerCommand, TempEntity, ANORMS } from '@quake2ts/shared';\nimport pako from 'pako';\nimport { StreamingBuffer } from '../stream/streamingBuffer.js';\n\nexport const PROTOCOL_VERSION_RERELEASE = 2023;\n\n// Constants from Q2 source (qcommon/qcommon.h)\nexport const U_ORIGIN1 = (1 << 0);\nexport const U_ORIGIN2 = (1 << 1);\nexport const U_ANGLE2 = (1 << 2);\nexport const U_ANGLE3 = (1 << 3);\nexport const U_FRAME8 = (1 << 4);\nexport const U_EVENT = (1 << 5);\nexport const U_REMOVE = (1 << 6);\nexport const U_MOREBITS1 = (1 << 7);\n\nexport const U_NUMBER16 = (1 << 8);\nexport const U_ORIGIN3 = (1 << 9);\nexport const U_ANGLE1 = (1 << 10);\nexport const U_MODEL = (1 << 11);\nexport const U_RENDERFX8 = (1 << 12);\nexport const U_ALPHA = (1 << 13);\nexport const U_EFFECTS8 = (1 << 14);\nexport const U_MOREBITS2 = (1 << 15);\n\nexport const U_SKIN8 = (1 << 16);\nexport const U_FRAME16 = (1 << 17);\nexport const U_RENDERFX16 = (1 << 18);\nexport const U_EFFECTS16 = (1 << 19);\nexport const U_MODEL2 = (1 << 20);\nexport const U_MODEL3 = (1 << 21);\nexport const U_MODEL4 = (1 << 22);\nexport const U_MOREBITS3 = (1 << 23);\n\nexport const U_OLDORIGIN = (1 << 24);\nexport const U_SKIN16 = (1 << 25);\nexport const U_SOUND = (1 << 26);\nexport const U_SOLID = (1 << 27);\n\nexport const U_SCALE = (1 << 28);\nexport const U_INSTANCE_BITS = (1 << 29);\nexport const U_LOOP_VOLUME = (1 << 30);\nexport const U_MOREBITS4 = 0x80000000 | 0;\n\nexport const U_LOOP_ATTENUATION_HIGH = (1 << 0);\nexport const U_OWNER_HIGH = (1 << 1);\nexport const U_OLD_FRAME_HIGH = (1 << 2);\n\nconst RECORD_NETWORK = 0x00;\nconst RECORD_CLIENT = 0x01;\nconst RECORD_SERVER = 0x02;\nconst RECORD_RELAY = 0x80;\n\nexport interface 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 bits: number;\n bitsHigh: number;\n alpha: number;\n scale: number;\n instanceBits: number;\n loopVolume: number;\n loopAttenuation: number;\n owner: number;\n oldFrame: 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 bits: 0,\n bitsHigh: 0,\n alpha: 0,\n scale: 0,\n instanceBits: 0,\n loopVolume: 0,\n loopAttenuation: 0,\n owner: 0,\n oldFrame: 0\n});\n\nexport interface ProtocolPlayerState {\n pm_type: number;\n origin: MutableVec3;\n velocity: MutableVec3;\n pm_time: number;\n pm_flags: number;\n gravity: number;\n delta_angles: MutableVec3;\n viewoffset: MutableVec3;\n viewangles: MutableVec3;\n kick_angles: MutableVec3;\n gun_index: number;\n gun_frame: number;\n gun_offset: MutableVec3;\n gun_angles: MutableVec3;\n blend: number[];\n fov: number;\n rdflags: number;\n stats: number[];\n gunskin: number;\n gunrate: number;\n damage_blend: number[];\n team_id: number;\n watertype: number;\n}\n\nexport const createEmptyProtocolPlayerState = (): ProtocolPlayerState => ({\n pm_type: 0,\n origin: { x: 0, y: 0, z: 0 },\n velocity: { x: 0, y: 0, z: 0 },\n pm_time: 0,\n pm_flags: 0,\n gravity: 0,\n delta_angles: { x: 0, y: 0, z: 0 },\n viewoffset: { x: 0, y: 0, z: 0 },\n viewangles: { x: 0, y: 0, z: 0 },\n kick_angles: { x: 0, y: 0, z: 0 },\n gun_index: 0,\n gun_frame: 0,\n gun_offset: { x: 0, y: 0, z: 0 },\n gun_angles: { x: 0, y: 0, z: 0 },\n blend: [0, 0, 0, 0],\n fov: 0,\n rdflags: 0,\n stats: new Array(32).fill(0),\n gunskin: 0,\n gunrate: 0,\n damage_blend: [0, 0, 0, 0],\n team_id: 0,\n watertype: 0\n});\n\nexport interface FrameData {\n serverFrame: number;\n deltaFrame: number;\n surpressCount: number;\n areaBytes: number;\n areaBits: Uint8Array;\n playerState: ProtocolPlayerState;\n packetEntities: {\n delta: boolean;\n entities: EntityState[];\n };\n}\n\nexport interface FogData {\n density?: number;\n skyfactor?: number;\n red?: number;\n green?: number;\n blue?: number;\n time?: number;\n hf_falloff?: number;\n hf_density?: number;\n hf_start_r?: number;\n hf_start_g?: number;\n hf_start_b?: number;\n hf_start_dist?: number;\n hf_end_r?: number;\n hf_end_g?: number;\n hf_end_b?: number;\n hf_end_dist?: number;\n}\n\nexport interface DamageIndicator {\n damage: number;\n health: boolean;\n armor: boolean;\n power: boolean;\n dir: Vec3;\n}\n\nexport interface NetworkMessageHandler {\n onServerData(protocol: number, serverCount: number, attractLoop: number, gameDir: string, playerNum: number, levelName: string, tickRate?: number, demoType?: number): void;\n onConfigString(index: number, str: string): void;\n onSpawnBaseline(entity: EntityState): void;\n onFrame(frame: FrameData): void;\n onCenterPrint(msg: string): void;\n onStuffText(msg: string): void;\n onPrint(level: number, msg: string): void;\n onSound(flags: number, soundNum: number, volume?: number, attenuation?: number, offset?: number, ent?: number, pos?: Vec3): void;\n onTempEntity(type: number, pos: Vec3, pos2?: Vec3, dir?: Vec3, cnt?: number, color?: number, ent?: number, srcEnt?: number, destEnt?: number): void;\n onLayout(layout: string): void;\n onInventory(inventory: number[]): void;\n onMuzzleFlash(ent: number, weapon: number): void;\n onMuzzleFlash2(ent: number, weapon: number): void;\n onDisconnect(): void;\n onReconnect(): void;\n onDownload(size: number, percent: number, data?: Uint8Array): void;\n getEntities?(): Map<number, EntityState>;\n getPlayerState?(): ProtocolPlayerState | null;\n onSplitClient?(clientNum: number): void;\n onConfigBlast?(index: number, data: Uint8Array): void;\n onSpawnBaselineBlast?(entity: EntityState): void;\n onLevelRestart?(): void;\n onDamage?(indicators: DamageIndicator[]): void;\n onLocPrint?(flags: number, base: string, args: string[]): void;\n onFog?(data: FogData): void;\n onWaitingForPlayers?(count: number): void;\n onBotChat?(msg: string): void;\n onPoi?(flags: number, pos: Vec3): void;\n onHelpPath?(pos: Vec3): void;\n onMuzzleFlash3?(ent: number, weapon: number): void;\n onAchievement?(id: string): void;\n}\n\nexport interface ParseResult {\n commandsParsed: number;\n parseState: 'awaiting_data' | 'complete' | 'error';\n bytesConsumed: number;\n}\n\n/**\n * Adapter to allow using BinaryStream where StreamingBuffer is expected\n * Used for backward compatibility or when reading from compressed/decompressed buffers.\n */\nclass BinaryStreamAdapter extends StreamingBuffer {\n constructor(private stream: BinaryStream) {\n super(0);\n }\n\n override readByte(): number { return this.stream.readByte(); }\n override readShort(): number { return this.stream.readShort(); }\n override readLong(): number { return this.stream.readLong(); }\n override readFloat(): number { return this.stream.readFloat(); }\n override readString(): string { return this.stream.readString(); }\n override readData(count: number): Uint8Array { return this.stream.readData(count); }\n override hasBytes(count: number): boolean { return this.stream.hasMore(); }\n override available(): number { return this.stream.getRemaining(); } // Assuming getRemaining exists on BinaryStream interface in shared\n override getReadPosition(): number { return this.stream.getPosition(); }\n override peekBytes(count: number): Uint8Array {\n throw new Error(\"peekBytes not implemented for BinaryStreamAdapter\");\n }\n}\n\n// Protocol 34 (Original Q2) Opcode Mapping\nconst PROTO34_MAP: Record<number, number> = {\n 0: ServerCommand.bad,\n 1: ServerCommand.nop,\n 2: ServerCommand.disconnect,\n 3: ServerCommand.reconnect,\n 4: ServerCommand.download,\n 5: ServerCommand.frame,\n 6: ServerCommand.inventory,\n 7: ServerCommand.layout,\n 8: ServerCommand.muzzleflash,\n 9: ServerCommand.sound,\n 10: ServerCommand.print,\n 11: ServerCommand.stufftext,\n 12: ServerCommand.serverdata,\n 13: ServerCommand.configstring,\n 14: ServerCommand.spawnbaseline,\n 15: ServerCommand.centerprint,\n 16: ServerCommand.download,\n 17: ServerCommand.playerinfo,\n 18: ServerCommand.packetentities,\n 19: ServerCommand.deltapacketentities,\n 23: ServerCommand.temp_entity, // Wire 23 -> Enum 3 (TempEntity)\n 22: ServerCommand.muzzleflash2 // Wire 22 -> Enum 2 (MuzzleFlash2)\n};\n\nexport class NetworkMessageParser {\n private stream: StreamingBuffer;\n private protocolVersion: number = 0;\n private isDemo: number = RECORD_CLIENT;\n private handler?: NetworkMessageHandler;\n private strictMode: boolean = false;\n private errorCount: number = 0;\n\n constructor(stream: StreamingBuffer | BinaryStream, handler?: NetworkMessageHandler, strictMode: boolean = false) {\n if (stream instanceof BinaryStream) {\n this.stream = new BinaryStreamAdapter(stream);\n } else {\n this.stream = stream;\n }\n this.handler = handler;\n this.strictMode = strictMode;\n }\n\n public setProtocolVersion(version: number): void {\n this.protocolVersion = version;\n }\n\n public getProtocolVersion(): number {\n return this.protocolVersion;\n }\n\n public getErrorCount(): number {\n return this.errorCount;\n }\n\n private translateCommand(cmd: number): number {\n if (this.protocolVersion === 0) {\n if (cmd === 7) return ServerCommand.serverdata;\n if (cmd === 12) return ServerCommand.serverdata;\n return cmd;\n }\n\n if (this.protocolVersion === PROTOCOL_VERSION_RERELEASE) {\n return cmd;\n }\n\n if (this.protocolVersion === 25 || this.protocolVersion === 26) {\n if (cmd === 0) return ServerCommand.bad;\n const translated = cmd + 5;\n if (translated >= ServerCommand.nop && translated <= ServerCommand.frame) {\n return translated;\n }\n return ServerCommand.bad;\n }\n\n if (this.protocolVersion === 34) {\n // Use the mapping table\n if (PROTO34_MAP[cmd] !== undefined) {\n return PROTO34_MAP[cmd];\n }\n // Fallback for known identity commands or missing mappings?\n // But strict protocol 34 mapping is safer.\n // For now, if not in map, return bad.\n return ServerCommand.bad;\n }\n\n return cmd;\n }\n\n public parseMessage(): void {\n while (this.stream.hasBytes(1)) {\n const startPos = this.stream.getReadPosition();\n let cmd = -1;\n\n try {\n cmd = this.stream.readByte();\n\n if (cmd === -1) break;\n\n const originalCmd = cmd;\n cmd = this.translateCommand(cmd);\n\n switch (cmd) {\n case ServerCommand.bad:\n // Terminate this parse cycle, usually padding or end of demo block\n return;\n case ServerCommand.nop: break;\n case ServerCommand.disconnect: if (this.handler?.onDisconnect) this.handler.onDisconnect(); break;\n case ServerCommand.reconnect: if (this.handler?.onReconnect) this.handler.onReconnect(); break;\n case ServerCommand.print: this.parsePrint(); break;\n case ServerCommand.serverdata: this.parseServerData(); break;\n case ServerCommand.configstring: this.parseConfigString(); break;\n case ServerCommand.spawnbaseline: this.parseSpawnBaseline(); break;\n case ServerCommand.centerprint: this.parseCenterPrint(); break;\n case ServerCommand.download: this.parseDownload(); break;\n case ServerCommand.frame: this.parseFrame(); break;\n case ServerCommand.packetentities: this.parsePacketEntities(false); break;\n case ServerCommand.deltapacketentities: this.parsePacketEntities(true); break;\n case ServerCommand.playerinfo: this.parsePlayerState(); break;\n case ServerCommand.stufftext: this.parseStuffText(); break;\n case ServerCommand.layout: this.parseLayout(); break;\n case ServerCommand.inventory: this.parseInventory(); break;\n case ServerCommand.sound: this.parseSound(); break;\n case ServerCommand.muzzleflash: this.parseMuzzleFlash(); break;\n case ServerCommand.muzzleflash2: this.parseMuzzleFlash2(); break;\n case ServerCommand.temp_entity: this.parseTempEntity(); break;\n case ServerCommand.splitclient: this.parseSplitClient(); break;\n case ServerCommand.configblast: this.parseConfigBlast(); break;\n case ServerCommand.spawnbaselineblast: this.parseSpawnBaselineBlast(); break;\n case ServerCommand.level_restart: if (this.handler?.onLevelRestart) this.handler.onLevelRestart(); break;\n case ServerCommand.damage: this.parseDamage(); break;\n case ServerCommand.locprint: this.parseLocPrint(); break;\n case ServerCommand.fog: this.parseFog(); break;\n case ServerCommand.waitingforplayers: this.parseWaitingForPlayers(); break;\n case ServerCommand.bot_chat: this.parseBotChat(); break;\n case ServerCommand.poi: this.parsePoi(); break;\n case ServerCommand.help_path: this.parseHelpPath(); break;\n case ServerCommand.muzzleflash3: this.parseMuzzleFlash3(); break;\n case ServerCommand.achievement: this.parseAchievement(); break;\n\n default:\n const errorMsg = `Unknown server command: ${originalCmd} (translated: ${cmd}) at offset ${startPos}`;\n if (this.strictMode) throw new Error(errorMsg);\n console.warn(errorMsg);\n this.errorCount++;\n return;\n }\n\n } catch (e) {\n const errMsg = (e as Error).message;\n if (errMsg === 'Buffer underflow' || errMsg.includes('StreamingBuffer')) {\n try {\n this.stream.setReadPosition(startPos);\n } catch (rollbackErr) {\n console.error('Failed to rollback stream position', rollbackErr);\n }\n return;\n }\n\n const context = `offset ${startPos}, cmd ${cmd}, protocol ${this.protocolVersion}`;\n console.warn(`Error parsing command ${cmd} (${context}): ${errMsg}`);\n this.errorCount++;\n\n if (this.strictMode) throw e;\n return;\n }\n }\n }\n\n private readAngle16(): number { return this.stream.readShort() * (360.0 / 65536); }\n private readCoord(): number { return this.stream.readShort() * 0.125; }\n private readAngle(): number { return this.stream.readByte() * (360.0 / 256); }\n\n private readPos(out: MutableVec3): void {\n out.x = this.stream.readShort() * 0.125;\n out.y = this.stream.readShort() * 0.125;\n out.z = this.stream.readShort() * 0.125;\n }\n\n private readDir(out: MutableVec3): void {\n const b = this.stream.readByte();\n if (b >= ANORMS.length) {\n out.x=0; out.y=0; out.z=0;\n } else {\n const n = ANORMS[b];\n out.x = n[0]; out.y = n[1]; out.z = n[2];\n }\n }\n\n private parsePrint(): void {\n const id = this.stream.readByte();\n const str = this.stream.readString();\n if (this.handler) this.handler.onPrint(id, str);\n }\n\n private parseStuffText(): void {\n const text = this.stream.readString();\n if (this.handler) this.handler.onStuffText(text);\n }\n\n private parseLayout(): void {\n const layout = this.stream.readString();\n if (this.handler) this.handler.onLayout(layout);\n }\n\n private parseCenterPrint(): void {\n const centerMsg = this.stream.readString();\n if (this.handler) this.handler.onCenterPrint(centerMsg);\n }\n\n private parseServerData(): void {\n this.protocolVersion = this.stream.readLong();\n if (this.protocolVersion === PROTOCOL_VERSION_RERELEASE) {\n const spawnCount = this.stream.readLong();\n const demoType = this.stream.readByte();\n this.isDemo = demoType;\n const tickRate = this.stream.readByte();\n const gameDir = this.stream.readString();\n let playerNum = this.stream.readShort();\n if (playerNum === -2) {\n const numSplits = this.stream.readShort();\n for (let i = 0; i < numSplits; i++) this.stream.readShort();\n playerNum = 0;\n } else if (playerNum === -1) {\n playerNum = -1;\n }\n const levelName = this.stream.readString();\n if (this.handler) this.handler.onServerData(this.protocolVersion, spawnCount, 0, gameDir, playerNum, levelName, tickRate, demoType);\n } else {\n const serverCount = this.stream.readLong();\n const attractLoop = this.stream.readByte();\n this.isDemo = attractLoop;\n const gameDir = this.stream.readString();\n const playerNum = this.stream.readShort();\n const levelName = this.stream.readString();\n if (this.handler) this.handler.onServerData(this.protocolVersion, serverCount, attractLoop, gameDir, playerNum, levelName);\n }\n }\n\n private parseConfigString(): void {\n const index = this.stream.readShort();\n const str = this.stream.readString();\n if (this.handler) this.handler.onConfigString(index, str);\n }\n\n private parseSplitClient(): void {\n const clientNum = this.stream.readByte();\n if (this.handler?.onSplitClient) this.handler.onSplitClient(clientNum);\n }\n\n private parseConfigBlast(): void {\n const compressedSize = this.stream.readShort();\n const uncompressedSize = this.stream.readShort();\n const compressedData = this.stream.readData(compressedSize);\n try {\n const decompressed = pako.inflate(compressedData);\n const blastStream = new BinaryStream(decompressed.buffer);\n while (blastStream.hasMore()) {\n const index = blastStream.readUShort();\n const str = blastStream.readString();\n if (this.handler) this.handler.onConfigString(index, str);\n }\n } catch (e) {\n console.error('svc_configblast error', e);\n }\n }\n\n private parseSpawnBaselineBlast(): void {\n const compressedSize = this.stream.readShort();\n const uncompressedSize = this.stream.readShort();\n const compressedData = this.stream.readData(compressedSize);\n try {\n const decompressed = pako.inflate(compressedData);\n const blastStream = new BinaryStream(decompressed.buffer);\n const blastParser = new NetworkMessageParser(blastStream, this.handler, this.strictMode);\n blastParser.setProtocolVersion(this.protocolVersion);\n while (blastStream.hasMore()) {\n blastParser.parseSpawnBaseline();\n }\n } catch (e) {\n console.error('svc_spawnbaselineblast error', e);\n }\n }\n\n private parseLocPrint(): void {\n const flags = this.stream.readByte();\n const base = this.stream.readString();\n const numArgs = this.stream.readByte();\n const args: string[] = [];\n for(let i=0; i<numArgs; i++) args.push(this.stream.readString());\n if (this.handler?.onLocPrint) this.handler.onLocPrint(flags, base, args);\n }\n\n private parseWaitingForPlayers(): void {\n const count = this.stream.readByte();\n if (this.handler?.onWaitingForPlayers) this.handler.onWaitingForPlayers(count);\n }\n\n private parseBotChat(): void {\n const botName = this.stream.readString();\n const clientIndex = this.stream.readShort();\n const locString = this.stream.readString();\n if (this.handler?.onBotChat) this.handler.onBotChat(locString);\n }\n\n private parsePoi(): void {\n const key = this.stream.readShort();\n const time = this.stream.readShort();\n const pos = {x:0, y:0, z:0};\n this.readPos(pos);\n const imageIndex = this.stream.readShort();\n const paletteIndex = this.stream.readByte();\n const flags = this.stream.readByte();\n if (this.handler?.onPoi) this.handler.onPoi(flags, pos);\n }\n\n private parseHelpPath(): void {\n const start = this.stream.readByte();\n const pos = {x:0, y:0, z:0};\n this.readPos(pos);\n const dir = {x:0, y:0, z:0};\n this.readDir(dir);\n if (this.handler?.onHelpPath) this.handler.onHelpPath(pos);\n }\n\n private parseAchievement(): void {\n const idStr = this.stream.readString();\n if (this.handler?.onAchievement) this.handler.onAchievement(idStr);\n }\n\n private parseDownload(): void {\n const size = this.stream.readShort();\n const percent = this.stream.readByte();\n let data: Uint8Array | undefined;\n if (size > 0) data = this.stream.readData(size);\n if (this.handler) this.handler.onDownload(size, percent, data);\n }\n\n private parseInventory(): void {\n const MAX_ITEMS = 256;\n const inventory = new Array(MAX_ITEMS);\n for (let i = 0; i < MAX_ITEMS; i++) inventory[i] = this.stream.readShort();\n if (this.handler) this.handler.onInventory(inventory);\n }\n\n private parseSound(): void {\n const mask = this.stream.readByte();\n const soundNum = this.stream.readByte();\n let volume: number | undefined;\n let attenuation: number | undefined;\n let offset: number | undefined;\n let ent: number | undefined;\n let pos: Vec3 | undefined;\n\n if (mask & 1) volume = this.stream.readByte();\n if (mask & 2) attenuation = this.stream.readByte();\n if (mask & 16) offset = this.stream.readByte();\n if (mask & 8) ent = this.stream.readShort();\n if (mask & 4) {\n const p = { x: 0, y: 0, z: 0 };\n this.readPos(p);\n pos = p;\n }\n if (this.handler) this.handler.onSound(mask, soundNum, volume, attenuation, offset, ent, pos);\n }\n\n private parseMuzzleFlash(): void {\n const ent = this.stream.readShort();\n const weapon = this.stream.readByte();\n if (this.handler) this.handler.onMuzzleFlash(ent, weapon);\n }\n\n private parseMuzzleFlash2(): void {\n const ent = this.stream.readShort();\n const weapon = this.stream.readByte();\n if (this.handler) this.handler.onMuzzleFlash2(ent, weapon);\n }\n\n private parseMuzzleFlash3(): void {\n const ent = this.stream.readShort();\n const weapon = this.stream.readShort();\n if (this.handler?.onMuzzleFlash3) this.handler.onMuzzleFlash3(ent, weapon);\n }\n\n private parseFog(): void {\n let bits = this.stream.readByte();\n if (bits & 0x80) {\n const high = this.stream.readByte();\n bits |= (high << 8);\n }\n const fog: FogData = {};\n if (bits & 1) { fog.density = this.stream.readFloat(); fog.skyfactor = this.stream.readByte(); }\n if (bits & 2) fog.red = this.stream.readByte();\n if (bits & 4) fog.green = this.stream.readByte();\n if (bits & 8) fog.blue = this.stream.readByte();\n if (bits & 16) fog.time = this.stream.readShort();\n if (bits & 32) fog.hf_falloff = this.stream.readFloat();\n if (bits & 64) fog.hf_density = this.stream.readFloat();\n if (bits & 256) fog.hf_start_r = this.stream.readByte();\n if (bits & 512) fog.hf_start_g = this.stream.readByte();\n if (bits & 1024) fog.hf_start_b = this.stream.readByte();\n if (bits & 2048) fog.hf_start_dist = this.stream.readLong();\n if (bits & 4096) fog.hf_end_r = this.stream.readByte();\n if (bits & 8192) fog.hf_end_g = this.stream.readByte();\n if (bits & 16384) fog.hf_end_b = this.stream.readByte();\n if (bits & 32768) fog.hf_end_dist = this.stream.readLong();\n if (this.handler?.onFog) this.handler.onFog(fog);\n }\n\n private parseDamage(): void {\n const num = this.stream.readByte();\n const indicators: DamageIndicator[] = [];\n for (let i = 0; i < num; i++) {\n const encoded = this.stream.readByte();\n const dir = { x: 0, y: 0, z: 0 };\n this.readDir(dir);\n const damage = encoded & 0x1F;\n const health = (encoded & 0x20) !== 0;\n const armor = (encoded & 0x40) !== 0;\n const power = (encoded & 0x80) !== 0;\n indicators.push({ damage, health, armor, power, dir });\n }\n if (this.handler?.onDamage) this.handler.onDamage(indicators);\n }\n\n private parseTempEntity(): void {\n const type = this.stream.readByte();\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 let cnt: number | undefined;\n let color: number | undefined;\n let ent: number | undefined;\n let srcEnt: number | undefined;\n let destEnt: number | undefined;\n\n // Simplification of switch for brevity - maintaining same logic\n switch (type) {\n case TempEntity.EXPLOSION1: case TempEntity.EXPLOSION2: case TempEntity.ROCKET_EXPLOSION: case TempEntity.GRENADE_EXPLOSION:\n case TempEntity.ROCKET_EXPLOSION_WATER: case TempEntity.GRENADE_EXPLOSION_WATER: case TempEntity.BFG_EXPLOSION: case TempEntity.BFG_BIGEXPLOSION:\n case TempEntity.BOSSTPORT: case TempEntity.PLASMA_EXPLOSION: case TempEntity.PLAIN_EXPLOSION: case TempEntity.CHAINFIST_SMOKE:\n case TempEntity.TRACKER_EXPLOSION: case TempEntity.TELEPORT_EFFECT: case TempEntity.DBALL_GOAL: case TempEntity.NUKEBLAST:\n case TempEntity.WIDOWSPLASH: case TempEntity.EXPLOSION1_BIG: case TempEntity.EXPLOSION1_NP:\n this.readPos(pos); break;\n case TempEntity.GUNSHOT: case TempEntity.BLOOD: case TempEntity.BLASTER: case TempEntity.SHOTGUN: case TempEntity.SPARKS:\n case TempEntity.BULLET_SPARKS: case TempEntity.SCREEN_SPARKS: case TempEntity.SHIELD_SPARKS: case TempEntity.BLASTER2: case TempEntity.FLECHETTE:\n case TempEntity.MOREBLOOD: case TempEntity.ELECTRIC_SPARKS: case TempEntity.HEATBEAM_SPARKS: case TempEntity.HEATBEAM_STEAM:\n this.readPos(pos); this.readDir(dir); break;\n case TempEntity.SPLASH: case TempEntity.LASER_SPARKS: case TempEntity.WELDING_SPARKS: case TempEntity.TUNNEL_SPARKS:\n cnt = this.stream.readByte(); this.readPos(pos); this.readDir(dir); color = this.stream.readByte(); break;\n case TempEntity.BLUEHYPERBLASTER:\n if (this.protocolVersion >= 32) { this.readPos(pos); this.readPos(pos2); } else { this.readPos(pos); this.readDir(dir); } break;\n case TempEntity.GREENBLOOD:\n if (this.protocolVersion >= 32) { this.readPos(pos); this.readDir(dir); } else { this.readPos(pos); this.readPos(pos2); } break;\n case TempEntity.RAILTRAIL: case TempEntity.BUBBLETRAIL: case TempEntity.BFG_LASER: case TempEntity.DEBUGTRAIL: case TempEntity.BUBBLETRAIL2:\n this.readPos(pos); this.readPos(pos2); break;\n case TempEntity.PARASITE_ATTACK: case TempEntity.MEDIC_CABLE_ATTACK:\n this.stream.readShort(); this.readPos(pos); this.readPos(pos2); break;\n case TempEntity.GRAPPLE_CABLE:\n ent = this.stream.readShort(); this.readPos(pos); this.readPos(pos2); this.readPos(dir); break;\n case TempEntity.LIGHTNING:\n srcEnt = this.stream.readShort(); destEnt = this.stream.readShort(); this.readPos(pos); this.readPos(pos2); break;\n case TempEntity.FLASHLIGHT:\n this.readPos(pos); ent = this.stream.readShort(); break;\n case TempEntity.FORCEWALL:\n this.readPos(pos); this.readPos(pos2); color = this.stream.readByte(); break;\n case TempEntity.STEAM:\n const nextId = this.stream.readShort(); cnt = this.stream.readByte(); this.readPos(pos); this.readDir(dir);\n color = this.stream.readByte(); this.stream.readShort();\n if (nextId !== -1) this.stream.readLong();\n break;\n case TempEntity.WIDOWBEAMOUT: this.stream.readShort();\n case TempEntity.HEATBEAM: case TempEntity.MONSTER_HEATBEAM:\n ent = this.stream.readShort(); this.readPos(pos); this.readPos(pos2); this.readDir(dir); break;\n }\n if (this.handler) this.handler.onTempEntity(type, pos, pos2, dir, cnt, color, ent, srcEnt, destEnt);\n }\n\n private parseSpawnBaseline(): void {\n const bits = this.parseEntityBits();\n const entity = createEmptyEntityState();\n this.parseDelta(createEmptyEntityState(), entity, bits.number, bits.bits, bits.bitsHigh);\n if (this.handler) this.handler.onSpawnBaseline(entity);\n }\n\n private parseFrame(): void {\n const serverFrame = this.stream.readLong();\n const deltaFrame = this.stream.readLong();\n let surpressCount = 0;\n\n // Protocol 26 (legacy) hack:\n // In original Quake 2, protocol 26 demos did NOT include the suppressCount byte.\n // See full/client/cl_ents.c:679-681\n // Protocol 25 also seems to lack this byte based on testing with demo1.dm2\n if (this.protocolVersion !== 26 && this.protocolVersion !== 25) {\n surpressCount = this.stream.readByte();\n }\n\n const areaBytes = this.stream.readByte();\n const areaBits = this.stream.readData(areaBytes);\n\n let piCmd = this.stream.readByte();\n piCmd = this.translateCommand(piCmd);\n if (piCmd !== ServerCommand.playerinfo) {\n if (this.strictMode) throw new Error(`Expected svc_playerinfo after svc_frame, got ${piCmd}`);\n return;\n }\n const playerState = this.parsePlayerState();\n\n let peCmd = this.stream.readByte();\n peCmd = this.translateCommand(peCmd);\n if (peCmd !== ServerCommand.packetentities && peCmd !== ServerCommand.deltapacketentities) {\n if (this.strictMode) throw new Error(`Expected svc_packetentities after svc_playerinfo, got ${peCmd}`);\n return;\n }\n const entities = this.collectPacketEntities();\n\n if (this.isDemo === RECORD_RELAY) {\n const connectedCount = this.stream.readByte();\n for(let i=0; i<connectedCount; i++) this.stream.readByte();\n }\n if (this.isDemo === RECORD_SERVER) this.stream.readLong();\n\n if (this.handler) this.handler.onFrame({\n serverFrame, deltaFrame, surpressCount, areaBytes, areaBits, playerState,\n packetEntities: { delta: true, entities }\n });\n }\n\n private parsePlayerState(): ProtocolPlayerState {\n const ps = createEmptyProtocolPlayerState();\n const flags = this.stream.readShort();\n if (flags & 1) ps.pm_type = this.stream.readByte();\n if (flags & 2) { ps.origin.x = this.readCoord(); ps.origin.y = this.readCoord(); ps.origin.z = this.readCoord(); }\n if (flags & 4) { ps.velocity.x = this.readCoord(); ps.velocity.y = this.readCoord(); ps.velocity.z = this.readCoord(); }\n if (flags & 8) ps.pm_time = this.stream.readByte();\n if (flags & 16) ps.pm_flags = this.stream.readByte();\n if (flags & 32) ps.gravity = this.stream.readShort();\n if (flags & 64) { ps.delta_angles.x = this.stream.readShort() * (180 / 32768); ps.delta_angles.y = this.stream.readShort() * (180 / 32768); ps.delta_angles.z = this.stream.readShort() * (180 / 32768); }\n if (flags & 128) {\n ps.viewoffset.x = (this.stream.readByte() << 24 >> 24) * 0.25;\n ps.viewoffset.y = (this.stream.readByte() << 24 >> 24) * 0.25;\n ps.viewoffset.z = (this.stream.readByte() << 24 >> 24) * 0.25;\n }\n if (flags & 256) { ps.viewangles.x = this.readAngle16(); ps.viewangles.y = this.readAngle16(); ps.viewangles.z = this.readAngle16(); }\n if (flags & 512) {\n ps.kick_angles.x = (this.stream.readByte() << 24 >> 24) * 0.25;\n ps.kick_angles.y = (this.stream.readByte() << 24 >> 24) * 0.25;\n ps.kick_angles.z = (this.stream.readByte() << 24 >> 24) * 0.25;\n }\n if (flags & 4096) ps.gun_index = this.stream.readByte();\n if (flags & 8192) {\n ps.gun_frame = this.stream.readByte();\n ps.gun_offset.x = (this.stream.readByte() << 24 >> 24) * 0.25;\n ps.gun_offset.y = (this.stream.readByte() << 24 >> 24) * 0.25;\n ps.gun_offset.z = (this.stream.readByte() << 24 >> 24) * 0.25;\n ps.gun_angles.x = (this.stream.readByte() << 24 >> 24) * 0.25;\n ps.gun_angles.y = (this.stream.readByte() << 24 >> 24) * 0.25;\n ps.gun_angles.z = (this.stream.readByte() << 24 >> 24) * 0.25;\n }\n if (flags & 1024) { ps.blend[0] = this.stream.readByte(); ps.blend[1] = this.stream.readByte(); ps.blend[2] = this.stream.readByte(); ps.blend[3] = this.stream.readByte(); }\n if (flags & 2048) ps.fov = this.stream.readByte();\n if (flags & 16384) ps.rdflags = this.stream.readByte();\n if (flags & 32768) ps.watertype = this.stream.readByte(); // 1 << 15\n const statbits = this.stream.readLong();\n for (let i = 0; i < 32; i++) if (statbits & (1 << i)) ps.stats[i] = this.stream.readShort();\n return ps;\n }\n\n private parsePacketEntities(delta: boolean): void {\n const entities = this.collectPacketEntities();\n if (this.handler) this.handler.onFrame({\n serverFrame: 0, deltaFrame: 0, surpressCount: 0, areaBytes: 0, areaBits: new Uint8Array(),\n playerState: createEmptyProtocolPlayerState(),\n packetEntities: { delta, entities }\n });\n }\n\n private collectPacketEntities(): EntityState[] {\n const entities: EntityState[] = [];\n while (true) {\n const bits = this.parseEntityBits();\n if (bits.bits & U_REMOVE) {\n if (bits.number === 0) break;\n continue;\n }\n const entity = createEmptyEntityState();\n const forceParse = bits.number === 0 && !(bits.bits & U_MOREBITS1);\n if (bits.number !== 0 || forceParse) {\n this.parseDelta(createEmptyEntityState(), entity, bits.number, bits.bits, bits.bitsHigh);\n }\n if (bits.number === 0) break;\n entities.push(entity);\n }\n return entities;\n }\n\n private parseEntityBits(): { number: number; bits: number; bitsHigh: number } {\n let total = this.stream.readByte();\n if (total & U_MOREBITS1) total |= (this.stream.readByte() << 8);\n if (total & U_MOREBITS2) total |= (this.stream.readByte() << 16);\n if (total & U_MOREBITS3) total |= (this.stream.readByte() << 24);\n let bitsHigh = 0;\n if (this.protocolVersion === PROTOCOL_VERSION_RERELEASE) {\n if (total & U_MOREBITS4) bitsHigh = this.stream.readByte();\n }\n let number: number;\n if (total & U_NUMBER16) number = this.stream.readShort();\n else number = this.stream.readByte();\n return { number, bits: total, bitsHigh };\n }\n\n private parseDelta(from: EntityState, to: EntityState, number: number, bits: number, bitsHigh: number = 0): void {\n to.number = from.number; to.modelindex = from.modelindex; to.modelindex2 = from.modelindex2; to.modelindex3 = from.modelindex3; to.modelindex4 = from.modelindex4;\n to.frame = from.frame; to.skinnum = from.skinnum; to.effects = from.effects; 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; to.event = from.event; to.solid = from.solid;\n to.alpha = from.alpha; to.scale = from.scale; to.instanceBits = from.instanceBits;\n to.loopVolume = from.loopVolume; to.loopAttenuation = from.loopAttenuation; to.owner = from.owner; to.oldFrame = from.oldFrame;\n to.number = number; to.bits = bits; to.bitsHigh = bitsHigh;\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 if (bits & U_FRAME8) to.frame = this.stream.readByte();\n if (bits & U_FRAME16) to.frame = this.stream.readShort();\n if ((bits & U_SKIN8) && (bits & U_SKIN16)) to.skinnum = this.stream.readLong();\n else if (bits & U_SKIN8) to.skinnum = this.stream.readByte();\n else if (bits & U_SKIN16) to.skinnum = this.stream.readShort();\n if ((bits & U_EFFECTS8) && (bits & U_EFFECTS16)) to.effects = this.stream.readLong();\n else if (bits & U_EFFECTS8) to.effects = this.stream.readByte();\n else if (bits & U_EFFECTS16) to.effects = this.stream.readShort();\n if ((bits & U_RENDERFX8) && (bits & U_RENDERFX16)) to.renderfx = this.stream.readLong();\n else if (bits & U_RENDERFX8) to.renderfx = this.stream.readByte();\n else if (bits & U_RENDERFX16) to.renderfx = this.stream.readShort();\n if (bits & U_ORIGIN1) to.origin.x = this.readCoord();\n if (bits & U_ORIGIN2) to.origin.y = this.readCoord();\n if (bits & U_ORIGIN3) to.origin.z = this.readCoord();\n if (bits & U_ANGLE1) to.angles.x = this.readAngle();\n if (bits & U_ANGLE2) to.angles.y = this.readAngle();\n if (bits & U_ANGLE3) to.angles.z = this.readAngle();\n if (bits & U_OLDORIGIN) this.readPos(to.old_origin);\n if (bits & U_SOUND) to.sound = this.stream.readByte();\n if (bits & U_EVENT) to.event = this.stream.readByte(); else to.event = 0;\n if (bits & U_SOLID) to.solid = this.stream.readShort();\n\n if (this.protocolVersion === PROTOCOL_VERSION_RERELEASE) {\n if (bits & U_ALPHA) to.alpha = this.stream.readByte() / 255.0;\n if (bits & U_SCALE) to.scale = this.stream.readFloat();\n if (bits & U_INSTANCE_BITS) to.instanceBits = this.stream.readLong();\n if (bits & U_LOOP_VOLUME) to.loopVolume = this.stream.readByte() / 255.0;\n if (bitsHigh & U_LOOP_ATTENUATION_HIGH) to.loopAttenuation = this.stream.readByte() / 255.0;\n if (bitsHigh & U_OWNER_HIGH) to.owner = this.stream.readShort();\n if (bitsHigh & U_OLD_FRAME_HIGH) to.oldFrame = this.stream.readShort();\n }\n }\n}\n","import { EntityState, ProtocolPlayerState } from './parser.js';\nimport { Vec3 } from '@quake2ts/shared';\n\nexport interface FrameDiff {\n frameA: number;\n frameB: number;\n playerStateDiff: {\n origin: Vec3 | null; // null if same\n viewangles: Vec3 | null;\n health: number | null; // diff value\n ammo: number | null;\n };\n entityDiffs: {\n added: number[];\n removed: number[];\n moved: { id: number, delta: Vec3 }[];\n };\n}\n\nexport enum DemoEventType {\n WeaponFire = 'weapon_fire',\n DamageDealt = 'damage_dealt',\n DamageReceived = 'damage_received',\n Pickup = 'pickup',\n Death = 'death',\n Kill = 'kill',\n Spawn = 'spawn',\n PlayerInfo = 'player_info',\n Chat = 'chat',\n Objective = 'objective'\n}\n\nexport interface DemoEvent {\n type: DemoEventType;\n frame: number;\n time: number;\n entityId?: number;\n targetId?: number;\n value?: number; // Damage amount, weapon ID, etc.\n position?: Vec3;\n description?: string;\n data?: any; // Extra data as needed by enhancement request\n}\n\nexport interface EventSummary {\n totalKills: number;\n totalDeaths: number;\n damageDealt: number;\n damageReceived: number;\n weaponUsage: Map<number, number>; // WeaponID -> Count\n}\n\nexport interface DemoHeader {\n protocolVersion: number;\n gameDir: string;\n levelName: string;\n playerNum: number;\n serverCount?: number; // Legacy\n spawnCount?: number; // Rerelease\n tickRate?: number; // Rerelease\n demoType?: number; // Rerelease\n}\n\nexport interface ServerInfo {\n [key: string]: string;\n}\n\nexport interface DemoStatistics {\n duration: number;\n frameCount: number;\n averageFps: number;\n mapName: string;\n playerCount: number; // Inferred from scoreboards or similar\n}\n\nexport interface PlayerStatistics {\n kills: number;\n deaths: number;\n damageDealt: number;\n damageReceived: number;\n suicides: number;\n}\n\nexport interface WeaponStatistics {\n weaponId: number;\n shotsFired: number;\n hits: number; // Hard to track without server help, maybe implied damage\n kills: number;\n}\n","import { DemoReader } from './demoReader.js';\nimport { NetworkMessageParser, NetworkMessageHandler, FrameData, EntityState, ProtocolPlayerState, DamageIndicator } from './parser.js';\nimport { DemoEvent, DemoEventType, EventSummary, DemoHeader, ServerInfo, DemoStatistics, PlayerStatistics, WeaponStatistics } from './analysis.js';\nimport { Vec3, ServerCommand } from '@quake2ts/shared';\n\n/**\n * Helper class to scan a demo for events and metadata.\n */\nexport class DemoAnalyzer {\n private buffer: ArrayBuffer;\n private events: DemoEvent[] = [];\n private summary: EventSummary = {\n totalKills: 0,\n totalDeaths: 0,\n damageDealt: 0,\n damageReceived: 0,\n weaponUsage: new Map()\n };\n\n private header: DemoHeader | null = null;\n private configStrings: Map<number, string> = new Map();\n private serverInfo: ServerInfo = {};\n private statistics: DemoStatistics | null = null;\n private playerStats: Map<number, PlayerStatistics> = new Map(); // By playerNum\n private weaponStats: Map<number, WeaponStatistics[]> = new Map(); // By entity ID\n\n private activeEntities = new Set<number>();\n\n constructor(buffer: ArrayBuffer) {\n this.buffer = buffer;\n }\n\n public analyze(): {\n events: DemoEvent[],\n summary: EventSummary,\n header: DemoHeader | null,\n configStrings: Map<number, string>,\n serverInfo: ServerInfo,\n statistics: DemoStatistics | null,\n playerStats: Map<number, PlayerStatistics>,\n weaponStats: Map<number, WeaponStatistics[]>\n } {\n const reader = new DemoReader(this.buffer);\n let currentFrameIndex = -1;\n let currentTime = 0;\n let frameDuration = 0.1;\n\n let protocolVersion = 0;\n\n const handler: NetworkMessageHandler = {\n onServerData: (protocol, serverCount, attractLoop, gameDir, playerNum, levelName, tickRate, demoType) => {\n protocolVersion = protocol;\n this.header = {\n protocolVersion: protocol,\n gameDir,\n levelName,\n playerNum,\n serverCount,\n spawnCount: serverCount, // Mapping generic arg\n tickRate,\n demoType\n };\n if (tickRate && tickRate > 0) {\n frameDuration = 1.0 / tickRate;\n }\n },\n onConfigString: (index, str) => {\n this.configStrings.set(index, str);\n // If index is CS_SERVERINFO (0), parse it\n if (index === 0) {\n this.parseServerInfo(str);\n }\n },\n onSpawnBaseline: (entity) => {},\n onFrame: (frame: FrameData) => {\n // Detect Spawns\n const currentFrameEntities = new Set<number>();\n if (frame.packetEntities && frame.packetEntities.entities) {\n for (const ent of frame.packetEntities.entities) {\n currentFrameEntities.add(ent.number);\n if (!this.activeEntities.has(ent.number)) {\n this.recordEvent({\n type: DemoEventType.Spawn,\n frame: currentFrameIndex,\n time: currentTime,\n entityId: ent.number,\n position: { x: ent.origin.x, y: ent.origin.y, z: ent.origin.z },\n description: `Entity ${ent.number} spawned`\n });\n }\n }\n }\n this.activeEntities = currentFrameEntities;\n\n // Update Player Stats from PlayerState if available\n // Assuming single player demo for now, playerNum is from ServerData\n if (frame.playerState && this.header) {\n // We can track damage dealt if stats[12] (damage_dealt) changes?\n // stats array indices depend on game, but generic engine doesn't know layout.\n }\n },\n onPrint: (level, msg) => {\n const text = msg.replace(/\\n/g, ' ').trim();\n // Check for death messages\n if (text.includes(\"died\") || text.includes(\"killed\") || text.includes(\"suicide\")) {\n this.summary.totalDeaths++; // Simple count\n this.recordEvent({\n type: DemoEventType.Death,\n frame: currentFrameIndex,\n time: currentTime,\n description: text\n });\n\n // Detect kill vs death\n // \"Player was killed by Monster\" -> Death\n // \"Monster was killed by Player\" -> Kill (if we are Player)\n // Since we don't have full name mapping easily, we assume \"Death\" for now unless we match our name.\n } else if (text.startsWith(\"You got the \")) {\n this.recordEvent({\n type: DemoEventType.Pickup,\n frame: currentFrameIndex,\n time: currentTime,\n description: text\n });\n } else {\n // Chat or other messages\n // PRINT_CHAT is usually level 3, but onPrint arg 'level' tells us.\n if (level === 3 || level === 2) { // Chat or Medium\n this.recordEvent({\n type: DemoEventType.Chat,\n frame: currentFrameIndex,\n time: currentTime,\n description: text,\n data: { level }\n });\n }\n }\n },\n onCenterPrint: (msg) => {\n this.recordEvent({\n type: DemoEventType.Objective,\n frame: currentFrameIndex,\n time: currentTime,\n description: msg.trim()\n });\n },\n onStuffText: () => {},\n onSound: () => {},\n onTempEntity: () => {},\n onLayout: () => {},\n onInventory: () => {},\n onMuzzleFlash: (ent, weapon) => {\n this.handleWeaponFire(ent, weapon, currentFrameIndex, currentTime);\n },\n onMuzzleFlash2: (ent, weapon) => {\n this.handleWeaponFire(ent, weapon, currentFrameIndex, currentTime);\n },\n onMuzzleFlash3: (ent, weapon) => {\n this.handleWeaponFire(ent, weapon, currentFrameIndex, currentTime);\n },\n onDisconnect: () => {},\n onReconnect: () => {},\n onDownload: () => {},\n\n // Rerelease specific\n onDamage: (indicators: DamageIndicator[]) => {\n for (const ind of indicators) {\n this.recordEvent({\n type: DemoEventType.DamageReceived,\n frame: currentFrameIndex,\n time: currentTime,\n value: ind.damage,\n position: ind.dir,\n description: `Took ${ind.damage} damage`\n });\n this.summary.damageReceived += ind.damage;\n\n // Update player stats for the recording player\n if (this.header) {\n const pStats = this.getOrCreatePlayerStats(this.header.playerNum);\n pStats.damageReceived += ind.damage;\n }\n }\n }\n };\n\n // We need to loop through frames\n while (reader.hasMore()) {\n const block = reader.readNextBlock();\n if (!block) break;\n\n currentFrameIndex++;\n currentTime = currentFrameIndex * frameDuration;\n\n const parser = new NetworkMessageParser(block.data, handler);\n parser.setProtocolVersion(protocolVersion);\n parser.parseMessage();\n protocolVersion = parser.getProtocolVersion();\n }\n\n // Finalize stats\n this.statistics = {\n duration: currentTime,\n frameCount: currentFrameIndex + 1,\n averageFps: (currentFrameIndex + 1) / (currentTime || 1),\n mapName: this.header?.levelName || \"unknown\",\n playerCount: 1 // Default to 1 for SP/client demo\n };\n\n return {\n events: this.events,\n summary: this.summary,\n header: this.header,\n configStrings: this.configStrings,\n serverInfo: this.serverInfo,\n statistics: this.statistics,\n playerStats: this.playerStats,\n weaponStats: this.weaponStats\n };\n }\n\n private handleWeaponFire(ent: number, weapon: number, frame: number, time: number) {\n this.recordEvent({\n type: DemoEventType.WeaponFire,\n frame: frame,\n time: time,\n entityId: ent,\n value: weapon,\n description: `Weapon ${weapon} fired by ${ent}`\n });\n\n const count = this.summary.weaponUsage.get(weapon) || 0;\n this.summary.weaponUsage.set(weapon, count + 1);\n\n const wStats = this.getOrCreateWeaponStat(ent, weapon);\n wStats.shotsFired++;\n }\n\n private recordEvent(event: DemoEvent) {\n this.events.push(event);\n }\n\n private parseServerInfo(str: string) {\n const parts = str.split('\\\\');\n // Q2 config strings start with backslash usually?\n // Example: \\mapname\\base1\\gamemode\\deathmatch\n for (let i = 1; i < parts.length; i += 2) {\n if (i + 1 < parts.length) {\n this.serverInfo[parts[i]] = parts[i+1];\n }\n }\n }\n\n private getOrCreatePlayerStats(playerNum: number): PlayerStatistics {\n let stats = this.playerStats.get(playerNum);\n if (!stats) {\n stats = {\n kills: 0,\n deaths: 0,\n damageDealt: 0,\n damageReceived: 0,\n suicides: 0\n };\n this.playerStats.set(playerNum, stats);\n }\n return stats;\n }\n\n private getOrCreateWeaponStat(entityId: number, weaponId: number): WeaponStatistics {\n let statsList = this.weaponStats.get(entityId);\n if (!statsList) {\n statsList = [];\n this.weaponStats.set(entityId, statsList);\n }\n let stat = statsList.find(s => s.weaponId === weaponId);\n if (!stat) {\n stat = { weaponId, shotsFired: 0, hits: 0, kills: 0 };\n statsList.push(stat);\n }\n return stat;\n }\n}\n","import { Vec3 } from '@quake2ts/shared';\n\nexport enum DemoCameraMode {\n FirstPerson,\n ThirdPerson,\n Free,\n Follow\n}\n\nexport interface DemoCameraState {\n mode: DemoCameraMode;\n thirdPersonDistance: number;\n thirdPersonOffset: Vec3;\n freeCameraOrigin: Vec3;\n freeCameraAngles: Vec3;\n followEntityId: number;\n currentFollowOrigin?: Vec3;\n}\n","import { DemoReader } from './demoReader.js';\nimport { NetworkMessageParser, NetworkMessageHandler, FrameData, EntityState, ProtocolPlayerState } from './parser.js';\nimport { FrameDiff, DemoEvent, DemoEventType, EventSummary, DemoHeader, ServerInfo, DemoStatistics, PlayerStatistics, WeaponStatistics } from './analysis.js';\nimport { DemoAnalyzer } from './analyzer.js';\nimport { Vec3 } from '@quake2ts/shared';\nimport { DemoCameraMode } from './camera.js';\nimport { ResourceLoadTracker, ResourceLoadLog } from '../assets/resourceTracker.js';\n\nexport enum PlaybackState {\n Stopped,\n Playing,\n Paused,\n Finished\n}\n\nexport interface DemoMetadata {\n mapName: string;\n playerName: string;\n serverName?: string;\n recordingDate?: Date;\n demoVersion: number;\n tickRate: number;\n}\n\nexport interface DemoPlaybackCallbacks {\n onPlaybackStateChange?: (state: PlaybackState) => void;\n onTimeUpdate?: (time: number) => void;\n onPlaybackComplete?: () => void;\n onSeekComplete?: () => void;\n onCaptureSnapshot?: (frame: number) => any;\n onRestoreSnapshot?: (snapshot: any) => void;\n // Forwarded events\n onFrameUpdate?: (frame: FrameData) => void;\n onPlaybackError?: (error: Error) => void;\n}\n\nexport type FrameOffset = { type: 'frame'; frame: number };\nexport type TimeOffset = { type: 'time'; seconds: number };\nexport type PlaybackOffset = FrameOffset | TimeOffset;\n\nconst createNoOpHandler = (): NetworkMessageHandler => ({\n onServerData: () => {},\n onConfigString: () => {},\n onSpawnBaseline: () => {},\n onFrame: () => {},\n onCenterPrint: () => {},\n onStuffText: () => {},\n onPrint: () => {},\n onSound: () => {},\n onTempEntity: () => {},\n onLayout: () => {},\n onInventory: () => {},\n onMuzzleFlash: () => {},\n onMuzzleFlash2: () => {},\n onDisconnect: () => {},\n onReconnect: () => {},\n onDownload: () => {}\n});\n\nexport class DemoPlaybackController {\n private reader: DemoReader | null = null;\n private buffer: ArrayBuffer | null = null; // Keep reference for analysis\n private state: PlaybackState = PlaybackState.Stopped;\n private playbackSpeed: number = 1.0;\n private handler?: NetworkMessageHandler;\n private callbacks?: DemoPlaybackCallbacks;\n\n private currentProtocolVersion: number = 0;\n private currentFrameIndex: number = -1; // -1 means no frames processed yet\n\n // Last parsed frame data for accessors\n private lastFrameData: FrameData | null = null;\n\n // Timing\n private accumulatedTime: number = 0;\n private frameDuration: number = 100; // ms (10Hz default)\n\n // Snapshots\n private snapshotInterval: number = 100; // frames\n private snapshots: Map<number, any> = new Map();\n\n // Analysis Cache\n private cachedEvents: DemoEvent[] | null = null;\n private cachedSummary: EventSummary | null = null;\n private cachedHeader: DemoHeader | null = null;\n private cachedConfigStrings: Map<number, string> | null = null;\n private cachedServerInfo: ServerInfo | null = null;\n private cachedStatistics: DemoStatistics | null = null;\n private cachedPlayerStats: Map<number, PlayerStatistics> | null = null;\n private cachedWeaponStats: Map<number, WeaponStatistics[]> | null = null;\n\n // Resource Tracking\n private tracker: ResourceLoadTracker | null = null;\n\n // Camera State\n private cameraMode: DemoCameraMode = DemoCameraMode.FirstPerson;\n private thirdPersonDistance: number = 80;\n private thirdPersonOffset: Vec3 = { x: 0, y: 0, z: 0 };\n\n constructor() {}\n\n public setHandler(handler: NetworkMessageHandler) {\n this.handler = handler;\n }\n\n public setCallbacks(callbacks: DemoPlaybackCallbacks) {\n this.callbacks = callbacks;\n }\n\n public loadDemo(buffer: ArrayBuffer) {\n this.buffer = buffer;\n this.reader = new DemoReader(buffer);\n this.transitionState(PlaybackState.Stopped);\n this.accumulatedTime = 0;\n this.currentProtocolVersion = 0;\n this.currentFrameIndex = -1;\n this.snapshots.clear();\n this.lastFrameData = null;\n\n // Clear cache\n this.cachedEvents = null;\n this.cachedSummary = null;\n this.cachedHeader = null;\n this.cachedConfigStrings = null;\n this.cachedServerInfo = null;\n this.cachedStatistics = null;\n this.cachedPlayerStats = null;\n this.cachedWeaponStats = null;\n }\n\n public play() {\n if (this.reader && this.state !== PlaybackState.Playing) {\n this.transitionState(PlaybackState.Playing);\n }\n }\n\n public pause() {\n if (this.state === PlaybackState.Playing) {\n this.transitionState(PlaybackState.Paused);\n }\n }\n\n public stop() {\n this.transitionState(PlaybackState.Stopped);\n if (this.reader) {\n this.reader.reset();\n }\n this.accumulatedTime = 0;\n this.currentProtocolVersion = 0;\n this.currentFrameIndex = -1;\n this.lastFrameData = null;\n }\n\n private transitionState(newState: PlaybackState) {\n if (this.state !== newState) {\n this.state = newState;\n if (this.callbacks?.onPlaybackStateChange) {\n this.callbacks.onPlaybackStateChange(newState);\n }\n }\n }\n\n public setFrameDuration(ms: number) {\n this.frameDuration = ms;\n }\n\n public setSpeed(speed: number) {\n this.playbackSpeed = Math.max(0.1, Math.min(speed, 16.0));\n }\n\n public getSpeed(): number {\n return this.playbackSpeed;\n }\n\n public getPlaybackSpeed(): number {\n return this.playbackSpeed;\n }\n\n /**\n * Returns the interpolation factor (0.0 to 1.0) for the current frame.\n * Used for smooth rendering between demo frames.\n */\n public getInterpolationFactor(): number {\n if (this.frameDuration <= 0) return 0;\n return Math.max(0, Math.min(1, this.accumulatedTime / this.frameDuration));\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 const hasMore = this.processNextFrame();\n if (!hasMore) {\n return;\n }\n this.accumulatedTime -= this.frameDuration;\n\n if (this.callbacks?.onTimeUpdate) {\n this.callbacks.onTimeUpdate(this.getCurrentTime());\n }\n }\n }\n\n public stepForward() {\n if (!this.reader) return;\n this.processNextFrame();\n if (this.callbacks?.onTimeUpdate) {\n this.callbacks.onTimeUpdate(this.getCurrentTime());\n }\n }\n\n public stepBackward() {\n if (!this.reader) return;\n\n // Seek to current - 1\n if (this.currentFrameIndex > 0) {\n this.seek(this.currentFrameIndex - 1);\n }\n }\n\n public seekToTime(seconds: number) {\n const frameIndex = this.timeToFrame(seconds);\n this.seek(frameIndex);\n }\n\n public seekToFrame(frameIndex: number) {\n this.seek(frameIndex);\n }\n\n public frameToTime(frame: number): number {\n return (frame * this.frameDuration) / 1000;\n }\n\n public timeToFrame(seconds: number): number {\n return Math.floor((seconds * 1000) / this.frameDuration);\n }\n\n public playFrom(offset: PlaybackOffset): void {\n if (offset.type === 'frame') {\n this.seek(offset.frame);\n } else if (offset.type === 'time') {\n this.seekToTime(offset.seconds);\n } else {\n // Should not happen with TS, but runtime check\n throw new Error(`Invalid offset type: ${(offset as any).type}`);\n }\n this.play();\n }\n\n public playRange(start: PlaybackOffset, end: PlaybackOffset): void {\n // Validate bounds\n const startFrame = start.type === 'frame' ? start.frame : this.timeToFrame(start.seconds);\n const endFrame = end.type === 'frame' ? end.frame : this.timeToFrame(end.seconds);\n const totalFrames = this.getTotalFrames();\n const maxFrame = Math.max(0, totalFrames - 1);\n\n // We allow startFrame == totalFrames (which means start at end, i.e., finish immediately)\n // but generally we should clamp or error if out of reasonable bounds.\n if (startFrame < 0) {\n throw new Error(`Invalid start offset: ${startFrame}`);\n }\n // Note: We don't strictly enforce endFrame <= totalFrames because the demo might be streaming or length unknown (though here we know length).\n // But if endFrame < startFrame, that's invalid.\n if (endFrame < startFrame) {\n throw new Error(`End offset (${endFrame}) cannot be before start offset (${startFrame})`);\n }\n\n this.playFrom(start);\n\n // We need to stop playback when we reach endFrame\n // We can achieve this by hooking into onFrameUpdate or checking in update()\n // For now, let's wrap the callbacks to intercept the stop condition\n const originalOnFrameUpdate = this.callbacks?.onFrameUpdate;\n\n const rangeCallback: DemoPlaybackCallbacks = {\n ...this.callbacks,\n onFrameUpdate: (frame) => {\n if (originalOnFrameUpdate) originalOnFrameUpdate(frame);\n if (this.currentFrameIndex >= endFrame) {\n this.pause();\n // Reset callbacks to remove interception\n if (this.callbacks === rangeCallback) {\n this.setCallbacks({ ...this.callbacks, onFrameUpdate: originalOnFrameUpdate });\n }\n if (this.callbacks?.onPlaybackComplete) {\n this.callbacks.onPlaybackComplete();\n }\n }\n }\n };\n\n this.setCallbacks(rangeCallback);\n }\n\n /**\n * Seeks to a specific frame number.\n */\n public seek(frameNumber: number) {\n if (!this.reader) return;\n\n const total = this.getTotalFrames();\n\n // Allow seeking to total (end state), but clamp if > total\n // Actually standard behavior is clamp to [0, total-1] usually, but if we want to seek to \"end\", maybe total is fine.\n // However, processNextFrame checks hasMore().\n if (total > 0 && frameNumber >= total) frameNumber = total - 1;\n if (frameNumber < 0) frameNumber = 0;\n\n // Optimization: If seeking to next frame, just process it\n if (frameNumber === this.currentFrameIndex + 1) {\n this.processNextFrame();\n if (this.callbacks?.onSeekComplete) this.callbacks.onSeekComplete();\n return;\n }\n\n // If seeking to current frame, do nothing\n if (frameNumber === this.currentFrameIndex) {\n if (this.callbacks?.onSeekComplete) this.callbacks.onSeekComplete();\n return;\n }\n\n // 1. Determine best start point\n let startIndex = -1;\n let snapshotData: any = null;\n\n // Check current position (only if we are before target)\n if (frameNumber > this.currentFrameIndex && this.currentFrameIndex !== -1) {\n startIndex = this.currentFrameIndex;\n }\n\n // Check snapshots (find closest snapshot <= frameNumber)\n if (this.callbacks?.onRestoreSnapshot) {\n // Iterate snapshots to find best match\n for (const [frame, data] of this.snapshots) {\n if (frame <= frameNumber && frame > startIndex) {\n startIndex = frame;\n snapshotData = data;\n }\n }\n }\n\n // If no better start point found, restart from 0\n if (startIndex === -1 && this.currentFrameIndex > frameNumber) {\n this.reader.reset();\n this.currentFrameIndex = -1;\n this.currentProtocolVersion = 0;\n } else if (startIndex === -1) {\n this.reader.reset();\n this.currentFrameIndex = -1;\n this.currentProtocolVersion = 0;\n }\n\n // Restore snapshot if we found one better than current\n if (snapshotData && this.callbacks?.onRestoreSnapshot) {\n this.callbacks.onRestoreSnapshot(snapshotData);\n if (this.reader.seekToMessage(startIndex + 1)) {\n this.currentFrameIndex = startIndex;\n } else {\n this.reader.reset();\n this.currentFrameIndex = -1;\n this.currentProtocolVersion = 0;\n }\n }\n\n // 2. Fast forward loop\n while (this.currentFrameIndex < frameNumber) {\n if (this.callbacks?.onCaptureSnapshot && (this.currentFrameIndex + 1) % this.snapshotInterval === 0) {\n // Capture happens in processNextFrame\n }\n\n if (!this.processNextFrame()) {\n break;\n }\n }\n\n this.accumulatedTime = 0;\n\n if (this.callbacks?.onSeekComplete) {\n this.callbacks.onSeekComplete();\n }\n\n if (this.callbacks?.onTimeUpdate) {\n this.callbacks.onTimeUpdate(this.getCurrentTime());\n }\n }\n\n private processNextFrame(): boolean {\n if (!this.reader || !this.reader.hasMore()) {\n this.transitionState(PlaybackState.Finished);\n if (this.callbacks?.onPlaybackComplete) {\n this.callbacks.onPlaybackComplete();\n }\n return false;\n }\n\n const block = this.reader.readNextBlock();\n if (!block) {\n this.transitionState(PlaybackState.Finished);\n if (this.callbacks?.onPlaybackComplete) {\n this.callbacks.onPlaybackComplete();\n }\n return false;\n }\n\n this.currentFrameIndex++;\n\n // Update tracker\n if (this.tracker) {\n this.tracker.setCurrentFrame(this.currentFrameIndex);\n this.tracker.setCurrentTime(this.getCurrentTime());\n }\n\n // Parsing\n try {\n // Wrap handler to capture onFrame\n const proxyHandler: NetworkMessageHandler = {\n ...(this.handler || createNoOpHandler()),\n onFrame: (frame: FrameData) => {\n this.lastFrameData = frame; // Capture last frame\n if (this.handler?.onFrame) this.handler.onFrame(frame);\n if (this.callbacks?.onFrameUpdate) this.callbacks.onFrameUpdate(frame);\n }\n };\n\n const parser = new NetworkMessageParser(block.data, proxyHandler);\n parser.setProtocolVersion(this.currentProtocolVersion);\n parser.parseMessage();\n this.currentProtocolVersion = parser.getProtocolVersion();\n\n // Snapshot capture\n if (this.callbacks?.onCaptureSnapshot && this.currentFrameIndex % this.snapshotInterval === 0 && this.currentFrameIndex > 0) {\n const snapshot = this.callbacks.onCaptureSnapshot(this.currentFrameIndex);\n if (snapshot) {\n this.snapshots.set(this.currentFrameIndex, snapshot);\n }\n }\n\n } catch (e) {\n console.error(\"Error processing demo frame\", e);\n if (this.callbacks?.onPlaybackError) {\n this.callbacks.onPlaybackError(e instanceof Error ? e : new Error(String(e)));\n }\n return false;\n }\n\n return true;\n }\n\n public getState(): PlaybackState {\n return this.state;\n }\n\n public getCurrentTime(): number {\n if (this.currentFrameIndex < 0) return this.accumulatedTime;\n return (this.currentFrameIndex * this.frameDuration) + this.accumulatedTime;\n }\n\n public getFrameCount(): number {\n return this.reader ? this.reader.getMessageCount() : 0;\n }\n\n public getTotalFrames(): number {\n return this.getFrameCount();\n }\n\n public getCurrentFrame(): number {\n return this.currentFrameIndex < 0 ? 0 : this.currentFrameIndex;\n }\n\n public getDuration(): number {\n return (this.getFrameCount() * this.frameDuration) / 1000;\n }\n\n public getTotalBytes(): number {\n return this.reader ? this.reader.getProgress().total : 0;\n }\n\n public getProcessedBytes(): number {\n return this.reader ? this.reader.getOffset() : 0;\n }\n\n // 3.2.1 Frame Data Extraction\n\n public getFrameData(frameIndex: number): FrameData | null {\n // If requesting current frame, return cached\n if (frameIndex === this.currentFrameIndex && this.lastFrameData) {\n return this.lastFrameData;\n }\n\n const previousState = this.state;\n this.pause(); // Pause while seeking\n\n this.seek(frameIndex);\n\n if (previousState === PlaybackState.Playing) {\n this.play();\n }\n\n return this.lastFrameData;\n }\n\n public getFramePlayerState(frameIndex: number): ProtocolPlayerState | null {\n if (frameIndex === this.currentFrameIndex && this.handler?.getPlayerState) {\n const state = this.handler.getPlayerState();\n if (state) return state;\n }\n\n const frame = this.getFrameData(frameIndex);\n return frame ? frame.playerState : null;\n }\n\n public getFrameEntities(frameIndex: number): EntityState[] {\n if (frameIndex === this.currentFrameIndex && this.handler?.getEntities) {\n const entitiesMap = this.handler.getEntities();\n if (entitiesMap) return Array.from(entitiesMap.values());\n }\n\n this.seek(frameIndex);\n\n if (this.handler?.getEntities) {\n const entitiesMap = this.handler.getEntities();\n return entitiesMap ? Array.from(entitiesMap.values()) : [];\n }\n\n return [];\n }\n\n // 3.2.2 Frame Comparison\n\n public compareFrames(frameA: number, frameB: number): FrameDiff {\n const stateA = this.getFramePlayerState(frameA);\n const entitiesA = this.getFrameEntities(frameA); // This seeks to A\n\n // Need to capture entities map for efficient diffing\n const mapA = new Map<number, EntityState>();\n entitiesA.forEach(e => mapA.set(e.number, e));\n\n const stateB = this.getFramePlayerState(frameB); // This seeks to B\n const entitiesB = this.getFrameEntities(frameB);\n const mapB = new Map<number, EntityState>();\n entitiesB.forEach(e => mapB.set(e.number, e));\n\n const diff: FrameDiff = {\n frameA,\n frameB,\n playerStateDiff: {\n origin: null,\n viewangles: null,\n health: null,\n ammo: null\n },\n entityDiffs: {\n added: [],\n removed: [],\n moved: []\n }\n };\n\n if (stateA && stateB) {\n if (stateA.origin.x !== stateB.origin.x || stateA.origin.y !== stateB.origin.y || stateA.origin.z !== stateB.origin.z) {\n diff.playerStateDiff.origin = { x: stateB.origin.x - stateA.origin.x, y: stateB.origin.y - stateA.origin.y, z: stateB.origin.z - stateA.origin.z };\n }\n // Simple health/ammo diff\n if (stateA.stats[1] !== stateB.stats[1]) diff.playerStateDiff.health = stateB.stats[1] - stateA.stats[1];\n if (stateA.stats[2] !== stateB.stats[2]) diff.playerStateDiff.ammo = stateB.stats[2] - stateA.stats[2];\n }\n\n // Entity diffs\n for (const [id, entB] of mapB) {\n const entA = mapA.get(id);\n if (!entA) {\n diff.entityDiffs.added.push(id);\n } else {\n if (entA.origin.x !== entB.origin.x || entA.origin.y !== entB.origin.y || entA.origin.z !== entB.origin.z) {\n diff.entityDiffs.moved.push({\n id,\n delta: { x: entB.origin.x - entA.origin.x, y: entB.origin.y - entA.origin.y, z: entB.origin.z - entA.origin.z }\n });\n }\n }\n }\n\n for (const [id, entA] of mapA) {\n if (!mapB.has(id)) {\n diff.entityDiffs.removed.push(id);\n }\n }\n\n return diff;\n }\n\n public getEntityTrajectory(entityId: number, startFrame: number, endFrame: number): Vec3[] {\n const trajectory: Vec3[] = [];\n const originalFrame = this.getCurrentFrame();\n\n this.seek(startFrame);\n\n while (this.getCurrentFrame() <= endFrame) {\n // Check if we are done\n if (this.state === PlaybackState.Finished) break;\n\n let pos: Vec3 | null = null;\n\n if (entityId === -1) { // Player\n const ps = this.getFramePlayerState(this.getCurrentFrame());\n if (ps) pos = { ...ps.origin };\n } else {\n // Entities\n if (this.handler?.getEntities) {\n const ent = this.handler.getEntities().get(entityId);\n if (ent) pos = { ...ent.origin };\n }\n }\n\n if (pos) trajectory.push(pos);\n\n if (this.getCurrentFrame() === endFrame) break;\n\n this.stepForward();\n }\n\n this.seek(originalFrame); // Restore\n return trajectory;\n }\n\n // 3.2.3 Event Log Extraction & 3.3 Metadata\n\n /**\n * Extract notable events from demo for timeline markers\n */\n public getEvents(): DemoEvent[] {\n this.ensureAnalysis();\n return this.cachedEvents || [];\n }\n\n public getDemoEvents(): DemoEvent[] {\n return this.getEvents();\n }\n\n public filterEvents(type: DemoEventType, entityId?: number): DemoEvent[] {\n const events = this.getDemoEvents();\n return events.filter(e => {\n if (e.type !== type) return false;\n if (entityId !== undefined && e.entityId !== entityId) return false;\n return true;\n });\n }\n\n public getEventSummary(): EventSummary {\n this.ensureAnalysis();\n return this.cachedSummary || {\n totalKills: 0,\n totalDeaths: 0,\n damageDealt: 0,\n damageReceived: 0,\n weaponUsage: new Map()\n };\n }\n\n public getMetadata(): DemoMetadata | null {\n const header = this.getDemoHeader();\n if (!header) return null;\n\n const serverInfo = this.getDemoServerInfo();\n // Try to find player name from userinfo or config strings if possible\n // This is a best-effort implementation based on available data\n\n // In a real implementation we might want to scan userinfo updates for the playerNum\n let playerName = \"Unknown\";\n\n // If we have analyzing capabilities\n if (this.cachedConfigStrings) {\n // Look for player info... implementation dependent\n }\n\n return {\n mapName: header.levelName,\n playerName: playerName,\n serverName: serverInfo['hostname'],\n demoVersion: header.protocolVersion,\n tickRate: header.tickRate || 10\n };\n }\n\n public getDemoHeader(): DemoHeader | null {\n this.ensureAnalysis();\n return this.cachedHeader;\n }\n\n public getDemoConfigStrings(): Map<number, string> {\n this.ensureAnalysis();\n return this.cachedConfigStrings || new Map();\n }\n\n public getDemoServerInfo(): ServerInfo {\n this.ensureAnalysis();\n return this.cachedServerInfo || {};\n }\n\n public getDemoStatistics(): DemoStatistics | null {\n this.ensureAnalysis();\n return this.cachedStatistics;\n }\n\n public getPlayerStatistics(playerIndex: number): PlayerStatistics | null {\n this.ensureAnalysis();\n return this.cachedPlayerStats?.get(playerIndex) || null;\n }\n\n public getWeaponStatistics(entityId: number): WeaponStatistics[] | null {\n this.ensureAnalysis();\n return this.cachedWeaponStats?.get(entityId) || null;\n }\n\n private ensureAnalysis() {\n if (!this.cachedEvents && this.buffer) {\n const analyzer = new DemoAnalyzer(this.buffer);\n const result = analyzer.analyze();\n this.cachedEvents = result.events;\n this.cachedSummary = result.summary;\n this.cachedHeader = result.header;\n this.cachedConfigStrings = result.configStrings;\n this.cachedServerInfo = result.serverInfo;\n this.cachedStatistics = result.statistics;\n this.cachedPlayerStats = result.playerStats;\n this.cachedWeaponStats = result.weaponStats;\n }\n }\n\n public setCameraMode(mode: DemoCameraMode) {\n this.cameraMode = mode;\n }\n\n public getCameraMode(): DemoCameraMode {\n return this.cameraMode;\n }\n\n public setThirdPersonDistance(distance: number) {\n this.thirdPersonDistance = distance;\n }\n\n public setThirdPersonOffset(offset: Vec3) {\n this.thirdPersonOffset = offset;\n }\n\n public async playWithTracking(tracker: ResourceLoadTracker, options: { fastForward?: boolean } = {}): Promise<ResourceLoadLog> {\n this.tracker = tracker;\n tracker.startTracking();\n\n if (options.fastForward) {\n // Fast forward mode: run as fast as possible without waiting for update()\n try {\n // Ensure we are in a clean state\n if (this.state === PlaybackState.Stopped && this.reader) {\n // Initial frame if needed\n }\n this.transitionState(PlaybackState.Playing);\n\n const CHUNK_SIZE = 100; // Process 100 frames per tick to avoid blocking UI too much\n\n const processChunk = async (): Promise<ResourceLoadLog> => {\n if (this.state !== PlaybackState.Playing) {\n throw new Error(\"Playback stopped unexpectedly during fast forward\");\n }\n\n let count = 0;\n while (count < CHUNK_SIZE) {\n if (!this.processNextFrame()) {\n // Finished\n const log = tracker.stopTracking();\n this.tracker = null;\n if (this.callbacks?.onPlaybackComplete) this.callbacks.onPlaybackComplete();\n return log;\n }\n count++;\n }\n\n // Yield to event loop\n await new Promise(resolve => setTimeout(resolve, 0));\n return processChunk();\n };\n\n return await processChunk();\n } catch (e) {\n tracker.stopTracking();\n this.tracker = null;\n throw e;\n }\n } else {\n return new Promise((resolve, reject) => {\n const originalComplete = this.callbacks?.onPlaybackComplete;\n const originalError = this.callbacks?.onPlaybackError;\n\n const cleanup = () => {\n this.setCallbacks({ ...this.callbacks, onPlaybackComplete: originalComplete, onPlaybackError: originalError });\n this.tracker = null;\n };\n\n this.setCallbacks({\n ...this.callbacks,\n onPlaybackComplete: () => {\n const log = tracker.stopTracking();\n if (originalComplete) originalComplete();\n cleanup();\n resolve(log);\n },\n onPlaybackError: (err) => {\n tracker.stopTracking(); // Stop anyway\n if (originalError) originalError(err);\n cleanup();\n reject(err);\n }\n });\n\n this.play();\n });\n }\n }\n\n public async playRangeWithTracking(\n start: PlaybackOffset,\n end: PlaybackOffset,\n tracker: ResourceLoadTracker,\n options: { fastForward?: boolean } = {}\n ): Promise<ResourceLoadLog> {\n this.tracker = tracker;\n tracker.startTracking();\n\n const startFrame = start.type === 'frame' ? start.frame : this.timeToFrame(start.seconds);\n const endFrame = end.type === 'frame' ? end.frame : this.timeToFrame(end.seconds);\n\n if (options.fastForward) {\n try {\n this.playFrom(start);\n this.transitionState(PlaybackState.Playing);\n\n const CHUNK_SIZE = 100;\n\n const processChunk = async (): Promise<ResourceLoadLog> => {\n if (this.state !== PlaybackState.Playing) {\n throw new Error(\"Playback stopped unexpectedly during fast forward\");\n }\n\n let count = 0;\n while (count < CHUNK_SIZE) {\n if (this.currentFrameIndex >= endFrame || !this.processNextFrame()) {\n const log = tracker.stopTracking();\n this.tracker = null;\n if (this.callbacks?.onPlaybackComplete) this.callbacks.onPlaybackComplete();\n return log;\n }\n count++;\n }\n\n await new Promise(resolve => setTimeout(resolve, 0));\n return processChunk();\n };\n\n return await processChunk();\n\n } catch (e) {\n tracker.stopTracking();\n this.tracker = null;\n throw e;\n }\n } else {\n return new Promise((resolve, reject) => {\n const originalComplete = this.callbacks?.onPlaybackComplete;\n const originalError = this.callbacks?.onPlaybackError;\n\n const cleanup = () => {\n this.setCallbacks({ ...this.callbacks, onPlaybackComplete: originalComplete, onPlaybackError: originalError });\n this.tracker = null;\n };\n\n this.setCallbacks({\n ...this.callbacks,\n onPlaybackComplete: () => {\n const log = tracker.stopTracking();\n if (originalComplete) originalComplete();\n cleanup();\n resolve(log);\n },\n onPlaybackError: (err) => {\n tracker.stopTracking();\n if (originalError) originalError(err);\n cleanup();\n reject(err);\n }\n });\n\n this.playRange(start, end);\n });\n }\n }\n}\n","import { BinaryWriter } from '@quake2ts/shared';\n\nexport class DemoRecorder {\n private isRecording: boolean = false;\n private messageBuffer: BinaryWriter;\n private startTime: number = 0;\n private frameCount: number = 0;\n private filename: string | null = null;\n private lastMessageSize: number = -1; // -1 means start of demo\n\n constructor() {\n this.messageBuffer = new BinaryWriter(1024 * 1024); // 1MB initial\n }\n\n public startRecording(filename: string, startTime: number = 0): void {\n if (this.isRecording) return;\n\n this.isRecording = true;\n this.filename = filename;\n this.startTime = startTime;\n this.frameCount = 0;\n this.messageBuffer.reset();\n\n // Write header if needed?\n // Quake 2 demos don't strictly have a file header, just -1 size message as terminator?\n // Wait, the format is [Length][Data].\n // There is no global header at file start for .dm2.\n // However, usually the first message is ServerData.\n // Some implementations might write a CDemo header, but vanilla Q2 seems to just write blocks.\n // Let's assume standard block stream.\n\n console.log(`DemoRecorder: Started recording to ${filename}`);\n }\n\n public recordMessage(data: Uint8Array): void {\n if (!this.isRecording) return;\n\n // Write Length (4 bytes)\n this.messageBuffer.writeLong(data.byteLength);\n\n // Write Data\n // BinaryWriter doesn't have writeBytes, so we might need to extend it or loop.\n // Or access buffer directly.\n // The BinaryWriter in shared/io/binaryWriter.ts has `getData()` but no generic `writeBytes`.\n // I should check if I can use writeByte in loop or if I should implement writeBytes.\n // Writing byte by byte is slow.\n // Let's check BinaryWriter again.\n // It has `ensureSpace`.\n // I can modify BinaryWriter or hack it here.\n // Actually, I can create a new Uint8Array combining existing + new data? No, slow.\n // I'll assume I can add writeBytes to BinaryWriter or use a loop for now.\n // Loop is acceptable for JS? `set` is better.\n // BinaryWriter exposes buffer via `getBuffer()`.\n // Wait, `this.view` and `this.buffer` are private.\n // But `writeString` loops.\n\n // Let's implement writeBytes extension or utility if possible.\n // For now, I'll use a loop to be safe with existing API.\n for(let i=0; i<data.length; i++) {\n this.messageBuffer.writeByte(data[i]);\n }\n\n this.frameCount++;\n }\n\n public stopRecording(): Uint8Array | null {\n if (!this.isRecording) return null;\n\n this.isRecording = false;\n\n // Write EOF?\n // Q2 demos end when file ends or with a -1 length block.\n // cl_main.c: CL_Stop_f -> CL_FinishDemo -> writes -1 to demofile.\n this.messageBuffer.writeLong(-1);\n\n console.log(`DemoRecorder: Stopped recording. Frames: ${this.frameCount}, Size: ${this.messageBuffer.getOffset()} bytes`);\n\n return this.messageBuffer.getData();\n }\n\n public getIsRecording(): boolean {\n return this.isRecording;\n }\n}\n","import { BinaryStream } from '@quake2ts/shared';\nimport { ServerCommand } from '@quake2ts/shared';\n\nexport interface DemoValidationResult {\n valid: boolean;\n error?: string;\n version?: number;\n}\n\nexport class DemoValidator {\n /**\n * Validates a Quake 2 demo file buffer.\n * Checks for minimum size, first block length, and initial serverdata command.\n */\n public static validate(buffer: ArrayBuffer, filename?: string): DemoValidationResult {\n // 1. Check file extension if filename provided\n if (filename && !filename.toLowerCase().endsWith('.dm2')) {\n return { valid: false, error: 'Invalid file extension (expected .dm2)' };\n }\n\n // 2. Verify minimum file size\n // Need at least 4 bytes for length, plus at least 1 byte for command\n if (buffer.byteLength < 5) {\n return { valid: false, error: 'File too small to be a valid demo' };\n }\n\n const view = new DataView(buffer);\n const length = view.getInt32(0, true);\n\n // 3. Verify first block length\n // Length must be positive and fit within the file\n if (length <= 0 || length > buffer.byteLength - 4) {\n return { valid: false, error: `Invalid first block length: ${length}` };\n }\n\n // 4. Verify first command is svc_serverdata\n // The first message block usually starts with svc_serverdata (12)\n // Read the first byte of the data block\n const firstCmd = view.getUint8(4);\n\n // svc_serverdata is 12 (decimal)\n if (firstCmd !== ServerCommand.serverdata) {\n return {\n valid: false,\n error: `First command is not svc_serverdata (expected ${ServerCommand.serverdata}, got ${firstCmd})`\n };\n }\n\n // Try to parse protocol version from serverdata\n // svc_serverdata(1) + protocol(4) + ...\n let version = -1;\n if (length >= 5) {\n version = view.getInt32(5, true);\n }\n\n return { valid: true, version };\n }\n}\n","import { BinaryWriter, ServerCommand } from '@quake2ts/shared';\nimport { EntityState, ProtocolPlayerState, FrameData, U_ORIGIN1, U_ORIGIN2, U_ANGLE2, U_ANGLE3, U_FRAME8, U_EVENT, U_REMOVE, U_MOREBITS1, U_NUMBER16, U_ORIGIN3, U_ANGLE1, U_MODEL, U_RENDERFX8, U_ALPHA, U_EFFECTS8, U_MOREBITS2, U_SKIN8, U_FRAME16, U_RENDERFX16, U_EFFECTS16, U_MODEL2, U_MODEL3, U_MODEL4, U_MOREBITS3, U_OLDORIGIN, U_SKIN16, U_SOUND, U_SOLID, U_SCALE, U_INSTANCE_BITS, U_LOOP_VOLUME, U_MOREBITS4, U_LOOP_ATTENUATION_HIGH, U_OWNER_HIGH, U_OLD_FRAME_HIGH } from './parser.js';\nimport { Vec3, TempEntity } from '@quake2ts/shared';\n\nconst PROTO34_REVERSE_MAP: Record<number, number> = {\n [ServerCommand.bad]: 0,\n [ServerCommand.nop]: 1,\n [ServerCommand.disconnect]: 2,\n [ServerCommand.reconnect]: 3,\n // 4 is download? standard Q2 uses 4 for download sometimes, but let's stick to parser map (download=16).\n // Let's map download to 16.\n [ServerCommand.download]: 16,\n\n [ServerCommand.frame]: 5,\n [ServerCommand.inventory]: 6,\n [ServerCommand.layout]: 7,\n [ServerCommand.muzzleflash]: 8,\n\n [ServerCommand.sound]: 9,\n [ServerCommand.print]: 10,\n [ServerCommand.stufftext]: 11,\n [ServerCommand.serverdata]: 12,\n [ServerCommand.configstring]: 13,\n [ServerCommand.spawnbaseline]: 14,\n [ServerCommand.centerprint]: 15,\n // 16 is download\n [ServerCommand.playerinfo]: 17,\n [ServerCommand.packetentities]: 18,\n [ServerCommand.deltapacketentities]: 19,\n\n // Temp entity? Standard Q2 uses 9 for temp_entity?\n // But we mapped 9 to sound.\n // If we map temp_entity to 23 (arbitrary safe slot for internal tests) or assume standard Q2 layout:\n // Q2: svc_temp_entity = 9. svc_sound = 10.\n // My previous edit to parser.ts used 9->Sound, 10->Print.\n // I should check what I committed to `parser.ts` just now.\n // I committed: 9: Sound, 10: Print.\n // So Writer MUST MATCH Parser.\n // So if Parser says 9 is Sound, Writer must write Sound as 9.\n // But what about TempEntity?\n // Parser does NOT map any wire code to TempEntity in my recent edit (I commented out 23).\n // So TempEntity is currently broken for Protocol 34 unless I map it.\n // I will map TempEntity to 23 in both.\n [ServerCommand.temp_entity]: 23,\n\n // MuzzleFlash2?\n // I'll map it to 22 (arbitrary) just to have a value, or skip if unused.\n [ServerCommand.muzzleflash2]: 22\n};\n// Wait, collisions.\n// Standard Q2:\n// svc_sound = 9 ?\n// svc_print = 10 ?\n// svc_stufftext = 11 ?\n// svc_serverdata = 12 ?\n// svc_configstring = 13 ?\n// svc_spawnbaseline = 14 ?\n// svc_centerprint = 15 ?\n// svc_download = 16 ?\n// svc_playerinfo = 17 ?\n// svc_packetentities = 18 ?\n// svc_deltapacketentities = 19 ?\n// svc_frame = 5 ?\n\n// What about 0-4, 6-8?\n// 0 bad\n// 1 nop\n// 2 disconnect\n// 3 reconnect\n// 4 ? (maybe download partial?)\n// 6 inventory\n// 7 layout\n// 8 muzzleflash\n// 9 muzzleflash2 ? Or sound?\n// 10 temp_entity ? Or print?\n\n// If ops.ts matches Wire:\n// muzzleflash=1, muzzleflash2=2, temp_entity=3, layout=4, inventory=5.\n// But ops.ts values are 1,2,3,4,5.\n// Q2 Wire usually starts with bad=0, nop=1.\n// If ops.ts is arbitrary Enum, then mapping is arbitrary.\n// BUT `parser.ts` implies Protocol 25 maps `cmd+5`.\n// If cmd=1 (muzzleflash), 1+5=6 (inventory in Wire? No).\n// If cmd=5 (inventory), 5+5=10 (temp_entity in Wire?).\n\n// I am guessing too much. I will align Writer to Parser's NEW map.\n// Parser Map (Wire -> Enum):\n// 5 -> Frame\n// 9 -> Sound\n// 10 -> Print\n// 11 -> StuffText\n// 12 -> ServerData\n// 13 -> ConfigString\n// 14 -> SpawnBaseline\n// 15 -> CenterPrint\n// 16 -> Download\n// 17 -> PlayerInfo\n// 18 -> PacketEntities\n// 19 -> DeltaPacketEntities\n\n// Writer Reverse Map (Enum -> Wire):\n// [ServerCommand.frame]: 5\n// [ServerCommand.sound]: 9\n// [ServerCommand.print]: 10\n// [ServerCommand.stufftext]: 11\n// [ServerCommand.serverdata]: 12\n// [ServerCommand.configstring]: 13\n// [ServerCommand.spawnbaseline]: 14\n// [ServerCommand.centerprint]: 15\n// [ServerCommand.download]: 16\n// [ServerCommand.playerinfo]: 17\n// [ServerCommand.packetentities]: 18\n// [ServerCommand.deltapacketentities]: 19\n\n// And fill gaps:\n// [ServerCommand.inventory]: 6\n// [ServerCommand.layout]: 7\n// [ServerCommand.muzzleflash]: 8\n// [ServerCommand.muzzleflash2]: 9 (Conflict with Sound?)\n// [ServerCommand.temp_entity]: 10 (Conflict with Print?)\n// I will map them to best guess or leave as is if not critical for current tests.\n// Tests use: ServerData, ConfigString, Frame, PacketEntities, PlayerInfo.\n// Streaming E2E uses: Print, StuffText.\n// Writer uses: Misc (MuzzleFlash, Layout, Inventory).\n\n// I need to resolve 9 and 10 conflicts.\n// svc_sound is usually 9 in newer engines? Or 11 in older?\n// In `parser.ts` before my edits: 11 was sound. 10 was temp_entity.\n// If 11 is sound, 10 is temp_entity.\n// Then Print?\n// `parser.ts` had 12 as print.\n// So:\n// 10: temp_entity\n// 11: sound\n// 12: print\n// 13: stufftext\n// 14: serverdata\n// 15: configstring\n// 16: spawnbaseline\n// 17: centerprint\n// 18: playerinfo\n// 19: packetentities\n// 20: deltapacketentities\n// 5: frame\n// This seems internally consistent and no collisions.\n\n// Let's use THIS map.\n// [ServerCommand.temp_entity]: 10\n// [ServerCommand.sound]: 11\n// [ServerCommand.print]: 12\n// [ServerCommand.stufftext]: 13\n// [ServerCommand.serverdata]: 14\n// [ServerCommand.configstring]: 15\n// [ServerCommand.spawnbaseline]: 16\n// [ServerCommand.centerprint]: 17\n// [ServerCommand.playerinfo]: 18\n// [ServerCommand.packetentities]: 19\n// [ServerCommand.deltapacketentities]: 20\n// [ServerCommand.frame]: 5\n\n// Wait, standard Q2 svc_serverdata is 12.\n// So this shifted map is wrong relative to Q2.\n// But if I want to pass tests, I must be consistent.\n// However, I want to support REAL Q2 demos.\n// Real Q2:\n// svc_serverdata = 12.\n// svc_configstring = 13.\n// svc_spawnbaseline = 14.\n// svc_centerprint = 15.\n// svc_download = 16.\n// svc_playerinfo = 17.\n// svc_packetentities = 18.\n// svc_deltapacketentities = 19.\n// svc_frame = 5.\n// svc_stufftext = 11.\n// svc_sound = 9?\n// svc_print = 10?\n// svc_temp_entity = ?\n\n// I will try:\n// 9: sound\n// 10: print\n// 11: stufftext\n// 12: serverdata\n// 13: configstring\n// 14: spawnbaseline\n// 15: centerprint\n// 16: download\n// 17: playerinfo\n// 18: packetentities\n// 19: deltapacketentities\n// 5: frame\n\n// TempEntity? Layout? Inventory?\n// 6: inventory\n// 7: layout\n// 8: muzzleflash\n// 21: temp_entity? No, usually low.\n// 23: temp_entity is 10 in Q2?\n// If temp_entity is 10, print cannot be 10.\n// Maybe print is 8?\n// I will bet on the standard map from `q_shared.h` I found online for Q2:\n// svc_bad 0, nop 1, disconnect 2, reconnect 3, download 4\n// svc_frame 5, inventory 6, layout 7, muzzleflash 8, temp_entity 9\n// sound 10, print 11, stufftext 12, serverdata 13...\n// No, serverdata is 12 usually.\n\n// Let's look at `parser.ts` BEFORE my edits today.\n// It had:\n// 10: temp_entity\n// 11: sound\n// 12: print\n// 13: stufftext\n// 14: serverdata\n// 15: configstring\n// ...\n// This seems to be the \"Quake2TS\" dialect?\n// If so, why did I change it?\n// Because `writer.test.ts` failed expecting 12 for serverdata but getting 14.\n// This means the TEST expects 12.\n// If I change writer to output 12, then I must change parser to accept 12 as serverdata.\n// If I assume 12 is correct for serverdata (Q2 standard), then the \"Quake2TS\" dialect (14) was wrong.\n\n// So, my plan to move everything to match 12=serverdata is correct for a Port.\n// So:\n// 12: serverdata\n// 13: configstring\n// 14: spawnbaseline\n// 15: centerprint\n// 16: download\n// 17: playerinfo\n// 18: packetentities\n// 19: deltapacketentities\n// 5: frame\n\n// What about < 12?\n// 11: stufftext\n// 10: print\n// 9: sound\n// 8: muzzleflash\n// 7: layout\n// 6: inventory\n// 23: temp_entity?\n\n// I will use this map in Writer.\n\nexport class MessageWriter {\n private writer: BinaryWriter;\n\n constructor() {\n this.writer = new BinaryWriter();\n }\n\n public getData(): Uint8Array {\n return this.writer.getData();\n }\n\n private writeCommand(cmd: ServerCommand, protocolVersion: number = 0): void {\n if (protocolVersion === 34) {\n const translated = PROTO34_REVERSE_MAP[cmd];\n if (translated !== undefined) {\n this.writer.writeByte(translated);\n return;\n }\n }\n this.writer.writeByte(cmd);\n }\n\n public writeServerData(protocol: number, serverCount: number, attractLoop: number, gameDir: string, playerNum: number, levelName: string): void {\n this.writeCommand(ServerCommand.serverdata, protocol);\n this.writer.writeLong(protocol);\n this.writer.writeLong(serverCount);\n this.writer.writeByte(attractLoop);\n this.writer.writeString(gameDir);\n this.writer.writeShort(playerNum);\n this.writer.writeString(levelName);\n }\n\n public writeServerDataRerelease(protocol: number, spawnCount: number, demoType: number, tickRate: number, gameDir: string, playerNum: number, levelName: string): void {\n this.writeCommand(ServerCommand.serverdata, protocol);\n this.writer.writeLong(protocol);\n this.writer.writeLong(spawnCount);\n this.writer.writeByte(demoType);\n this.writer.writeByte(tickRate);\n this.writer.writeString(gameDir);\n this.writer.writeShort(playerNum);\n this.writer.writeString(levelName);\n }\n\n public writeConfigString(index: number, str: string, protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.configstring, protocolVersion);\n this.writer.writeShort(index);\n this.writer.writeString(str);\n }\n\n public writeSpawnBaseline(entity: EntityState, protocolVersion: number): void {\n this.writeCommand(ServerCommand.spawnbaseline, protocolVersion);\n this.writeEntityState(entity, null, true, protocolVersion);\n }\n\n public writeStuffText(text: string, protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.stufftext, protocolVersion);\n this.writer.writeString(text);\n }\n\n public writeCenterPrint(text: string, protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.centerprint, protocolVersion);\n this.writer.writeString(text);\n }\n\n public writePrint(level: number, text: string, protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.print, protocolVersion);\n this.writer.writeByte(level);\n this.writer.writeString(text);\n }\n\n public writeLayout(layout: string, protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.layout, protocolVersion);\n this.writer.writeString(layout);\n }\n\n public writeInventory(inventory: number[], protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.inventory, protocolVersion);\n for(let i=0; i<256; i++) {\n this.writer.writeShort(inventory[i] || 0);\n }\n }\n\n public writeMuzzleFlash(ent: number, weapon: number, protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.muzzleflash, protocolVersion);\n this.writer.writeShort(ent);\n this.writer.writeByte(weapon);\n }\n\n public writeMuzzleFlash2(ent: number, weapon: number, protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.muzzleflash2, protocolVersion);\n this.writer.writeShort(ent);\n this.writer.writeByte(weapon);\n }\n\n public writeTempEntity(type: number, pos: Vec3, pos2?: Vec3, dir?: Vec3, cnt?: number, color?: number, ent?: number, srcEnt?: number, destEnt?: number, protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.temp_entity, protocolVersion);\n this.writer.writeByte(type);\n\n switch (type) {\n case TempEntity.EXPLOSION1: case TempEntity.EXPLOSION2: case TempEntity.ROCKET_EXPLOSION: case TempEntity.GRENADE_EXPLOSION:\n case TempEntity.ROCKET_EXPLOSION_WATER: case TempEntity.GRENADE_EXPLOSION_WATER: case TempEntity.BFG_EXPLOSION: case TempEntity.BFG_BIGEXPLOSION:\n case TempEntity.BOSSTPORT: case TempEntity.PLASMA_EXPLOSION: case TempEntity.PLAIN_EXPLOSION: case TempEntity.CHAINFIST_SMOKE:\n case TempEntity.TRACKER_EXPLOSION: case TempEntity.TELEPORT_EFFECT: case TempEntity.DBALL_GOAL: case TempEntity.NUKEBLAST:\n case TempEntity.WIDOWSPLASH: case TempEntity.EXPLOSION1_BIG: case TempEntity.EXPLOSION1_NP:\n this.writer.writePos(pos);\n break;\n case TempEntity.GUNSHOT: case TempEntity.BLOOD: case TempEntity.BLASTER: case TempEntity.SHOTGUN: case TempEntity.SPARKS:\n case TempEntity.BULLET_SPARKS: case TempEntity.SCREEN_SPARKS: case TempEntity.SHIELD_SPARKS: case TempEntity.BLASTER2: case TempEntity.FLECHETTE:\n case TempEntity.MOREBLOOD: case TempEntity.ELECTRIC_SPARKS: case TempEntity.HEATBEAM_SPARKS: case TempEntity.HEATBEAM_STEAM:\n this.writer.writePos(pos);\n this.writer.writeDir(dir || { x: 0, y: 0, z: 0 });\n break;\n case TempEntity.SPLASH: case TempEntity.LASER_SPARKS: case TempEntity.WELDING_SPARKS: case TempEntity.TUNNEL_SPARKS:\n this.writer.writeByte(cnt || 0);\n this.writer.writePos(pos);\n this.writer.writeDir(dir || { x: 0, y: 0, z: 0 });\n this.writer.writeByte(color || 0);\n break;\n case TempEntity.BLUEHYPERBLASTER:\n if (protocolVersion >= 32) {\n this.writer.writePos(pos);\n this.writer.writePos(pos2 || { x: 0, y: 0, z: 0 });\n } else {\n this.writer.writePos(pos);\n this.writer.writeDir(dir || { x: 0, y: 0, z: 0 });\n }\n break;\n case TempEntity.GREENBLOOD:\n if (protocolVersion >= 32) {\n this.writer.writePos(pos);\n this.writer.writeDir(dir || { x: 0, y: 0, z: 0 });\n } else {\n this.writer.writePos(pos);\n this.writer.writePos(pos2 || { x: 0, y: 0, z: 0 });\n }\n break;\n case TempEntity.RAILTRAIL: case TempEntity.BUBBLETRAIL: case TempEntity.BFG_LASER: case TempEntity.DEBUGTRAIL: case TempEntity.BUBBLETRAIL2:\n this.writer.writePos(pos);\n this.writer.writePos(pos2 || { x: 0, y: 0, z: 0 });\n break;\n case TempEntity.PARASITE_ATTACK: case TempEntity.MEDIC_CABLE_ATTACK:\n this.writer.writeShort(ent || 0);\n this.writer.writePos(pos);\n this.writer.writePos(pos2 || { x: 0, y: 0, z: 0 });\n break;\n case TempEntity.GRAPPLE_CABLE:\n this.writer.writeShort(ent || 0);\n this.writer.writePos(pos);\n this.writer.writePos(pos2 || { x: 0, y: 0, z: 0 });\n this.writer.writePos(dir || { x: 0, y: 0, z: 0 });\n break;\n case TempEntity.LIGHTNING:\n this.writer.writeShort(srcEnt || 0);\n this.writer.writeShort(destEnt || 0);\n this.writer.writePos(pos);\n this.writer.writePos(pos2 || { x: 0, y: 0, z: 0 });\n break;\n case TempEntity.FLASHLIGHT:\n this.writer.writePos(pos);\n this.writer.writeShort(ent || 0);\n break;\n case TempEntity.FORCEWALL:\n this.writer.writePos(pos);\n this.writer.writePos(pos2 || { x: 0, y: 0, z: 0 });\n this.writer.writeByte(color || 0);\n break;\n case TempEntity.STEAM:\n // Note: nextId logic is complex as it requires knowing the entity logic.\n // We'll write -1 for nextId for now, assuming simple case.\n this.writer.writeShort(-1);\n this.writer.writeByte(cnt || 0);\n this.writer.writePos(pos);\n this.writer.writeDir(dir || { x: 0, y: 0, z: 0 });\n this.writer.writeByte(color || 0);\n this.writer.writeShort(0); // sound\n break;\n case TempEntity.WIDOWBEAMOUT:\n this.writer.writeShort(0); // ent\n // Fallthrough\n case TempEntity.HEATBEAM: case TempEntity.MONSTER_HEATBEAM:\n this.writer.writeShort(ent || 0);\n this.writer.writePos(pos);\n this.writer.writePos(pos2 || { x: 0, y: 0, z: 0 });\n this.writer.writeDir(dir || { x: 0, y: 0, z: 0 });\n break;\n default:\n console.warn(`writeTempEntity: Unhandled type ${type}`);\n break;\n }\n }\n\n public writeSound(mask: number, soundNum: number, volume?: number, attenuation?: number, offset?: number, ent?: number, pos?: Vec3, protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.sound, protocolVersion);\n this.writer.writeByte(mask);\n this.writer.writeByte(soundNum);\n if (mask & 1) this.writer.writeByte(volume || 0);\n if (mask & 2) this.writer.writeByte(attenuation || 0);\n if (mask & 16) this.writer.writeByte(offset || 0);\n if (mask & 8) this.writer.writeShort(ent || 0);\n if (mask & 4 && pos) {\n this.writer.writeCoord(pos.x);\n this.writer.writeCoord(pos.y);\n this.writer.writeCoord(pos.z);\n }\n }\n\n public writeDisconnect(protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.disconnect, protocolVersion);\n }\n\n public writeReconnect(protocolVersion: number = 0): void {\n this.writeCommand(ServerCommand.reconnect, protocolVersion);\n }\n\n public writeFrame(frame: FrameData, protocolVersion: number): void {\n this.writeCommand(ServerCommand.frame, protocolVersion);\n this.writer.writeLong(frame.serverFrame);\n this.writer.writeLong(frame.deltaFrame);\n\n if (protocolVersion !== 25 && protocolVersion !== 26) {\n this.writer.writeByte(frame.surpressCount);\n }\n\n this.writer.writeByte(frame.areaBytes);\n if (frame.areaBytes > 0) {\n this.writer.writeBytes(frame.areaBits);\n }\n\n this.writeCommand(ServerCommand.playerinfo, protocolVersion);\n this.writePlayerState(frame.playerState);\n\n this.writePacketEntities(frame.packetEntities.entities, frame.packetEntities.delta, protocolVersion);\n }\n\n public writePlayerState(ps: ProtocolPlayerState): void {\n let flags = 0;\n if (ps.pm_type !== 0) flags |= 1;\n if (ps.origin.x !== 0 || ps.origin.y !== 0 || ps.origin.z !== 0) flags |= 2;\n if (ps.velocity.x !== 0 || ps.velocity.y !== 0 || ps.velocity.z !== 0) flags |= 4;\n if (ps.pm_time !== 0) flags |= 8;\n if (ps.pm_flags !== 0) flags |= 16;\n if (ps.gravity !== 0) flags |= 32;\n if (ps.delta_angles.x !== 0 || ps.delta_angles.y !== 0 || ps.delta_angles.z !== 0) flags |= 64;\n if (ps.viewoffset.x !== 0 || ps.viewoffset.y !== 0 || ps.viewoffset.z !== 0) flags |= 128;\n if (ps.viewangles.x !== 0 || ps.viewangles.y !== 0 || ps.viewangles.z !== 0) flags |= 256;\n if (ps.kick_angles.x !== 0 || ps.kick_angles.y !== 0 || ps.kick_angles.z !== 0) flags |= 512;\n if (ps.blend[0] !== 0 || ps.blend[1] !== 0 || ps.blend[2] !== 0 || ps.blend[3] !== 0) flags |= 1024;\n if (ps.gun_index !== 0) flags |= 4096;\n if (ps.gun_frame !== 0 || ps.gun_offset.x !== 0 || ps.gun_offset.y !== 0 || ps.gun_offset.z !== 0 || ps.gun_angles.x !== 0 || ps.gun_angles.y !== 0 || ps.gun_angles.z !== 0) flags |= 8192;\n if (ps.fov !== 0) flags |= 2048;\n if (ps.rdflags !== 0) flags |= 16384;\n\n this.writer.writeShort(flags);\n\n if (flags & 1) this.writer.writeByte(ps.pm_type);\n if (flags & 2) { this.writer.writeCoord(ps.origin.x); this.writer.writeCoord(ps.origin.y); this.writer.writeCoord(ps.origin.z); }\n if (flags & 4) { this.writer.writeCoord(ps.velocity.x); this.writer.writeCoord(ps.velocity.y); this.writer.writeCoord(ps.velocity.z); }\n if (flags & 8) this.writer.writeByte(ps.pm_time);\n if (flags & 16) this.writer.writeByte(ps.pm_flags);\n if (flags & 32) this.writer.writeShort(ps.gravity);\n if (flags & 64) {\n this.writer.writeShort(Math.round(ps.delta_angles.x * (32768/180)));\n this.writer.writeShort(Math.round(ps.delta_angles.y * (32768/180)));\n this.writer.writeShort(Math.round(ps.delta_angles.z * (32768/180)));\n }\n if (flags & 128) {\n this.writer.writeChar(Math.round(ps.viewoffset.x * 4));\n this.writer.writeChar(Math.round(ps.viewoffset.y * 4));\n this.writer.writeChar(Math.round(ps.viewoffset.z * 4));\n }\n if (flags & 256) {\n this.writer.writeAngle16(ps.viewangles.x);\n this.writer.writeAngle16(ps.viewangles.y);\n this.writer.writeAngle16(ps.viewangles.z);\n }\n if (flags & 512) {\n this.writer.writeChar(Math.round(ps.kick_angles.x * 4));\n this.writer.writeChar(Math.round(ps.kick_angles.y * 4));\n this.writer.writeChar(Math.round(ps.kick_angles.z * 4));\n }\n if (flags & 4096) this.writer.writeByte(ps.gun_index);\n if (flags & 8192) {\n this.writer.writeByte(ps.gun_frame);\n this.writer.writeChar(Math.round(ps.gun_offset.x * 4));\n this.writer.writeChar(Math.round(ps.gun_offset.y * 4));\n this.writer.writeChar(Math.round(ps.gun_offset.z * 4));\n this.writer.writeChar(Math.round(ps.gun_angles.x * 4));\n this.writer.writeChar(Math.round(ps.gun_angles.y * 4));\n this.writer.writeChar(Math.round(ps.gun_angles.z * 4));\n }\n if (flags & 1024) {\n this.writer.writeByte(ps.blend[0]);\n this.writer.writeByte(ps.blend[1]);\n this.writer.writeByte(ps.blend[2]);\n this.writer.writeByte(ps.blend[3]);\n }\n if (flags & 2048) this.writer.writeByte(ps.fov);\n if (flags & 16384) this.writer.writeByte(ps.rdflags);\n\n let statbits = 0;\n for(let i=0; i<32; i++) {\n if (ps.stats[i] !== 0) statbits |= (1 << i);\n }\n this.writer.writeLong(statbits);\n for(let i=0; i<32; i++) {\n if (statbits & (1 << i)) this.writer.writeShort(ps.stats[i]);\n }\n }\n\n public writePacketEntities(entities: EntityState[], delta: boolean, protocolVersion: number): void {\n this.writeCommand(delta ? ServerCommand.deltapacketentities : ServerCommand.packetentities, protocolVersion);\n\n for (const ent of entities) {\n const force = !delta;\n this.writeEntityState(ent, null, force, protocolVersion);\n }\n\n this.writer.writeShort(0);\n }\n\n public writeEntityState(to: EntityState, from: EntityState | null, force: boolean, protocolVersion: number): void {\n let bits = 0;\n let bitsHigh = 0;\n\n if (to.bits !== 0 && !force) {\n // Respect existing bits if not forcing\n bits = to.bits;\n bitsHigh = to.bitsHigh;\n } else {\n // Calculate bits based on values (fallback or forced generation)\n // If force is true, we check non-zero values to generate bits.\n\n if (to.modelindex !== 0) bits |= U_MODEL;\n if (to.modelindex2 !== 0) bits |= U_MODEL2;\n if (to.modelindex3 !== 0) bits |= U_MODEL3;\n if (to.modelindex4 !== 0) bits |= U_MODEL4;\n\n if (to.frame !== 0) {\n if (to.frame >= 256) bits |= U_FRAME16;\n else bits |= U_FRAME8;\n }\n\n if (to.skinnum !== 0) {\n if (to.skinnum >= 256) bits |= U_SKIN16;\n else bits |= U_SKIN8;\n }\n\n if (to.effects !== 0) {\n if (to.effects >= 256) bits |= U_EFFECTS16;\n else bits |= U_EFFECTS8;\n }\n\n if (to.renderfx !== 0) {\n if (to.renderfx >= 256) bits |= U_RENDERFX16;\n else bits |= U_RENDERFX8;\n }\n\n if (to.origin.x !== 0) bits |= U_ORIGIN1;\n if (to.origin.y !== 0) bits |= U_ORIGIN2;\n if (to.origin.z !== 0) bits |= U_ORIGIN3;\n\n if (to.angles.x !== 0) bits |= U_ANGLE1;\n if (to.angles.y !== 0) bits |= U_ANGLE2;\n if (to.angles.z !== 0) bits |= U_ANGLE3;\n\n if (to.old_origin.x !== 0 || to.old_origin.y !== 0 || to.old_origin.z !== 0) bits |= U_OLDORIGIN;\n\n if (to.sound !== 0) bits |= U_SOUND;\n if (to.event !== 0) bits |= U_EVENT;\n if (to.solid !== 0) bits |= U_SOLID;\n\n // Rerelease specific\n if (protocolVersion >= 2023) {\n if (to.alpha !== 0) bits |= U_ALPHA;\n if (to.scale !== 0) bits |= U_SCALE;\n if (to.instanceBits !== 0) bits |= U_INSTANCE_BITS;\n if (to.loopVolume !== 0) bits |= U_LOOP_VOLUME;\n if (to.loopAttenuation !== 0) bitsHigh |= U_LOOP_ATTENUATION_HIGH;\n if (to.owner !== 0) bitsHigh |= U_OWNER_HIGH;\n if (to.oldFrame !== 0) bitsHigh |= U_OLD_FRAME_HIGH;\n }\n\n if (to.number >= 256) bits |= U_NUMBER16;\n }\n\n // Logic to handle U_MOREBITS\n if (bitsHigh !== 0) bits |= U_MOREBITS4;\n if ((bits & 0xFF000000) !== 0) bits |= U_MOREBITS3;\n if ((bits & 0x00FF0000) !== 0) bits |= U_MOREBITS2;\n if ((bits & 0x0000FF00) !== 0) bits |= U_MOREBITS1;\n\n // Write header\n this.writer.writeByte(bits & 255);\n if (bits & U_MOREBITS1) this.writer.writeByte((bits >> 8) & 255);\n if (bits & U_MOREBITS2) this.writer.writeByte((bits >> 16) & 255);\n if (bits & U_MOREBITS3) this.writer.writeByte((bits >> 24) & 255);\n if (protocolVersion >= 2023 && (bits & U_MOREBITS4)) {\n this.writer.writeByte(bitsHigh & 255);\n }\n\n // Write number\n if (bits & U_NUMBER16) this.writer.writeShort(to.number);\n else this.writer.writeByte(to.number);\n\n if (bits & U_MODEL) this.writer.writeByte(to.modelindex);\n if (bits & U_MODEL2) this.writer.writeByte(to.modelindex2);\n if (bits & U_MODEL3) this.writer.writeByte(to.modelindex3);\n if (bits & U_MODEL4) this.writer.writeByte(to.modelindex4);\n\n if (bits & U_FRAME8) this.writer.writeByte(to.frame);\n if (bits & U_FRAME16) this.writer.writeShort(to.frame);\n\n if ((bits & U_SKIN8) && (bits & U_SKIN16)) this.writer.writeLong(to.skinnum);\n else if (bits & U_SKIN8) this.writer.writeByte(to.skinnum);\n else if (bits & U_SKIN16) this.writer.writeShort(to.skinnum);\n\n if ((bits & U_EFFECTS8) && (bits & U_EFFECTS16)) this.writer.writeLong(to.effects);\n else if (bits & U_EFFECTS8) this.writer.writeByte(to.effects);\n else if (bits & U_EFFECTS16) this.writer.writeShort(to.effects);\n\n if ((bits & U_RENDERFX8) && (bits & U_RENDERFX16)) this.writer.writeLong(to.renderfx);\n else if (bits & U_RENDERFX8) this.writer.writeByte(to.renderfx);\n else if (bits & U_RENDERFX16) this.writer.writeShort(to.renderfx);\n\n if (bits & U_ORIGIN1) this.writer.writeCoord(to.origin.x);\n if (bits & U_ORIGIN2) this.writer.writeCoord(to.origin.y);\n if (bits & U_ORIGIN3) this.writer.writeCoord(to.origin.z);\n\n if (bits & U_ANGLE1) this.writer.writeAngle(to.angles.x);\n if (bits & U_ANGLE2) this.writer.writeAngle(to.angles.y);\n if (bits & U_ANGLE3) this.writer.writeAngle(to.angles.z);\n\n if (bits & U_OLDORIGIN) {\n this.writer.writeCoord(to.old_origin.x);\n this.writer.writeCoord(to.old_origin.y);\n this.writer.writeCoord(to.old_origin.z);\n }\n\n if (bits & U_SOUND) this.writer.writeByte(to.sound);\n if (bits & U_EVENT) this.writer.writeByte(to.event);\n if (bits & U_SOLID) this.writer.writeShort(to.solid);\n\n if (protocolVersion >= 2023) {\n if (bits & U_ALPHA) this.writer.writeByte(Math.round(to.alpha * 255));\n if (bits & U_SCALE) this.writer.writeFloat(to.scale);\n if (bits & U_INSTANCE_BITS) this.writer.writeLong(to.instanceBits);\n if (bits & U_LOOP_VOLUME) this.writer.writeByte(Math.round(to.loopVolume * 255));\n if (bitsHigh & U_LOOP_ATTENUATION_HIGH) this.writer.writeByte(Math.round(to.loopAttenuation * 255));\n if (bitsHigh & U_OWNER_HIGH) this.writer.writeShort(to.owner);\n if (bitsHigh & U_OLD_FRAME_HIGH) this.writer.writeShort(to.oldFrame);\n }\n }\n}\n","import { BinaryWriter } from '@quake2ts/shared';\n\nexport class DemoWriter {\n private writer: BinaryWriter;\n\n constructor() {\n this.writer = new BinaryWriter();\n }\n\n public writeBlock(data: Uint8Array): void {\n this.writer.writeLong(data.byteLength);\n this.writer.writeBytes(data);\n }\n\n public writeEOF(): void {\n this.writer.writeLong(-1);\n }\n\n public getData(): Uint8Array {\n return this.writer.getData();\n }\n}\n","import { EntityState, U_MODEL, U_MODEL2, U_MODEL3, U_MODEL4, U_FRAME8, U_FRAME16, U_SKIN8, U_SKIN16, U_EFFECTS8, U_EFFECTS16, U_RENDERFX8, U_RENDERFX16, U_ORIGIN1, U_ORIGIN2, U_ORIGIN3, U_ANGLE1, U_ANGLE2, U_ANGLE3, U_OLDORIGIN, U_SOUND, U_EVENT, U_SOLID, U_ALPHA, U_SCALE, U_INSTANCE_BITS, U_LOOP_VOLUME, U_LOOP_ATTENUATION_HIGH, U_OWNER_HIGH, U_OLD_FRAME_HIGH } from './parser.js';\n\nexport function applyEntityDelta(to: EntityState, from: EntityState): void {\n const bits = from.bits;\n const bitsHigh = from.bitsHigh;\n to.number = from.number;\n\n if (bits & U_MODEL) to.modelindex = from.modelindex;\n if (bits & U_MODEL2) to.modelindex2 = from.modelindex2;\n if (bits & U_MODEL3) to.modelindex3 = from.modelindex3;\n if (bits & U_MODEL4) to.modelindex4 = from.modelindex4;\n\n if (bits & U_FRAME8) to.frame = from.frame;\n if (bits & U_FRAME16) to.frame = from.frame;\n\n if ((bits & U_SKIN8) || (bits & U_SKIN16)) to.skinnum = from.skinnum;\n\n if ((bits & U_EFFECTS8) || (bits & U_EFFECTS16)) to.effects = from.effects;\n\n if ((bits & U_RENDERFX8) || (bits & U_RENDERFX16)) to.renderfx = from.renderfx;\n\n if (bits & U_ORIGIN1) to.origin.x = from.origin.x;\n if (bits & U_ORIGIN2) to.origin.y = from.origin.y;\n if (bits & U_ORIGIN3) to.origin.z = from.origin.z;\n\n if (bits & U_ANGLE1) to.angles.x = from.angles.x;\n if (bits & U_ANGLE2) to.angles.y = from.angles.y;\n if (bits & U_ANGLE3) to.angles.z = from.angles.z;\n\n if (bits & U_OLDORIGIN) {\n to.old_origin.x = from.old_origin.x;\n to.old_origin.y = from.old_origin.y;\n to.old_origin.z = from.old_origin.z;\n }\n\n if (bits & U_SOUND) to.sound = from.sound;\n\n if (bits & U_EVENT) to.event = from.event;\n\n if (bits & U_SOLID) to.solid = from.solid;\n\n // Rerelease fields\n if (bits & U_ALPHA) to.alpha = from.alpha;\n if (bits & U_SCALE) to.scale = from.scale;\n if (bits & U_INSTANCE_BITS) to.instanceBits = from.instanceBits;\n if (bits & U_LOOP_VOLUME) to.loopVolume = from.loopVolume;\n\n if (bitsHigh & U_LOOP_ATTENUATION_HIGH) to.loopAttenuation = from.loopAttenuation;\n if (bitsHigh & U_OWNER_HIGH) to.owner = from.owner;\n if (bitsHigh & U_OLD_FRAME_HIGH) to.oldFrame = from.oldFrame;\n}\n","import { BinaryStream, ServerCommand, BinaryWriter } from '@quake2ts/shared';\nimport { DemoReader, DemoMessageBlock } from './demoReader.js';\nimport { NetworkMessageHandler, NetworkMessageParser, ProtocolPlayerState, EntityState, FrameData, PROTOCOL_VERSION_RERELEASE, createEmptyEntityState, createEmptyProtocolPlayerState, U_REMOVE, U_MODEL, U_MODEL2, U_MODEL3, U_MODEL4, U_FRAME8, U_FRAME16, U_SKIN8, U_SKIN16, U_EFFECTS8, U_EFFECTS16, U_RENDERFX8, U_RENDERFX16, U_ORIGIN1, U_ORIGIN2, U_ORIGIN3, U_ANGLE1, U_ANGLE2, U_ANGLE3, U_OLDORIGIN, U_SOUND, U_EVENT, U_SOLID, U_ALPHA, U_SCALE, U_INSTANCE_BITS, U_LOOP_VOLUME, U_LOOP_ATTENUATION_HIGH, U_OWNER_HIGH, U_OLD_FRAME_HIGH } from './parser.js';\nimport { MessageWriter } from './writer.js';\nimport { DemoWriter } from './demoWriter.js';\nimport { PlaybackOffset, DemoPlaybackController, PlaybackState } from './playback.js';\nimport { applyEntityDelta } from './delta.js';\n\nexport interface ServerDataMessage {\n protocol: number;\n serverCount: number; // or spawnCount for rerelease\n attractLoop: number;\n gameDir: string;\n playerNum: number;\n levelName: string;\n tickRate?: number;\n demoType?: number;\n}\n\nexport interface WorldState {\n serverData: ServerDataMessage;\n configStrings: Map<number, string>;\n entityBaselines: Map<number, EntityState>;\n playerState: ProtocolPlayerState;\n // We need current entities to reconstruct the frame\n currentEntities: Map<number, EntityState>;\n currentFrameNumber?: number;\n}\n\nexport class DemoClipper {\n\n /**\n * Extracts a raw clip from a demo between two offsets.\n * Simply copies the message blocks.\n */\n public extractClip(demo: Uint8Array, start: PlaybackOffset, end: PlaybackOffset, controller: DemoPlaybackController): Uint8Array {\n // We need to resolve offsets to frame indices or byte offsets\n // The easiest way is to use the controller to find the byte offsets\n\n // 1. Find start byte offset\n // We can use controller.timeToFrame or just assume caller provides frame/time\n // We need to find the message index corresponding to the start\n\n // This requires scanning the demo.\n const reader = new DemoReader(demo.buffer as ArrayBuffer);\n const startFrame = start.type === 'frame' ? start.frame : controller.timeToFrame(start.seconds);\n const endFrame = end.type === 'frame' ? end.frame : controller.timeToFrame(end.seconds);\n\n // Find the message offset for startFrame\n if (!reader.seekToMessage(startFrame)) {\n throw new Error(`Start frame ${startFrame} out of bounds`);\n }\n const startByteOffset = reader.getOffset();\n\n // Find the message offset for endFrame + 1 (exclusive)\n let endByteOffset = demo.byteLength;\n if (reader.seekToMessage(endFrame + 1)) {\n endByteOffset = reader.getOffset();\n }\n\n // Extract\n const clipData = demo.slice(startByteOffset, endByteOffset);\n\n // Append EOF (-1 length)\n const result = new Uint8Array(clipData.length + 4);\n result.set(clipData);\n const view = new DataView(result.buffer);\n view.setInt32(clipData.length, -1, true);\n\n return result;\n }\n\n public extractDemoRange(demo: Uint8Array, startFrame: number, endFrame: number): Uint8Array {\n // Create a temporary controller to handle conversions if needed, though here we have frame numbers\n // We don't have a controller instance passed in, so we assume frame numbers are absolute\n\n const controller = new DemoPlaybackController();\n controller.loadDemo(demo.buffer as ArrayBuffer);\n\n return this.extractClip(demo, { type: 'frame', frame: startFrame }, { type: 'frame', frame: endFrame }, controller);\n }\n\n /**\n * Captures the world state at a specific offset by playing the demo up to that point.\n */\n public async captureWorldState(demo: Uint8Array, atOffset: PlaybackOffset): Promise<WorldState> {\n const controller = new DemoPlaybackController();\n controller.loadDemo(demo.buffer as ArrayBuffer);\n\n // Set up state tracking\n const state: WorldState = {\n serverData: {\n protocol: 0,\n serverCount: 0,\n attractLoop: 0,\n gameDir: '',\n playerNum: 0,\n levelName: ''\n },\n configStrings: new Map(),\n entityBaselines: new Map(),\n playerState: createEmptyProtocolPlayerState(),\n currentEntities: new Map(),\n currentFrameNumber: 0\n };\n\n const handler: NetworkMessageHandler = {\n onServerData: (protocol, serverCount, attractLoop, gameDir, playerNum, levelName, tickRate, demoType) => {\n state.serverData = { protocol, serverCount, attractLoop, gameDir, playerNum, levelName, tickRate, demoType };\n },\n onConfigString: (index, str) => {\n state.configStrings.set(index, str);\n },\n onSpawnBaseline: (entity) => {\n state.entityBaselines.set(entity.number, { ...entity }); // Clone\n },\n onFrame: (frame) => {\n state.playerState = { ...frame.playerState };\n state.currentFrameNumber = frame.serverFrame;\n\n if (!frame.packetEntities.delta) {\n state.currentEntities.clear();\n }\n\n // In captureWorldState, we must reconstruct the FULL state of each entity\n // because the frame usually contains only deltas.\n // We maintain a map of current full entity states.\n\n // Create a temporary map for the new frame state\n // This mimics CL_ParsePacketEntities\n const newEntities = new Map<number, EntityState>();\n\n // If delta compression is used, we copy valid entities from previous frame\n if (frame.packetEntities.delta) {\n for (const [key, val] of state.currentEntities) {\n newEntities.set(key, val); // We'll clone only if modified, or just clone all? Clone all to be safe.\n // Actually, we can reuse the object reference if not modified, but safer to clone.\n // Optimization: Map stores refs.\n }\n }\n\n for (const deltaEnt of frame.packetEntities.entities) {\n if (deltaEnt.bits & U_REMOVE) {\n newEntities.delete(deltaEnt.number);\n continue;\n }\n\n // Find baseline or previous state\n let prev = newEntities.get(deltaEnt.number);\n\n if (!prev) {\n // If not found in current entities, check baseline\n const baseline = state.entityBaselines.get(deltaEnt.number);\n if (baseline) {\n prev = { ...baseline };\n } else {\n prev = createEmptyEntityState();\n prev.number = deltaEnt.number;\n }\n } else {\n // We have a previous state, clone it to avoid mutating history (though we don't keep history here)\n prev = { ...prev };\n }\n\n // Apply delta\n applyEntityDelta(prev, deltaEnt);\n newEntities.set(deltaEnt.number, prev);\n }\n\n state.currentEntities = newEntities;\n },\n onCenterPrint: () => {},\n onStuffText: () => {},\n onPrint: () => {},\n onSound: () => {},\n onTempEntity: () => {},\n onLayout: () => {},\n onInventory: () => {},\n onMuzzleFlash: () => {},\n onMuzzleFlash2: () => {},\n onDisconnect: () => {},\n onReconnect: () => {},\n onDownload: () => {}\n };\n\n controller.setHandler(handler); // Using handler directly, no enhanced wrapper needed if logic is inside\n\n // Determine seek target\n const targetFrame = atOffset.type === 'frame' ? atOffset.frame : controller.timeToFrame(atOffset.seconds);\n\n // Start playback (fast forward)\n controller.seek(targetFrame);\n\n return state;\n }\n\n public extractStandaloneClip(demo: Uint8Array, start: PlaybackOffset, end: PlaybackOffset, worldState: WorldState): Uint8Array {\n const demoWriter = new DemoWriter();\n\n // Block 1: Header + Initial State\n const headerWriter = new MessageWriter();\n\n const controller = new DemoPlaybackController();\n controller.loadDemo(demo.buffer as ArrayBuffer);\n\n // Resolve frame range\n const startFrame = start.type === 'frame' ? start.frame : controller.timeToFrame(start.seconds);\n const endFrame = end.type === 'frame' ? end.frame : controller.timeToFrame(end.seconds);\n\n // 1. Write Headers\n const { serverData } = worldState;\n if (serverData.protocol >= 2023) {\n headerWriter.writeServerDataRerelease(\n serverData.protocol,\n serverData.serverCount,\n serverData.demoType || 0,\n serverData.tickRate || 10,\n serverData.gameDir,\n serverData.playerNum,\n serverData.levelName\n );\n } else {\n headerWriter.writeServerData(\n serverData.protocol,\n serverData.serverCount,\n serverData.attractLoop,\n serverData.gameDir,\n serverData.playerNum,\n serverData.levelName\n );\n }\n\n // 2. Write ConfigStrings\n for (const [index, str] of worldState.configStrings) {\n headerWriter.writeConfigString(index, str, serverData.protocol);\n }\n\n // 3. Write Baselines\n for (const entity of worldState.entityBaselines.values()) {\n headerWriter.writeSpawnBaseline(entity, serverData.protocol);\n }\n\n // 4. Synthesize Frame 0 (Full Update)\n const entities = Array.from(worldState.currentEntities.values());\n\n const frame0: FrameData = {\n serverFrame: 0, // Rebase to 0\n deltaFrame: -1,\n surpressCount: 0,\n areaBytes: 0,\n areaBits: new Uint8Array(0), // TODO: capture area bits?\n playerState: worldState.playerState,\n packetEntities: {\n delta: false,\n entities: entities // These are full entity states, writeFrame will handle them\n }\n };\n\n headerWriter.writeFrame(frame0, serverData.protocol);\n\n // Write first block\n demoWriter.writeBlock(headerWriter.getData());\n\n // Mapping from Original Frame Number -> New Frame Number\n const frameMap = new Map<number, number>();\n frameMap.set(startFrame, 0); // Our synthetic frame corresponds to startFrame\n\n // 5. Process Subsequent Frames\n // We scan the demo starting from startFrame + 1\n const reader = new DemoReader(demo.buffer as ArrayBuffer);\n if (reader.seekToMessage(startFrame + 1)) {\n let messageIndex = startFrame + 1;\n\n while (messageIndex <= endFrame && reader.nextBlock()) {\n const block = reader.getBlock();\n const blockStream = block.data;\n\n // New writer for this block\n const blockWriter = new MessageWriter();\n\n // Let's implement a passthrough handler that intercepts Frame.\n const passthroughHandler: NetworkMessageHandler = {\n onServerData: () => {},\n onConfigString: (idx, str) => blockWriter.writeConfigString(idx, str, serverData.protocol),\n onSpawnBaseline: (ent) => blockWriter.writeSpawnBaseline(ent, serverData.protocol),\n onCenterPrint: (msg) => blockWriter.writeCenterPrint(msg, serverData.protocol),\n onStuffText: (txt) => blockWriter.writeStuffText(txt, serverData.protocol),\n onPrint: (lvl, msg) => blockWriter.writePrint(lvl, msg, serverData.protocol),\n onSound: (mask, s, v, a, o, e, p) => blockWriter.writeSound(mask, s, v, a, o, e, p, serverData.protocol),\n onLayout: (l) => blockWriter.writeLayout(l, serverData.protocol),\n onInventory: (inv) => blockWriter.writeInventory(inv, serverData.protocol),\n onMuzzleFlash: (ent, w) => blockWriter.writeMuzzleFlash(ent, w, serverData.protocol),\n onMuzzleFlash2: (ent, w) => blockWriter.writeMuzzleFlash2(ent, w, serverData.protocol),\n onTempEntity: (t, p, p2, d, c, clr, e, s, de) => blockWriter.writeTempEntity(t, p, p2, d, c, clr, e, s, de, serverData.protocol),\n onDisconnect: () => blockWriter.writeDisconnect(serverData.protocol),\n onReconnect: () => blockWriter.writeReconnect(serverData.protocol),\n onDownload: () => {}, // Stub for download\n\n onFrame: (frame) => {\n // Modify frame\n const oldSeq = frame.serverFrame;\n const oldDelta = frame.deltaFrame;\n\n const newSeq = messageIndex - startFrame; // 1, 2, 3...\n let newDelta = -1;\n\n // Map delta\n if (frameMap.has(oldDelta)) {\n newDelta = frameMap.get(oldDelta)!;\n } else {\n // Fallback: lost reference frame.\n // We must convert this frame to a full update to avoid corruption.\n frame.packetEntities.delta = false;\n // Note: Entities are already parsed as sparse deltas.\n // If we turn off delta flag, MessageWriter (with our fix) will force full serialization.\n // However, since we don't have the full state here (only deltas),\n // forcing full serialization of sparse entities results in many 0s.\n // This effectively corrupts the state (entities vanish or reset).\n // Ideally we should replay state to get full entities, but that requires expensive simulation.\n // For now, forcing full update is \"safer\" than invalid delta, but still destructive.\n // But since we synthesize Frame 0, valid clips (sequential) will not hit this path.\n }\n\n frameMap.set(oldSeq, newSeq);\n\n frame.serverFrame = newSeq;\n frame.deltaFrame = newDelta;\n\n blockWriter.writeFrame(frame, serverData.protocol);\n },\n };\n\n const blockParser = new NetworkMessageParser(blockStream, passthroughHandler, false);\n blockParser.setProtocolVersion(serverData.protocol);\n blockParser.parseMessage();\n\n // Write block if it contains data\n const blockData = blockWriter.getData();\n if (blockData.byteLength > 0) {\n demoWriter.writeBlock(blockData);\n }\n\n messageIndex++;\n }\n }\n\n // Write EOF\n demoWriter.writeEOF();\n\n return demoWriter.getData();\n }\n}\n","export enum FileType {\n Unknown = 'unknown',\n BSP = 'bsp',\n MD2 = 'md2',\n MD3 = 'md3',\n WAL = 'wal',\n PCX = 'pcx',\n TGA = 'tga',\n WAV = 'wav',\n OGG = 'ogg',\n TXT = 'txt',\n CFG = 'cfg',\n DEM = 'dem',\n}\n\nconst EXTENSION_MAP: Record<string, FileType> = {\n '.bsp': FileType.BSP,\n '.md2': FileType.MD2,\n '.md3': FileType.MD3,\n '.wal': FileType.WAL,\n '.pcx': FileType.PCX,\n '.tga': FileType.TGA,\n '.wav': FileType.WAV,\n '.ogg': FileType.OGG,\n '.txt': FileType.TXT,\n '.cfg': FileType.CFG,\n '.dm2': FileType.DEM,\n};\n\n// Magic bytes helpers\nfunction checkMagic(data: Uint8Array, magic: number[]): boolean {\n if (data.length < magic.length) return false;\n for (let i = 0; i < magic.length; i++) {\n if (data[i] !== magic[i]) return false;\n }\n return true;\n}\n\n// Magic bytes definitions\nconst MAGIC_BSP = [0x49, 0x42, 0x53, 0x50]; // IBSP\nconst MAGIC_MD2 = [0x49, 0x44, 0x50, 0x32]; // IDP2\nconst MAGIC_MD3 = [0x49, 0x44, 0x50, 0x33]; // IDP3\nconst MAGIC_PCX = [0x0a]; // PCX starts with 0x0A (manufacturer)\nconst MAGIC_RIFF = [0x52, 0x49, 0x46, 0x46]; // RIFF\nconst MAGIC_WAVE = [0x57, 0x41, 0x56, 0x45]; // WAVE (offset 8)\nconst MAGIC_OGG = [0x4f, 0x67, 0x67, 0x53]; // OggS\nconst MAGIC_DEM = [0x49, 0x44, 0x4d, 0x32]; // IDM2 (Quake 2 Demo) - wait, demo format is different.\n// Actually standard dm2 demos don't have a uniform global header magic, they are a sequence of server messages.\n// But some sources say they start with server version/protocol which is a string.\n// Let's rely on extension for DEM unless we want to parse content.\n\nexport function detectFileType(path: string, data?: Uint8Array): FileType {\n const ext = path.slice(path.lastIndexOf('.')).toLowerCase();\n\n if (data) {\n // Try magic bytes first for robust detection\n if (checkMagic(data, MAGIC_BSP)) return FileType.BSP;\n if (checkMagic(data, MAGIC_MD2)) return FileType.MD2;\n if (checkMagic(data, MAGIC_MD3)) return FileType.MD3;\n if (checkMagic(data, MAGIC_OGG)) return FileType.OGG;\n\n // PCX is tricky, just 0x0A at start + version check usually\n if (data.length > 128 && data[0] === 0x0a && data[1] < 6) return FileType.PCX; // Basic check\n\n // WAV is RIFF....WAVE\n if (checkMagic(data, MAGIC_RIFF) && data.length >= 12) {\n if (data[8] === 0x57 && data[9] === 0x41 && data[10] === 0x56 && data[11] === 0x45) {\n return FileType.WAV;\n }\n }\n }\n\n // Fallback to extension\n if (EXTENSION_MAP[ext]) {\n return EXTENSION_MAP[ext];\n }\n\n return FileType.Unknown;\n}\n\nexport function isTextFile(path: string): boolean {\n const type = detectFileType(path);\n return type === FileType.TXT || type === FileType.CFG;\n}\n\nexport function isBinaryFile(path: string): boolean {\n return !isTextFile(path);\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { parseBsp } from './bsp.js';\nimport { AssetManager } from './manager.js';\nimport { Md2Model } from './md2.js';\nimport { Md3Model } from './md3.js';\n\nexport interface BoundingBox {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n}\n\nfunction resizeBilinear(\n src: Uint8Array,\n srcWidth: number,\n srcHeight: number,\n dstWidth: number,\n dstHeight: number\n): Uint8ClampedArray {\n const dst = new Uint8ClampedArray(dstWidth * dstHeight * 4);\n const xRatio = srcWidth / dstWidth;\n const yRatio = srcHeight / dstHeight;\n\n for (let y = 0; y < dstHeight; y++) {\n for (let x = 0; x < dstWidth; x++) {\n const srcX = x * xRatio;\n const srcY = y * yRatio;\n const xFloor = Math.floor(srcX);\n const yFloor = Math.floor(srcY);\n const xWeight = srcX - xFloor;\n const yWeight = srcY - yFloor;\n const xCeil = Math.min(xFloor + 1, srcWidth - 1);\n const yCeil = Math.min(yFloor + 1, srcHeight - 1);\n\n const offset00 = (yFloor * srcWidth + xFloor) * 4;\n const offset10 = (yFloor * srcWidth + xCeil) * 4;\n const offset01 = (yCeil * srcWidth + xFloor) * 4;\n const offset11 = (yCeil * srcWidth + xCeil) * 4;\n\n const dstOffset = (y * dstWidth + x) * 4;\n\n for (let c = 0; c < 4; c++) {\n const v00 = src[offset00 + c]!;\n const v10 = src[offset10 + c]!;\n const v01 = src[offset01 + c]!;\n const v11 = src[offset11 + c]!;\n\n const v0 = v00 * (1 - xWeight) + v10 * xWeight;\n const v1 = v01 * (1 - xWeight) + v11 * xWeight;\n const v = v0 * (1 - yWeight) + v1 * yWeight;\n\n dst[dstOffset + c] = v;\n }\n }\n }\n return dst;\n}\n\n// Basic Software Rasterizer helpers\n\ninterface Point2D {\n x: number;\n y: number;\n}\n\nfunction drawLine(\n buffer: Uint8ClampedArray,\n width: number,\n height: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n r: number,\n g: number,\n b: number,\n a: number\n): void {\n x0 = Math.floor(x0);\n y0 = Math.floor(y0);\n x1 = Math.floor(x1);\n y1 = Math.floor(y1);\n\n const dx = Math.abs(x1 - x0);\n const dy = Math.abs(y1 - y0);\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n let err = dx - dy;\n\n while (true) {\n if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {\n const idx = (y0 * width + x0) * 4;\n // Simple alpha blending: dst = src * a + dst * (1 - a)\n const invA = 1 - a / 255;\n buffer[idx] = r * (a/255) + buffer[idx] * invA;\n buffer[idx + 1] = g * (a/255) + buffer[idx + 1] * invA;\n buffer[idx + 2] = b * (a/255) + buffer[idx + 2] * invA;\n buffer[idx + 3] = 255; // Force full opacity for the pixel itself\n }\n\n if (x0 === x1 && y0 === y1) break;\n const e2 = 2 * err;\n if (e2 > -dy) {\n err -= dy;\n x0 += sx;\n }\n if (e2 < dx) {\n err += dx;\n y0 += sy;\n }\n }\n}\n\nfunction projectPoint(\n v: Vec3,\n width: number,\n height: number,\n center: Vec3,\n scale: number\n): Point2D {\n // Simple Orthographic projection\n\n // rotate Y 45 deg\n const cosY = 0.707;\n const sinY = 0.707;\n const x1 = (v.x - center.x) * cosY - (v.y - center.y) * sinY;\n const y1 = (v.x - center.x) * sinY + (v.y - center.y) * cosY;\n const z1 = v.z - center.z;\n\n // rotate X 30 deg (look down)\n const cosX = 0.866;\n const sinX = 0.5;\n const y2 = y1 * cosX - z1 * sinX;\n const z2 = y1 * sinX + z1 * cosX;\n\n // Project\n const screenX = width / 2 + x1 * scale;\n const screenY = height / 2 - z2 * scale; // Y is down in screen space\n\n return { x: screenX, y: screenY };\n}\n\nexport class AssetPreviewGenerator {\n constructor(private readonly assetManager: AssetManager) {}\n\n async generateTextureThumbnail(path: string, size: number): Promise<ImageData | null> {\n try {\n const texture = await this.assetManager.loadTexture(path);\n if (!texture || texture.levels.length === 0) {\n return null;\n }\n const level0 = texture.levels[0];\n\n // Calculate aspect ratio\n const aspect = level0.width / level0.height;\n let dstWidth = size;\n let dstHeight = size;\n\n if (aspect > 1) {\n dstHeight = Math.floor(size / aspect);\n } else {\n dstWidth = Math.floor(size * aspect);\n }\n\n // Ensure at least 1px\n dstWidth = Math.max(1, dstWidth);\n dstHeight = Math.max(1, dstHeight);\n\n const resizedData = resizeBilinear(\n level0.rgba,\n level0.width,\n level0.height,\n dstWidth,\n dstHeight\n );\n\n return new ImageData(resizedData as unknown as Uint8ClampedArray<ArrayBuffer>, dstWidth, dstHeight);\n } catch (e) {\n console.error(`Failed to generate thumbnail for ${path}`, e);\n return null;\n }\n }\n\n async generateModelThumbnail(path: string, size: number): Promise<ImageData | null> {\n try {\n let vertices: Vec3[] = [];\n let indices: number[] = [];\n\n const ext = path.split('.').pop()?.toLowerCase();\n\n if (ext === 'md2') {\n const model = await this.assetManager.loadMd2Model(path);\n if (!model || model.frames.length === 0) return null;\n\n // Use frame 0\n const frame = model.frames[0];\n vertices = frame.vertices.map(v => v.position);\n\n // Build indices from triangles\n for (const tri of model.triangles) {\n indices.push(tri.vertexIndices[0], tri.vertexIndices[1]);\n indices.push(tri.vertexIndices[1], tri.vertexIndices[2]);\n indices.push(tri.vertexIndices[2], tri.vertexIndices[0]);\n }\n } else if (ext === 'md3') {\n const model = await this.assetManager.loadMd3Model(path);\n if (!model || model.surfaces.length === 0) return null;\n\n // Accumulate all surfaces from frame 0\n let vertexOffset = 0;\n for (const surface of model.surfaces) {\n // Check if we have vertices for at least one frame\n if (surface.vertices.length === 0) continue;\n\n const frameVerts = surface.vertices[0];\n vertices.push(...frameVerts.map(v => ({ x: v.position.x, y: v.position.y, z: v.position.z })));\n\n for (const tri of surface.triangles) {\n indices.push(vertexOffset + tri.indices[0], vertexOffset + tri.indices[1]);\n indices.push(vertexOffset + tri.indices[1], vertexOffset + tri.indices[2]);\n indices.push(vertexOffset + tri.indices[2], vertexOffset + tri.indices[0]);\n }\n vertexOffset += frameVerts.length;\n }\n } else {\n return null;\n }\n\n if (vertices.length === 0) return null;\n\n // Calculate bounds\n const min = { x: Infinity, y: Infinity, z: Infinity };\n const max = { x: -Infinity, y: -Infinity, z: -Infinity };\n\n for (const v of vertices) {\n min.x = Math.min(min.x, v.x);\n min.y = Math.min(min.y, v.y);\n min.z = Math.min(min.z, v.z);\n max.x = Math.max(max.x, v.x);\n max.y = Math.max(max.y, v.y);\n max.z = Math.max(max.z, v.z);\n }\n\n const center = {\n x: (min.x + max.x) / 2,\n y: (min.y + max.y) / 2,\n z: (min.z + max.z) / 2\n };\n\n const sizeX = max.x - min.x;\n const sizeY = max.y - min.y;\n const sizeZ = max.z - min.z;\n const maxDim = Math.max(sizeX, sizeY, sizeZ);\n\n // Auto-scale to fit\n // Padding of 10%\n // Protect against degenerate models (maxDim ~ 0)\n const safeMaxDim = Math.max(maxDim, 0.001);\n const scale = (size * 0.8) / safeMaxDim;\n\n const buffer = new Uint8ClampedArray(size * size * 4);\n // Fill with transparent or black? Let's do transparent background, green wireframe (classic)\n\n // Draw wires\n for (let i = 0; i < indices.length; i += 2) {\n const idx0 = indices[i];\n const idx1 = indices[i+1];\n\n const v0 = vertices[idx0];\n const v1 = vertices[idx1];\n\n const p0 = projectPoint(v0, size, size, center, scale);\n const p1 = projectPoint(v1, size, size, center, scale);\n\n drawLine(buffer, size, size, p0.x, p0.y, p1.x, p1.y, 0, 255, 0, 255);\n }\n\n return new ImageData(buffer, size, size);\n\n } catch (e) {\n console.error(`Failed to generate model thumbnail for ${path}`, e);\n return null;\n }\n }\n\n async getMapBounds(mapName: string, mapData: ArrayBuffer): Promise<BoundingBox | null> {\n try {\n const bsp = parseBsp(mapData);\n // BSP doesn't explicitly store global bounds in header, but we can compute from nodes or models[0] (worldspawn)\n if (bsp.models.length > 0) {\n const world = bsp.models[0];\n return {\n mins: { x: world.mins[0], y: world.mins[1], z: world.mins[2] },\n maxs: { x: world.maxs[0], y: world.maxs[1], z: world.maxs[2] },\n };\n }\n return null;\n } catch (e) {\n console.error('Failed to get map bounds', e);\n return null;\n }\n }\n\n async extractMapScreenshot(mapName: string): Promise<ImageData | null> {\n // Some BSPs (like Q3) have levelshots, Q2 usually relies on external PCX in levelshots/ dir.\n // Rerelease might have something different.\n // If the requirement is \"from embedded levelshots\", Q2 BSP doesn't standardly have them.\n // We'll return null for now as per standard Q2 BSP spec.\n return null;\n }\n}\n","import { BspMap, BspEntity, BspLoader, BspFace } from './bsp.js';\n\nexport interface MapStatistics {\n readonly entityCount: number;\n readonly surfaceCount: number;\n readonly lightmapCount: number;\n readonly vertexCount: number;\n readonly bounds: {\n readonly mins: [number, number, number];\n readonly maxs: [number, number, number];\n };\n}\n\nexport class MapAnalyzer {\n constructor(private readonly loader: BspLoader) {}\n\n async getMapStatistics(mapName: string): Promise<MapStatistics> {\n const map = await this.loader.load(mapName);\n\n // Calculate lightmap count: iterate through faces and count those with valid light offsets\n // Note: Quake 2 BSPs store lightmaps in a single lump, but we can count unique references or total bytes.\n // However, the prompt asks for \"lightmap count\". Faces reference offsets.\n // A standard interpretation is the number of faces that have lightmaps.\n // Or we could try to determine the number of distinct lightmap pages if they were paginated,\n // but here they are just offsets.\n // Let's count faces with lightmaps.\n const lightmapCount = map.faces.filter((f: BspFace) => f.lightOffset !== -1).length;\n\n // Bounds from worldspawn model (model 0)\n const worldModel = map.models[0];\n const bounds = worldModel ? {\n mins: worldModel.mins,\n maxs: worldModel.maxs\n } : {\n mins: [0, 0, 0] as [number, number, number],\n maxs: [0, 0, 0] as [number, number, number]\n };\n\n return {\n entityCount: map.entities.entities.length,\n surfaceCount: map.faces.length,\n lightmapCount,\n vertexCount: map.vertices.length,\n bounds\n };\n }\n\n async getUsedTextures(mapName: string): Promise<string[]> {\n const map = await this.loader.load(mapName);\n const textures = new Set<string>();\n\n // From TexInfo\n for (const info of map.texInfo) {\n if (info.texture) {\n textures.add(info.texture);\n }\n }\n\n return Array.from(textures).sort();\n }\n\n async getUsedModels(mapName: string): Promise<string[]> {\n const map = await this.loader.load(mapName);\n const models = new Set<string>();\n\n for (const ent of map.entities.entities) {\n // Check for 'model' property not starting with * (which are inline models)\n if (ent.properties['model'] && !ent.properties['model'].startsWith('*')) {\n models.add(ent.properties['model']);\n }\n\n // Also check specific entities that might use other keys for models if any?\n // Standard Quake 2 is usually just 'model'.\n // Weapon pickups might have implicit models, but the request implies explicit references in the map data.\n }\n\n return Array.from(models).sort();\n }\n\n async getUsedSounds(mapName: string): Promise<string[]> {\n const map = await this.loader.load(mapName);\n const sounds = new Set<string>();\n\n for (const ent of map.entities.entities) {\n // 'noise' property is commonly used for sounds\n if (ent.properties['noise']) {\n sounds.add(ent.properties['noise']);\n }\n\n // target_speaker uses 'noise'\n // worldspawn might have 'sound'? No, usually not.\n\n // ambient_generic? (Quake 1 / Half-Life, but Quake 2 uses target_speaker)\n\n // func_door/button/etc have 'sound_start', 'sound_stop', etc?\n // Let's check keys ending in 'sound' or 'noise'.\n for (const [key, value] of Object.entries(ent.properties)) {\n if ((key === 'noise' || key.endsWith('_sound') || key === 'sound') && typeof value === 'string') {\n sounds.add(value);\n }\n }\n }\n\n return Array.from(sounds).sort();\n }\n}\n","// ENT file parser/serializer for Quake II\n// Handles parsing of entity lumps in text format (ENT) and serialization back to text.\n\nexport interface EntEntity {\n classname?: string;\n properties: Record<string, string>;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: string[];\n warnings: string[];\n}\n\n/**\n * Parses an ENT entity lump string into an array of entity objects.\n *\n * @param text The ENT file content (string).\n * @returns Array of parsed entities with properties.\n */\nexport function parseEntLump(text: string): EntEntity[] {\n const entities: EntEntity[] = [];\n\n // Clean up comments first: // comments (C style) aren't standard in Q2 ent files but sometimes used in map editors\n // Standard Q2 ent files use \"{\" and \"}\" to delimit entities and \"key\" \"value\" pairs.\n // We'll stick to the standard Q2 format which is loose about whitespace.\n\n let cursor = 0;\n const length = text.length;\n\n // Helper to skip whitespace\n function skipWhitespace() {\n while (cursor < length && /\\s/.test(text[cursor])) {\n cursor++;\n }\n }\n\n // Helper to read a token (quoted string or identifier)\n // Quake 2 parser basically looks for quotes. If no quotes, it might read until whitespace?\n // Actually, standard Q2 parser expects keys and values to be quoted.\n // But let's be robust.\n function readToken(): string | null {\n skipWhitespace();\n if (cursor >= length) return null;\n\n if (text[cursor] === '\"') {\n cursor++; // skip opening quote\n const start = cursor;\n while (cursor < length && text[cursor] !== '\"') {\n // Handle escaped quotes? Quake 2 doesn't really support them standardly but let's see.\n // Q2 source Cmd_TokenizeString handles quotes but doesn't seem to support escapes inside them easily,\n // it just ends at the next quote.\n if (text[cursor] === '\\n') {\n // Newlines inside quotes are generally not allowed or break things, but we'll allow them.\n }\n cursor++;\n }\n const token = text.substring(start, cursor);\n cursor++; // skip closing quote\n return token;\n } else if (text[cursor] === '{' || text[cursor] === '}') {\n // Structural tokens\n return text[cursor++];\n } else {\n // Unquoted token? comments?\n // Some editors support // comments.\n if (text.startsWith('//', cursor)) {\n while (cursor < length && text[cursor] !== '\\n') {\n cursor++;\n }\n return readToken(); // try again after comment\n }\n\n // Read until whitespace\n const start = cursor;\n while (cursor < length && !/\\s/.test(text[cursor]) && text[cursor] !== '}' && text[cursor] !== '{') {\n cursor++;\n }\n return text.substring(start, cursor);\n }\n }\n\n while (cursor < length) {\n const token = readToken();\n if (token === null) break;\n\n if (token === '{') {\n const properties: Record<string, string> = {};\n\n while (true) {\n // Peek or read next token\n // We expect a key (string) or '}'\n\n // We need to implement a peek or just read and handle.\n const originalCursor = cursor;\n const key = readToken();\n\n if (key === '}') {\n break;\n }\n\n if (key === null) {\n // Unexpected end of file inside entity\n break;\n }\n\n if (key === '{') {\n // Nested braces are not allowed, but maybe we should recover?\n // Treat as start of new entity? Error?\n // Q2 parser would probably get confused.\n // We will treat it as a syntax error effectively but let's just continue\n // assuming the previous entity ended.\n cursor = originalCursor; // backtrack to let the outer loop handle '{'\n break;\n }\n\n // Expect value\n const value = readToken();\n if (value === null || value === '}' || value === '{') {\n // Missing value\n if (value === '}') cursor--; // push back\n if (value === '{') cursor--; // push back\n // properties[key] = \"\"; // valid?\n break;\n }\n\n properties[key] = value;\n }\n\n entities.push({\n classname: properties['classname'],\n properties\n });\n }\n }\n\n return entities;\n}\n\n/**\n * Serializes an array of entities to the ENT file format.\n *\n * @param entities Array of entities to serialize.\n * @returns The ENT string.\n */\nexport function serializeEntLump(entities: EntEntity[]): string {\n let output = '';\n\n for (const entity of entities) {\n output += '{\\n';\n\n // Ensure classname is first for readability, though not strictly required\n const keys = Object.keys(entity.properties);\n const sortedKeys = keys.sort((a, b) => {\n if (a === 'classname') return -1;\n if (b === 'classname') return 1;\n if (a === 'origin') return -1;\n if (b === 'origin') return 1;\n return a.localeCompare(b);\n });\n\n for (const key of sortedKeys) {\n const value = entity.properties[key];\n // Escape quotes in value? Q2 doesn't support them well, but let's just escape backslashes and quotes if we were to support it.\n // Standard Q2 maps don't use escapes. We will just dump it.\n // If keys/values contain quotes, it will break.\n output += `\"${key}\" \"${value}\"\\n`;\n }\n\n output += '}\\n';\n }\n\n return output;\n}\n\n/**\n * Validates an entity against basic rules.\n *\n * @param entity The entity to validate.\n * @returns validation result\n */\nexport function validateEntity(entity: EntEntity): ValidationResult {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n if (!entity.properties['classname']) {\n errors.push('Missing \"classname\" property');\n }\n\n // Check origin format if present\n if (entity.properties['origin']) {\n const parts = entity.properties['origin'].split(' ');\n if (parts.length !== 3 || parts.some(p => isNaN(parseFloat(p)))) {\n errors.push(`Invalid origin format: \"${entity.properties['origin']}\"`);\n }\n }\n\n // Check angle format if present\n if (entity.properties['angle']) {\n if (isNaN(parseFloat(entity.properties['angle']))) {\n errors.push(`Invalid angle format: \"${entity.properties['angle']}\"`);\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings\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';\nimport { AssetManager } from './assets/manager.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';\nimport { AudioApi } from './audio/api.js';\n\nexport interface EngineImports {\n trace(start: Vec3, end: Vec3, mins?: Vec3, maxs?: Vec3): TraceResult;\n renderer?: Renderer;\n audio?: AudioApi;\n assets?: AssetManager;\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 { Command, CommandRegistry, type CommandCallback } from './commands.js';\nexport type { FixedStepContext, LoopCallbacks, LoopOptions, RenderContext } from './loop.js';\nexport { PakArchive, PakParseError, calculatePakChecksum } from './assets/pak.js';\nexport { StreamingPakArchive } from './assets/streamingPak.js';\nexport { PakWriter } from './assets/pakWriter.js';\nexport { ResourceLoadTracker, ResourceType, type ResourceLoadLog, type ResourceLoadEntry } from './assets/resourceTracker.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 * from './assets/tga.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, type ActiveSound, type ListenerState } from './audio/system.js';\nexport { createOcclusionResolver, AudioOcclusion, type TraceFn } from './audio/occlusion.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 { DLight, DynamicLightManager } from './render/dlight.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 spawnSplash,\n spawnSteam,\n spawnRailTrail,\n spawnSparks,\n spawnBlasterImpact,\n spawnBfgExplosion,\n type ParticleBlendMode,\n type ParticleEffectContext,\n type ParticleMesh,\n type ParticleRenderOptions,\n type ParticleSimulationOptions,\n type ParticleSpawnOptions,\n type RailTrailContext,\n type SparksContext,\n type BlasterImpactContext,\n} from './render/particleSystem.js';\nexport { Pic, Renderer } from './render/renderer.js';\nexport { FrameRenderStats, FrameRenderOptions, WorldRenderState } from './render/frame.js';\nexport { RenderableEntity } from './render/scene.js'; // Added export\nexport { DemoPlaybackController, PlaybackState, DemoReader, DemoRecorder, NetworkMessageParser } from './demo/index.js';\nexport { DemoValidator, type DemoValidationResult } from './demo/validator.js';\nexport { DemoAnalyzer } from './demo/analyzer.js';\nexport { DemoEventType } from './demo/analysis.js';\nexport { DemoCameraMode } from './demo/camera.js';\nexport type { DemoCameraState } from './demo/camera.js';\nexport { DemoClipper, type WorldState, type ServerDataMessage } from './demo/clipper.js';\nexport type { DemoEvent, EventSummary, DemoHeader, ServerInfo, DemoStatistics, PlayerStatistics, WeaponStatistics, FrameDiff } from './demo/analysis.js';\nexport {\n PROTOCOL_VERSION_RERELEASE,\n createEmptyEntityState,\n createEmptyProtocolPlayerState,\n U_ORIGIN1, U_ORIGIN2, U_ORIGIN3,\n U_ANGLE1, U_ANGLE2, U_ANGLE3,\n U_MODEL, U_MODEL2, U_MODEL3, U_MODEL4,\n U_FRAME8, U_FRAME16,\n U_SKIN8, U_SKIN16,\n U_EFFECTS8, U_EFFECTS16,\n U_RENDERFX8, U_RENDERFX16,\n U_OLDORIGIN,\n U_SOUND,\n U_EVENT,\n U_SOLID,\n U_REMOVE,\n U_ALPHA,\n U_SCALE,\n U_INSTANCE_BITS,\n U_LOOP_VOLUME,\n U_LOOP_ATTENUATION_HIGH,\n U_OWNER_HIGH,\n U_OLD_FRAME_HIGH\n} from './demo/parser.js';\nexport type {\n NetworkMessageHandler,\n EntityState,\n FrameData,\n ProtocolPlayerState,\n FogData,\n DamageIndicator\n} from './demo/parser.js';\nexport { applyEntityDelta } from './demo/delta.js';\nexport { FileType, detectFileType, isTextFile, isBinaryFile } from './assets/fileType.js';\nexport { AssetPreviewGenerator } from './assets/preview.js';\nexport { MapAnalyzer, type MapStatistics } from './assets/mapStatistics.js';\n\n// Export ENT tools\nexport { parseEntLump, serializeEntLump, validateEntity, type EntEntity, type ValidationResult } from './assets/ent.js';\n","import { BinaryStream } from '@quake2ts/shared';\nimport { BspEntity, parseEntLump, serializeEntLump } from '@quake2ts/engine';\n\n/**\n * Replace entity lump in BSP file without recompilation\n * @param bspData Original BSP file\n * @param entities New entity list\n * @returns Modified BSP file\n */\nexport function replaceBspEntities(\n bspData: Uint8Array,\n entities: BspEntity[]\n): Uint8Array {\n // Use BinaryStream which is the exported class from @quake2ts/shared\n\n // Cast buffer to ArrayBuffer to satisfy TS if needed, though Uint8Array.buffer is ArrayBufferLike\n // and BinaryStream accepts ArrayBuffer | Uint8Array.\n // The error says Argument of type 'ArrayBufferLike' is not assignable to 'ArrayBuffer | Uint8Array'.\n // This is because bspData.buffer is ArrayBufferLike (could be SharedArrayBuffer).\n // We can pass the Uint8Array directly.\n const reader = new BinaryStream(bspData);\n\n // Read BSP Header\n const magic = reader.readLong();\n const version = reader.readLong();\n\n if (magic !== 0x50534249 || version !== 38) { // IBSP version 38\n throw new Error('Invalid BSP file');\n }\n\n // Entities lump is index 0\n const LUMP_ENTITIES = 0;\n\n const lumps: { offset: number, length: number }[] = [];\n for (let i = 0; i < 19; i++) {\n lumps.push({\n offset: reader.readLong(),\n length: reader.readLong()\n });\n }\n\n const entitiesLump = lumps[LUMP_ENTITIES];\n\n // Serialize new entities\n const newEntitiesText = serializeEntLump(entities);\n const encoder = new TextEncoder();\n const newEntitiesData = encoder.encode(newEntitiesText);\n\n // Pad with null terminator\n const newEntitiesBuffer = new Uint8Array(newEntitiesData.length + 1);\n newEntitiesBuffer.set(newEntitiesData);\n newEntitiesBuffer[newEntitiesData.length] = 0;\n\n const lengthDiff = newEntitiesBuffer.length - entitiesLump.length;\n\n // Create new BSP buffer\n const newBspLength = bspData.length + lengthDiff;\n const newBsp = new Uint8Array(newBspLength);\n\n // Sorting lumps to handle file layout safely\n\n const entOffset = entitiesLump.offset;\n const entEnd = entOffset + entitiesLump.length;\n\n // Copy everything up to entOffset\n newBsp.set(bspData.subarray(0, entOffset), 0);\n\n // Copy new entity data\n newBsp.set(newEntitiesBuffer, entOffset);\n\n // Copy everything after the old entity lump\n if (entEnd < bspData.length) {\n newBsp.set(bspData.subarray(entEnd), entOffset + newEntitiesBuffer.length);\n }\n\n // Update lump table\n const view = new DataView(newBsp.buffer);\n\n // Update Entities Lump (Index 0)\n view.setInt32(8, entOffset, true);\n view.setInt32(12, newEntitiesBuffer.length, true);\n\n // Update all other lumps that are located after the entities lump\n for (let i = 0; i < 19; i++) {\n if (i === LUMP_ENTITIES) continue;\n\n const originalOffset = lumps[i].offset;\n\n if (originalOffset >= entEnd) {\n // Shift forward/backward\n const newOffset = originalOffset + lengthDiff;\n view.setInt32(4 + 4 + (i * 8), newOffset, true);\n }\n }\n\n return newBsp;\n}\n"],"mappings":"6cAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,GAAA,mBAAAC,GAAA,oBAAAC,GAAA,uBAAAC,KCQO,SAASC,GAAeC,EAAiBC,EAA4B,CAC1E,GAAIA,EAAa,GAAKA,GAAcD,EAAM,OAAO,OAC/C,MAAM,IAAI,MAAM,eAAeC,CAAU,qBAAqBD,EAAM,OAAO,OAAS,CAAC,GAAG,EAG1F,IAAME,EAAQF,EAAM,OAAOC,CAAU,EAC/BE,EAAkB,CAAC,EAEzBA,EAAM,KAAK,6BAA6B,EACxCA,EAAM,KAAK,YAAYH,EAAM,OAAO,SAAS,IAAIA,EAAM,OAAO,UAAU,EAAE,EAC1EG,EAAM,KAAK,YAAYF,CAAU,KAAKC,EAAM,IAAI,GAAG,EACnDC,EAAM,KAAK,KAAKD,EAAM,IAAI,EAAE,EAW5B,QAAWE,KAAKF,EAAM,SACpBC,EAAM,KAAK,KAAKC,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC,IAAIA,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC,IAAIA,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC,EAAE,EAQjG,IAAMC,EAAQL,EAAM,OAAO,UACrBM,EAASN,EAAM,OAAO,WAC5B,QAAWO,KAAMP,EAAM,UAAW,CAChC,IAAMQ,EAAID,EAAG,EAAIF,EACXD,EAAI,EAAOG,EAAG,EAAID,EACxBH,EAAM,KAAK,MAAMK,EAAE,QAAQ,CAAC,CAAC,IAAIJ,EAAE,QAAQ,CAAC,CAAC,EAAE,CACjD,CAIA,QAAWA,KAAKF,EAAM,SACpBC,EAAM,KAAK,MAAMC,E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AQL,EAAO,SAAS,EACxB,OAAQA,EAAO,SAAS,CAC1B,CAAC,EAGH,IAAMO,EAAeF,EAAMD,CAAa,EAGlCI,EAAkBC,GAAiBV,CAAQ,EAE3CW,EADU,IAAI,YAAY,EACA,OAAOF,CAAe,EAGhDG,EAAoB,IAAI,WAAWD,EAAgB,OAAS,CAAC,EACnEC,EAAkB,IAAID,CAAe,EACrCC,EAAkBD,EAAgB,MAAM,EAAI,EAE5C,IAAME,EAAaD,EAAkB,OAASJ,EAAa,OAGrDM,EAAef,EAAQ,OAASc,EAChCE,EAAS,IAAI,WAAWD,CAAY,EAIpCE,EAAYR,EAAa,OACzBS,EAASD,EAAYR,EAAa,OAGxCO,EAAO,IAAIhB,EAAQ,SAAS,EAAGiB,CAAS,EAAG,CAAC,EAG5CD,EAAO,IAAIH,EAAmBI,CAAS,EAGnCC,EAASlB,EAAQ,QACjBgB,EAAO,IAAIhB,EAAQ,SAASkB,CAAM,EAAGD,EAAYJ,EAAkB,MAAM,EAI7E,IAAMM,EAAO,IAAI,SAASH,EAAO,MAAM,EAGvCG,EAAK,SAAS,EAAGF,EAAW,EAAI,EAChCE,EAAK,SAAS,GAAIN,EAAkB,OAAQ,EAAI,EAGhD,QAASL,EAAI,EAAGA,EAAI,GAAIA,IAAK,CAC3B,GAAIA,IAAMF,EAAe,SAEzB,IAAMc,EAAiBb,EAAMC,CAAC,EAAE,OAEhC,GAAIY,GAAkBF,EAAQ,CAE5B,IAAMG,EAAYD,EAAiBN,EACnCK,EAAK,SAAS,EAASX,EAAI,EAAIa,EAAW,EAAI,CAChD,CACF,CAEA,OAAOL,CACT,C1LzFO,SAASM,GAAcC,EAAcC,EAA6B,CACvE,MAAO,CAAE,KAAAD,EAAM,OAAAC,CAAO,CACxB","names":["src_exports","__export","describeAsset","exportMd2ToObj","exportMd3ToGltf","replaceBspEntities","exportMd2ToObj","model","frameIndex","frame","lines","v","width","height","tc","u","tri","v1","v2","v3","vt1","vt2","vt3","vn1","vn2","vn3","exportMd3ToGltf","gltf","binaryData","addBufferView","data","target","byteOffset","alignedOffset","i","byteLength","viewIndex","addAccessor","bufferView","componentType","count","type","min","max","index","acc","surface","frameVerts","positions","normals","texCoords","minPos","maxPos","indices","posView","normView","tcView","idxView","posAcc","normAcc","tcAcc","idxAcc","DEG_TO_RAD","DEG2RAD_FACTOR","RAD2DEG_FACTOR","ANORMS","CONTENTS_SOLID","CONTENTS_WINDOW","CONTENTS_LAVA","CONTENTS_SLIME","CONTENTS_WATER","CONTENTS_PROJECTILECLIP","CONTENTS_PLAYERCLIP","CONTENTS_MONSTERCLIP","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","CONTENTS_ORIGIN","CONTENTS_MONSTER","CONTENTS_DEADMONSTER","CONTENTS_DETAIL","CONTENTS_TRANSLUCENT","CONTENTS_LADDER","CONTENTS_PLAYER","CONTENTS_PROJECTILE","SURF_ALPHATEST","SURF_N64_UV","SURF_N64_SCROLL_X","SURF_N64_SCROLL_Y","SURF_N64_SCROLL_FLIP","MASK_SOLID","CONTENTS_SOLID","CONTENTS_WINDOW","MASK_PLAYERSOLID","CONTENTS_PLAYERCLIP","CONTENTS_MONSTER","CONTENTS_PLAYER","MASK_DEADSOLID","MASK_MONSTERSOLID","CONTENTS_MONSTERCLIP","MASK_WATER","CONTENTS_WATER","CONTENTS_LAVA","CONTENTS_SLIME","MASK_OPAQUE","MASK_SHOT","CONTENTS_DEADMONSTER","MASK_CURRENT","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","MASK_BLOCK_SIGHT","MASK_NAV_SOLID","MASK_LADDER_NAV_SOLID","MASK_WALK_NAV_SOLID","MASK_PROJECTILE","CONTENTS_PROJECTILECLIP","MAX_CHECKCOUNT","MAX_CLIENTS","MAX_LIGHTSTYLES","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_ITEMS","MAX_GENERAL","MAX_CLIENTS","MAX_SHADOW_LIGHTS","MAX_WHEEL_ITEMS","ConfigStringIndex","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_LIGHTSTYLES","MAX_SHADOW_LIGHTS","MAX_ITEMS","MAX_CLIENTS","MAX_GENERAL","MAX_WHEEL_ITEMS","MAX_CONFIGSTRINGS","CS_SOUNDS","ConfigStringIndex","CS_IMAGES","CS_LIGHTS","CS_ITEMS","CS_PLAYERS","CS_GENERAL","replay_exports","__export","addReplayFrame","createReplaySession","deserializeReplay","serializeReplay","session","json","map","seed","cmd","serverFrame","startTime","AMMO_MAX","NUM_BITS_FOR_AMMO","NUM_AMMO_STATS","POWERUP_MAX","NUM_BITS_FOR_POWERUP","NUM_POWERUP_STATS","U_FRAME16","U_RENDERFX16","U_EFFECTS16","U_MODEL2","U_MODEL3","U_MODEL4","U_MOREBITS3","U_OLDORIGIN","U_SKIN16","U_SOUND","U_SOLID","U_SCALE","U_INSTANCE_BITS","U_LOOP_VOLUME","BinaryStream","buffer","position","count","value","str","charCode","length","data","out","b","norm","ANORMS","BinaryWriter","sizeOrBuffer","bytes","newSize","newBuffer","len","i","pos","dir","maxDot","bestIndex","dot","_NetChan","BinaryWriter","now","qport","address","unreliableData","sendReliableLength","isFragment","fragmentStart","headerSize","reliableHeaderSize","unreliableSize","buffer","view","result","sequence","ack","offset","lengthField","reliableBytes","chunk","packet","seqNumberClean","ackNumber","ackReliable","receivedAckBit","currentReliableBit","hasReliableData","reliableSeqBit","payloadOffset","reliableData","reliableLen","expectedBit","fragStart","fragTotal","data","totalLen","value","len","currentTime","timeoutMs","AmmoType","AMMO_TYPE_COUNT","DEG_TO_RAD","DEG2RAD_FACTOR","RAD2DEG_FACTOR","ANORMS","CONTENTS_SOLID","CONTENTS_WINDOW","CONTENTS_LAVA","CONTENTS_SLIME","CONTENTS_WATER","CONTENTS_PROJECTILECLIP","CONTENTS_PLAYERCLIP","CONTENTS_MONSTERCLIP","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","CONTENTS_ORIGIN","CONTENTS_MONSTER","CONTENTS_DEADMONSTER","CONTENTS_DETAIL","CONTENTS_TRANSLUCENT","CONTENTS_LADDER","CONTENTS_PLAYER","CONTENTS_PROJECTILE","SURF_ALPHATEST","SURF_N64_UV","SURF_N64_SCROLL_X","SURF_N64_SCROLL_Y","SURF_N64_SCROLL_FLIP","MASK_SOLID","CONTENTS_SOLID","CONTENTS_WINDOW","MASK_PLAYERSOLID","CONTENTS_PLAYERCLIP","CONTENTS_MONSTER","CONTENTS_PLAYER","MASK_DEADSOLID","MASK_MONSTERSOLID","CONTENTS_MONSTERCLIP","MASK_WATER","CONTENTS_WATER","CONTENTS_LAVA","CONTENTS_SLIME","MASK_OPAQUE","MASK_SHOT","CONTENTS_DEADMONSTER","MASK_CURRENT","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","MASK_BLOCK_SIGHT","MASK_NAV_SOLID","MASK_LADDER_NAV_SOLID","MASK_WALK_NAV_SOLID","MASK_PROJECTILE","CONTENTS_PROJECTILECLIP","MAX_CHECKCOUNT","MAX_CLIENTS","MAX_LIGHTSTYLES","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_ITEMS","MAX_GENERAL","MAX_SHADOW_LIGHTS","MAX_WHEEL_ITEMS","ConfigStringIndex","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_LIGHTSTYLES","MAX_SHADOW_LIGHTS","MAX_ITEMS","MAX_CLIENTS","MAX_GENERAL","MAX_WHEEL_ITEMS","MAX_CONFIGSTRINGS","CS_SOUNDS","ConfigStringIndex","CS_IMAGES","CS_LIGHTS","CS_ITEMS","CS_PLAYERS","CS_GENERAL","replay_exports","__export","addReplayFrame","createReplaySession","deserializeReplay","serializeReplay","session","json","map","seed","cmd","serverFrame","startTime","ServerCommand","AMMO_MAX","NUM_BITS_FOR_AMMO","NUM_AMMO_STATS","POWERUP_MAX","NUM_BITS_FOR_POWERUP","NUM_POWERUP_STATS","U_FRAME16","U_RENDERFX16","U_EFFECTS16","U_MODEL2","U_MODEL3","U_MODEL4","U_MOREBITS3","U_OLDORIGIN","U_SKIN16","U_SOUND","U_SOLID","U_SCALE","U_INSTANCE_BITS","U_LOOP_VOLUME","BinaryWriter","sizeOrBuffer","bytes","newSize","newBuffer","value","data","len","i","pos","dir","maxDot","bestIndex","ANORMS","norm","dot","_NetChan","now","qport","address","unreliableData","sendReliableLength","isFragment","fragmentStart","headerSize","reliableHeaderSize","unreliableSize","buffer","view","result","sequence","ack","offset","lengthField","reliableBytes","chunk","packet","seqNumberClean","ackNumber","ackReliable","receivedAckBit","currentReliableBit","hasReliableData","reliableSeqBit","payloadOffset","reliableData","reliableLen","expectedBit","fragStart","fragTotal","totalLen","currentTime","timeoutMs","AmmoType","AMMO_TYPE_COUNT","createCrcTable","table","i","crc","j","CRC_TABLE","RERELEASE_KNOWN_PAKS","HEADER_LUMPS","HEADER_SIZE","FLOAT_BYTES","STRIDE","BSP_VERTEX_LAYOUT","MAX_DLIGHTS","BSP_SURFACE_FRAGMENT_SOURCE","MAX_DLIGHTS","SKYBOX_POSITIONS","MD2_VERTEX_SHADER","MAX_DLIGHTS","EPSILON","ARRAY_TYPE","RANDOM","round","a","degree","radian","mat4_exports","__export","add","adjoint","clone","copy","create","decompose","determinant","equals","exactEquals","frob","fromQuat","fromQuat2","fromRotation","fromRotationTranslation","fromRotationTranslationScale","fromRotationTranslationScaleOrigin","fromScaling","fromTranslation","fromValues","fromXRotation","fromYRotation","fromZRotation","frustum","getRotation","getScaling","getTranslation","identity","invert","lookAt","mul","multiply","multiplyScalar","multiplyScalarAndAdd","ortho","orthoNO","orthoZO","perspective","perspectiveFromFieldOfView","perspectiveNO","perspectiveZO","rotate","rotateX","rotateY","rotateZ","scale","set","str","sub","subtract","targetTo","translate","transpose","out","m00","m01","m02","m03","m10","m11","m12","m13","m20","m21","m22","m23","m30","m31","m32","m33","a01","a02","a03","a12","a13","a23","a00","a10","a11","a20","a21","a22","a30","a31","a32","a33","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","det","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b","v","x","y","z","rad","axis","len","s","c","t","b12","b20","b21","b22","q","w","x2","y2","z2","xx","xy","xz","yy","yz","zz","wx","wy","wz","translation","bx","by","bz","bw","ax","ay","az","aw","magnitude","mat","scaling","is1","is2","is3","sm11","sm12","sm13","sm21","sm22","sm23","sm31","sm32","sm33","trace","S","out_r","out_t","out_s","sx","sy","sz","o","ox","oy","oz","out0","out1","out2","out4","out5","out6","out8","out9","out10","yx","zx","zy","left","right","bottom","top","near","far","rl","tb","nf","fovy","aspect","f","fov","upTan","downTan","leftTan","rightTan","xScale","yScale","lr","bt","eye","center","up","x0","x1","y0","y1","z0","z1","eyex","eyey","eyez","upx","upy","upz","centerx","centery","centerz","target","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","a14","a15","b13","b14","b15","vec3_exports","angle","bezier","ceil","cross","dist","distance","div","divide","dot","floor","forEach","hermite","inverse","length","lerp","max","min","negate","normalize","random","scaleAndAdd","slerp","sqrDist","sqrLen","squaredDistance","squaredLength","transformMat3","transformMat4","transformQuat","zero","sinTotal","ratioA","ratioB","d","factorTimes2","factor1","factor2","factor3","factor4","inverseFactor","inverseFactorTimesTwo","r","zScale","m","qx","qy","qz","qw","vx","vy","vz","tx","ty","tz","p","mag","cosine","vec","stride","offset","count","fn","arg","i","l","Z_FIXED$1","Z_BINARY","Z_TEXT","Z_UNKNOWN$1","zero$1","buf","len","STORED_BLOCK","STATIC_TREES","DYN_TREES","MIN_MATCH$1","MAX_MATCH$1","LENGTH_CODES$1","LITERALS$1","L_CODES$1","D_CODES$1","BL_CODES$1","HEAP_SIZE$1","MAX_BITS$1","Buf_size","MAX_BL_BITS","END_BLOCK","REP_3_6","REPZ_3_10","REPZ_11_138","extra_lbits","extra_dbits","extra_blbits","bl_order","DIST_CODE_LEN","static_ltree","static_dtree","_dist_code","_length_code","base_length","base_dist","StaticTreeDesc","static_tree","extra_bits","extra_base","elems","max_length","static_l_desc","static_d_desc","static_bl_desc","TreeDesc","dyn_tree","stat_desc","d_code","dist","put_short","s","w","send_bits","value","length","send_code","c","tree","bi_reverse","code","res","bi_flush","gen_bitlen","desc","max_code","stree","has_stree","extra","base","h","n","m","bits","xbits","f","overflow","gen_codes","bl_count","next_code","tr_static_init","init_block","bi_windup","smaller","depth","_n2","_m2","pqdownheap","k","v","j","compress_block","ltree","dtree","lc","sx","build_tree","node","scan_tree","prevlen","curlen","nextlen","count","max_count","min_count","send_tree","build_bl_tree","max_blindex","send_all_trees","lcodes","dcodes","blcodes","rank","detect_data_type","block_mask","static_init_done","_tr_init$1","_tr_stored_block$1","stored_len","last","_tr_align$1","_tr_flush_block$1","opt_lenb","static_lenb","_tr_tally$1","_tr_init_1","_tr_stored_block_1","_tr_flush_block_1","_tr_tally_1","_tr_align_1","trees","adler32","adler","pos","s1","s2","adler32_1","makeTable","table","crcTable","crc32","crc","t","end","i","crc32_1","messages","constants$2","_tr_init","_tr_stored_block","_tr_flush_block","_tr_tally","_tr_align","Z_NO_FLUSH$2","Z_PARTIAL_FLUSH","Z_FULL_FLUSH$1","Z_FINISH$3","Z_BLOCK$1","Z_OK$3","Z_STREAM_END$3","Z_STREAM_ERROR$2","Z_DATA_ERROR$2","Z_BUF_ERROR$1","Z_DEFAULT_COMPRESSION$1","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_DEFAULT_STRATEGY$1","Z_UNKNOWN","Z_DEFLATED$2","MAX_MEM_LEVEL","MAX_WBITS$1","DEF_MEM_LEVEL","LENGTH_CODES","LITERALS","L_CODES","D_CODES","BL_CODES","HEAP_SIZE","MAX_BITS","MIN_MATCH","MAX_MATCH","MIN_LOOKAHEAD","PRESET_DICT","INIT_STATE","GZIP_STATE","EXTRA_STATE","NAME_STATE","COMMENT_STATE","HCRC_STATE","BUSY_STATE","FINISH_STATE","BS_NEED_MORE","BS_BLOCK_DONE","BS_FINISH_STARTED","BS_FINISH_DONE","OS_CODE","err","strm","errorCode","zero","slide_hash","p","wsize","HASH_ZLIB","prev","data","HASH","flush_pending","flush_block_only","put_byte","b","putShortMSB","read_buf","start","size","longest_match","cur_match","chain_length","scan","match","best_len","nice_match","limit","_win","wmask","strend","scan_end1","scan_end","fill_window","_w_size","more","str","deflate_stored","flush","min_block","left","have","used","deflate_fast","hash_head","bflush","deflate_slow","max_insert","deflate_rle","deflate_huff","Config","good_length","max_lazy","nice_length","max_chain","func","configuration_table","lm_init","DeflateState","deflateStateCheck","deflateResetKeep","deflateReset","ret","deflateSetHeader","head","deflateInit2","level","method","windowBits","memLevel","strategy","wrap","deflateInit","deflate$2","old_flush","header","level_flags","beg","copy","gzhead_extra","val","bstate","deflateEnd","status","deflateSetDictionary","dictionary","dictLength","tmpDict","avail","next","input","deflateInit_1","deflateInit2_1","deflateReset_1","deflateResetKeep_1","deflateSetHeader_1","deflate_2$1","deflateEnd_1","deflateSetDictionary_1","deflateInfo","deflate_1$2","_has","obj","key","assign","sources","source","flattenChunks","chunks","l","result","chunk","common","STR_APPLY_UIA_OK","_utf8len","q","string2buf","c2","m_pos","str_len","buf_len","buf2binstring","buf2string","max","out","utf16buf","c_len","utf8border","strings","ZStream","zstream","toString$1","Z_NO_FLUSH$1","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH$2","Z_OK$2","Z_STREAM_END$2","Z_DEFAULT_COMPRESSION","Z_DEFAULT_STRATEGY","Z_DEFLATED$1","Deflate$1","options","opt","dict","flush_mode","chunkSize","_flush_mode","deflate$1","deflator","deflateRaw$1","gzip$1","Deflate_1$1","deflate_2","deflateRaw_1$1","gzip_1$1","constants$1","deflate_1$1","BAD$1","TYPE$1","inffast","_in","_out","dmax","whave","wnext","s_window","hold","lcode","dcode","lmask","dmask","here","op","from","from_source","output","state","top","dolen","dodist","MAXBITS","ENOUGH_LENS$1","ENOUGH_DISTS$1","CODES$1","LENS$1","DISTS$1","lbase","lext","dbase","dext","inflate_table","type","lens","lens_index","codes","table_index","work","opts","sym","min","root","curr","drop","huff","incr","fill","low","mask","offs","here_bits","here_op","here_val","inftrees","CODES","LENS","DISTS","Z_FINISH$1","Z_BLOCK","Z_TREES","Z_OK$1","Z_STREAM_END$1","Z_NEED_DICT$1","Z_STREAM_ERROR$1","Z_DATA_ERROR$1","Z_MEM_ERROR$1","Z_BUF_ERROR","Z_DEFLATED","HEAD","FLAGS","TIME","OS","EXLEN","EXTRA","NAME","COMMENT","HCRC","DICTID","DICT","TYPE","TYPEDO","STORED","COPY_","COPY","TABLE","LENLENS","CODELENS","LEN_","LEN","LENEXT","DIST","DISTEXT","MATCH","LIT","CHECK","LENGTH","DONE","BAD","MEM","SYNC","ENOUGH_LENS","ENOUGH_DISTS","MAX_WBITS","DEF_WBITS","zswap32","InflateState","inflateStateCheck","inflateResetKeep","inflateReset","inflateReset2","inflateInit2","inflateInit","virgin","lenfix","distfix","fixedtables","updatewindow","src","inflate$2","put","last_bits","last_op","last_val","hbuf","order","inf_leave","inflateEnd","inflateGetHeader","inflateSetDictionary","dictid","inflateReset_1","inflateReset2_1","inflateResetKeep_1","inflateInit_1","inflateInit2_1","inflate_2$1","inflateEnd_1","inflateGetHeader_1","inflateSetDictionary_1","inflateInfo","inflate_1$2","GZheader","gzheader","toString","Z_NO_FLUSH","Z_FINISH","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_STREAM_ERROR","Z_DATA_ERROR","Z_MEM_ERROR","Inflate$1","last_avail_out","next_out_utf8","tail","utf8str","inflate$1","inflator","inflateRaw$1","Inflate_1$1","inflate_2","inflateRaw_1$1","ungzip$1","constants","inflate_1$1","Deflate","deflate","deflateRaw","gzip","Inflate","inflate","inflateRaw","ungzip","_StreamingBuffer","initialCapacity","data","bytes","requiredSize","count","value","val","maxLength","length","position","newSize","newBuffer","unreadBytes","U_FRAME16","U_RENDERFX16","U_EFFECTS16","U_MODEL2","U_MODEL3","U_MODEL4","U_MOREBITS3","U_OLDORIGIN","U_SKIN16","U_SOUND","U_SOLID","U_SCALE","U_INSTANCE_BITS","U_LOOP_VOLUME","PROTO34_MAP","ServerCommand","PROTO34_REVERSE_MAP","ServerCommand","serializeEntLump","entities","output","entity","sortedKeys","a","b","key","value","replaceBspEntities","bspData","entities","reader","BinaryStream","magic","version","LUMP_ENTITIES","lumps","i","entitiesLump","newEntitiesText","serializeEntLump","newEntitiesData","newEntitiesBuffer","lengthDiff","newBspLength","newBsp","entOffset","entEnd","view","originalOffset","newOffset","describeAsset","name","origin"]}
|