diff --git a/analyze_zfight.mjs b/analyze_zfight.mjs new file mode 100644 index 0000000..e903d9b --- /dev/null +++ b/analyze_zfight.mjs @@ -0,0 +1,127 @@ +// minimal DOM stubs for headless run +globalThis.document = { + createElement: () => ({ + width: 0, height: 0, + getContext: () => ({ + createRadialGradient: () => ({ addColorStop: () => {} }), + fillRect: () => {}, + }), + }), +}; +globalThis.window = globalThis; +globalThis.self = globalThis; +globalThis.ProgressEvent = class ProgressEvent { constructor(type, init){ this.type=type; Object.assign(this, init);} }; +const RealRequest = globalThis.Request; +globalThis.Request = class extends RealRequest { + constructor(url, ...a) { + if (typeof url === "string" && url.startsWith("/")) url = "http://localhost" + url; + super(url, ...a); + } +}; +import fs from "node:fs"; +import path from "node:path"; +globalThis.fetch = async (url) => { + let u = typeof url === "string" ? url : url.url; + let p = u.split("?")[0]; + try { p = decodeURIComponent(new URL(p).pathname); } catch {} + if (p.startsWith("/models/")) p = "models/" + p.slice(8); + else if (p.startsWith("/vendor/")) p = "public/vendor/" + p.slice(8); + else if (p.startsWith("/data/")) p = "data/" + p.slice(6); + else return new Response("not found", { status: 404 }); + try { + const buf = fs.readFileSync(path.resolve(p)); + return new Response(buf, { status: 200 }); + } catch { return new Response("nf", { status: 404 }); } +}; + +import * as THREE from "three"; +import { buildRocket } from "./dist/shared/physics/buildRocket.js"; +import { createStarterDesign } from "./dist/shared/physics/starters.js"; +import { buildRocketMesh } from "./dist/client/three/rocketMesh/assembly.js"; + +const parts = JSON.parse(fs.readFileSync("data/parts.json", "utf8")); +const materials = JSON.parse(fs.readFileSync("data/materials.json", "utf8")); + +const payloadId = process.env.PAYLOAD || "payload-cubesat-1u"; +const design = createStarterDesign(null, "sandbox"); +design.payloadPartId = payloadId; +design.stages.push({ + engineId: "eng-merlin-vac", engineCount: 1, nozzleRatio: 1.4, gimbalDeg: 3, + tankId: "tank-med-kero", diameter: 3.7, length: 14, fillRatio: 0.9, + structureId: "struct-frame-std", materialId: "al-7075", + wallThicknessFactor: 1.0, hasFins: false, hasHeatshield: false, +}); +design.stages[0].interstageId = "interstage-std"; + +const asm = buildRocket(design, parts, materials, {}); +console.log("height", asm.height.toFixed(2), "stages", asm.stages.length, "payload", payloadId); +const handle = await buildRocketMesh(asm, { realModels: true, fairingCutaway: false }); +handle.group.updateMatrixWorld(true); + +const faces = []; +let meshId = 0; +const meshNames = new Map(); +handle.group.traverse((obj) => { + if (!obj.isMesh) return; + const id = meshId++; + const chain = []; + let n = obj; + while (n && chain.length < 5) { chain.push(n.name || n.type); n = n.parent; } + meshNames.set(id, chain.reverse().join("<")); + const geo = obj.geometry; + const pos = geo.attributes.position; + if (!pos) return; + const index = geo.index; + const triCount = index ? index.count / 3 : pos.count / 3; + const p = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()]; + for (let t = 0; t < triCount; t++) { + const i0 = index ? index.getX(t * 3) : t * 3; + const i1 = index ? index.getX(t * 3 + 1) : t * 3 + 1; + const i2 = index ? index.getX(t * 3 + 2) : t * 3 + 2; + p[0].fromBufferAttribute(pos, i0).applyMatrix4(obj.matrixWorld); + p[1].fromBufferAttribute(pos, i1).applyMatrix4(obj.matrixWorld); + p[2].fromBufferAttribute(pos, i2).applyMatrix4(obj.matrixWorld); + const e1 = p[1].clone().sub(p[0]); + const e2 = p[2].clone().sub(p[0]); + const nrm = e1.cross(e2); + const area = nrm.length(); + if (area < 1e-8) continue; + nrm.normalize(); + if (Math.abs(nrm.y) < 0.999) continue; + const y = (p[0].y + p[1].y + p[2].y) / 3; + const cx = (p[0].x + p[1].x + p[2].x) / 3; + const cz = (p[0].z + p[1].z + p[2].z) / 3; + const rr = Math.max( + Math.hypot(p[0].x - cx, p[0].z - cz), + Math.hypot(p[1].x - cx, p[1].z - cz), + Math.hypot(p[2].x - cx, p[2].z - cz), + ); + faces.push({ y, cx, cz, r: rr, ny: Math.sign(nrm.y), id, area }); + } +}); +console.log("meshes:", meshId, "horizontal faces:", faces.length); +faces.sort((a, b) => a.y - b.y); +const EPS = 0.03; +const groups = []; +for (const f of faces) { + const g = groups[groups.length - 1]; + if (g && Math.abs(f.y - g.y) < EPS) g.items.push(f); + else groups.push({ y: f.y, items: [f] }); +} +const seen = new Set(); +for (const g of groups) { + const items = g.items; + for (let i = 0; i < items.length; i++) { + for (let j = i + 1; j < items.length; j++) { + const a = items[i], b = items[j]; + if (a.id === b.id) continue; + const d = Math.hypot(a.cx - b.cx, a.cz - b.cz); + if (d < a.r + b.r - 0.05) { + const key = `${g.y.toFixed(2)}|${Math.min(a.id,b.id)}|${Math.max(a.id,b.id)}`; + if (seen.has(key)) continue; + seen.add(key); + console.log(`ZF y=${g.y.toFixed(3)}\n A m${a.id} ${meshNames.get(a.id)} ny=${a.ny} r=${a.r.toFixed(2)} @(${a.cx.toFixed(1)},${a.cz.toFixed(1)})\n B m${b.id} ${meshNames.get(b.id)} ny=${b.ny} r=${b.r.toFixed(2)} @(${b.cx.toFixed(1)},${b.cz.toFixed(1)})`); + } + } + } +} diff --git a/src/client/screens/contracts/customModal.ts b/src/client/screens/contracts/customModal.ts index a886217..65003f3 100644 --- a/src/client/screens/contracts/customModal.ts +++ b/src/client/screens/contracts/customModal.ts @@ -19,11 +19,15 @@ export interface LeaderboardRow { difficultyLabel?: string; aiSkill?: number | null; bankrupt: boolean; + bankruptcyReason?: string | null; sponsorId: string | null; treasury: number; reputation: number; missionsCompleted: number; missionsFailed: number; + careerMissionsCompleted?: number; + careerMissionsFailed?: number; + contractsAbandoned?: number; earnedTotal: number; score: number; } diff --git a/src/client/screens/contracts/marketPanel.ts b/src/client/screens/contracts/marketPanel.ts index 90a2d37..5491253 100644 --- a/src/client/screens/contracts/marketPanel.ts +++ b/src/client/screens/contracts/marketPanel.ts @@ -127,7 +127,7 @@ export function renderMarketPanel( h( "span", {}, - `${row.missionsCompleted} OK / ${row.missionsFailed} FAIL`, + `${row.missionsCompleted} OK / ${row.missionsFailed} FAIL${row.contractsAbandoned ? ` / ${row.contractsAbandoned} VOID` : ""}`, ), ), live diff --git a/src/client/session.ts b/src/client/session.ts index d12f76e..b3ed9aa 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -133,7 +133,10 @@ function handleLiveEvent(ev: { void refreshWorld(); if (isMine) void refreshMe(); } else if (ev.type === "agency.bankrupt") { - const msg = `INSOLVENCY ALERT: ${d.agency} declared bankruptcy.`; + const reason = d.reason + ? ` (${String(d.reason).replace(/_/g, " ")})` + : ""; + const msg = `INSOLVENCY ALERT: ${d.agency} declared bankruptcy${reason}.`; pushNotification( msg, isMine ? "err" : "warn", @@ -179,6 +182,17 @@ function handleLiveEvent(ev: { "world", ); void refreshWorld(); + } else if (ev.type === "contract.abandoned") { + const reason = String(d.reason ?? "unknown").replace(/_/g, " "); + const penalty = ((Number(d.penalty) || 0) / 1e6).toFixed(1); + const msg = `${d.agency} abandoned contract ${d.missionId ?? d.offerId ?? "contract"} (${reason}) — $${penalty}M penalty.`; + if (isMine) { + toast(msg, "warn", false); + void refreshMe(); + } else { + pushNotification(msg, "warn", "world", false); + } + void refreshWorld(); } else if (ev.type === "agency.updated" && isMine) { if (state.agency && d.rocketDesign) { state.agency.rocketDesign = d.rocketDesign; diff --git a/src/client/three/rocketMesh/assembly.ts b/src/client/three/rocketMesh/assembly.ts index e16387e..547f55b 100644 --- a/src/client/three/rocketMesh/assembly.ts +++ b/src/client/three/rocketMesh/assembly.ts @@ -9,6 +9,7 @@ import { buildEngineClusterStandard, buildPayloadNode, buildStageConnector, + cappedColumnGroup, fitPayloadInsideFairing, } from "./geometry.js"; import { @@ -190,7 +191,7 @@ export async function buildRocketMesh( const cR = Math.max(0.6, topDia * 0.48); const compGroup = new THREE.Group(); const housing = new THREE.Mesh( - new THREE.CylinderGeometry(cR * 1.03, cR * 1.03, 0.36, 28), + new THREE.CylinderGeometry(cR * 1.03, cR * 1.03, 0.36, 28, 1, true), new THREE.MeshStandardMaterial({ color: 0x1e293b, metalness: 0.75, @@ -248,15 +249,18 @@ export async function buildRocketMesh( } payloadGroup = builtPayload; } else if (!isPro || topProPayload) { - const generic = new THREE.Mesh( - new THREE.CylinderGeometry(1.0, 1.2, 3.0, 16), + const generic = cappedColumnGroup( + 1.0, + 1.2, + 3.0, new THREE.MeshStandardMaterial({ color: 0x60a5fa, metalness: 0.6, roughness: 0.35, }), + { radialSegs: 16 }, ); - generic.position.y = assembly.payloadY + 1.5; + generic.position.y = assembly.payloadY; const genericGroup = new THREE.Group(); genericGroup.add(generic); if (topProPayload) { @@ -318,17 +322,20 @@ export async function buildRocketMesh( let lasGroup: THREE.Group | null = null; if (assembly.lasPart) { lasGroup = new THREE.Group(); - const tower = new THREE.Mesh( - new THREE.CylinderGeometry(0.28, 0.75, assembly.lasPart.length, 16), + const tower = cappedColumnGroup( + 0.28, + 0.75, + assembly.lasPart.length, new THREE.MeshStandardMaterial({ color: 0xe2e8f0, metalness: 0.4, roughness: 0.5, }), + { radialSegs: 16 }, ); - tower.position.y = assembly.lasY + assembly.lasPart.length / 2; + tower.position.y = assembly.lasY; const tip = new THREE.Mesh( - new THREE.ConeGeometry(0.28, 1.4, 16), + new THREE.ConeGeometry(0.28, 1.4, 16, 1, true), new THREE.MeshStandardMaterial({ color: 0xf87171, metalness: 0.3, diff --git a/src/client/three/rocketMesh/geometry.ts b/src/client/three/rocketMesh/geometry.ts index 666aba3..fd323e1 100644 --- a/src/client/three/rocketMesh/geometry.ts +++ b/src/client/three/rocketMesh/geometry.ts @@ -165,6 +165,40 @@ export function buildOgiveFairingGeo( const CONNECTOR_RADIUS_FRAC = 0.94; +// Stacked parts butt end-to-end, so any two capped faces on the same plane +// z-fight. Body columns are therefore built as an open wall plus cap discs +// recessed CAP_INSET from each end; trim rings keep exact bounds and stay +// clear of the recessed caps. +const CAP_INSET = 0.035; + +export function cappedColumnGroup( + rt: number, + rb: number, + h: number, + mat: THREE.Material, + opts: { radialSegs?: number; heightSegs?: number; caps?: boolean } = {}, +): THREE.Group { + const g = new THREE.Group(); + const segs = opts.radialSegs ?? 32; + const wall = new THREE.Mesh( + new THREE.CylinderGeometry(rt, rb, h, segs, opts.heightSegs ?? 1, true), + mat, + ); + wall.position.y = h / 2; + g.add(wall); + if (opts.caps !== false) { + const inset = Math.min(CAP_INSET, h * 0.2); + const top = new THREE.Mesh(new THREE.CircleGeometry(rt, segs), mat); + top.rotation.x = -Math.PI / 2; + top.position.y = h - inset; + const bot = new THREE.Mesh(new THREE.CircleGeometry(rb, segs), mat); + bot.rotation.x = Math.PI / 2; + bot.position.y = inset; + g.add(top, bot); + } + return g; +} + export function buildStageConnector( botR: number, topR: number, @@ -174,13 +208,13 @@ export function buildStageConnector( const g = new THREE.Group(); const bR = Math.max(0.15, botR * CONNECTOR_RADIUS_FRAC); const tR = Math.max(0.15, topR * CONNECTOR_RADIUS_FRAC); - const body = new THREE.Mesh( - new THREE.CylinderGeometry(tR, bR, len, 48, 1, false), - mat, - ); - body.position.y = len / 2; - body.castShadow = true; - body.receiveShadow = true; + const body = cappedColumnGroup(tR, bR, len, mat, { radialSegs: 48 }); + body.traverse((o) => { + if ((o as THREE.Mesh).isMesh) { + o.castShadow = true; + o.receiveShadow = true; + } + }); g.add(body); const flangeH = Math.min(0.22, len * 0.12); const lerpR = (y: number) => bR + (tR - bR) * (y / len); @@ -227,16 +261,15 @@ export function buildEngineClusterStandard( ringR *= k; singleR *= k; } - const dome = new THREE.Mesh( - new THREE.CylinderGeometry( - stageR * 0.88, - stageR * 0.78, - comp.length * 0.28, - 28, - ), + const domeH = comp.length * 0.28; + const dome = cappedColumnGroup( + stageR * 0.88, + stageR * 0.78, + domeH, AVIONICS_RING_MAT, + { radialSegs: 28 }, ); - dome.position.y = comp.yBottom + comp.length * 0.86; + dome.position.y = comp.yBottom + comp.length * 0.86 - domeH / 2; cluster.add(dome); const offsets: Array<[number, number]> = []; if (count === 1) { @@ -366,20 +399,18 @@ export async function buildPayloadNode( } } const g = new THREE.Group(); - const body = new THREE.Mesh( - new THREE.CylinderGeometry( - part.diameter * 0.42, - part.diameter * 0.45, - part.length * 0.85, - 20, - ), + const body = cappedColumnGroup( + part.diameter * 0.42, + part.diameter * 0.45, + part.length * 0.85, new THREE.MeshStandardMaterial({ color: 0x94a3b8, metalness: 0.7, roughness: 0.3, }), + { radialSegs: 20 }, ); - body.position.y = yPos + part.length * 0.425; + body.position.y = yPos; g.add(body); return g; } diff --git a/src/client/three/rocketMesh/partBuilder.ts b/src/client/three/rocketMesh/partBuilder.ts index 742b1b1..6122dc0 100644 --- a/src/client/three/rocketMesh/partBuilder.ts +++ b/src/client/three/rocketMesh/partBuilder.ts @@ -5,6 +5,7 @@ import { buildOgiveFairingGeo, buildParabolicBellGeo, buildStageConnector, + cappedColumnGroup, } from "./geometry.js"; import { ACCENT_STRIPE_MAT, @@ -25,11 +26,14 @@ export function buildSinglePartCopy( const g = new THREE.Group(); const r = comp.diameter / 2; if (comp.role === "engine") { - const skirt = new THREE.Mesh( - new THREE.CylinderGeometry(r * 0.55, r * 0.38, comp.length * 0.22, 18), + const skirt = cappedColumnGroup( + r * 0.55, + r * 0.38, + comp.length * 0.22, AVIONICS_RING_MAT, + { radialSegs: 18 }, ); - skirt.position.y = comp.length * 0.89; + skirt.position.y = comp.length * 0.78; g.add(skirt); const bellH = comp.length * 0.8; const bell = new THREE.Mesh( @@ -53,28 +57,37 @@ export function buildSinglePartCopy( const aftH = Math.max(0.28, comp.length * 0.06); const noseH = Math.max(0.55, comp.length * 0.22); const cylLen = Math.max(0.6, comp.length - aftH - noseH); - const aftCap = new THREE.Mesh( - new THREE.CylinderGeometry(r, r * 0.62, aftH, 32), - barrelMat, - ); - aftCap.position.y = aftH / 2; - aftCap.castShadow = true; - aftCap.receiveShadow = true; + const aftCap = cappedColumnGroup(r, r * 0.62, aftH, barrelMat, { + radialSegs: 32, + }); + aftCap.traverse((o) => { + if ((o as THREE.Mesh).isMesh) { + o.castShadow = true; + o.receiveShadow = true; + } + }); g.add(aftCap); - const tankMesh = new THREE.Mesh( - new THREE.CylinderGeometry(r, r, cylLen, 36), - barrelMat, - ); - tankMesh.position.y = aftH + cylLen / 2; - tankMesh.castShadow = true; - tankMesh.receiveShadow = true; + const tankMesh = cappedColumnGroup(r, r, cylLen, barrelMat, { + radialSegs: 36, + }); + tankMesh.position.y = aftH; + tankMesh.traverse((o) => { + if ((o as THREE.Mesh).isMesh) { + o.castShadow = true; + o.receiveShadow = true; + } + }); g.add(tankMesh); - const nose = new THREE.Mesh( - new THREE.CylinderGeometry(r * 0.14, r, noseH, 36), - barrelMat, - ); - nose.position.y = aftH + cylLen + noseH / 2; - nose.castShadow = true; + const nose = cappedColumnGroup(r * 0.14, r, noseH, barrelMat, { + radialSegs: 36, + }); + nose.position.y = aftH + cylLen; + nose.traverse((o) => { + if ((o as THREE.Mesh).isMesh) { + o.castShadow = true; + o.receiveShadow = true; + } + }); g.add(nose); const noseTip = new THREE.Mesh( new THREE.SphereGeometry(r * 0.14, 16, 10), @@ -91,13 +104,15 @@ export function buildSinglePartCopy( g.add(band); } } else { - const tankMesh = new THREE.Mesh( - new THREE.CylinderGeometry(r, r, comp.length, 48), - tankMat, - ); - tankMesh.position.y = comp.length / 2; - tankMesh.castShadow = true; - tankMesh.receiveShadow = true; + const tankMesh = cappedColumnGroup(r, r, comp.length, tankMat, { + radialSegs: 48, + }); + tankMesh.traverse((o) => { + if ((o as THREE.Mesh).isMesh) { + o.castShadow = true; + o.receiveShadow = true; + } + }); g.add(tankMesh); for (const frac of [0.15, 0.5, 0.85]) { const ring = new THREE.Mesh( @@ -120,24 +135,28 @@ export function buildSinglePartCopy( g.add(raceway); } } else if (comp.role === "heatshield") { - const shield = new THREE.Mesh( - new THREE.CylinderGeometry(r * 1.03, r * 1.03, comp.length, 32), + const shield = cappedColumnGroup( + r * 1.03, + r * 1.03, + comp.length, new THREE.MeshStandardMaterial({ color: 0x451a03, metalness: 0.3, roughness: 0.85, }), + { radialSegs: 32 }, ); - shield.position.y = comp.length / 2; g.add(shield); } else if (comp.role === "structure") { - const avionics = new THREE.Mesh( - new THREE.CylinderGeometry(r, r, comp.length, 48), - tankMat, - ); - avionics.position.y = comp.length / 2; - avionics.castShadow = true; - avionics.receiveShadow = true; + const avionics = cappedColumnGroup(r, r, comp.length, tankMat, { + radialSegs: 48, + }); + avionics.traverse((o) => { + if ((o as THREE.Mesh).isMesh) { + o.castShadow = true; + o.receiveShadow = true; + } + }); g.add(avionics); const botTrim = new THREE.Mesh( new THREE.CylinderGeometry( @@ -172,20 +191,19 @@ export function buildSinglePartCopy( const topR = nextStageDia > 0.2 ? nextStageDia / 2 : r; g.add(buildStageConnector(botR, topR, Math.max(0.6, comp.length), tankMat)); } else if (comp.role === "computer") { - const collar = new THREE.Mesh( - new THREE.CylinderGeometry( - r * 1.02, - r * 1.02, - Math.max(0.45, comp.length), - 24, - ), + const collarH = Math.max(0.45, comp.length); + const collar = cappedColumnGroup( + r * 1.02, + r * 1.02, + collarH, new THREE.MeshStandardMaterial({ color: 0x0f172a, metalness: 0.72, roughness: 0.28, }), + { radialSegs: 24 }, ); - collar.position.y = Math.max(0.45, comp.length) / 2; + g.add(collar); const ledColor = (comp.part.radHardeningLevel ?? 1) >= 3 ? 0x34d399 @@ -198,7 +216,7 @@ export function buildSinglePartCopy( ); busRing.rotation.x = Math.PI / 2; busRing.position.y = Math.max(0.45, comp.length) * 0.55; - g.add(collar, busRing); + g.add(busRing); } else if (comp.role === "fairing") { const shroud = new THREE.Mesh( buildOgiveFairingGeo(r, comp.length), diff --git a/src/server/ai/agencies.ts b/src/server/ai/agencies.ts index 8a84826..2c6d3bc 100644 --- a/src/server/ai/agencies.ts +++ b/src/server/ai/agencies.ts @@ -157,8 +157,11 @@ export function makeAiAgency(def: AiAgencyDef): AgencyState { profile.startingFunds * (sponsor?.budgetMult ?? 1.0) + skill * 4_000_000, ), reputation: Math.round((1 + skill * 5) * 10) / 10, - missionsCompleted: Math.floor(skill * 2), - missionsFailed: Math.floor((1 - skill) * 2), + missionsCompleted: 0, + missionsFailed: 0, + careerMissionsCompleted: Math.floor(skill * 2), + careerMissionsFailed: Math.floor((1 - skill) * 2), + contractsAbandoned: 0, earnedTotal: 0, rocketDesign: null, crewConfig: { crewSize: 0, lifeSupport: 1 }, @@ -166,6 +169,7 @@ export function makeAiAgency(def: AiAgencyDef): AgencyState { contractHistory: [], bankrupt: false, bankruptAt: null, + bankruptcyReason: null, bailoutsTaken: 0, unlockedTechs: defaultTechsForDifficulty(def.difficulty), partHeritage: {}, @@ -232,6 +236,33 @@ export function seedAI(): void { agency.partHeritage = {}; dirty = true; } + if ( + agency.careerMissionsCompleted == null || + agency.careerMissionsFailed == null + ) { + const careerSkill = def ? def.skill : clamp01(agency.aiSkill ?? 0.65); + const seededCompleted = Math.floor(careerSkill * 2); + const seededFailed = Math.floor((1 - careerSkill) * 2); + agency.careerMissionsCompleted = seededCompleted; + agency.careerMissionsFailed = seededFailed; + agency.missionsCompleted = Math.max( + 0, + (agency.missionsCompleted ?? 0) - seededCompleted, + ); + agency.missionsFailed = Math.max( + 0, + (agency.missionsFailed ?? 0) - seededFailed, + ); + dirty = true; + } + if (agency.contractsAbandoned == null) { + agency.contractsAbandoned = 0; + dirty = true; + } + if (agency.bankruptcyReason === undefined) { + agency.bankruptcyReason = agency.bankrupt ? "legacy_insolvency" : null; + dirty = true; + } if (agency.bailoutsTaken == null) { agency.bailoutsTaken = 0; dirty = true; diff --git a/src/server/ai/runner.ts b/src/server/ai/runner.ts index e3e7001..88b3628 100644 --- a/src/server/ai/runner.ts +++ b/src/server/ai/runner.ts @@ -29,6 +29,9 @@ import type { ActiveMission, AgencyState, ContractOffer, + RocketAssembly, + RocketDesign, + ValidationResult, } from "../../shared/types.js"; import { clamp01, @@ -43,14 +46,122 @@ import { synthesizeAiRocket } from "./synthesizer.js"; let lastStartupAt = 0; +function estimateAiMissionCost( + agency: AgencyState, + offer: ContractOffer, +): number { + const payload = Math.max(0, effectivePayloadMass(agency, offer) || 0); + const dv = Math.max(0, offer.requiredDv || 0); + const base = 16_000_000 + payload * 2_600 + dv * 1_800; + let mult = 1; + if (offer.tier >= 2) mult *= 1.12; + else if (offer.tier === 1) mult *= 1.05; + if (offer.advanced || offer.isConvoluted) mult *= 1.18; + if (offer.requiredDv > 12_500) mult *= 1.22; + if (offer.crewed) mult *= 1.12; + return Math.round(base * mult); +} + +function expectedContractPayout(offer: ContractOffer): number { + return Math.round(offer.budget * 0.68); +} + +function estimateAiMissionEconomics( + agency: AgencyState, + contract: ContractOffer, + design: RocketDesign, + asm: RocketAssembly, + validation: ValidationResult, + totalCost: number, + anomalyRiskPct: number, +): { + successCash: number; + failureCash: number; + expectedCash: number; + launchNet: number; + abandonCost: number; + successProbability: number; +} { + const profile = getDifficultyProfile(agency.difficulty); + const budget = contract.budget; + const reqDv = contract.requiredDv ?? 9_000; + const margin = Math.max(0, validation.dvMargin / Math.max(1, reqDv)); + const bus = validation.assembly?.spacecraftBus; + const gradeBonusRate = + bus?.efficiencyGrade === "S" + ? 0.05 + : bus?.efficiencyGrade === "A" + ? 0.025 + : 0; + const effBonusRate = + Math.min( + 0.1, + margin * 0.4 + + ((validation.compliance.waivedCount ?? 0) === 0 ? 0.04 : 0), + ) + gradeBonusRate; + const grossPayout = Math.round(budget * (0.65 + effBonusRate)); + const scienceBonus = Math.round( + budget * ((bus?.scienceBonusPct ?? 0) / 100), + ); + const canRecover = + (contract.isReusable || + (agency.unlockedTechs ?? []).includes("methalox-reusable")) && + validation.dvMargin >= 450 && + (!!design.stages?.[0]?.hasFins || (design.stages?.length ?? 0) >= 2); + const stage0Cost = + asm.stages?.[0]?.stageCost ?? Math.round(totalCost * 0.55); + const reusabilityBonus = canRecover ? Math.round(stage0Cost * 0.28) : 0; + const successCash = grossPayout + scienceBonus + reusabilityBonus; + + const exempt = profile.id === "explorer" || profile.id === "sandbox"; + const insured = !!agency.launchInsured; + const insurancePayout = insured ? Math.round(totalCost * 0.7) : 0; + const breachPenalty = + exempt || insured ? 0 : Math.round(budget * profile.breachFineRate); + const padRepairExpected = exempt + ? 0 + : Math.round( + (6_000_000 + Math.min(8_000_000, Math.round(totalCost * 0.22))) * + 0.45, + ); + const crewInquiryExpected = + contract.crewed && !exempt ? 10_000_000 : 0; + const failureCash = + insurancePayout - breachPenalty - padRepairExpected - crewInquiryExpected; + + const skill = clamp01(agency.aiSkill ?? 0.65); + const successProbability = Math.max( + 0.55, + Math.min(0.97, 0.88 + skill * 0.08 - anomalyRiskPct / 140), + ); + const expectedCash = Math.round( + successProbability * successCash + + (1 - successProbability) * failureCash, + ); + const abandonCost = + Math.round(budget * 0.35) + Math.round(budget * profile.breachFineRate); + return { + successCash, + failureCash, + expectedCash, + launchNet: expectedCash - totalCost, + abandonCost, + successProbability, + }; +} + function isContractFeasibleForAi( agency: AgencyState, offer: ContractOffer, ): boolean { + const skill = clamp01(agency.aiSkill ?? 0.65); const advance = Math.round(offer.budget * 0.35); - const estCost = offer.budget * 0.62; - if (estCost > (agency.treasury + advance) * 0.72) return false; - if (agency.treasury + advance - estCost < 10_000_000) return false; + const estCost = estimateAiMissionCost(agency, offer); + const expectedPayout = expectedContractPayout(offer); + const requiredMargin = 1.08 - skill * 0.06; + if (expectedPayout < estCost * requiredMargin) return false; + if (estCost > (agency.treasury + advance) * 0.9) return false; + if (agency.treasury + advance - estCost < INSOLVENCY_THRESHOLD) return false; const prof = getDifficultyProfile(agency.difficulty); if (!prof.allTechUnlocked && offer.requiredDv > 9800) { const unlocked = new Set(agency.unlockedTechs ?? []); @@ -88,10 +199,14 @@ function chooseContractForAi(agency: AgencyState): ContractOffer | null { const skill = clamp01(agency.aiSkill ?? 0.65); const cryoUnlocked = isPartUnlocked("eng-rl10", agency); const scored = offers.map((offer) => { + const feasible = isContractFeasibleForAi(agency, offer); const postAdvanceCash = agency.treasury + Math.round(offer.budget * 0.35); - const estCost = offer.budget * 0.62; - let score = offer.budget / 1e6; - if (!isContractFeasibleForAi(agency, offer)) { + const estCost = estimateAiMissionCost(agency, offer); + const estMargin = expectedContractPayout(offer) - estCost; + let score = + offer.budget / 1e6 + + Math.max(-25, Math.min(25, estMargin / 1e6)) * 0.5; + if (!feasible) { score -= 1000; } if (estCost > postAdvanceCash * 1.05 && offer.tier > 0) { @@ -107,10 +222,10 @@ function chooseContractForAi(agency: AgencyState): ContractOffer | null { score -= 40; } score += (Math.random() - 0.5) * (1 - skill) * 140; - return { offer, score }; + return { offer, score, feasible }; }); scored.sort((a, b) => b.score - a.score); - return scored[0]?.offer ?? offers[0]; + return scored.find((s) => s.feasible)?.offer ?? null; } export function aiTick(): void { @@ -124,6 +239,7 @@ export function aiTick(): void { if (!agency.isAI) continue; if (agency.terminatedReason) { agency.bankrupt = true; + agency.bankruptcyReason = agency.terminatedReason; putAgency(agency.name, agency); continue; } @@ -167,6 +283,7 @@ export function aiTick(): void { agency.treasury += grant; agency.bankrupt = false; agency.bankruptAt = null; + agency.bankruptcyReason = null; agency.bailoutsTaken = (agency.bailoutsTaken ?? 0) + 1; agency.reputation = Math.max( 0, @@ -188,9 +305,15 @@ export function aiTick(): void { if (!agency.bankrupt) { agency.bankrupt = true; agency.bankruptAt = simTime; + agency.bankruptcyReason = "treasury_below_operating_threshold"; clearActiveContract(agency); putAgency(agency.name, agency); - emit("agency.bankrupt", { agency: agency.name, isAI: true }); + emit("agency.bankrupt", { + agency: agency.name, + isAI: true, + reason: agency.bankruptcyReason, + treasury: agency.treasury, + }); } continue; } @@ -261,12 +384,14 @@ export function aiTick(): void { if ((agency.aiContractReadyAtSimTime ?? 0) > simTime) { continue; } - const abandonContract = () => { + const abandonContract = (reason: string) => { if (agency.activeContract) { const cur = agency.activeContract; const advanceRefund = Math.round(cur.budget * 0.35); const breachFine = Math.round(cur.budget * profile.breachFineRate); - agency.treasury -= advanceRefund + breachFine; + const penalty = advanceRefund + breachFine; + agency.treasury -= penalty; + agency.contractsAbandoned = (agency.contractsAbandoned ?? 0) + 1; agency.reputation = Math.max( 0, Math.round((agency.reputation - 1.5) * 10) / 10, @@ -278,6 +403,16 @@ export function aiTick(): void { ); clearActiveContract(agency); putAgency(agency.name, agency); + emit("contract.abandoned", { + agency: agency.name, + missionId: cur.id, + offerId: cur.offerId, + contractName: cur.name, + reason, + penalty, + treasury: agency.treasury, + ai: true, + }); } }; maybeUnlockAiTech(agency, contract); @@ -289,7 +424,7 @@ export function aiTick(): void { { chargeDryRuns: true }, ); if (design.maturity !== "flight-ready") { - abandonContract(); + abandonContract("design_not_flight_ready"); continue; } const effectiveMission = { @@ -313,11 +448,11 @@ export function aiTick(): void { !validation.valid || validation.compliance.mandatoryFailed.length > 0 ) { - abandonContract(); + abandonContract("validation_failed"); continue; } if (validation.totalMissionCost > agency.treasury) { - abandonContract(); + abandonContract("unaffordable"); continue; } const asm = @@ -356,10 +491,23 @@ export function aiTick(): void { : 0; const totalCost = validation.totalMissionCost + insurancePremium; if (agency.treasury < totalCost) { - putAgency(agency.name, agency); + abandonContract("unaffordable"); continue; } const reliability = computeDesignReliability(design, asm, agency); + const economics = estimateAiMissionEconomics( + agency, + contract, + design, + asm, + validation, + totalCost, + reliability.anomalyRiskPct, + ); + if (economics.launchNet < -economics.abandonCost) { + abandonContract("negative_expected_value"); + continue; + } const ascent = simulateAscent(design, PARTS, MATERIALS, { weather: world.weather, activeHazards, @@ -435,6 +583,10 @@ export function getLeaderboard() { return listAgencies() .map((a) => { const profile = getDifficultyProfile(a.difficulty); + const recordCompleted = + (a.missionsCompleted ?? 0) + (a.careerMissionsCompleted ?? 0); + const recordFailed = + (a.missionsFailed ?? 0) + (a.careerMissionsFailed ?? 0); return { name: a.name, isAI: !!a.isAI, @@ -444,17 +596,21 @@ export function getLeaderboard() { difficultyLabel: profile.label, aiSkill: a.isAI ? clamp01(a.aiSkill ?? 0.65) : null, bankrupt: !!a.bankrupt, + bankruptcyReason: a.bankruptcyReason ?? null, sponsorId: a.sponsorId, treasury: a.treasury, reputation: Math.round(a.reputation * 10) / 10, - missionsCompleted: a.missionsCompleted, - missionsFailed: a.missionsFailed, + missionsCompleted: recordCompleted, + missionsFailed: recordFailed, + careerMissionsCompleted: a.careerMissionsCompleted ?? 0, + careerMissionsFailed: a.careerMissionsFailed ?? 0, + contractsAbandoned: a.contractsAbandoned ?? 0, earnedTotal: a.earnedTotal, score: Math.round( (a.bankrupt ? -1000 : 0) + a.reputation * 120 + - a.missionsCompleted * 300 - - a.missionsFailed * 90 + + recordCompleted * 300 - + recordFailed * 90 + Math.log10(Math.max(1, a.treasury) + 1) * 55, ), }; diff --git a/src/server/contracts/generator.ts b/src/server/contracts/generator.ts index 0773bd6..f4b792c 100644 --- a/src/server/contracts/generator.ts +++ b/src/server/contracts/generator.ts @@ -102,7 +102,9 @@ export function agencyTier(agency: AgencyState | null | undefined): number { if (!agency) return 0; let score = 0; score += Math.max(0, (agency.reputation ?? 0) - 1) * 0.35; - score += (agency.missionsCompleted ?? 0) * 0.95; + score += + ((agency.missionsCompleted ?? 0) + (agency.careerMissionsCompleted ?? 0)) * + 0.95; score += DIFF_TIER_BONUS[normalizeDifficulty(agency.difficulty)] ?? 0; return Math.max(0, Math.min(3, Math.floor(score))); } diff --git a/src/server/routes/agencyRoutes.ts b/src/server/routes/agencyRoutes.ts index cf36804..2b49c6a 100644 --- a/src/server/routes/agencyRoutes.ts +++ b/src/server/routes/agencyRoutes.ts @@ -51,6 +51,7 @@ export function registerAgencyRoutes(router: Router): void { agency.sponsorId = sponsorId ?? null; agency.bankrupt = false; agency.bankruptAt = null; + agency.bankruptcyReason = null; agency.terminatedReason = null; if (!agency.unlockedTechs?.length) { agency.unlockedTechs = profile.allTechUnlocked @@ -140,6 +141,7 @@ export function registerAgencyRoutes(router: Router): void { agency.treasury += grant; agency.bankrupt = false; agency.bankruptAt = null; + agency.bankruptcyReason = null; agency.bailoutsTaken = (agency.bailoutsTaken ?? 0) + 1; agency.reputation = Math.max( 0, @@ -165,6 +167,7 @@ export function registerAgencyRoutes(router: Router): void { agency.reputation = 1; agency.missionsCompleted = 0; agency.missionsFailed = 0; + agency.contractsAbandoned = 0; agency.earnedTotal = 0; agency.rocketDesign = null; agency.crewConfig = { crewSize: 0, lifeSupport: 1 }; @@ -172,6 +175,7 @@ export function registerAgencyRoutes(router: Router): void { agency.contractHistory = []; agency.bankrupt = false; agency.bankruptAt = null; + agency.bankruptcyReason = null; agency.bailoutsTaken = 0; agency.unlockedTechs = profile.allTechUnlocked ? TECH_TREE.map((t) => t.id) diff --git a/src/server/settlement.ts b/src/server/settlement.ts index 03c1bc3..97829fd 100644 --- a/src/server/settlement.ts +++ b/src/server/settlement.ts @@ -177,6 +177,7 @@ export function settleMissionOutcome( "Catastrophic Loss of Crew — Flight Director License Revoked"; agency.bankrupt = true; agency.bankruptAt = simTime; + agency.bankruptcyReason = agency.terminatedReason; } summary = profile.id === "sandbox" @@ -215,7 +216,13 @@ export function settleMissionOutcome( if (agency.treasury < 5_000_000 && !agency.bankrupt) { agency.bankrupt = true; agency.bankruptAt = simTime; - emit("agency.bankrupt", { agency: agency.name, isAI: !!agency.isAI }); + agency.bankruptcyReason = "mission_failure_insolvency"; + emit("agency.bankrupt", { + agency: agency.name, + isAI: !!agency.isAI, + reason: agency.bankruptcyReason, + treasury: agency.treasury, + }); } emit("mission.failed", { agency: agency.name, diff --git a/src/server/world.ts b/src/server/world.ts index a689d89..09931a4 100644 --- a/src/server/world.ts +++ b/src/server/world.ts @@ -77,6 +77,7 @@ function chargeFacilityOverhead(simTime: number): void { if (agency.treasury < 0) { agency.bankrupt = true; agency.bankruptAt = simTime; + agency.bankruptcyReason = "facility_overhead_insolvency"; emit("agency.bankrupt", { agency: agency.name, isAI: !!agency.isAI, diff --git a/src/shared/types/agency.ts b/src/shared/types/agency.ts index aa4c6e7..2ac293b 100644 --- a/src/shared/types/agency.ts +++ b/src/shared/types/agency.ts @@ -60,6 +60,9 @@ export interface AgencyState { reputation: number; missionsCompleted: number; missionsFailed: number; + careerMissionsCompleted?: number; + careerMissionsFailed?: number; + contractsAbandoned?: number; earnedTotal: number; rocketDesign: RocketDesign | null; crewConfig: CrewConfig | null; @@ -67,6 +70,7 @@ export interface AgencyState { contractHistory: string[]; bankrupt: boolean; bankruptAt?: number | null; + bankruptcyReason?: string | null; bailoutsTaken?: number; unlockedTechs?: string[]; partHeritage?: Record;