import '../../../../globals.js';
// Copyright 2023-2024, University of Colorado Boulder
/**
 * A GPUBuffer that is typed to a specific type, and can be used to encode/decode values to/from it.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */
import { alpenglow, ByteEncoder, getArrayType, webgpu } from '../../imports.js';
export default class TypedBuffer {
    constructor(buffer, type) {
        this.buffer = buffer;
        this.type = type;
    }
    setValue(device, value) {
        const encoder = new ByteEncoder();
        this.type.encode(value, encoder);
        webgpu.deviceWriteBuffer(device, this.buffer, 0, encoder.fullArrayBuffer, 0, encoder.byteLength);
    }
    async getValue(encoder, bufferLogger) {
        const arrayBuffer = await bufferLogger.arrayBuffer(encoder, this.buffer);
        return this.type.decode(new ByteEncoder(arrayBuffer), 0);
    }
    dispose() {
        webgpu.bufferDestroy(this.buffer);
    }
    static createArray(deviceContext, type, size, outOfRangeElement) {
        const buffer = deviceContext.createBuffer(size * type.bytesPerElement);
        return new TypedBuffer(buffer, getArrayType(type, size, outOfRangeElement));
    }
    static createArrayFromData(deviceContext, type, data) {
        const buffer = deviceContext.createBuffer(data.length * type.bytesPerElement);
        const typedBuffer = new TypedBuffer(buffer, getArrayType(type, data.length));
        typedBuffer.setValue(deviceContext.device, data);
        return typedBuffer;
    }
    static wrapArray(buffer, type, outOfRangeElement, size = 0) {
        if (size === 0) {
            size = Math.floor(buffer.size / type.bytesPerElement);
        }
        return new TypedBuffer(buffer, getArrayType(type, size, outOfRangeElement));
    }
}
alpenglow.register('TypedBuffer', TypedBuffer);
//# sourceMappingURL=TypedBuffer.js.map