Библиотека дизайна / Фоны

ФоныТёмный3DБесплатно

Протопланетный диск: из пыли слипаются планеты

Диск из 4096 обломков вращается под заголовком, гравитация на видеокарте слепляет их в планеты, каждые полминуты всё начинается заново.

Протопланетный диск: из пыли слипаются планеты
Промпт
Добавь на мою страницу фон «Протопланетный диск» (по мотивам официального примера three.js webgl_gpgpu_protoplanet, лицензия MIT). Ниже готовая страница одним файлом: three.js 0.170.0 и дополнение `GPUComputationRenderer` через importmap с jsdelivr, внешних картинок и моделей нет. Холст `<canvas class="bg">` закреплён на весь экран, заголовок `.hero` лежит поверх. Сначала перенеси как есть, открой через локальный сервер и проверь, что обломки слипаются в планеты, а камера реагирует на мышь, потом подгоняй.

Как устроен код. Симуляция: `GPUComputationRenderer` хранит две текстуры `WIDTH × WIDTH` (64, то есть 4096 частиц): в `texturePosition` координаты, в `textureVelocity` скорость и масса (канал w). Шейдер скорости в двойном цикле проходит по всем частицам: суммирует притяжение `GRAVITY · m / r²` (с потолком 1000, чтобы близкие пары не разлетались), а если два тела касаются (радиус считается из массы и `DENSITY`), то тело с меньшим номером забирает массу и импульс другого, а второе получает массу 0 и пропадает. Шейдер позиции просто прибавляет скорость. Шаг времени `SIM_SPEED / 60`: при 1 всё слипается за несколько секунд, 0.35 растягивает рост на полминуты. Стартовый диск (`fillTextures`) — случайные точки в круге `DISC_RADIUS` толщиной `DISC_HEIGHT`, каждой сразу дана орбитальная скорость. Отрисовка: `THREE.Points`, у каждой точки uv указывает на её тексель; вершинный шейдер берёт позицию и массу из текстур, размер точки — радиус тела в пикселях (`cameraConstant` учитывает высоту окна и `devicePixelRatio`), фрагментный рисует шарик с освещением сверху слева и красит его от `COLOR_DUST` к `COLOR_PLANET` по массе. Свечение в центре — спрайт с радиальным градиентом, в физике не участвует. Каждые `RESTART_EVERY` секунд `restart()` заливает новый диск, а uniform `fade` гасит картинку за полторы секунды до и после.

Что менять: число частиц `WIDTH` (64 — 4096 тел; 48 — 2304, в 3 раза легче для слабых телефонов; больше 64 не ставь, цикл растёт квадратично), силу тяготения `GRAVITY`, плотность `DENSITY` (меньше — тела крупнее и чаще сталкиваются), размер и толщину диска, скорость вращения `ORBIT_VELOCITY` (меньше — диск схлопывается к центру), темп `SIM_SPEED` и период `RESTART_EVERY`, цвета `COLOR_DUST`, `COLOR_PLANET`, свечения (градиент `grad`) и фона `BACKGROUND` (продублируй в `background` у `body`), облёт `ORBIT_SPEED` и параллакс `PARALLAX`, высоту камеры (170) и точку взгляда (`lookAt`).

Если проект на React: холст в компоненте, инициализацию в `useEffect` с пустым списком зависимостей и `ref` на холст. При размонтировании вызови `renderer.setAnimationLoop(null)`, `gpu.dispose()`, `geometry.dispose()`, `material.dispose()`, `renderer.dispose()` и сними слушатели `pointermove` и `resize`. Не убирай `points.frustumCulled = false` (позиции берутся из текстуры, и three.js иначе может решить, что точки вне кадра), проверку `mass == 0.0` в обоих шейдерах (поглощённые тела должны пропадать), ограничение `devicePixelRatio` двойкой и ветку `prefers-reduced-motion`, которая считает физику раз в четыре кадра и замедляет облёт.
Покажи, как поставить этот диск под первый экран моего сайта, и подбери цвета пыли, планет и свечения под мой бренд.

Код скопируется вместе с промптом

