Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

17.8 KB
Raw Blame
// "Omarchy Orbital — Living Earth"
// Cinema-grade real-time 3D Earth desktop wallpaper in standard three.js WebGPURenderer + TSL.
// Uses real 4K NASA Blue Marble / Black Marble / Elevation+Roughness+Cloud maps, two-layer cloud
// drift with surface shadows, Rayleigh/twilight atmospheric scattering, and subtle Omarchy theme
// harmony. Runs identically in BOTH ThreeRT (`threert-wallpaper`) and Chromium WebGPU.
import * as THREE from "three/webgpu";
import {
  bumpMap,
  cameraPosition,
  clamp,
  dot,
  float,
  mix,
  normalize,
  normalWorld,
  positionWorld,
  pow,
  smoothstep,
  texture,
  uniform,
  uv,
  vec2,
  vec3,
} from "three/tsl";

interface ThemePalette {
  mode?: string;
  accent?: string;
  background?: string;
  dark_background?: string;
  darker_background?: string;
  lighter_background?: string;
  blue?: string;
  cyan?: string;
  magenta?: string;
  orange?: string;
  yellow?: string;
}

interface WallpaperBridge {
  theme?: ThemePalette;
  fixedTime?: number | null;
  fps?: number;
  onThemeChange?: (fn: (t: ThemePalette) => void) => void;
}

declare global {
  var __threertGpuCanvas: HTMLCanvasElement | undefined;
  var __wallpaper: WallpaperBridge | undefined;
  var __WALLPAPER_THEME: ThemePalette | undefined;
  var __native: { sys?: { resource?: (path: string) => ArrayBuffer | null } } | undefined;
  var __ttffMs: number | undefined;
  var __frameCount: number | undefined;
  var __rendererBackend: string | undefined;
}

const DEFAULT_THEME: Required<ThemePalette> = {
  mode: "dark",
  accent: "#7aa2f7",
  background: "#1a1b26",
  dark_background: "#13141c",
  darker_background: "#0e0e14",
  lighter_background: "#24283b",
  blue: "#7aa2f7",
  cyan: "#449dab",
  magenta: "#ad8ee6",
  orange: "#eb927b",
  yellow: "#e0af68",
};

function resolveTheme(raw?: ThemePalette): Required<ThemePalette> {
  return { ...DEFAULT_THEME, ...(raw || {}) };
}

function getQueryParam(name: string): string | null {
  try {
    const loc = globalThis.location;
    if (!loc || !loc.search) return null;
    return new URLSearchParams(loc.search).get(name);
  } catch {
    return null;
  }
}

function mulberry32(seed: number) {
  let a = seed >>> 0;
  return () => {
    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;
  };
}

/** Load an equirectangular 4K JPEG asset identically in ThreeRT (native resource) and Chromium (fetch). */
async function loadPlanetTexture(
  filename: string,
  srgb: boolean,
  maxAnisotropy: number,
): Promise<THREE.Texture> {
  let source: Blob | { arrayBuffer: () => Promise<ArrayBuffer> };
  const nativeRes = globalThis.__native?.sys?.resource;
  if (typeof nativeRes === "function") {
    const buf = nativeRes(filename);
    if (!buf) throw new Error(`Missing local planet texture: ${filename}`);
    source = { arrayBuffer: () => Promise.resolve(buf) };
  } else {
    const res = await fetch(`./assets/${filename}`);
    if (!res.ok) throw new Error(`Failed to fetch ./assets/${filename}: ${res.status}`);
    source = await res.blob();
  }
  const bitmap = await createImageBitmap(source as Blob);
  const tex = new THREE.Texture(bitmap);
  tex.colorSpace = srgb ? THREE.SRGBColorSpace : THREE.NoColorSpace;
  tex.wrapS = THREE.RepeatWrapping;
  tex.wrapT = THREE.ClampToEdgeWrapping;
  tex.anisotropy = maxAnisotropy;
  tex.generateMipmaps = true;
  tex.minFilter = THREE.LinearMipmapLinearFilter;
  tex.magFilter = THREE.LinearFilter;
  tex.needsUpdate = true;
  return tex;
}

