react-native-webgpu 0.19.2 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/Package.swift +19 -7
  2. package/android/CMakeLists.txt +1 -0
  3. package/android/build.gradle +7 -0
  4. package/android/cpp/cpp-adapter.cpp +23 -1
  5. package/android/src/main/java/com/webgpu/WebGPUModule.java +34 -3
  6. package/apple/ApplePlatformContext.h +6 -1
  7. package/apple/ApplePlatformContext.mm +7 -8
  8. package/apple/AppleVideoPlayer.mm +21 -11
  9. package/apple/MetalLayerColorSpace.mm +24 -1
  10. package/apple/WebGPUModule.mm +30 -1
  11. package/cpp/jsi/Promise.cpp +4 -0
  12. package/cpp/jsi/Promise.h +3 -0
  13. package/cpp/rnwgpu/CanvasColorSpace.h +5 -0
  14. package/cpp/rnwgpu/DawnBlobCache.cpp +477 -0
  15. package/cpp/rnwgpu/DawnBlobCache.h +76 -0
  16. package/cpp/rnwgpu/RNWebGPUManager.cpp +2 -4
  17. package/cpp/rnwgpu/SurfaceRegistry.h +16 -7
  18. package/cpp/rnwgpu/WebGPURuntime.cpp +2 -1
  19. package/cpp/rnwgpu/api/GPU.cpp +6 -6
  20. package/cpp/rnwgpu/api/GPU.h +1 -1
  21. package/cpp/rnwgpu/api/GPUAdapter.cpp +43 -7
  22. package/cpp/rnwgpu/api/GPUBuffer.cpp +5 -6
  23. package/cpp/rnwgpu/api/GPUCanvasContext.cpp +2 -1
  24. package/cpp/rnwgpu/api/GPUDevice.cpp +165 -48
  25. package/cpp/rnwgpu/api/GPUDevice.h +67 -14
  26. package/cpp/rnwgpu/api/GPUQueue.cpp +11 -2
  27. package/cpp/rnwgpu/api/GPUQueue.h +7 -2
  28. package/cpp/rnwgpu/api/GPUShaderModule.cpp +2 -2
  29. package/cpp/rnwgpu/api/RNWebGPU.h +11 -10
  30. package/cpp/rnwgpu/api/descriptors/GPUCanvasConfiguration.h +24 -0
  31. package/cpp/rnwgpu/async/AsyncTaskHandle.cpp +33 -45
  32. package/cpp/rnwgpu/async/AsyncTaskHandle.h +5 -6
  33. package/cpp/rnwgpu/async/RuntimeContext.cpp +321 -112
  34. package/cpp/rnwgpu/async/RuntimeContext.h +90 -82
  35. package/lib/commonjs/Canvas.js +1 -0
  36. package/lib/commonjs/Canvas.js.map +1 -1
  37. package/lib/commonjs/WebGPUViewNativeComponent.js.map +1 -1
  38. package/lib/commonjs/WebGPUViewNativeComponent.web.js.map +1 -1
  39. package/lib/commonjs/external/reanimated/registerWebGPUForReanimated.js +19 -1
  40. package/lib/commonjs/external/reanimated/registerWebGPUForReanimated.js.map +1 -1
  41. package/lib/commonjs/install.js +6 -5
  42. package/lib/commonjs/install.js.map +1 -1
  43. package/lib/module/Canvas.js +1 -0
  44. package/lib/module/Canvas.js.map +1 -1
  45. package/lib/module/WebGPUViewNativeComponent.js.map +1 -1
  46. package/lib/module/WebGPUViewNativeComponent.web.js.map +1 -1
  47. package/lib/module/external/reanimated/registerWebGPUForReanimated.js +19 -1
  48. package/lib/module/external/reanimated/registerWebGPUForReanimated.js.map +1 -1
  49. package/lib/module/install.js +6 -5
  50. package/lib/module/install.js.map +1 -1
  51. package/lib/typescript/lib/commonjs/Canvas.d.ts.map +1 -1
  52. package/lib/typescript/lib/commonjs/external/reanimated/registerWebGPUForReanimated.d.ts.map +1 -1
  53. package/lib/typescript/lib/commonjs/install.d.ts +6 -5
  54. package/lib/typescript/lib/commonjs/install.d.ts.map +1 -1
  55. package/lib/typescript/lib/module/Canvas.d.ts.map +1 -1
  56. package/lib/typescript/lib/module/external/reanimated/registerWebGPUForReanimated.d.ts.map +1 -1
  57. package/lib/typescript/lib/module/install.d.ts.map +1 -1
  58. package/lib/typescript/src/Canvas.d.ts.map +1 -1
  59. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts +6 -7
  60. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts.map +1 -1
  61. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts +2 -3
  62. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  63. package/lib/typescript/src/external/reanimated/registerWebGPUForReanimated.d.ts +1 -0
  64. package/lib/typescript/src/external/reanimated/registerWebGPUForReanimated.d.ts.map +1 -1
  65. package/lib/typescript/src/install.d.ts +6 -5
  66. package/lib/typescript/src/install.d.ts.map +1 -1
  67. package/package.json +3 -2
  68. package/src/Canvas.tsx +4 -2
  69. package/src/WebGPUViewNativeComponent.ts +6 -10
  70. package/src/WebGPUViewNativeComponent.web.ts +2 -3
  71. package/src/external/reanimated/registerWebGPUForReanimated.ts +21 -1
  72. package/src/install.ts +6 -5
