Reference set()

set()

This feature requires the p5.webgpu.js addon.
This API is experimental

Its behavior may change in a future version of p5.js.

Updates a single element in the buffer at a given index. Use this when only a small number of elements need to change. If you need to replace all the data at once, use update() instead.

let buf;

async function setup() {
  await createCanvas(100, 100, WEBGPU);

  // Float buffer: update one value by index
  buf = createStorage(new Float32Array([1, 2, 3, 4]));
  buf.set(2, 9.5); // only index 2 changes → [1, 2, 9.5, 4]

  let result = await buf.read();
  print(result[2]); // 9.5
  describe('Prints 9.5 to the console.');
}
let particles;
const numParticles = 100;

async function setup() {
  await createCanvas(100, 100, WEBGPU);
  particles = createStorage(makeParticles());

  // Replace particle 42 without touching the others
  particles.set(42, {
    position: createVector(0, 0),
    velocity: createVector(1, 0),
  });

  // Read back to confirm the update
  let result = await particles.read();
  print(result[42].position.x, result[42].position.y); // 0, 0
  describe('Prints the position of particle 42 after updating it.');
}

function makeParticles() {
  let data = [];
  for (let i = 0; i < numParticles; i++) {
    data.push({
      position: createVector(random(width), random(height)),
      velocity: createVector(random(-1, 1), random(-1, 1)),
    });
  }
  return data;
}

Examples

Syntax

set(index, value)

Parameters

index
Number: The zero-based index of the element to update.
value
Number|Object: The new value. Pass a number for float buffers, or a plain object matching the original struct layout for struct buffers.
Notice any errors or typos? Please let us know. Please feel free to edit src/webgpu/p5.RendererWebGPU.js and open a pull request!

Related References