Nerf random events

Add earth some fanciness
This commit is contained in:
tyuXX 2026-11-15 15:42:41 +03:00
parent 142164edd4
commit 2e3cea5a30
11 changed files with 356 additions and 21 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 221 KiB

BIN
models/earth/earth_day.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 501 KiB

View file

@ -1,6 +1,6 @@
{ {
"name": "org.gsdistance.spacegaem", "name": "org.gsdistance.spacegaem",
"version": "0.0.1", "version": "1.0.3",
"description": "Space mission design game made to be as realistic as I could make it.", "description": "Space mission design game made to be as realistic as I could make it.",
"keywords": [ "keywords": [
"Space", "Space",

View file

@ -1,11 +1,14 @@
// Ascent sky, curved Earth horizon, clouds, and supersonic aero shock shaders // Ascent sky, curved Earth horizon, clouds, and supersonic aero shock shaders
// The earth is just a blue ball, source? Trust me bro
import * as THREE from "three"; import * as THREE from "three";
import { getSettings } from "../../api.js"; import { getSettings } from "../../api.js";
import { isReducedEffects } from "../../theme.js"; import { isReducedEffects } from "../../theme.js";
import type { RocketMeshHandle } from "../../three/rocketMesh.js"; import type { RocketMeshHandle } from "../../three/rocketMesh.js";
import { getSoftParticleTexture } from "../../three/sceneManager.js"; import { getSoftParticleTexture } from "../../three/sceneManager.js";
import { createGpuParticlePool, type GpuParticlePool } from "./particles.js"; import { createGpuParticlePool, type GpuParticlePool } from "./particles.js";
import {
getEarthCloudTexture,
getEarthSurfaceTexture,
} from "../../three/earthTexture.js";
export function createAscentEnvironment(): { export function createAscentEnvironment(): {
env: THREE.Group; env: THREE.Group;
@ -15,16 +18,56 @@ export function createAscentEnvironment(): {
const env = new THREE.Group(); const env = new THREE.Group();
const earthRadius = 18000; const earthRadius = 18000;
const earth = new THREE.Mesh( const earth = new THREE.Mesh(
new THREE.SphereGeometry(earthRadius, 72, 54), new THREE.SphereGeometry(earthRadius, 96, 72),
new THREE.MeshStandardMaterial({ new THREE.MeshStandardMaterial({
color: 0x0e2540, map: getEarthSurfaceTexture(),
roughness: 0.88, color: 0x8ea6bd,
metalness: 0.06, roughness: 0.95,
metalness: 0.0,
envMapIntensity: 0.25,
}), }),
); );
earth.position.set(0, -earthRadius - 0.25, 0); earth.position.set(0, -earthRadius - 0.25, 0);
earth.receiveShadow = true; earth.receiveShadow = true;
env.add(earth); env.add(earth);
const cloudMat = new THREE.ShaderMaterial({
uniforms: {
uMap: { value: getEarthCloudTexture() },
uTime: { value: 0 },
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform sampler2D uMap;
uniform float uTime;
varying vec2 vUv;
void main() {
vec2 uv = vec2(fract(vUv.x + uTime * 0.0035), vUv.y);
vec4 tex = texture2D(uMap, uv);
if (tex.a < 0.015) discard;
gl_FragColor = vec4(tex.rgb * 0.92, tex.a * 0.88);
}
`,
transparent: true,
depthWrite: false,
polygonOffset: true,
polygonOffsetFactor: -2,
polygonOffsetUnits: -8,
});
const clouds = new THREE.Mesh(
new THREE.SphereGeometry(earthRadius + 320, 64, 48),
cloudMat,
);
clouds.position.copy(earth.position);
clouds.onBeforeRender = () => {
cloudMat.uniforms.uTime.value = performance.now() * 0.001;
};
env.add(clouds);
const atmoLimb = new THREE.Mesh( const atmoLimb = new THREE.Mesh(
new THREE.SphereGeometry(earthRadius + 210, 72, 54), new THREE.SphereGeometry(earthRadius + 210, 72, 54),
new THREE.ShaderMaterial({ new THREE.ShaderMaterial({

View file

@ -4,6 +4,7 @@ import { applyThemeFromState, currentContract } from "../../state.js";
import { BODY_RADIUS_KM } from "../../../shared/ephemeris.js"; import { BODY_RADIUS_KM } from "../../../shared/ephemeris.js";
import type { SimResult, TelemetrySample } from "../../../shared/types.js"; import type { SimResult, TelemetrySample } from "../../../shared/types.js";
import type { LaunchContext } from "./context.js"; import type { LaunchContext } from "./context.js";
import { getEarthSurfaceTexture } from "../../three/earthTexture.js";
import { pushEventLog } from "./hud.js"; import { pushEventLog } from "./hud.js";
import { resetGpuPool } from "./particles.js"; import { resetGpuPool } from "./particles.js";
@ -121,7 +122,8 @@ export function enterOrbitPhase(ctx: LaunchContext): void {
bodyId === "sun" bodyId === "sun"
? new THREE.MeshBasicMaterial({ color: bodyColors[bodyId] }) ? new THREE.MeshBasicMaterial({ color: bodyColors[bodyId] })
: new THREE.MeshStandardMaterial({ : new THREE.MeshStandardMaterial({
color: bodyColors[bodyId] ?? 0x4f9cf9, map: bodyId === "earth" ? getEarthSurfaceTexture() : null,
color: bodyId === "earth" ? 0xffffff : (bodyColors[bodyId] ?? 0x4f9cf9),
roughness: 0.72, roughness: 0.72,
metalness: 0.08, metalness: 0.08,
}), }),

View file

@ -217,6 +217,9 @@ export function renderLaunchSequence(
color: 0x151b26, color: 0x151b26,
roughness: 0.92, roughness: 0.92,
metalness: 0.06, metalness: 0.06,
polygonOffset: true,
polygonOffsetFactor: -2,
polygonOffsetUnits: -4,
}), }),
); );
apron.rotation.x = -Math.PI / 2; apron.rotation.x = -Math.PI / 2;

View file

@ -0,0 +1,273 @@
// Earth surface + cloud textures. Real equirectangular NASA-derived maps are
// loaded from /models/earth/ and swapped in over a procedural placeholder so the
// sphere is never untextured while the download is in flight.
import * as THREE from "three";
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const PERM = new Uint8Array(512);
{
const p = new Uint8Array(256);
for (let i = 0; i < 256; i++) p[i] = i;
const rnd = mulberry32(20261115);
for (let i = 255; i > 0; i--) {
const j = (rnd() * (i + 1)) | 0;
const t = p[i];
p[i] = p[j];
p[j] = t;
}
for (let i = 0; i < 512; i++) PERM[i] = p[i & 255];
}
function hash3(x: number, y: number, z: number): number {
return PERM[(PERM[(PERM[x & 255] + y) & 255] + z) & 255] / 255;
}
const fade = (t: number) => t * t * t * (t * (t * 6 - 15) + 10);
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
const sstep = (a: number, b: number, x: number) => {
const t = Math.min(1, Math.max(0, (x - a) / (b - a)));
return t * t * (3 - 2 * t);
};
function vnoise(x: number, y: number, z: number): number {
const xi = Math.floor(x);
const yi = Math.floor(y);
const zi = Math.floor(z);
const xf = x - xi;
const yf = y - yi;
const zf = z - zi;
const u = fade(xf);
const v = fade(yf);
const w = fade(zf);
const c000 = hash3(xi, yi, zi);
const c100 = hash3(xi + 1, yi, zi);
const c010 = hash3(xi, yi + 1, zi);
const c110 = hash3(xi + 1, yi + 1, zi);
const c001 = hash3(xi, yi, zi + 1);
const c101 = hash3(xi + 1, yi, zi + 1);
const c011 = hash3(xi, yi + 1, zi + 1);
const c111 = hash3(xi + 1, yi + 1, zi + 1);
return lerp(
lerp(lerp(c000, c100, u), lerp(c010, c110, u), v),
lerp(lerp(c001, c101, u), lerp(c011, c111, u), v),
w,
);
}
function fbm(
x: number,
y: number,
z: number,
octaves: number,
gain = 0.5,
lacunarity = 2.03,
): number {
let amp = 0.5;
let freq = 1;
let sum = 0;
let norm = 0;
for (let i = 0; i < octaves; i++) {
sum += amp * vnoise(x * freq, y * freq, z * freq);
norm += amp;
amp *= gain;
freq *= lacunarity;
}
return sum / norm;
}
const SURFACE_W = 640;
const SURFACE_H = 320;
const CLOUD_W = 640;
const CLOUD_H = 320;
let surfaceTex: THREE.Texture | null = null;
let cloudTex: THREE.Texture | null = null;
function buildEarthSurface(): HTMLCanvasElement {
const canvas = document.createElement("canvas");
canvas.width = SURFACE_W;
canvas.height = SURFACE_H;
const ctx = canvas.getContext("2d");
if (!ctx) return canvas;
const img = ctx.createImageData(SURFACE_W, SURFACE_H);
const d = img.data;
for (let y = 0; y < SURFACE_H; y++) {
const lat = (0.5 - (y + 0.5) / SURFACE_H) * Math.PI;
const cosLat = Math.cos(lat);
const sinLat = Math.sin(lat);
const latN = Math.abs(lat) / (Math.PI / 2);
for (let x = 0; x < SURFACE_W; x++) {
const lon = ((x + 0.5) / SURFACE_W) * Math.PI * 2 - Math.PI;
const px = cosLat * Math.cos(lon);
const py = sinLat;
const pz = cosLat * Math.sin(lon);
const wx = fbm(px * 1.6 + 11.3, py * 1.6 + 7.1, pz * 1.6 + 3.7, 3);
const wy = fbm(px * 1.6 + 3.1, py * 1.6 + 9.4, pz * 1.6 + 5.2, 3);
const wz = fbm(px * 1.6 + 8.8, py * 1.6 + 2.6, pz * 1.6 + 12.9, 3);
const ox = px * 2.4 + wx * 1.5;
const oy = py * 2.4 + wy * 1.5;
const oz = pz * 2.4 + wz * 1.5;
const cont = fbm(ox, oy, oz, 5);
const elev = fbm(px * 5.2 - wx, py * 5.2 - wy, pz * 5.2 - wz, 3);
const moist = fbm(px * 7.1 + 31.7, py * 7.1 + 17.3, pz * 7.1 + 7.9, 2);
const land = sstep(0.53, 0.57, cont);
const coast = sstep(0.0, 0.1, land) * (1 - sstep(0.1, 0.28, land));
const shallowF = 1 - sstep(0.55, 0.68, cont);
let r: number;
let g: number;
let b: number;
if (land > 0) {
const arid = 1 - sstep(0.38, 0.55, moist);
const trop = 1 - sstep(0.25, 0.55, latN);
let vr = lerp(64, 46, trop);
let vg = lerp(102, 116, trop);
let vb = lerp(62, 58, trop);
vr = lerp(vr, 172, arid * 0.85);
vg = lerp(vg, 148, arid * 0.85);
vb = lerp(vb, 96, arid * 0.85);
const tundra = sstep(0.55, 0.75, latN);
vr = lerp(vr, 122, tundra * 0.6);
vg = lerp(vg, 118, tundra * 0.6);
vb = lerp(vb, 104, tundra * 0.6);
const rock = sstep(0.58, 0.72, elev) * land;
vr = lerp(vr, 118, rock * 0.7);
vg = lerp(vg, 112, rock * 0.7);
vb = lerp(vb, 104, rock * 0.7);
const snow =
(sstep(0.66, 0.74, elev) + sstep(0.8, 0.9, latN + (elev - 0.5) * 0.25)) *
land;
const iceCap = sstep(0.86, 0.94, latN + (cont - 0.5) * 0.3) * land;
r = lerp(vr, 232, Math.min(1, snow * 0.9 + iceCap));
g = lerp(vg, 238, Math.min(1, snow * 0.9 + iceCap));
b = lerp(vb, 244, Math.min(1, snow * 0.9 + iceCap));
r = lerp(r, 206, coast);
g = lerp(g, 188, coast);
b = lerp(b, 148, coast);
} else {
r = lerp(11, 36, shallowF);
g = lerp(42, 112, shallowF);
b = lerp(88, 168, shallowF);
r += (elev - 0.5) * 8;
g += (elev - 0.5) * 10;
b += (elev - 0.5) * 12;
}
const shade = 0.94 + elev * 0.12;
const i = (y * SURFACE_W + x) * 4;
d[i] = Math.max(0, Math.min(255, r * shade));
d[i + 1] = Math.max(0, Math.min(255, g * shade));
d[i + 2] = Math.max(0, Math.min(255, b * shade));
d[i + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
return canvas;
}
function buildClouds(): HTMLCanvasElement {
const canvas = document.createElement("canvas");
canvas.width = CLOUD_W;
canvas.height = CLOUD_H;
const ctx = canvas.getContext("2d");
if (!ctx) return canvas;
const img = ctx.createImageData(CLOUD_W, CLOUD_H);
const d = img.data;
for (let y = 0; y < CLOUD_H; y++) {
const lat = (0.5 - (y + 0.5) / CLOUD_H) * Math.PI;
const cosLat = Math.cos(lat);
const sinLat = Math.sin(lat);
for (let x = 0; x < CLOUD_W; x++) {
const lon = ((x + 0.5) / CLOUD_W) * Math.PI * 2 - Math.PI;
const px = cosLat * Math.cos(lon);
const py = sinLat;
const pz = cosLat * Math.sin(lon);
const wx = fbm(px * 2.1 + 4.2, py * 2.1 + 9.7, pz * 2.1 + 1.3, 3);
const wy = fbm(px * 2.1 + 7.7, py * 2.1 + 2.9, pz * 2.1 + 6.1, 3);
const wz = fbm(px * 2.1 + 1.4, py * 2.1 + 5.5, pz * 2.1 + 8.8, 3);
const base = fbm(
px * 3.1 + wx * 1.8,
py * 3.1 + wy * 1.8,
pz * 3.1 + wz * 1.8,
5,
);
const detail = fbm(px * 8.5 + 13.1, py * 8.5 + 4.4, pz * 8.5 + 9.2, 3);
const cl = base * 0.72 + detail * 0.28;
const a = sstep(0.56, 0.74, cl);
const shade = 0.82 + detail * 0.3;
const i = (y * CLOUD_W + x) * 4;
d[i] = Math.min(255, 245 * shade);
d[i + 1] = Math.min(255, 248 * shade);
d[i + 2] = Math.min(255, 252 * shade);
d[i + 3] = a * 235;
}
}
ctx.putImageData(img, 0, 0);
return canvas;
}
const loader = new THREE.TextureLoader();
function compressHighlights(
img: HTMLImageElement,
): HTMLCanvasElement | HTMLImageElement {
const w = img.width;
const h = img.height;
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
if (!ctx) return img;
ctx.drawImage(img, 0, 0, w, h);
const data = ctx.getImageData(0, 0, w, h);
const d = data.data;
for (let i = 0; i < d.length; i += 4) {
for (let c = 0; c < 3; c++) {
const v = d[i + c];
if (v > 185) d[i + c] = 185 + (v - 185) * 0.5;
}
}
ctx.putImageData(data, 0, 0);
return canvas;
}
function upgradeTexture(tex: THREE.Texture, url: string, soften = false): void {
loader.load(url, (loaded) => {
tex.image = soften && loaded.image instanceof HTMLImageElement
? compressHighlights(loaded.image)
: loaded.image;
tex.needsUpdate = true;
});
}
export function getEarthSurfaceTexture(): THREE.Texture {
if (!surfaceTex) {
surfaceTex = new THREE.Texture(buildEarthSurface());
surfaceTex.colorSpace = THREE.SRGBColorSpace;
surfaceTex.wrapS = THREE.RepeatWrapping;
surfaceTex.anisotropy = 8;
surfaceTex.needsUpdate = true;
upgradeTexture(surfaceTex, "/models/earth/earth_day.jpg", true);
}
return surfaceTex;
}
export function getEarthCloudTexture(): THREE.Texture {
if (!cloudTex) {
cloudTex = new THREE.Texture(buildClouds());
cloudTex.colorSpace = THREE.SRGBColorSpace;
cloudTex.wrapS = THREE.RepeatWrapping;
cloudTex.anisotropy = 8;
cloudTex.needsUpdate = true;
upgradeTexture(cloudTex, "/models/earth/earth_clouds.png");
}
return cloudTex;
}

View file

@ -6,6 +6,7 @@ import {
PLANETS, PLANETS,
bodyPosition, bodyPosition,
} from "../../shared/ephemeris.js"; } from "../../shared/ephemeris.js";
import { getEarthSurfaceTexture } from "./earthTexture.js";
export interface SolarSystemHandle { export interface SolarSystemHandle {
group: THREE.Group; group: THREE.Group;
@ -101,10 +102,12 @@ export function buildSolarSystem(
group.add(ring); group.add(ring);
} }
const rVis = visualRadius[body.id] ?? 3.5; const rVis = visualRadius[body.id] ?? 3.5;
const isEarth = body.id === "earth";
const mesh = new THREE.Mesh( const mesh = new THREE.Mesh(
new THREE.SphereGeometry(rVis, 24, 24), new THREE.SphereGeometry(rVis, 24, 24),
new THREE.MeshStandardMaterial({ new THREE.MeshStandardMaterial({
color: body.color, map: isEarth ? getEarthSurfaceTexture() : null,
color: isEarth ? 0xffffff : body.color,
roughness: 0.72, roughness: 0.72,
metalness: 0.08, metalness: 0.08,
}), }),

View file

@ -7,6 +7,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
export const APP_ROOT = path.resolve(__dirname, "..", ".."); export const APP_ROOT = path.resolve(__dirname, "..", "..");
export const config = { export const config = {
version: process.env.npm_package_version || "dev",
port: Number(process.env.PORT ?? 3100), port: Number(process.env.PORT ?? 3100),
serverPassword: process.env.SPACEGAEM_PASSWORD ?? "", serverPassword: process.env.SPACEGAEM_PASSWORD ?? "",
dataFile: process.env.DATA_FILE || path.join(APP_ROOT, "data", "db.json"), dataFile: process.env.DATA_FILE || path.join(APP_ROOT, "data", "db.json"),

View file

@ -20,6 +20,10 @@ export const WEATHER_POOL: SpaceWeather[] = [
const HAZARD_WINDOW_SEC = 2400; const HAZARD_WINDOW_SEC = 2400;
// Probability that a given slot produces a hazard during its epoch.
// Epochs following an eventful epoch are skipped entirely (cooldown).
const SLOT_OCCURRENCE: Record<number, number> = { 0: 0.6, 1: 0.35 };
function seededRand(seed: number): () => number { function seededRand(seed: number): () => number {
let s = seed >>> 0; let s = seed >>> 0;
return () => { return () => {
@ -111,24 +115,30 @@ function buildHazardEvent(epoch: number, slot: number): PreLaunchHazardEvent {
}; };
} }
function slotsWithEvents(epoch: number): number[] {
const slots = epoch % 2 === 1 ? [0, 1] : [0];
return slots.filter((slot) => {
const rnd = seededRand(epoch * 104729 + slot * 7919 + 3);
return rnd() < SLOT_OCCURRENCE[slot];
});
}
// An epoch only spawns hazards if the previous epoch was completely quiet,
// guaranteeing a cooldown gap between hazard windows.
function eventsForEpoch(epoch: number): PreLaunchHazardEvent[] {
if (slotsWithEvents(epoch - 1).length > 0) return [];
return slotsWithEvents(epoch).map((slot) => buildHazardEvent(epoch, slot));
}
export function ensureHazards(simTime: number): void { export function ensureHazards(simTime: number): void {
const world = getWorld(); const world = getWorld();
const curEpoch = Math.floor(simTime / HAZARD_WINDOW_SEC); const curEpoch = Math.floor(simTime / HAZARD_WINDOW_SEC);
if ( if (world.hazardEpoch === curEpoch && world.activeHazards) {
world.hazardEpoch === curEpoch &&
(world.activeHazards?.length || world.upcomingHazards?.length)
) {
return; return;
} }
const prevActiveIds = (world.activeHazards ?? []).map((h) => h.id).join(","); const prevActiveIds = (world.activeHazards ?? []).map((h) => h.id).join(",");
const active: PreLaunchHazardEvent[] = [buildHazardEvent(curEpoch, 0)]; const active = eventsForEpoch(curEpoch);
if (curEpoch % 2 === 1) { const upcoming = [...eventsForEpoch(curEpoch + 1), ...eventsForEpoch(curEpoch + 2)];
active.push(buildHazardEvent(curEpoch, 1));
}
const upcoming: PreLaunchHazardEvent[] = [
buildHazardEvent(curEpoch + 1, 0),
buildHazardEvent(curEpoch + 2, 1),
];
world.activeHazards = active; world.activeHazards = active;
world.upcomingHazards = upcoming; world.upcomingHazards = upcoming;
world.hazardEpoch = curEpoch; world.hazardEpoch = curEpoch;

View file

@ -67,7 +67,7 @@ setInterval(tick, 1000);
app.listen(config.port, () => { app.listen(config.port, () => {
const gmatConsole = resolveGmatConsoleBin(); const gmatConsole = resolveGmatConsoleBin();
console.log( console.log(
`Space Gaem: You Will Feel the Pain (TypeScript Prototype) on http://localhost:${config.port}`, `Space Gaem: You Will Feel the Pain v${config.version} on http://localhost:${config.port}`,
); );
console.log( console.log(
` GMAT: ${gmatConsole ?? "NOT FOUND (analytic ephemeris fallback)"}`, ` GMAT: ${gmatConsole ?? "NOT FOUND (analytic ephemeris fallback)"}`,