Светлое небо и тысяча маленьких птиц, которые машут крыльями и кружат одной стаей: то растягиваются лентой, то сжимаются в плотный ком, то разлетаются. Ближние птицы тёмные и крупные, дальние светлеют и растворяются в небе. Курсор работает как хищник: стоит провести мышью, и птицы рядом с ним шарахаются в стороны, а потом снова собираются. Это официальный пример three.js webgl_gpgpu_birds: поведение стаи (разделение, выравнивание, сближение — классические «боиды» Крейга Рейнольдса) считается на видеокарте через GPUComputationRenderer, каждая птица — три треугольника, которые вершинный шейдер разворачивает по направлению полёта. В стенде убраны панель настроек и счётчик кадров, птицы покрашены в двухцветную палитру «чернила и небо», добавлены поддержка касания и замедление при prefers-reduced-motion. Подойдёт как фон первого экрана для студии, некоммерческого проекта, сервиса про командную работу, природу или путешествия.
Стая из тысячи птиц, которая облетает курсор
1024 птицы машут крыльями и кружат стаей по правилам боидов, а курсор пугает их, как хищник: стая расступается.

Промпт
Добавь на мою страницу фон «Стая из тысячи птиц, которая облетает курсор» (по мотивам официального примера three.js `webgl_gpgpu_birds`, MIT, https://github.com/mrdoob/three.js/blob/dev/examples/webgl_gpgpu_birds.html). Ниже готовая страница одним файлом: three.js 0.170.0 и дополнение `GPUComputationRenderer` через importmap с jsdelivr, шейдеры лежат в тегах `<script type="x-shader/...">`. Картинок и моделей нет. Сначала перенеси её как есть, открой через локальный сервер и проверь, что стая летает и расступается вокруг курсора, и только потом подгоняй. Как устроен код. Птиц `WIDTH × WIDTH` (32 × 32 = 1024). Две текстуры-«переменные» `GPUComputationRenderer`: `texturePosition` (xyz и фаза взмаха в w) и `textureVelocity`. Шейдер `velocityShader` для каждой птицы обходит всех остальных и по расстоянию решает, отталкиваться (`separationDistance`), лететь в ту же сторону (`alignmentDistance`) или сближаться (`cohesionDistance`), плюс тянет стаю к центру и уводит от точки `predator` в радиусе 150. Шейдер `positionShader` сдвигает птицу на скорость и крутит фазу взмаха. Геометрия `birdGeometry()` — по 3 треугольника на птицу и атрибут `reference` (адрес птицы в текстуре). Вершинный шейдер `birdVS` машет концами крыльев (`sin(phase)`) и поворачивает птицу по скорости, фрагментный `birdFS` смешивает `inkColor` и `skyColor` по глубине. Курсор: `pointermove` на один кадр ставит хищника в точку курсора, затем он уводится за край (`10000`). Что менять: цвета `SKY` (фон и дальние птицы) и `INK` (ближние птицы), характер стаи — `FLOCK.separation`, `alignment`, `cohesion` (0–100; больше сближение — плотнее ком, больше разделение — реже стая), скорость `SPEED_LIMIT` и радиус испуга `preyRadius` в `velocityShader`, размер птиц (`g.scale(0.2, …)`) и размах крыльев (`wing`). Число птиц задаёт `WIDTH`, но стоимость растёт как квадрат: 32 — хороший предел для телефонов, 64 (4096 птиц) только для мощных компьютеров. Для тёмной версии поставь `SKY` тёмным, `INK` светлым. Если проект на React или React Three Fiber: перенеси код в `useEffect` с пустым списком зависимостей, канвас бери через `ref`, шейдеры держи строками в модуле вместо тегов `<script>`. При размонтировании вызови `renderer.setAnimationLoop(null)`, `gpu.dispose()`, `birds.geometry.dispose()`, `birds.material.dispose()`, `renderer.dispose()` и сними `pointermove` и `resize`. В R3F вызывай `gpu.compute()` в `useFrame`. Не трогай `RepeatWrapping` у переменных, `frustumCulled = false` у сетки птиц (иначе стая будет пропадать у краёв), порядок вершин в `shape` (по номерам 4 и 7 шейдер узнаёт концы крыльев) и `touch-action: none` на канвасе, если хочешь, чтобы стая пугалась пальца. Ветка `prefers-reduced-motion` замедляет время в 3 раза: оставь её. Покажи, где на моём сайте этот фон смотрится лучше всего, и подбери цвета под мой бренд.
Код скопируется вместе с промптом
Код
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GPGPU Birds Flock</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>
html, body { margin: 0; height: 100%; background: #f3efe8; overflow: hidden; }
canvas.birds { position: fixed; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; }
</style>
</head>
<body>
<canvas class="birds"></canvas>
<!-- Position step: move each bird by its velocity, advance the wing-flap phase (w) -->
<script type="x-shader/x-fragment" id="positionShader">
uniform float delta;
void main() {
vec2 uv = gl_FragCoord.xy / resolution.xy;
vec4 tmpPos = texture2D(texturePosition, uv);
vec3 velocity = texture2D(textureVelocity, uv).xyz;
float phase = mod(tmpPos.w + delta + length(velocity.xz) * delta * 3.0 + max(velocity.y, 0.0) * delta * 6.0, 62.83);
gl_FragColor = vec4(tmpPos.xyz + velocity * delta * 15.0, phase);
}
</script>
<!-- Velocity step: flee the pointer, pull to the centre, then separation / alignment / cohesion with every other bird -->
<script type="x-shader/x-fragment" id="velocityShader">
uniform float delta, separationDistance, alignmentDistance, cohesionDistance;
uniform vec3 predator;
const float width = resolution.x;
const float height = resolution.y;
const float PI_2 = 6.283185307179586;
const float UPPER_BOUNDS = BOUNDS;
const float SPEED_LIMIT = 9.0;
void main() {
float zoneRadius = separationDistance + alignmentDistance + cohesionDistance;
float separationThresh = separationDistance / zoneRadius;
float alignmentThresh = (separationDistance + alignmentDistance) / zoneRadius;
float zoneRadiusSquared = zoneRadius * zoneRadius;
vec2 uv = gl_FragCoord.xy / resolution.xy;
vec3 selfPosition = texture2D(texturePosition, uv).xyz;
vec3 velocity = texture2D(textureVelocity, uv).xyz;
float limit = SPEED_LIMIT;
float f, percent;
vec3 dir = predator * UPPER_BOUNDS - selfPosition;
dir.z = 0.0;
float dist = length(dir);
float preyRadius = 150.0;
if (dist < preyRadius) {
f = (dist * dist / (preyRadius * preyRadius) - 1.0) * delta * 100.0;
velocity += normalize(dir) * f;
limit += 5.0;
}
dir = selfPosition;
dir.y *= 2.5;
velocity -= normalize(dir) * delta * 5.0;
for (float y = 0.0; y < height; y++) {
for (float x = 0.0; x < width; x++) {
vec2 ref = vec2(x + 0.5, y + 0.5) / resolution.xy;
vec3 birdPosition = texture2D(texturePosition, ref).xyz;
dir = birdPosition - selfPosition;
dist = length(dir);
if (dist < 0.0001) continue;
float distSquared = dist * dist;
if (distSquared > zoneRadiusSquared) continue;
percent = distSquared / zoneRadiusSquared;
if (percent < separationThresh) {
f = (separationThresh / percent - 1.0) * delta;
velocity -= normalize(dir) * f;
} else if (percent < alignmentThresh) {
float adjusted = (percent - separationThresh) / (alignmentThresh - separationThresh);
vec3 birdVelocity = texture2D(textureVelocity, ref).xyz;
f = (0.5 - cos(adjusted * PI_2) * 0.5 + 0.5) * delta;
velocity += normalize(birdVelocity) * f;
} else {
float threshDelta = 1.0 - alignmentThresh;
float adjusted = threshDelta == 0.0 ? 1.0 : (percent - alignmentThresh) / threshDelta;
f = (0.5 - (cos(adjusted * PI_2) * -0.5 + 0.5)) * delta;
velocity += normalize(dir) * f;
}
}
}
if (length(velocity) > limit) velocity = normalize(velocity) * limit;
gl_FragColor = vec4(velocity, 1.0);
}
</script>
<!-- Bird drawing: flap the wing tips, turn the bird along its velocity -->
<script type="x-shader/x-vertex" id="birdVS">
attribute vec2 reference;
attribute float birdVertex;
attribute vec3 birdColor;
uniform sampler2D texturePosition, textureVelocity;
varying vec3 vColor;
varying float z;
void main() {
vec4 tmpPos = texture2D(texturePosition, reference);
vec3 velocity = normalize(texture2D(textureVelocity, reference).xyz);
vec3 newPosition = position;
if (birdVertex == 4.0 || birdVertex == 7.0) newPosition.y = sin(tmpPos.w) * 5.0;
newPosition = mat3(modelMatrix) * newPosition;
velocity.z *= -1.0;
float xz = length(velocity.xz);
float x = sqrt(1.0 - velocity.y * velocity.y);
float cosry = velocity.x / xz, sinry = velocity.z / xz;
mat3 maty = mat3(cosry, 0, -sinry, 0, 1, 0, sinry, 0, cosry);
mat3 matz = mat3(x, velocity.y, 0, -velocity.y, x, 0, 0, 0, 1);
newPosition = maty * matz * newPosition + tmpPos.xyz;
z = newPosition.z;
vColor = birdColor;
gl_Position = projectionMatrix * viewMatrix * vec4(newPosition, 1.0);
}
</script>
<script type="x-shader/x-fragment" id="birdFS">
uniform vec3 inkColor, skyColor;
varying vec3 vColor;
varying float z;
void main() {
// Near birds are dark ink, far birds fade into the sky
float depth = 0.2 + (1000.0 - z) / 1000.0 * vColor.x;
gl_FragColor = vec4(mix(inkColor, skyColor, clamp(depth - 0.35, 0.0, 1.0)), 1.0);
}
</script>
<script type="module">
// Based on the three.js example webgl_gpgpu_birds, Copyright © 2010–2026 three.js authors, MIT
// https://github.com/mrdoob/three.js/blob/dev/examples/webgl_gpgpu_birds.html
import * as THREE from 'three';
import { GPUComputationRenderer } from 'three/addons/misc/GPUComputationRenderer.js';
const WIDTH = 32; // 32 × 32 = 1024 birds (cost grows as the square)
const BIRDS = WIDTH * WIDTH;
const BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
const FLOCK = { separation: 20, alignment: 20, cohesion: 20 };
const SKY = 0xf3efe8, INK = 0x1d2433;
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const TIME_SCALE = reduceMotion ? 0.35 : 1;
const shader = (id) => document.getElementById(id).textContent;
// Each bird is 3 triangles: body and two wings; reference = the bird's texel in the simulation textures
function birdGeometry() {
const points = BIRDS * 9;
const vertices = new Float32Array(points * 3), colors = new Float32Array(points * 3);
const references = new Float32Array(points * 2), birdVertex = new Float32Array(points);
const wing = 20;
const shape = [0, 0, -20, 0, 4, -20, 0, 0, 30, 0, 0, -15, -wing, 0, 0, 0, 0, 15, 0, 0, 15, wing, 0, 0, 0, 0, -15];
const c = new THREE.Color();
for (let v = 0; v < points; v++) {
const bird = Math.floor(v / 9);
for (let k = 0; k < 3; k++) vertices[v * 3 + k] = shape[(v % 9) * 3 + k];
c.set(0x666666 + Math.floor(v / 9) / BIRDS * 0x666666);
colors.set([c.r, c.g, c.b], v * 3);
references[v * 2] = (bird % WIDTH) / WIDTH;
references[v * 2 + 1] = Math.floor(bird / WIDTH) / WIDTH;
birdVertex[v] = v % 9;
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
g.setAttribute('birdColor', new THREE.BufferAttribute(colors, 3));
g.setAttribute('reference', new THREE.BufferAttribute(references, 2));
g.setAttribute('birdVertex', new THREE.BufferAttribute(birdVertex, 1));
g.scale(0.2, 0.2, 0.2);
return g;
}
const canvas = document.querySelector('canvas.birds');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
const camera = new THREE.PerspectiveCamera(75, innerWidth / innerHeight, 1, 3000);
camera.position.z = 350;
const scene = new THREE.Scene();
scene.background = new THREE.Color(SKY);
// GPU simulation: two float textures, positions (xyz + flap phase) and velocities
const gpu = new GPUComputationRenderer(WIDTH, WIDTH, renderer);
const pos0 = gpu.createTexture(), vel0 = gpu.createTexture();
for (let k = 0; k < pos0.image.data.length; k += 4) {
pos0.image.data.set([Math.random() * BOUNDS - BOUNDS_HALF, Math.random() * BOUNDS - BOUNDS_HALF, Math.random() * BOUNDS - BOUNDS_HALF, 1], k);
vel0.image.data.set([(Math.random() - 0.5) * 10, (Math.random() - 0.5) * 10, (Math.random() - 0.5) * 10, 1], k);
}
const velocityVar = gpu.addVariable('textureVelocity', shader('velocityShader'), vel0);
const positionVar = gpu.addVariable('texturePosition', shader('positionShader'), pos0);
gpu.setVariableDependencies(velocityVar, [positionVar, velocityVar]);
gpu.setVariableDependencies(positionVar, [positionVar, velocityVar]);
const posU = positionVar.material.uniforms, velU = velocityVar.material.uniforms;
posU.delta = { value: 0 };
velU.delta = { value: 0 };
velU.separationDistance = { value: FLOCK.separation };
velU.alignmentDistance = { value: FLOCK.alignment };
velU.cohesionDistance = { value: FLOCK.cohesion };
velU.predator = { value: new THREE.Vector3() };
velocityVar.material.defines.BOUNDS = BOUNDS.toFixed(2);
for (const v of [velocityVar, positionVar]) v.wrapS = v.wrapT = THREE.RepeatWrapping;
const err = gpu.init();
if (err !== null) console.error(err);
const birdUniforms = {
texturePosition: { value: null }, textureVelocity: { value: null },
inkColor: { value: new THREE.Color(INK) }, skyColor: { value: new THREE.Color(SKY) }
};
const birds = new THREE.Mesh(birdGeometry(), new THREE.ShaderMaterial({
uniforms: birdUniforms, vertexShader: shader('birdVS'), fragmentShader: shader('birdFS'), side: THREE.DoubleSide
}));
birds.rotation.y = Math.PI / 2;
birds.matrixAutoUpdate = false;
birds.updateMatrix();
birds.frustumCulled = false; // vertices are moved in the shader, the bounding sphere is meaningless
scene.add(birds);
// Pointer acts as a predator for one frame per move: the flock splits around it
let mouseX = 10000, mouseY = 10000;
canvas.addEventListener('pointermove', (e) => {
if (!e.isPrimary) return;
mouseX = e.clientX - innerWidth / 2;
mouseY = e.clientY - innerHeight / 2;
});
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
let last = performance.now();
renderer.setAnimationLoop(() => {
const now = performance.now();
const delta = Math.min((now - last) / 1000, 1) * TIME_SCALE;
last = now;
posU.delta.value = velU.delta.value = delta;
velU.predator.value.set(0.5 * mouseX / (innerWidth / 2), -0.5 * mouseY / (innerHeight / 2), 0);
mouseX = mouseY = 10000;
gpu.compute();
birdUniforms.texturePosition.value = gpu.getCurrentRenderTarget(positionVar).texture;
birdUniforms.textureVelocity.value = gpu.getCurrentRenderTarget(velocityVar).texture;
renderer.render(scene, camera);
});
</script>
</body>
</html>Похожие


Протопланетный диск: из пыли слипаются планеты
Three.js · Шейдер

Живое небо: солнце садится и встаёт за заголовком
Three.js · Шейдер

Полёт по неоновому тоннелю-узлу
Three.js · Шейдер