Atlaslog
Atlaslog / Examples / deck.gl / Business scenarios / Generative Particles
deck.gl · Business scenario

Generative Particles

40,000 particles switch between a vortex field and a radial diffusion field; color mixes instantaneous speed with intrinsic phase, and a strength slider changes acceleration in real time.

Open standalone → Chinese notes All business examples
/demos/deckgl-nongis-generative-particles.htmlLIVE
single HTML file · CDN dependencies onlyinterface labels are in Chinese

Business context

Generative particles are common in exhibitions, stage backdrops and brand visuals. The users are creative technologists, installation artists and design teams working on real-time visuals, and the goal is motion that holds up rather than data communication. Data is a procedurally generated initial state and force-field parameters with no external source, sized to about 40,000 by device capability; the same parameters and fixed step must reproduce the same motion, or recorded footage and the live piece will diverge.

There is no coordinate system to respect here, so the preparation before deck.gl is to write the force fields, damping and boundary as fixed constants and pin the time step to 1/60 so the integration does not depend on machine frame rate; when the particle count exceeds budget, particles are decimated proportionally rather than by shrinking point size. three.js is freer but requires manual buffer and camera management, and OrbitView with attribute recomputation is enough for per-frame coordinate changes at far lower cost.

Motion speed is unrelated to real time: the step is fixed while render frame rate floats, so a slower machine advances less phase over the same interval. Color mixes speed with intrinsic phase, so an identical color patch does not mean identical speed. The boundary reflects at a radius, so particles look blocked by a wall when they are actually under a spherical constraint, and the pile-up near the edge is an artifact of the algorithm.

How it works

Initial positions fill a ±75×±75×±55 box and initial velocity is tangential, (-0.25y, 0.25x), giving a natural spin. Each frame integrates at a fixed 1/60 s: the vortex field sets acceleration to (-y/r, x/r)·48·s plus a centripetal term (-x/r, -y/r)·12·s and a sine perturbation along z; the diffusion field points acceleration radially outward at the same 48·s magnitude and adds 10·s·sin(1.5t+φ) on z. Velocity is damped by 0.986 each frame, and out-of-bounds particles are pulled back at radius 250 with velocity reversed and scaled by -0.45 so they do not leave the frame.

The [x,y,z] array is allocated once and rewritten in place every frame, with the frame number in updateTriggers making getPosition and getFillColor recompute; color normalizes speed by 55 with a 68% weight and intrinsic phase with 32%, looked up in a 32-step ramp, so a cluster of particles never reads as a flat block of color. Exposing field strength and step as constants means the same parameter set over the same frame count reproduces the same trajectory, and screen recording needs no dependence on machine frame rate. Beyond 50,000 particles, 150,000 floats of position plus color are re-uploaded each frame, and attribute upload saturates mainstream integrated GPUs first; decimate 2:1 or even 4:1 rather than shrinking point size.

SettingEffect
STEP = 1/60Fixed step so the same parameter sequence reproduces the same motion
48 × strengthAcceleration magnitude of both fields, scaled directly by the 0.2–3 slider
velocity damping 0.986Caps terminal speed, reached in about 1.1 s
R = 250 reflective boundaryOut-of-bounds particles pulled back at the radius with velocity × -0.45

Note. Expose field strength, damping and boundary radius as parameters and fix the step; only then does one parameter set reproduce the same motion.

Source

demos/deckgl-nongis-generative-particles.html
<!--
  示例:生成式粒子
  要点:4 万粒子逐帧在两个力场里积分,位置数组原地改写,颜色由速度与相位共同决定
  依赖:deck.gl 9.0 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>生成式粒子</title>
