Split The code is public; the app answers only to the crew.
Utility, part one: a grenade you can throw, and an HE that hurts #47
Check · Review · Land · Live done — Landed and live in production.
vesper/cs:vesper/36-utility-part-one-a-grenade-you-can-throw → main 2 commits fork 1 thread · 1 unresolved
16 files
changed +866
−47
README.md +20 −3
| @@ -50,7 +50,20 @@ wants one, but the running server never reads it. | ||
| 50 | 50 | one already, <kbd>E</kbd> swaps, and the gun you were holding lands at your |
| 51 | 51 | feet. There is no team rule: a CT who finds an AK-47 keeps it. The floor is |
| 52 | 52 | swept at the start of the next round, and whatever you are carrying then comes |
| 53 | back with a full magazine. Hit feedback runs both ways: a hit marker and a beep when you hit | |
| 53 | back with a full magazine. There is one piece of utility: an **HE grenade**, | |
| 54 | $300 in the buy menu, one in a pocket at a time. <kbd>4</kbd> puts it in your | |
| 55 | hand and fire throws it — out of your eye, a little above where you are | |
| 56 | looking, carrying whatever speed you were already running at. It falls under | |
| 57 | the same 800 u/s² the rest of the game does, bounces off walls and crates | |
| 58 | keeping 45% of the speed it hit them with, and goes off **1.6 seconds** after | |
| 59 | it left your hand wherever it is by then. The blast is **98 damage at its | |
| 60 | centre, falling linearly to nothing at 350 units**, halved by armour (which | |
| 61 | takes half of what it stops), and it does nothing at all through a wall — the | |
| 62 | same sight line a bot sees you with, its centre to your eye. It cannot hurt | |
| 63 | your own side, and it can very much kill you. A grenade thrown is gone; one | |
| 64 | kept is still yours next round, the same rule the guns follow. The bots do not | |
| 65 | buy or throw one: their fight was learned in an arena that has no grenades in | |
| 66 | it, and they keep buying guns. Hit feedback runs both ways: a hit marker and a beep when you hit | |
| 54 | 67 | someone, and when you are hit a view punch away from the shot, a wedge around |
| 55 | 68 | the crosshair pointing at whoever fired, a vignette that reddens as your health |
| 56 | 69 | falls and a pain sound. Every world sound is panned around the listener's |
| @@ -82,7 +95,9 @@ wants one, but the running server never reads it. | ||
| 82 | 95 | <kbd>Q</kbd> scopes on the AWP, <kbd>R</kbd> reload, |
| 83 | 96 | <kbd>E</kbd> plants, defuses or takes the gun you are standing on (the HUD says |
| 84 | 97 | which gun when it is one you have to ask for), <kbd>B</kbd> opens the buy menu in the freeze |
| 85 | time, <kbd>1</kbd>/<kbd>2</kbd>/<kbd>3</kbd> switch guns, <kbd>Tab</kbd> shows | |
| 98 | time, <kbd>1</kbd>/<kbd>2</kbd>/<kbd>3</kbd> switch guns and <kbd>4</kbd> takes | |
| 99 | out the HE grenade if you bought one (fire throws it, and the hand goes back to | |
| 100 | the gun once it is gone), <kbd>Tab</kbd> shows | |
| 86 | 101 | the scoreboard, <kbd>Esc</kbd> pauses. Pausing also opens mute, volume and |
| 87 | 102 | look sensitivity, which take effect at once and are remembered for next time. |
| 88 | 103 | |
| @@ -96,6 +111,7 @@ On a touch screen the same actions are a pad, and the view is the aim: | ||
| 96 | 111 | | scope (AWP only) | right click or <kbd>Q</kbd> | `scope`, held like the mouse | |
| 97 | 112 | | crouch, jump, use, reload | <kbd>Ctrl</kbd> <kbd>Space</kbd> <kbd>E</kbd> <kbd>R</kbd> | the pad under the view | |
| 98 | 113 | | guns | <kbd>1</kbd>/<kbd>2</kbd>/<kbd>3</kbd> | `1 rifle`, `2 pistol`, `3 knife` | |
| 114 | | grenade | <kbd>4</kbd>, then fire | `4 nade`, then the fire bar | | |
| 99 | 115 | | scoreboard | <kbd>Tab</kbd> | hold `scores` | |
| 100 | 116 | | buy | <kbd>B</kbd> | `buy`, and `Close` when you are done | |
| 101 | 117 | | pause, leave the match, or change mute/volume/sensitivity | <kbd>Esc</kbd> | `menu` | |
| @@ -134,7 +150,8 @@ with the canvas as you turn; nobody re-walks the grid to draw it. | ||
| 134 | 150 | ## Shape |
| 135 | 151 | |
| 136 | 152 | - `src/client/` — the game, in modules named for one thing each: `math`, `map`, |
| 137 | `physics`, `weapons`, `combat`, `match` (the rules), `world` (the simulation), | |
| 153 | `physics`, `weapons`, `combat`, `grenades` (a thrown thing's flight: gravity, | |
| 154 | bounce, fuse and how far a blast reaches), `match` (the rules), `world` (the simulation), | |
| 138 | 155 | `bots`, `plan` (which site a side commits to, and when the carrier has run out |
| 139 | 156 | of clock), `observe`, `action`, `policy`, `weights`, `models`, `textures`, |
| 140 | 157 | `press` (the input latch), `quality` (the render scale the frame time buys), |
src/client/audio.ts +70
| @@ -11,6 +11,10 @@ import { WEAPONS, type WeaponId } from "./weapons.ts"; | ||
| 11 | 11 | export type Audio = { |
| 12 | 12 | shot(weapon: WeaponId, at: Vec3, listener: Vec3, listenerYaw: number): void; |
| 13 | 13 | step(at: Vec3, listener: Vec3, listenerYaw: number): void; |
| 14 | /** A grenade hitting something: a short hard tick, panned like everything else. */ | |
| 15 | bounce(at: Vec3, listener: Vec3, listenerYaw: number): void; | |
| 16 | /** A grenade going off: a low boom under a long crack of noise. */ | |
| 17 | blast(at: Vec3, listener: Vec3, listenerYaw: number): void; | |
| 14 | 18 | hit(headshot: boolean): void; |
| 15 | 19 | pain(amount: number): void; |
| 16 | 20 | beep(pitch: number, gain?: number): void; |
| @@ -135,6 +139,72 @@ export function createAudio(): Audio { | ||
| 135 | 139 | source.start(now); |
| 136 | 140 | source.stop(now + length); |
| 137 | 141 | }, |
| 142 | /** A grenade off a wall: a tick of filtered noise, shorter than a footstep. */ | |
| 143 | bounce(at, listener, listenerYaw) { | |
| 144 | if (muted) return; | |
| 145 | const live = ensure(); | |
| 146 | if (live === null) return; | |
| 147 | const { ctx: context, noise, master } = live; | |
| 148 | const { pan, volume } = ears(at, listener, listenerYaw); | |
| 149 | const now = context.currentTime; | |
| 150 | const length = 0.07; | |
| 151 | const source = context.createBufferSource(); | |
| 152 | source.buffer = noise; | |
| 153 | source.playbackRate.value = 1.4 + Math.random() * 0.3; | |
| 154 | const filter = context.createBiquadFilter(); | |
| 155 | filter.type = "bandpass"; | |
| 156 | filter.frequency.value = 1700; | |
| 157 | filter.Q.value = 2.4; | |
| 158 | const gain = context.createGain(); | |
| 159 | gain.gain.setValueAtTime(0.11 * volume, now); | |
| 160 | gain.gain.exponentialRampToValueAtTime(0.0008, now + length); | |
| 161 | const panner = context.createStereoPanner(); | |
| 162 | panner.pan.value = pan; | |
| 163 | source.connect(filter).connect(gain).connect(panner).connect(master); | |
| 164 | source.start(now); | |
| 165 | source.stop(now + length); | |
| 166 | }, | |
| 167 | /** | |
| 168 | * The blast: a sine falling through two octaves for the punch in the | |
| 169 | * chest, and a long low-passed tail of noise over it for the debris. | |
| 170 | */ | |
| 171 | blast(at, listener, listenerYaw) { | |
| 172 | if (muted) return; | |
| 173 | const live = ensure(); | |
| 174 | if (live === null) return; | |
| 175 | const { ctx: context, noise, master } = live; | |
| 176 | const { pan, volume } = ears(at, listener, listenerYaw); | |
| 177 | const now = context.currentTime; | |
| 178 | const length = 0.8; | |
| 179 | const panner = context.createStereoPanner(); | |
| 180 | panner.pan.value = pan; | |
| 181 | panner.connect(master); | |
| 182 | ||
| 183 | const boom = context.createOscillator(); | |
| 184 | boom.type = "sine"; | |
| 185 | boom.frequency.setValueAtTime(140, now); | |
| 186 | boom.frequency.exponentialRampToValueAtTime(32, now + length * 0.7); | |
| 187 | const boomGain = context.createGain(); | |
| 188 | boomGain.gain.setValueAtTime(0.5 * volume, now); | |
| 189 | boomGain.gain.exponentialRampToValueAtTime(0.0008, now + length); | |
| 190 | boom.connect(boomGain).connect(panner); | |
| 191 | boom.start(now); | |
| 192 | boom.stop(now + length); | |
| 193 | ||
| 194 | const tail = context.createBufferSource(); | |
| 195 | tail.buffer = noise; | |
| 196 | tail.playbackRate.value = 0.8; | |
| 197 | const filter = context.createBiquadFilter(); | |
| 198 | filter.type = "lowpass"; | |
| 199 | filter.frequency.setValueAtTime(3200, now); | |
| 200 | filter.frequency.exponentialRampToValueAtTime(220, now + length); | |
| 201 | const tailGain = context.createGain(); | |
| 202 | tailGain.gain.setValueAtTime(0.4 * volume, now); | |
| 203 | tailGain.gain.exponentialRampToValueAtTime(0.0008, now + length); | |
| 204 | tail.connect(filter).connect(tailGain).connect(panner); | |
| 205 | tail.start(now); | |
| 206 | tail.stop(now + length); | |
| 207 | }, | |
| 138 | 208 | hit(headshot) { |
| 139 | 209 | audio.beep(headshot ? 1400 : 900, 0.08); |
| 140 | 210 | }, |
src/client/grenades.test.ts added +117
| @@ -0,0 +1,117 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { blastDamage, blastFalloff, GRENADE, step, thrown, type Grenade } from "./grenades.ts"; | |
| 3 | import * as map from "./map.ts"; | |
| 4 | import type { Box } from "./map.ts"; | |
| 5 | import type { Vec3 } from "./math.ts"; | |
| 6 | ||
| 7 | const TICK = 1 / 64; | |
| 8 | const FLOOR: Box[] = [{ min: [-10000, -10000, -64], max: [10000, 10000, 0], mat: 0 }]; | |
| 9 | ||
| 10 | /** Step `g` for `seconds`, stopping at the tick its fuse runs out. */ | |
| 11 | const fly = (g: Grenade, seconds: number, boxes: Box[]): number => { | |
| 12 | let bounces = 0; | |
| 13 | for (let t = 0; t < seconds; t += TICK) { | |
| 14 | const { bounced, detonated } = step(g, TICK, boxes); | |
| 15 | if (bounced) bounces += 1; | |
| 16 | if (detonated) break; | |
| 17 | } | |
| 18 | return bounces; | |
| 19 | }; | |
| 20 | ||
| 21 | test("a flat throw falls like a thrown thing: the range the numbers say", () => { | |
| 22 | // Thrown level — the pitch cancels the lift the throw adds — from 200 units | |
| 23 | // up over a floor at zero. It is a projectile from there: it should land | |
| 24 | // v·√(2h/g) away, the same answer as the back of an envelope. | |
| 25 | const from: Vec3 = [0, 0, 200]; | |
| 26 | const g = thrown(0, "t", from, 0, GRENADE.throwLift, [0, 0, 0]); | |
| 27 | const drop = (g.pos[2] as number) - GRENADE.radius; | |
| 28 | const expected = GRENADE.throwSpeed * Math.sqrt((2 * drop) / GRENADE.gravity); | |
| 29 | ||
| 30 | let landed = 0; | |
| 31 | for (let t = 0; t < 2; t += TICK) { | |
| 32 | const before = g.pos[2] as number; | |
| 33 | step(g, TICK, FLOOR); | |
| 34 | if ((g.pos[2] as number) <= GRENADE.radius + 0.01 && before > GRENADE.radius + 0.01) { | |
| 35 | landed = g.pos[0] as number; | |
| 36 | break; | |
| 37 | } | |
| 38 | } | |
| 39 | expect(landed).toBeGreaterThan(expected * 0.95); | |
| 40 | expect(landed).toBeLessThan(expected * 1.05); | |
| 41 | expect(Math.abs(g.pos[1] as number)).toBeLessThan(1); // straight ahead, +x | |
| 42 | }); | |
| 43 | ||
| 44 | test("the thrower's own speed goes with it: running throws further", () => { | |
| 45 | const still = thrown(0, "t", [0, 0, 200], 0, GRENADE.throwLift, [0, 0, 0]); | |
| 46 | const running = thrown(0, "t", [0, 0, 200], 0, GRENADE.throwLift, [250, 0, 0]); | |
| 47 | fly(still, 0.5, FLOOR); | |
| 48 | fly(running, 0.5, FLOOR); | |
| 49 | expect(running.pos[0] as number).toBeGreaterThan((still.pos[0] as number) + 100); | |
| 50 | }); | |
| 51 | ||
| 52 | test("a wall bounces it back, slower, and it never ends up inside one", () => { | |
| 53 | const wall: Box[] = [...FLOOR, { min: [300, -500, 0], max: [340, 500, 400], mat: 0 }]; | |
| 54 | const g = thrown(0, "t", [0, 0, 64], 0, 0, [0, 0, 0]); | |
| 55 | const bounces = fly(g, GRENADE.fuse, wall); | |
| 56 | expect(bounces).toBeGreaterThan(0); | |
| 57 | expect(g.pos[0] as number).toBeLessThan(300); | |
| 58 | expect(Math.hypot(g.vel[0], g.vel[1], g.vel[2])).toBeLessThan(GRENADE.throwSpeed); | |
| 59 | // Out of the wall and above the floor, by its own radius, wherever it ended. | |
| 60 | expect(g.pos[0] as number).toBeLessThanOrEqual(300 - GRENADE.radius + 0.001); | |
| 61 | expect(g.pos[2] as number).toBeGreaterThanOrEqual(GRENADE.radius - 0.001); | |
| 62 | }); | |
| 63 | ||
| 64 | test("thrown at a wall of de_forge it stays in the map and comes to rest", () => { | |
| 65 | const at = map.spawns.t[0] as Vec3; | |
| 66 | const eye: Vec3 = [at[0], at[1], 64]; | |
| 67 | // Eight directions from a spawn, hard: none of them may put it outside. | |
| 68 | for (let i = 0; i < 8; i++) { | |
| 69 | const g = thrown(0, "t", eye, i * 45, -20, [0, 0, 0]); | |
| 70 | fly(g, GRENADE.fuse, map.boxes); | |
| 71 | expect(Number.isFinite(g.pos[0]) && Number.isFinite(g.pos[2])).toBe(true); | |
| 72 | expect(map.walkable(map.colOf(g.pos[0] as number), map.rowOf(g.pos[1] as number))).toBe(true); | |
| 73 | expect(g.pos[2] as number).toBeGreaterThan(0); | |
| 74 | expect(g.pos[2] as number).toBeLessThan(map.WALL_HEIGHT); | |
| 75 | } | |
| 76 | }); | |
| 77 | ||
| 78 | test("a grenade dropped on the floor stops instead of trembling on it", () => { | |
| 79 | const g: Grenade = { kind: "he", owner: 0, team: "t", pos: [0, 0, 120], vel: [0, 0, 0], fuse: 5 }; | |
| 80 | fly(g, 1.5, FLOOR); | |
| 81 | expect(g.vel).toEqual([0, 0, 0]); | |
| 82 | expect(g.pos[2]).toBeCloseTo(GRENADE.radius, 6); | |
| 83 | }); | |
| 84 | ||
| 85 | test("the fuse runs on the clock: nothing before 1.6s, and then it goes", () => { | |
| 86 | const g = thrown(0, "t", [0, 0, 64], 0, 0, [0, 0, 0]); | |
| 87 | let fired = -1; | |
| 88 | for (let i = 0; i < 200; i++) { | |
| 89 | if (step(g, TICK, FLOOR).detonated) { fired = i; break; } | |
| 90 | } | |
| 91 | expect(fired).toBeGreaterThanOrEqual(Math.floor(GRENADE.fuse / TICK) - 1); | |
| 92 | expect(fired).toBeLessThanOrEqual(Math.ceil(GRENADE.fuse / TICK)); | |
| 93 | }); | |
| 94 | ||
| 95 | test("a hard hit sounds and a settling one does not", () => { | |
| 96 | const fast: Grenade = { kind: "he", owner: 0, team: "t", pos: [0, 0, 60], vel: [0, 0, -400], fuse: 5 }; | |
| 97 | expect(fly(fast, 0.25, FLOOR)).toBeGreaterThan(0); | |
| 98 | const settled: Grenade = { kind: "he", owner: 0, team: "t", pos: [0, 0, GRENADE.radius], vel: [0, 0, 0], fuse: 5 }; | |
| 99 | for (let i = 0; i < 10; i++) expect(step(settled, TICK, FLOOR).bounced).toBe(false); | |
| 100 | }); | |
| 101 | ||
| 102 | test("damage is full at the centre, nothing at the radius, and armour halves it", () => { | |
| 103 | expect(blastFalloff(0)).toBe(1); | |
| 104 | expect(blastFalloff(GRENADE.blastRadius)).toBe(0); | |
| 105 | const centre = blastDamage(0, 0).health; | |
| 106 | const middle = blastDamage(GRENADE.blastRadius / 2, 0).health; | |
| 107 | const edge = blastDamage(GRENADE.blastRadius, 0).health; | |
| 108 | expect(centre).toBeGreaterThan(90); | |
| 109 | expect(middle).toBeLessThan(centre); | |
| 110 | expect(middle).toBeGreaterThan(edge); | |
| 111 | expect(edge).toBe(0); | |
| 112 | expect(blastDamage(GRENADE.blastRadius * 2, 0).health).toBe(0); | |
| 113 | ||
| 114 | const armoured = blastDamage(0, 100); | |
| 115 | expect(armoured.health).toBeLessThan(centre * 0.6); | |
| 116 | expect(armoured.armor).toBeGreaterThan(0); | |
| 117 | }); |
src/client/grenades.ts added +145
| @@ -0,0 +1,145 @@ | ||
| 1 | /** | |
| 2 | * A thrown object's flight, and nothing else: it leaves a hand with a velocity, | |
| 3 | * falls under the same gravity a player does, bounces off the world losing | |
| 4 | * speed each time, comes to rest, and its fuse runs out wherever it is by then. | |
| 5 | * | |
| 6 | * There is no WebGL, no audio and no HUD here — `world.ts` steps these and | |
| 7 | * decides what a detonation means — so a throw can be checked in a test by | |
| 8 | * reading three numbers, which is the only way to know a grenade lands where | |
| 9 | * the arc says it does. | |
| 10 | * | |
| 11 | * A grenade is a ball of `GRENADE.radius`, not a hull: it is resolved out of | |
| 12 | * whatever box it ended up inside along the shallowest face, and reflects off | |
| 13 | * that face. One ball against fifty boxes a tick, and only while one is in the | |
| 14 | * air, so nothing here is on the path of a round that never buys one. | |
| 15 | */ | |
| 16 | ||
| 17 | import type { Box } from "./map.ts"; | |
| 18 | import { angleVectors, clamp, type Vec3 } from "./math.ts"; | |
| 19 | import { armorSplit, WEAPONS } from "./weapons.ts"; | |
| 20 | ||
| 21 | export type Grenade = { | |
| 22 | kind: "he"; | |
| 23 | owner: number; // the player id who threw it; the blast is credited to them | |
| 24 | team: "t" | "ct"; // their side when it left the hand, for friendly fire | |
| 25 | pos: Vec3; | |
| 26 | vel: Vec3; | |
| 27 | fuse: number; // seconds left, counted down every step | |
| 28 | }; | |
| 29 | ||
| 30 | export const GRENADE = { | |
| 31 | radius: 4, // the ball the world is resolved against | |
| 32 | gravity: 800, // the same gravity a player falls under | |
| 33 | bounce: 0.45, // the share of the speed into a surface that comes back out | |
| 34 | friction: 0.75, // the share of the speed along it that survives the hit | |
| 35 | rest: 50, // below this, a grenade against a floor stops dead | |
| 36 | fuse: 1.6, // seconds from the hand to the bang, whatever it hit on the way | |
| 37 | throwSpeed: 780, // u/s out of the hand, before the thrower's own velocity | |
| 38 | throwLift: 12, // degrees above where you are looking | |
| 39 | throwFrom: 18, // units in front of the eye it appears | |
| 40 | blastRadius: 350, // where the damage has fallen to nothing | |
| 41 | /** A bounce softer than this is a grenade settling, not a wall being hit. */ | |
| 42 | bounceSound: 90, | |
| 43 | }; | |
| 44 | ||
| 45 | /** What one step did, for the caller that owns sound and damage. */ | |
| 46 | export type Step = { bounced: boolean; detonated: boolean }; | |
| 47 | ||
| 48 | /** What the world did to a grenade this step: the hardest hit, and a floor. */ | |
| 49 | type Contact = { into: number; floor: boolean }; | |
| 50 | ||
| 51 | /** | |
| 52 | * Push `g` out of `box` along the face it is least far through and reflect it | |
| 53 | * off that face, recording the speed it went in with. A grenade that is not | |
| 54 | * inside the box at all costs three comparisons and nothing else. | |
| 55 | */ | |
| 56 | function resolve(g: Grenade, box: Box, contact: Contact): void { | |
| 57 | const r = GRENADE.radius; | |
| 58 | let axis = 0, sign = 0, depth = Infinity; | |
| 59 | for (let i = 0; i < 3; i++) { | |
| 60 | const above = (g.pos[i] as number) - r - (box.max[i] as number); // clear of the far face | |
| 61 | const below = (box.min[i] as number) - (g.pos[i] as number) - r; // clear of the near one | |
| 62 | if (above >= 0 || below >= 0) return; | |
| 63 | if (-above < depth) { depth = -above; axis = i; sign = 1; } | |
| 64 | if (-below < depth) { depth = -below; axis = i; sign = -1; } | |
| 65 | } | |
| 66 | g.pos[axis] += depth * sign; | |
| 67 | if (axis === 2 && sign === 1) contact.floor = true; | |
| 68 | const into = -(g.vel[axis] as number) * sign; | |
| 69 | if (into <= 0) return; // it was already leaving; the push-out is enough | |
| 70 | if (into > contact.into) contact.into = into; | |
| 71 | g.vel[axis] = (g.vel[axis] as number) * -GRENADE.bounce; | |
| 72 | for (let i = 0; i < 3; i++) if (i !== axis) g.vel[i] = (g.vel[i] as number) * GRENADE.friction; | |
| 73 | } | |
| 74 | ||
| 75 | /** | |
| 76 | * One tick of flight: gravity, the move, then the world. The fuse runs on the | |
| 77 | * clock and not on what it hit, so `detonated` is true exactly once — the | |
| 78 | * caller drops the grenade from its list when it sees it. | |
| 79 | */ | |
| 80 | export function step(g: Grenade, dt: number, boxes: Box[]): Step { | |
| 81 | g.fuse -= dt; | |
| 82 | g.vel[2] -= GRENADE.gravity * dt; | |
| 83 | g.pos[0] += (g.vel[0] as number) * dt; | |
| 84 | g.pos[1] += (g.vel[1] as number) * dt; | |
| 85 | g.pos[2] += (g.vel[2] as number) * dt; | |
| 86 | ||
| 87 | const contact: Contact = { into: 0, floor: false }; | |
| 88 | for (const box of boxes) resolve(g, box, contact); | |
| 89 | // A grenade rolling out of speed on a floor stops, rather than trembling on | |
| 90 | // it for the rest of the fuse: gravity would give it a new hop every tick. | |
| 91 | if (contact.floor && Math.hypot(g.vel[0], g.vel[1], g.vel[2]) < GRENADE.rest) { | |
| 92 | g.vel[0] = 0; | |
| 93 | g.vel[1] = 0; | |
| 94 | g.vel[2] = 0; | |
| 95 | } | |
| 96 | return { bounced: contact.into >= GRENADE.bounceSound, detonated: g.fuse <= 0 }; | |
| 97 | } | |
| 98 | ||
| 99 | /** | |
| 100 | * A grenade leaving `eye`: forward along the view, lifted a little so it | |
| 101 | * arcs rather than sliding along the floor, with the thrower's own velocity | |
| 102 | * added — running out of a doorway throws it further than standing does. | |
| 103 | */ | |
| 104 | export function thrown( | |
| 105 | owner: number, | |
| 106 | team: "t" | "ct", | |
| 107 | eye: Vec3, | |
| 108 | yaw: number, | |
| 109 | pitch: number, | |
| 110 | velocity: Vec3, | |
| 111 | ): Grenade { | |
| 112 | // Pitch is positive downwards, so lifting the throw subtracts from it. | |
| 113 | const dir = angleVectors(yaw, pitch - GRENADE.throwLift).forward; | |
| 114 | return { | |
| 115 | kind: "he", | |
| 116 | owner, | |
| 117 | team, | |
| 118 | pos: [ | |
| 119 | eye[0] + dir[0] * GRENADE.throwFrom, | |
| 120 | eye[1] + dir[1] * GRENADE.throwFrom, | |
| 121 | eye[2] + dir[2] * GRENADE.throwFrom, | |
| 122 | ], | |
| 123 | vel: [ | |
| 124 | dir[0] * GRENADE.throwSpeed + velocity[0], | |
| 125 | dir[1] * GRENADE.throwSpeed + velocity[1], | |
| 126 | dir[2] * GRENADE.throwSpeed + velocity[2], | |
| 127 | ], | |
| 128 | fuse: GRENADE.fuse, | |
| 129 | }; | |
| 130 | } | |
| 131 | ||
| 132 | /** The share of a blast something `distance` from its centre takes: 1 to 0. */ | |
| 133 | export const blastFalloff = (distance: number): number => | |
| 134 | clamp(1 - distance / GRENADE.blastRadius, 0, 1); | |
| 135 | ||
| 136 | /** | |
| 137 | * What a blast `distance` away costs someone wearing `armor`. Full at the | |
| 138 | * centre, nothing at the radius, and armour takes its share the way it does | |
| 139 | * off a bullet — a vest is worth about half an HE. | |
| 140 | */ | |
| 141 | export function blastDamage(distance: number, armor: number): { health: number; armor: number } { | |
| 142 | const damage = WEAPONS.he.damage * blastFalloff(distance); | |
| 143 | if (armor <= 0 || damage <= 0) return { health: Math.round(damage), armor: 0 }; | |
| 144 | return armorSplit(damage, armor, WEAPONS.he.armorPenetration); | |
| 145 | } |
src/client/hud.test.ts +24
| @@ -235,3 +235,27 @@ test("the radar sits in the bottom-left corner and labels both sites", () => { | ||
| 235 | 235 | ); |
| 236 | 236 | expect(border).toBeDefined(); |
| 237 | 237 | }); |
| 238 | ||
| 239 | test("the HUD says what is in the pocket, and counts it where the ammo goes", () => { | |
| 240 | const world = createWorld(SHORT, "me", "ct", 5, 97); | |
| 241 | world.me.grenades = 1; | |
| 242 | const carrying = recorder(); | |
| 243 | draw(carrying, world); | |
| 244 | const texts = (r: { calls: Call[] }): string[] => | |
| 245 | r.calls.filter((c) => c.name === "fillText").map((c) => c.text); | |
| 246 | expect(texts(carrying).some((t) => t.startsWith("HE ×1"))).toBe(true); | |
| 247 | ||
| 248 | // Held, the count is what the magazine would have said, under its name. | |
| 249 | world.me.weapon = "he"; | |
| 250 | const held = recorder(); | |
| 251 | draw(held, world); | |
| 252 | expect(texts(held)).toContain("×1"); | |
| 253 | expect(texts(held)).toContain("HE Grenade"); | |
| 254 | ||
| 255 | // With none, neither line is there to read. | |
| 256 | world.me.grenades = 0; | |
| 257 | world.me.weapon = world.me.secondary; | |
| 258 | const without = recorder(); | |
| 259 | draw(without, world); | |
| 260 | expect(without.calls.some((c) => c.text.includes("HE"))).toBe(false); | |
| 261 | }); |
src/client/hud.ts +14 −3
| @@ -321,10 +321,18 @@ export function drawHud( | ||
| 321 | 321 | ctx.fillStyle = "#7ddc8a"; |
| 322 | 322 | ctx.font = mid; |
| 323 | 323 | ctx.fillText(`$${view.money}`, pad, pad + Math.round(18 * scale)); |
| 324 | ctx.font = small; | |
| 325 | let carried = pad + Math.round(38 * scale); | |
| 324 | 326 | if (view.team === "ct" && view.defuseKit) { |
| 325 | 327 | ctx.fillStyle = "#9fd0ff"; |
| 326 | ctx.font = small; | |
| 327 | ctx.fillText("defuse kit", pad, pad + Math.round(38 * scale)); | |
| 328 | ctx.fillText("defuse kit", pad, carried); | |
| 329 | carried += Math.round(20 * scale); | |
| 330 | } | |
| 331 | // What is in the pocket, whether or not it is in the hands: a grenade you | |
| 332 | // forgot you bought is a grenade you never threw. | |
| 333 | if (view.grenades > 0) { | |
| 334 | ctx.fillStyle = "#c8e6a0"; | |
| 335 | ctx.fillText(`HE ×${view.grenades} · 4`, pad, carried); | |
| 328 | 336 | } |
| 329 | 337 | |
| 330 | 338 | // --- ammo and weapon |
| @@ -332,7 +340,10 @@ export function drawHud( | ||
| 332 | 340 | ctx.font = big; |
| 333 | 341 | ctx.fillStyle = "#f3f5f8"; |
| 334 | 342 | const ammo = view.ammo[weapon.id]; |
| 335 | const ammoText = weapon.magazine === 0 ? "—" : `${ammo?.mag ?? 0} / ${ammo?.reserve ?? 0}`; | |
| 343 | // A grenade counts what is left in the pocket where a gun counts its magazine. | |
| 344 | const ammoText = weapon.kind === "grenade" | |
| 345 | ? `×${view.grenades}` | |
| 346 | : weapon.magazine === 0 ? "—" : `${ammo?.mag ?? 0} / ${ammo?.reserve ?? 0}`; | |
| 336 | 347 | ctx.fillText(ammoText, width - pad, height - pad); |
| 337 | 348 | ctx.font = small; |
| 338 | 349 | ctx.fillStyle = "#c8ccd4"; |
src/client/input.test.ts +2 −2
| @@ -176,13 +176,13 @@ test("the menu button pauses without pointer lock", () => { | ||
| 176 | 176 | |
| 177 | 177 | test("the pad's slot, scoreboard and buy buttons are the keyboard's actions", () => { |
| 178 | 178 | const { controls } = harness(); |
| 179 | const buttons = pad("slot1", "slot2", "slot3", "scoreboard", "buy"); | |
| 179 | const buttons = pad("slot1", "slot2", "slot3", "slot4", "scoreboard", "buy"); | |
| 180 | 180 | attachButtons(buttons.root, controls); |
| 181 | 181 | let buys = 0; |
| 182 | 182 | controls.onBuy = () => { buys += 1; }; |
| 183 | 183 | |
| 184 | 184 | expect(controls.slotWanted).toBe(null); |
| 185 | for (const [action, slot] of [["slot1", 1], ["slot2", 2], ["slot3", 3]] as const) { | |
| 185 | for (const [action, slot] of [["slot1", 1], ["slot2", 2], ["slot3", 3], ["slot4", 4]] as const) { | |
| 186 | 186 | buttons.press(action); |
| 187 | 187 | expect(controls.slotWanted).toBe(slot); |
| 188 | 188 | buttons.release(action); |
src/client/input.ts +6 −4
| @@ -26,7 +26,8 @@ export type Controls = { | ||
| 26 | 26 | /** The Input for one step of a taken frame. The object is reused. */ |
| 27 | 27 | inputAt(frame: Frame, step: number): Input; |
| 28 | 28 | readonly scoreboard: boolean; |
| 29 | readonly slotWanted: 1 | 2 | 3 | null; // 1 primary, 2 pistol, 3 knife — main knows what they are | |
| 29 | /** 1 primary, 2 pistol, 3 knife, 4 grenade — main knows what they are. */ | |
| 30 | readonly slotWanted: 1 | 2 | 3 | 4 | null; | |
| 30 | 31 | sensitivity: number; |
| 31 | 32 | locked: boolean; |
| 32 | 33 | setAction(action: string, down: boolean): void; |
| @@ -40,7 +41,7 @@ const KEY_ACTIONS: Record<string, string> = { | ||
| 40 | 41 | ArrowUp: "forward", ArrowDown: "back", ArrowLeft: "left", ArrowRight: "right", |
| 41 | 42 | Space: "jump", ControlLeft: "duck", KeyC: "duck", ShiftLeft: "walk", |
| 42 | 43 | KeyR: "reload", KeyE: "use", KeyB: "buy", Tab: "scoreboard", KeyQ: "scope", |
| 43 | Digit1: "slot1", Digit2: "slot2", Digit3: "slot3", | |
| 44 | Digit1: "slot1", Digit2: "slot2", Digit3: "slot3", Digit4: "slot4", | |
| 44 | 45 | }; |
| 45 | 46 | |
| 46 | 47 | export function createControls(canvas: HTMLCanvasElement, sensitivity = 2.2): Controls { |
| @@ -74,8 +75,9 @@ export function createControls(canvas: HTMLCanvasElement, sensitivity = 2.2): Co | ||
| 74 | 75 | get scoreboard(): boolean { |
| 75 | 76 | return press.isDown("scoreboard"); |
| 76 | 77 | }, |
| 77 | get slotWanted(): 1 | 2 | 3 | null { | |
| 78 | return press.isDown("slot3") ? 3 : press.isDown("slot2") ? 2 : press.isDown("slot1") ? 1 : null; | |
| 78 | get slotWanted(): 1 | 2 | 3 | 4 | null { | |
| 79 | return press.isDown("slot4") ? 4 : press.isDown("slot3") ? 3 | |
| 80 | : press.isDown("slot2") ? 2 : press.isDown("slot1") ? 1 : null; | |
| 79 | 81 | }, |
| 80 | 82 | sensitivity, |
| 81 | 83 | locked: false, |
src/client/main.ts +12 −4
| @@ -18,7 +18,8 @@ import { nextWatched, watched } from "./spectate.ts"; | ||
| 18 | 18 | import { summarize, type MatchSummary } from "./summary.ts"; |
| 19 | 19 | import { buyable } from "./weapons.ts"; |
| 20 | 20 | import { |
| 21 | buy, canBuy, createWorld, eyePos, flinch, priceOf, update, type BuyItem, type Player, type World, | |
| 21 | buy, canBuy, canBuyItem, createWorld, eyePos, flinch, priceOf, update, | |
| 22 | type BuyItem, type Player, type World, | |
| 22 | 23 | } from "./world.ts"; |
| 23 | 24 | |
| 24 | 25 | const TICK = 1 / 64; |
| @@ -162,7 +163,7 @@ function boot(): void { | ||
| 162 | 163 | const button = document.createElement("button"); |
| 163 | 164 | button.type = "button"; |
| 164 | 165 | button.textContent = `${label} · $${price}`; |
| 165 | button.disabled = price > me.money || !canBuy(world, me); | |
| 166 | button.disabled = !canBuyItem(world, me, item); | |
| 166 | 167 | button.addEventListener("click", () => { |
| 167 | 168 | if (world === null) return; |
| 168 | 169 | if (buy(world, world.me, item)) audio.beep(700, 0.05); |
| @@ -304,8 +305,12 @@ function boot(): void { | ||
| 304 | 305 | else if (effect.kind === "hurt" && effect.victim === current.me.id) { |
| 305 | 306 | flinch(current.me, effect.from, effect.amount); |
| 306 | 307 | audio.pain(effect.amount); |
| 307 | } else if (effect.kind === "sound" && effect.name === "step" && dist(effect.pos, at) <= FOOTSTEP_EARSHOT) { | |
| 308 | audio.step(effect.pos, at, ears.yaw); | |
| 308 | } else if (effect.kind === "sound") { | |
| 309 | // A footstep is a room away at the most; a grenade is heard across the | |
| 310 | // map, which is the point of one landing behind you. | |
| 311 | if (effect.name === "step" && dist(effect.pos, at) <= FOOTSTEP_EARSHOT) audio.step(effect.pos, at, ears.yaw); | |
| 312 | else if (effect.name === "bounce") audio.bounce(effect.pos, at, ears.yaw); | |
| 313 | else if (effect.name === "blast") audio.blast(effect.pos, at, ears.yaw); | |
| 309 | 314 | } |
| 310 | 315 | } |
| 311 | 316 | lastSound = current.time; |
| @@ -330,7 +335,10 @@ function boot(): void { | ||
| 330 | 335 | me.yaw -= dx; |
| 331 | 336 | me.pitch = clamp(me.pitch + dy, -89, 89); |
| 332 | 337 | } |
| 338 | // Slot 4 is asked for whether or not there is a grenade in the pocket; the | |
| 339 | // world is the one that says no, so the rule lives in one place. | |
| 333 | 340 | const switchTo = |
| 341 | controls.slotWanted === 4 ? "he" : | |
| 334 | 342 | controls.slotWanted === 3 ? "knife" : |
| 335 | 343 | controls.slotWanted === 2 ? me.secondary : |
| 336 | 344 | controls.slotWanted === 1 ? me.primary : null; |
src/client/models.ts +21
| @@ -115,6 +115,20 @@ export function pickupMesh(): Mesh { | ||
| 115 | 115 | return finish(b); |
| 116 | 116 | } |
| 117 | 117 | |
| 118 | /** | |
| 119 | * A grenade in the world, around its own centre: a body with a spoon down one | |
| 120 | * side, small enough to be a grenade and big enough to follow through the air. | |
| 121 | * It is drawn spinning, so the spoon is what says it is turning at all. | |
| 122 | */ | |
| 123 | export function grenadeMesh(): Mesh { | |
| 124 | const b = builder(); | |
| 125 | const GEAR = 7, KIT = 6; | |
| 126 | cube(b, 0, 0, 0, 7, 7, 9, GEAR); // the body | |
| 127 | cube(b, 0, 0, 5.5, 4, 4, 2.5, KIT); // the fuse on top | |
| 128 | cube(b, 4, 0, 1, 1.5, 2, 7, KIT); // the spoon down one side | |
| 129 | return finish(b); | |
| 130 | } | |
| 131 | ||
| 118 | 132 | /** |
| 119 | 133 | * A first-person weapon, in view space: X right, Y up, Z back, so the barrel |
| 120 | 134 | * runs down -Z and the model needs no rotation at all. |
| @@ -122,6 +136,13 @@ export function pickupMesh(): Mesh { | ||
| 122 | 136 | export function viewModelMesh(kind: string): Mesh { |
| 123 | 137 | const b = builder(); |
| 124 | 138 | const GUN = 7, GRIP = 6; |
| 139 | if (kind === "grenade") { | |
| 140 | // Held out in front, not aimed: a fist with a grenade in it. | |
| 141 | cube(b, 0.5, -0.8, -1.1, 0.34, 0.34, 0.44, GUN); | |
| 142 | cube(b, 0.5, -0.66, -1.1, 0.2, 0.16, 0.12, GRIP); | |
| 143 | cube(b, 0.5, -1.05, -0.7, 0.3, 0.32, 0.5, GRIP); | |
| 144 | return finish(b); | |
| 145 | } | |
| 125 | 146 | if (kind === "knife") { |
| 126 | 147 | cube(b, 0.7, -0.7, -1.6, 0.12, 0.5, 1.6, GUN); |
| 127 | 148 | cube(b, 0.7, -0.95, -0.5, 0.2, 0.34, 0.7, GRIP); |
src/client/renderer.test.ts +19
| @@ -108,3 +108,22 @@ test("a body is one more draw of the same mesh, and no body is no cost at all", | ||
| 108 | 108 | expect(programs).toBeLessThanOrEqual(2); |
| 109 | 109 | expect(uploads).toBe(0); |
| 110 | 110 | }); |
| 111 | ||
| 112 | test("a grenade in the air is one more draw, off a mesh uploaded before the frame", () => { | |
| 113 | const { canvas, calls } = recorder(); | |
| 114 | const world = scene(); | |
| 115 | const empty = frame(canvas, calls, world, world.me).length; | |
| 116 | world.grenades.push({ | |
| 117 | kind: "he", owner: world.me.id, team: world.me.team, | |
| 118 | pos: [64, 0, 40], vel: [300, 0, 120], fuse: 1.2, | |
| 119 | }); | |
| 120 | const flying = frame(canvas, calls, world, world.me); | |
| 121 | expect(flying.length).toBe(empty + 1); | |
| 122 | // Its mesh is built with the others when the renderer is made, so a grenade | |
| 123 | // appearing mid-round costs a matrix and a draw and not an upload. | |
| 124 | expect(calls.filter((c) => c.name === "bufferData").length).toBe(0); | |
| 125 | ||
| 126 | // And a round that never throws one pays nothing for the loop at all. | |
| 127 | world.grenades.length = 0; | |
| 128 | expect(frame(canvas, calls, world, world.me).length).toBe(empty); | |
| 129 | }); |
src/client/renderer.ts +15 −1
| @@ -6,7 +6,9 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import { fallenMatrix, multiply, perspective, viewMatrix, modelMatrix, type Vec3 } from "./math.ts"; |
| 9 | import { bombMesh, levelMesh, pickupMesh, playerMesh, viewModelMesh, type Mesh } from "./models.ts"; | |
| 9 | import { | |
| 10 | bombMesh, grenadeMesh, levelMesh, pickupMesh, playerMesh, viewModelMesh, type Mesh, | |
| 11 | } from "./models.ts"; | |
| 10 | 12 | import { MAX_SCALE, MIN_SCALE } from "./quality.ts"; |
| 11 | 13 | import { LAYERS, TEX_SIZE, materialTextures } from "./textures.ts"; |
| 12 | 14 | import type { Player, World } from "./world.ts"; |
| @@ -194,6 +196,7 @@ export function createRenderer(canvas: HTMLCanvasElement): Renderer | null { | ||
| 194 | 196 | const player = upload(gl, playerMesh()); |
| 195 | 197 | const bomb = upload(gl, bombMesh()); |
| 196 | 198 | const pickup = upload(gl, pickupMesh()); |
| 199 | const grenade = upload(gl, grenadeMesh()); | |
| 197 | 200 | const viewModels = new Map<string, Buffers>(); |
| 198 | 201 | |
| 199 | 202 | // One buffer for every line drawn this frame: tracers, sparks, the bomb beam. |
| @@ -303,6 +306,17 @@ export function createRenderer(canvas: HTMLCanvasElement): Renderer | null { | ||
| 303 | 306 | } |
| 304 | 307 | } |
| 305 | 308 | |
| 309 | // Grenades in the air, tumbling as they go — a thrown object you cannot | |
| 310 | // see land is one nobody can play around. | |
| 311 | if (world.grenades.length > 0) { | |
| 312 | gl.uniform3f(u.tint, 0.8, 0.95, 0.72); | |
| 313 | gl.bindVertexArray(grenade.vao); | |
| 314 | for (const g of world.grenades) { | |
| 315 | gl.uniformMatrix4fv(u.model, false, modelMatrix(g.pos, world.time * 520)); | |
| 316 | gl.drawElements(gl.TRIANGLES, grenade.count, gl.UNSIGNED_INT, 0); | |
| 317 | } | |
| 318 | } | |
| 319 | ||
| 306 | 320 | if (world.bomb.state === "planted" || world.bomb.state === "dropped") { |
| 307 | 321 | gl.uniformMatrix4fv(u.model, false, modelMatrix(world.bomb.pos, 0)); |
| 308 | 322 | gl.uniform3f(u.tint, 1, 1, 1); |
src/client/weapons.ts +28 −9
| @@ -11,12 +11,12 @@ | ||
| 11 | 11 | import { rng } from "./math.ts"; |
| 12 | 12 | |
| 13 | 13 | export type WeaponId = |
| 14 | | "knife" | "glock" | "usp" | "deagle" | "mp9" | "ak47" | "m4a4" | "awp"; | |
| 14 | | "knife" | "glock" | "usp" | "deagle" | "mp9" | "ak47" | "m4a4" | "awp" | "he"; | |
| 15 | 15 | |
| 16 | 16 | export type Weapon = { |
| 17 | 17 | id: WeaponId; |
| 18 | 18 | name: string; |
| 19 | kind: "knife" | "pistol" | "smg" | "rifle" | "sniper"; | |
| 19 | kind: "knife" | "pistol" | "smg" | "rifle" | "sniper" | "grenade"; | |
| 20 | 20 | team: "t" | "ct" | "both"; |
| 21 | 21 | price: number; |
| 22 | 22 | damage: number; |
| @@ -44,6 +44,11 @@ const WEAPON_LIST: Weapon[] = [ | ||
| 44 | 44 | { id: "ak47", name: "AK-47", kind: "rifle", team: "t", price: 2700, damage: 36, armorPenetration: 0.775, rangeModifier: 0.98, rpm: 600, magazine: 30, reserve: 90, reloadTime: 2.5, killReward: 300, carrySpeed: 215, spread: 0.16, moveSpread: 3.4, recoil: 1.5, automatic: true }, |
| 45 | 45 | { id: "m4a4", name: "M4A4", kind: "rifle", team: "ct", price: 3100, damage: 33, armorPenetration: 0.7, rangeModifier: 0.97, rpm: 666, magazine: 30, reserve: 90, reloadTime: 3.1, killReward: 300, carrySpeed: 225, spread: 0.15, moveSpread: 3.2, recoil: 1.25, automatic: true }, |
| 46 | 46 | { id: "awp", name: "AWP", kind: "sniper", team: "both", price: 4750, damage: 115, armorPenetration: 0.975, rangeModifier: 0.99, rpm: 41, magazine: 10, reserve: 30, reloadTime: 3.7, killReward: 100, carrySpeed: 200, spread: 0.05, moveSpread: 12, recoil: 3.5, zoom: 40, automatic: false }, |
| 47 | // Thrown, not fired: the rate is the hand's, `damage` is what the blast does | |
| 48 | // at its centre, and how far that reaches is grenades.ts's business. It goes | |
| 49 | // last because a weapon's spray pattern is seeded from its place in this | |
| 50 | // list, and every gun above it already has the pattern people have learned. | |
| 51 | { id: "he", name: "HE Grenade", kind: "grenade", team: "both", price: 300, damage: 98, armorPenetration: 0.5, rangeModifier: 1, rpm: 120, magazine: 0, reserve: 0, reloadTime: 0, killReward: 300, carrySpeed: 245, spread: 0, moveSpread: 0, recoil: 0, automatic: false }, | |
| 47 | 52 | ]; |
| 48 | 53 | |
| 49 | 54 | export const WEAPONS: Record<WeaponId, Weapon> = Object.fromEntries( |
| @@ -108,6 +113,26 @@ export function inaccuracy(weapon: Weapon, state: Accuracy): number { | ||
| 108 | 113 | export const HITGROUP = { head: 4, chest: 1, stomach: 1.25, arm: 1, leg: 0.75 } as const; |
| 109 | 114 | export type Hitgroup = keyof typeof HITGROUP; |
| 110 | 115 | |
| 116 | /** | |
| 117 | * What armour leaves of a hit it protects against: `penetration` of the damage | |
| 118 | * goes through to health, armour takes half of what it stopped, and a vest | |
| 119 | * with less left than that stops only what it has. A blast asks this the same | |
| 120 | * way a bullet does, which is why it is out here and not inside computeDamage. | |
| 121 | */ | |
| 122 | export function armorSplit( | |
| 123 | damage: number, | |
| 124 | armor: number, | |
| 125 | penetration: number, | |
| 126 | ): { health: number; armor: number } { | |
| 127 | let health = damage * penetration; | |
| 128 | let armorDamage = (damage - health) * 0.5; | |
| 129 | if (armorDamage > armor) { | |
| 130 | armorDamage = armor; | |
| 131 | health = damage - armor * 2; | |
| 132 | } | |
| 133 | return { health: Math.max(0, Math.round(health)), armor: Math.round(armorDamage) }; | |
| 134 | } | |
| 135 | ||
| 111 | 136 | /** |
| 112 | 137 | * CS's damage sum: range falloff, then the hitgroup, then armour. Armour takes |
| 113 | 138 | * half of what it stops; a helmet is the only thing that helps a headshot. |
| @@ -123,11 +148,5 @@ export function computeDamage( | ||
| 123 | 148 | damage *= HITGROUP[group]; |
| 124 | 149 | const protectedHere = armor > 0 && (group !== "head" || helmet) && group !== "leg"; |
| 125 | 150 | if (!protectedHere) return { health: Math.round(damage), armor: 0 }; |
| 126 | let health = damage * weapon.armorPenetration; | |
| 127 | let armorDamage = (damage - health) * 0.5; | |
| 128 | if (armorDamage > armor) { | |
| 129 | armorDamage = armor; | |
| 130 | health = damage - armor * 2; | |
| 131 | } | |
| 132 | return { health: Math.max(0, Math.round(health)), armor: Math.round(armorDamage) }; | |
| 151 | return armorSplit(damage, armor, weapon.armorPenetration); | |
| 133 | 152 | } |
src/client/world.test.ts +222
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { expect, test } from "bun:test"; |
| 2 | import { GRENADE } from "./grenades.ts"; | |
| 2 | 3 | import { siteAt, sites } from "./map.ts"; |
| 3 | 4 | import { SHORT } from "./match.ts"; |
| 4 | 5 | import { WEAPONS } from "./weapons.ts"; |
| @@ -430,3 +431,224 @@ test("a match plays itself to the end inside its own time", () => { | ||
| 430 | 431 | expect(world.match.matchWinner).not.toBe(null); |
| 431 | 432 | expect(Math.max(world.match.score.t, world.match.score.ct)).toBe(2); |
| 432 | 433 | }); |
| 434 | ||
| 435 | /** | |
| 436 | * Grenades. The buy, the slot, the throw and the blast — stepped through | |
| 437 | * `update` the way a round steps them, so the fuse, the kill feed and the | |
| 438 | * round's end are the real ones and not a fixture's. | |
| 439 | */ | |
| 440 | ||
| 441 | /** The person, on an empty map in a live round, with a grenade in the pocket. */ | |
| 442 | function armWithGrenade(world: World): void { | |
| 443 | world.boxes = []; | |
| 444 | world.match.phase = "live"; | |
| 445 | world.me.pos = [0, 0, 0]; | |
| 446 | world.me.vel = [0, 0, 0]; | |
| 447 | world.me.yaw = 0; | |
| 448 | world.me.pitch = 0; | |
| 449 | world.me.grenades = 1; | |
| 450 | world.me.nextShotAt = 0; | |
| 451 | world.effects.length = 0; | |
| 452 | } | |
| 453 | ||
| 454 | /** Put a grenade about to go off at `pos`, thrown by `thrower`, and step once. */ | |
| 455 | function blastAt(world: World, thrower: Player, pos: [number, number, number]): void { | |
| 456 | world.grenades.push({ | |
| 457 | kind: "he", owner: thrower.id, team: thrower.team, | |
| 458 | pos: [...pos], vel: [0, 0, 0], fuse: TICK / 2, | |
| 459 | }); | |
| 460 | world.effects.length = 0; | |
| 461 | update(world, TICK, NO_INPUT); | |
| 462 | } | |
| 463 | ||
| 464 | const blastsIn = (world: World): number => | |
| 465 | world.effects.filter((e) => e.kind === "sound" && e.name === "blast").length; | |
| 466 | ||
| 467 | /** World sounds of one name pushed on this very tick, so a step can be counted. */ | |
| 468 | const soundsNow = (world: World, name: string): number => | |
| 469 | world.effects.filter((e) => e.kind === "sound" && e.name === name && e.at === world.time).length; | |
| 470 | ||
| 471 | test("an HE costs $300, only in the freeze, and only one fits in a pocket", () => { | |
| 472 | const world = createWorld(SHORT, "me", "ct", 5, 211); | |
| 473 | world.me.money = 1000; | |
| 474 | expect(buy(world, world.me, "he")).toBe(true); | |
| 475 | expect(world.me.grenades).toBe(1); | |
| 476 | expect(world.me.money).toBe(700); | |
| 477 | expect(world.me.weapon).not.toBe("he"); // bought into a pocket, not into your hands | |
| 478 | expect(buy(world, world.me, "he")).toBe(false); // one at a time | |
| 479 | expect(world.me.grenades).toBe(1); | |
| 480 | expect(world.me.money).toBe(700); | |
| 481 | ||
| 482 | run(world, SHORT.freezeTime + 0.5); | |
| 483 | world.me.grenades = 0; | |
| 484 | expect(buy(world, world.me, "he")).toBe(false); // the buy is over | |
| 485 | expect(world.me.grenades).toBe(0); | |
| 486 | }); | |
| 487 | ||
| 488 | test("slot 4 needs a grenade in the pocket, and the throw sends one on its way", () => { | |
| 489 | const world = createWorld(SHORT, "me", "ct", 5, 223); | |
| 490 | armWithGrenade(world); | |
| 491 | world.me.grenades = 0; | |
| 492 | applyInput(world, world.me, { ...NO_INPUT, switchTo: "he" }, TICK); | |
| 493 | expect(world.me.weapon).not.toBe("he"); // nothing to hold | |
| 494 | ||
| 495 | world.me.grenades = 1; | |
| 496 | applyInput(world, world.me, { ...NO_INPUT, switchTo: "he" }, TICK); | |
| 497 | expect(world.me.weapon).toBe("he"); | |
| 498 | expect(currentWeapon(world.me).name).toBe("HE Grenade"); | |
| 499 | ||
| 500 | applyInput(world, world.me, { ...NO_INPUT, switchTo: "he", fire: true }, TICK); | |
| 501 | expect(world.grenades.length).toBe(1); | |
| 502 | expect(world.me.grenades).toBe(0); | |
| 503 | expect(world.me.weapon).toBe(world.me.secondary); // the hand goes back to the gun | |
| 504 | const thrown = world.grenades[0]; | |
| 505 | expect(thrown.owner).toBe(world.me.id); | |
| 506 | expect(thrown.vel[0]).toBeGreaterThan(400); // out along the view, which is +x | |
| 507 | expect(thrown.vel[2]).toBeGreaterThan(0); // and up, so it arcs | |
| 508 | }); | |
| 509 | ||
| 510 | test("the fuse goes off once, and the grenade is gone with it", () => { | |
| 511 | const world = createWorld(SHORT, "me", "ct", 5, 227); | |
| 512 | armWithGrenade(world); | |
| 513 | for (const p of world.players) if (p !== world.me) p.alive = false; | |
| 514 | applyInput(world, world.me, { ...NO_INPUT, switchTo: "he", fire: true }, TICK); | |
| 515 | let blasts = 0; | |
| 516 | for (let t = 0; t < 4; t += TICK) { | |
| 517 | update(world, TICK, NO_INPUT); | |
| 518 | blasts += blastsIn(world) > 0 && world.effects.some((e) => e.kind === "sound" && e.name === "blast" && e.at === world.time) ? 1 : 0; | |
| 519 | } | |
| 520 | expect(blasts).toBe(1); | |
| 521 | expect(world.grenades.length).toBe(0); | |
| 522 | }); | |
| 523 | ||
| 524 | test("a blast hurts more the closer it is, and nothing at all through a wall", () => { | |
| 525 | const near = createWorld(SHORT, "me", "ct", 5, 229); | |
| 526 | armWithGrenade(near); | |
| 527 | blastAt(near, near.players.find((p) => p.team === "t") as Player, [40, 0, 40]); | |
| 528 | const close = 100 - near.me.health; | |
| 529 | expect(close).toBeGreaterThan(50); | |
| 530 | ||
| 531 | const far = createWorld(SHORT, "me", "ct", 5, 229); | |
| 532 | armWithGrenade(far); | |
| 533 | blastAt(far, far.players.find((p) => p.team === "t") as Player, [260, 0, 40]); | |
| 534 | expect(100 - far.me.health).toBeGreaterThan(0); | |
| 535 | expect(100 - far.me.health).toBeLessThan(close); | |
| 536 | ||
| 537 | const behind = createWorld(SHORT, "me", "ct", 5, 229); | |
| 538 | armWithGrenade(behind); | |
| 539 | behind.boxes = [{ min: [100, -400, -100], max: [140, 400, 400], mat: 0 }]; | |
| 540 | blastAt(behind, behind.players.find((p) => p.team === "t") as Player, [260, 0, 40]); | |
| 541 | expect(behind.me.health).toBe(100); | |
| 542 | expect(hurtsIn(behind).length).toBe(0); | |
| 543 | }); | |
| 544 | ||
| 545 | test("a blast counts to the thrower, spares their own side and can kill them", () => { | |
| 546 | const world = createWorld(SHORT, "me", "ct", 5, 233); | |
| 547 | armWithGrenade(world); | |
| 548 | const mate = world.players.find((p) => p.team === "ct" && p !== world.me) as Player; | |
| 549 | const enemy = world.players.find((p) => p.team === "t") as Player; | |
| 550 | for (const p of world.players) if (p !== world.me && p !== mate && p !== enemy) p.alive = false; | |
| 551 | mate.pos = [40, 0, 0]; | |
| 552 | enemy.pos = [0, 40, 0]; | |
| 553 | enemy.armor = 0; | |
| 554 | world.me.armor = 0; | |
| 555 | // An HE is 98 at its centre: it finishes people, it does not open them up. | |
| 556 | enemy.health = 80; | |
| 557 | world.me.health = 80; | |
| 558 | blastAt(world, world.me, [20, 20, 40]); | |
| 559 | ||
| 560 | expect(mate.health).toBe(100); // no friendly fire, here as everywhere | |
| 561 | expect(enemy.alive).toBe(false); // an enemy at arm's length does not survive one | |
| 562 | expect(world.me.alive).toBe(false); // and neither does the person who threw it | |
| 563 | expect(world.me.damage).toBeGreaterThan(0); | |
| 564 | expect(world.me.kills).toBe(1); // the enemy counts; killing yourself does not | |
| 565 | expect(world.me.deaths).toBe(1); | |
| 566 | expect(world.feed.some((f) => f.weapon === "he" && f.victim === enemy.name)).toBe(true); | |
| 567 | expect(world.bodies.length).toBe(2); | |
| 568 | }); | |
| 569 | ||
| 570 | test("a blast can end a round, and cannot end one twice", () => { | |
| 571 | const world = createWorld(SHORT, "me", "ct", 5, 239); | |
| 572 | armWithGrenade(world); | |
| 573 | const last = world.players.find((p) => p.team === "t") as Player; | |
| 574 | for (const p of world.players) if (p !== world.me && p !== last) p.alive = false; | |
| 575 | world.bomb.state = "dropped"; | |
| 576 | last.pos = [30, 0, 0]; | |
| 577 | last.armor = 0; | |
| 578 | last.health = 60; | |
| 579 | world.me.pos = [-2000, 0, 0]; // well out of it | |
| 580 | blastAt(world, world.me, [30, 30, 40]); | |
| 581 | ||
| 582 | expect(last.alive).toBe(false); | |
| 583 | expect(world.match.phase).toBe("over"); | |
| 584 | expect(world.match.winner).toBe("ct"); | |
| 585 | expect(world.match.score.ct).toBe(1); | |
| 586 | // A second blast on the same corpse changes nothing about the round. | |
| 587 | blastAt(world, world.me, [30, 30, 40]); | |
| 588 | expect(world.match.score.ct).toBe(1); | |
| 589 | expect(last.deaths).toBe(1); | |
| 590 | }); | |
| 591 | ||
| 592 | test("a grenade thrown is gone at the next round; one kept is still yours", () => { | |
| 593 | const world = createWorld(SHORT, "me", "ct", 5, 241); | |
| 594 | armWithGrenade(world); | |
| 595 | applyInput(world, world.me, { ...NO_INPUT, switchTo: "he", fire: true }, TICK); | |
| 596 | expect(world.grenades.length).toBe(1); | |
| 597 | startRound(world); | |
| 598 | expect(world.grenades.length).toBe(0); | |
| 599 | expect(world.me.grenades).toBe(0); | |
| 600 | ||
| 601 | world.me.grenades = 1; | |
| 602 | startRound(world); | |
| 603 | expect(world.me.grenades).toBe(1); | |
| 604 | expect(world.me.weapon).not.toBe("he"); // a round starts with the gun up | |
| 605 | }); | |
| 606 | ||
| 607 | test("a player killed holding a grenade leaves their gun, never the grenade", () => { | |
| 608 | const world = createWorld(SHORT, "me", "ct", 5, 251); | |
| 609 | const shooter = world.players.find((p) => p.team === "t") as Player; | |
| 610 | faceOff(world, shooter); | |
| 611 | world.me.primary = "m4a4"; | |
| 612 | world.me.ammo.m4a4 = { mag: 12, reserve: 30 }; | |
| 613 | world.me.grenades = 1; | |
| 614 | world.me.weapon = "he"; | |
| 615 | world.me.health = 1; | |
| 616 | world.me.armor = 0; | |
| 617 | expect(shoot(world, shooter)).toBe(true); | |
| 618 | expect(world.me.alive).toBe(false); | |
| 619 | expect(world.pickups.map((g) => g.weapon)).toEqual(["m4a4"]); | |
| 620 | }); | |
| 621 | ||
| 622 | test("a grenade off a wall says so: one bounce effect, where it hit", () => { | |
| 623 | const world = createWorld(SHORT, "me", "ct", 5, 257); | |
| 624 | armWithGrenade(world); | |
| 625 | // A wall two rooms ahead and a floor under it: the throw has to hit one. | |
| 626 | world.boxes = [ | |
| 627 | { min: [-4000, -4000, -64], max: [4000, 4000, 0], mat: 0 }, | |
| 628 | { min: [400, -600, 0], max: [440, 600, 400], mat: 0 }, | |
| 629 | ]; | |
| 630 | world.me.pos = [0, 0, 0]; | |
| 631 | applyInput(world, world.me, { ...NO_INPUT, switchTo: "he", fire: true }, TICK); | |
| 632 | ||
| 633 | let bounces = 0; | |
| 634 | let firstAt: [number, number, number] | null = null; | |
| 635 | for (let t = 0; t < GRENADE.fuse; t += TICK) { | |
| 636 | update(world, TICK, NO_INPUT); | |
| 637 | const now = soundsNow(world, "bounce"); | |
| 638 | if (now > 0 && firstAt === null) { | |
| 639 | firstAt = (world.effects.find( | |
| 640 | (e) => e.kind === "sound" && e.name === "bounce" && e.at === world.time, | |
| 641 | ) as { pos: [number, number, number] }).pos; | |
| 642 | } | |
| 643 | bounces += now; | |
| 644 | } | |
| 645 | expect(bounces).toBeGreaterThan(0); | |
| 646 | expect(firstAt).not.toBeNull(); | |
| 647 | // The sound is where the grenade is, which is against the wall it hit. | |
| 648 | expect((firstAt as [number, number, number])[0]).toBeGreaterThan(300); | |
| 649 | expect((firstAt as [number, number, number])[0]).toBeLessThanOrEqual(400); | |
| 650 | // And a round with nothing in the air is silent. | |
| 651 | world.grenades.length = 0; | |
| 652 | update(world, TICK, NO_INPUT); | |
| 653 | expect(soundsNow(world, "bounce")).toBe(0); | |
| 654 | }); |
src/client/world.ts +146 −18
| @@ -9,6 +9,9 @@ | ||
| 9 | 9 | |
| 10 | 10 | import { addBody, type Corpse } from "./bodies.ts"; |
| 11 | 11 | import { applyHit, traceBullet, type Actor } from "./combat.ts"; |
| 12 | import { | |
| 13 | blastDamage, GRENADE, step as stepGrenade, thrown, type Grenade, | |
| 14 | } from "./grenades.ts"; | |
| 12 | 15 | import * as map from "./map.ts"; |
| 13 | 16 | import { angleVectors, angleDelta, clamp, dist, dist2d, normalize, rng, sub, type Vec3 } from "./math.ts"; |
| 14 | 17 | import * as rules from "./match.ts"; |
| @@ -35,6 +38,7 @@ export type Player = Actor & Body & { | ||
| 35 | 38 | primary: WeaponId | null; |
| 36 | 39 | secondary: WeaponId; |
| 37 | 40 | ammo: Record<string, Ammo>; |
| 41 | grenades: number; // HE grenades carried, thrown one at a time | |
| 38 | 42 | defuseKit: boolean; |
| 39 | 43 | hasBomb: boolean; |
| 40 | 44 | nextShotAt: number; |
| @@ -121,6 +125,7 @@ export type World = { | ||
| 121 | 125 | plan: Plan; |
| 122 | 126 | bomb: Bomb; |
| 123 | 127 | pickups: Pickup[]; |
| 128 | grenades: Grenade[]; // the ones in the air, or on the floor with a fuse left | |
| 124 | 129 | bodies: Corpse[]; // the dead of this round, cleared when the next one starts |
| 125 | 130 | effects: Effect[]; |
| 126 | 131 | feed: FeedEntry[]; |
| @@ -148,6 +153,7 @@ function makePlayer(id: number, team: Team, name: string, bot: boolean): Player | ||
| 148 | 153 | money: 800, |
| 149 | 154 | weapon: secondary, primary: null, secondary, |
| 150 | 155 | ammo: { knife: { mag: 0, reserve: 0 }, [secondary]: emptyAmmo(secondary) }, |
| 156 | grenades: 0, | |
| 151 | 157 | defuseKit: false, hasBomb: false, |
| 152 | 158 | nextShotAt: 0, reloadUntil: 0, shotIndex: 0, lastShotAt: -99, scoped: false, firedThisPress: false, |
| 153 | 159 | punch: [0, 0], nextPickupAt: 0, |
| @@ -182,7 +188,7 @@ export function createWorld( | ||
| 182 | 188 | seed: seed >>> 0, |
| 183 | 189 | plan: roundPlan(seed, match.round), |
| 184 | 190 | bomb: { state: "carried", pos: [0, 0, 0], site: null, plantProgress: 0, defuseProgress: 0, defuser: null }, |
| 185 | pickups: [], bodies: [], | |
| 191 | pickups: [], grenades: [], bodies: [], | |
| 186 | 192 | effects: [], feed: [], messages: [], |
| 187 | 193 | random, boxes: map.boxes, bombPlanted: false, pendingBuy: false, |
| 188 | 194 | }; |
| @@ -243,6 +249,10 @@ export function startRound(world: World): void { | ||
| 243 | 249 | } |
| 244 | 250 | world.bombPlanted = false; |
| 245 | 251 | world.pickups.length = 0; |
| 252 | // A grenade still in the air belongs to a round that is over. What is in a | |
| 253 | // pocket stays there: a grenade thrown is gone and one kept is still yours, | |
| 254 | // which is the rule the guns above already follow. | |
| 255 | world.grenades.length = 0; | |
| 246 | 256 | world.bodies.length = 0; |
| 247 | 257 | world.feed = []; |
| 248 | 258 | for (const p of world.players) if (p.bot) botBuy(world, p); |
| @@ -293,26 +303,44 @@ export function priceOf(item: BuyItem, player: Player): number { | ||
| 293 | 303 | export const canBuy = (world: World, player: Player): boolean => |
| 294 | 304 | world.match.phase === "freeze" && player.alive; |
| 295 | 305 | |
| 296 | /** Buy one thing. Refuses anything the round, the side or the wallet says no to. */ | |
| 297 | export function buy(world: World, player: Player, item: BuyItem): boolean { | |
| 306 | /** How many HE grenades fit in a pocket. One, the way CS counts them. */ | |
| 307 | export const MAX_GRENADES = 1; | |
| 308 | ||
| 309 | /** | |
| 310 | * Would `buy` take this? The buy panel asks so a button can be dead before it | |
| 311 | * is pressed, and `buy` asks so there is one list of reasons and not two. | |
| 312 | */ | |
| 313 | export function canBuyItem(world: World, player: Player, item: BuyItem): boolean { | |
| 298 | 314 | if (!canBuy(world, player)) return false; |
| 299 | 315 | const price = priceOf(item, player); |
| 300 | 316 | if (!Number.isFinite(price) || price > player.money) return false; |
| 317 | if (item === "armor") return player.armor < 100; | |
| 318 | if (item === "helmet") return !player.helmet; | |
| 319 | if (item === "kit") return player.team === "ct" && !player.defuseKit; | |
| 320 | const weapon = WEAPONS[item]; | |
| 321 | if (weapon === undefined || weapon.kind === "knife") return false; | |
| 322 | if (weapon.team !== "both" && weapon.team !== player.team) return false; | |
| 323 | if (weapon.kind === "grenade") return player.grenades < MAX_GRENADES; | |
| 324 | return true; | |
| 325 | } | |
| 326 | ||
| 327 | /** Buy one thing. Refuses anything the round, the side or the wallet says no to. */ | |
| 328 | export function buy(world: World, player: Player, item: BuyItem): boolean { | |
| 329 | if (!canBuyItem(world, player, item)) return false; | |
| 330 | const price = priceOf(item, player); // before the item changes what it costs | |
| 301 | 331 | if (item === "armor") { |
| 302 | if (player.armor >= 100) return false; | |
| 303 | 332 | player.armor = 100; |
| 304 | 333 | } else if (item === "helmet") { |
| 305 | if (player.helmet) return false; | |
| 306 | 334 | player.armor = 100; |
| 307 | 335 | player.helmet = true; |
| 308 | 336 | } else if (item === "kit") { |
| 309 | if (player.team !== "ct" || player.defuseKit) return false; | |
| 310 | 337 | player.defuseKit = true; |
| 338 | } else if (WEAPONS[item].kind === "grenade") { | |
| 339 | // Bought, not drawn: a grenade goes in a pocket and the gun stays in the | |
| 340 | // hands. Slot 4 is how it comes out, which is a choice, not a side effect. | |
| 341 | player.grenades += 1; | |
| 311 | 342 | } else { |
| 312 | const weapon = WEAPONS[item]; | |
| 313 | if (weapon === undefined || weapon.kind === "knife") return false; | |
| 314 | if (weapon.team !== "both" && weapon.team !== player.team) return false; | |
| 315 | if (weapon.kind === "pistol") player.secondary = item; | |
| 343 | if (WEAPONS[item].kind === "pistol") player.secondary = item; | |
| 316 | 344 | else player.primary = item; |
| 317 | 345 | player.ammo[item] = emptyAmmo(item); |
| 318 | 346 | player.weapon = item; |
| @@ -388,6 +416,7 @@ export function shoot(world: World, p: Player): boolean { | ||
| 388 | 416 | const w = currentWeapon(p); |
| 389 | 417 | if (world.time < p.nextShotAt || world.time < p.reloadUntil) return false; |
| 390 | 418 | if (world.match.phase === "freeze") return false; |
| 419 | if (w.kind === "grenade") return throwGrenade(world, p); | |
| 391 | 420 | const ammo = p.ammo[w.id]; |
| 392 | 421 | if (w.magazine > 0 && (ammo === undefined || ammo.mag <= 0)) { |
| 393 | 422 | reload(world, p); |
| @@ -439,9 +468,13 @@ function onKill(world: World, killer: Player, victim: Player, weapon: WeaponId, | ||
| 439 | 468 | victim.deaths += 1; |
| 440 | 469 | victim.scoped = false; |
| 441 | 470 | addBody(world.bodies, victim, world.boxes, world.time); |
| 442 | killer.kills += 1; | |
| 443 | if (headshot) killer.headshots += 1; | |
| 444 | killer.money = rules.capMoney(killer.money + WEAPONS[weapon].killReward, world.match.rules); | |
| 471 | // Only a grenade can reach the person who threw it, and killing yourself is | |
| 472 | // not a kill: the death and the feed line stand, the credit does not. | |
| 473 | if (killer !== victim) { | |
| 474 | killer.kills += 1; | |
| 475 | if (headshot) killer.headshots += 1; | |
| 476 | killer.money = rules.capMoney(killer.money + WEAPONS[weapon].killReward, world.match.rules); | |
| 477 | } | |
| 445 | 478 | world.feed.push({ |
| 446 | 479 | at: world.time, |
| 447 | 480 | killer: killer.name, killerId: killer.id, |
| @@ -454,9 +487,10 @@ function onKill(world: World, killer: Player, victim: Player, weapon: WeaponId, | ||
| 454 | 487 | world.bomb.state = "dropped"; |
| 455 | 488 | world.bomb.pos = [victim.pos[0], victim.pos[1], victim.pos[2] + 4]; |
| 456 | 489 | } |
| 457 | // The gun they were holding stays where they fell. A knife is never a pickup, | |
| 458 | // so someone killed holding one leaves their primary instead — or nothing. | |
| 459 | dropWeapon(world, victim, victim.weapon === "knife" ? victim.primary : victim.weapon); | |
| 490 | // The gun they were holding stays where they fell. A knife and a grenade are | |
| 491 | // never pickups, so someone killed holding one leaves their primary instead | |
| 492 | // — or nothing. | |
| 493 | dropWeapon(world, victim, droppable(victim.weapon) ? victim.weapon : victim.primary); | |
| 460 | 494 | checkRoundEnd(world); |
| 461 | 495 | } |
| 462 | 496 | |
| @@ -482,9 +516,14 @@ const PICKUP_COOLDOWN = 0.75; | ||
| 482 | 516 | export const pickupSlot = (id: WeaponId): "primary" | "secondary" => |
| 483 | 517 | WEAPONS[id]?.kind === "pistol" ? "secondary" : "primary"; |
| 484 | 518 | |
| 519 | /** Is this something that can lie on the floor? A knife and a grenade are not. */ | |
| 520 | const droppable = (id: WeaponId | null): boolean => | |
| 521 | id !== null && WEAPONS[id] !== undefined && | |
| 522 | WEAPONS[id].kind !== "knife" && WEAPONS[id].kind !== "grenade"; | |
| 523 | ||
| 485 | 524 | /** Leave `id` on the floor under `p`, with the ammunition `p` had left in it. */ |
| 486 | 525 | function dropWeapon(world: World, p: Player, id: WeaponId | null): void { |
| 487 | if (id === null || WEAPONS[id] === undefined || WEAPONS[id].kind === "knife") return; | |
| 526 | if (!droppable(id) || id === null) return; | |
| 488 | 527 | const ammo = p.ammo[id] ?? emptyAmmo(id); |
| 489 | 528 | world.pickups.push({ |
| 490 | 529 | weapon: id, |
| @@ -555,6 +594,88 @@ function updatePickups(world: World, p: Player, input: Input): void { | ||
| 555 | 594 | if (asked !== null) takePickup(world, p, asked); |
| 556 | 595 | } |
| 557 | 596 | |
| 597 | // --- grenades ------------------------------------------------------------- | |
| 598 | ||
| 599 | /** How long after a throw before the hand is free again. */ | |
| 600 | const THROW_COOLDOWN = 0.6; | |
| 601 | ||
| 602 | /** Where the sparks of a blast go: out along the walls, and up. */ | |
| 603 | const BURST: Vec3[] = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1]]; | |
| 604 | const BURST_SPREAD = 70; | |
| 605 | ||
| 606 | /** | |
| 607 | * Throw the grenade in `p`'s hand. It leaves the eye, forward and a little up, | |
| 608 | * carrying whatever `p` was doing at the time, and the hand goes back to the | |
| 609 | * gun once the last one is gone — a slot with nothing in it is not a slot. | |
| 610 | */ | |
| 611 | function throwGrenade(world: World, p: Player): boolean { | |
| 612 | if (p.grenades <= 0) return false; | |
| 613 | p.grenades -= 1; | |
| 614 | p.nextShotAt = world.time + THROW_COOLDOWN; | |
| 615 | p.lastShotAt = world.time; | |
| 616 | world.grenades.push(thrown(p.id, p.team, eyePos(p), p.yaw, p.pitch, p.vel)); | |
| 617 | if (p.grenades <= 0) p.weapon = p.primary ?? p.secondary; | |
| 618 | return true; | |
| 619 | } | |
| 620 | ||
| 621 | /** | |
| 622 | * A blast: everyone it can see, from full damage at the centre down to nothing | |
| 623 | * at the radius, less whatever their armour stops. A wall between the two is | |
| 624 | * the whole of the cover rule — the same `visible` trace a bot sees with, eye | |
| 625 | * to blast — and there is no friendly fire here any more than there is for a | |
| 626 | * bullet, though the thrower is very much in range of their own grenade. | |
| 627 | */ | |
| 628 | function detonate(world: World, g: Grenade): void { | |
| 629 | world.effects.push({ kind: "sound", at: world.time, pos: [...g.pos] as Vec3, name: "blast" }); | |
| 630 | for (const n of BURST) { | |
| 631 | world.effects.push({ | |
| 632 | kind: "impact", | |
| 633 | at: world.time, | |
| 634 | pos: [g.pos[0] + n[0] * BURST_SPREAD, g.pos[1] + n[1] * BURST_SPREAD, g.pos[2] + n[2] * BURST_SPREAD], | |
| 635 | normal: n, | |
| 636 | }); | |
| 637 | } | |
| 638 | const thrower = world.players.find((p) => p.id === g.owner) ?? null; | |
| 639 | for (const victim of world.players) { | |
| 640 | if (!victim.alive) continue; | |
| 641 | if (victim.team === g.team && victim.id !== g.owner) continue; | |
| 642 | const eye = eyePos(victim); | |
| 643 | const range = dist(g.pos, eye); | |
| 644 | if (range >= GRENADE.blastRadius || !visible(g.pos, eye, world.boxes)) continue; | |
| 645 | const { health, armor } = blastDamage(range, victim.armor); | |
| 646 | if (health <= 0) continue; | |
| 647 | const dealt = Math.min(health, victim.health); | |
| 648 | victim.armor = Math.max(0, victim.armor - armor); | |
| 649 | victim.health -= health; | |
| 650 | if (thrower !== null && thrower !== victim) thrower.damage += dealt; | |
| 651 | hurt(world, victim, g.pos, dealt); | |
| 652 | if (victim.health <= 0) { | |
| 653 | victim.health = 0; | |
| 654 | onKill(world, thrower ?? victim, victim, "he", false); | |
| 655 | } | |
| 656 | } | |
| 657 | } | |
| 658 | ||
| 659 | /** | |
| 660 | * Step whatever is in the air. The empty list is the first thing tested, the | |
| 661 | * way `updatePickups` tests its own: the training arena never throws one, so a | |
| 662 | * round without grenades pays one comparison a tick for this whole section. | |
| 663 | */ | |
| 664 | function updateGrenades(world: World, dt: number): void { | |
| 665 | if (world.grenades.length === 0) return; | |
| 666 | for (let i = world.grenades.length - 1; i >= 0; i--) { | |
| 667 | const g = world.grenades[i] as Grenade; | |
| 668 | const { bounced, detonated } = stepGrenade(g, dt, world.boxes); | |
| 669 | if (bounced) world.effects.push({ kind: "sound", at: world.time, pos: [...g.pos] as Vec3, name: "bounce" }); | |
| 670 | // Off the list before it goes off: a fuse fires once, and a kill that ends | |
| 671 | // the round must not find the grenade that caused it still in the world. | |
| 672 | if (detonated) { | |
| 673 | world.grenades.splice(i, 1); | |
| 674 | detonate(world, g); | |
| 675 | } | |
| 676 | } | |
| 677 | } | |
| 678 | ||
| 558 | 679 | // --- the bomb ------------------------------------------------------------- |
| 559 | 680 | |
| 560 | 681 | const PLANT_RANGE = 64; |
| @@ -641,10 +762,15 @@ function footsteps(world: World, p: Player, wish: Wish, before: Vec3): void { | ||
| 641 | 762 | |
| 642 | 763 | // --- the tick ------------------------------------------------------------- |
| 643 | 764 | |
| 765 | /** Is `id` something `p` can put in their hands right now? */ | |
| 766 | const holds = (p: Player, id: WeaponId): boolean => | |
| 767 | id === "knife" || id === p.primary || id === p.secondary || | |
| 768 | (WEAPONS[id]?.kind === "grenade" && p.grenades > 0); | |
| 769 | ||
| 644 | 770 | export function applyInput(world: World, p: Player, input: Input, dt: number): void { |
| 645 | 771 | if (!p.alive) return; |
| 646 | 772 | const frozen = world.match.phase === "freeze" || world.match.phase === "over"; |
| 647 | if (input.switchTo !== null && (input.switchTo === "knife" || input.switchTo === p.primary || input.switchTo === p.secondary)) { | |
| 773 | if (input.switchTo !== null && holds(p, input.switchTo)) { | |
| 648 | 774 | if (p.weapon !== input.switchTo) { |
| 649 | 775 | p.weapon = input.switchTo; |
| 650 | 776 | p.shotIndex = 0; |
| @@ -708,6 +834,7 @@ export function update(world: World, dt: number, input: Input): void { | ||
| 708 | 834 | p.armor = 0; |
| 709 | 835 | p.helmet = false; |
| 710 | 836 | p.defuseKit = false; |
| 837 | p.grenades = 0; | |
| 711 | 838 | p.secondary = p.team === "t" ? "glock" : "usp"; |
| 712 | 839 | p.ammo = { knife: { mag: 0, reserve: 0 }, [p.secondary]: emptyAmmo(p.secondary) }; |
| 713 | 840 | p.weapon = p.secondary; |
| @@ -720,6 +847,7 @@ export function update(world: World, dt: number, input: Input): void { | ||
| 720 | 847 | } |
| 721 | 848 | if (world.match.phase === "freeze" && before === "over") startRound(world); |
| 722 | 849 | |
| 850 | updateGrenades(world, dt); | |
| 723 | 851 | applyInput(world, world.me, world.me.alive ? input : NO_INPUT, dt); |
| 724 | 852 | for (const p of world.players) { |
| 725 | 853 | if (!p.bot || !p.alive) continue; |
src/pages/game.ts +5 −3
| @@ -145,11 +145,12 @@ export function gamePage(db: Database, options: PageOptions): string { | ||
| 145 | 145 | <div class="row"><button type="button" class="primary" id="play">Play</button></div> |
| 146 | 146 | <p class="hint"><kbd>WASD</kbd> move · <kbd>Space</kbd> jump · <kbd>Ctrl</kbd> crouch · <kbd>Shift</kbd> walk · |
| 147 | 147 | mouse to aim and fire · <kbd>R</kbd> reload · <kbd>E</kbd> plant, defuse or take a gun · <kbd>B</kbd> buy · |
| 148 | right click or <kbd>Q</kbd> to scope · <kbd>1</kbd><kbd>2</kbd><kbd>3</kbd> guns · <kbd>Tab</kbd> scores · | |
| 148 | right click or <kbd>Q</kbd> to scope · <kbd>1</kbd><kbd>2</kbd><kbd>3</kbd> guns · | |
| 149 | <kbd>4</kbd> the HE grenade, thrown with fire · <kbd>Tab</kbd> scores · | |
| 149 | 150 | <kbd>Esc</kbd> pause, where sound and sensitivity live too</p> |
| 150 | 151 | <p class="hint">On a phone: the left of the view is a thumb stick, the right aims, a second |
| 151 | finger on the right fires, and the pad under the view does the rest — guns, scores, buy | |
| 152 | and a menu you can leave the match from.</p> | |
| 152 | finger on the right fires, and the pad under the view does the rest — guns, the grenade, | |
| 153 | scores, buy and a menu you can leave the match from.</p> | |
| 153 | 154 | </div> |
| 154 | 155 | <div class="overlay" id="pause" hidden> |
| 155 | 156 | <h2>Paused</h2> |
| @@ -178,6 +179,7 @@ export function gamePage(db: Database, options: PageOptions): string { | ||
| 178 | 179 | <button type="button" data-action="slot1"><b>1</b>rifle</button> |
| 179 | 180 | <button type="button" data-action="slot2"><b>2</b>pistol</button> |
| 180 | 181 | <button type="button" data-action="slot3"><b>3</b>knife</button> |
| 182 | <button type="button" data-action="slot4"><b>4</b>nade</button> | |
| 181 | 183 | <button type="button" data-action="scoreboard">scores</button> |
| 182 | 184 | <button type="button" data-action="menu">menu</button> |
| 183 | 185 | </div> |
new above
offline
Changes requested — one miss, and it is a test. Everything else about this pull is right, and I checked it properly:
bun testis 236 pass / 0 fail at this head, the app serves/in 20 ms with the CSP / nosniff / Referrer-Policy floor intact and the new4 nadebutton and4hint in the first paint, the arena benches 11–13k steps/s on both the base and this head over three alternating runs (theworld.grenades.length === 0fast path holds), and a few hundred headless throws across six matches produced no NaN, nothing outside the map, and an 830–1020 unit flat throw with two bounces — the right feel.grenades.tsis one honest concept; the ball-vs-box resolve cannot tunnel here (cells merge to 128 units minimum, the grenade moves ~16 a tick at worst); the fuse fires once because the grenade leaves the list beforedetonate; cover is the samevisibletrace the bots use;armorSplitis a clean extraction;canBuyItemis a real improvement. No server, session or boundary touched, no dependency, no dead code, and the README numbers match the constants.This line is the miss. The new draw loop over
world.grenadeshas no test, andrenderer.test.tsis untouched — yet the harness is already sitting in that file: "a body is one more draw of the same mesh" countsdrawElementsthroughframe(). Fix this first, in the same shape: take a frame's draw count, push oneGrenadeintoworld.grenades, and assert the next frame is exactly one draw longer with no newbufferData. Three lines. Without it a stray guard or a mis-bound VAO ships silently, and the whole point of a thrown object is that you can watch it land — the issue asks for exactly that ("the grenade visible in the world while it flies").Second, smaller: the bounce sound.
grenades.test.tsassertsstepreturnsbounced, but nothing assertsupdateGrenadesturns that into a{kind:"sound", name:"bounce"}effect;world.test.tschecks the blast sound and stops. One assertion besideblastsIn: throw at a wall, step to the first hard contact, expect abounceeffect atworld.time.Not blocking, for the record. A steep throw clears the 384-unit walls (apex ~380 above the eye at 780 u/s), so a grenade can come to rest on a roof and go off where it hurts nobody — harmless, and CS has those spots too. And the roll stops fast because the 0.75 friction is applied on every floor contact, about a quarter of the speed a tick, so a grenade sits down roughly where it first touched. Both are feel, not faults; open an issue if you want a longer roll.
Add those two tests and this is an approve.