1 // Copyright 2021 The Dawn Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef DAWN_NODE_BINDING_GPUBUFFER_H_ 16 #define DAWN_NODE_BINDING_GPUBUFFER_H_ 17 18 #include "dawn/webgpu_cpp.h" 19 #include "dawn_native/DawnNative.h" 20 #include "napi.h" 21 #include "src/dawn_node/binding/AsyncRunner.h" 22 #include "src/dawn_node/interop/WebGPU.h" 23 24 namespace wgpu { namespace binding { 25 26 // GPUBuffer is an implementation of interop::GPUBuffer that wraps a wgpu::Buffer. 27 class GPUBuffer final : public interop::GPUBuffer { 28 public: 29 GPUBuffer(wgpu::Buffer buffer, 30 wgpu::BufferDescriptor desc, 31 wgpu::Device device, 32 std::shared_ptr<AsyncRunner> async); 33 34 // Desc() returns the wgpu::BufferDescriptor used to construct the buffer Desc()35 const wgpu::BufferDescriptor& Desc() const { 36 return desc_; 37 } 38 39 // Implicit cast operator to Dawn GPU object 40 inline operator const wgpu::Buffer &() const { 41 return buffer_; 42 } 43 44 // interop::GPUBuffer interface compliance 45 interop::Promise<void> mapAsync(Napi::Env env, 46 interop::GPUMapModeFlags mode, 47 interop::GPUSize64 offset, 48 std::optional<interop::GPUSize64> size) override; 49 interop::ArrayBuffer getMappedRange(Napi::Env env, 50 interop::GPUSize64 offset, 51 std::optional<interop::GPUSize64> size) override; 52 void unmap(Napi::Env) override; 53 void destroy(Napi::Env) override; 54 std::optional<std::string> getLabel(Napi::Env) override; 55 void setLabel(Napi::Env, std::optional<std::string> value) override; 56 57 private: 58 struct Mapping { 59 uint64_t start; 60 uint64_t end; IntersectsMapping61 inline bool Intersects(uint64_t s, uint64_t e) const { 62 return s < end && e > start; 63 } 64 Napi::Reference<interop::ArrayBuffer> buffer; 65 }; 66 67 // https://www.w3.org/TR/webgpu/#buffer-interface 68 enum class State { 69 Unmapped, 70 Mapped, 71 MappedAtCreation, 72 MappingPending, 73 Destroyed, 74 }; 75 76 wgpu::Buffer buffer_; 77 wgpu::BufferDescriptor const desc_; 78 wgpu::Device const device_; 79 std::shared_ptr<AsyncRunner> async_; 80 State state_ = State::Unmapped; 81 std::vector<Mapping> mapped_; 82 }; 83 84 }} // namespace wgpu::binding 85 86 #endif // DAWN_NODE_BINDING_GPUBUFFER_H_ 87