<style>
  html,body{height:100%;margin:0;background:#0d1117}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#e6e8ec}
  .bar{position:relative;z-index:5;flex:0 0 auto;padding:8px 12px;background:#161b22;border-bottom:1px solid #252c36;
       display:flex;gap:14px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600}
  .bar label{display:flex;align-items:center;gap:5px;cursor:pointer}
  .bar input[type=checkbox]{accent-color:#4f9ef8}
  .bar input[type=range]{width:150px;accent-color:#4f9ef8}
  .bar button{font:inherit;font-size:12px;padding:3px 10px;border-radius:4px;cursor:pointer;
       border:1px solid #2f3947;background:#1d242e;color:#c9d3e0}
  .bar button:hover{background:#26303d}
  .bar button.on{background:#2c4a7a;border-color:#4f8ad6;color:#dfe9ff}
  .bar .sep{width:1px;height:18px;background:#2a313c;margin:0 4px}
  #cv{flex:1 1 auto;min-height:0;width:100%;display:block}
</style>
</head>
<body>
<div class="bar">
  <span>粒子 40,000 · 边界半径 250</span>
  <span class="sep"></span>
  <button data-m="swirl" class="on">漩涡</button>
  <button data-m="diffuse">扩散</button>
  <label>强度 <b id="s">1.0</b> <input id="str" type="range" min="0.2" max="3" step="0.1" value="1"></label>
</div>
<canvas id="cv"></canvas>
<script src="https://cdn.jsdelivr.net/npm/deck.gl@9.0.35/dist.min.js"></script>
<script>
(function () {
  'use strict';

  if (typeof deck === 'undefined') {
    document.body.innerHTML =
      '<div style="padding:24px;color:#ff8c74">deck.gl 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  function rng(seed) {
    var a = seed >>> 0;
    return function () {
      a = (a + 0x6D2B79F5) >>> 0;
      var t = Math.imul(a ^ (a >>> 15), 1 | a);
      t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
      return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
    };
  }

  var N = 40000, R = 250, TAU = Math.PI * 2, STEP = 1 / 60;
  var rand = rng(61803);
  var i;

  var pos = new Array(N);
  var vx = new Float32Array(N), vy = new Float32Array(N), vz = new Float32Array(N);
  var ph = new Float32Array(N);

  for (i = 0; i < N; i++) {
    var x = (rand() - 0.5) * 150;
    var y = (rand() - 0.5) * 150;
    var z = (rand() - 0.5) * 110;
    pos[i] = [x, y, z];
    vx[i] = -y * 0.25;
    vy[i] = x * 0.25;
    vz[i] = (rand() - 0.5) * 8;
    ph[i] = rand() * TAU;
  }

  var STOPS = [
    [38, 96, 220], [64, 206, 226], [86, 214, 168],
    [246, 186, 78], [240, 104, 72]
  ];
  var LUT = [];
  for (i = 0; i < 32; i++) {
    var u = i / 31 * (STOPS.length - 1);
    var k = Math.min(STOPS.length - 2, Math.floor(u));
    var f = u - k;
    LUT.push([
      Math.round(STOPS[k][0] + (STOPS[k + 1][0] - STOPS[k][0]) * f),
      Math.round(STOPS[k][1] + (STOPS[k + 1][1] - STOPS[k][1]) * f),
      Math.round(STOPS[k][2] + (STOPS[k + 1][2] - STOPS[k][2]) * f),
      225
    ]);
  }

  var mode = 'swirl', strength = 1, t = 0, frameNo = 0;

  function step(dt) {
    var s = strength;
    var acc = 48 * s;
    for (var k = 0; k < N; k++) {
      var p = pos[k];
      var x = p[0], y = p[1], z = p[2];
      var r = Math.sqrt(x * x + y * y + z * z) + 0.001;
      var ax, ay, az;
      if (mode === 'swirl') {
        ax = (-y / r) * acc - (x / r) * 12 * s;
        ay = (x / r) * acc - (y / r) * 12 * s;
        az = (Math.sin(t * 1.2 + ph[k]) * 0.9 - (z / r) * 0.4) * 18 * s;
      } else {
        ax = (x / r) * acc;
        ay = (y / r) * acc;
        az = (z / r) * acc + Math.sin(t * 1.5 + ph[k]) * 10 * s;
      }
      vx[k] = (vx[k] + ax * dt) * 0.986;
      vy[k] = (vy[k] + ay * dt) * 0.986;
      vz[k] = (vz[k] + az * dt) * 0.986;
      p[0] = x + vx[k] * dt;
      p[1] = y + vy[k] * dt;
      p[2] = z + vz[k] * dt;
      var r2 = Math.sqrt(p[0] * p[0] + p[1] * p[1] + p[2] * p[2]);
      if (r2 > R) {
        var kb = R / r2;
        p[0] *= kb; p[1] *= kb; p[2] *= kb;
        vx[k] *= -0.45; vy[k] *= -0.45; vz[k] *= -0.45;
      } else if (r2 < 6) {
        p[0] += 0.8; p[1] += 0.8; p[2] += 0.4;
      }
    }
  }

  function getFillColor(d, info) {
    var k = info.index;
    var v = Math.sqrt(vx[k] * vx[k] + vy[k] * vy[k] + vz[k] * vz[k]);
    var u = v / 55;
    if (u > 1) u = 1;
    var idx = ((u * 0.68 + (ph[k] / TAU) * 0.32) * 31) | 0;
    return LUT[idx];
  }

  function buildLayers() {
    return [
      new deck.ScatterplotLayer({
        id: 'generative-particles',
        data: pos,
        coordinateSystem: deck.COORDINATE_SYSTEM.CARTESIAN,
        getPosition: function (d) { return d; },
        getFillColor: getFillColor,
        getRadius: 1.7,
        radiusUnits: 'pixels',
        radiusMinPixels: 1,
        opacity: 0.85,
        pickable: false,
        updateTriggers: { getPosition: frameNo, getFillColor: frameNo }
      })
    ];
  }

  var deckgl = new deck.Deck({
    canvas: 'cv',
    width: '100%',
    height: '100%',
    views: new deck.OrbitView({ target: [0, 0, 0], fovy: 30 }),
    initialViewState: { target: [0, 0, 0], rotationX: 27, rotationOrbit: -30, zoom: 0.3 },
    controller: true,
    layers: buildLayers()
  });

  var btns = document.querySelectorAll('.bar button[data-m]');
  for (i = 0; i < btns.length; i++) {
    btns[i].addEventListener('click', function () {
      mode = this.getAttribute('data-m');
      for (var b = 0; b < btns.length; b++) {
        btns[b].className = btns[b] === this ? 'on' : '';
      }
      frameNo++;
      deckgl.setProps({ layers: buildLayers() });
    });
  }

  var strEl = document.getElementById('str');
  strEl.addEventListener('input', function () {
    strength = +strEl.value;
    document.getElementById('s').textContent = strength.toFixed(1);
  });

  function loop() {
    t += STEP;
    step(STEP);
    frameNo++;
    deckgl.setProps({ layers: buildLayers() });
    requestAnimationFrame(loop);
  }

  window.__deck = deckgl;
  requestAnimationFrame(loop);
})();
</script>
</body>
</html>
Language: this page is in English; the demo keeps Chinese interface labels and code comments. The Chinese page carries the full notes and the same runnable file.

More business examples

deck.gl · APIScatterplotLayer deck.gl · APIOrbitView deck.gl · APICOORDINATE_SYSTEM