Split The code is public; the app answers only to the crew.

A bullet through a crate: penetration a rifle has and a pistol does not #113

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

vesper/cs:vesper/79-a-bullet-through-a-crate-penetration-a-r → main 2 commits fork

  • Merged. vesper/79-a-bullet-through-a-crate-penetration-a-r was merged into main as ff7bae9.

Review

Sign in to review this change.
7 files changed +268 −37
README.md +15 −1
@@ -44,7 +44,21 @@ wants one, but the running server never reads it.
4444 movement (ground friction, air acceleration, an 18-unit step, strafe jumping),
4545 CS damage with range falloff, armour and hitgroups, deterministic spray patterns,
4646 a 1:55 round with a 40-second bomb, plant and defuse timers, kill rewards and
47 loss bonuses. The economy has CS's loop: weapons drop. A player killed leaves
47 loss bonuses. Cover is not all equal: a bullet goes **through a crate** if
48 the round is strong enough for the thickness it meets. Crates are the only
49 penetrable material — walls, floors, the site plates and metal stop
50 everything — and every crate on `de_forge` is 128 units across, so the AWP
51 (230 units), AK-47 (175), M4A4 (165) and Desert Eagle (150) punch one
52 face-on while the Glock (48), USP (55) and MP9 (60) manage nothing but a
53 clipped corner, and a knife nothing at all. The thickness is measured along
54 the bullet's own line, so a crate crossed at an angle is thicker than one
55 crossed square. What comes out the far side hits for a share of its damage
56 — 85% for the AWP, 70% for the AK, less for the rest — taken off before
57 armour sees it. One surface a shot: two crates in a line stop the round as
58 surely as a wall, and the far side of a punched crate is marked where the
59 bullet went in as well as where it stopped. The bots do not know any of
60 this: their sight is still blocked by a crate, so shooting one off a box
61 they think is cover is yours to use. The economy has CS's loop: weapons drop. A player killed leaves
4862 the gun they were holding on the floor with whatever was left in the magazine
4963 — a knife never drops, and someone killed holding one leaves their primary —
5064 and it can be picked up. With no primary you take it by walking over it; with
src/client/bodies.test.ts +2 −1
@@ -1,6 +1,7 @@
11 import { expect, test } from "bun:test";
22 import { addBody, MAX_BODIES, type Corpse } from "./bodies.ts";
33 import { traceBullet } from "./combat.ts";
4 import { WEAPONS } from "./weapons.ts";
45 import { SHORT } from "./match.ts";
56 import { move, MOVE, type Body, type Wish } from "./physics.ts";
67 import {
@@ -108,6 +109,6 @@ test("a body is decoration: nobody collides with it and no bullet stops on it",
108109 expect(walker.pos[1]).toBeGreaterThan(0); // straight over where the body lies
109110
110111 // A bullet along the same line finds nothing: only living players are actors.
111 const hit = traceBullet([0, -300, 20], [0, 300, 20], world.boxes, world.players, shooter.id);
112 const hit = traceBullet([0, -300, 20], [0, 300, 20], world.boxes, world.players, shooter.id, WEAPONS.ak47);
112113 expect(hit.kind).toBe("none");
113114 });
src/client/combat.test.ts +70 −6
@@ -1,8 +1,8 @@
11 import { expect, test } from "bun:test";
22 import { applyHit, hitboxes, traceBullet, type Actor } from "./combat.ts";
3 import type { Box } from "./map.ts";
3 import { MAT, type Box } from "./map.ts";
44 import type { Vec3 } from "./math.ts";
5 import { WEAPONS } from "./weapons.ts";
5 import { WEAPONS, type Weapon } from "./weapons.ts";
66
77 const actor = (over: Partial<Actor> = {}): Actor => ({
88 id: 1, team: "t", pos: [500, 0, 0], yaw: 180, duckAmount: 0,
@@ -20,25 +20,25 @@ test("a crouching head sits where a crouching head looks", () => {
2020
2121 test("a bullet at head height hits the head", () => {
2222 const target = actor();
23 const hit = traceBullet([0, 0, 66], [1000, 0, 66], [], [target], 0);
23 const hit = traceBullet([0, 0, 66], [1000, 0, 66], [], [target], 0, WEAPONS.ak47);
2424 expect(hit.kind).toBe("actor");
2525 if (hit.kind === "actor") expect(hit.group).toBe("head");
2626 });
2727
2828 test("a wall in the way stops the bullet before the body", () => {
2929 const wall: Box = { min: [200, -100, 0], max: [216, 100, 384], mat: 1 };
30 const hit = traceBullet([0, 0, 40], [1000, 0, 40], [wall], [actor()], 0);
30 const hit = traceBullet([0, 0, 40], [1000, 0, 40], [wall], [actor()], 0, WEAPONS.ak47);
3131 expect(hit.kind).toBe("world");
3232 if (hit.kind === "world") expect(hit.point[0]).toBeCloseTo(200, 3);
3333 });
3434
3535 test("you cannot shoot yourself", () => {
3636 const me = actor({ id: 7, pos: [10, 0, 0] });
37 expect(traceBullet([0, 0, 40], [1000, 0, 40], [], [me], 7).kind).toBe("none");
37 expect(traceBullet([0, 0, 40], [1000, 0, 40], [], [me], 7, WEAPONS.ak47).kind).toBe("none");
3838 });
3939
4040 test("a dead body does not stop bullets", () => {
41 expect(traceBullet([0, 0, 40], [1000, 0, 40], [], [actor({ alive: false })], 0).kind).toBe("none");
41 expect(traceBullet([0, 0, 40], [1000, 0, 40], [], [actor({ alive: false })], 0, WEAPONS.ak47).kind).toBe("none");
4242 });
4343
4444 test("two AK headshots are one too many", () => {
@@ -56,3 +56,67 @@ test("damage credited never exceeds the health that was there", () => {
5656 expect(hit.damage).toBe(12);
5757 expect(hit.killed).toBe(true);
5858 });
59
60 // --- penetration ----------------------------------------------------------
61
62 const crate = (x0: number, x1: number, mat = MAT.CRATE): Box =>
63 ({ min: [x0, -100, 0], max: [x1, 100, 384], mat });
64
65 /** One shot down the x axis at a body at 500, and what it took off them. */
66 const shootThrough = (weapon: Weapon, boxes: Box[]): number => {
67 const target = actor();
68 const hit = traceBullet([0, 0, 40], [1000, 0, 40], boxes, [target], 0, weapon);
69 if (hit.kind !== "actor") return 0;
70 return applyHit(target, weapon, hit.group, hit.distance, hit.damageScale).damage;
71 };
72
73 test("a rifle crosses a thin crate and still hurts, for less than the clear shot", () => {
74 const through = shootThrough(WEAPONS.ak47, [crate(200, 280)]);
75 const clear = shootThrough(WEAPONS.ak47, []);
76 expect(through).toBeGreaterThan(0);
77 expect(through).toBeLessThan(clear);
78 });
79
80 test("a pistol's round stays in the crate a rifle's crosses", () => {
81 expect(shootThrough(WEAPONS.glock, [crate(200, 280)])).toBe(0);
82 });
83
84 test("no round crosses a wall, a floor, a site plate or metal, however thin", () => {
85 for (const mat of [MAT.WALL, MAT.FLOOR, MAT.SITE, MAT.METAL]) {
86 expect(shootThrough(WEAPONS.awp, [crate(200, 216, mat)])).toBe(0);
87 }
88 });
89
90 test("a crate thicker than the round's limit stops it", () => {
91 // 200 units of crate: the AWP's 230 goes through, the AK's 175 does not.
92 expect(shootThrough(WEAPONS.ak47, [crate(200, 400)])).toBe(0);
93 expect(shootThrough(WEAPONS.awp, [crate(200, 400)])).toBeGreaterThan(0);
94 });
95
96 test("two crates in a line stop the bullet: one surface a shot", () => {
97 expect(shootThrough(WEAPONS.ak47, [crate(200, 280), crate(320, 400)])).toBe(0);
98 const hit = traceBullet([0, 0, 40], [1000, 0, 40], [crate(200, 280), crate(320, 400)], [actor()], 0, WEAPONS.ak47);
99 expect(hit.kind).toBe("world");
100 if (hit.kind === "world") expect(hit.point[0]).toBeCloseTo(320, 3);
101 });
102
103 test("a punched crate reports the face it was punched at, and the tracer ends past it", () => {
104 const hit = traceBullet([0, 0, 40], [1000, 0, 40], [crate(200, 280)], [actor()], 0, WEAPONS.ak47);
105 expect(hit.kind).toBe("actor");
106 expect(hit.through?.point[0]).toBeCloseTo(200, 3);
107 expect(hit.through?.normal).toEqual([-1, 0, 0]);
108 expect(hit.point[0]).toBeGreaterThan(280);
109 });
110
111 test("a body in front of the crate is hit at full damage, nothing punched", () => {
112 const target = actor({ pos: [100, 0, 0] });
113 const hit = traceBullet([0, 0, 40], [1000, 0, 40], [crate(200, 280)], [target], 0, WEAPONS.ak47);
114 expect(hit.kind).toBe("actor");
115 if (hit.kind === "actor") expect(hit.damageScale).toBe(1);
116 expect(hit.through).toBeNull();
117 });
118
119 test("a knife has no penetration: a crate is a crate", () => {
120 const hit = traceBullet([0, 0, 40], [1000, 0, 40], [crate(200, 216)], [actor()], 0, WEAPONS.knife);
121 expect(hit.kind).toBe("world");
122 });
src/client/combat.ts +113 −23
@@ -4,11 +4,11 @@
44 * crouching head really is where a crouching head looks.
55 */
66
7 import type { Box } from "./map.ts";
7 import { MAT, type Box } from "./map.ts";
88 import { dist, type Vec3 } from "./math.ts";
99 import { HULL } from "./physics.ts";
10 import { rayBox, traceWorld } from "./trace.ts";
11 import { computeDamage, type Hitgroup, type Weapon } from "./weapons.ts";
10 import { rayBox, traceWorld, type Hit } from "./trace.ts";
11 import { computeDamage, penetration, type Hitgroup, type Weapon } from "./weapons.ts";
1212
1313 export type Actor = {
1414 id: number;
@@ -41,45 +41,134 @@ export function hitboxes(a: Actor): Part[] {
4141 }));
4242 }
4343
44 export type BulletHit =
45 | { kind: "actor"; actor: Actor; group: Hitgroup; point: Vec3; distance: number }
46 | { kind: "world"; point: Vec3; normal: Vec3; distance: number }
47 | { kind: "none"; point: Vec3 };
44 /** The face a bullet went in by, when it came out the other side. */
45 export type Punch = { point: Vec3; normal: Vec3 };
4846
49 /** The first thing a bullet meets: a body beats a wall only if it is nearer. */
50 export function traceBullet(
47 export type BulletHit =
48 | {
49 kind: "actor"; actor: Actor; group: Hitgroup; point: Vec3; distance: number;
50 /** What is left of the damage: 1, or the weapon's share through a crate. */
51 damageScale: number;
52 /** Where it entered the crate it crossed, or null if it crossed nothing. */
53 through: Punch | null;
54 }
55 | { kind: "world"; point: Vec3; normal: Vec3; distance: number; through: Punch | null }
56 | { kind: "none"; point: Vec3; through: Punch | null };
57
58 const at = (from: Vec3, to: Vec3, t: number): Vec3 => [
59 from[0] + (to[0] - from[0]) * t,
60 from[1] + (to[1] - from[1]) * t,
61 from[2] + (to[2] - from[2]) * t,
62 ];
63
64 /** How far past the exit face the next leg starts, so it cannot re-enter. */
65 const SKIN = 0.25;
66
67 type Leg = { body: Extract<BulletHit, { kind: "actor" }> | null; world: Hit | null };
68
69 /**
70 * One straight leg: the nearest body, and the nearest solid. `origin` is where
71 * the shot came from, which is what range falloff measures against even when
72 * this leg starts at the far side of a crate.
73 */
74 function traceLeg(
5175 from: Vec3,
5276 to: Vec3,
5377 boxes: Box[],
5478 actors: Actor[],
5579 shooterId: number,
56 ): BulletHit {
80 origin: Vec3,
81 ): Leg {
5782 const world = traceWorld(from, to, boxes);
5883 let bestT = world === null ? 1 : world.t;
59 let best: BulletHit | null = null;
84 let body: Leg["body"] = null;
6085 for (const actor of actors) {
6186 if (!actor.alive || actor.id === shooterId) continue;
6287 for (const part of hitboxes(actor)) {
6388 const hit = rayBox(from, to, part.min, part.max);
6489 if (hit === null || hit.t >= bestT) continue;
6590 bestT = hit.t;
66 best = {
91 const point = at(from, to, hit.t);
92 body = {
6793 kind: "actor",
6894 actor,
6995 group: part.group,
70 point: [
71 from[0] + (to[0] - from[0]) * hit.t,
72 from[1] + (to[1] - from[1]) * hit.t,
73 from[2] + (to[2] - from[2]) * hit.t,
74 ],
75 distance: dist(from, to) * hit.t,
96 point,
97 distance: dist(origin, point),
98 damageScale: 1,
99 through: null,
76100 };
77101 }
78102 }
79 if (best !== null) return best;
80 if (world !== null)
81 return { kind: "world", point: world.point, normal: world.normal, distance: dist(from, to) * world.t };
82 return { kind: "none", point: to };
103 return { body, world };
104 }
105
106 /**
107 * Where a bullet leaves the solid it just entered, or null if it stays in it.
108 * Only `MAT.CRATE` is soft: a wall, a floor, a site plate and metal all stop
109 * everything. The thickness is the entry and exit fractions of the same box,
110 * so a round clipping a corner spends far less of its budget than one going
111 * through the middle of a face.
112 */
113 function punchThrough(
114 from: Vec3,
115 to: Vec3,
116 hit: Hit,
117 weapon: Weapon,
118 ): { entry: Punch; exit: Vec3 } | null {
119 const box = hit.what as Box;
120 const limit = penetration(weapon);
121 if (box.mat !== MAT.CRATE || limit.units <= 0) return null;
122 const span = rayBox(from, to, box.min, box.max);
123 if (span === null) return null;
124 const segment = dist(from, to);
125 if ((span.tExit - span.t) * segment > limit.units) return null;
126 const tOut = span.tExit + SKIN / Math.max(segment, 1);
127 if (tOut >= 1) return null; // the shot ran out of range inside the crate
128 return { entry: { point: hit.point, normal: hit.normal }, exit: at(from, to, tOut) };
129 }
130
131 /**
132 * The first thing a bullet meets: a body beats a wall only if it is nearer.
133 * A crate thin enough for the round is crossed — once. Whatever the bullet
134 * meets on the far side is what it hit, at `damageScale` of its damage, and
135 * two crates in a line stop it as surely as a wall does.
136 */
137 export function traceBullet(
138 from: Vec3,
139 to: Vec3,
140 boxes: Box[],
141 actors: Actor[],
142 shooterId: number,
143 weapon: Weapon,
144 ): BulletHit {
145 const near = traceLeg(from, to, boxes, actors, shooterId, from);
146 if (near.body !== null) return near.body;
147 if (near.world === null) return { kind: "none", point: to, through: null };
148
149 const punched = punchThrough(from, to, near.world, weapon);
150 if (punched === null)
151 return {
152 kind: "world",
153 point: near.world.point,
154 normal: near.world.normal,
155 distance: dist(from, near.world.point),
156 through: null,
157 };
158
159 const { entry, exit } = punched;
160 const far = traceLeg(exit, to, boxes, actors, shooterId, from);
161 if (far.body !== null)
162 return { ...far.body, damageScale: penetration(weapon).survives, through: entry };
163 if (far.world !== null)
164 return {
165 kind: "world",
166 point: far.world.point,
167 normal: far.world.normal,
168 distance: dist(from, far.world.point),
169 through: entry,
170 };
171 return { kind: "none", point: to, through: entry };
83172 }
84173
85174 /** Apply a hit and say what it cost: health off, armour off, and whether it killed. */
@@ -88,8 +177,9 @@ export function applyHit(
88177 weapon: Weapon,
89178 group: Hitgroup,
90179 distance: number,
180 damageScale = 1,
91181 ): { damage: number; killed: boolean; headshot: boolean } {
92 const { health, armor } = computeDamage(weapon, distance, group, target.armor, target.helmet);
182 const { health, armor } = computeDamage(weapon, distance, group, target.armor, target.helmet, damageScale);
93183 const dealt = Math.min(health, target.health);
94184 target.armor = Math.max(0, target.armor - armor);
95185 target.health -= health;
src/client/weapons.test.ts +27 −1
@@ -1,5 +1,5 @@
11 import { expect, test } from "bun:test";
2 import { buyable, computeDamage, inaccuracy, recoilOffset, WEAPONS } from "./weapons.ts";
2 import { buyable, computeDamage, inaccuracy, penetration, recoilOffset, WEAPONS, type WeaponId } from "./weapons.ts";
33
44 test("an AK chest shot through armour is survivable, a headshot is not", () => {
55 const ak = WEAPONS.ak47;
@@ -62,3 +62,29 @@ test("the buy menu only offers what your side carries", () => {
6262 expect(ct).not.toContain("ak47");
6363 expect(buyable("t").map((w) => w.id)).toContain("ak47");
6464 });
65
66 test("every weapon says what it does to cover, and a rifle says more than a pistol", () => {
67 for (const id of Object.keys(WEAPONS) as WeaponId[]) {
68 const { units, survives } = penetration(WEAPONS[id]);
69 expect(units).toBeGreaterThanOrEqual(0);
70 expect(survives).toBeGreaterThanOrEqual(0);
71 expect(survives).toBeLessThanOrEqual(1);
72 }
73 // A crate on the map is 128 units across: the strong rounds cross one
74 // face-on, the weak ones never do, and a knife has nothing to say.
75 for (const id of ["awp", "ak47", "m4a4", "deagle"] as WeaponId[])
76 expect(penetration(WEAPONS[id]).units).toBeGreaterThan(128);
77 for (const id of ["glock", "usp", "mp9"] as WeaponId[]) {
78 expect(penetration(WEAPONS[id]).units).toBeGreaterThan(0);
79 expect(penetration(WEAPONS[id]).units).toBeLessThan(128);
80 }
81 expect(penetration(WEAPONS.knife)).toEqual({ units: 0, survives: 0 });
82 });
83
84 test("what comes out the far side of a crate is less than what went in", () => {
85 const ak = WEAPONS.ak47;
86 const full = computeDamage(ak, 500, "chest", 0, false);
87 const punched = computeDamage(ak, 500, "chest", 0, false, penetration(ak).survives);
88 expect(punched.health).toBeLessThan(full.health);
89 expect(punched.health).toBeGreaterThan(0);
90 });
src/client/weapons.ts +34 −3
@@ -66,6 +66,33 @@ export const ARMOR_PRICE = 650;
6666 export const HELMET_PRICE = 350;
6767 export const DEFUSE_KIT_PRICE = 400;
6868
69 /**
70 * What a round does to cover. `units` is how much thickness — measured along
71 * the ray, so a corner is thinner than a face — the bullet crosses before it
72 * stops; `survives` is the share of its damage that comes out the far side.
73 * Which surfaces are soft enough to ask is `combat.ts`'s business: only a
74 * crate is, and a crate on the map is 128 units across, so a rifle goes
75 * through one and a pistol clips corners at best.
76 */
77 export type Penetration = { units: number; survives: number };
78
79 const SOLID: Penetration = { units: 0, survives: 0 };
80
81 const PENETRATION: Record<WeaponId, Penetration> = {
82 awp: { units: 230, survives: 0.85 },
83 ak47: { units: 175, survives: 0.7 },
84 m4a4: { units: 165, survives: 0.66 },
85 deagle: { units: 150, survives: 0.62 },
86 mp9: { units: 60, survives: 0.45 },
87 usp: { units: 55, survives: 0.45 },
88 glock: { units: 48, survives: 0.42 },
89 knife: SOLID,
90 he: SOLID,
91 bomb: SOLID,
92 };
93
94 export const penetration = (weapon: Weapon): Penetration => PENETRATION[weapon.id];
95
6996 /**
7097 * A spray pattern: shot 0 goes where you aim, the next few climb hard, and
7198 * after that the muzzle wanders sideways. [right, up] in degrees.
@@ -138,8 +165,11 @@ export function armorSplit(
138165 }
139166
140167 /**
141 * CS's damage sum: range falloff, then the hitgroup, then armour. Armour takes
142 * half of what it stops; a helmet is the only thing that helps a headshot.
168 * CS's damage sum: range falloff, then what cover took out of it, then the
169 * hitgroup, then armour. Armour takes half of what it stops; a helmet is the
170 * only thing that helps a headshot. `scale` is 1 for a bullet that met
171 * nothing on the way and `Penetration.survives` for one that came through a
172 * crate — the loss is spent once, here, before armour sees the number.
143173 */
144174 export function computeDamage(
145175 weapon: Weapon,
@@ -147,8 +177,9 @@ export function computeDamage(
147177 group: Hitgroup,
148178 armor: number,
149179 helmet: boolean,
180 scale = 1,
150181 ): { health: number; armor: number } {
151 let damage = weapon.damage * Math.pow(weapon.rangeModifier, distance / 500);
182 let damage = weapon.damage * Math.pow(weapon.rangeModifier, distance / 500) * scale;
152183 damage *= HITGROUP[group];
153184 const protectedHere = armor > 0 && (group !== "head" || helmet) && group !== "leg";
154185 if (!protectedHere) return { health: Math.round(damage), armor: 0 };
src/client/world.ts +7 −2
@@ -548,16 +548,21 @@ export function shoot(world: World, p: Player): boolean {
548548 const range = w.kind === "knife" ? 64 : RANGE;
549549 const dir = angleVectors(yaw, pitch).forward;
550550 const to: Vec3 = [from[0] + dir[0] * range, from[1] + dir[1] * range, from[2] + dir[2] * range];
551 const hit = traceBullet(from, to, world.boxes, world.players, p.id);
551 const hit = traceBullet(from, to, world.boxes, world.players, p.id, w);
552552 world.effects.push({ kind: "shot", at: world.time, pos: from, weapon: w.id, mine: p === world.me, shooter: p.id });
553553 if (w.kind !== "knife") world.effects.push({ kind: "tracer", at: world.time, from, to: hit.kind === "none" ? to : hit.point });
554554
555 // A crate the round went through is marked where it went in, as well as
556 // wherever the round finally stopped.
557 if (hit.through !== null)
558 world.effects.push({ kind: "impact", at: world.time, pos: hit.through.point, normal: hit.through.normal });
559
555560 if (hit.kind === "world") {
556561 world.effects.push({ kind: "impact", at: world.time, pos: hit.point, normal: hit.normal });
557562 } else if (hit.kind === "actor") {
558563 const victim = hit.actor as Player;
559564 if (victim.team === p.team && victim !== p) return true; // no friendly fire in this match
560 const result = applyHit(victim, w, hit.group, hit.distance);
565 const result = applyHit(victim, w, hit.group, hit.distance, hit.damageScale);
561566 p.damage += result.damage;
562567 recordDamage(world, p.id, victim.id, result.damage, result.killed);
563568 world.effects.push({ kind: "blood", at: world.time, pos: hit.point });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs