@@ -257,14 +257,15 @@ class WebGLAttributeUtils {
257257 * a storage buffer attribute from the GPU to the CPU.
258258 *
259259 * @async
260- * @param {StorageBufferAttribute } attribute - The storage buffer attribute .
260+ * @param {ReadbackBuffer } readbackBuffer - The readback buffer.
261261 * @return {Promise<ArrayBuffer> } A promise that resolves with the buffer data when the data are ready.
262262 */
263- async getArrayBufferAsync ( attribute ) {
263+ async getArrayBufferAsync ( readbackBuffer ) {
264264
265265 const backend = this . backend ;
266266 const { gl } = backend ;
267267
268+ const attribute = readbackBuffer . attribute ;
268269 const bufferAttribute = attribute . isInterleavedBufferAttribute ? attribute . data : attribute ;
269270 const { bufferGPU } = backend . get ( bufferAttribute ) ;
270271
@@ -273,10 +274,40 @@ class WebGLAttributeUtils {
273274
274275 gl . bindBuffer ( gl . COPY_READ_BUFFER , bufferGPU ) ;
275276
276- const writeBuffer = gl . createBuffer ( ) ;
277+ const readbackBufferData = backend . get ( readbackBuffer ) ;
277278
278- gl . bindBuffer ( gl . COPY_WRITE_BUFFER , writeBuffer ) ;
279- gl . bufferData ( gl . COPY_WRITE_BUFFER , byteLength , gl . STREAM_READ ) ;
279+ let { writeBuffer } = readbackBufferData ;
280+
281+ if ( writeBuffer === undefined ) {
282+
283+ writeBuffer = gl . createBuffer ( ) ;
284+
285+ gl . bindBuffer ( gl . COPY_WRITE_BUFFER , writeBuffer ) ;
286+ gl . bufferData ( gl . COPY_WRITE_BUFFER , byteLength , gl . STREAM_READ ) ;
287+
288+ // dispose
289+
290+ const dispose = ( ) => {
291+
292+ gl . deleteBuffer ( writeBuffer ) ;
293+
294+ backend . delete ( readbackBuffer ) ;
295+
296+ readbackBuffer . removeEventListener ( 'dispose' , dispose ) ;
297+
298+ } ;
299+
300+ readbackBuffer . addEventListener ( 'dispose' , dispose ) ;
301+
302+ // register
303+
304+ readbackBufferData . writeBuffer = writeBuffer ;
305+
306+ } else {
307+
308+ gl . bindBuffer ( gl . COPY_WRITE_BUFFER , writeBuffer ) ;
309+
310+ }
280311
281312 gl . copyBufferSubData ( gl . COPY_READ_BUFFER , gl . COPY_WRITE_BUFFER , 0 , 0 , byteLength ) ;
282313
@@ -289,12 +320,10 @@ class WebGLAttributeUtils {
289320
290321 gl . getBufferSubData ( gl . COPY_WRITE_BUFFER , 0 , dstBuffer ) ;
291322
292- gl . deleteBuffer ( writeBuffer ) ;
293-
294323 gl . bindBuffer ( gl . COPY_READ_BUFFER , null ) ;
295324 gl . bindBuffer ( gl . COPY_WRITE_BUFFER , null ) ;
296325
297- return dstBuffer . buffer ;
326+ return dstBuffer ;
298327
299328 }
300329
0 commit comments