Antialiasing MSAA interactivo para gráficas de línea WebGPU

El post de la onda senoidal renderizó una onda senoidal evaluada en GPU como line strip — pero sin anti-aliasing los bordes de la línea van dentados, sobre todo donde la curva es empinada. Este post añade MSAA (multi-sample anti-aliasing) a esa pipeline y lo hace interactivo: arrastra hacia arriba para subir el sample count (bordes más suaves), hacia abajo para bajarlo (más aliasing).

El demo en vivo siguiente carga /scripts/sine-aa-webgpu.js. Empieza en 1× (sin AA) para que veas el aliasing; luego arrastra hacia arriba para comparar.

Arrastra arriba/abajo para cambiar el sample count MSAA. 6 ciclos senoidales completos — más empinado que el post original, así que el aliasing es más visible a sample counts bajos. Requiere un navegador con WebGPU (Chrome / Edge 113+). MSAA actual: 1×

Cómo funciona

La gráfica es la misma pipeline compute→storage-buffer→render-pass del post de la onda senoidal. La única adición es MSAA, que es un asunto de render pipeline y render pass — el compute shader y el fuente WGSL no cambian.

MSAA en WebGPU: pipeline + render pass

MSAA en WebGPU requiere dos cosas:

  1. sampleCount de pipeline: la render pipeline se crea con multisample: { count: N } donde N es 1, 2, 4, 8 o 16. Esto le dice a la GPU que tome N muestras por píxel durante la rasterización. El sample count es una propiedad de pipeline — no se puede cambiar en el momento del draw.

  2. Render target multisampleado: cuando sampleCount > 1, el color attachment del render pass debe usar una textura multisampleada como view, con la textura del canvas como resolveTarget. El hardware promedia las N muestras a la textura del canvas automáticamente al final del pass — sin código de shader ni comando de copia.

msaa.js
// Pipeline: set sampleCount
const pipeline = device.createRenderPipeline({
  // ...
  multisample: { count: 4 },
});

// Render pass: multisampled texture → canvas resolve
const rp = encoder.beginRenderPass({
  colorAttachments: [{
    view: msaaTexture.createView(),        // multisampled
    resolveTarget: canvasView,             // non-multisampled
    clearValue: { r: 0.05, g: 0.05, b: 0.07, a: 1 },
    loadOp: 'clear',
    storeOp: 'store',
  }],
});

Con sampleCount = 1 no hace falta textura multisampleada — el render pass renderiza directamente a la textura del canvas y se omite resolveTarget.

Pipelines pre-creadas para los sample counts soportados

Como sampleCount es una propiedad de pipeline, cambiarlo en runtime requiere una pipeline diferente. Para evitar tirones durante la interacción, se pre-crea una pipeline por sample count soportado al inicio.

No todos los sample counts están soportados por cada adapter GPU. La spec de WebGPU solo garantiza 1× y 4×; 2×, 8× y 16× dependen del adapter. Si creas una pipeline con un sample count no soportado, puede compilar sin error pero no producir salida visible — la traza simplemente desaparece.

La forma más portable de sondear es createRenderPipelineAsync: devuelve una Promise que se rechaza en errores de validación (incluidos sample counts no soportados), y está disponible desde el lanzamiento de WebGPU. APIs más nuevas como pushErrorFilter/popErrorFilter aún no se distribuyen ampliamente:

pipelines.js
for (const sc of SAMPLE_COUNTS) {
  try {
    const pipe = await device.createRenderPipelineAsync({
      // ... same shader, same layout ...
      multisample: { count: sc },
    });
    supportedSC.push(sc);
    renderPipelines.push(pipe);
  } catch {
    // Unsupported sample count — skip.
  }
}

Todas las pipelines comparten el mismo shader module y bind group layout, así que un único renderBindGroup sirve para todas. Cambiar de sample count es solo renderPipelines[sampleIndex] — sin recompilación, sin creación de recursos, sin tirones.

Ciclo de vida de la textura MSAA

La textura multisampleada debe coincidir con el tamaño del canvas y el sample count actual. Se recrea cuando cualquiera cambia:

msaa-texture.js
function ensureMsaa(w, h, sc) {
  if (sc === 1) {
    if (msaaTexture) { msaaTexture.destroy(); msaaTexture = null; }
    return;
  }
  if (msaaTexture && msaaSC === sc && msaaW === w && msaaH === h) return;
  if (msaaTexture) msaaTexture.destroy();
  msaaTexture = device.createTexture({
    size: [w, h, 1],
    format,
    usage: GPUTextureUsage.RENDER_ATTACHMENT,
    sampleCount: sc,
  });
  msaaSC = sc; msaaW = w; msaaH = h;
}