Тёмный экран, под заголовком вращается диск из четырёх тысяч раскалённых обломков вокруг тёплого свечения. Каждый обломок притягивает все остальные: соседи сближаются, слипаются, и на глазах вместо пыли вырастают светлые шары-протопланеты, мелкие оранжевые, крупные почти белые. Через полминуты от диска остаётся горстка планет, экран плавно гаснет, и всё начинается с новой пыли. Камера сама облетает диск, мышь наклоняет и поворачивает взгляд. Это официальный пример three.js webgl_gpgpu_protoplanet: честная задача N тел (каждый с каждым, 16 млн пар за кадр) считается на видеокарте через GPUComputationRenderer, координаты и скорости лежат в текстурах 64×64, а масса — в четвёртом канале скорости. В стенде убраны панель настроек и OrbitControls, вместо них автооблёт, параллакс и перезапуск по таймеру; плоские диски заменены шариками с объёмным светом, симуляция замедлена, чтобы рост планет было видно. Подойдёт для научных и образовательных проектов, астрономии, игр, AI-сервисов и любых тёмных лендингов про «рост из малого».

Код
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Protoplanet disc</title>
<link rel="icon" href="data:,">
<script type="importmap">{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
} }</script>
<style>
  *, *::before, *::after { box-sizing: border-box; }
  html, body { height: 100%; margin: 0; overflow: hidden; background: #07060c; color: #fff;
               font-family: system-ui, -apple-system, "Segoe UI", sans-serif; }
  .bg { position: fixed; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; }
  .hero { position: relative; z-index: 1; min-height: 100%; display: grid; place-content: start center; gap: 1rem;
          padding: 12vh 1.5rem 1.5rem; text-align: center; pointer-events: none; }
  .hero h1 { margin: 0; font-size: clamp(2.2rem, 7vw, 5.5rem); font-weight: 700; letter-spacing: -0.03em; line-height: 1;
             text-shadow: 0 2px 30px rgba(0, 0, 0, 0.7); }
  .hero p { margin: 0; font-size: clamp(1rem, 2vw, 1.35rem); opacity: 0.65; }
</style>
</head>
<body>
<canvas class="bg" aria-hidden="true"></canvas>
<main class="hero">
  <h1>Из пыли — планеты</h1>
  <p>Четыре тысячи обломков и одна гравитация</p>
</main>

<script type="module">
// По мотивам примера three.js webgl_gpgpu_protoplanet
// Copyright © 2010–2026 three.js authors, MIT License
// https://github.com/mrdoob/three.js/blob/dev/examples/webgl_gpgpu_protoplanet.html
import * as THREE from 'three';
import { GPUComputationRenderer } from 'three/addons/misc/GPUComputationRenderer.js';

// settings
const WIDTH = 64;                 // simulation texture side: WIDTH² debris particles (64 → 4096)
const GRAVITY = 100;              // gravity constant
const DENSITY = 0.45;             // lower → bigger bodies for the same mass
const DISC_RADIUS = 300;          // initial disc radius
const DISC_HEIGHT = 8;            // initial disc thickness
const MAX_MASS = 15;              // max mass of one debris particle (scaled by count)
const ORBIT_VELOCITY = 70;        // initial orbital speed at the edge
const SIM_SPEED = 0.35;           // simulation time per frame (1 = original 1/60 s)
const RESTART_EVERY = 32;         // seconds until a fresh dust disc is spawned
const COLOR_DUST = '#ea580c';     // small debris
const COLOR_PLANET = '#fff3c4';   // grown protoplanets
const BACKGROUND = 0x07060c;
const ORBIT_SPEED = 0.05;         // camera auto-orbit, rad per second
const PARALLAX = 0.4;             // how strongly the camera follows the pointer

const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const PARTICLES = WIDTH * WIDTH;

const canvas = document.querySelector('.bg');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight, false);

const scene = new THREE.Scene();
scene.background = new THREE.Color(BACKGROUND);
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 5, 15000);

const common = /* glsl */`
  #include <common>
  uniform float density;
  float radiusFromMass(float mass) { return pow((3.0 / (4.0 * PI)) * mass / density, 1.0 / 3.0); }
`;

// position step: pos += vel * dt
const positionShader = /* glsl */`
  uniform float delta;
  void main() {
    vec2 uv = gl_FragCoord.xy / resolution.xy;
    vec3 pos = texture2D(texturePosition, uv).xyz;
    vec4 tmpVel = texture2D(textureVelocity, uv);
    vec3 vel = tmpVel.w == 0.0 ? vec3(0.0) : tmpVel.xyz;
    gl_FragColor = vec4(pos + vel * delta, 1.0);
  }
`;