/** Compute harmonized planetary atmosphere & deep-space tint from an Omarchy theme palette. */
function computeThemeHarmonics(p: Required<ThemePalette>) {
  // Keep space authentically deep dark with a subtle nod to the Omarchy background
  const spaceBg = new THREE.Color(0x02040a).lerp(
    new THREE.Color(p.darker_background),
    p.mode === "light" ? 0.12 : 0.28,
  );
  // Natural Rayleigh sky blue gently harmonized (20%) with Omarchy's accent/cyan
  const atmoDay = new THREE.Color(0x4cb4ff).lerp(new THREE.Color(p.accent), 0.22);
  // Natural fiery sunset scattering gently harmonized (18%) with Omarchy's orange/yellow
  const atmoTwilight = new THREE.Color(0xff6b35).lerp(new THREE.Color(p.orange), 0.20);
  // Subtle night-side ambient starlight tint
  const nightAmb = new THREE.Color(0x0e182a).lerp(new THREE.Color(p.blue), 0.15);
  return { spaceBg, atmoDay, atmoTwilight, nightAmb };
}

async function main() {
  const bootT0 = performance.now();
  const canvas: HTMLCanvasElement =
    globalThis.__threertGpuCanvas ??
    (document.getElementById("canvas") as HTMLCanvasElement);

  const queryFixedT = getQueryParam("t");
  const fixedTime: number | null =
    typeof globalThis.__wallpaper?.fixedTime === "number"
      ? globalThis.__wallpaper.fixedTime
      : queryFixedT !== null && Number.isFinite(parseFloat(queryFixedT))
        ? parseFloat(queryFixedT)
        : null;

  const queryFps = getQueryParam("fps");
  const maxBrowserFps =
    !globalThis.__threertGpuCanvas && queryFps !== null && Number.isFinite(parseFloat(queryFps))
      ? Math.max(1, parseFloat(queryFps))
      : null;

  const queryDpr = getQueryParam("dpr");
  const dpr =
    queryDpr !== null && Number.isFinite(parseFloat(queryDpr))
      ? parseFloat(queryDpr)
      : window.devicePixelRatio || 1;

  const queryW = getQueryParam("w");
  const queryH = getQueryParam("h");
  const targetW =
    queryW !== null && Number.isFinite(parseInt(queryW, 10))
      ? parseInt(queryW, 10)
      : window.innerWidth;
  const targetH =
    queryH !== null && Number.isFinite(parseInt(queryH, 10))
      ? parseInt(queryH, 10)
      : window.innerHeight;

  const renderer = new THREE.WebGPURenderer({
    canvas,
    antialias: true,
    powerPreference: "low-power",
  });
  renderer.setPixelRatio(dpr);
  renderer.setSize(targetW, targetH, false);
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.12;
  await renderer.init();

  const backendName =
    (renderer.backend as { isWebGPUBackend?: boolean })?.isWebGPUBackend
      ? "WebGPU"
      : "WebGL2";
  globalThis.__rendererBackend = backendName;

  // Decode all three 4K NASA planet maps in parallel
  const [dayTex, nightTex, brcTex] = await Promise.all([
    loadPlanetTexture("earth_day_4096.jpg", true, 8),
    loadPlanetTexture("earth_night_4096.jpg", true, 8),
    loadPlanetTexture("earth_bump_roughness_clouds_4096.jpg", false, 8),
  ]);

  const scene = new THREE.Scene();
  const initialPalette = resolveTheme(
    globalThis.__wallpaper?.theme ?? globalThis.__WALLPAPER_THEME,
  );
  let targetHarmonics = computeThemeHarmonics(initialPalette);
  scene.background = targetHarmonics.spaceBg.clone();

  // Telephoto orbital camera for dignified, low-distortion planetary perspective
  const camera = new THREE.PerspectiveCamera(27, targetW / targetH, 0.1, 200);
  camera.position.set(0, 0.16, 4.95);
  camera.lookAt(0, -0.02, 0);

  // ---- Solar Lighting (crisp three-quarter crescent lighting) ----
  const sunDirVec = new THREE.Vector3(6.8, 2.3, 3.6).normalize();
  const uSunDir = uniform(sunDirVec.clone());
  const uAtmoDay = uniform(targetHarmonics.atmoDay.clone());
  const uAtmoTwilight = uniform(targetHarmonics.atmoTwilight.clone());

  const sunLight = new THREE.DirectionalLight(0xfff6ea, 3.25);
  sunLight.position.copy(sunDirVec).multiplyScalar(20);
  scene.add(sunLight);

  // Very faint cosmic bounce so the dark limb retains subtle silhouette without washing out city lights
  const cosmicAmbient = new THREE.AmbientLight(targetHarmonics.nightAmb, 0.12);
  scene.add(cosmicAmbient);

  // ---- Earth Axial Tilt Group (23.44° obliquity) ----
  const earthTilt = new THREE.Group();
  earthTilt.rotation.z = THREE.MathUtils.degToRad(-23.44);
  earthTilt.rotation.x = THREE.MathUtils.degToRad(11.5);
  scene.add(earthTilt);

  // ---- 1. Earth Surface Sphere (4K Albedo + Night Cities + Relief Bump + Ocean Specular + Cloud Shadow) ----
  const earthGeo = new THREE.SphereGeometry(1.0, 96, 96);
  const earthMat = new THREE.MeshStandardNodeMaterial({
    metalness: 0.04,
  });

  const baseUv = uv();
  const dayColor = texture(dayTex, baseUv).rgb;
  const nightColor = texture(nightTex, baseUv).rgb;
  const brcSample = texture(brcTex, baseUv);
  const elevMap = brcSample.r;
  const roughMap = brcSample.g;
  const cloudDensity = brcSample.b;

  // Soft cloud shadow projected slightly opposite the sun onto oceans/land below
  const shadowCloud = texture(brcTex, baseUv.add(vec2(-0.0022, 0.0010))).b;
  const cloudShadowFactor = float(1.0).sub(smoothstep(float(0.18), float(0.85), shadowCloud).mul(0.32));

  // Physically-motivated ocean/continent roughness (glossy ocean sun-glint, matte continents)
  earthMat.roughnessNode = mix(float(0.16), float(0.86), roughMap);
  earthMat.bumpMap = null;
  earthMat.normalNode = bumpMap(elevMap, float(0.032));

  // Sun angle & view-dependent atmospheric limb Fresnel
  const sunDot = dot(normalWorld, uSunDir);
  const viewDir = normalize(cameraPosition.sub(positionWorld));
  const fresnel = pow(float(1.0).sub(clamp(dot(viewDir, normalWorld), 0.0, 1.0)), float(3.2));

  const dayFactor = smoothstep(float(-0.18), float(0.28), sunDot);
  const nightFactor = smoothstep(float(0.10), float(-0.24), sunDot);
  const twilightFactor = smoothstep(float(-0.26), float(0.01), sunDot).mul(
    smoothstep(float(0.34), float(0.01), sunDot),
  );

  // Subtle surface atmospheric aerial perspective + sunset reddening at the terminator
  const atmoColor = mix(uAtmoDay, uAtmoTwilight, twilightFactor.mul(0.85));
  const surfaceAtmoMix = fresnel.mul(smoothstep(float(-0.22), float(0.35), sunDot)).mul(0.68);
  const litSurface = dayColor.mul(cloudShadowFactor);
  // Subtle warm sunset grazing tint right on the terminator
  const terminatorWarmth = litSurface.mul(mix(vec3(1.0, 1.0, 1.0), vec3(1.18, 0.86, 0.72), twilightFactor.mul(0.65)));
  earthMat.colorNode = mix(terminatorWarmth, atmoColor, surfaceAtmoMix);

  // Warm golden city lights on the night hemisphere (softly attenuated by dense cloud cover)
  const cloudAttenuation = float(1.0).sub(smoothstep(float(0.25), float(0.92), cloudDensity).mul(0.50));
  const cityGlow = nightColor.mul(vec3(2.4, 1.68, 0.96)).mul(nightFactor).mul(cloudAttenuation);
  // Emissive atmospheric limb scattering glow
  const limbGlow = atmoColor.mul(fresnel).mul(smoothstep(float(-0.22), float(0.45), sunDot)).mul(0.72);
  earthMat.emissiveNode = cityGlow.add(limbGlow);

  const earthMesh = new THREE.Mesh(earthGeo, earthMat);
  earthTilt.add(earthMesh);

  // ---- 2. Elevated Drifting Cloud Deck (subtle parallax & independent wind rotation) ----
  const cloudGeo = new THREE.SphereGeometry(1.0085, 96, 96);
  const cloudMat = new THREE.MeshStandardNodeMaterial({
    transparent: true,
    depthWrite: false,
    roughness: 0.92,
    metalness: 0.0,
  });
  const cloudSample = texture(brcTex, uv()).b;
  const cloudAlpha = smoothstep(float(0.14), float(0.82), cloudSample).mul(0.92);
  const cloudSunDot = dot(normalWorld, uSunDir);
  const cloudTwilight = smoothstep(float(-0.20), float(0.03), cloudSunDot).mul(
    smoothstep(float(0.32), float(0.03), cloudSunDot),
  );
  // Sunlit clouds pure bright white, terminator clouds warm coral/gold, night clouds dark silhouette
  const cloudTint = mix(vec3(0.97, 0.98, 1.0), vec3(1.0, 0.72, 0.54), cloudTwilight.mul(0.75));
  cloudMat.colorNode = cloudTint;
  cloudMat.emissiveNode = uAtmoTwilight.mul(cloudTwilight.mul(0.16));
  cloudMat.opacityNode = cloudAlpha.mul(mix(float(0.22), float(1.0), smoothstep(float(-0.25), float(0.15), cloudSunDot)));

  const cloudMesh = new THREE.Mesh(cloudGeo, cloudMat);
  earthTilt.add(cloudMesh);

  // ---- 3. Outer Volumetric Rayleigh/Mie Atmosphere Halo Shell ----
  const atmoGeo = new THREE.SphereGeometry(1.072, 96, 96);
  const atmoMat = new THREE.MeshBasicNodeMaterial({
    side: THREE.BackSide,
    transparent: true,
    depthWrite: false,
    blending: THREE.AdditiveBlending,
  });
  const atmoViewDir = normalize(cameraPosition.sub(positionWorld));
  // Use explicit geometric outward normal (Earth is centered at origin) so BackSide normal flipping
  // never cancels the limb profile. Peaks at Earth's horizon (~0.36) and feathers smoothly to 0 at r=1.072.
  const geoNormal = normalize(positionWorld);
  const rimDot = clamp(dot(atmoViewDir, geoNormal.negate()), 0.0, 1.0);
  const haloFalloff = pow(clamp(rimDot.mul(2.55), 0.0, 1.0), float(3.2));
  const atmoSunDot = dot(geoNormal, uSunDir);
  const haloSunMask = smoothstep(float(-0.32), float(0.45), atmoSunDot);
  const haloTwilight = smoothstep(float(-0.28), float(0.02), atmoSunDot).mul(
    smoothstep(float(0.36), float(0.02), atmoSunDot),
  );
  const haloCol = mix(uAtmoDay, uAtmoTwilight, haloTwilight.mul(0.58));
  atmoMat.colorNode = haloCol.mul(haloFalloff).mul(haloSunMask).mul(1.15);
  atmoMat.opacityNode = clamp(haloFalloff.mul(haloSunMask).mul(0.95), 0.0, 1.0);

  const atmoMesh = new THREE.Mesh(atmoGeo, atmoMat);
  earthTilt.add(atmoMesh);

  // ---- 4. Deep-Space Multi-Spectral Starfield (1 InstancedMesh draw call) ----
  const rng = mulberry32(20261130);
  const starCount = 1400;
  const starGeo = new THREE.IcosahedronGeometry(0.068, 0);
  const starMat = new THREE.MeshBasicMaterial({ color: 0xffffff });
  const stars = new THREE.InstancedMesh(starGeo, starMat, starCount);
  const dummy = new THREE.Object3D();
  const starCol = new THREE.Color();
  // Realistic stellar color temperatures (O/B blue-white, A/F white, G pale gold, K warm amber)
  const starPalette = [0xcad8ff, 0xe8efff, 0xffffff, 0xfff4e0, 0xffd7a8, 0xa8c8ff];
  for (let i = 0; i < starCount; i++) {
    // Uniform spherical distribution on deep sky dome
    const u = rng();
    const v = rng();
    const theta = u * Math.PI * 2;
    const phi = Math.acos(2 * v - 1);
    const rad = 48 + rng() * 36;
    dummy.position.set(
      rad * Math.sin(phi) * Math.cos(theta),
      rad * Math.cos(phi),
      rad * Math.sin(phi) * Math.sin(theta),
    );
    // Power-law star size distribution: mostly crisp faint pinpoints, a few brighter stars
    const mag = Math.pow(rng(), 2.8);
    const s = 0.32 + mag * 1.45;
    dummy.scale.setScalar(s);
    dummy.updateMatrix();
    stars.setMatrixAt(i, dummy.matrix);

    starCol.setHex(starPalette[Math.floor(rng() * starPalette.length)]);
    starCol.multiplyScalar(0.38 + mag * 0.62);
    stars.setColorAt(i, starCol);
  }
  stars.instanceMatrix.needsUpdate = true;
  if (stars.instanceColor) stars.instanceColor.needsUpdate = true;
  scene.add(stars);

  // ---- 5. Subtle Off-Axis Solar Corona Glow ----
  const sunGlowGeo = new THREE.PlaneGeometry(18, 18);
  const sunGlowMat = new THREE.MeshBasicNodeMaterial({
    transparent: true,
    depthWrite: false,
    blending: THREE.AdditiveBlending,
  });
  const gUv = uv().sub(vec2(0.5, 0.5)).mul(2.0);
  const gDist = clamp(gUv.length(), 0.0, 1.0);
  const corona = pow(float(1.0).sub(gDist), float(5.5));
  sunGlowMat.colorNode = mix(uAtmoDay, vec3(1.0, 0.94, 0.84), pow(float(1.0).sub(gDist), float(2.0))).mul(corona).mul(0.55);
  sunGlowMat.opacityNode = corona.mul(0.45);
  const sunGlow = new THREE.Mesh(sunGlowGeo, sunGlowMat);
  sunGlow.position.copy(sunDirVec).multiplyScalar(42);
  sunGlow.lookAt(camera.position);
  scene.add(sunGlow);

  // ---- Live Omarchy Theme Sync ----
  globalThis.__wallpaper?.onThemeChange?.((next) => {
    targetHarmonics = computeThemeHarmonics(resolveTheme(next));
  });

  window.addEventListener("resize", () => {
    if (queryW !== null && queryH !== null) return;
    const w = Math.max(1, window.innerWidth);
    const h = Math.max(1, window.innerHeight);
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
    renderer.setSize(w, h, false);
  });

  // ---- Main Orbital Loop ----
  // Start longitude so golden Europe / Nile / Middle East city lights glow on the night hemisphere
  // while East Asia / Indian Ocean / Pacific catch dramatic sunlit clouds & ocean glint.
  const START_LON = -2.85;
  let frameCount = 0;
  let lastRenderWall = 0;
  let lastLogWall = performance.now();
  let lastLogFrames = 0;
  const simStart = performance.now();

  const animate = (now: number) => {
    requestAnimationFrame(animate);

    if (maxBrowserFps !== null && frameCount > 0) {
      const minInterval = 1000 / maxBrowserFps;
      if (now - lastRenderWall < minInterval - 0.5) {
        return;
      }
    }
    lastRenderWall = now;

    const t = fixedTime !== null ? fixedTime : (now - simStart) * 0.001;

    // Smoothly harmonize colors on Omarchy theme changes
    const k = 0.05;
    (scene.background as THREE.Color).lerp(targetHarmonics.spaceBg, k);
    uAtmoDay.value.lerp(targetHarmonics.atmoDay, k);
    uAtmoTwilight.value.lerp(targetHarmonics.atmoTwilight, k);
    cosmicAmbient.color.lerp(targetHarmonics.nightAmb, k);

    // Slow, dignified planetary rotation (~3.7 min per full revolution) + independent cloud drift
    earthMesh.rotation.y = START_LON + t * 0.028;
    cloudMesh.rotation.y = START_LON + t * 0.034;
    stars.rotation.y = t * 0.002;

    // Subtle, serene orbital camera breathing
    camera.position.x = Math.sin(t * 0.055) * 0.18;
    camera.position.y = 0.16 + Math.sin(t * 0.04) * 0.08;
    camera.position.z = 4.92 + Math.cos(t * 0.055) * 0.06;
    camera.lookAt(0, -0.02, 0);

    renderer.render(scene, camera);
    frameCount++;
    globalThis.__frameCount = frameCount;

    if (frameCount === 1) {
      const ttff = performance.now() - bootT0;
      globalThis.__ttffMs = ttff;
      console.log(`WALLPAPER_READY backend=${backendName} ttff_ms=${ttff.toFixed(1)} canvas=${canvas.width}x${canvas.height}`);
    } else if (now - lastLogWall >= 3000) {
      const fps = ((frameCount - lastLogFrames) * 1000) / (now - lastLogWall);
      console.log(`WALLPAPER_FPS fps=${fps.toFixed(1)} frames=${frameCount} canvas=${canvas.width}x${canvas.height} backend=${backendName}`);
      lastLogWall = now;
      lastLogFrames = frameCount;
    }
  };

  requestAnimationFrame(animate);
}

main().catch((err) => {
  console.error("earth wallpaper failed:", err);
});