GPUCommandEncoder: copyBufferToBuffer() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

GPUCommandEncoder 介面的 copyBufferToBuffer() 方法會編碼一個命令,該命令將資料從一個 GPUBuffer 複製到另一個。

語法

js
copyBufferToBuffer(source, destination)
copyBufferToBuffer(source, destination, size)
copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)

引數

source

要從中複製的 GPUBuffer

sourceOffset 可選

source 開始複製的偏移量(以位元組為單位)。

destination

要複製到的 GPUBuffer

destinationOffset 可選

複製到 destination 的偏移量(以位元組為單位)。

size 可選

要複製的位元組數。

注意: 如果您要在源緩衝區和目標緩衝區都以 0 偏移量複製源緩衝區的某一部分,則可以省略 sourceOffsetdestinationOffset。如果您要將整個源緩衝區複製到目標緩衝區,則可以省略 sourceOffsetdestinationOffsetsize

返回值

無 (Undefined)。

驗證

呼叫 copyBufferToBuffer() 時必須滿足以下條件,否則將生成 GPUValidationError,並且 GPUCommandEncoder 將失效。

  • sourceGPUBuffer.usage 包含 GPUBufferUsage.COPY_SRC 標誌。
  • destinationGPUBuffer.usage 包含 GPUBufferUsage.COPY_DST 標誌。
  • sizesourceOffsetdestinationOffset 都必須是 4 的倍數。
  • sourceGPUBuffer.size 大於或等於 sourceOffset + size
  • destinationGPUBuffer.size 大於或等於 destinationOffset + size
  • sourcedestination 是不同的 GPUBuffer(不能從同一緩衝區複製到同一緩衝區)。

示例

在我們 基本的計算演示中,我們使用 copyBufferToBuffer()outputBuffer 的內容複製到 stagingBuffer

js
// …

// 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);

// …

規範

規範
WebGPU
# dom-gpucommandencoder-copybuffertobuffer

瀏覽器相容性

另見