// velocity step: every particle feels every other one (N²); touching bodies merge, mass is kept in .w
const velocityShader = common + /* glsl */`
  uniform float delta;
  uniform float gravityConstant;
  const float width = resolution.x;
  const float height = resolution.y;
  void main() {
    vec2 uv = gl_FragCoord.xy / resolution.xy;
    float id = uv.y * resolution.x + uv.x;
    vec3 pos = texture2D(texturePosition, uv).xyz;
    vec4 tmpVel = texture2D(textureVelocity, uv);
    vec3 vel = tmpVel.xyz;
    float mass = tmpVel.w;
    if (mass > 0.0) {
      float radius = radiusFromMass(mass);
      vec3 acceleration = vec3(0.0);
      for (float y = 0.0; y < height; y++) {
        for (float x = 0.0; x < width; x++) {
          vec2 uv2 = vec2(x + 0.5, y + 0.5) / resolution.xy;
          vec3 pos2 = texture2D(texturePosition, uv2).xyz;
          vec4 velTemp2 = texture2D(textureVelocity, uv2);
          float mass2 = velTemp2.w;
          float id2 = uv2.y * resolution.x + uv2.x;
          if (id == id2 || mass2 == 0.0) continue;
          vec3 dPos = pos2 - pos;
          float dist = length(dPos);
          if (dist == 0.0) continue;
          float radius2 = radiusFromMass(mass2);
          if (dist < radius + radius2) {
            if (id < id2) {          // this body swallows the other one
              vel = (vel * mass + velTemp2.xyz * mass2) / (mass + mass2);
              mass += mass2;
              radius = radiusFromMass(mass);
            } else {                 // this body is swallowed
              mass = 0.0; vel = vec3(0.0);
              break;
            }
          }
          float field = min(gravityConstant * mass2 / (dist * dist), 1000.0);
          acceleration += field * normalize(dPos);
        }
        if (mass == 0.0) break;
      }
      vel += delta * acceleration;
    }
    gl_FragColor = vec4(vel, mass);
  }
`;

const gpu = new GPUComputationRenderer(WIDTH, WIDTH, renderer);
const dtPosition = gpu.createTexture();
const dtVelocity = gpu.createTexture();
fillTextures(dtPosition, dtVelocity);
const velocityVar = gpu.addVariable('textureVelocity', velocityShader, dtVelocity);
const positionVar = gpu.addVariable('texturePosition', positionShader, dtPosition);
gpu.setVariableDependencies(velocityVar, [positionVar, velocityVar]);
gpu.setVariableDependencies(positionVar, [positionVar, velocityVar]);
velocityVar.material.uniforms.gravityConstant = { value: GRAVITY };
velocityVar.material.uniforms.density = { value: DENSITY };
velocityVar.material.uniforms.delta = { value: SIM_SPEED / 60 };
positionVar.material.uniforms.delta = { value: SIM_SPEED / 60 };
const gpuError = gpu.init();
if (gpuError !== null) console.error(gpuError);

// random dust in a thin disc, every particle already on a circular-ish orbit
function fillTextures(texPos, texVel) {
  const p = texPos.image.data, v = texVel.image.data;
  const maxMass = MAX_MASS * 1024 / PARTICLES;
  for (let k = 0; k < p.length; k += 4) {
    let x, z, rr;
    do { x = Math.random() * 2 - 1; z = Math.random() * 2 - 1; rr = x * x + z * z; } while (rr > 1);
    rr = Math.sqrt(rr);
    const r = DISC_RADIUS * Math.pow(rr, 0.4);
    const vel = ORBIT_VELOCITY * Math.pow(rr, 0.2);
    p[k] = x * r; p[k + 1] = (Math.random() * 2 - 1) * DISC_HEIGHT; p[k + 2] = z * r; p[k + 3] = 1;
    v[k] = vel * z; v[k + 1] = 0; v[k + 2] = -vel * x; v[k + 3] = Math.random() * maxMass + 1;
  }
}
function restart() {
  const tp = gpu.createTexture(), tv = gpu.createTexture();
  fillTextures(tp, tv);
  for (const i of [0, 1]) {
    gpu.renderTexture(tp, positionVar.renderTargets[i]);
    gpu.renderTexture(tv, velocityVar.renderTargets[i]);
  }
  tp.dispose(); tv.dispose();
}

// one point per texel; size and colour come from the mass
const geometry = new THREE.BufferGeometry();
const uvs = new Float32Array(PARTICLES * 2);
for (let j = 0, p = 0; j < WIDTH; j++) for (let i = 0; i < WIDTH; i++) { uvs[p++] = i / (WIDTH - 1); uvs[p++] = j / (WIDTH - 1); }
geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(PARTICLES * 3), 3));
geometry.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));

