GPUCommandEncoder: copyBufferToBuffer() method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Phương thức copyBufferToBuffer() của giao diện GPUCommandEncoder mã hóa một lệnh sao chép dữ liệu từ một GPUBuffer sang buffer khác.

Cú pháp

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

Tham số

source

GPUBuffer nguồn để sao chép từ đó.

sourceOffset Optional

Độ lệch, tính bằng byte, trong source nơi bắt đầu sao chép.

destination

GPUBuffer đích để sao chép tới.

destinationOffset Optional

Độ lệch, tính bằng byte, trong destination nơi bắt đầu sao chép.

size Optional

Số byte cần sao chép.

Note: sourceOffsetdestinationOffset có thể được bỏ qua nếu bạn đang sao chép một phần của source buffer với độ lệch 0 ở cả source và destination. sourceOffset, destinationOffset, và size có thể được bỏ qua nếu bạn đang sao chép toàn bộ source buffer sang destination buffer.

Giá trị trả về

Không có (Undefined).

Kiểm tra hợp lệ

Các tiêu chí sau phải được đáp ứng khi gọi copyBufferToBuffer(), nếu không một GPUValidationError sẽ được tạo và GPUCommandEncoder trở nên không hợp lệ:

  • usage của source bao gồm cờ GPUBufferUsage.COPY_SRC.
  • usage của destination bao gồm cờ GPUBufferUsage.COPY_DST.
  • size, sourceOffset, và destinationOffset đều là bội số của 4.
  • GPUBuffer.size của source lớn hơn hoặc bằng sourceOffset + size.
  • GPUBuffer.size của destination lớn hơn hoặc bằng destinationOffset + size.
  • sourcedestination là hai GPUBuffer khác nhau (bạn không thể sao chép từ và sang cùng một buffer).

Ví dụ

Trong bản demo compute cơ bản của chúng tôi, copyBufferToBuffer() được dùng để sao chép nội dung của outputBuffer sang stagingBuffer.

js
// …

// Tạo một output buffer để đọc các phép tính GPU, và một staging buffer để map cho JavaScript truy cập

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,
});

// …

// Tạo GPUCommandEncoder để mã hóa các lệnh gửi tới GPU
const commandEncoder = device.createCommandEncoder();

// …

// Sao chép output buffer sang staging buffer
commandEncoder.copyBufferToBuffer(
  outputBuffer,
  0, // Độ lệch nguồn
  stagingBuffer,
  0, // Độ lệch đích
  BUFFER_SIZE,
);

// Vì đang sao chép toàn bộ buffer, có thể rút gọn thành
// commandEncoder.copyBufferToBuffer(outputBuffer, stagingBuffer);

// …

Thông số kỹ thuật

Specification
WebGPU
# dom-gpucommandencoder-copybuffertobuffer

Tương thích trình duyệt

Xem thêm