space-browser / commits / 7a2eb8e
fix: big polish pass, fixing most game breaking issues
@@ -80,6 +80,7 @@ export interface GameConfig {
8080 npc: {
8181 engageRange: number;
8282 hailRange: number;
83+ safeRadius: number;
8384 minFleetSize: number;
8485 maxFleetSize: number;
8586 };
@@ -195,6 +195,15 @@ interface ShipInstance {
195195 a: number;
196196 }
197197
198+export interface AttachPreview {
199+ shape: Shape;
200+ x: number;
201+ y: number;
202+ a: number;
203+ valid: boolean;
204+ anchor?: { shape: Shape; x: number; y: number; a: number };
205+}
206+
198207 export class Engine {
199208 private renderer: THREE.WebGLRenderer;
200209 private scene = new THREE.Scene();
@@ -214,6 +223,11 @@ export class Engine {
214223 private projCol: Float32Array;
215224 private projCount = 0;
216225 private shipMeshes: Record<Shape, THREE.InstancedMesh>;
226+ private pieceGeoms: Record<Shape, THREE.BufferGeometry>;
227+ private previewGhost: THREE.Mesh;
228+ private anchorGhost: THREE.Mesh;
229+ private previewMat: THREE.MeshBasicMaterial;
230+ private anchorMat: THREE.MeshBasicMaterial;
217231 private matrix = new THREE.Matrix4();
218232 private pos = new THREE.Vector3();
219233 private quat = new THREE.Quaternion();
@@ -299,9 +313,12 @@ export class Engine {
299313 this.scene.add(this.projPoints);
300314
301315 this.shipMeshes = {} as Record<Shape, THREE.InstancedMesh>;
316+ this.pieceGeoms = {} as Record<Shape, THREE.BufferGeometry>;
302317 for (const s of SHAPES) {
318+ const geo = pieceGeometry(s);
319+ this.pieceGeoms[s] = geo;
303320 const mesh = new THREE.InstancedMesh(
304- pieceGeometry(s),
321+ geo,
305322 new THREE.MeshBasicMaterial({ color: 0xffffff }),
306323 4096,
307324 );
@@ -312,6 +329,27 @@ export class Engine {
312329 this.scene.add(mesh);
313330 }
314331
332+ // attach ghosts: translucent filled silhouettes of the piece being placed
333+ // and of the piece it will connect to, so the player can see valid spots.
334+ this.previewMat = new THREE.MeshBasicMaterial({
335+ color: 0xffcf6b,
336+ transparent: true,
337+ opacity: 0.55,
338+ depthTest: false,
339+ depthWrite: false,
340+ });
341+ this.anchorMat = this.previewMat.clone();
342+ this.anchorMat.opacity = 0.4;
343+ this.anchorMat.color.set("#c18f45");
344+ this.previewGhost = new THREE.Mesh(this.pieceGeoms.circle, this.previewMat);
345+ this.anchorGhost = new THREE.Mesh(this.pieceGeoms.circle, this.anchorMat);
346+ for (const g of [this.previewGhost, this.anchorGhost]) {
347+ g.frustumCulled = false;
348+ g.visible = false;
349+ g.renderOrder = 10;
350+ this.scene.add(g);
351+ }
352+
315353 this.resize();
316354 }
317355
@@ -440,7 +478,7 @@ export class Engine {
440478 for (const p of projs) put(p.x, p.y, 8, 0, "#ffcf6b");
441479 for (const it of items)
442480 put(it.x, it.y, 10, it.item.kind === "ore" ? 1 : 2, it.item.kind === "ore" ? "#8a5f2c" : "#ffcf6b");
443- for (const m of markers) put(m.x, m.y, 7, 2, "#ffcf6b");
481+ for (const m of markers ?? []) put(m.x, m.y, 7, 2, "#ffcf6b");
444482 this.projCount = i;
445483 this.projGeom.setDrawRange(0, i);
446484 (this.projGeom.getAttribute("position") as THREE.BufferAttribute).needsUpdate = true;
@@ -456,6 +494,30 @@ export class Engine {
456494 this.viewHeight = viewHeight;
457495 }
458496
497+ // setAttachPreview shows where a loose piece would attach: a translucent
498+ // silhouette of the piece and of the piece it snaps to. Gold when valid.
499+ setAttachPreview(p: AttachPreview | null) {
500+ if (!p) {
501+ this.previewGhost.visible = false;
502+ this.anchorGhost.visible = false;
503+ return;
504+ }
505+ this.previewGhost.geometry = this.pieceGeoms[p.shape];
506+ this.previewGhost.position.set(p.x, p.y, 2);
507+ this.previewGhost.rotation.z = p.a;
508+ this.previewMat.color.set(p.valid ? "#ffcf6b" : "#ff7a3c");
509+ this.previewGhost.visible = true;
510+ if (p.anchor) {
511+ this.anchorGhost.geometry = this.pieceGeoms[p.anchor.shape];
512+ this.anchorGhost.position.set(p.anchor.x, p.anchor.y, 1.5);
513+ this.anchorGhost.rotation.z = p.anchor.a;
514+ this.anchorMat.color.set(p.valid ? "#c18f45" : "#ff7a3c");
515+ this.anchorGhost.visible = true;
516+ } else {
517+ this.anchorGhost.visible = false;
518+ }
519+ }
520+
459521 resize() {
460522 const w = window.innerWidth;
461523 const h = window.innerHeight;
@@ -33,10 +33,10 @@ export type Location = { id: string; kind: POIKind; name: string } | null;
3333
3434 export class HUD {
3535 private root: HTMLElement;
36+ private tlPanel = el("div", "panel tl");
3637 private call = el("div", "call");
3738 private loc = el("div", "loc");
38- private statsRow = el("div", "row");
39- private hpRow = el("div", "row");
39+ private hpRow = el("div", "row hull");
4040 private fuelLabel = el("div", "label");
4141 private fuelMeter = el("div", "meter");
4242 private fuelFill = el("div", "fill");
@@ -44,22 +44,25 @@ export class HUD {
4444 private cargoLabel = el("div", "label");
4545 private cargoBox = el("div", "cargo");
4646 private piecesBox = el("div", "pieces");
47- private targetBox = el("div", "target");
47+ private targetPanel = el("div", "panel target");
48+ private targetBox = el("div", "target-inner");
4849 private radioLog = el("div", "log");
4950 private radioInput = el("input") as HTMLInputElement;
5051 private toasts = el("div", "toasts");
5152 private hint = el("div", "hint");
5253 private conn = el("div", "conn");
53- private keyhint = el("div", "keyhint");
5454 private side = el("div", "side");
5555 private ctx: HTMLElement | null = null;
5656
5757 onRadioSend: (text: string) => void = () => {};
5858 onEject: (slot: number) => void = () => {};
59+ resolveName: (id: string) => string = (id) => id;
5960
6061 constructor(root: HTMLElement) {
6162 this.root = root;
6263 this.build();
64+ this.targetPanel.hidden = true;
65+ this.tlPanel.hidden = true;
6366 window.addEventListener("resize", () => {});
6467 window.addEventListener("keydown", (e) => {
6568 const tag = (document.activeElement?.tagName ?? "").toLowerCase();
@@ -71,14 +74,10 @@ export class HUD {
7174 }
7275
7376 private build() {
74- const tl = el("div", "panel tl");
75- const locWrap = el("div");
76- locWrap.append(this.loc);
77- tl.append(this.call, locWrap, this.hpRow, this.statsRow, this.fuelMeter, this.fuelLabel, this.cargoLabel, this.cargoBox, this.piecesBox);
77+ this.tlPanel.append(this.call, this.loc, this.hpRow, this.piecesBox, this.fuelMeter, this.fuelLabel, this.cargoLabel, this.cargoBox);
7878 this.fuelMeter.append(this.fuelGhost, this.fuelFill);
7979
80- const target = el("div", "panel target");
81- target.append(this.targetBox);
80+ this.targetPanel.append(this.targetBox);
8281
8382 const radio = el("div", "panel radio");
8483 const inputRow = el("div", "input");
@@ -95,8 +94,7 @@ export class HUD {
9594 inputRow.append(this.radioInput);
9695 radio.append(this.radioLog, inputRow);
9796
98- this.keyhint.textContent = "? help wheel zoom drag-pan LMB move/attack RMB menu";
99- this.root.append(tl, target, radio, this.side, this.toasts, this.hint, this.keyhint);
97+ this.root.append(this.tlPanel, this.targetPanel, radio, this.side, this.toasts, this.hint);
10098 this.root.append(this.conn);
10199 }
102100
@@ -109,10 +107,11 @@ export class HUD {
109107 this.call.textContent = "";
110108 this.loc.textContent = "";
111109 this.hpRow.innerHTML = "";
112- this.statsRow.innerHTML = "";
113110 this.cargoBox.innerHTML = "";
114111 this.piecesBox.innerHTML = "";
115112 this.targetBox.innerHTML = "";
113+ this.targetPanel.hidden = true;
114+ this.tlPanel.hidden = true;
116115 this.fuelFill.style.width = "0%";
117116 this.fuelGhost.style.width = "0%";
118117 this.lastFuel = 0;
@@ -124,6 +123,7 @@ export class HUD {
124123
125124 update(self: SelfView | null, location: Location) {
126125 if (!self) return;
126+ this.tlPanel.hidden = false;
127127 this.call.textContent = self.callsign + (self.combat ? " [combat]" : "");
128128 if (location) {
129129 this.loc.innerHTML = "";
@@ -133,15 +133,9 @@ export class HUD {
133133 } else {
134134 this.loc.textContent = "deep space";
135135 }
136+
136137 this.hpRow.innerHTML = "";
137138 this.hpRow.append(el("span", "stat", `HULL ${Math.round(self.hp)}/${Math.round(self.maxHp)}`));
138- this.hpRow.append(el("span", "stat", `SPD ${self.speed}`));
139-
140- this.statsRow.innerHTML = "";
141- const s = self.stats;
142- this.statsRow.append(el("span", "stat", `ATK ${fmt(s.atk)}`));
143- this.statsRow.append(el("span", "stat", `DEF ${fmt(s.def)}`));
144- this.statsRow.append(el("span", "stat", `FUEL+ ${fmt(s.fuel)}`));
145139
146140 const fr = self.fuelCap > 0 ? self.fuel / self.fuelCap : 0;
147141 this.fuelFill.style.width = `${Math.max(0, Math.min(1, fr)) * 100}%`;
@@ -171,12 +165,13 @@ export class HUD {
171165 this.piecesBox.innerHTML = "";
172166 const pieces = Object.values(self.ship.pieces).sort((a, b) => a.id - b.id);
173167 for (const p of pieces) {
174- const c = el("div", "pc");
168+ const frac = Math.max(0, p.hp / p.maxHp);
169+ const c = el("div", "pc" + (frac < 0.4 ? " low" : ""));
175170 c.textContent = SHAPE_GLYPH[p.shape];
176171 c.title = `${p.shape} ${stars(p.q)} ${Math.round(p.hp)}/${Math.round(p.maxHp)}`;
172+ c.append(el("span", "q", String(p.q)));
177173 const bar = el("div", "hpbar");
178- bar.style.width = `${Math.max(0, p.hp / p.maxHp) * 100}%`;
179- if (p.hp / p.maxHp < 0.4) bar.style.background = "var(--hot)";
174+ bar.style.width = `${frac * 100}%`;
180175 c.append(bar);
181176 this.piecesBox.append(c);
182177 }
@@ -185,19 +180,22 @@ export class HUD {
185180 }
186181
187182 private updateTarget(self: SelfView) {
183+ const s = self.stats;
188184 this.targetBox.innerHTML = "";
189185 if (self.mode === "attack" && self.target) {
190- this.targetBox.append(el("div", "name", `ENGAGING ${self.target}`));
191- this.targetBox.append(el("div", "sub", "auto-fire triangles"));
186+ this.targetBox.append(el("div", "name", `ENGAGING ${this.resolveName(self.target)}`));
192187 } else if (self.mode === "orbit" && self.target) {
193- this.targetBox.append(el("div", "name", `APPROACHING`));
194- this.targetBox.append(el("div", "sub", self.target));
195- } else if (self.queue.length) {
188+ this.targetBox.append(el("div", "name", `APPROACHING ${this.resolveName(self.target)}`));
189+ } else if (self.queue?.length) {
196190 this.targetBox.append(el("div", "name", `ROUTE ${self.queue.length}`));
197191 }
198192 if (self.antennas.length) {
199193 this.targetBox.append(el("div", "sub", `COMMS ${self.antennas.length} linked`));
200194 }
195+ this.targetBox.append(
196+ el("div", "sub", `ATK ${fmt(s.atk)} DEF ${fmt(s.def)} SPD ${self.speed}`),
197+ );
198+ this.targetPanel.hidden = false;
201199 }
202200
203201 // --- radio ----------------------------------------------------------------
@@ -226,6 +224,7 @@ export class HUD {
226224 setHint(text: string, x: number, y: number) {
227225 if (!text) {
228226 this.hint.style.display = "none";
227+ this.hint.textContent = "";
229228 return;
230229 }
231230 this.hint.style.display = "";
@@ -380,11 +379,11 @@ export class HUD {
380379 "SHIFT+LMB queue a move",
381380 "RMB context menu on anything",
382381 "WHEEL zoom: ship scale to galaxy scale",
383- "DRAG pan the view",
382+ "DRAG pan the view C centre on ship",
384383 "ENTER radio input ? help",
385384 "orbit a POI to name it; shipyards refuel and craft",
386385 "right-click your pieces to detach, upgrade, repair",
387- "right-click a loose piece to attach it, then click to place",
386+ "attach: right-click a loose piece, then click a glowing spot on your ship",
388387 ];
389388 for (const l of lines) m.append(el("div", "kv", l));
390389 const row = el("div", "choices");
@@ -1,7 +1,7 @@
11 import "./style.css";
22 import { Camera } from "./camera";
33 import { loadConfig, type GameConfig } from "./config";
4-import { Engine } from "./engine";
4+import { Engine, type AttachPreview } from "./engine";
55 import { HUD, type CtxItem, type Location } from "./hud";
66 import { Socket, wsURL } from "./net";
77 import type {
@@ -76,6 +76,7 @@ class Game {
7676 this.camera = new Camera(this.cfg.galaxy.radius);
7777 this.hud.onRadioSend = (t) => this.send({ t: "radio", text: t });
7878 this.hud.onEject = (slot) => this.send({ t: "eject", slot });
79+ this.hud.resolveName = (id) => this.nameOf(id);
7980 this.bindInput();
8081 window.addEventListener("resize", () => this.engine.resize());
8182
@@ -102,6 +103,7 @@ class Game {
102103 this.selfId = "";
103104 this.follow = true;
104105 this.spawned = false;
106+ this.hud.clear();
105107 this.onboarding = this.hud.onboarding((callsign, shape) => {
106108 this.send({ t: "join", callsign, shape });
107109 });
@@ -222,6 +224,16 @@ class Game {
222224 return { id: poi.id, kind: poi.kind, name: poi.name || `unnamed ${KIND_LABEL[poi.kind]}` };
223225 }
224226
227+ private nameOf(id: string): string {
228+ const poi = this.pois.get(id);
229+ if (poi && poi.kind !== "fleet") return poi.name || `unnamed ${KIND_LABEL[poi.kind]}`;
230+ const p = this.players.get(id);
231+ if (p) return p.cs;
232+ const n = this.npcs.get(id);
233+ if (n) return n.name;
234+ return id;
235+ }
236+
225237 // ---- render loop ---------------------------------------------------------
226238
227239 private frame() {
@@ -243,7 +255,7 @@ class Game {
243255 this.camera.update(dt);
244256 this.engine.setView(this.camera.cx, this.camera.cy, this.camera.viewHeight);
245257 this.engine.updateShips([...this.players.values()], [...this.npcs.values()], this.selfId);
246- this.engine.updateDynamic(this.projs, this.items, this.self ? this.self.queue : []);
258+ this.engine.updateDynamic(this.projs, this.items, this.self?.queue ?? []);
247259 this.engine.render(dt);
248260 requestAnimationFrame(() => this.frame());
249261 }
@@ -294,14 +306,18 @@ class Game {
294306 if (e.key === "c") this.follow = true;
295307 if (e.key === "Escape") {
296308 this.hud.closeContext();
297- this.attachItem = null;
309+ this.cancelAttach();
298310 }
299311 });
300312 }
301313
302314 private hover() {
303315 if (this.attachItem) {
304- this.hud.setHint("click to attach near a piece", this.lastPointer.x, this.lastPointer.y);
316+ const world = this.camera.screenToWorld(this.lastPointer.x, this.lastPointer.y);
317+ const s = this.snapAttach(world);
318+ this.engine.setAttachPreview(s ? this.toPreview(s) : null);
319+ const valid = s?.valid ?? false;
320+ this.hud.setHint(valid ? "click to attach" : "no room here", this.lastPointer.x, this.lastPointer.y);
305321 return;
306322 }
307323 const hit = this.pick(this.lastPointer.x, this.lastPointer.y);
@@ -348,27 +364,89 @@ class Game {
348364
349365 private placePiece(world: Vec2) {
350366 if (!this.self || !this.attachItem) return;
351- const local = rotate(
352- { x: world.x - this.self.x, y: world.y - this.self.y },
353- -this.self.a,
354- );
355- let best = -1;
367+ const s = this.snapAttach(world);
368+ if (!s) return;
369+ if (!s.valid) {
370+ this.hud.toast("pieces would overlap");
371+ return;
372+ }
373+ this.send({ t: "attach", target: this.attachItem, piece: s.anchorId, x: s.localX, y: s.localY });
374+ this.cancelAttach();
375+ }
376+
377+ private cancelAttach() {
378+ this.attachItem = null;
379+ this.engine.setAttachPreview(null);
380+ this.hud.setHint("", 0, 0);
381+ }
382+
383+ // snapAttach maps the cursor to a local position on a ring around the
384+ // nearest ship piece, so the loose piece snaps onto a connection point.
385+ private snapAttach(world: Vec2): Snap | null {
386+ if (!this.self) return null;
387+ const item = this.items.find((i) => i.id === this.attachItem);
388+ const shape = item?.item.shape;
389+ if (!shape) return null;
390+ const a = this.self.a;
391+ const local = rotate({ x: world.x - this.self.x, y: world.y - this.self.y }, -a);
392+ const pieces = Object.values(this.self.ship.pieces);
393+ if (!pieces.length) return null;
394+ let anchor = pieces[0];
356395 let bestD = Infinity;
357- for (const p of Object.values(this.self.ship.pieces)) {
358- const d = Math.hypot(p.x - local.x, p.y - local.y);
396+ for (const q of pieces) {
397+ const d = Math.hypot(q.x - local.x, q.y - local.y);
359398 if (d < bestD) {
360399 bestD = d;
361- best = p.id;
400+ anchor = q;
362401 }
363402 }
364- if (best < 0) return;
365- if (bestD > this.cfg.ship.attachMax) {
366- this.hud.toast("place the piece adjacent to your ship");
367- return;
403+ let dx = local.x - anchor.x;
404+ let dy = local.y - anchor.y;
405+ const len = Math.hypot(dx, dy);
406+ if (len < 1e-3) {
407+ dx = 1;
408+ dy = 0;
409+ } else {
410+ dx /= len;
411+ dy /= len;
368412 }
369- this.send({ t: "attach", target: this.attachItem, piece: best, x: local.x, y: local.y });
370- this.attachItem = null;
371- this.hud.setHint("", 0, 0);
413+ const sep = this.cfg.ship.minSeparation + 4;
414+ const lx = anchor.x + dx * sep;
415+ const ly = anchor.y + dy * sep;
416+ let valid = true;
417+ for (const q of pieces) {
418+ if (q.id === anchor.id) continue;
419+ if (Math.hypot(q.x - lx, q.y - ly) < this.cfg.ship.minSeparation) {
420+ valid = false;
421+ break;
422+ }
423+ }
424+ const toWorld = (x: number, y: number): Vec2 => ({
425+ x: this.self!.x + Math.cos(a) * x - Math.sin(a) * y,
426+ y: this.self!.y + Math.sin(a) * x + Math.cos(a) * y,
427+ });
428+ return {
429+ shape,
430+ anchorId: anchor.id,
431+ anchorShape: anchor.shape,
432+ localX: lx,
433+ localY: ly,
434+ valid,
435+ world: toWorld(lx, ly),
436+ anchorWorld: toWorld(anchor.x, anchor.y),
437+ a,
438+ };
439+ }
440+
441+ private toPreview(s: Snap): AttachPreview {
442+ return {
443+ shape: s.shape,
444+ x: s.world.x,
445+ y: s.world.y,
446+ a: s.a,
447+ valid: s.valid,
448+ anchor: { shape: s.anchorShape, x: s.anchorWorld.x, y: s.anchorWorld.y, a: s.a },
449+ };
372450 }
373451
374452 // ---- picking -------------------------------------------------------------
@@ -500,7 +578,7 @@ class Game {
500578 action: () => {
501579 this.attachItem = id;
502580 this.follow = true;
503- this.hud.toast("click near a piece to attach");
581+ this.hud.toast("move to a glowing spot and click");
504582 },
505583 });
506584 }
@@ -611,6 +689,18 @@ interface Pick {
611689 moveTo?: Vec2;
612690 }
613691
692+interface Snap {
693+ shape: Shape;
694+ anchorId: number;
695+ anchorShape: Shape;
696+ localX: number;
697+ localY: number;
698+ valid: boolean;
699+ world: Vec2;
700+ anchorWorld: Vec2;
701+ a: number;
702+}
703+
614704 function rotate(v: Vec2, a: number): Vec2 {
615705 const c = Math.cos(a);
616706 const s = Math.sin(a);
@@ -161,7 +161,7 @@ body {
161161 }
162162
163163 #hud .pieces {
164- margin-top: 6px;
164+ margin-top: 8px;
165165 display: grid;
166166 grid-template-columns: repeat(auto-fill, 22px);
167167 gap: 3px;
@@ -179,6 +179,14 @@ body {
179179 color: var(--gold);
180180 }
181181
182+#hud .pc .q {
183+ position: absolute;
184+ right: 1px;
185+ bottom: 0;
186+ font-size: 8px;
187+ color: var(--p2);
188+}
189+
182190 #hud .pc .hpbar {
183191 position: absolute;
184192 left: 0;
@@ -187,12 +195,25 @@ body {
187195 background: var(--gold);
188196 }
189197
198+#hud .pc.low {
199+ animation: pulse 0.8s steps(2) infinite;
200+}
201+
202+#hud .pc.low .hpbar {
203+ background: var(--hot);
204+}
205+
190206 #hud .target {
191207 position: absolute;
192208 top: 12px;
193209 right: 12px;
194210 min-width: 180px;
195211 text-align: right;
212+ pointer-events: none;
213+}
214+
215+#hud .target[hidden] {
216+ display: none;
196217 }
197218
198219 #hud .target .name {
@@ -219,6 +240,10 @@ body {
219240 justify-content: flex-end;
220241 }
221242
243+#hud .radio .log:empty {
244+ display: none;
245+}
246+
222247 #hud .radio .line {
223248 color: var(--p2);
224249 }
@@ -409,12 +434,3 @@ body {
409434 right: 12px;
410435 color: var(--hot);
411436 }
412-
413-#hud .keyhint {
414- position: absolute;
415- bottom: 12px;
416- left: 50%;
417- transform: translateX(-50%);
418- color: var(--dim);
419- font-size: 11px;
420-}
@@ -109,6 +109,7 @@ type Config struct {
109109 NPC struct {
110110 EngageRange float64 `json:"engageRange"`
111111 HailRange float64 `json:"hailRange"`
112+ SafeRadius float64 `json:"safeRadius"`
112113 MinFleetSize int `json:"minFleetSize"`
113114 MaxFleetSize int `json:"maxFleetSize"`
114115 } `json:"npc"`
@@ -99,6 +99,7 @@
9999 "npc": {
100100 "engageRange": 1500,
101101 "hailRange": 5000,
102+ "safeRadius": 9000,
102103 "minFleetSize": 1,
103104 "maxFleetSize": 12
104105 }
@@ -341,16 +341,20 @@ func (g *Galaxy) populate(r *rng, star *POI, home bool) {
341341 }
342342 hosts := append(append([]*POI{}, planets...), star)
343343
344+ // fleets never spawn in the home system, and only as friendly within the
345+ // spawn safe zone: new players are not thrown straight into combat.
346+ safe := home || (g.Home != nil && math.Hypot(star.X-g.Home.X, star.Y-g.Home.Y) <= config.NPC.SafeRadius)
347+
344348 // the home system always gets a shipyard and some ore to start on
345349 if home {
346- if p := g.satellite(r, star, kindShipyard, hosts, sysR, placed); p != nil {
350+ if p := g.satellite(r, star, kindShipyard, hosts, sysR, placed, safe); p != nil {
347351 commit(p)
348352 }
349353 }
350354 for _, kind := range poiKinds {
351355 chance := poiChance(kind) * (config.Galaxy.POI.EdgeFade + (1-config.Galaxy.POI.EdgeFade)*density)
352356 if home {
353- if kind == kindShipyard {
357+ if kind == kindShipyard || kind == kindFleet {
354358 continue
355359 }
356360 if kind == kindAsteroid {
@@ -360,7 +364,7 @@ func (g *Galaxy) populate(r *rng, star *POI, home bool) {
360364 if !r.Chance(chance) {
361365 continue
362366 }
363- if p := g.satellite(r, star, kind, hosts, sysR, placed); p != nil {
367+ if p := g.satellite(r, star, kind, hosts, sysR, placed, safe); p != nil {
364368 commit(p)
365369 }
366370 }
@@ -424,7 +428,7 @@ func (g *Galaxy) planet(r *rng, star *POI, sysR float64, placed []*POI) *POI {
424428 }
425429
426430 // satellite places a POI in orbit of one of the system's hosts.
427-func (g *Galaxy) satellite(r *rng, star *POI, kind string, hosts []*POI, sysR float64, placed []*POI) *POI {
431+func (g *Galaxy) satellite(r *rng, star *POI, kind string, hosts []*POI, sysR float64, placed []*POI, safe bool) *POI {
428432 gc := config.Galaxy
429433 start := r.Intn(len(hosts))
430434 for i := 0; i < len(hosts); i++ {
@@ -453,7 +457,7 @@ func (g *Galaxy) satellite(r *rng, star *POI, kind string, hosts []*POI, sysR fl
453457 case kindWreck:
454458 p.Wreck = randomWreckPieces(r, config.Cargo.WreckPieces)
455459 case kindFleet:
456- p.Hostile = r.Chance(0.45 + 0.35*densityAt(star.X, star.Y))
460+ p.Hostile = r.Chance(0.45+0.35*densityAt(star.X, star.Y)) && !safe
457461 p.FleetCap = config.NPC.MinFleetSize + r.Intn(config.NPC.MaxFleetSize-config.NPC.MinFleetSize+1)
458462 }
459463 p.orbitAround(h)
@@ -88,18 +88,35 @@ func (w *World) stepNPC(n *NPC, dt float64) {
8888 n.POI.X, n.POI.Y = n.Pos.X, n.Pos.Y
8989 }
9090
91+// inSafeZone reports whether pos lies inside the spawn safe zone, where
92+// hostile fleets must not engage new players.
93+func (w *World) inSafeZone(pos Vec2) bool {
94+ h := w.galaxy.Home
95+ return h != nil && pos.Dist(Vec2{h.X, h.Y}) <= config.NPC.SafeRadius
96+}
97+
9198 // npcAcquire picks the nearest player within engage range as a target.
9299 func (w *World) npcAcquire(n *NPC) {
93100 if n.Target != "" {
94- if _, ok := w.players[n.Target]; ok {
95- if tpos, _, ok := w.entityPos(n.Target); ok && n.Pos.Dist(tpos) <= config.NPC.EngageRange*2 {
101+ if p, ok := w.players[n.Target]; ok {
102+ if tpos, _, ok := w.entityPos(n.Target); ok && n.Pos.Dist(tpos) <= config.NPC.EngageRange*2 && !w.inSafeZone(p.Pos) {
96103 return
97104 }
98105 }
99106 n.Target = ""
100107 }
101- if p := w.nearestPlayer(n.Pos, config.NPC.EngageRange); p != nil {
102- n.Target = p.ID
108+ var best *Player
109+ bestD := config.NPC.EngageRange
110+ for _, p := range w.players {
111+ if w.inSafeZone(p.Pos) {
112+ continue
113+ }
114+ if d := n.Pos.Dist(p.Pos); d < bestD {
115+ bestD, best = d, p
116+ }
117+ }
118+ if best != nil {
119+ n.Target = best.ID
103120 }
104121 }
105122
@@ -71,7 +71,7 @@ func (s *Store) seed() (uint64, error) {
7171
7272 // layoutVersion identifies the galaxy layout. Exploration rows written for an
7373 // older layout would name the wrong places, so they are dropped on a change.
74-const layoutVersion = "2"
74+const layoutVersion = "3"
7575
7676 func (s *Store) checkLayout() error {
7777 if v, ok := s.meta("layout"); ok && v == layoutVersion {
@@ -99,12 +99,16 @@ func (w *World) selfMessage(p *Player) map[string]any {
9999 for id := range p.Antennas {
100100 antennas = append(antennas, id)
101101 }
102+ queue := p.Queue
103+ if queue == nil {
104+ queue = []Vec2{} // never marshal as null; the client iterates it
105+ }
102106 return map[string]any{
103107 "t": "you", "id": p.ID, "callsign": p.Callsign,
104108 "x": p.Pos.X, "y": p.Pos.Y, "a": p.Angle,
105109 "fuel": p.Fuel, "fuelCap": p.fuelCap(),
106110 "cargo": p.Cargo, "cap": p.cargoCap(),
107- "orbit": p.Orbit, "target": p.Target, "mode": p.Mode, "queue": p.Queue,
111+ "orbit": p.Orbit, "target": p.Target, "mode": p.Mode, "queue": queue,
108112 "antennas": antennas,
109113 "combat": p.inCombat(w.t),
110114 "hp": p.Ship.hp(), "maxHp": p.Ship.maxHP(),