Atlaslog
Atlaslog / Examples / deck.gl / Business scenarios / Large-Scale Particle Field
deck.gl · Business scenario

Large-Scale Particle Field

120,000 particles oscillate harmonically inside a 40×40×12 box; color shifts from deep blue to orange-red with instantaneous speed, and the run can be paused with the particle count adjustable.

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

Business context

Particle fields of this kind appear most often when previewing results from computational fluid dynamics, plasma simulation and molecular dynamics; the users are simulation engineers and researchers who need to judge flow structure quickly. Data is exported from a CFD or SPH solver as per-frame particle positions and velocities. A single case commonly holds 100,000 to 1,000,000 particles, and browser previews are usually decimated to the 100,000 range before shape and evolution are discussed.

Solver output is a local Cartesian frame, so units are unified, the cloud is centered on its bounding box and different time steps are aligned to a common frame index before entering deck.gl; when the particle budget is exceeded, particles are sampled in strata over a spatial grid. Cesium requires WGS84 and a terrain basemap, and three.js leaves camera and picking to the developer. What is needed here is a rotatable box with a stable color mapping, which OrbitView and managed attributes provide with less code.

The usual misreading is to treat point size as particle radius or concentration: the radius is fixed at 1.6 px and only color varies with speed, so density differences have to be inferred indirectly from accumulated brightness. Positions also follow a closed-form expression rather than numerical integration, so a frozen picture does not mean the system has reached equilibrium, and animation rate bears no relation to physical time.

How it works

Base coordinates are sampled uniformly inside a box with x, y ∈ [-20,20] and z ∈ [-6,6], then multiplied by 10 into scene units. Each particle carries an amplitude of 2–8, an angular frequency of 0.5–1.5 rad/s and its own phase; position updates as x = x0 + A·sin(ωt+φ), with y and z offset in frequency by factors of 0.9 and 1.3. Each frame writes the new coordinates back into the same [x,y,z] array without creating a new data object; getPosition returns a reference to that array, and the frame number inside updateTriggers makes ScatterplotLayer recompute both the position and fillColor attributes.

Speed is approximated as A·ω·|cos(ωt+φ)|, normalized and looked up in a 24-step color ramp, which avoids generating an RGB array per frame. When the slider drops to 30,000, data is sliced once while the frame loop keeps the same array references; pressing 'static' stops setProps, and drag-rotation still works. 120,000 points mean roughly 600,000 trigonometric calls per frame plus two rounds of attribute recomputation for position and fillColor, so the frame rate falls clearly below an empty scene. Binary Float32Array attributes remove the accessor calls, at the cost of assembling the data as a {length, attributes} object yourself.

SettingEffect
updateTriggers: {getPosition: frame number}Forces coordinate attribute recomputation while the data reference is unchanged
radiusUnits: 'pixels'Particle radius fixed at 1.6 px, unaffected by zoom
amplitude × angular frequencyActs as the speed quantity, normalized before mapping to color
data.slice(0, n)Trims visible particles only when the slider changes; the frame loop never rebuilds the array

Note. When rewriting coordinates every frame, keep the same array references and only advance updateTriggers; this prevents deck.gl from rebuilding the attribute buffer on each frame.

Source

demos/deckgl-nongis-particle-field.html
<!--
  示例:大规模粒子场
  要点:12 万粒子在 40×40×12 的盒内做简谐运动,逐帧原地改写坐标,靠 updateTriggers 触发属性重算
  依赖: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>粒子 <b id="n">120,000</b></span><span class="sep"></span>
  <button id="run" class="on">运动</button>
  <label>数量 <input id="cnt" type="range" min="30000" max="120000" step="10000" value="120000"></label>
  <span id="fps">—</span>
</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 = 120000;
  var U = 10;                 // 盒子 40×40×12 映射到 400×400×120 场景单位
  var TAU = Math.PI * 2;
  var rand = rng(20261124);

  var pos = new Array(N);
  var bx = new Float32Array(N), by = new Float32Array(N), bz = new Float32Array(N);
  var amp = new Float32Array(N), om = new Float32Array(N), ph = new Float32Array(N);
  var spd = new Float32Array(N);
  var i, maxV = 0;

  for (i = 0; i < N; i++) {
    var a0 = 2 + rand() * 6;
    var w0 = 0.5 + rand();
    bx[i] = (rand() - 0.5) * 40 * U;
    by[i] = (rand() - 0.5) * 40 * U;
    bz[i] = (rand() - 0.5) * 12 * U;
    amp[i] = a0;
    om[i] = w0;
    ph[i] = rand() * TAU;
    pos[i] = [bx[i], by[i], bz[i]];
    if (a0 * w0 > maxV) maxV = a0 * w0;
  }
  maxV *= 1.8;

  var stops = [[26, 52, 120], [42, 148, 226], [70, 216, 190], [248, 208, 96], [238, 96, 58]];
  var LUT = [];
  for (i = 0; i < 24; i++) {
    var u = i / 23 * (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),
      235
    ]);
  }

  var t = 0, frameNo = 0, paused = false, visible = pos;

  function updateField() {
    for (var j = 0; j < N; j++) {
      var th = t * om[j] + ph[j];
      var a = amp[j];
      var p = pos[j];
      p[0] = bx[j] + a * Math.sin(th);
      p[1] = by[j] + a * 0.8 * Math.sin(th * 0.9 + 1.7);
      p[2] = bz[j] + a * 0.35 * Math.sin(th * 1.3 + 0.6);
      spd[j] = a * om[j] * (Math.abs(Math.cos(th)) + 0.8 * Math.abs(Math.cos(th * 0.9 + 1.7)));
    }
  }
  updateField();

  function getPosition(d) {
    return d;
  }

  function getFillColor(d, info) {
    var v = spd[info.index] / maxV;
    if (v > 1) v = 1;
    return LUT[(v * 23) | 0];
  }

  function buildLayers() {
    return [
      new deck.ScatterplotLayer({
        id: 'particle-field',
        data: visible,
        coordinateSystem: deck.COORDINATE_SYSTEM.CARTESIAN,
        getPosition: getPosition,
        getFillColor: getFillColor,
        getRadius: 1.6,
        radiusUnits: 'pixels',
        radiusMinPixels: 1,
        opacity: 0.9,
        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: 20 }),
    initialViewState: { target: [0, 0, 0], rotationX: 28, rotationOrbit: -34, zoom: 0.45 },
    controller: true,
    layers: buildLayers()
  });

  var fpsEl = document.getElementById('fps');
  var runEl = document.getElementById('run');
  var cntEl = document.getElementById('cnt');
  var last = performance.now();

  runEl.addEventListener('click', function () {
    paused = !paused;
    runEl.className = paused ? '' : 'on';
    runEl.textContent = paused ? '静止' : '运动';
    if (!paused) last = performance.now();
  });

  cntEl.addEventListener('input', function () {
    var n = +cntEl.value;
    visible = pos.slice(0, n);
    document.getElementById('n').textContent = n.toLocaleString();
    frameNo++;
    deckgl.setProps({ layers: buildLayers() });
  });

  function loop(now) {
    var dt = Math.min((now - last) / 1000, 0.06);
    last = now;
    if (!paused) {
      t += dt;
      updateField();
      frameNo++;
      deckgl.setProps({ layers: buildLayers() });
      fpsEl.textContent = Math.round(1 / dt) + ' fps';
    }
    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