WebGPUAttributes.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. class WebGPUAttributes {
  2. constructor( device ) {
  3. this.buffers = new WeakMap();
  4. this.device = device;
  5. }
  6. get( attribute ) {
  7. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8. return this.buffers.get( attribute );
  9. }
  10. remove( attribute ) {
  11. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  12. const data = this.buffers.get( attribute );
  13. if ( data ) {
  14. data.buffer.destroy();
  15. this.buffers.delete( attribute );
  16. }
  17. }
  18. update( attribute, isIndex = false, usage = null ) {
  19. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20. let data = this.buffers.get( attribute );
  21. if ( data === undefined ) {
  22. if ( usage === null ) {
  23. usage = ( isIndex === true ) ? GPUBufferUsage.INDEX : GPUBufferUsage.VERTEX;
  24. }
  25. data = this._createBuffer( attribute, usage );
  26. this.buffers.set( attribute, data );
  27. } else if ( usage && usage !== data.usage ) {
  28. data.buffer.destroy();
  29. data = this._createBuffer( attribute, usage );
  30. this.buffers.set( attribute, data );
  31. } else if ( data.version < attribute.version ) {
  32. this._writeBuffer( data.buffer, attribute );
  33. data.version = attribute.version;
  34. }
  35. }
  36. _createBuffer( attribute, usage ) {
  37. const array = attribute.array;
  38. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  39. const buffer = this.device.createBuffer( {
  40. size: size,
  41. usage: usage | GPUBufferUsage.COPY_DST,
  42. mappedAtCreation: true,
  43. } );
  44. new array.constructor( buffer.getMappedRange() ).set( array );
  45. buffer.unmap();
  46. attribute.onUploadCallback();
  47. return {
  48. version: attribute.version,
  49. buffer: buffer,
  50. usage: usage
  51. };
  52. }
  53. _writeBuffer( buffer, attribute ) {
  54. const array = attribute.array;
  55. const updateRange = attribute.updateRange;
  56. if ( updateRange.count === - 1 ) {
  57. // Not using update ranges
  58. this.device.queue.writeBuffer(
  59. buffer,
  60. 0,
  61. array,
  62. 0
  63. );
  64. } else {
  65. this.device.queue.writeBuffer(
  66. buffer,
  67. 0,
  68. array,
  69. updateRange.offset * array.BYTES_PER_ELEMENT,
  70. updateRange.count * array.BYTES_PER_ELEMENT
  71. );
  72. updateRange.count = - 1; // reset range
  73. }
  74. }
  75. }
  76. export default WebGPUAttributes;