Con sc = 1 la textura MSAA se destruye y el render pass renderiza directamente al canvas. Con sc > 1 se crea una textura nueva bajo demanda. La comprobación msaaSC === sc && msaaW === w && msaaH === h evita recrear la textura cada frame cuando nada cambió.

Interacción de arrastre → sample count

El arrastre vertical se mapea a una posición continua que se ajusta al índice de sample count más cercano. Cada 80px de arrastre mueve un paso:

interaction.js
canvas.addEventListener('pointermove', (e) => {
  if (!dragging) return;
  const dy = e.clientY - startY;
  const idx = Math.round(startIndex - dy / SAMPLE_STEP_PX);
  sampleIndex = Math.max(0, Math.min(SAMPLE_COUNTS.length - 1, idx));
});

Arrastrar arriba (dy negativo) → índice mayor → más muestras → bordes más suaves. Arrastrar abajo → índice menor → menos muestras → más aliasing.

El canvas puede opcionalmente actualizar un elemento HTML con el sample count actual vía un atributo data-samples-display="elementId", el mismo patrón de callback usado en el post de los cubos de dirección.

¿Por qué 6 ciclos?

El post original de la onda senoidal usa 4 ciclos (frequency = 8π). Este post usa 6 ciclos (frequency = 12π) para hacer la línea más empinada en los cruces por cero. Las líneas más empinadas tienen más segmentos casi horizontales y casi verticales, donde el aliasing es más visible — el efecto “escalera” en las diagonales es más pronunciado a 1× y claramente suavizado a 16×.

Usarlo en tu propia página

Suelta el script en tu carpeta static y añade un canvas con la clase sine-aa-canvas:

example.html
<canvas class="sine-aa-canvas"
        data-samples-display="aa-readout"
        style="width:100%;height:350px;"></canvas>
<span id="aa-readout">1×</span>
<script src="/scripts/sine-aa-webgpu.js" defer></script>

El atributo data-samples-display es opcional — si está presente, el elemento se actualiza con el sample count actual en cada arrastre.

Para cambiar la frecuencia, la amplitud o el conjunto de sample counts, edita las constantes FREQUENCY, AMPLITUDE y SAMPLE_COUNTS al principio del script.

Código completo