const uniforms = {
  texturePosition: { value: null }, textureVelocity: { value: null },
  cameraConstant: { value: 1 }, density: { value: DENSITY }, fade: { value: 0 },
  colorDust: { value: new THREE.Color(COLOR_DUST) }, colorPlanet: { value: new THREE.Color(COLOR_PLANET) },
};
const material = new THREE.ShaderMaterial({
  uniforms,
  vertexShader: common + /* glsl */`
    uniform sampler2D texturePosition, textureVelocity;
    uniform float cameraConstant;
    varying float vMass;
    void main() {
      vec3 pos = texture2D(texturePosition, uv).xyz;
      vMass = texture2D(textureVelocity, uv).w;
      vec4 mv = modelViewMatrix * vec4(pos, 1.0);
      gl_PointSize = vMass == 0.0 ? 0.0 : max(radiusFromMass(vMass) * cameraConstant / -mv.z, 2.0);
      gl_Position = projectionMatrix * mv;
    }`,
  fragmentShader: /* glsl */`
    uniform vec3 colorDust, colorPlanet;
    uniform float fade;
    varying float vMass;
    void main() {
      if (vMass == 0.0) discard;
      vec2 c = gl_PointCoord - 0.5;
      float r = length(c) * 2.0;
      if (r > 1.0) discard;
      // fake sphere lighting: lit from the upper left, dark limb
      float z = sqrt(1.0 - r * r);
      float light = 0.35 + 0.65 * max(dot(vec3(c.x * 2.0, -c.y * 2.0, z), normalize(vec3(-0.5, 0.6, 0.7))), 0.0);
      vec3 col = mix(colorDust, colorPlanet, smoothstep(1.0, 60.0, vMass)) * light;
      gl_FragColor = vec4(col * fade, 1.0);
    }`,
});
const points = new THREE.Points(geometry, material);
points.frustumCulled = false;
scene.add(points);

// soft glow in the middle of the disc (decor only, not part of the physics)
const glowCanvas = document.createElement('canvas');
glowCanvas.width = glowCanvas.height = 128;
const g = glowCanvas.getContext('2d');
const grad = g.createRadialGradient(64, 64, 0, 64, 64, 64);
grad.addColorStop(0, 'rgba(255,214,150,0.55)'); grad.addColorStop(0.35, 'rgba(234,88,12,0.18)'); grad.addColorStop(1, 'rgba(0,0,0,0)');
g.fillStyle = grad; g.fillRect(0, 0, 128, 128);
const glow = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(glowCanvas), blending: THREE.AdditiveBlending, depthWrite: false }));
glow.scale.setScalar(420);
scene.add(glow);

// pointer → camera parallax
const pointer = { x: 0, y: 0 }, eased = { x: 0, y: 0 };
addEventListener('pointermove', (e) => {
  if (!e.isPrimary) return;
  pointer.x = e.clientX / innerWidth * 2 - 1;
  pointer.y = e.clientY / innerHeight * 2 - 1;
}, { passive: true });

function fit() {
  camera.aspect = innerWidth / innerHeight;
  camera.fov = camera.aspect < 1 ? 60 / Math.max(camera.aspect, 0.5) * 0.7 : 60; // portrait: wider lens
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight, false);
  uniforms.cameraConstant.value = innerHeight * renderer.getPixelRatio() / Math.tan(THREE.MathUtils.DEG2RAD * 0.5 * camera.fov);
}
fit();
addEventListener('resize', fit);

const clock = new THREE.Clock();
let orbit = 0.6, age = 0, frame = 0;
renderer.setAnimationLoop(() => {
  const dt = Math.min(clock.getDelta(), 0.1);
  age += dt;
  if (age > RESTART_EVERY) { restart(); age = 0; }
  // fade in after a restart and out right before the next one
  uniforms.fade.value = Math.min(age / 1.5, 1, (RESTART_EVERY - age) / 1.5);
  // reduced motion: simulate every 4th frame and orbit slower
  if (!reduceMotion || frame++ % 4 === 0) gpu.compute();
  uniforms.texturePosition.value = gpu.getCurrentRenderTarget(positionVar).texture;
  uniforms.textureVelocity.value = gpu.getCurrentRenderTarget(velocityVar).texture;

  orbit += dt * ORBIT_SPEED * (reduceMotion ? 0.25 : 1);
  eased.x += (pointer.x - eased.x) * 0.04;
  eased.y += (pointer.y - eased.y) * 0.04;
  const a = orbit + eased.x * PARALLAX;
  const h = 170 + eased.y * 120;
  camera.position.set(Math.sin(a) * 430, h, Math.cos(a) * 430);
  camera.lookAt(0, 60, 0); // aim above the centre so the disc sits under the headline
  renderer.render(scene, camera);
});
</script>
</body>
</html>

Похожие