PhysicsBasedAnimationToolkit 0.0.10
Cross-platform C++20 library of algorithms and data structures commonly used in computer graphics research on physically-based simulation.
Loading...
Searching...
No Matches
SynchronizedList.cuh
1#ifndef PBAT_GPU_IMPL_COMMON_SYNCHRONIZEDLIST_H
2#define PBAT_GPU_IMPL_COMMON_SYNCHRONIZEDLIST_H
3
4#include "Buffer.cuh"
5#include "Var.cuh"
6#include "pbat/HostDevice.h"
7#include "pbat/gpu/Aliases.h"
8
9#include <cuda/atomic>
10#include <exception>
11#include <string>
12#include <vector>
13
14namespace pbat {
15namespace gpu {
16namespace impl {
17namespace common {
18
19template <class T>
20class DeviceSynchronizedList
21{
22 public:
23 PBAT_HOST DeviceSynchronizedList(Buffer<T>& buffer, Var<GpuIndex>& size)
24 : mBuffer(buffer.Raw()), mSize(size.Raw()), mCapacity(buffer.Size())
25 {
26 }
27
28 PBAT_DEVICE bool Append(T const& value)
29 {
30 cuda::atomic_ref<GpuIndex, cuda::thread_scope_device> aSize{*mSize};
31 GpuIndex k = aSize++;
32 if (k >= mCapacity)
33 {
34 aSize.store(mCapacity);
35 return false;
36 }
37 mBuffer[k] = value;
38 return true;
39 }
40
41 PBAT_DEVICE T& operator[](auto i)
42 {
43 assert(i >= 0);
44 assert(i < (*mSize));
45 return mBuffer[i];
46 }
47
48 PBAT_DEVICE T const& operator[](auto i) const
49 {
50 assert(i >= 0);
51 assert(i < (*mSize));
52 return mBuffer[i];
53 }
54
55 private:
56 T* mBuffer;
57 GpuIndex* mSize;
58 std::size_t mCapacity;
59};
60
61template <class T>
62class SynchronizedList
63{
64 public:
65 SynchronizedList(std::size_t capacity) : mBuffer(capacity), mSize{0} {}
66 DeviceSynchronizedList<T> Raw() { return DeviceSynchronizedList<T>(mBuffer, mSize); }
67 std::vector<T> Get() const { return mBuffer.Get(mSize.Get()); }
68 void Clear() { mSize = 0; }
69 std::size_t Capacity() const { return mBuffer.Size(); }
70 Buffer<T>& Memory() { return mBuffer; }
71 Buffer<T> const& Memory() const { return mBuffer; }
72 GpuIndex Size() const { return mSize.Get(); }
73 void Resize(GpuIndex size)
74 {
75 if ((size < 0) or (size > mBuffer.Size()))
76 {
77 std::string const what = "Resize called with size outside of range [0,buffer capacity]";
78 throw std::invalid_argument(what);
79 }
80 mSize = size;
81 }
82 auto Begin() { return mBuffer.Data(); }
83 auto End() { return mBuffer.Data() + mSize.Get(); }
84
85 private:
86 Buffer<T> mBuffer;
87 Var<GpuIndex> mSize;
88};
89
90} // namespace common
91} // namespace impl
92} // namespace gpu
93} // namespace pbat
94
95#endif // PBAT_GPU_IMPL_COMMON_SYNCHRONIZEDLIST_H
Definition Buffer.cuh:21
Definition SynchronizedList.cuh:21
Definition Var.cuh:15
Type aliases for GPU code.
GPU algorithm implementations.
Definition VertexTriangleMixedCcdDcd.h:21
GPU related public functionality.
Definition Buffer.cu:16
The main namespace of the library.
Definition Aliases.h:15
std::int32_t GpuIndex
Index type for GPU code.
Definition Aliases.h:20