WebGPUAttributes.js 2.0 KB

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