sine-aa-webgpu.js
// SPDX-FileCopyrightText: 2026 Uli Köhler <gitlab@techoverflow.net>
// SPDX-License-Identifier: CC0-1.0
//
// Minimal WebGPU line plot with GPU-side function evaluation and
// interactive MSAA (multi-sample anti-aliasing).
//
// Renders a sine wave by evaluating sin() in a compute shader, then
// drawing the resulting points as a line strip. The JavaScript side
// only writes uniforms and submits command buffers — no function
// evaluation happens on the CPU.
//
// MSAA is controlled by the user: up-down drag changes the sample
// count between 1, 2, 4, 8, and 16. Five render pipelines are
// pre-created at init time (one per sample count) so no pipeline
// compilation happens during interaction. A multisampled texture
// serves as the render target when sampleCount > 1, with the canvas
// texture as the resolve target.
//
// Auto-initializes every <canvas class="sine-aa-canvas"> on the page.
// Optional: data-samples-display="elementId" to update an HTML element
// with the current sample count.
//
// Why an IIFE?  We wrap everything in an immediately-invoked function
// expression so that none of the helpers, constants, or the WGSL source
// leak into the global scope.  The script is intended to be included
// verbatim with <script src=... defer>, possibly alongside other scripts
// on the same page, so isolation matters.
(function () {
  'use strict';

  // ─────────────────────────────────────────────────────────────────────
  // Configuration
  // ─────────────────────────────────────────────────────────────────────
  // 6 full cycles across the width — steeper than the 4-cycle sine
  // post, so aliasing is more visible at low sample counts.
  const FREQUENCY = 12.0 * Math.PI;  // 6 full cycles
  const AMPLITUDE = 0.8;
  const MAX_POINTS = 4096;

  // MSAA sample counts supported by WebGPU (powers of 2, max 16).
  // Five pipelines are pre-created at init — one per sample count —
  // so switching is instant with no shader recompilation.
  const SAMPLE_COUNTS = [1, 2, 4, 8, 16];
  const DEFAULT_SAMPLE_INDEX = 0;    // start at 1× (no AA) to show aliasing
  const SAMPLE_STEP_PX = 80;         // pixels of drag per sample-count step

  // ─────────────────────────────────────────────────────────────────────
  // WGSL shader
  // ─────────────────────────────────────────────────────────────────────
  // Identical to the sine-wave post. MSAA does not change the shader —
  // it only changes the render pipeline's sampleCount and the render
  // pass's color attachment (multisampled texture + resolve target).
  // The GPU hardware performs the multi-sampling automatically.
  //
  // The compute shader fills a storage buffer with vec2<f32> points:
  //   x = i / (pointCount - 1)   →  0..1 across the width
  //   y = amplitude * sin(x * frequency)
  //
  // The render shader reads the same buffer and draws it as a line
  // strip in clip space.

  const SHADER = /* wgsl */ `
  // ── Compute: fill points[] with sin(x) ──────────────────────────────
  struct ComputeUniforms {
    pointCount : u32,
    frequency  : f32,
    amplitude  : f32,
    _pad       : f32,
  };

  @group(0) @binding(0) var<uniform>  cu : ComputeUniforms;
  @group(0) @binding(1) var<storage, read_write> points : array<vec2<f32>>;

  @compute @workgroup_size(64)
  fn cs_main(@builtin(global_invocation_id) gid : vec3<u32>) {
    let i = gid.x;
    if (i >= cu.pointCount) { return; }
    let n = f32(cu.pointCount);
    let x = f32(i) / max(n - 1.0, 1.0);
    let y = cu.amplitude * sin(x * cu.frequency);
    points[i] = vec2<f32>(x, y);
  }

  // ── Render: line-strip in clip space ────────────────────────────────
  struct RenderUniforms {
    yScale : f32,
    _pad0  : f32,
    _pad1  : f32,
    _pad2  : f32,
  };

  @group(0) @binding(0) var<uniform>  ru : RenderUniforms;
  @group(0) @binding(1) var<storage, read> rpoints : array<vec2<f32>>;

  struct VSOut {
    @builtin(position) pos : vec4<f32>,
    @location(0)       uv  : vec2<f32>,
  };

  @vertex
  fn vs_main(@builtin(vertex_index) vi : u32) -> VSOut {
    let p = rpoints[vi];
    var out : VSOut;
    out.pos = vec4<f32>(2.0 * p.x - 1.0, p.y * ru.yScale, 0.0, 1.0);
    out.uv  = p;
    return out;
  }

  @fragment
  fn fs_main(in : VSOut) -> @location(0) vec4<f32> {
    let t = in.uv.y * 0.5 + 0.5;
    return vec4<f32>(0.2 + 0.1 * t, 0.5 + 0.2 * t, 1.0, 1.0);
  }
`;

  // ─────────────────────────────────────────────────────────────────────
  // Per-canvas initialization
  // ─────────────────────────────────────────────────────────────────────

  async function initCanvas(canvas) {
    if (!navigator.gpu) {
      canvas.replaceWith(document.createTextNode('WebGPU is not supported in this browser.'));
      return;
    }
    const adapter = await navigator.gpu.requestAdapter();
    if (!adapter) {
      canvas.replaceWith(document.createTextNode('No WebGPU adapter available.'));
      return;
    }
    const device = await adapter.requestDevice();
    const ctx = canvas.getContext('webgpu');
    const format = navigator.gpu.getPreferredCanvasFormat();
    ctx.configure({ device, format, alphaMode: 'premultiplied' });

    const module = device.createShaderModule({ code: SHADER });

    // --- Explicit bind group layouts ---
    // Using explicit layouts (not 'auto') so all five render pipelines
    // share the same bind group layout, and a single renderBindGroup
    // works for all of them.  The compute layout is separate because
    // the point buffer is read_write in compute but read-only in render.

    const computeLayout = device.createBindGroupLayout({
      entries: [
        { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform' } },
        { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'storage' } },
      ],
    });

    const renderLayout = device.createBindGroupLayout({
      entries: [
        { binding: 0, visibility: GPUShaderStage.VERTEX, buffer: { type: 'uniform' } },
        { binding: 1, visibility: GPUShaderStage.VERTEX, buffer: { type: 'read-only-storage' } },
      ],
    });

    // --- Compute pipeline (shared, no MSAA) ---
    const computePipeline = device.createComputePipeline({
      layout: device.createPipelineLayout({ bindGroupLayouts: [computeLayout] }),
      compute: { module, entryPoint: 'cs_main' },
    });

    // --- Render pipelines: one per supported MSAA sample count ---
    // WebGPU requires sampleCount to be a pipeline property — you
    // cannot change it at draw time.  So we pre-create one pipeline
    // per supported sample count.  All share the same shader module
    // and bind group layout; only sampleCount differs.
    //
    // At sampleCount=1, the render pass renders directly to the canvas
    // texture (no multisampled texture needed).  At sampleCount>1, the
    // render pass renders to a multisampled texture and resolves to the
    // canvas texture — the hardware averages the samples automatically.
    //
    // Not all sample counts are supported by every adapter.  The WebGPU
    // spec only guarantees 1× and 4×; 2×, 8×, and 16× are
    // adapter-dependent.  We probe by creating the pipeline with
    // createRenderPipelineAsync — if the sample count is unsupported,
    // the Promise rejects and we skip that count.
    const supportedSC = [];
    const renderPipelines = [];
    const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [renderLayout] });
    for (const sc of SAMPLE_COUNTS) {
      try {
        const pipe = await device.createRenderPipelineAsync({
          layout: pipelineLayout,
          vertex:   { module, entryPoint: 'vs_main' },
          fragment: { module, entryPoint: 'fs_main', targets: [{ format }] },
          primitive: { topology: 'line-strip' },
          multisample: { count: sc },
        });
        supportedSC.push(sc);
        renderPipelines.push(pipe);
      } catch {
        // Unsupported sample count — skip.
      }
    }

    // --- Buffers ---
    const computeUniforms = device.createBuffer({
      size: 16,
      usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
    });

    const renderUniforms = device.createBuffer({
      size: 16,
      usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
    });

    const pointBuffer = device.createBuffer({
      size: MAX_POINTS * 8,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
    });

    const computeBindGroup = device.createBindGroup({
      layout: computeLayout,
      entries: [
        { binding: 0, resource: { buffer: computeUniforms } },
        { binding: 1, resource: { buffer: pointBuffer } },
      ],
    });

    // One render bind group works for all five pipelines because they
    // share the same renderLayout.
    const renderBindGroup = device.createBindGroup({
      layout: renderLayout,
      entries: [
        { binding: 0, resource: { buffer: renderUniforms } },
        { binding: 1, resource: { buffer: pointBuffer } },
      ],
    });

    // --- MSAA texture management ---
    // When sampleCount > 1, the render pass needs a multisampled texture
    // as its color attachment, with the canvas texture as the resolve
    // target.  The MSAA texture must match the canvas size and the
    // current sample count — it is recreated when either changes.
    //
    // At sampleCount = 1, msaaTexture is null and the render pass
    // renders directly to the canvas texture (no resolve needed).
    let msaaTexture = null;
    let msaaSC = 0, msaaW = 0, msaaH = 0;

    function ensureMsaa(w, h, sc) {
      if (sc === 1) {
        if (msaaTexture) { msaaTexture.destroy(); msaaTexture = null; }
        msaaSC = 1; msaaW = w; msaaH = h;
        return;
      }
      if (msaaTexture && msaaSC === sc && msaaW === w && msaaH === h) return;
      if (msaaTexture) msaaTexture.destroy();
      msaaTexture = device.createTexture({
        size: [w, h, 1],
        format,
        usage: GPUTextureUsage.RENDER_ATTACHMENT,
        sampleCount: sc,
      });
      msaaSC = sc; msaaW = w; msaaH = h;
    }

    // --- Interaction: drag to change MSAA sample count ---
    // Up-down drag cycles through supportedSC (the sample counts that
    // this adapter actually supports).
    // Drag up (deltaY < 0) → more samples (better AA).
    // Drag down (deltaY > 0) → fewer samples (more aliasing).
    //
    // The drag maps to a continuous position that snaps to the nearest
    // sample-count index.  setPointerCapture ensures we keep receiving
    // pointermove events even if the pointer leaves the canvas.
    let sampleIndex = Math.min(DEFAULT_SAMPLE_INDEX, supportedSC.length - 1);
    let dragging = false, startY = 0, startIndex = 0;

    const displayId = canvas.getAttribute('data-samples-display');
    const display = displayId ? document.getElementById(displayId) : null;
    function updateDisplay() {
      if (display) display.textContent = supportedSC[sampleIndex] + '×';
    }
    updateDisplay();

    canvas.style.cursor = 'ns-resize';
    canvas.style.touchAction = 'none';
    canvas.addEventListener('pointerdown', (e) => {
      dragging = true; startY = e.clientY; startIndex = sampleIndex;
      canvas.setPointerCapture(e.pointerId);
    });
    canvas.addEventListener('pointerup', () => { dragging = false; });
    canvas.addEventListener('pointermove', (e) => {
      if (!dragging) return;
      const dy = e.clientY - startY;
      // Drag up (negative dy) → increase index.  Clamp to valid range.
      const idx = Math.round(startIndex - dy / SAMPLE_STEP_PX);
      sampleIndex = Math.max(0, Math.min(supportedSC.length - 1, idx));
      updateDisplay();
    });

    // --- Render loop ---
    function frame() {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      const cw = Math.max(1, Math.floor(canvas.clientWidth * dpr));
      const ch = Math.max(1, Math.floor(canvas.clientHeight * dpr));
      if (canvas.width !== cw || canvas.height !== ch) {
        canvas.width = cw; canvas.height = ch;
      }

      const pointCount = Math.min(MAX_POINTS, cw);
      const sc = supportedSC[sampleIndex];

      // Write compute uniforms (same as the sine-wave post).
      const cuData = new ArrayBuffer(16);
      const cuView = new DataView(cuData);
      cuView.setUint32(0, pointCount, true);
      cuView.setFloat32(4, FREQUENCY, true);
      cuView.setFloat32(8, AMPLITUDE, true);
      cuView.setFloat32(12, 0, true);
      device.queue.writeBuffer(computeUniforms, 0, cuData);

      device.queue.writeBuffer(renderUniforms, 0, new Float32Array([
        1.0, 0, 0, 0,
      ]));

      // Ensure the MSAA texture matches the current canvas size and
      // sample count.  At sc=1 this destroys any existing MSAA texture.
      ensureMsaa(cw, ch, sc);

      const encoder = device.createCommandEncoder();

      // Compute pass — generate sine wave points on the GPU.
      const cp = encoder.beginComputePass();
      cp.setPipeline(computePipeline);
      cp.setBindGroup(0, computeBindGroup);
      cp.dispatchWorkgroups(Math.ceil(pointCount / 64));
      cp.end();

      // Render pass — draw the points as a line strip with MSAA.
      //
      // Two cases:
      //   sc = 1: render directly to the canvas texture (no resolve).
      //   sc > 1: render to the multisampled texture, resolve to canvas.
      //
      // The resolve is performed by the hardware — no shader code or
      // copy command needed.  The multisampled texture is automatically
      // averaged down to the canvas texture at the end of the pass.
      //
      // When using resolveTarget, storeOp must be 'discard' — we don't
      // need the multisampled texture's contents after the resolve, only
      // the resolved result in the canvas texture.  Using 'store' on a
      // multisampled texture with resolveTarget can cause the rendered
      // content to disappear on some implementations (the resolve step
      // may not fire correctly).
      const canvasView = ctx.getCurrentTexture().createView();
      const colorAttachment = {
        clearValue: { r: 0.055, g: 0.055, b: 0.07, a: 1 },
        loadOp: 'clear',
      };
      if (sc > 1) {
        colorAttachment.view = msaaTexture.createView();
        colorAttachment.resolveTarget = canvasView;
        colorAttachment.storeOp = 'discard';
      } else {
        colorAttachment.view = canvasView;
        colorAttachment.storeOp = 'store';
      }

      const rp = encoder.beginRenderPass({ colorAttachments: [colorAttachment] });
      rp.setPipeline(renderPipelines[sampleIndex]);
      rp.setBindGroup(0, renderBindGroup);
      rp.draw(pointCount);
      rp.end();

      device.queue.submit([encoder.finish()]);
      requestAnimationFrame(frame);
    }
    requestAnimationFrame(frame);
  }

  // ─────────────────────────────────────────────────────────────────────
  // Auto-initialization
  // ─────────────────────────────────────────────────────────────────────
  function initAll() {
    document.querySelectorAll('canvas.sine-aa-canvas').forEach(initCanvas);
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initAll);
  } else {
    initAll();
  }
})();

El script y el listado inline de arriba son idénticos y ambos se publican bajo CC0-1.0. La implementación extiende el post de la onda senoidal con el soporte MSAA integrado de WebGPU. El mismo patrón de pipelines pre-creadas lo usa el ToolpathRenderer del proyecto WebGCodeViewer, que crea pipelines separadas para los caminos de renderizado MSAA y no-MSAA para evitar compilación de pipelines en runtime.


Echa un vistazo a artículos similares por categoría: JavaScript WebGPU Web