@@ -0,0 +1,477 @@
1
+ #include "DawnBlobCache.h"
2
+
3
+ #include <dirent.h>
4
+ #include <sys/stat.h>
5
+ #include <unistd.h>
6
+
7
+ #include <chrono>
8
+ #include <condition_variable>
9
+ #include <cstdint>
10
+ #include <cstdio>
11
+ #include <cstring>
12
+ #include <ctime>
13
+ #include <deque>
14
+ #include <functional>
15
+ #include <mutex>
16
+ #include <string>
17
+ #include <system_error>
18
+ #include <thread>
19
+ #include <utility>
20
+ #include <vector>
21
+
22
+ namespace rnwgpu {
23
+
24
+ namespace {
25
+
26
+ // Entries only accumulate as an app's shaders change from release to release.
27
+ // A cache found past this size when it is set up is cleared, and a session
28
+ // whose stores would take it past this size drops them until the next setup.
29
+ constexpr off_t kMaxCacheBytes = 64 * 1024 * 1024;
30
+
31
+ // An entry this large is not stored, so that one entry cannot take more than
32
+ // half the cache from all the others. The entry already on disk under its key,
33
+ // if any, is left as it is, and a blob that has outgrown this stops being
34
+ // updated.
35
+ constexpr off_t kMaxEntryBytes = kMaxCacheBytes / 2;
36
+
37
+ // A temporary file this old is taken for a write that will never finish (its
38
+ // process was killed). A younger one may still be being written by another
39
+ // process using the same cache, so it is left. A writer suspended for longer
40
+ // than this loses its entry (its rename fails), which only costs a cache miss.
41
+ constexpr time_t kAbandonedWriteSeconds = 60;
42
+
43
+ // Before a store is dropped for taking the cache past its limit, the
44
+ // directory is measured again, in case the entries counted so far are gone.
45
+ // Not before every one, though: a session at its limit may be refused a store
46
+ // per shader it compiles, and a measure reads every entry. The directory is
47
+ // measured again when its modification time changed since the last measure
48
+ // (an entry written to it or removed from it, by anyone, changes it) and, as
49
+ // that time can be coarse, when the last measure is this old.
50
+ constexpr std::chrono::seconds kMeasureAgainAfter{10};
51
+
52
+ // Never destroyed: a store can still be queued when the process starts to
53
+ // exit.
54
+ std::mutex &directoryMutex() {
55
+ static std::mutex *const mutex = new std::mutex;
56
+ return *mutex;
57
+ }
58
+
59
+ std::string &directorySlot() {
60
+ static std::string *const directory = new std::string;
61
+ return *directory;
62
+ }
63
+
64
+ std::string directory() {
65
+ std::lock_guard<std::mutex> lock(directoryMutex());
66
+ return directorySlot();
67
+ }
68
+
69
+ // Stores refused on this thread because the entry was too large. Dawn stores
70
+ // on the thread that has it write (see refusedStoresOnThisThread()).
71
+ thread_local uint64_t refusedStores = 0;
72
+
73
+ // Everything that changes the directory runs here, one job after another: the
74
+ // tidying of setDirectory() and the stores. Dawn stores from the thread that
75
+ // compiles, a JS thread included, and holds the device's lock while it stores
76
+ // its pipeline cache, so none of them should wait for the disk. Never
77
+ // destroyed, so a job queued as the process exits never runs into a destroyed
78
+ // queue; a write cut short by the exit leaves a temporary file the next setup
79
+ // removes.
80
+ class Writer {
81
+ public:
82
+ static Writer &shared() {
83
+ static Writer *const writer = new Writer;
84
+ return *writer;
85
+ }
86
+
87
+ // Queues `job` for the thread. Without a thread to be had (a process at its
88
+ // limit) the jobs queued so far are dropped, not run here: a store run on
89
+ // Dawn's thread would keep it waiting for the disk, and two run at once
90
+ // would write the same temporary file. The next post tries for a thread
91
+ // again, and the first store to run tidies the directory in place of the
92
+ // tidying dropped (see writeEntry).
93
+ void post(std::function<void()> job) {
94
+ std::lock_guard<std::mutex> lock(_mutex);
95
+ _queue.push_back(std::move(job));
96
+ if (!_started) {
97
+ try {
98
+ std::thread([this] { run(); }).detach();
99
+ _started = true;
100
+ } catch (const std::system_error &) {
101
+ _queue.clear();
102
+ return;
103
+ }
104
+ }
105
+ _wake.notify_one();
106
+ }
107
+
108
+ // Blocks until every job posted so far has run.
109
+ void wait() {
110
+ std::unique_lock<std::mutex> lock(_mutex);
111
+ _idle.wait(lock, [this] { return _queue.empty() && !_busy; });
112
+ }
113
+
114
+ // The directory last tidied, and the bytes of the entries in it: what the
115
+ // tidying found, plus what this session stored since. Read and written by
116
+ // jobs only.
117
+ std::string tidied;
118
+ off_t total = 0;
119
+
120
+ // When the directory was last measured: its modification time then, and the
121
+ // time (see kMeasureAgainAfter). Read and written by jobs only.
122
+ timespec measuredModification{};
123
+ std::chrono::steady_clock::time_point measuredAt{};
124
+
125
+ private:
126
+ void run() {
127
+ std::unique_lock<std::mutex> lock(_mutex);
128
+ for (;;) {
129
+ _wake.wait(lock, [this] { return !_queue.empty(); });
130
+ std::function<void()> job = std::move(_queue.front());
131
+ _queue.pop_front();
132
+ _busy = true;
133
+ lock.unlock();
134
+ try {
135
+ job();
136
+ } catch (...) {
137
+ // Out of memory, most likely. The cache is best effort, and a write
138
+ // cut short leaves a temporary file the next setup removes; on a
139
+ // detached thread the exception would end the process instead.
140
+ }
141
+ // Frees the job's copy of the blob before the queue is locked again.
142
+ job = nullptr;
143
+ lock.lock();
144
+ _busy = false;
145
+ if (_queue.empty()) {
146
+ _idle.notify_all();
147
+ }
148
+ }
149
+ }
150
+
151
+ std::mutex _mutex;
152
+ std::condition_variable _wake;
153
+ std::condition_variable _idle;
154
+ std::deque<std::function<void()>> _queue;
155
+ bool _started = false;
156
+ bool _busy = false;
157
+ };
158
+
159
+ // Creates `dir` and any of its parents that are missing.
160
+ void makeDirectories(const std::string &dir) {
161
+ for (size_t slash = dir.find('/', 1); slash != std::string::npos;
162
+ slash = dir.find('/', slash + 1)) {
163
+ mkdir(dir.substr(0, slash).c_str(), 0700);
164
+ }
165
+ mkdir(dir.c_str(), 0700);
166
+ }
167
+
168
+ // One file per entry, named by a 64-bit FNV-1a hash of its key.
169
+ std::string entryPath(const std::string &dir, size_t keySize,
170
+ const uint8_t *key) {
171
+ uint64_t hash = 14695981039346656037ull;
172
+ for (size_t i = 0; i < keySize; ++i) {
173
+ hash ^= key[i];
174
+ hash *= 1099511628211ull;
175
+ }
176
+ char name[18];
177
+ snprintf(name, sizeof(name), "/%016llx",
178
+ static_cast<unsigned long long>(hash));
179
+ return dir + name;
180
+ }
181
+
182
+ off_t entryBytes(size_t keySize, size_t valueSize) {
183
+ return static_cast<off_t>(2 * sizeof(uint64_t) + keySize + valueSize);
184
+ }
185
+
186
+ timespec modificationTime(const struct stat &info) {
187
+ #ifdef __APPLE__
188
+ return info.st_mtimespec;
189
+ #else
190
+ return info.st_mtim;
191
+ #endif
192
+ }
193
+
194
+ // What measure() found in the directory.
195
+ struct Contents {
196
+ std::vector<std::string> entries;
197
+ off_t bytes = 0;
198
+ };
199
+
200
+ Contents measure(const std::string &dir);
201
+ void tidy(const std::string &dir);
202
+
203
+ // Whether the directory may hold other entries than the last measure found:
204
+ // it was changed since, or is gone, or the measure is old enough for its
205
+ // modification time to be the same as then although it was changed (see
206
+ // kMeasureAgainAfter). Runs on the writer.
207
+ bool changedSinceMeasured(const std::string &dir) {
208
+ const Writer &writer = Writer::shared();
209
+ if (std::chrono::steady_clock::now() - writer.measuredAt >
210
+ kMeasureAgainAfter) {
211
+ return true;
212
+ }
213
+ struct stat info{};
214
+ if (stat(dir.c_str(), &info) != 0) {
215
+ return true;
216
+ }
217
+ const timespec modified = modificationTime(info);
218
+ return modified.tv_sec != writer.measuredModification.tv_sec ||
219
+ modified.tv_nsec != writer.measuredModification.tv_nsec;
220
+ }
221
+
222
+ // An entry is the key's size, the value's size, the key and the value. The
223
+ // stored key is compared on load, so a hash collision reads as a miss, and so
224
+ // does an entry shorter than its recorded size. Dawn asks for the size first
225
+ // (no buffer), then for the value.
226
+ size_t loadEntry(size_t keySize, const uint8_t *key, size_t valueSize,
227
+ uint8_t *value, void * /* userdata1 */,
228
+ void * /* userdata2 */) {
229
+ const std::string dir = directory();
230
+ if (dir.empty()) {
231
+ return 0;
232
+ }
233
+ FILE *file = fopen(entryPath(dir, keySize, key).c_str(), "rb");
234
+ if (file == nullptr) {
235
+ return 0;
236
+ }
237
+ size_t result = 0;
238
+ uint64_t sizes[2] = {0, 0};
239
+ if (fread(sizes, sizeof(sizes), 1, file) == 1 && sizes[0] == keySize) {
240
+ std::vector<uint8_t> storedKey(keySize);
241
+ if (fread(storedKey.data(), 1, keySize, file) == keySize &&
242
+ memcmp(storedKey.data(), key, keySize) == 0) {
243
+ const long start = ftell(file);
244
+ fseek(file, 0, SEEK_END);
245
+ const size_t stored = static_cast<size_t>(ftell(file) - start);
246
+ if (stored == sizes[1]) {
247
+ if (value == nullptr || valueSize == 0) {
248
+ result = stored;
249
+ } else if (valueSize >= stored) {
250
+ fseek(file, start, SEEK_SET);
251
+ result = fread(value, 1, stored, file) == stored ? stored : 0;
252
+ }
253
+ }
254
+ }
255
+ }
256
+ fclose(file);
257
+ return result;
258
+ }
259
+
260
+ // Written aside and renamed into place, so a load on another thread never
261
+ // sees half an entry. Runs on the writer.
262
+ void writeEntry(const std::string &dir, const std::vector<uint8_t> &key,
263
+ const std::vector<uint8_t> &value) {
264
+ Writer &writer = Writer::shared();
265
+ // The tidying of setDirectory() has not run for this directory: it was
266
+ // dropped for want of a thread then, or this store was queued ahead of it,
267
+ // or the store is bound for a directory set before the current one. Done
268
+ // now, so that the store is counted against its own directory.
269
+ if (writer.tidied != dir) {
270
+ tidy(dir);
271
+ }
272
+ const std::string path = entryPath(dir, key.size(), key.data());
273
+ const off_t bytes = entryBytes(key.size(), value.size());
274
+ struct stat replaced{};
275
+ const off_t previousBytes =
276
+ stat(path.c_str(), &replaced) == 0 ? replaced.st_size : 0;
277
+ if (previousBytes == 0) {
278
+ // A new entry, unless the system or the app cleared the cache directory,
279
+ // or its parent, during the session: then it has to be made again.
280
+ struct stat info{};
281
+ if (stat(dir.c_str(), &info) != 0) {
282
+ makeDirectories(dir);
283
+ }
284
+ }
285
+ // Past the limit the cache stops growing until the next setup clears it.
286
+ // Replacing an entry with one no larger is not growth: Dawn's monolithic
287
+ // pipeline cache is one entry stored over and over. Before a store is
288
+ // dropped the directory is measured again, if it may have changed, since
289
+ // the entries counted so far may be gone: the system clears app caches as
290
+ // it needs the space (iOS removes the files, not always the directory), and
291
+ // so may the app.
292
+ const off_t growth = bytes > previousBytes ? bytes - previousBytes : 0;
293
+ if (growth > 0 && writer.total + growth > kMaxCacheBytes) {
294
+ if (changedSinceMeasured(dir)) {
295
+ writer.total = measure(dir).bytes;
296
+ }
297
+ if (writer.total + growth > kMaxCacheBytes) {
298
+ return;
299
+ }
300
+ }
301
+ const std::string temporary = path + "." + std::to_string(getpid()) + ".tmp";
302
+ FILE *file = fopen(temporary.c_str(), "wb");
303
+ if (file == nullptr) {
304
+ return;
305
+ }
306
+ const uint64_t sizes[2] = {key.size(), value.size()};
307
+ bool written = fwrite(sizes, sizeof(sizes), 1, file) == 1 &&
308
+ fwrite(key.data(), 1, key.size(), file) == key.size() &&
309
+ fwrite(value.data(), 1, value.size(), file) == value.size();
310
+ written = fclose(file) == 0 && written;
311
+ if (!written || rename(temporary.c_str(), path.c_str()) != 0) {
312
+ remove(temporary.c_str());
313
+ return;
314
+ }
315
+ writer.total += bytes - previousBytes;
316
+ }
317
+
318
+ // Dawn's buffers last only for this call: the bytes are copied, and written
319
+ // later on the writer.
320
+ void storeEntry(size_t keySize, const uint8_t *key, size_t valueSize,
321
+ const uint8_t *value, void * /* userdata1 */,
322
+ void * /* userdata2 */) {
323
+ const std::string dir = directory();
324
+ if (dir.empty()) {
325
+ return;
326
+ }
327
+ if (entryBytes(keySize, valueSize) > kMaxEntryBytes) {
328
+ refusedStores++;
329
+ return;
330
+ }
331
+ Writer::shared().post(
332
+ [dir, key = std::vector<uint8_t>(key, key + keySize),
333
+ value = std::vector<uint8_t>(value, value + valueSize)] {
334
+ writeEntry(dir, key, value);
335
+ });
336
+ }
337
+
338
+ enum class Kind { Entry, Temporary, Other };
339
+
340
+ // An entry's name is 16 lowercase hex digits. A temporary file's is one
341
+ // followed by a dot, the writing process's id and ".tmp". Anything else in
342
+ // the directory is not the cache's to remove.
343
+ Kind kindOf(const std::string &name) {
344
+ if (name.size() < 16) {
345
+ return Kind::Other;
346
+ }
347
+ for (size_t i = 0; i < 16; i++) {
348
+ const char c = name[i];
349
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
350
+ return Kind::Other;
351
+ }
352
+ }
353
+ if (name.size() == 16) {
354
+ return Kind::Entry;
355
+ }
356
+ if (name[16] != '.') {
357
+ return Kind::Other;
358
+ }
359
+ size_t i = 17;
360
+ while (i < name.size() && name[i] >= '0' && name[i] <= '9') {
361
+ i++;
362
+ }
363
+ return i > 17 && name.compare(i, std::string::npos, ".tmp") == 0
364
+ ? Kind::Temporary
365
+ : Kind::Other;
366
+ }
367
+
368
+ // Remembers the directory as measured now, as it is (see
369
+ // changedSinceMeasured). Runs on the writer.
370
+ void noteMeasured(const std::string &dir) {
371
+ Writer &writer = Writer::shared();
372
+ struct stat info{};
373
+ writer.measuredModification =
374
+ stat(dir.c_str(), &info) == 0 ? modificationTime(info) : timespec{};
375
+ writer.measuredAt = std::chrono::steady_clock::now();
376
+ }
377
+
378
+ // The entries in the directory and their bytes together: none when the
379
+ // directory is gone. Removes the temporary files of writes a killed process
380
+ // left unfinished on the way. Runs on the writer.
381
+ Contents measure(const std::string &dir) {
382
+ Contents contents;
383
+ if (DIR *listing = opendir(dir.c_str())) {
384
+ const time_t now = time(nullptr);
385
+ while (dirent *entry = readdir(listing)) {
386
+ const std::string name = entry->d_name;
387
+ const Kind kind = kindOf(name);
388
+ if (kind == Kind::Other) {
389
+ continue;
390
+ }
391
+ const std::string path = dir + "/" + name;
392
+ struct stat info{};
393
+ if (stat(path.c_str(), &info) != 0) {
394
+ continue;
395
+ }
396
+ if (kind == Kind::Temporary) {
397
+ if (now - info.st_mtime > kAbandonedWriteSeconds) {
398
+ remove(path.c_str());
399
+ }
400
+ continue;
401
+ }
402
+ contents.bytes += info.st_size;
403
+ contents.entries.push_back(path);
404
+ }
405
+ closedir(listing);
406
+ }
407
+ noteMeasured(dir);
408
+ return contents;
409
+ }
410
+
411
+ // Measures the directory, and removes every entry when together they are past
412
+ // kMaxCacheBytes: a cache that has outgrown the limit holds mostly what the
413
+ // app no longer uses, and one launch that builds everything is the price of
414
+ // starting over. Leaves the writer's total at what the directory holds. Runs
415
+ // on the writer.
416
+ void tidy(const std::string &dir) {
417
+ Writer &writer = Writer::shared();
418
+ Contents contents = measure(dir);
419
+ if (contents.bytes > kMaxCacheBytes) {
420
+ for (const auto &path : contents.entries) {
421
+ remove(path.c_str());
422
+ }
423
+ contents.bytes = 0;
424
+ noteMeasured(dir);
425
+ }
426
+ writer.total = contents.bytes;
427
+ writer.tidied = dir;
428
+ }
429
+
430
+ } // namespace
431
+
432
+ void DawnBlobCache::setDirectory(const std::string &dir) {
433
+ std::string usable = dir;
434
+ if (!usable.empty()) {
435
+ makeDirectories(usable);
436
+ struct stat info{};
437
+ if (stat(usable.c_str(), &info) != 0 || !S_ISDIR(info.st_mode)) {
438
+ // Nowhere to keep blobs: leave the cache off rather than fail every
439
+ // load and store.
440
+ usable.clear();
441
+ }
442
+ }
443
+ {
444
+ std::lock_guard<std::mutex> lock(directoryMutex());
445
+ directorySlot() = usable;
446
+ }
447
+ // Posted once the directory is in use, so that a store that reaches the
448
+ // writer first is bound for this directory, and counted by the tidying. A
449
+ // store still bound for the previous directory, queued after the tidying,
450
+ // is counted against that one (see writeEntry).
451
+ if (!usable.empty()) {
452
+ Writer::shared().post([usable] { tidy(usable); });
453
+ }
454
+ }
455
+
456
+ bool DawnBlobCache::chain(wgpu::DeviceDescriptor &descriptor,
457
+ WGPUDawnCacheDeviceDescriptor &storage) {
458
+ if (directory().empty()) {
459
+ return false;
460
+ }
461
+ storage.dawnLoadCacheDataCallbackInfo.callback = loadEntry;
462
+ storage.dawnStoreCacheDataCallbackInfo.callback = storeEntry;
463
+ storage.chain.next = reinterpret_cast<WGPUChainedStruct *>(
464
+ const_cast<wgpu::ChainedStruct *>(descriptor.nextInChain));
465
+ descriptor.nextInChain = reinterpret_cast<wgpu::ChainedStruct *>(&storage);
466
+ return true;
467
+ }
468
+
469
+ void DawnBlobCache::post(std::function<void()> job) {
470
+ Writer::shared().post(std::move(job));
471
+ }
472
+
473
+ uint64_t DawnBlobCache::refusedStoresOnThisThread() { return refusedStores; }
474
+
475
+ void DawnBlobCache::waitForWrites() { Writer::shared().wait(); }
476
+
477
+ } // namespace rnwgpu
@@ -0,0 +1,76 @@
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+ #include <functional>
5
+ #include <string>
6
+
7
+ #include "webgpu/webgpu_cpp.h"
8
+
9
+ namespace rnwgpu {
10
+
11
+ // Dawn's blob cache, kept on disk so what a device produces while building
12
+ // shaders and pipelines (Vulkan pipeline data, translated MSL) survives a
13
+ // relaunch. Dawn only reuses those blobs across launches when the embedder
14
+ // gives it storage: load and store callbacks on the device descriptor, or a
15
+ // caching interface on the platform the instance was created with (how Chrome
16
+ // does it). The instance can be React Native Skia's, so the callbacks go on
17
+ // each device. Without them every launch builds every pipeline from scratch,
18
+ // and on Vulkan drivers that can take a noticeable time per pipeline.
19
+ //
20
+ // Each platform's module points the cache at the app's cache directory when it
21
+ // installs, and requestDevice() chains it onto every device it creates. A
22
+ // device requested with the `disable_blob_cache` Dawn toggle does not use it.
23
+ //
24
+ // Loads read the file on the calling thread, since Dawn needs the bytes
25
+ // before it goes on. Stores copy the bytes and return: a thread of the cache's
26
+ // own writes them, so neither the thread Dawn compiles on (a JS thread
27
+ // included) nor a device lock Dawn holds while it stores waits for the disk.
28
+ //
29
+ // The cache is best effort. By default Dawn checks a hash of every blob it
30
+ // loads, and an entry that is torn, truncated or for another key reads as a
31
+ // miss. Entries are replaced whole, so the writer that finishes last wins:
32
+ // devices or processes that share a key (Dawn's monolithic Vulkan pipeline
33
+ // cache has one per device) can replace a fuller blob with a smaller one,
34
+ // which only costs the pipelines in it being built again.
35
+ class DawnBlobCache {
36
+ public:
37
+ // The directory to keep the blobs in, created (with its parents) if
38
+ // missing. Each platform's module calls this when it installs. The cache is
39
+ // then tidied on its own thread: abandoned writes are removed, and when the
40
+ // entries together are past the limit (about 64 MB) all of them are, so that
41
+ // a cache full of what the app no longer uses starts over, at the price of
42
+ // one launch that builds everything. A session whose stores would take the
43
+ // cache past the limit drops them (replacing an entry with one no larger is
44
+ // never dropped), and an entry larger than half the limit is not stored.
45
+ // Only the cache's own files are ever removed. An empty path, or one where
46
+ // no directory can be made, leaves the cache off.
47
+ static void setDirectory(const std::string &directory);
48
+
49
+ // Chains the cache onto `descriptor`, in front of whatever it already
50
+ // chains, and returns true. `storage` holds the chained struct and must
51
+ // outlive the RequestDevice call that reads it. Does nothing, and returns
52
+ // false, without a directory.
53
+ static bool chain(wgpu::DeviceDescriptor &descriptor,
54
+ WGPUDawnCacheDeviceDescriptor &storage);
55
+
56
+ // Runs `job` on the cache's thread, after the jobs queued so far (the
57
+ // tidying, the stores), or not at all when no thread can be had. GPUDevice
58
+ // has Dawn write a device's pipeline cache there (flushPipelineCacheIfDue),
59
+ // so that the thread submitting a frame does not wait while Dawn serializes
60
+ // it.
61
+ static void post(std::function<void()> job);
62
+
63
+ // How many stores asked for on the calling thread the cache has refused
64
+ // because the entry was too large (see setDirectory). Dawn stores on the
65
+ // thread that has it write, so a flush (GPUDevice::flushPipelineCache) that
66
+ // sees this grow learns that the device's pipeline cache has outgrown what
67
+ // the cache keeps, and stops having Dawn serialize it.
68
+ static uint64_t refusedStoresOnThisThread();
69
+
70
+ // Blocks until the cache's thread has done everything asked of it so far:
71
+ // the tidying of setDirectory(), the stores and the posted jobs. Nothing in
72
+ // an app needs to wait for a write; tests do.
73
+ static void waitForWrites();
74
+ };
75
+
76
+ } // namespace rnwgpu
@@ -64,10 +64,8 @@ RNWebGPUManager::RNWebGPUManager(
64
64
  : _jsRuntime(jsRuntime), _jsCallInvoker(jsCallInvoker),
65
65
  _platformContext(platformContext) {
66
66
 
67
- // Register the main runtime + its CallInvoker so spontaneous events
68
- // (device.lost / uncapturederror) on main-runtime devices can be delivered to
69
- // the JS thread without the ProcessEvents pump. Worklet-runtime devices have
70
- // no invoker (best-effort; see README "Threading model").
67
+ // Register the main runtime + its CallInvoker: how async results reach the
68
+ // main runtime, and the way to the UI runtime (see async::RuntimeContext).
71
69
  async::RuntimeContext::registerMainRuntime(_jsRuntime, _jsCallInvoker);
72
70
 
73
71
  // Expose the platform context to API objects created later without a
@@ -39,11 +39,13 @@ namespace rnwgpu {
39
39
 
40
40
  #ifdef __APPLE__
41
41
  // Tags the CAMetalLayer with the colorspace matching the configured texture
42
- // format and the canvas's colorSpace. Implemented in
42
+ // format and the canvas's colorSpace, and opts it into the display's extended
43
+ // dynamic range for an "extended" toneMapping mode. Implemented in
43
44
  // apple/MetalLayerColorSpace.mm.
44
45
  void applyCAMetalLayerColorSpace(void *nativeSurface,
45
46
  wgpu::TextureFormat format,
46
- CanvasColorSpace colorSpace);
47
+ CanvasColorSpace colorSpace,
48
+ CanvasToneMappingMode toneMappingMode);
47
49
  #endif
48
50
 
49
51
  struct NativeInfo {
@@ -297,7 +299,8 @@ public:
297
299
  }
298
300
  configureSurfaceLocked(config);
299
301
  #ifdef __APPLE__
300
- applyCAMetalLayerColorSpace(_nativeSurface, _config.format, _colorSpace);
302
+ applyCAMetalLayerColorSpace(_nativeSurface, _config.format, _colorSpace,
303
+ _toneMappingMode);
301
304
  #endif
302
305
  if (blit) {
303
306
  presentBlit = blitOffscreenToSurfaceLocked();
@@ -333,13 +336,16 @@ public:
333
336
  // --- Rendering thread
334
337
  // -------------------------------------------------------
335
338
 
336
- void configure(wgpu::SurfaceConfiguration &newConfig,
337
- std::vector<wgpu::TextureFormat> viewFormats,
338
- CanvasColorSpace colorSpace = CanvasColorSpace::SRGB) {
339
+ void configure(
340
+ wgpu::SurfaceConfiguration &newConfig,
341
+ std::vector<wgpu::TextureFormat> viewFormats,
342
+ CanvasColorSpace colorSpace = CanvasColorSpace::SRGB,
343
+ CanvasToneMappingMode toneMappingMode = CanvasToneMappingMode::Standard) {
339
344
  applyPendingAttach(/* supersedeInFlightFrame = */ true);
340
345
  std::unique_lock<std::shared_mutex> lock(_mutex);
341
346
  _viewFormats = std::move(viewFormats);
342
347
  _colorSpace = colorSpace;
348
+ _toneMappingMode = toneMappingMode;
343
349
  _config = newConfig;
344
350
  // The caller's viewFormats storage dies with the call; point the stored
345
351
  // configuration at our own copy.
@@ -405,6 +411,7 @@ public:
405
411
  _texture = nullptr;
406
412
  _config = {};
407
413
  _colorSpace = CanvasColorSpace::SRGB;
414
+ _toneMappingMode = CanvasToneMappingMode::Standard;
408
415
  _viewFormats.clear();
409
416
  _acquiredFromSurface = false;
410
417
  _frameEpoch++;
@@ -911,7 +918,8 @@ private:
911
918
  if (_surface) {
912
919
  configureSurfaceLocked(_config);
913
920
  #ifdef __APPLE__
914
- applyCAMetalLayerColorSpace(_nativeSurface, _config.format, _colorSpace);
921
+ applyCAMetalLayerColorSpace(_nativeSurface, _config.format, _colorSpace,
922
+ _toneMappingMode);
915
923
  #endif
916
924
  } else {
917
925
  _texture = createOffscreenTextureLocked();
@@ -1276,6 +1284,7 @@ private:
1276
1284
  wgpu::SurfaceConfiguration _config;
1277
1285
  std::vector<wgpu::TextureFormat> _viewFormats;
1278
1286
  CanvasColorSpace _colorSpace = CanvasColorSpace::SRGB;
1287
+ CanvasToneMappingMode _toneMappingMode = CanvasToneMappingMode::Standard;
1279
1288
  // Keeps the Dawn instance alive for as long as any canvas exists.
1280
1289
  wgpu::Instance _gpu;
1281
1290
  // Native view size in dp (surfaced as clientWidth/clientHeight on the JS
@@ -18,7 +18,8 @@ wgpu::Instance createInstance() {
18
18
  // react-native-webgpu installs (see the RTLD_NOLOAD lookup below), so the
19
19
  // native-module init order decides whether the instance is shared.
20
20
  // RNWebGPU.importDevice does not depend on it: an imported device's async
21
- // work is pumped on the instance that owns it (see async::RuntimeContext).
21
+ // work is waited for on the instance that owns it (see
22
+ // async::RuntimeContext).
22
23
  // Both packages must link the same single Dawn copy (they vendor the same
23
24
  // artifact) for the handles they exchange to be meaningful.
24
25
  using GetInstanceFn = WGPUInstance (*)();
@@ -33,17 +33,17 @@ async::AsyncTaskHandle GPU::requestAdapter(
33
33
  aOptions.backendType = kDefaultBackendType;
34
34
 
35
35
  // Per-runtime context: async ops requested on this runtime resolve on this
36
- // runtime's own thread (via its ProcessEvents pump).
36
+ // runtime's own thread (see RuntimeContext).
37
37
  auto context = async::RuntimeContext::getOrCreate(runtime, _instance);
38
38
  return context->postTask(
39
39
  [this, aOptions,
40
40
  context](const async::AsyncTaskHandle::ResolveFunction &resolve,
41
41
  const async::AsyncTaskHandle::RejectFunction &reject) {
42
- _instance.RequestAdapter(
43
- &aOptions, wgpu::CallbackMode::AllowProcessEvents,
44
- [context, resolve,
45
- reject](wgpu::RequestAdapterStatus status, wgpu::Adapter adapter,
46
- wgpu::StringView message) {
42
+ return _instance.RequestAdapter(
43
+ &aOptions, wgpu::CallbackMode::WaitAnyOnly,
44
+ [context, resolve, reject](wgpu::RequestAdapterStatus status,
45
+ wgpu::Adapter adapter,
46
+ wgpu::StringView message) {
47
47
  if (message.length) {
48
48
  fprintf(stderr, "%s", message.data);
49
49
  }
@@ -33,7 +33,7 @@ public:
33
33
  std::string getBrand() { return CLASS_NAME; }
34
34
 
35
35
  // requestAdapter needs the calling runtime so each runtime gets its own
36
- // RuntimeContext (and ProcessEvents pump on its own thread).
36
+ // RuntimeContext, which settles the promise on that runtime's thread.
37
37
  async::AsyncTaskHandle requestAdapter(
38
38
  jsi::Runtime &runtime,
39
39
  std::optional<std::shared_ptr<GPURequestAdapterOptions>> options);