LINE1 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 2001import * as THREE from 'three';2import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';3import { ZOMBIES } from './config.js';4import { buildings, blockedAt, inBuilding, nearPlayerBuilding, STOREY } from './city.js';5import * as audio from './audio.js';6import * as eco from './economy.js';78const { BoxGeometry, SphereGeometry, CylinderGeometry, CircleGeometry, Color, Group, InstancedMesh, Mesh, MeshLambertMaterial, MeshBasicMaterial, Object3D, DynamicDrawUsage, Quaternion, Vector3 } = THREE;9const UP = new Vector3(0, 1, 0);10const POOL_MAX = 140;1112const HOUSE_CLEARANCE = 14;13const DESPAWN_DIST = 340;1415const RIG_HYSTERESIS = 15;1617let GEO = null;18function geometry() {19 if (GEO) return GEO;20 const B = (w, h, d, x, y, z) => new BoxGeometry(w, h, d).translate(x, y, z);21 GEO = {22 pelvis: B(0.38, 0.2, 0.24, 0, 0, 0),23 chest: B(0.44, 0.5, 0.26, 0, 0.25, 0),24 rags: B(0.46, 0.08, 0.27, 0, 0.02, 0),25 belly: new SphereGeometry(0.2, 12, 8).scale(1, 1.1, 0.9).translate(0, 0.14, 0.12),26 neck: new CylinderGeometry(0.055, 0.065, 0.12, 8).translate(0, 0.56, 0),27 skull: new SphereGeometry(0.13, 14, 10).scale(1, 1.15, 1.05).translate(0, 0.13, 0),28 jaw: B(0.13, 0.05, 0.12, 0, -0.03, 0.04),29 eye: new SphereGeometry(0.022, 6, 4),30 hair: [B(0.1, 0.05, 0.1, -0.05, 0.25, -0.02), B(0.08, 0.06, 0.09, 0.05, 0.26, 0), B(0.12, 0.04, 0.08, 0, 0.22, -0.07)],31 upperArm: B(0.13, 0.32, 0.14, 0, -0.16, 0),32 forearm: B(0.12, 0.3, 0.13, 0, -0.15, 0),33 hand: B(0.12, 0.12, 0.1, 0, -0.36, 0.02),34 thigh: B(0.17, 0.44, 0.18, 0, -0.22, 0),35 shin: B(0.14, 0.42, 0.15, 0, -0.21, 0),36 foot: B(0.15, 0.08, 0.26, 0, -0.46, 0.06),37 blood: B(0.12, 0.14, 0.01, 0.08, 0.3, 0.135),38 };39 return GEO;40}4142const MATS = {};43function mats(type) {44 if (!MATS[type]) {45 const d = ZOMBIES[type];46 MATS[type] = {47 skin: new MeshLambertMaterial({ color: d.skin }),48 cloth: new MeshLambertMaterial({ color: d.cloth }),49 pants: new MeshLambertMaterial({ color: 0x2c2c33 }),50 shoes: new MeshLambertMaterial({ color: 0x1a1816 }),51 hair: new MeshLambertMaterial({ color: 0x2a2019 }),52 blood: new MeshLambertMaterial({ color: 0x5a0d0d }),53 eye: new MeshBasicMaterial({ color: d.eye }),54 };55 }56 return MATS[type];57}58596061function mesh(geo, mat) {62 const m = new Mesh(geo, mat);63 m.receiveShadow = true;64 return m;65}66676869function randomShade() {70 return {71 skin: [rand(-0.01, 0.01), rand(-0.05, 0.03), rand(-0.07, 0.05)],72 cloth: [rand(-0.01, 0.01), rand(-0.05, 0.03), rand(-0.07, 0.05)],73 };74}757677function tintedMats(type, shade) {78 const base = mats(type);79 const own = [];80 const tint = (src, offset) => {81 const c = src.color.clone().offsetHSL(offset[0], offset[1], offset[2]);82 const m = new MeshLambertMaterial({ color: c });83 own.push(m);84 return m;85 };86 return { m: { ...base, skin: tint(base.skin, shade.skin), cloth: tint(base.cloth, shade.cloth) }, own };87}88899091let CROWD_GEO = null;92let CROWD_MAT = null;93function crowdAssets() {94 if (!CROWD_GEO) {95 const B = (w, h, d, x, y, z) => new BoxGeometry(w, h, d).translate(x, y, z);96 CROWD_GEO = mergeGeometries([97 B(0.46, 0.6, 0.28, 0, 1.25, 0),98 B(0.38, 0.22, 0.24, 0, 0.98, 0),99 B(0.17, 0.92, 0.2, -0.11, 0.46, 0),100 B(0.17, 0.92, 0.2, 0.11, 0.46, 0),101 B(0.13, 0.66, 0.14, -0.31, 1.02, 0),102 B(0.13, 0.66, 0.14, 0.31, 1.02, 0),103 new SphereGeometry(0.13, 8, 6).translate(0, 1.8, 0),104 ]);105 CROWD_MAT = new MeshLambertMaterial({ color: 0xffffff });106 }107 return { geo: CROWD_GEO, mat: CROWD_MAT };108}109const dummy = new Object3D();110111function pivot(parent, x, y, z) {112 const g = new Group();113 g.position.set(x, y, z);114 parent.add(g);115 return g;116}117118function buildZombieMesh(type, shade) {119 const def = ZOMBIES[type];120 const { m, own } = tintedMats(type, shade);121 const G = geometry();122 const bulk = def.bulk;123124 const root = new Group();125 root.rotation.order = 'YXZ';126 root.scale.setScalar(def.scale);127128 const hips = pivot(root, 0, 0.98, 0);129 hips.add(mesh(G.pelvis, m.pants));130 const spine = pivot(hips, 0, 0.08, 0);131132 const chest = mesh(G.chest, m.cloth);133 chest.scale.set(bulk, 1, 1.05);134 spine.add(chest);135 spine.add(mesh(G.rags, m.cloth));136 spine.add(mesh(G.blood, m.blood));137 if (bulk > 1.2) spine.add(mesh(G.belly, m.cloth));138 spine.add(mesh(G.neck, m.skin));139140 const head = pivot(spine, 0, 0.62, 0);141 head.add(mesh(G.skull, m.skin));142 const jaw = pivot(head, 0, 0.02, 0.06);143 jaw.add(mesh(G.jaw, m.skin));144 for (const x of [-0.05, 0.05]) {145 const e = mesh(G.eye, m.eye);146 e.position.set(x, 0.16, 0.13);147 head.add(e);148 }149 for (const h of G.hair) head.add(mesh(h, m.hair));150151 const arms = {};152 for (const side of [-1, 1]) {153 const shoulder = pivot(spine, side * 0.3 * bulk, 0.44, 0);154 shoulder.add(mesh(G.upperArm, m.skin));155 const elbow = pivot(shoulder, 0, -0.32, 0);156 elbow.add(mesh(G.forearm, m.skin));157 elbow.add(mesh(G.hand, m.skin));158 arms[side] = { shoulder, elbow };159 }160161 const legs = {};162 for (const side of [-1, 1]) {163 const hip = pivot(hips, side * 0.11, -0.05, 0);164 hip.add(mesh(G.thigh, m.pants));165 const knee = pivot(hip, 0, -0.44, 0);166 knee.add(mesh(G.shin, m.pants));167 const ankle = pivot(knee, 0, -0.42, 0);168 ankle.add(mesh(G.foot, m.shoes));169 legs[side] = { hip, knee };170 }171172 root.add(hips);173 return {174 group: root,175 own,176 p: { hips, spine, head, jaw, armL: arms[-1].shoulder, elL: arms[-1].elbow, armR: arms[1].shoulder, elR: arms[1].elbow, legL: legs[-1].hip, kneeL: legs[-1].knee, legR: legs[1].hip, kneeR: legs[1].knee },177 };178}179180function segmentSphere(p0, d, c, r) {181 const fx = p0.x - c.x;182 const fy = p0.y - c.y;183 const fz = p0.z - c.z;184 const a = d.x * d.x + d.y * d.y + d.z * d.z;185 const b = 2 * (fx * d.x + fy * d.y + fz * d.z);186 const cc = fx * fx + fy * fy + fz * fz - r * r;187 const disc = b * b - 4 * a * cc;188 if (disc < 0 || a < 1e-12) return -1;189 const sq = Math.sqrt(disc);190 const t1 = (-b - sq) / (2 * a);191 if (t1 >= 0 && t1 <= 1) return t1;192 return -1;193}194195const rand = (a, b) => a + Math.random() * (b - a);196const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];197198let POOL_GEO = null;199let POOL_MAT = null;200function poolAssets() {201 if (!POOL_GEO) {202 POOL_GEO = new CircleGeometry(0.5, 14).rotateX(-Math.PI / 2);203 POOL_MAT = new MeshBasicMaterial({ color: 0x3a0707, transparent: true, opacity: 0.85, polygonOffset: true, polygonOffsetFactor: -2 });204 }205 return { geo: POOL_GEO, mat: POOL_MAT };206}207208export const PARTS = {209 head: { mult: 2.5, y: 1.8, r: 0.2 },210 torso: { mult: 1, y: 1.3, r: 0.34 },211 legs: { mult: 0.5, y: 0.5, r: 0.3 },212};213214export class Zombies {215 constructor(scene) {216 this.scene = scene;217 this.list = [];218 this.pools = [];219 this.types = Object.keys(ZOMBIES);220 this.player = null;221 this.groanT = rand(2, 5);222 this.crowd = {};223 this.population = 0;224 this.rigRange = Infinity;225 this.bounds = null;226 this.insideChance = 0;227 this.spawnRange = [0, Infinity];228 }229230 231 load(opts, player, isVisible) {232 this.clear();233 this.player = player;234 this.population = opts.population;235 this.rigRange = opts.rigRange;236 this.bounds = opts.bounds;237 this.insideChance = opts.insideChance;238 this.spawnRange = opts.spawnRange;239 this.buildCrowd();240 for (let tries = 0; tries < this.population * 3 && this.aliveCount() < this.population; tries++) {241 this.spawnOne(player, isVisible);242 }243 }244245 246 clear() {247 for (const z of this.list) this.unrig(z);248 this.list = [];249 for (const pool of this.pools) this.scene.remove(pool);250 this.pools = [];251 for (const m of Object.values(this.crowd)) {252 this.scene.remove(m);253 m.dispose();254 }255 this.crowd = {};256 }257258 buildCrowd() {259 const { geo, mat } = crowdAssets();260 for (const t of this.types) {261 const m = new InstancedMesh(geo, mat, this.population);262 m.instanceMatrix.setUsage(DynamicDrawUsage);263 m.count = 0;264 m.frustumCulled = false;265 m.receiveShadow = true;266 this.scene.add(m);267 this.crowd[t] = m;268 }269 }270271 alive() {272 return this.list.filter((z) => !z.dead);273 }274275 aliveCount() {276 let n = 0;277 for (const z of this.list) if (!z.dead) n++;278 return n;279 }280281 pickType() {282 let total = 0;283 for (const t of this.types) total += ZOMBIES[t].weight;284 let r = Math.random() * total;285 for (const t of this.types) {286 r -= ZOMBIES[t].weight;287 if (r <= 0) return t;288 }289 return this.types[0];290 }291292 spawnOne(player, isVisible) {293 const type = this.pickType();294 const B = this.bounds;295 const [near, far] = this.spawnRange;296 for (let tries = 0; tries < 12; tries++) {297 const inside = this.insideChance > 0 && Math.random() < this.insideChance;298 let x, z, y = 0, b = null;299 if (inside) {300 b = pick(buildings.filter((bb) => !bb.player));301 x = rand(b.x0 + 1, b.x1 - 1);302 z = rand(b.z0 + 1, b.z1 - 1);303 y = Math.floor(rand(0, b.storeys)) * STOREY + 0.1;304 } else {305 x = rand(B.x0 + 4, B.x1 - 4);306 z = rand(B.z0 + 4, B.z1 - 4);307 }308 const dist = Math.hypot(x - player.x, z - player.z);309 if (dist < near || dist > far) continue;310 if (!inside && (blockedAt(x, z, 0.5) || inBuilding(x, z, 0.8) || nearPlayerBuilding(x, z, HOUSE_CLEARANCE))) continue;311 if (isVisible(x, y + 1, z)) continue;312 this.create(type, x, y, z, inside);313 return true;314 }315 return false;316 }317318 create(type, x, y, z, inside) {319 const def = ZOMBIES[type];320 const shade = randomShade();321 const zo = {322 type,323 def,324 x,325 y,326 z,327 yaw: Math.random() * Math.PI * 2,328 inside,329 shade,330 tint: new Color(def.cloth).offsetHSL(shade.cloth[0], shade.cloth[1], shade.cloth[2]),331 hp: def.hp * eco.hpMult(),332 speed: rand(def.speed[0], def.speed[1]),333 state: 'wander',334 target: null,335 pause: rand(0, 2),336 alertT: 0,337 walkT: rand(0, 6),338 moving: 0,339 dead: false,340 deathT: 0,341 fall: null,342 hitT: 0,343 hitKick: 0,344 group: null,345 own: [],346 p: null,347 };348 this.list.push(zo);349 return zo;350 }351352 353 rig(z) {354 if (z.group) return;355 const built = buildZombieMesh(z.type, z.shade);356 built.group.position.set(z.x, z.y, z.z);357 built.group.rotation.y = z.yaw;358 this.scene.add(built.group);359 z.group = built.group;360 z.own = built.own;361 z.p = built.p;362 }363364 365 unrig(z) {366 if (!z.group) return;367 this.scene.remove(z.group);368 for (const m of z.own) m.dispose();369 z.group = null;370 z.own = [];371 z.p = null;372 }373374 375 updateCrowd() {376 const used = {};377 for (const t of this.types) used[t] = 0;378 for (const z of this.list) {379 if (z.dead || z.group) continue;380 const i = used[z.type]++;381 dummy.position.set(z.x, z.y, z.z);382 dummy.rotation.set(0, z.yaw, 0);383 dummy.scale.set(z.def.scale * z.def.bulk, z.def.scale, z.def.scale * z.def.bulk);384 dummy.updateMatrix();385 const m = this.crowd[z.type];386 m.setMatrixAt(i, dummy.matrix);387 m.setColorAt(i, z.tint);388 }389 for (const t of this.types) {390 const m = this.crowd[t];391 m.count = used[t];392 m.instanceMatrix.needsUpdate = true;393 if (m.instanceColor) m.instanceColor.needsUpdate = true;394 }395 }396397 update(dt, player, isVisible) {398 this.player = player;399 this.groanT -= dt;400 if (this.groanT <= 0) {401 this.groanT = rand(3, 7);402 const near = this.list.filter((z) => !z.dead && !z.inside && Math.hypot(z.x - player.x, z.z - player.z) < 120);403 if (near.length) this.groanFrom(pick(near), 0.6);404 }405406 let spawns = 0;407 const count = this.aliveCount();408 while (count + spawns < this.population && spawns < 2) {409 if (!this.spawnOne(player, isVisible)) break;410 spawns++;411 if (this.aliveCount() >= this.population) break;412 }413414 for (let i = this.list.length - 1; i >= 0; i--) {415 const z = this.list[i];416 if (z.dead) {417 z.deathT += dt;418 419 const k = Math.min(1, z.deathT / 0.45);420 this.topple(z, (1 - Math.pow(1 - k, 3)) * (Math.PI / 2));421 if (z.deathT > 4.5) z.group.position.y -= dt * 0.35;422 if (z.deathT > 6.5) {423 this.unrig(z);424 this.list.splice(i, 1);425 }426 continue;427 }428 const dist = Math.hypot(z.x - player.x, z.z - player.z);429 if (dist > DESPAWN_DIST && !isVisible(z.x, z.y + 1, z.z)) {430 this.unrig(z);431 this.list.splice(i, 1);432 continue;433 }434 if (z.hitT > 0) z.hitT -= dt;435 this.think(z, dt);436 if (dist < this.rigRange) this.rig(z);437 else if (z.group && dist > this.rigRange + RIG_HYSTERESIS) this.unrig(z);438 if (z.group) this.animate(z, dt);439 }440 this.updateCrowd();441 }442443 think(z, dt) {444 if (z.inside) {445 z.moving = 0;446 return;447 }448 if (z.state === 'alert') {449 z.moving = 0;450 z.alertT -= dt;451 if (z.alertT <= 0) {452 z.state = 'wander';453 z.target = null;454 z.pause = rand(1, 3);455 }456 return;457 }458 if (z.pause > 0) {459 z.pause -= dt;460 z.moving = 0;461 return;462 }463 if (!z.target) {464 z.target = this.randomTarget(z);465 if (!z.target) {466 z.pause = rand(0.5, 2);467 return;468 }469 }470 const dx = z.target.x - z.x;471 const dz = z.target.z - z.z;472 const d = Math.hypot(dx, dz);473 if (d <= 0.6) {474 z.target = null;475 z.moving = 0;476 z.pause = rand(1, 4);477 return;478 }479 const step = Math.min(d, z.speed * dt);480 const mx = (dx / d) * step;481 const mz = (dz / d) * step;482 z.yaw = Math.atan2(mx, mz);483 z.moving = z.speed;484 const r = 0.4;485 let moved = false;486 if (!blockedAt(z.x + mx, z.z, r)) {487 z.x += mx;488 moved = true;489 }490 if (!blockedAt(z.x, z.z + mz, r)) {491 z.z += mz;492 moved = true;493 }494 if (!moved) {495 z.target = null;496 z.pause = 0.5;497 }498 }499500 randomTarget(z) {501 const B = this.bounds;502 for (let i = 0; i < 8; i++) {503 const a = Math.random() * Math.PI * 2;504 const d = rand(4, 16);505 const tx = z.x + Math.cos(a) * d;506 const tz = z.z + Math.sin(a) * d;507 if (tx < B.x0 || tx > B.x1 || tz < B.z0 || tz > B.z1) continue;508 if (blockedAt(tx, tz, 0.5) || inBuilding(tx, tz, 0.6) || nearPlayerBuilding(tx, tz, HOUSE_CLEARANCE)) continue;509 return { x: tx, z: tz };510 }511 return null;512 }513514 animate(z, dt) {515 const g = z.group;516 g.position.set(z.x, z.y, z.z);517 g.rotation.y = z.yaw;518 const walking = z.moving > 0.05;519 z.walkT += dt * (walking ? z.moving * 3 : 1.2);520 const m = walking ? Math.min(1, z.moving / 1.5) : 0.15;521 const s = Math.sin(z.walkT);522 const c = Math.cos(z.walkT);523 const p = z.p;524525 p.hips.position.y = 0.98 + Math.abs(c) * 0.03 * m;526 p.spine.rotation.x = z.def.lean + 0.04 * m * Math.sin(2 * z.walkT);527 p.head.rotation.x = 0.12 + 0.05 * Math.sin(z.walkT * 0.6);528 p.head.rotation.z = 0.15 * Math.sin(z.walkT * 0.4);529 p.jaw.rotation.x = 0.25 + 0.12 * Math.sin(z.walkT * 0.7);530531 if (z.hitT > 0) {532 const kick = (z.hitT / 0.3) * z.hitKick;533 p.spine.rotation.x -= 0.35 * kick;534 p.head.rotation.x -= 0.5 * kick;535 p.head.rotation.z += 0.3 * kick * Math.sin(z.hitT * 60);536 }537538 p.legL.rotation.x = s * 0.55 * m;539 p.legR.rotation.x = -s * 0.55 * m;540 p.kneeL.rotation.x = 0.1 + Math.max(0, -s) * 0.9 * m;541 p.kneeR.rotation.x = 0.1 + Math.max(0, s) * 0.9 * m;542543 p.armL.rotation.x = -1.25 + 0.12 * s * m;544 p.armR.rotation.x = -1.25 - 0.12 * s * m;545 p.elL.rotation.x = -0.35 + 0.1 * Math.sin(z.walkT + 1) * m;546 p.elR.rotation.x = -0.35 + 0.1 * Math.sin(z.walkT + 2.5) * m;547 }548549 alertAt(x, z, radius) {550 const heard = [];551 for (const zo of this.list) {552 if (zo.dead) continue;553 if (Math.hypot(zo.x - x, zo.z - z) > radius) continue;554 this.flinch(zo, x, z, rand(6, 14));555 if (!zo.inside) heard.push(zo);556 }557 if (heard.length && Math.random() < 0.5) this.groanFrom(pick(heard), 1);558 }559560 561 groanFrom(zo, loud) {562 const p = this.player;563 if (!p) return;564 const dx = zo.x - p.x;565 const dz = zo.z - p.z;566 const dist = Math.hypot(dx, dz) || 1;567 568 const pan = (dx * Math.cos(p.yaw) - dz * Math.sin(p.yaw)) / dist;569 audio.groan(dist, pan, loud);570 }571572 573 hit(zo, part) {574 zo.hitT = 0.3;575 zo.hitKick = part === 'head' ? 1 : part === 'torso' ? 0.6 : 0.2;576 }577578 flinch(zo, x, z, time = 8) {579 zo.state = 'alert';580 zo.target = null;581 zo.alertT = time;582 zo.moving = 0;583 zo.yaw = Math.atan2(x - zo.x, z - zo.z);584 }585586 kill(z, dirX = 0, dirZ = 0) {587 588 this.rig(z);589 z.dead = true;590 z.deathT = 0;591 z.target = null;592 593 const len = Math.hypot(dirX, dirZ);594 z.fall = len > 0.01 ? { x: dirX / len, z: dirZ / len } : { x: Math.sin(z.yaw), z: Math.cos(z.yaw) };595 this.addPool(z);596 }597598 addPool(z) {599 const { geo, mat } = poolAssets();600 const pool = new Mesh(geo, mat);601 const s = z.def.scale * rand(0.9, 1.4);602 pool.scale.set(s * 1.3, 1, s * (rand(0.8, 1.1)));603 pool.rotation.y = rand(0, Math.PI);604 pool.position.set(z.x + rand(-0.1, 0.1), z.y + 0.02 + this.pools.length * 0.0004, z.z + rand(-0.1, 0.1));605 this.scene.add(pool);606 this.pools.push(pool);607 if (this.pools.length > POOL_MAX) this.scene.remove(this.pools.shift());608 }609610 topple(z, angle) {611 const f = z.fall;612 613 const axis = new Vector3(f.z, 0, -f.x).normalize();614 const tilt = new Quaternion().setFromAxisAngle(axis, angle);615 const yaw = new Quaternion().setFromAxisAngle(UP, z.yaw);616 z.group.quaternion.copy(tilt).multiply(yaw);617 }618619 segmentHit(p0, d) {620 let best = { t: Infinity, z: null, part: null };621 for (const z of this.list) {622 if (z.dead) continue;623 const s = z.def.scale;624 for (const [name, p] of Object.entries(PARTS)) {625 const t = segmentSphere(p0, d, { x: z.x, y: z.y + p.y * s, z: z.z }, p.r * s);626 if (t >= 0 && t < best.t) best = { t, z, part: name };627 }628 }629 return best;630 }631}