web api instance method
GPUCommandEncoder: copyBufferToBuffer() method
Secure context
The copyBufferToBuffer() method of the
GPUCommandEncoder interface encodes a command that copies data from one GPUBuffer to another.
Syntax
copyBufferToBuffer(source, destination)
copyBufferToBuffer(source, destination, size)
copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)
Parameters
source- : The
GPUBufferto copy from.
- : The
sourceOffsetOptional- : The offset, in bytes, into the
sourceto begin copying from.
- : The offset, in bytes, into the
destination- : The
GPUBufferto copy to.
- : The
destinationOffsetOptional- : The offset, in bytes, into the
destinationto begin copying to.
- : The offset, in bytes, into the
sizeOptional- : The number of bytes to copy.
[!NOTE] The
sourceOffsetanddestinationOffsetcan be omitted if you are copying part of the source buffer at a0offset in both the source and destination buffers. ThesourceOffset,destinationOffset, andsizecan be omitted if you are copying the entire source buffer to the destination buffer.
Return value
None (undefined).
Validation
The following criteria must be met when calling copyBufferToBuffer(), otherwise a GPUValidationError is generated and the GPUCommandEncoder becomes invalid:
- The
source’susageincludes theGPUBufferUsage.COPY_SRCflag. - The
destination’susageincludes theGPUBufferUsage.COPY_DSTflag. size,sourceOffset, anddestinationOffsetare all multiples of 4.- The
source’ssizeis greater than or equal tosourceOffset+size. - The
destination’ssizeis greater than or equal todestinationOffset+size. sourceanddestinationare differentGPUBuffers (you can’t copy from and to the same buffer).
Examples
In our basic compute demo, we use copyBufferToBuffer() to copy the contents of our outputBuffer to the stagingBuffer.
// …
// Create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access
const outputBuffer = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
const stagingBuffer = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
// …
// Create GPUCommandEncoder to encode commands to issue to the GPU
const commandEncoder = device.createCommandEncoder();
// …
// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
outputBuffer,
0, // Source offset
stagingBuffer,
0, // Destination offset
BUFFER_SIZE,
);
// Since we are copying the entire buffer, this can be shortened to
// commandEncoder.copyBufferToBuffer(outputBuffer, stagingBuffer);
// …
Specifications
Browser compatibility
See also
- The WebGPU API