space-browser / commits / 02ae4f4
fix: more visual fidelity interacting
@@ -56,6 +56,7 @@ export interface GameConfig {
5656 fuelPerPoint: number;
5757 minSeparation: number;
5858 attachMax: number;
59+ pieceRadius: number;
5960 cargoBaseSlots: number;
6061 cargoPointsPerSlot: number;
6162 maxPieces: number;
@@ -78,7 +79,9 @@ export interface GameConfig {
7879 upgradeCostPerLevel: number;
7980 repairCost: number;
8081 fieldOre: number;
82+ oreRegenSeconds: number;
8183 wreckPieces: number;
84+ lootedDespawnSeconds: number;
8285 };
8386 npc: {
8487 engageRange: number;
@@ -3,17 +3,21 @@ import type { GameConfig } from "./config";
33 import { buildGlyphAtlas, CELL_H, CELL_W, PAL, RAMP } from "./palette";
44 import type { ItemView, NPCView, PlayerView, POI, ProjView, Shape, Vec2 } from "./protocol";
55
6-const PIECE_R = 20;
76 const SHAPES: Shape[] = ["triangle", "square", "circle", "pentagon", "star"];
87
8+// Glyph cells are not square: one scene texel is drawn as CELL_W x CELL_H px.
9+// Point sprites are square in texels, so every sprite shape is stretched back
10+// here or points would render as vertical ovals.
11+const CELL_ASPECT = CELL_H / CELL_W;
12+
913 // Fleet contacts share the gold accent; the mark shape tells them apart:
1014 // a solid disc is a rogue fleet, a hollow ring a friendly one.
1115 const FLEET_COLOR = "#ffcf6b";
1216
1317 // hullRadius is how far the outermost piece reaches from the ship centre.
14-function hullRadius(pieces: PlayerView["ship"]["pieces"]): number {
18+function hullRadius(pieces: PlayerView["ship"]["pieces"], pieceRadius: number): number {
1519 let hull = 0;
16- for (const key in pieces) hull = Math.max(hull, Math.hypot(pieces[key].x, pieces[key].y) + PIECE_R);
20+ for (const key in pieces) hull = Math.max(hull, Math.hypot(pieces[key].x, pieces[key].y) + pieceRadius);
1721 return hull;
1822 }
1923
@@ -41,6 +45,7 @@ attribute vec3 aColor;
4145 attribute float aShape;
4246 attribute float aPhase;
4347 uniform float uZoom;
48+uniform float uAspect;
4449 uniform float uTime;
4550 uniform sampler2D tFog;
4651 uniform float uFogRadius;
@@ -56,16 +61,18 @@ void main() {
5661 vTw = 0.7 + 0.3 * sin(uTime * 1.3 + aPhase);
5762 vec4 mv = modelViewMatrix * vec4(position, 1.0);
5863 gl_Position = projectionMatrix * mv;
59- gl_PointSize = clamp(aSize * 2.0 * uZoom, 1.0, 900.0);
64+ gl_PointSize = clamp(aSize * 2.0 * uZoom * uAspect, 1.0, 900.0);
6065 }
6166 `;
6267
6368 const POINT_FRAG = /* glsl */ `
69+uniform float uAspect;
6470 varying vec3 vColor;
6571 varying float vShape;
6672 varying float vTw;
6773 void main() {
6874 vec2 d = gl_PointCoord * 2.0 - 1.0;
75+ d.y *= uAspect;
6976 float r = length(d);
7077 float a;
7178 if (vShape < 0.5) {
@@ -204,11 +211,11 @@ function galaxyShape(x: number, y: number, sh: GalaxyShape, radius: number): num
204211 return disc * (1 + sh.armStrength * armTerm(x, y, r, sh, radius)) + sh.bulgeWeight * Math.exp(-b * b);
205212 }
206213
207-function polyGeom(n: number, rot: number): THREE.BufferGeometry {
214+function polyGeom(n: number, rot: number, r: number): THREE.BufferGeometry {
208215 const pts: number[] = [];
209216 for (let i = 0; i < n; i++) {
210217 const a = rot + (i / n) * Math.PI * 2;
211- pts.push(Math.cos(a) * PIECE_R, Math.sin(a) * PIECE_R, 0);
218+ pts.push(Math.cos(a) * r, Math.sin(a) * r, 0);
212219 }
213220 const g = new THREE.BufferGeometry();
214221 g.setAttribute("position", new THREE.Float32BufferAttribute(pts, 3));
@@ -218,12 +225,12 @@ function polyGeom(n: number, rot: number): THREE.BufferGeometry {
218225 return g;
219226 }
220227
221-function starGeom(points: number, inner: number): THREE.BufferGeometry {
228+function starGeom(points: number, inner: number, r: number): THREE.BufferGeometry {
222229 const pts: number[] = [];
223230 for (let i = 0; i < points * 2; i++) {
224231 const a = -Math.PI / 2 + (i / (points * 2)) * Math.PI * 2;
225- const r = i % 2 === 0 ? PIECE_R : PIECE_R * inner;
226- pts.push(Math.cos(a) * r, Math.sin(a) * r, 0);
232+ const d = i % 2 === 0 ? r : r * inner;
233+ pts.push(Math.cos(a) * d, Math.sin(a) * d, 0);
227234 }
228235 const g = new THREE.BufferGeometry();
229236 g.setAttribute("position", new THREE.Float32BufferAttribute(pts, 3));
@@ -233,18 +240,18 @@ function starGeom(points: number, inner: number): THREE.BufferGeometry {
233240 return g;
234241 }
235242
236-function pieceGeometry(shape: Shape): THREE.BufferGeometry {
243+function pieceGeometry(shape: Shape, r: number): THREE.BufferGeometry {
237244 switch (shape) {
238245 case "triangle":
239- return polyGeom(3, Math.PI / 2);
246+ return polyGeom(3, Math.PI / 2, r);
240247 case "square":
241- return polyGeom(4, Math.PI / 4);
248+ return polyGeom(4, Math.PI / 4, r);
242249 case "pentagon":
243- return polyGeom(5, Math.PI / 2);
250+ return polyGeom(5, Math.PI / 2, r);
244251 case "star":
245- return starGeom(5, 0.45);
252+ return starGeom(5, 0.45, r);
246253 default:
247- return polyGeom(20, 0);
254+ return polyGeom(20, 0, r);
248255 }
249256 }
250257
@@ -259,7 +266,6 @@ export interface AttachPreview {
259266 x: number;
260267 y: number;
261268 a: number;
262- valid: boolean;
263269 anchor?: { shape: Shape; x: number; y: number; a: number };
264270 }
265271
@@ -295,6 +301,9 @@ export class Engine {
295301 private scale = new THREE.Vector3(1, 1, 1);
296302 private time = 0;
297303 private cfg: GameConfig;
304+ // scale the self hull is drawn at when zoomed out (1 = true size); the
305+ // attach ghost has to use it too, or it drifts away from the cursor.
306+ selfScale = 1;
298307
299308 viewWidth = 2000;
300309 viewHeight = 2000;
@@ -405,7 +414,7 @@ export class Engine {
405414 depthWrite: false,
406415 });
407416 for (const s of SHAPES) {
408- const geo = pieceGeometry(s);
417+ const geo = pieceGeometry(s, cfg.ship.pieceRadius);
409418 this.pieceGeoms[s] = geo;
410419 const mesh = new THREE.InstancedMesh(geo, pieceMat, 4096);
411420 mesh.frustumCulled = false;
@@ -416,7 +425,7 @@ export class Engine {
416425 }
417426
418427 // attach ghosts: translucent filled silhouettes of the piece being placed
419- // and of the piece it will connect to, so the player can see valid spots.
428+ // and of the piece it will connect to, so the player sees where it lands.
420429 this.previewMat = new THREE.MeshBasicMaterial({
421430 color: 0xffcf6b,
422431 transparent: true,
@@ -445,6 +454,7 @@ export class Engine {
445454 const mat = new THREE.ShaderMaterial({
446455 uniforms: {
447456 uZoom: { value: 1 },
457+ uAspect: { value: CELL_ASPECT },
448458 uTime: { value: 0 },
449459 tFog: { value: this.fogTex },
450460 uFogRadius: { value: this.cfg.galaxy.radius },
@@ -594,11 +604,12 @@ export class Engine {
594604 const add = (id: string, pieces: PlayerView["ship"]["pieces"], x: number, y: number, a: number) => {
595605 seen.add(id);
596606 const jig = this.jiggle(id, x, y);
597- const hull = hullRadius(pieces);
607+ const hull = hullRadius(pieces, this.cfg.ship.pieceRadius);
598608 // zoomed out the hull would vanish between two glyph cells: grow it into
599609 // an icon of itself instead, so the player never loses their ship.
600610 const minHull = (ICON_CELLS * this.viewHeight) / this.cells.y;
601611 const k = id === selfId ? Math.max(1, minHull / Math.max(hull, 1)) : 1;
612+ if (id === selfId) this.selfScale = k;
602613 for (const key in pieces) {
603614 const p = pieces[key];
604615 const mesh = this.shipMeshes[p.shape];
@@ -652,7 +663,7 @@ export class Engine {
652663 // fleets read as a glyph block at any zoom: a hot filled disc for rogue
653664 // AI, a hollow ring for a friendly fleet.
654665 const floor = (2 * ICON_CELLS * this.viewHeight) / this.cells.y;
655- const size = Math.max(1.6 * hullRadius(n.ship.pieces), floor);
666+ const size = Math.max(1.6 * hullRadius(n.ship.pieces, this.cfg.ship.pieceRadius), floor);
656667 put(n.x, n.y, size, n.hostile ? 0 : 1, FLEET_COLOR);
657668 }
658669 for (const it of items)
@@ -673,8 +684,8 @@ export class Engine {
673684 this.viewHeight = viewHeight;
674685 }
675686
676- // setAttachPreview shows where a loose piece would attach: a translucent
677- // silhouette of the piece and of the piece it snaps to. Gold when valid.
687+ // setAttachPreview shows where a loose piece will attach: a translucent
688+ // silhouette of the piece and of the piece it snaps to.
678689 setAttachPreview(p: AttachPreview | null) {
679690 if (!p) {
680691 this.previewGhost.visible = false;
@@ -684,13 +695,11 @@ export class Engine {
684695 this.previewGhost.geometry = this.pieceGeoms[p.shape];
685696 this.previewGhost.position.set(p.x, p.y, 2);
686697 this.previewGhost.rotation.z = p.a;
687- this.previewMat.color.set(p.valid ? "#ffcf6b" : "#ff7a3c");
688698 this.previewGhost.visible = true;
689699 if (p.anchor) {
690700 this.anchorGhost.geometry = this.pieceGeoms[p.anchor.shape];
691701 this.anchorGhost.position.set(p.anchor.x, p.anchor.y, 1.5);
692702 this.anchorGhost.rotation.z = p.anchor.a;
693- this.anchorMat.color.set(p.valid ? "#c18f45" : "#ff7a3c");
694703 this.anchorGhost.visible = true;
695704 } else {
696705 this.anchorGhost.visible = false;
@@ -131,6 +131,7 @@ class Game {
131131 break;
132132 case "explore":
133133 for (const p of m.pois) this.pois.set(p.id, p);
134+ for (const id of m.gone ?? []) this.pois.delete(id);
134135 this.syncPOIs();
135136 break;
136137 case "named": {
@@ -263,8 +264,10 @@ class Game {
263264 const dt = Math.min(0.1, (now - this.last) / 1000);
264265 this.last = now;
265266
266- const k = 1 - Math.exp(-12 * dt);
267267 for (const e of [...this.players.values(), ...this.npcs.values()]) {
268+ // own hull follows the server almost exactly: a lagging hull would be
269+ // somewhere else than the ship the server collides with.
270+ const k = 1 - Math.exp(-(e.id === this.selfId ? 40 : 12) * dt);
268271 e.x += (e.tx - e.x) * k;
269272 e.y += (e.ty - e.y) * k;
270273 let da = e.ta - e.a;
@@ -321,11 +324,7 @@ class Game {
321324 const world = this.camera.screenToWorld(this.lastPointer.x, this.lastPointer.y);
322325 const s = this.placeSpot(world);
323326 this.engine.setAttachPreview(s ? this.toPreview(s) : null);
324- this.hud.setHint(
325- s && s.valid ? "click to attach" : "piece must touch the hull, without overlapping",
326- this.lastPointer.x,
327- this.lastPointer.y,
328- );
327+ this.hud.setHint(s ? "click to attach" : "no room on the hull", this.lastPointer.x, this.lastPointer.y);
329328 return;
330329 }
331330 const hit = this.pick(this.lastPointer.x, this.lastPointer.y);
@@ -365,12 +364,11 @@ class Game {
365364 private placePiece(world: Vec2) {
366365 if (!this.self || !this.attachItem) return;
367366 const s = this.placeSpot(world);
368- if (!s) return;
369- if (!s.valid) {
370- this.hud.toast("piece must touch the hull, without overlapping");
367+ if (!s) {
368+ this.hud.toast("no room on the hull");
371369 return;
372370 }
373- this.send({ t: "attach", target: this.attachItem, piece: s.anchorId, x: s.localX, y: s.localY });
371+ this.send({ t: "attach", target: this.attachItem, x: s.localX, y: s.localY });
374372 this.cancelAttach();
375373 }
376374
@@ -386,8 +384,9 @@ class Game {
386384 return this.players.get(this.selfId) ?? this.self;
387385 }
388386
389- // placeSpot maps the cursor to a spot on the hull: anywhere the loose piece
390- // stays connected to it and clear of every other piece.
387+ // placeSpot maps the cursor to the spot the piece will land on: the cursor
388+ // itself when that spot is in reach and clear, else the closest free spot
389+ // that touches the hull. Mirrors the server's attachSpot.
391390 private placeSpot(world: Vec2): Snap | null {
392391 const me = this.me();
393392 const self = this.self;
@@ -395,38 +394,46 @@ class Game {
395394 const item = this.items.find((i) => i.id === this.attachItem);
396395 const shape = item?.item.shape;
397396 if (!shape) return null;
397+ const k = this.engine.selfScale;
398398 const a = me.a;
399- const local = rotate({ x: world.x - me.x, y: world.y - me.y }, -a);
399+ // the hull is drawn k times larger when zoomed out: undo that first
400+ const want = rotate({ x: (world.x - me.x) / k, y: (world.y - me.y) / k }, -a);
400401 const pieces = Object.values(self.ship.pieces);
401402 if (!pieces.length) return null;
403+ const sep = this.cfg.ship.minSeparation;
404+ const gap = (x: number, y: number, q: Vec2) => Math.hypot(q.x - x, q.y - y);
405+ const clear = (x: number, y: number) => pieces.every((q) => gap(x, y, q) >= sep);
402406 let anchor = pieces[0];
403- let bestD = Infinity;
404- for (const q of pieces) {
405- const d = Math.hypot(q.x - local.x, q.y - local.y);
406- if (d < bestD) {
407- bestD = d;
408- anchor = q;
409- }
410- }
411- let valid = bestD <= this.cfg.ship.attachMax;
412- for (const q of pieces) {
413- if (Math.hypot(q.x - local.x, q.y - local.y) < this.cfg.ship.minSeparation) {
414- valid = false;
415- break;
407+ for (const q of pieces) if (gap(want.x, want.y, q) < gap(want.x, want.y, anchor)) anchor = q;
408+ let spot = want;
409+ if (gap(want.x, want.y, anchor) > this.cfg.ship.attachMax || !clear(want.x, want.y)) {
410+ let bestD = Infinity;
411+ for (const q of pieces) {
412+ const base = Math.atan2(want.y - q.y, want.x - q.x);
413+ for (let i = 0; i < 16; i++) {
414+ const ang = base + (i * Math.PI) / 8;
415+ const px = q.x + Math.cos(ang) * sep;
416+ const py = q.y + Math.sin(ang) * sep;
417+ const d = gap(want.x, want.y, { x: px, y: py });
418+ if (d < bestD && clear(px, py)) {
419+ bestD = d;
420+ spot = { x: px, y: py };
421+ anchor = q;
422+ }
423+ }
416424 }
425+ if (bestD === Infinity) return null;
417426 }
418427 const toWorld = (x: number, y: number): Vec2 => ({
419- x: me.x + Math.cos(a) * x - Math.sin(a) * y,
420- y: me.y + Math.sin(a) * x + Math.cos(a) * y,
428+ x: me.x + k * (Math.cos(a) * x - Math.sin(a) * y),
429+ y: me.y + k * (Math.sin(a) * x + Math.cos(a) * y),
421430 });
422431 return {
423432 shape,
424- anchorId: anchor.id,
425433 anchorShape: anchor.shape,
426- localX: local.x,
427- localY: local.y,
428- valid,
429- world: toWorld(local.x, local.y),
434+ localX: spot.x,
435+ localY: spot.y,
436+ world: toWorld(spot.x, spot.y),
430437 anchorWorld: toWorld(anchor.x, anchor.y),
431438 a,
432439 };
@@ -438,7 +445,6 @@ class Game {
438445 x: s.world.x,
439446 y: s.world.y,
440447 a: s.a,
441- valid: s.valid,
442448 anchor: { shape: s.anchorShape, x: s.anchorWorld.x, y: s.anchorWorld.y, a: s.a },
443449 };
444450 }
@@ -457,12 +463,27 @@ class Game {
457463 }
458464 };
459465 const ppu = this.camera.pixelsPerUnit();
466+ // loose pieces come first: a piece lying under the hull must still be
467+ // reachable, or it can never be attached again.
468+ for (const it of this.items) {
469+ const s = this.camera.worldToScreen(it.x, it.y);
470+ consider({
471+ kind: "item",
472+ id: it.id,
473+ sx: s.x,
474+ sy: s.y,
475+ w: { x: it.x, y: it.y },
476+ screenR: this.cfg.ship.pieceRadius * ppu,
477+ hint: it.item.kind === "ore" ? "ore" : `${it.item.shape} ${it.item.q}\u2605`,
478+ });
479+ }
460480 const me = this.me();
461481 if (me && this.self) {
462482 const a = me.a;
483+ const k = this.engine.selfScale;
463484 for (const p of Object.values(this.self.ship.pieces)) {
464- const wx = me.x + Math.cos(a) * p.x - Math.sin(a) * p.y;
465- const wy = me.y + Math.sin(a) * p.x + Math.cos(a) * p.y;
485+ const wx = me.x + k * (Math.cos(a) * p.x - Math.sin(a) * p.y);
486+ const wy = me.y + k * (Math.sin(a) * p.x + Math.cos(a) * p.y);
466487 const s = this.camera.worldToScreen(wx, wy);
467488 consider({
468489 kind: "piece",
@@ -470,7 +491,7 @@ class Game {
470491 sx: s.x,
471492 sy: s.y,
472493 w: { x: wx, y: wy },
473- screenR: Math.max(8, 20 * ppu),
494+ screenR: Math.max(8, k * this.cfg.ship.pieceRadius * ppu),
474495 hint: `${p.shape} ${p.q}\u2605 ${Math.round(p.hp)}/${Math.round(p.maxHp)}`,
475496 });
476497 }
@@ -500,18 +521,6 @@ class Game {
500521 hint: n.name,
501522 });
502523 }
503- for (const it of this.items) {
504- const s = this.camera.worldToScreen(it.x, it.y);
505- consider({
506- kind: "item",
507- id: it.id,
508- sx: s.x,
509- sy: s.y,
510- w: { x: it.x, y: it.y },
511- screenR: 20,
512- hint: it.item.kind,
513- });
514- }
515524 for (const poi of this.pois.values()) {
516525 if (poi.kind === "fleet") continue;
517526 const s = this.camera.worldToScreen(poi.x, poi.y);
@@ -678,11 +687,9 @@ interface Pick {
678687
679688 interface Snap {
680689 shape: Shape;
681- anchorId: number;
682690 anchorShape: Shape;
683691 localX: number;
684692 localY: number;
685- valid: boolean;
686693 world: Vec2;
687694 anchorWorld: Vec2;
688695 a: number;
@@ -143,7 +143,7 @@ export type ServerMsg =
143143 dotsHz: number;
144144 }
145145 | { t: "dots"; pois: POI[]; fog: string }
146- | { t: "explore"; pois: POI[] }
146+ | { t: "explore"; pois: POI[]; gone?: string[] }
147147 | { t: "fog"; reveals: [number, number, number][] }
148148 | { t: "named"; id: string; name: string; by: string }
149149 | {
@@ -169,7 +169,7 @@ export type ClientMsg =
169169 | { t: "orbit"; target: string }
170170 | { t: "name"; target: string; name: string }
171171 | { t: "detach"; piece: number }
172- | { t: "attach"; target: string; piece: number; x: number; y: number }
172+ | { t: "attach"; target: string; x: number; y: number }
173173 | { t: "cargo"; target: string }
174174 | { t: "eject"; slot: number }
175175 | { t: "pickup"; target: string }
@@ -80,6 +80,7 @@ type Config struct {
8080 FuelPerPoint float64 `json:"fuelPerPoint"`
8181 MinSeparation float64 `json:"minSeparation"`
8282 AttachMax float64 `json:"attachMax"`
83+ PieceRadius float64 `json:"pieceRadius"`
8384 CargoBaseSlots float64 `json:"cargoBaseSlots"`
8485 CargoPointsPerSlot float64 `json:"cargoPointsPerSlot"`
8586 } `json:"ship"`
@@ -100,14 +101,16 @@ type Config struct {
100101 LocalRange float64 `json:"localRange"`
101102 } `json:"radio"`
102103 Cargo struct {
103- PickupRange float64 `json:"pickupRange"`
104- EjectSpeed float64 `json:"ejectSpeed"`
105- RePickDelay float64 `json:"rePickDelay"`
106- CraftCost int `json:"craftCost"`
107- UpgradeCostPerLevel int `json:"upgradeCostPerLevel"`
108- RepairCost int `json:"repairCost"`
109- FieldOre int `json:"fieldOre"`
110- WreckPieces int `json:"wreckPieces"`
104+ PickupRange float64 `json:"pickupRange"`
105+ EjectSpeed float64 `json:"ejectSpeed"`
106+ RePickDelay float64 `json:"rePickDelay"`
107+ CraftCost int `json:"craftCost"`
108+ UpgradeCostPerLevel int `json:"upgradeCostPerLevel"`
109+ RepairCost int `json:"repairCost"`
110+ FieldOre int `json:"fieldOre"`
111+ OreRegenSeconds float64 `json:"oreRegenSeconds"`
112+ WreckPieces int `json:"wreckPieces"`
113+ LootedDespawnSeconds float64 `json:"lootedDespawnSeconds"`
111114 } `json:"cargo"`
112115 NPC struct {
113116 EngageRange float64 `json:"engageRange"`
@@ -70,6 +70,7 @@
7070 "fuelPerPoint": 10,
7171 "minSeparation": 45,
7272 "attachMax": 140,
73+ "pieceRadius": 20,
7374 "cargoBaseSlots": 4,
7475 "cargoPointsPerSlot": 2.5
7576 },
@@ -97,7 +98,9 @@
9798 "upgradeCostPerLevel": 3,
9899 "repairCost": 1,
99100 "fieldOre": 10,
100- "wreckPieces": 2
101+ "oreRegenSeconds": 300,
102+ "wreckPieces": 2,
103+ "lootedDespawnSeconds": 8
101104 },
102105 "npc": {
103106 "engageRange": 1500,
@@ -92,6 +92,57 @@ func (w *World) salvage(p *Player, poi *POI) {
9292 p.Stats.PiecesGathered++
9393 }
9494 }
95+ w.poiChanged(poi)
96+}
97+
98+// lootable reports whether a poi still holds something to take.
99+func (p *POI) lootable() bool {
100+ switch p.Kind {
101+ case kindAsteroid:
102+ return p.Ore > 0
103+ case kindWreck:
104+ return len(p.Wreck) > 0
105+ }
106+ return false
107+}
108+
109+// poiChanged publishes a poi whose contents changed, and starts the despawn
110+// countdown the moment a poi has been looted empty.
111+func (w *World) poiChanged(poi *POI) {
112+ if !poi.lootable() && poi.emptyAt == 0 {
113+ poi.emptyAt = w.t
114+ }
115+ w.poiOut[poi.ID] = poi
116+}
117+
118+// stepPOIs regrows depleted asteroid fields and clears away wrecks that have
119+// been looted empty.
120+func (w *World) stepPOIs() {
121+ var gone []*POI
122+ for _, poi := range w.galaxy.POIs {
123+ switch poi.Kind {
124+ case kindAsteroid:
125+ switch {
126+ case poi.Ore >= poi.OreMax:
127+ poi.regenAt = 0
128+ case poi.regenAt == 0:
129+ poi.regenAt = w.t + config.Cargo.OreRegenSeconds
130+ case w.t >= poi.regenAt:
131+ poi.Ore++
132+ poi.regenAt = w.t + config.Cargo.OreRegenSeconds
133+ w.poiOut[poi.ID] = poi
134+ }
135+ case kindWreck:
136+ if poi.emptyAt > 0 && w.t-poi.emptyAt >= config.Cargo.LootedDespawnSeconds {
137+ gone = append(gone, poi)
138+ }
139+ }
140+ }
141+ for _, poi := range gone {
142+ w.galaxy.remove(poi.ID)
143+ delete(w.poiOut, poi.ID)
144+ w.poiGone = append(w.poiGone, poi.ID)
145+ }
95146 }
96147
97148 func (w *World) removeOre(p *Player, n int) bool {
@@ -32,8 +32,11 @@ type POI struct {
3232 NamedBy string `json:"by,omitempty"`
3333 sent bool // already announced to clients (fog decides visibility)
3434
35- Ore int `json:"ore,omitempty"`
36- Wreck []*Piece `json:"wreck,omitempty"`
35+ Ore int `json:"ore,omitempty"`
36+ OreMax int `json:"-"`
37+ Wreck []*Piece `json:"wreck,omitempty"`
38+ emptyAt float64 // world time the poi was emptied, 0 while it still holds loot
39+ regenAt float64 // world time the next ore appears in a depleted field
3740
3841 Hostile bool `json:"hostile,omitempty"`
3942 FleetCap int `json:"-"`
@@ -485,6 +488,7 @@ func (g *Galaxy) satellite(r *rng, star *POI, kind string, hosts []*POI, sysR fl
485488 switch kind {
486489 case kindAsteroid:
487490 p.Ore = config.Cargo.FieldOre
491+ p.OreMax = p.Ore
488492 case kindComms:
489493 p.Linked = map[string]bool{}
490494 case kindWreck:
@@ -50,7 +50,7 @@ func (w *World) handle(c *Client, m *InMsg) {
5050 case "detach":
5151 w.detach(p, m.Piece)
5252 case "attach":
53- w.attach(p, m.Target, m.Piece, m.X, m.Y)
53+ w.attach(p, m.Target, m.X, m.Y)
5454 case "cargo":
5555 w.stow(p, m.Target)
5656 case "eject":
@@ -231,10 +231,12 @@ func (w *World) stepPlayer(p *Player, dt float64) {
231231 w.fireShip(p.ID, p.Ship, p.Pos, p.Angle, p.Target, dt, p.fire)
232232 }
233233
234-// touchesStar reports whether any piece of the ship overlaps a star.
234+// touchesStar reports whether any piece of the ship overlaps a star. The
235+// piece's own reach counts, so the collision happens exactly where the player
236+// sees the hull touch the star.
235237 func (w *World) touchesStar(p *Player) bool {
236238 for _, piece := range p.Ship.piecesSlice() {
237- if w.galaxy.starAt(p.Pos.Add(rotate(Vec2{piece.X, piece.Y}, p.Angle)), 0) != nil {
239+ if w.galaxy.starAt(p.Pos.Add(rotate(Vec2{piece.X, piece.Y}, p.Angle)), config.Ship.PieceRadius) != nil {
238240 return true
239241 }
240242 }
@@ -288,27 +290,22 @@ func (w *World) detach(p *Player, pieceID int) {
288290 }
289291 }
290292
291-func (w *World) attach(p *Player, itemID string, to int, x, y float64) {
293+func (w *World) attach(p *Player, itemID string, x, y float64) {
292294 it, ok := w.items[itemID]
293- if !ok || it.Item.Kind != "piece" || p.Pos.Dist(it.Pos) > config.Cargo.PickupRange {
295+ if !ok || it.Item.Kind != "piece" {
294296 return
295297 }
296- if _, ok := p.Ship.Pieces[to]; !ok {
298+ if p.Pos.Dist(it.Pos) > config.Cargo.PickupRange {
299+ w.toast(p, "the loose piece is out of reach")
297300 return
298301 }
299- np := Vec2{x, y}
300- if np.Dist(Vec2{p.Ship.Pieces[to].X, p.Ship.Pieces[to].Y}) > config.Ship.AttachMax {
301- w.toast(p, "piece is not adjacent")
302+ spot, to, ok := p.Ship.attachSpot(Vec2{x, y})
303+ if !ok {
304+ w.toast(p, "no room left on the hull")
302305 return
303306 }
304- for _, q := range p.Ship.Pieces {
305- if np.Dist(Vec2{q.X, q.Y}) < config.Ship.MinSeparation {
306- w.toast(p, "pieces would overlap")
307- return
308- }
309- }
310307 piece := newPiece(p.Ship.nextID, it.Item.Shape, it.Item.Quality)
311- piece.X, piece.Y = x, y
308+ piece.X, piece.Y = spot.X, spot.Y
312309 if it.Item.HP > 0 {
313310 piece.HP = it.Item.HP
314311 }
@@ -322,7 +319,7 @@ func (w *World) attach(p *Player, itemID string, to int, x, y float64) {
322319 p.Ship.connect(to, piece.ID)
323320 link := config.Ship.MinSeparation * 1.2
324321 for _, q := range p.Ship.Pieces {
325- if q.ID != piece.ID && np.Dist(Vec2{q.X, q.Y}) <= link {
322+ if q.ID != piece.ID && spot.Dist(Vec2{q.X, q.Y}) <= link {
326323 p.Ship.connect(q.ID, piece.ID)
327324 }
328325 }
@@ -117,15 +117,27 @@ func (w *World) selfMessage(p *Player) map[string]any {
117117 }
118118 }
119119
120-// broadcastDots is the slow loop: shared fog-of-war reveals and new names.
120+// broadcastDots is the slow loop: shared fog-of-war reveals, new names, and
121+// the pois whose loot changed or that are gone.
121122 func (w *World) broadcastDots() {
122123 w.mu.Lock()
123124 defer w.mu.Unlock()
124- if len(w.newPOIs) > 0 {
125+ for id, poi := range w.poiOut {
126+ if w.fog.known(poi.Pos()) {
127+ w.newPOIs = append(w.newPOIs, poi)
128+ }
129+ delete(w.poiOut, id)
130+ }
131+ if len(w.newPOIs) > 0 || len(w.poiGone) > 0 {
132+ pois := w.newPOIs
133+ if pois == nil {
134+ pois = []*POI{}
135+ }
125136 for c := range w.clients {
126- c.push(map[string]any{"t": "explore", "pois": w.newPOIs})
137+ c.push(map[string]any{"t": "explore", "pois": pois, "gone": w.poiGone})
127138 }
128139 w.newPOIs = nil
140+ w.poiGone = nil
129141 }
130142 if len(w.fogOut) > 0 {
131143 reveals := make([]any, 0, len(w.fogOut))
@@ -1,5 +1,7 @@
11 package main
22
3+import "math"
4+
35 const maxQuality = 3
46
57 var allShapes = []string{"triangle", "square", "circle", "pentagon", "star"}
@@ -144,6 +146,57 @@ func (s *Ship) cluster(start int) map[int]bool {
144146 return seen
145147 }
146148
149+// nearestPiece returns the piece closest to a local point.
150+func (s *Ship) nearestPiece(p Vec2) *Piece {
151+ best, bestD := (*Piece)(nil), math.Inf(1)
152+ for _, q := range s.Pieces {
153+ if d := p.Dist(Vec2{q.X, q.Y}); d < bestD {
154+ bestD, best = d, q
155+ }
156+ }
157+ return best
158+}
159+
160+// clearOf reports whether a local point keeps minSeparation from every piece.
161+func (s *Ship) clearOf(p Vec2) bool {
162+ for _, q := range s.Pieces {
163+ if p.Dist(Vec2{q.X, q.Y}) < config.Ship.MinSeparation {
164+ return false
165+ }
166+ }
167+ return true
168+}
169+
170+// attachSpot returns the place nearest want a loose piece can sit: within the
171+// hull's reach and clear of every piece. When that fails it slides the piece
172+// to the closest free spot that touches the hull, so a piece can always be
173+// added while the ship has room. The int is the anchor the piece connects to.
174+func (s *Ship) attachSpot(want Vec2) (Vec2, int, bool) {
175+ anchor := s.nearestPiece(want)
176+ if anchor == nil {
177+ return want, -1, true
178+ }
179+ if want.Dist(Vec2{anchor.X, anchor.Y}) <= config.Ship.AttachMax && s.clearOf(want) {
180+ return want, anchor.ID, true
181+ }
182+ best, bestID, bestD := Vec2{}, -1, math.Inf(1)
183+ for _, q := range s.Pieces {
184+ qp := Vec2{q.X, q.Y}
185+ base := want.Sub(qp).Angle()
186+ for i := 0; i < 16; i++ {
187+ spot := qp.Add(Vec2{math.Cos(base), math.Sin(base)}.Mul(config.Ship.MinSeparation))
188+ base += math.Pi / 8
189+ if !s.clearOf(spot) {
190+ continue
191+ }
192+ if d := spot.Dist(want); d < bestD {
193+ best, bestID, bestD = spot, q.ID, d
194+ }
195+ }
196+ }
197+ return best, bestID, bestID >= 0
198+}
199+
147200 // sever removes every piece not connected to the root and returns them.
148201 func (s *Ship) sever() []*Piece {
149202 keep := s.cluster(s.Root)
@@ -98,6 +98,9 @@ type World struct {
9898 spawned int
9999 rng *rng
100100 newPOIs []*POI
101+ poiOut map[string]*POI
102+ poiGone []string
103+ poiAt float64
101104 fog fogMask
102105 fogOut []fogReveal
103106 fogDirty bool
@@ -130,6 +133,7 @@ func newWorld(store *Store, g *Galaxy) *World {
130133 clients: map[*Client]bool{},
131134 cmd: make(chan func(), 1024),
132135 rng: newRNG(g.Seed ^ 0x1234),
136+ poiOut: map[string]*POI{},
133137 fog: newFogMask(),
134138 }
135139 if w.store != nil {
@@ -201,6 +205,11 @@ func (w *World) step(dt float64) {
201205 w.stepProjectiles(dt)
202206 w.stepItems(dt)
203207 w.reapPlayers()
208+ // loot and ore counts move slowly, once a second is plenty
209+ if w.t-w.poiAt >= 1 {
210+ w.poiAt = w.t
211+ w.stepPOIs()
212+ }
204213 }
205214
206215 // clearFog lifts the shared fog of war: the disc is cleared, queued for