@luma.gl/webgpu 9.0.0-alpha.9 → 9.0.0-beta.2

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 (121) hide show
  1. package/LICENSE +3 -1
  2. package/dist/adapter/helpers/accessor-to-format.js.map +1 -1
  3. package/dist/adapter/helpers/convert-texture-format.d.ts +2 -2
  4. package/dist/adapter/helpers/convert-texture-format.d.ts.map +1 -1
  5. package/dist/adapter/helpers/convert-texture-format.js +0 -1
  6. package/dist/adapter/helpers/convert-texture-format.js.map +1 -1
  7. package/dist/adapter/helpers/generate-mipmaps.d.ts +1 -1
  8. package/dist/adapter/helpers/generate-mipmaps.js +20 -15
  9. package/dist/adapter/helpers/generate-mipmaps.js.map +1 -1
  10. package/dist/adapter/helpers/get-bind-group.d.ts +4 -4
  11. package/dist/adapter/helpers/get-bind-group.d.ts.map +1 -1
  12. package/dist/adapter/helpers/get-bind-group.js +11 -18
  13. package/dist/adapter/helpers/get-bind-group.js.map +1 -1
  14. package/dist/adapter/helpers/get-vertex-buffer-layout.d.ts +5 -5
  15. package/dist/adapter/helpers/get-vertex-buffer-layout.d.ts.map +1 -1
  16. package/dist/adapter/helpers/get-vertex-buffer-layout.js +39 -43
  17. package/dist/adapter/helpers/get-vertex-buffer-layout.js.map +1 -1
  18. package/dist/adapter/helpers/webgpu-parameters.d.ts +2 -2
  19. package/dist/adapter/helpers/webgpu-parameters.d.ts.map +1 -1
  20. package/dist/adapter/helpers/webgpu-parameters.js +14 -20
  21. package/dist/adapter/helpers/webgpu-parameters.js.map +1 -1
  22. package/dist/adapter/resources/webgpu-buffer.d.ts +14 -5
  23. package/dist/adapter/resources/webgpu-buffer.d.ts.map +1 -1
  24. package/dist/adapter/resources/webgpu-buffer.js +19 -29
  25. package/dist/adapter/resources/webgpu-buffer.js.map +1 -1
  26. package/dist/adapter/resources/webgpu-command-encoder.d.ts +7 -14
  27. package/dist/adapter/resources/webgpu-command-encoder.d.ts.map +1 -1
  28. package/dist/adapter/resources/webgpu-command-encoder.js +13 -27
  29. package/dist/adapter/resources/webgpu-command-encoder.js.map +1 -1
  30. package/dist/adapter/resources/webgpu-compute-pass.d.ts +5 -5
  31. package/dist/adapter/resources/webgpu-compute-pass.d.ts.map +1 -1
  32. package/dist/adapter/resources/webgpu-compute-pass.js +13 -27
  33. package/dist/adapter/resources/webgpu-compute-pass.js.map +1 -1
  34. package/dist/adapter/resources/webgpu-compute-pipeline.d.ts +4 -4
  35. package/dist/adapter/resources/webgpu-compute-pipeline.d.ts.map +1 -1
  36. package/dist/adapter/resources/webgpu-compute-pipeline.js +8 -13
  37. package/dist/adapter/resources/webgpu-compute-pipeline.js.map +1 -1
  38. package/dist/adapter/resources/webgpu-external-texture.d.ts +5 -5
  39. package/dist/adapter/resources/webgpu-external-texture.d.ts.map +1 -1
  40. package/dist/adapter/resources/webgpu-external-texture.js +6 -14
  41. package/dist/adapter/resources/webgpu-external-texture.js.map +1 -1
  42. package/dist/adapter/resources/webgpu-framebuffer.d.ts +4 -21
  43. package/dist/adapter/resources/webgpu-framebuffer.d.ts.map +1 -1
  44. package/dist/adapter/resources/webgpu-framebuffer.js +4 -105
  45. package/dist/adapter/resources/webgpu-framebuffer.js.map +1 -1
  46. package/dist/adapter/resources/webgpu-query.js.map +1 -1
  47. package/dist/adapter/resources/webgpu-render-pass.d.ts +12 -7
  48. package/dist/adapter/resources/webgpu-render-pass.d.ts.map +1 -1
  49. package/dist/adapter/resources/webgpu-render-pass.js +53 -36
  50. package/dist/adapter/resources/webgpu-render-pass.js.map +1 -1
  51. package/dist/adapter/resources/webgpu-render-pipeline.d.ts +15 -22
  52. package/dist/adapter/resources/webgpu-render-pipeline.d.ts.map +1 -1
  53. package/dist/adapter/resources/webgpu-render-pipeline.js +46 -118
  54. package/dist/adapter/resources/webgpu-render-pipeline.js.map +1 -1
  55. package/dist/adapter/resources/webgpu-sampler.d.ts +5 -5
  56. package/dist/adapter/resources/webgpu-sampler.d.ts.map +1 -1
  57. package/dist/adapter/resources/webgpu-sampler.js +8 -14
  58. package/dist/adapter/resources/webgpu-sampler.js.map +1 -1
  59. package/dist/adapter/resources/webgpu-shader.d.ts +9 -9
  60. package/dist/adapter/resources/webgpu-shader.d.ts.map +1 -1
  61. package/dist/adapter/resources/webgpu-shader.js +16 -29
  62. package/dist/adapter/resources/webgpu-shader.js.map +1 -1
  63. package/dist/adapter/resources/webgpu-texture.d.ts +18 -8
  64. package/dist/adapter/resources/webgpu-texture.d.ts.map +1 -1
  65. package/dist/adapter/resources/webgpu-texture.js +38 -33
  66. package/dist/adapter/resources/webgpu-texture.js.map +1 -1
  67. package/dist/adapter/resources/webgpu-vertex-array.d.ts +26 -0
  68. package/dist/adapter/resources/webgpu-vertex-array.d.ts.map +1 -0
  69. package/dist/adapter/resources/webgpu-vertex-array.js +45 -0
  70. package/dist/adapter/resources/webgpu-vertex-array.js.map +1 -0
  71. package/dist/adapter/webgpu-canvas-context.d.ts +17 -12
  72. package/dist/adapter/webgpu-canvas-context.d.ts.map +1 -1
  73. package/dist/adapter/webgpu-canvas-context.js +26 -47
  74. package/dist/adapter/webgpu-canvas-context.js.map +1 -1
  75. package/dist/adapter/webgpu-device.d.ts +34 -17
  76. package/dist/adapter/webgpu-device.d.ts.map +1 -1
  77. package/dist/adapter/webgpu-device.js +94 -103
  78. package/dist/adapter/webgpu-device.js.map +1 -1
  79. package/dist/adapter/webgpu-types.js.map +1 -1
  80. package/dist/dist.dev.js +3142 -0
  81. package/dist/glsl/glsllang.js +0 -1
  82. package/dist/glsl/glsllang.js.map +1 -1
  83. package/dist/index.cjs +1550 -0
  84. package/dist/index.d.ts +5 -7
  85. package/dist/index.d.ts.map +1 -1
  86. package/dist/index.js +5 -7
  87. package/dist/index.js.map +1 -1
  88. package/dist.min.js +30 -0
  89. package/package.json +18 -9
  90. package/src/adapter/helpers/accessor-to-format.ts +1 -2
  91. package/src/adapter/helpers/convert-texture-format.ts +1 -1
  92. package/src/adapter/helpers/generate-mipmaps.ts +2 -2
  93. package/src/adapter/helpers/get-bind-group.ts +23 -13
  94. package/src/adapter/helpers/get-vertex-buffer-layout.ts +65 -39
  95. package/src/adapter/helpers/webgpu-parameters.ts +20 -14
  96. package/src/adapter/resources/webgpu-buffer.ts +63 -8
  97. package/src/adapter/resources/webgpu-command-encoder.ts +68 -48
  98. package/src/adapter/resources/webgpu-compute-pass.ts +13 -12
  99. package/src/adapter/resources/webgpu-compute-pipeline.ts +8 -7
  100. package/src/adapter/resources/webgpu-external-texture.ts +5 -5
  101. package/src/adapter/resources/webgpu-framebuffer.ts +8 -109
  102. package/src/adapter/resources/webgpu-query.ts +3 -3
  103. package/src/adapter/resources/webgpu-render-pass.ts +68 -15
  104. package/src/adapter/resources/webgpu-render-pipeline.ts +117 -97
  105. package/src/adapter/resources/webgpu-sampler.ts +6 -6
  106. package/src/adapter/resources/webgpu-shader.ts +25 -16
  107. package/src/adapter/resources/webgpu-texture.ts +54 -25
  108. package/src/adapter/resources/webgpu-vertex-array.ts +83 -0
  109. package/src/adapter/webgpu-canvas-context.ts +51 -26
  110. package/src/adapter/webgpu-device.ts +144 -48
  111. package/src/index.ts +7 -9
  112. package/dist/bundle.d.ts +0 -2
  113. package/dist/bundle.d.ts.map +0 -1
  114. package/dist/bundle.js +0 -5
  115. package/dist/bundle.js.map +0 -1
  116. package/dist/init.d.ts +0 -2
  117. package/dist/init.d.ts.map +0 -1
  118. package/dist/init.js +0 -4
  119. package/dist/init.js.map +0 -1
  120. package/src/bundle.ts +0 -4
  121. package/src/init.ts +0 -4
@@ -0,0 +1,3142 @@
1
+ (function webpackUniversalModuleDefinition(root, factory) {
2
+ if (typeof exports === 'object' && typeof module === 'object')
3
+ module.exports = factory();
4
+ else if (typeof define === 'function' && define.amd) define([], factory);
5
+ else if (typeof exports === 'object') exports['luma'] = factory();
6
+ else root['luma'] = factory();})(globalThis, function () {
7
+ var __exports__ = (() => {
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __export = (target, all) => {
14
+ for (var name2 in all)
15
+ __defProp(target, name2, { get: all[name2], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var __publicField = (obj, key, value) => {
27
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
+ return value;
29
+ };
30
+
31
+ // src/index.ts
32
+ var src_exports = {};
33
+ __export(src_exports, {
34
+ WebGPUBuffer: () => WebGPUBuffer,
35
+ WebGPUDevice: () => WebGPUDevice,
36
+ WebGPUSampler: () => WebGPUSampler,
37
+ WebGPUShader: () => WebGPUShader,
38
+ WebGPUTexture: () => WebGPUTexture
39
+ });
40
+
41
+ // ../../node_modules/@probe.gl/env/dist/lib/is-electron.js
42
+ function isElectron(mockUserAgent) {
43
+ if (typeof window !== "undefined" && typeof window.process === "object" && window.process.type === "renderer") {
44
+ return true;
45
+ }
46
+ if (typeof process !== "undefined" && typeof process.versions === "object" && Boolean(process.versions["electron"])) {
47
+ return true;
48
+ }
49
+ const realUserAgent = typeof navigator === "object" && typeof navigator.userAgent === "string" && navigator.userAgent;
50
+ const userAgent = mockUserAgent || realUserAgent;
51
+ if (userAgent && userAgent.indexOf("Electron") >= 0) {
52
+ return true;
53
+ }
54
+ return false;
55
+ }
56
+
57
+ // ../../node_modules/@probe.gl/env/dist/lib/is-browser.js
58
+ function isBrowser() {
59
+ const isNode = typeof process === "object" && String(process) === "[object process]" && !process.browser;
60
+ return !isNode || isElectron();
61
+ }
62
+
63
+ // ../../node_modules/@probe.gl/env/dist/lib/globals.js
64
+ var self_ = globalThis.self || globalThis.window || globalThis.global;
65
+ var window_ = globalThis.window || globalThis.self || globalThis.global;
66
+ var document_ = globalThis.document || {};
67
+ var process_ = globalThis.process || {};
68
+ var console_ = globalThis.console;
69
+ var navigator_ = globalThis.navigator || {};
70
+
71
+ // ../../node_modules/@probe.gl/env/dist/utils/globals.js
72
+ var VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "untranspiled source";
73
+ var isBrowser2 = isBrowser();
74
+
75
+ // ../../node_modules/@probe.gl/env/dist/lib/get-browser.js
76
+ var window2 = globalThis;
77
+ function getBrowser(mockUserAgent) {
78
+ if (!mockUserAgent && !isBrowser()) {
79
+ return "Node";
80
+ }
81
+ if (isElectron(mockUserAgent)) {
82
+ return "Electron";
83
+ }
84
+ const userAgent = mockUserAgent || navigator_.userAgent || "";
85
+ if (userAgent.indexOf("Edge") > -1) {
86
+ return "Edge";
87
+ }
88
+ const isMSIE = userAgent.indexOf("MSIE ") !== -1;
89
+ const isTrident = userAgent.indexOf("Trident/") !== -1;
90
+ if (isMSIE || isTrident) {
91
+ return "IE";
92
+ }
93
+ if (window2.chrome) {
94
+ return "Chrome";
95
+ }
96
+ if (window2.safari) {
97
+ return "Safari";
98
+ }
99
+ if (window2.mozInnerScreenX) {
100
+ return "Firefox";
101
+ }
102
+ return "Unknown";
103
+ }
104
+
105
+ // ../../node_modules/@probe.gl/log/dist/utils/local-storage.js
106
+ function getStorage(type) {
107
+ try {
108
+ const storage = window[type];
109
+ const x = "__storage_test__";
110
+ storage.setItem(x, x);
111
+ storage.removeItem(x);
112
+ return storage;
113
+ } catch (e) {
114
+ return null;
115
+ }
116
+ }
117
+ var LocalStorage = class {
118
+ constructor(id, defaultConfig) {
119
+ let type = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "sessionStorage";
120
+ this.storage = void 0;
121
+ this.id = void 0;
122
+ this.config = void 0;
123
+ this.storage = getStorage(type);
124
+ this.id = id;
125
+ this.config = defaultConfig;
126
+ this._loadConfiguration();
127
+ }
128
+ getConfiguration() {
129
+ return this.config;
130
+ }
131
+ setConfiguration(configuration) {
132
+ Object.assign(this.config, configuration);
133
+ if (this.storage) {
134
+ const serialized = JSON.stringify(this.config);
135
+ this.storage.setItem(this.id, serialized);
136
+ }
137
+ }
138
+ _loadConfiguration() {
139
+ let configuration = {};
140
+ if (this.storage) {
141
+ const serializedConfiguration = this.storage.getItem(this.id);
142
+ configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
143
+ }
144
+ Object.assign(this.config, configuration);
145
+ return this;
146
+ }
147
+ };
148
+
149
+ // ../../node_modules/@probe.gl/log/dist/utils/formatters.js
150
+ function formatTime(ms) {
151
+ let formatted;
152
+ if (ms < 10) {
153
+ formatted = "".concat(ms.toFixed(2), "ms");
154
+ } else if (ms < 100) {
155
+ formatted = "".concat(ms.toFixed(1), "ms");
156
+ } else if (ms < 1e3) {
157
+ formatted = "".concat(ms.toFixed(0), "ms");
158
+ } else {
159
+ formatted = "".concat((ms / 1e3).toFixed(2), "s");
160
+ }
161
+ return formatted;
162
+ }
163
+ function leftPad(string) {
164
+ let length = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 8;
165
+ const padLength = Math.max(length - string.length, 0);
166
+ return "".concat(" ".repeat(padLength)).concat(string);
167
+ }
168
+ function formatImage(image, message, scale) {
169
+ let maxWidth = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 600;
170
+ const imageUrl = image.src.replace(/\(/g, "%28").replace(/\)/g, "%29");
171
+ if (image.width > maxWidth) {
172
+ scale = Math.min(scale, maxWidth / image.width);
173
+ }
174
+ const width = image.width * scale;
175
+ const height = image.height * scale;
176
+ const style = ["font-size:1px;", "padding:".concat(Math.floor(height / 2), "px ").concat(Math.floor(width / 2), "px;"), "line-height:".concat(height, "px;"), "background:url(".concat(imageUrl, ");"), "background-size:".concat(width, "px ").concat(height, "px;"), "color:transparent;"].join("");
177
+ return ["".concat(message, " %c+"), style];
178
+ }
179
+
180
+ // ../../node_modules/@probe.gl/log/dist/utils/color.js
181
+ var COLOR;
182
+ (function(COLOR2) {
183
+ COLOR2[COLOR2["BLACK"] = 30] = "BLACK";
184
+ COLOR2[COLOR2["RED"] = 31] = "RED";
185
+ COLOR2[COLOR2["GREEN"] = 32] = "GREEN";
186
+ COLOR2[COLOR2["YELLOW"] = 33] = "YELLOW";
187
+ COLOR2[COLOR2["BLUE"] = 34] = "BLUE";
188
+ COLOR2[COLOR2["MAGENTA"] = 35] = "MAGENTA";
189
+ COLOR2[COLOR2["CYAN"] = 36] = "CYAN";
190
+ COLOR2[COLOR2["WHITE"] = 37] = "WHITE";
191
+ COLOR2[COLOR2["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
192
+ COLOR2[COLOR2["BRIGHT_RED"] = 91] = "BRIGHT_RED";
193
+ COLOR2[COLOR2["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
194
+ COLOR2[COLOR2["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
195
+ COLOR2[COLOR2["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
196
+ COLOR2[COLOR2["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
197
+ COLOR2[COLOR2["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
198
+ COLOR2[COLOR2["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
199
+ })(COLOR || (COLOR = {}));
200
+ var BACKGROUND_INCREMENT = 10;
201
+ function getColor(color) {
202
+ if (typeof color !== "string") {
203
+ return color;
204
+ }
205
+ color = color.toUpperCase();
206
+ return COLOR[color] || COLOR.WHITE;
207
+ }
208
+ function addColor(string, color, background) {
209
+ if (!isBrowser && typeof string === "string") {
210
+ if (color) {
211
+ const colorCode = getColor(color);
212
+ string = "\x1B[".concat(colorCode, "m").concat(string, "\x1B[39m");
213
+ }
214
+ if (background) {
215
+ const colorCode = getColor(background);
216
+ string = "\x1B[".concat(colorCode + BACKGROUND_INCREMENT, "m").concat(string, "\x1B[49m");
217
+ }
218
+ }
219
+ return string;
220
+ }
221
+
222
+ // ../../node_modules/@probe.gl/log/dist/utils/autobind.js
223
+ function autobind(obj) {
224
+ let predefined = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ["constructor"];
225
+ const proto = Object.getPrototypeOf(obj);
226
+ const propNames = Object.getOwnPropertyNames(proto);
227
+ const object = obj;
228
+ for (const key of propNames) {
229
+ const value = object[key];
230
+ if (typeof value === "function") {
231
+ if (!predefined.find((name2) => key === name2)) {
232
+ object[key] = value.bind(obj);
233
+ }
234
+ }
235
+ }
236
+ }
237
+
238
+ // ../../node_modules/@probe.gl/log/dist/utils/assert.js
239
+ function assert(condition, message) {
240
+ if (!condition) {
241
+ throw new Error(message || "Assertion failed");
242
+ }
243
+ }
244
+
245
+ // ../../node_modules/@probe.gl/log/dist/utils/hi-res-timestamp.js
246
+ function getHiResTimestamp() {
247
+ let timestamp;
248
+ if (isBrowser() && window_.performance) {
249
+ var _window$performance, _window$performance$n;
250
+ timestamp = window_ === null || window_ === void 0 ? void 0 : (_window$performance = window_.performance) === null || _window$performance === void 0 ? void 0 : (_window$performance$n = _window$performance.now) === null || _window$performance$n === void 0 ? void 0 : _window$performance$n.call(_window$performance);
251
+ } else if ("hrtime" in process_) {
252
+ var _process$hrtime;
253
+ const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
254
+ timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6;
255
+ } else {
256
+ timestamp = Date.now();
257
+ }
258
+ return timestamp;
259
+ }
260
+
261
+ // ../../node_modules/@probe.gl/log/dist/log.js
262
+ var originalConsole = {
263
+ debug: isBrowser() ? console.debug || console.log : console.log,
264
+ log: console.log,
265
+ info: console.info,
266
+ warn: console.warn,
267
+ error: console.error
268
+ };
269
+ var DEFAULT_LOG_CONFIGURATION = {
270
+ enabled: true,
271
+ level: 0
272
+ };
273
+ function noop() {
274
+ }
275
+ var cache = {};
276
+ var ONCE = {
277
+ once: true
278
+ };
279
+ var Log = class {
280
+ constructor() {
281
+ let {
282
+ id
283
+ } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {
284
+ id: ""
285
+ };
286
+ this.id = void 0;
287
+ this.VERSION = VERSION;
288
+ this._startTs = getHiResTimestamp();
289
+ this._deltaTs = getHiResTimestamp();
290
+ this._storage = void 0;
291
+ this.userData = {};
292
+ this.LOG_THROTTLE_TIMEOUT = 0;
293
+ this.id = id;
294
+ this.userData = {};
295
+ this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_LOG_CONFIGURATION);
296
+ this.timeStamp("".concat(this.id, " started"));
297
+ autobind(this);
298
+ Object.seal(this);
299
+ }
300
+ set level(newLevel) {
301
+ this.setLevel(newLevel);
302
+ }
303
+ get level() {
304
+ return this.getLevel();
305
+ }
306
+ isEnabled() {
307
+ return this._storage.config.enabled;
308
+ }
309
+ getLevel() {
310
+ return this._storage.config.level;
311
+ }
312
+ getTotal() {
313
+ return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
314
+ }
315
+ getDelta() {
316
+ return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
317
+ }
318
+ set priority(newPriority) {
319
+ this.level = newPriority;
320
+ }
321
+ get priority() {
322
+ return this.level;
323
+ }
324
+ getPriority() {
325
+ return this.level;
326
+ }
327
+ enable() {
328
+ let enabled = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
329
+ this._storage.setConfiguration({
330
+ enabled
331
+ });
332
+ return this;
333
+ }
334
+ setLevel(level) {
335
+ this._storage.setConfiguration({
336
+ level
337
+ });
338
+ return this;
339
+ }
340
+ get(setting) {
341
+ return this._storage.config[setting];
342
+ }
343
+ set(setting, value) {
344
+ this._storage.setConfiguration({
345
+ [setting]: value
346
+ });
347
+ }
348
+ settings() {
349
+ if (console.table) {
350
+ console.table(this._storage.config);
351
+ } else {
352
+ console.log(this._storage.config);
353
+ }
354
+ }
355
+ assert(condition, message) {
356
+ assert(condition, message);
357
+ }
358
+ warn(message) {
359
+ return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
360
+ }
361
+ error(message) {
362
+ return this._getLogFunction(0, message, originalConsole.error, arguments);
363
+ }
364
+ deprecated(oldUsage, newUsage) {
365
+ return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
366
+ }
367
+ removed(oldUsage, newUsage) {
368
+ return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
369
+ }
370
+ probe(logLevel, message) {
371
+ return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
372
+ time: true,
373
+ once: true
374
+ });
375
+ }
376
+ log(logLevel, message) {
377
+ return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
378
+ }
379
+ info(logLevel, message) {
380
+ return this._getLogFunction(logLevel, message, console.info, arguments);
381
+ }
382
+ once(logLevel, message) {
383
+ return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
384
+ }
385
+ table(logLevel, table, columns) {
386
+ if (table) {
387
+ return this._getLogFunction(logLevel, table, console.table || noop, columns && [columns], {
388
+ tag: getTableHeader(table)
389
+ });
390
+ }
391
+ return noop;
392
+ }
393
+ image(_ref) {
394
+ let {
395
+ logLevel,
396
+ priority,
397
+ image,
398
+ message = "",
399
+ scale = 1
400
+ } = _ref;
401
+ if (!this._shouldLog(logLevel || priority)) {
402
+ return noop;
403
+ }
404
+ return isBrowser() ? logImageInBrowser({
405
+ image,
406
+ message,
407
+ scale
408
+ }) : logImageInNode({
409
+ image,
410
+ message,
411
+ scale
412
+ });
413
+ }
414
+ time(logLevel, message) {
415
+ return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
416
+ }
417
+ timeEnd(logLevel, message) {
418
+ return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
419
+ }
420
+ timeStamp(logLevel, message) {
421
+ return this._getLogFunction(logLevel, message, console.timeStamp || noop);
422
+ }
423
+ group(logLevel, message) {
424
+ let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {
425
+ collapsed: false
426
+ };
427
+ const options = normalizeArguments({
428
+ logLevel,
429
+ message,
430
+ opts
431
+ });
432
+ const {
433
+ collapsed
434
+ } = opts;
435
+ options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
436
+ return this._getLogFunction(options);
437
+ }
438
+ groupCollapsed(logLevel, message) {
439
+ let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
440
+ return this.group(logLevel, message, Object.assign({}, opts, {
441
+ collapsed: true
442
+ }));
443
+ }
444
+ groupEnd(logLevel) {
445
+ return this._getLogFunction(logLevel, "", console.groupEnd || noop);
446
+ }
447
+ withGroup(logLevel, message, func) {
448
+ this.group(logLevel, message)();
449
+ try {
450
+ func();
451
+ } finally {
452
+ this.groupEnd(logLevel)();
453
+ }
454
+ }
455
+ trace() {
456
+ if (console.trace) {
457
+ console.trace();
458
+ }
459
+ }
460
+ _shouldLog(logLevel) {
461
+ return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
462
+ }
463
+ _getLogFunction(logLevel, message, method, args, opts) {
464
+ if (this._shouldLog(logLevel)) {
465
+ opts = normalizeArguments({
466
+ logLevel,
467
+ message,
468
+ args,
469
+ opts
470
+ });
471
+ method = method || opts.method;
472
+ assert(method);
473
+ opts.total = this.getTotal();
474
+ opts.delta = this.getDelta();
475
+ this._deltaTs = getHiResTimestamp();
476
+ const tag = opts.tag || opts.message;
477
+ if (opts.once && tag) {
478
+ if (!cache[tag]) {
479
+ cache[tag] = getHiResTimestamp();
480
+ } else {
481
+ return noop;
482
+ }
483
+ }
484
+ message = decorateMessage(this.id, opts.message, opts);
485
+ return method.bind(console, message, ...opts.args);
486
+ }
487
+ return noop;
488
+ }
489
+ };
490
+ Log.VERSION = VERSION;
491
+ function normalizeLogLevel(logLevel) {
492
+ if (!logLevel) {
493
+ return 0;
494
+ }
495
+ let resolvedLevel;
496
+ switch (typeof logLevel) {
497
+ case "number":
498
+ resolvedLevel = logLevel;
499
+ break;
500
+ case "object":
501
+ resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
502
+ break;
503
+ default:
504
+ return 0;
505
+ }
506
+ assert(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
507
+ return resolvedLevel;
508
+ }
509
+ function normalizeArguments(opts) {
510
+ const {
511
+ logLevel,
512
+ message
513
+ } = opts;
514
+ opts.logLevel = normalizeLogLevel(logLevel);
515
+ const args = opts.args ? Array.from(opts.args) : [];
516
+ while (args.length && args.shift() !== message) {
517
+ }
518
+ switch (typeof logLevel) {
519
+ case "string":
520
+ case "function":
521
+ if (message !== void 0) {
522
+ args.unshift(message);
523
+ }
524
+ opts.message = logLevel;
525
+ break;
526
+ case "object":
527
+ Object.assign(opts, logLevel);
528
+ break;
529
+ default:
530
+ }
531
+ if (typeof opts.message === "function") {
532
+ opts.message = opts.message();
533
+ }
534
+ const messageType = typeof opts.message;
535
+ assert(messageType === "string" || messageType === "object");
536
+ return Object.assign(opts, {
537
+ args
538
+ }, opts.opts);
539
+ }
540
+ function decorateMessage(id, message, opts) {
541
+ if (typeof message === "string") {
542
+ const time = opts.time ? leftPad(formatTime(opts.total)) : "";
543
+ message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
544
+ message = addColor(message, opts.color, opts.background);
545
+ }
546
+ return message;
547
+ }
548
+ function logImageInNode(_ref2) {
549
+ let {
550
+ image,
551
+ message = "",
552
+ scale = 1
553
+ } = _ref2;
554
+ console.warn("removed");
555
+ return noop;
556
+ }
557
+ function logImageInBrowser(_ref3) {
558
+ let {
559
+ image,
560
+ message = "",
561
+ scale = 1
562
+ } = _ref3;
563
+ if (typeof image === "string") {
564
+ const img = new Image();
565
+ img.onload = () => {
566
+ const args = formatImage(img, message, scale);
567
+ console.log(...args);
568
+ };
569
+ img.src = image;
570
+ return noop;
571
+ }
572
+ const element = image.nodeName || "";
573
+ if (element.toLowerCase() === "img") {
574
+ console.log(...formatImage(image, message, scale));
575
+ return noop;
576
+ }
577
+ if (element.toLowerCase() === "canvas") {
578
+ const img = new Image();
579
+ img.onload = () => console.log(...formatImage(img, message, scale));
580
+ img.src = image.toDataURL();
581
+ return noop;
582
+ }
583
+ return noop;
584
+ }
585
+ function getTableHeader(table) {
586
+ for (const key in table) {
587
+ for (const title in table[key]) {
588
+ return title || "untitled";
589
+ }
590
+ }
591
+ return "empty";
592
+ }
593
+
594
+ // ../../node_modules/@probe.gl/log/dist/index.js
595
+ var dist_default = new Log({
596
+ id: "@probe.gl/log"
597
+ });
598
+
599
+ // ../core/src/utils/log.ts
600
+ var log = new Log({
601
+ id: "luma.gl"
602
+ });
603
+
604
+ // ../../node_modules/@probe.gl/stats/dist/utils/hi-res-timestamp.js
605
+ function getHiResTimestamp2() {
606
+ let timestamp;
607
+ if (typeof window !== "undefined" && window.performance) {
608
+ timestamp = window.performance.now();
609
+ } else if (typeof process !== "undefined" && process.hrtime) {
610
+ const timeParts = process.hrtime();
611
+ timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6;
612
+ } else {
613
+ timestamp = Date.now();
614
+ }
615
+ return timestamp;
616
+ }
617
+
618
+ // ../../node_modules/@probe.gl/stats/dist/lib/stat.js
619
+ var Stat = class {
620
+ constructor(name2, type) {
621
+ this.name = void 0;
622
+ this.type = void 0;
623
+ this.sampleSize = 1;
624
+ this.time = 0;
625
+ this.count = 0;
626
+ this.samples = 0;
627
+ this.lastTiming = 0;
628
+ this.lastSampleTime = 0;
629
+ this.lastSampleCount = 0;
630
+ this._count = 0;
631
+ this._time = 0;
632
+ this._samples = 0;
633
+ this._startTime = 0;
634
+ this._timerPending = false;
635
+ this.name = name2;
636
+ this.type = type;
637
+ this.reset();
638
+ }
639
+ reset() {
640
+ this.time = 0;
641
+ this.count = 0;
642
+ this.samples = 0;
643
+ this.lastTiming = 0;
644
+ this.lastSampleTime = 0;
645
+ this.lastSampleCount = 0;
646
+ this._count = 0;
647
+ this._time = 0;
648
+ this._samples = 0;
649
+ this._startTime = 0;
650
+ this._timerPending = false;
651
+ return this;
652
+ }
653
+ setSampleSize(samples) {
654
+ this.sampleSize = samples;
655
+ return this;
656
+ }
657
+ incrementCount() {
658
+ this.addCount(1);
659
+ return this;
660
+ }
661
+ decrementCount() {
662
+ this.subtractCount(1);
663
+ return this;
664
+ }
665
+ addCount(value) {
666
+ this._count += value;
667
+ this._samples++;
668
+ this._checkSampling();
669
+ return this;
670
+ }
671
+ subtractCount(value) {
672
+ this._count -= value;
673
+ this._samples++;
674
+ this._checkSampling();
675
+ return this;
676
+ }
677
+ addTime(time) {
678
+ this._time += time;
679
+ this.lastTiming = time;
680
+ this._samples++;
681
+ this._checkSampling();
682
+ return this;
683
+ }
684
+ timeStart() {
685
+ this._startTime = getHiResTimestamp2();
686
+ this._timerPending = true;
687
+ return this;
688
+ }
689
+ timeEnd() {
690
+ if (!this._timerPending) {
691
+ return this;
692
+ }
693
+ this.addTime(getHiResTimestamp2() - this._startTime);
694
+ this._timerPending = false;
695
+ this._checkSampling();
696
+ return this;
697
+ }
698
+ getSampleAverageCount() {
699
+ return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
700
+ }
701
+ getSampleAverageTime() {
702
+ return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
703
+ }
704
+ getSampleHz() {
705
+ return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1e3) : 0;
706
+ }
707
+ getAverageCount() {
708
+ return this.samples > 0 ? this.count / this.samples : 0;
709
+ }
710
+ getAverageTime() {
711
+ return this.samples > 0 ? this.time / this.samples : 0;
712
+ }
713
+ getHz() {
714
+ return this.time > 0 ? this.samples / (this.time / 1e3) : 0;
715
+ }
716
+ _checkSampling() {
717
+ if (this._samples === this.sampleSize) {
718
+ this.lastSampleTime = this._time;
719
+ this.lastSampleCount = this._count;
720
+ this.count += this._count;
721
+ this.time += this._time;
722
+ this.samples += this._samples;
723
+ this._time = 0;
724
+ this._count = 0;
725
+ this._samples = 0;
726
+ }
727
+ }
728
+ };
729
+
730
+ // ../../node_modules/@probe.gl/stats/dist/lib/stats.js
731
+ var Stats = class {
732
+ constructor(options) {
733
+ this.id = void 0;
734
+ this.stats = {};
735
+ this.id = options.id;
736
+ this.stats = {};
737
+ this._initializeStats(options.stats);
738
+ Object.seal(this);
739
+ }
740
+ get(name2) {
741
+ let type = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "count";
742
+ return this._getOrCreate({
743
+ name: name2,
744
+ type
745
+ });
746
+ }
747
+ get size() {
748
+ return Object.keys(this.stats).length;
749
+ }
750
+ reset() {
751
+ for (const stat of Object.values(this.stats)) {
752
+ stat.reset();
753
+ }
754
+ return this;
755
+ }
756
+ forEach(fn) {
757
+ for (const stat of Object.values(this.stats)) {
758
+ fn(stat);
759
+ }
760
+ }
761
+ getTable() {
762
+ const table = {};
763
+ this.forEach((stat) => {
764
+ table[stat.name] = {
765
+ time: stat.time || 0,
766
+ count: stat.count || 0,
767
+ average: stat.getAverageTime() || 0,
768
+ hz: stat.getHz() || 0
769
+ };
770
+ });
771
+ return table;
772
+ }
773
+ _initializeStats() {
774
+ let stats = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
775
+ stats.forEach((stat) => this._getOrCreate(stat));
776
+ }
777
+ _getOrCreate(stat) {
778
+ const {
779
+ name: name2,
780
+ type
781
+ } = stat;
782
+ let result = this.stats[name2];
783
+ if (!result) {
784
+ if (stat instanceof Stat) {
785
+ result = stat;
786
+ } else {
787
+ result = new Stat(name2, type);
788
+ }
789
+ this.stats[name2] = result;
790
+ }
791
+ return result;
792
+ }
793
+ };
794
+
795
+ // ../core/src/utils/stats-manager.ts
796
+ var StatsManager = class {
797
+ stats = /* @__PURE__ */ new Map();
798
+ getStats(name2) {
799
+ return this.get(name2);
800
+ }
801
+ get(name2) {
802
+ if (!this.stats.has(name2)) {
803
+ this.stats.set(name2, new Stats({
804
+ id: name2
805
+ }));
806
+ }
807
+ return this.stats.get(name2);
808
+ }
809
+ };
810
+ var lumaStats = new StatsManager();
811
+
812
+ // ../core/src/init.ts
813
+ function initializeLuma() {
814
+ const VERSION3 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "running from source";
815
+ const STARTUP_MESSAGE = "set luma.log.level=1 (or higher) to trace rendering";
816
+ if (globalThis.luma && globalThis.luma.VERSION !== VERSION3) {
817
+ throw new Error(`luma.gl - multiple VERSIONs detected: ${globalThis.luma.VERSION} vs ${VERSION3}`);
818
+ }
819
+ if (!globalThis.luma) {
820
+ if (isBrowser()) {
821
+ log.log(1, `${VERSION3} - ${STARTUP_MESSAGE}`)();
822
+ }
823
+ globalThis.luma = globalThis.luma || {
824
+ VERSION: VERSION3,
825
+ version: VERSION3,
826
+ log,
827
+ stats: lumaStats
828
+ };
829
+ }
830
+ return VERSION3;
831
+ }
832
+ var VERSION2 = initializeLuma();
833
+
834
+ // ../core/src/utils/utils.ts
835
+ var uidCounters = {};
836
+ function uid(id = "id") {
837
+ uidCounters[id] = uidCounters[id] || 1;
838
+ const count = uidCounters[id]++;
839
+ return `${id}-${count}`;
840
+ }
841
+ function isObjectEmpty(obj) {
842
+ let isEmpty = true;
843
+ for (const key in obj) {
844
+ isEmpty = false;
845
+ break;
846
+ }
847
+ return isEmpty;
848
+ }
849
+
850
+ // ../core/src/adapter/resources/resource.ts
851
+ var Resource = class {
852
+ userData = {};
853
+ destroyed = false;
854
+ allocatedBytes = 0;
855
+ _attachedResources = /* @__PURE__ */ new Set();
856
+ constructor(device, props, defaultProps) {
857
+ if (!device) {
858
+ throw new Error("no device");
859
+ }
860
+ this._device = device;
861
+ this.props = selectivelyMerge(props, defaultProps);
862
+ const id = this.props.id !== "undefined" ? this.props.id : uid(this[Symbol.toStringTag]);
863
+ this.props.id = id;
864
+ this.id = id;
865
+ this.userData = this.props.userData || {};
866
+ this.addStats();
867
+ }
868
+ destroy() {
869
+ this.destroyResource();
870
+ }
871
+ delete() {
872
+ this.destroy();
873
+ return this;
874
+ }
875
+ toString() {
876
+ return `${this[Symbol.toStringTag] || this.constructor.name}(${this.id})`;
877
+ }
878
+ getProps() {
879
+ return this.props;
880
+ }
881
+ attachResource(resource) {
882
+ this._attachedResources.add(resource);
883
+ }
884
+ detachResource(resource) {
885
+ this._attachedResources.delete(resource);
886
+ }
887
+ destroyAttachedResource(resource) {
888
+ if (this._attachedResources.delete(resource)) {
889
+ resource.destroy();
890
+ }
891
+ }
892
+ destroyAttachedResources() {
893
+ for (const resource of Object.values(this._attachedResources)) {
894
+ resource.destroy();
895
+ }
896
+ this._attachedResources = /* @__PURE__ */ new Set();
897
+ }
898
+ destroyResource() {
899
+ this.destroyAttachedResources();
900
+ this.removeStats();
901
+ this.destroyed = true;
902
+ }
903
+ removeStats() {
904
+ const stats = this._device.statsManager.getStats("Resource Counts");
905
+ const name2 = this[Symbol.toStringTag];
906
+ stats.get(`${name2}s Active`).decrementCount();
907
+ }
908
+ trackAllocatedMemory(bytes, name2 = this[Symbol.toStringTag]) {
909
+ const stats = this._device.statsManager.getStats("Resource Counts");
910
+ stats.get("GPU Memory").addCount(bytes);
911
+ stats.get(`${name2} Memory`).addCount(bytes);
912
+ this.allocatedBytes = bytes;
913
+ }
914
+ trackDeallocatedMemory(name2 = this[Symbol.toStringTag]) {
915
+ const stats = this._device.statsManager.getStats("Resource Counts");
916
+ stats.get("GPU Memory").subtractCount(this.allocatedBytes);
917
+ stats.get(`${name2} Memory`).subtractCount(this.allocatedBytes);
918
+ this.allocatedBytes = 0;
919
+ }
920
+ addStats() {
921
+ const stats = this._device.statsManager.getStats("Resource Counts");
922
+ const name2 = this[Symbol.toStringTag];
923
+ stats.get("Resources Created").incrementCount();
924
+ stats.get(`${name2}s Created`).incrementCount();
925
+ stats.get(`${name2}s Active`).incrementCount();
926
+ }
927
+ };
928
+ __publicField(Resource, "defaultProps", {
929
+ id: "undefined",
930
+ handle: void 0,
931
+ userData: void 0
932
+ });
933
+ function selectivelyMerge(props, defaultProps) {
934
+ const mergedProps = {
935
+ ...defaultProps
936
+ };
937
+ for (const key in props) {
938
+ if (props[key] !== void 0) {
939
+ mergedProps[key] = props[key];
940
+ }
941
+ }
942
+ return mergedProps;
943
+ }
944
+
945
+ // ../core/src/adapter/resources/buffer.ts
946
+ var _Buffer = class extends Resource {
947
+ get [Symbol.toStringTag]() {
948
+ return "Buffer";
949
+ }
950
+ constructor(device, props) {
951
+ const deducedProps = {
952
+ ...props
953
+ };
954
+ if ((props.usage || 0) & _Buffer.INDEX && !props.indexType) {
955
+ if (props.data instanceof Uint32Array) {
956
+ deducedProps.indexType = "uint32";
957
+ } else if (props.data instanceof Uint16Array) {
958
+ deducedProps.indexType = "uint16";
959
+ }
960
+ }
961
+ super(device, deducedProps, _Buffer.defaultProps);
962
+ this.usage = props.usage || 0;
963
+ this.indexType = deducedProps.indexType;
964
+ }
965
+ readSyncWebGL2(byteOffset, byteLength) {
966
+ throw new Error("not implemented");
967
+ }
968
+ debugData = new ArrayBuffer(0);
969
+ _setDebugData(data, byteOffset, byteLength) {
970
+ const buffer = ArrayBuffer.isView(data) ? data.buffer : data;
971
+ const debugDataLength = Math.min(data ? data.byteLength : byteLength, _Buffer.DEBUG_DATA_MAX_LENGTH);
972
+ if (data === null) {
973
+ this.debugData = new ArrayBuffer(debugDataLength);
974
+ } else if (byteOffset === 0 && byteLength === data.byteLength) {
975
+ this.debugData = buffer.slice(0, debugDataLength);
976
+ } else {
977
+ this.debugData = buffer.slice(byteOffset, byteOffset + debugDataLength);
978
+ }
979
+ }
980
+ };
981
+ var Buffer2 = _Buffer;
982
+ __publicField(Buffer2, "defaultProps", {
983
+ ...Resource.defaultProps,
984
+ usage: 0,
985
+ byteLength: 0,
986
+ byteOffset: 0,
987
+ data: null,
988
+ indexType: "uint16",
989
+ mappedAtCreation: false
990
+ });
991
+ __publicField(Buffer2, "MAP_READ", 1);
992
+ __publicField(Buffer2, "MAP_WRITE", 2);
993
+ __publicField(Buffer2, "COPY_SRC", 4);
994
+ __publicField(Buffer2, "COPY_DST", 8);
995
+ __publicField(Buffer2, "INDEX", 16);
996
+ __publicField(Buffer2, "VERTEX", 32);
997
+ __publicField(Buffer2, "UNIFORM", 64);
998
+ __publicField(Buffer2, "STORAGE", 128);
999
+ __publicField(Buffer2, "INDIRECT", 256);
1000
+ __publicField(Buffer2, "QUERY_RESOLVE", 512);
1001
+ __publicField(Buffer2, "DEBUG_DATA_MAX_LENGTH", 32);
1002
+
1003
+ // ../core/src/adapter/device.ts
1004
+ var _Device = class {
1005
+ get [Symbol.toStringTag]() {
1006
+ return "Device";
1007
+ }
1008
+ constructor(props) {
1009
+ this.props = {
1010
+ ..._Device.defaultProps,
1011
+ ...props
1012
+ };
1013
+ this.id = this.props.id || uid(this[Symbol.toStringTag].toLowerCase());
1014
+ }
1015
+ statsManager = lumaStats;
1016
+ userData = {};
1017
+ _lumaData = {};
1018
+ loseDevice() {
1019
+ return false;
1020
+ }
1021
+ getCanvasContext() {
1022
+ if (!this.canvasContext) {
1023
+ throw new Error("Device has no CanvasContext");
1024
+ }
1025
+ return this.canvasContext;
1026
+ }
1027
+ createTexture(props) {
1028
+ if (props instanceof Promise || typeof props === "string") {
1029
+ props = {
1030
+ data: props
1031
+ };
1032
+ }
1033
+ return this._createTexture(props);
1034
+ }
1035
+ createCommandEncoder(props = {}) {
1036
+ throw new Error("not implemented");
1037
+ }
1038
+ readPixelsToArrayWebGL(source, options) {
1039
+ throw new Error("not implemented");
1040
+ }
1041
+ readPixelsToBufferWebGL2(source, options) {
1042
+ throw new Error("not implemented");
1043
+ }
1044
+ setParametersWebGL(parameters) {
1045
+ throw new Error("not implemented");
1046
+ }
1047
+ withParametersWebGL(parameters, func) {
1048
+ throw new Error("not implemented");
1049
+ }
1050
+ clearWebGL(options) {
1051
+ throw new Error("not implemented");
1052
+ }
1053
+ _getBufferProps(props) {
1054
+ if (props instanceof ArrayBuffer || ArrayBuffer.isView(props)) {
1055
+ props = {
1056
+ data: props
1057
+ };
1058
+ }
1059
+ const newProps = {
1060
+ ...props
1061
+ };
1062
+ if ((props.usage || 0) & Buffer2.INDEX && !props.indexType) {
1063
+ if (props.data instanceof Uint32Array) {
1064
+ newProps.indexType = "uint32";
1065
+ } else if (props.data instanceof Uint16Array) {
1066
+ newProps.indexType = "uint16";
1067
+ } else {
1068
+ log.warn("indices buffer content must be of integer type")();
1069
+ }
1070
+ }
1071
+ return newProps;
1072
+ }
1073
+ };
1074
+ var Device = _Device;
1075
+ __publicField(Device, "defaultProps", {
1076
+ id: null,
1077
+ type: "best-available",
1078
+ canvas: null,
1079
+ container: null,
1080
+ webgl2: true,
1081
+ webgl1: true,
1082
+ manageState: true,
1083
+ width: 800,
1084
+ height: 600,
1085
+ debug: Boolean(log.get("debug")),
1086
+ break: [],
1087
+ gl: null
1088
+ });
1089
+ __publicField(Device, "VERSION", VERSION2);
1090
+
1091
+ // ../core/src/adapter/canvas-context.ts
1092
+ var isPage = isBrowser() && typeof document !== "undefined";
1093
+ var isPageLoaded = () => isPage && document.readyState === "complete";
1094
+ var DEFAULT_CANVAS_CONTEXT_PROPS = {
1095
+ canvas: null,
1096
+ width: 800,
1097
+ height: 600,
1098
+ useDevicePixels: true,
1099
+ autoResize: true,
1100
+ container: null,
1101
+ visible: true,
1102
+ colorSpace: "srgb",
1103
+ alphaMode: "opaque"
1104
+ };
1105
+ var CanvasContext = class {
1106
+ width = 1;
1107
+ height = 1;
1108
+ _canvasSizeInfo = {
1109
+ clientWidth: 0,
1110
+ clientHeight: 0,
1111
+ devicePixelRatio: 1
1112
+ };
1113
+ static get isPageLoaded() {
1114
+ return isPageLoaded();
1115
+ }
1116
+ constructor(props) {
1117
+ this.props = {
1118
+ ...DEFAULT_CANVAS_CONTEXT_PROPS,
1119
+ ...props
1120
+ };
1121
+ props = this.props;
1122
+ if (!isBrowser()) {
1123
+ this.id = "node-canvas-context";
1124
+ this.type = "node";
1125
+ this.width = this.props.width;
1126
+ this.height = this.props.height;
1127
+ this.canvas = null;
1128
+ return;
1129
+ }
1130
+ if (!props.canvas) {
1131
+ const canvas = createCanvas(props);
1132
+ const container = getContainer(props?.container || null);
1133
+ container.insertBefore(canvas, container.firstChild);
1134
+ this.canvas = canvas;
1135
+ if (!props?.visible) {
1136
+ this.canvas.style.visibility = "hidden";
1137
+ }
1138
+ } else if (typeof props.canvas === "string") {
1139
+ this.canvas = getCanvasFromDOM(props.canvas);
1140
+ } else {
1141
+ this.canvas = props.canvas;
1142
+ }
1143
+ if (this.canvas instanceof HTMLCanvasElement) {
1144
+ this.id = this.canvas.id;
1145
+ this.type = "html-canvas";
1146
+ this.htmlCanvas = this.canvas;
1147
+ } else {
1148
+ this.id = "offscreen-canvas";
1149
+ this.type = "offscreen-canvas";
1150
+ this.offscreenCanvas = this.canvas;
1151
+ }
1152
+ if (this.canvas instanceof HTMLCanvasElement && props.autoResize) {
1153
+ this.resizeObserver = new ResizeObserver((entries) => {
1154
+ for (const entry of entries) {
1155
+ if (entry.target === this.canvas) {
1156
+ this.update();
1157
+ }
1158
+ }
1159
+ });
1160
+ this.resizeObserver.observe(this.canvas);
1161
+ }
1162
+ }
1163
+ getDevicePixelRatio(useDevicePixels) {
1164
+ if (typeof OffscreenCanvas !== "undefined" && this.canvas instanceof OffscreenCanvas) {
1165
+ return 1;
1166
+ }
1167
+ useDevicePixels = useDevicePixels === void 0 ? this.props.useDevicePixels : useDevicePixels;
1168
+ if (!useDevicePixels || useDevicePixels <= 0) {
1169
+ return 1;
1170
+ }
1171
+ if (useDevicePixels === true) {
1172
+ const dpr = typeof window !== "undefined" && window.devicePixelRatio;
1173
+ return dpr || 1;
1174
+ }
1175
+ return useDevicePixels;
1176
+ }
1177
+ getPixelSize() {
1178
+ switch (this.type) {
1179
+ case "node":
1180
+ return [this.width, this.height];
1181
+ case "offscreen-canvas":
1182
+ return [this.canvas.width, this.canvas.height];
1183
+ case "html-canvas":
1184
+ const dpr = this.getDevicePixelRatio();
1185
+ const canvas = this.canvas;
1186
+ return canvas.parentElement ? [canvas.clientWidth * dpr, canvas.clientHeight * dpr] : [this.canvas.width, this.canvas.height];
1187
+ default:
1188
+ throw new Error(this.type);
1189
+ }
1190
+ }
1191
+ getAspect() {
1192
+ const [width, height] = this.getPixelSize();
1193
+ return width / height;
1194
+ }
1195
+ cssToDeviceRatio() {
1196
+ try {
1197
+ const [drawingBufferWidth] = this.getDrawingBufferSize();
1198
+ const {
1199
+ clientWidth
1200
+ } = this._canvasSizeInfo;
1201
+ return clientWidth ? drawingBufferWidth / clientWidth : 1;
1202
+ } catch {
1203
+ return 1;
1204
+ }
1205
+ }
1206
+ cssToDevicePixels(cssPixel, yInvert = true) {
1207
+ const ratio = this.cssToDeviceRatio();
1208
+ const [width, height] = this.getDrawingBufferSize();
1209
+ return scalePixels(cssPixel, ratio, width, height, yInvert);
1210
+ }
1211
+ setDevicePixelRatio(devicePixelRatio, options = {}) {
1212
+ if (!this.htmlCanvas) {
1213
+ return;
1214
+ }
1215
+ let clientWidth = "width" in options ? options.width : this.htmlCanvas.clientWidth;
1216
+ let clientHeight = "height" in options ? options.height : this.htmlCanvas.clientHeight;
1217
+ if (!clientWidth || !clientHeight) {
1218
+ log.log(1, "Canvas clientWidth/clientHeight is 0")();
1219
+ devicePixelRatio = 1;
1220
+ clientWidth = this.htmlCanvas.width || 1;
1221
+ clientHeight = this.htmlCanvas.height || 1;
1222
+ }
1223
+ const cachedSize = this._canvasSizeInfo;
1224
+ if (cachedSize.clientWidth !== clientWidth || cachedSize.clientHeight !== clientHeight || cachedSize.devicePixelRatio !== devicePixelRatio) {
1225
+ let clampedPixelRatio = devicePixelRatio;
1226
+ const canvasWidth = Math.floor(clientWidth * clampedPixelRatio);
1227
+ const canvasHeight = Math.floor(clientHeight * clampedPixelRatio);
1228
+ this.htmlCanvas.width = canvasWidth;
1229
+ this.htmlCanvas.height = canvasHeight;
1230
+ const [drawingBufferWidth, drawingBufferHeight] = this.getDrawingBufferSize();
1231
+ if (drawingBufferWidth !== canvasWidth || drawingBufferHeight !== canvasHeight) {
1232
+ clampedPixelRatio = Math.min(drawingBufferWidth / clientWidth, drawingBufferHeight / clientHeight);
1233
+ this.htmlCanvas.width = Math.floor(clientWidth * clampedPixelRatio);
1234
+ this.htmlCanvas.height = Math.floor(clientHeight * clampedPixelRatio);
1235
+ log.warn("Device pixel ratio clamped")();
1236
+ }
1237
+ this._canvasSizeInfo.clientWidth = clientWidth;
1238
+ this._canvasSizeInfo.clientHeight = clientHeight;
1239
+ this._canvasSizeInfo.devicePixelRatio = devicePixelRatio;
1240
+ }
1241
+ }
1242
+ getDrawingBufferSize() {
1243
+ const gl = this.device.gl;
1244
+ if (!gl) {
1245
+ throw new Error("canvas size");
1246
+ }
1247
+ return [gl.drawingBufferWidth, gl.drawingBufferHeight];
1248
+ }
1249
+ _setAutoCreatedCanvasId(id) {
1250
+ if (this.htmlCanvas?.id === "lumagl-auto-created-canvas") {
1251
+ this.htmlCanvas.id = id;
1252
+ }
1253
+ }
1254
+ };
1255
+ __publicField(CanvasContext, "pageLoaded", getPageLoadPromise());
1256
+ function getPageLoadPromise() {
1257
+ if (isPageLoaded() || typeof window === "undefined") {
1258
+ return Promise.resolve();
1259
+ }
1260
+ return new Promise((resolve) => {
1261
+ window.addEventListener("load", () => resolve());
1262
+ });
1263
+ }
1264
+ function getContainer(container) {
1265
+ if (typeof container === "string") {
1266
+ const element = document.getElementById(container);
1267
+ if (!element && !isPageLoaded()) {
1268
+ throw new Error(`Accessing '${container}' before page was loaded`);
1269
+ }
1270
+ if (!element) {
1271
+ throw new Error(`${container} is not an HTML element`);
1272
+ }
1273
+ return element;
1274
+ } else if (container) {
1275
+ return container;
1276
+ }
1277
+ return document.body;
1278
+ }
1279
+ function getCanvasFromDOM(canvasId) {
1280
+ const canvas = document.getElementById(canvasId);
1281
+ if (!canvas && !isPageLoaded()) {
1282
+ throw new Error(`Accessing '${canvasId}' before page was loaded`);
1283
+ }
1284
+ if (!(canvas instanceof HTMLCanvasElement)) {
1285
+ throw new Error("Object is not a canvas element");
1286
+ }
1287
+ return canvas;
1288
+ }
1289
+ function createCanvas(props) {
1290
+ const {
1291
+ width,
1292
+ height
1293
+ } = props;
1294
+ const targetCanvas = document.createElement("canvas");
1295
+ targetCanvas.id = "lumagl-auto-created-canvas";
1296
+ targetCanvas.width = width || 1;
1297
+ targetCanvas.height = height || 1;
1298
+ targetCanvas.style.width = Number.isFinite(width) ? `${width}px` : "100%";
1299
+ targetCanvas.style.height = Number.isFinite(height) ? `${height}px` : "100%";
1300
+ return targetCanvas;
1301
+ }
1302
+ function scalePixels(pixel, ratio, width, height, yInvert) {
1303
+ const point = pixel;
1304
+ const x = scaleX(point[0], ratio, width);
1305
+ let y = scaleY(point[1], ratio, height, yInvert);
1306
+ let t = scaleX(point[0] + 1, ratio, width);
1307
+ const xHigh = t === width - 1 ? t : t - 1;
1308
+ t = scaleY(point[1] + 1, ratio, height, yInvert);
1309
+ let yHigh;
1310
+ if (yInvert) {
1311
+ t = t === 0 ? t : t + 1;
1312
+ yHigh = y;
1313
+ y = t;
1314
+ } else {
1315
+ yHigh = t === height - 1 ? t : t - 1;
1316
+ }
1317
+ return {
1318
+ x,
1319
+ y,
1320
+ width: Math.max(xHigh - x + 1, 1),
1321
+ height: Math.max(yHigh - y + 1, 1)
1322
+ };
1323
+ }
1324
+ function scaleX(x, ratio, width) {
1325
+ const r = Math.min(Math.round(x * ratio), width - 1);
1326
+ return r;
1327
+ }
1328
+ function scaleY(y, ratio, height, yInvert) {
1329
+ return yInvert ? Math.max(0, height - 1 - Math.round(y * ratio)) : Math.min(Math.round(y * ratio), height - 1);
1330
+ }
1331
+
1332
+ // ../core/src/adapter/resources/texture.ts
1333
+ var _Texture = class extends Resource {
1334
+ get [Symbol.toStringTag]() {
1335
+ return "Texture";
1336
+ }
1337
+ constructor(device, props, defaultProps = _Texture.defaultProps) {
1338
+ super(device, props, defaultProps);
1339
+ this.dimension = this.props.dimension;
1340
+ this.format = this.props.format;
1341
+ this.width = this.props.width;
1342
+ this.height = this.props.height;
1343
+ this.depth = this.props.depth;
1344
+ }
1345
+ };
1346
+ var Texture = _Texture;
1347
+ __publicField(Texture, "defaultProps", {
1348
+ ...Resource.defaultProps,
1349
+ data: null,
1350
+ dimension: "2d",
1351
+ format: "rgba8unorm",
1352
+ width: void 0,
1353
+ height: void 0,
1354
+ depth: 1,
1355
+ mipmaps: true,
1356
+ sampler: {},
1357
+ compressed: false,
1358
+ usage: 0,
1359
+ mipLevels: void 0,
1360
+ samples: void 0,
1361
+ type: void 0
1362
+ });
1363
+ __publicField(Texture, "COPY_SRC", 1);
1364
+ __publicField(Texture, "COPY_DST", 2);
1365
+ __publicField(Texture, "TEXTURE_BINDING", 4);
1366
+ __publicField(Texture, "STORAGE_BINDING", 8);
1367
+ __publicField(Texture, "RENDER_ATTACHMENT", 16);
1368
+
1369
+ // ../core/src/adapter/resources/external-texture.ts
1370
+ var _ExternalTexture = class extends Resource {
1371
+ get [Symbol.toStringTag]() {
1372
+ return "ExternalTexture";
1373
+ }
1374
+ constructor(device, props) {
1375
+ super(device, props, _ExternalTexture.defaultProps);
1376
+ }
1377
+ };
1378
+ var ExternalTexture = _ExternalTexture;
1379
+ __publicField(ExternalTexture, "defaultProps", {
1380
+ ...Resource.defaultProps,
1381
+ source: null,
1382
+ colorSpace: "srgb"
1383
+ });
1384
+
1385
+ // ../core/src/lib/compiler-log/format-compiler-log.ts
1386
+ function formatCompilerLog(shaderLog, source, options) {
1387
+ let formattedLog = "";
1388
+ const lines = source.split(/\r?\n/);
1389
+ const log2 = shaderLog.slice().sort((a, b) => a.lineNum - b.lineNum);
1390
+ switch (options?.showSourceCode || "no") {
1391
+ case "all":
1392
+ let currentMessage = 0;
1393
+ for (let lineNum = 1; lineNum <= lines.length; lineNum++) {
1394
+ formattedLog += getNumberedLine(lines[lineNum - 1], lineNum, options);
1395
+ while (log2.length > currentMessage && log2[currentMessage].lineNum === lineNum) {
1396
+ const message = log2[currentMessage++];
1397
+ formattedLog += formatCompilerMessage(message, lines, message.lineNum, {
1398
+ ...options,
1399
+ inlineSource: false
1400
+ });
1401
+ }
1402
+ }
1403
+ return formattedLog;
1404
+ case "issues":
1405
+ case "no":
1406
+ for (const message of shaderLog) {
1407
+ formattedLog += formatCompilerMessage(message, lines, message.lineNum, {
1408
+ inlineSource: options?.showSourceCode !== "no"
1409
+ });
1410
+ }
1411
+ return formattedLog;
1412
+ }
1413
+ }
1414
+ function formatCompilerMessage(message, lines, lineNum, options) {
1415
+ if (options?.inlineSource) {
1416
+ const numberedLines = getNumberedLines(lines, lineNum);
1417
+ const positionIndicator = message.linePos > 0 ? `${" ".repeat(message.linePos + 5)}^^^
1418
+ ` : "";
1419
+ return `
1420
+ ${numberedLines}${positionIndicator}${message.type.toUpperCase()}: ${message.message}
1421
+
1422
+ `;
1423
+ }
1424
+ return options?.html ? `<div class='luma-compiler-log-error' style="color:red;"><b> ${message.type.toUpperCase()}: ${message.message}</b></div>` : `${message.type.toUpperCase()}: ${message.message}`;
1425
+ }
1426
+ function getNumberedLines(lines, lineNum, options) {
1427
+ let numberedLines = "";
1428
+ for (let lineIndex = lineNum - 2; lineIndex <= lineNum; lineIndex++) {
1429
+ const sourceLine = lines[lineIndex - 1];
1430
+ if (sourceLine !== void 0) {
1431
+ numberedLines += getNumberedLine(sourceLine, lineNum, options);
1432
+ }
1433
+ }
1434
+ return numberedLines;
1435
+ }
1436
+ function getNumberedLine(line, lineNum, options) {
1437
+ const escapedLine = options?.html ? escapeHTML(line) : line;
1438
+ return `${padLeft(String(lineNum), 4)}: ${escapedLine}${options?.html ? "<br/>" : "\n"}`;
1439
+ }
1440
+ function padLeft(string, paddedLength) {
1441
+ let result = "";
1442
+ for (let i = string.length; i < paddedLength; ++i) {
1443
+ result += " ";
1444
+ }
1445
+ return result + string;
1446
+ }
1447
+ function escapeHTML(unsafe) {
1448
+ return unsafe.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#039;");
1449
+ }
1450
+
1451
+ // ../core/src/lib/compiler-log/get-shader-info.ts
1452
+ function getShaderInfo(source, defaultName) {
1453
+ return {
1454
+ name: getShaderName(source, defaultName),
1455
+ language: "glsl",
1456
+ version: getShaderVersion(source)
1457
+ };
1458
+ }
1459
+ function getShaderName(shader, defaultName = "unnamed") {
1460
+ const SHADER_NAME_REGEXP = /#define[\s*]SHADER_NAME[\s*]([A-Za-z0-9_-]+)[\s*]/;
1461
+ const match = SHADER_NAME_REGEXP.exec(shader);
1462
+ return match ? match[1] : defaultName;
1463
+ }
1464
+ function getShaderVersion(source) {
1465
+ let version = 100;
1466
+ const words = source.match(/[^\s]+/g);
1467
+ if (words && words.length >= 2 && words[0] === "#version") {
1468
+ const v = parseInt(words[1], 10);
1469
+ if (Number.isFinite(v)) {
1470
+ version = v;
1471
+ }
1472
+ }
1473
+ return version;
1474
+ }
1475
+
1476
+ // ../core/src/adapter/resources/shader.ts
1477
+ var _Shader = class extends Resource {
1478
+ get [Symbol.toStringTag]() {
1479
+ return "Shader";
1480
+ }
1481
+ compilationStatus = "pending";
1482
+ constructor(device, props) {
1483
+ super(device, {
1484
+ id: getShaderIdFromProps(props),
1485
+ ...props
1486
+ }, _Shader.defaultProps);
1487
+ this.stage = this.props.stage;
1488
+ this.source = this.props.source;
1489
+ }
1490
+ getCompilationInfoSync() {
1491
+ return null;
1492
+ }
1493
+ async debugShader() {
1494
+ switch (this.props.debug) {
1495
+ case "never":
1496
+ return;
1497
+ case "errors":
1498
+ if (this.compilationStatus === "success") {
1499
+ return;
1500
+ }
1501
+ break;
1502
+ case "warnings":
1503
+ case "always":
1504
+ break;
1505
+ }
1506
+ const messages = await this.getCompilationInfo();
1507
+ if (this.props.debug === "warnings" && messages?.length === 0) {
1508
+ return;
1509
+ }
1510
+ this._displayShaderLog(messages);
1511
+ }
1512
+ _displayShaderLog(messages) {
1513
+ if (typeof document === "undefined" || !document?.createElement) {
1514
+ return;
1515
+ }
1516
+ const shaderName = getShaderInfo(this.source).name;
1517
+ const shaderTitle = `${this.stage} ${shaderName}`;
1518
+ const htmlLog = formatCompilerLog(messages, this.source, {
1519
+ showSourceCode: "all",
1520
+ html: true
1521
+ });
1522
+ const button = document.createElement("Button");
1523
+ button.innerHTML = `
1524
+ <h1>Shader Compilation Error in ${shaderTitle}</h1><br /><br />
1525
+ <code style="user-select:text;"><pre>
1526
+ ${htmlLog}
1527
+ </pre></code>`;
1528
+ button.style.top = "10px";
1529
+ button.style.left = "10px";
1530
+ button.style.position = "absolute";
1531
+ button.style.zIndex = "9999";
1532
+ button.style.width = "100%";
1533
+ button.style.textAlign = "left";
1534
+ document.body.appendChild(button);
1535
+ const errors = document.getElementsByClassName("luma-compiler-log-error");
1536
+ if (errors[0]?.scrollIntoView) {
1537
+ errors[0].scrollIntoView();
1538
+ }
1539
+ button.onclick = () => {
1540
+ const dataURI = `data:text/plain,${encodeURIComponent(this.source)}`;
1541
+ navigator.clipboard.writeText(dataURI);
1542
+ };
1543
+ }
1544
+ };
1545
+ var Shader = _Shader;
1546
+ __publicField(Shader, "defaultProps", {
1547
+ ...Resource.defaultProps,
1548
+ language: "auto",
1549
+ stage: "vertex",
1550
+ source: "",
1551
+ sourceMap: null,
1552
+ entryPoint: "main",
1553
+ debug: "errors"
1554
+ });
1555
+ function getShaderIdFromProps(props) {
1556
+ return getShaderInfo(props.source).name || props.id || uid(`unnamed ${props.stage}-shader`);
1557
+ }
1558
+
1559
+ // ../core/src/adapter/resources/sampler.ts
1560
+ var _Sampler = class extends Resource {
1561
+ get [Symbol.toStringTag]() {
1562
+ return "Sampler";
1563
+ }
1564
+ constructor(device, props) {
1565
+ super(device, props, _Sampler.defaultProps);
1566
+ }
1567
+ };
1568
+ var Sampler = _Sampler;
1569
+ __publicField(Sampler, "defaultProps", {
1570
+ ...Resource.defaultProps,
1571
+ type: "color-sampler",
1572
+ addressModeU: "clamp-to-edge",
1573
+ addressModeV: "clamp-to-edge",
1574
+ addressModeW: "clamp-to-edge",
1575
+ magFilter: "nearest",
1576
+ minFilter: "nearest",
1577
+ mipmapFilter: "nearest",
1578
+ lodMinClamp: 0,
1579
+ lodMaxClamp: 32,
1580
+ compare: "less-equal",
1581
+ maxAnisotropy: 1
1582
+ });
1583
+
1584
+ // ../core/src/adapter/resources/framebuffer.ts
1585
+ var _Framebuffer = class extends Resource {
1586
+ get [Symbol.toStringTag]() {
1587
+ return "Framebuffer";
1588
+ }
1589
+ colorAttachments = [];
1590
+ depthStencilAttachment = null;
1591
+ constructor(device, props = {}) {
1592
+ super(device, props, _Framebuffer.defaultProps);
1593
+ this.width = this.props.width;
1594
+ this.height = this.props.height;
1595
+ }
1596
+ resize(size) {
1597
+ let updateSize = !size;
1598
+ if (size) {
1599
+ const [width, height] = Array.isArray(size) ? size : [size.width, size.height];
1600
+ updateSize = updateSize || height !== this.height || width !== this.width;
1601
+ this.width = width;
1602
+ this.height = height;
1603
+ }
1604
+ if (updateSize) {
1605
+ log.log(2, `Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)();
1606
+ this.resizeAttachments(this.width, this.height);
1607
+ }
1608
+ }
1609
+ autoCreateAttachmentTextures() {
1610
+ this.colorAttachments = this.props.colorAttachments.map((attachment) => {
1611
+ if (typeof attachment === "string") {
1612
+ const texture = this.createColorTexture(attachment);
1613
+ this.attachResource(texture);
1614
+ return texture;
1615
+ }
1616
+ return attachment;
1617
+ });
1618
+ if (this.props.depthStencilAttachment) {
1619
+ if (typeof this.props.depthStencilAttachment === "string") {
1620
+ const texture = this.createDepthStencilTexture(this.props.depthStencilAttachment);
1621
+ this.attachResource(texture);
1622
+ this.depthStencilAttachment = texture;
1623
+ } else {
1624
+ this.depthStencilAttachment = this.props.depthStencilAttachment;
1625
+ }
1626
+ }
1627
+ }
1628
+ createColorTexture(format) {
1629
+ return this.device.createTexture({
1630
+ id: "color-attachment",
1631
+ usage: Texture.RENDER_ATTACHMENT,
1632
+ format,
1633
+ width: this.width,
1634
+ height: this.height
1635
+ });
1636
+ }
1637
+ createDepthStencilTexture(format) {
1638
+ return this.device.createTexture({
1639
+ id: "depth-stencil-attachment",
1640
+ usage: Texture.RENDER_ATTACHMENT,
1641
+ format,
1642
+ width: this.width,
1643
+ height: this.height
1644
+ });
1645
+ }
1646
+ resizeAttachments(width, height) {
1647
+ for (let i = 0; i < this.colorAttachments.length; ++i) {
1648
+ if (this.colorAttachments[i]) {
1649
+ const resizedTexture = this.device._createTexture({
1650
+ ...this.colorAttachments[i].props,
1651
+ width,
1652
+ height
1653
+ });
1654
+ this.destroyAttachedResource(this.colorAttachments[i]);
1655
+ this.colorAttachments[i] = resizedTexture;
1656
+ this.attachResource(resizedTexture);
1657
+ }
1658
+ }
1659
+ if (this.depthStencilAttachment) {
1660
+ const resizedTexture = this.device._createTexture({
1661
+ ...this.depthStencilAttachment.props,
1662
+ width,
1663
+ height
1664
+ });
1665
+ this.destroyAttachedResource(this.depthStencilAttachment);
1666
+ this.depthStencilAttachment = resizedTexture;
1667
+ this.attachResource(resizedTexture);
1668
+ }
1669
+ }
1670
+ };
1671
+ var Framebuffer = _Framebuffer;
1672
+ __publicField(Framebuffer, "defaultProps", {
1673
+ ...Resource.defaultProps,
1674
+ width: 1,
1675
+ height: 1,
1676
+ colorAttachments: [],
1677
+ depthStencilAttachment: null
1678
+ });
1679
+
1680
+ // ../core/src/adapter/resources/render-pipeline.ts
1681
+ var _RenderPipeline = class extends Resource {
1682
+ get [Symbol.toStringTag]() {
1683
+ return "RenderPipeline";
1684
+ }
1685
+ hash = "";
1686
+ constructor(device, props) {
1687
+ super(device, props, _RenderPipeline.defaultProps);
1688
+ this.shaderLayout = this.props.shaderLayout;
1689
+ this.bufferLayout = this.props.bufferLayout || [];
1690
+ }
1691
+ };
1692
+ var RenderPipeline = _RenderPipeline;
1693
+ __publicField(RenderPipeline, "defaultProps", {
1694
+ ...Resource.defaultProps,
1695
+ vs: null,
1696
+ vsEntryPoint: "",
1697
+ vsConstants: {},
1698
+ fs: null,
1699
+ fsEntryPoint: "",
1700
+ fsConstants: {},
1701
+ shaderLayout: null,
1702
+ bufferLayout: [],
1703
+ topology: "triangle-list",
1704
+ parameters: {},
1705
+ vertexCount: 0,
1706
+ instanceCount: 0,
1707
+ bindings: {},
1708
+ uniforms: {}
1709
+ });
1710
+
1711
+ // ../core/src/adapter/resources/compute-pipeline.ts
1712
+ var _ComputePipeline = class extends Resource {
1713
+ get [Symbol.toStringTag]() {
1714
+ return "ComputePipeline";
1715
+ }
1716
+ hash = "";
1717
+ constructor(device, props) {
1718
+ super(device, props, _ComputePipeline.defaultProps);
1719
+ }
1720
+ };
1721
+ var ComputePipeline = _ComputePipeline;
1722
+ __publicField(ComputePipeline, "defaultProps", {
1723
+ ...Resource.defaultProps,
1724
+ cs: void 0,
1725
+ csEntryPoint: void 0,
1726
+ csConstants: {},
1727
+ shaderLayout: []
1728
+ });
1729
+
1730
+ // ../core/src/adapter/resources/render-pass.ts
1731
+ var _RenderPass = class extends Resource {
1732
+ get [Symbol.toStringTag]() {
1733
+ return "RenderPass";
1734
+ }
1735
+ constructor(device, props) {
1736
+ super(device, props, _RenderPass.defaultProps);
1737
+ }
1738
+ };
1739
+ var RenderPass = _RenderPass;
1740
+ __publicField(RenderPass, "defaultProps", {
1741
+ ...Resource.defaultProps,
1742
+ framebuffer: null,
1743
+ parameters: void 0,
1744
+ clearColor: [0, 0, 0, 0],
1745
+ clearDepth: 1,
1746
+ clearStencil: 0,
1747
+ depthReadOnly: false,
1748
+ stencilReadOnly: false,
1749
+ discard: false
1750
+ });
1751
+
1752
+ // ../core/src/adapter/resources/compute-pass.ts
1753
+ var ComputePass = class extends Resource {
1754
+ get [Symbol.toStringTag]() {
1755
+ return "ComputePass";
1756
+ }
1757
+ constructor(device, props) {
1758
+ super(device, props, Resource.defaultProps);
1759
+ }
1760
+ };
1761
+ __publicField(ComputePass, "defaultProps", {
1762
+ ...Resource.defaultProps
1763
+ });
1764
+
1765
+ // ../core/src/adapter/type-utils/decode-attribute-type.ts
1766
+ function decodeShaderAttributeType(attributeType) {
1767
+ const [dataType, components] = TYPE_INFO[attributeType];
1768
+ const integer = dataType === "i32" || dataType === "u32";
1769
+ const signed = dataType !== "u32";
1770
+ const byteLength = TYPE_SIZES[dataType] * components;
1771
+ const defaultVertexFormat = getCompatibleVertexFormat(dataType, components);
1772
+ return {
1773
+ dataType,
1774
+ components,
1775
+ defaultVertexFormat,
1776
+ byteLength,
1777
+ integer,
1778
+ signed
1779
+ };
1780
+ }
1781
+ function getCompatibleVertexFormat(dataType, components) {
1782
+ let vertexType;
1783
+ switch (dataType) {
1784
+ case "f32":
1785
+ vertexType = "float32";
1786
+ break;
1787
+ case "i32":
1788
+ vertexType = "sint32";
1789
+ break;
1790
+ case "u32":
1791
+ vertexType = "uint32";
1792
+ break;
1793
+ case "f16":
1794
+ return components <= 2 ? "float16x2" : "float16x4";
1795
+ }
1796
+ if (components === 1) {
1797
+ return vertexType;
1798
+ }
1799
+ return `${vertexType}x${components}`;
1800
+ }
1801
+ var TYPE_INFO = {
1802
+ f32: ["f32", 1],
1803
+ "vec2<f32>": ["f32", 2],
1804
+ "vec3<f32>": ["f32", 3],
1805
+ "vec4<f32>": ["f32", 4],
1806
+ f16: ["f16", 1],
1807
+ "vec2<f16>": ["f16", 2],
1808
+ "vec3<f16>": ["f16", 3],
1809
+ "vec4<f16>": ["f16", 4],
1810
+ i32: ["i32", 1],
1811
+ "vec2<i32>": ["i32", 2],
1812
+ "vec3<i32>": ["i32", 3],
1813
+ "vec4<i32>": ["i32", 4],
1814
+ u32: ["u32", 1],
1815
+ "vec2<u32>": ["u32", 2],
1816
+ "vec3<u32>": ["u32", 3],
1817
+ "vec4<u32>": ["u32", 4]
1818
+ };
1819
+ var TYPE_SIZES = {
1820
+ f32: 4,
1821
+ f16: 2,
1822
+ i32: 4,
1823
+ u32: 4
1824
+ };
1825
+
1826
+ // ../core/src/adapter/type-utils/decode-data-type.ts
1827
+ function decodeVertexType(type) {
1828
+ const dataType = TYPE_MAP[type];
1829
+ const bytes = getDataTypeBytes(dataType);
1830
+ const normalized = type.includes("norm");
1831
+ const integer = !normalized && !type.startsWith("float");
1832
+ const signed = type.startsWith("s");
1833
+ return {
1834
+ dataType: TYPE_MAP[type],
1835
+ byteLength: bytes,
1836
+ integer,
1837
+ signed,
1838
+ normalized
1839
+ };
1840
+ }
1841
+ function getDataTypeBytes(type) {
1842
+ const bytes = TYPE_SIZES2[type];
1843
+ return bytes;
1844
+ }
1845
+ var TYPE_MAP = {
1846
+ uint8: "uint8",
1847
+ sint8: "sint8",
1848
+ unorm8: "uint8",
1849
+ snorm8: "sint8",
1850
+ uint16: "uint16",
1851
+ sint16: "sint16",
1852
+ unorm16: "uint16",
1853
+ snorm16: "sint16",
1854
+ float16: "float16",
1855
+ float32: "float32",
1856
+ uint32: "uint32",
1857
+ sint32: "sint32"
1858
+ };
1859
+ var TYPE_SIZES2 = {
1860
+ uint8: 1,
1861
+ sint8: 1,
1862
+ uint16: 2,
1863
+ sint16: 2,
1864
+ float16: 2,
1865
+ float32: 4,
1866
+ uint32: 4,
1867
+ sint32: 4
1868
+ };
1869
+
1870
+ // ../core/src/adapter/type-utils/decode-vertex-format.ts
1871
+ function decodeVertexFormat(format) {
1872
+ let webglOnly;
1873
+ if (format.endsWith("-webgl")) {
1874
+ format.replace("-webgl", "");
1875
+ webglOnly = true;
1876
+ }
1877
+ const [type_, count] = format.split("x");
1878
+ const type = type_;
1879
+ const components = count ? parseInt(count) : 1;
1880
+ const decodedType = decodeVertexType(type);
1881
+ const result = {
1882
+ type,
1883
+ components,
1884
+ byteLength: decodedType.byteLength * components,
1885
+ integer: decodedType.integer,
1886
+ signed: decodedType.signed,
1887
+ normalized: decodedType.normalized
1888
+ };
1889
+ if (webglOnly) {
1890
+ result.webglOnly = true;
1891
+ }
1892
+ return result;
1893
+ }
1894
+
1895
+ // ../core/src/adapter/attribute-utils/get-attribute-from-layouts.ts
1896
+ function getAttributeInfosFromLayouts(shaderLayout, bufferLayout) {
1897
+ const attributeInfos = {};
1898
+ for (const attribute of shaderLayout.attributes) {
1899
+ attributeInfos[attribute.name] = getAttributeInfoFromLayouts(shaderLayout, bufferLayout, attribute.name);
1900
+ }
1901
+ return attributeInfos;
1902
+ }
1903
+ function getAttributeInfosByLocation(shaderLayout, bufferLayout, maxVertexAttributes = 16) {
1904
+ const attributeInfos = getAttributeInfosFromLayouts(shaderLayout, bufferLayout);
1905
+ const locationInfos = new Array(maxVertexAttributes).fill(null);
1906
+ for (const attributeInfo of Object.values(attributeInfos)) {
1907
+ locationInfos[attributeInfo.location] = attributeInfo;
1908
+ }
1909
+ return locationInfos;
1910
+ }
1911
+ function getAttributeInfoFromLayouts(shaderLayout, bufferLayout, name2) {
1912
+ const shaderDeclaration = getAttributeFromShaderLayout(shaderLayout, name2);
1913
+ const bufferMapping = getAttributeFromBufferLayout(bufferLayout, name2);
1914
+ if (!shaderDeclaration) {
1915
+ return null;
1916
+ }
1917
+ const attributeTypeInfo = decodeShaderAttributeType(shaderDeclaration.type);
1918
+ const vertexFormat = bufferMapping?.vertexFormat || attributeTypeInfo.defaultVertexFormat;
1919
+ const vertexFormatInfo = decodeVertexFormat(vertexFormat);
1920
+ return {
1921
+ attributeName: bufferMapping?.attributeName || shaderDeclaration.name,
1922
+ bufferName: bufferMapping?.bufferName || shaderDeclaration.name,
1923
+ location: shaderDeclaration.location,
1924
+ shaderType: shaderDeclaration.type,
1925
+ shaderDataType: attributeTypeInfo.dataType,
1926
+ shaderComponents: attributeTypeInfo.components,
1927
+ vertexFormat,
1928
+ bufferDataType: vertexFormatInfo.type,
1929
+ bufferComponents: vertexFormatInfo.components,
1930
+ normalized: vertexFormatInfo.normalized,
1931
+ integer: attributeTypeInfo.integer,
1932
+ stepMode: bufferMapping?.stepMode || shaderDeclaration.stepMode,
1933
+ byteOffset: bufferMapping?.byteOffset || 0,
1934
+ byteStride: bufferMapping?.byteStride || 0
1935
+ };
1936
+ }
1937
+ function getAttributeFromShaderLayout(shaderLayout, name2) {
1938
+ const attribute = shaderLayout.attributes.find((attr) => attr.name === name2);
1939
+ if (!attribute) {
1940
+ log.warn(`shader layout attribute "${name2}" not present in shader`);
1941
+ }
1942
+ return attribute || null;
1943
+ }
1944
+ function getAttributeFromBufferLayout(bufferLayouts, name2) {
1945
+ checkBufferLayouts(bufferLayouts);
1946
+ let bufferLayoutInfo = getAttributeFromShortHand(bufferLayouts, name2);
1947
+ if (bufferLayoutInfo) {
1948
+ return bufferLayoutInfo;
1949
+ }
1950
+ bufferLayoutInfo = getAttributeFromAttributesList(bufferLayouts, name2);
1951
+ if (bufferLayoutInfo) {
1952
+ return bufferLayoutInfo;
1953
+ }
1954
+ log.warn(`layout for attribute "${name2}" not present in buffer layout`);
1955
+ return null;
1956
+ }
1957
+ function checkBufferLayouts(bufferLayouts) {
1958
+ for (const bufferLayout of bufferLayouts) {
1959
+ if (bufferLayout.attributes && bufferLayout.format || !bufferLayout.attributes && !bufferLayout.format) {
1960
+ log.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`);
1961
+ }
1962
+ }
1963
+ }
1964
+ function getAttributeFromShortHand(bufferLayouts, name2) {
1965
+ for (const bufferLayout of bufferLayouts) {
1966
+ if (bufferLayout.format && bufferLayout.name === name2) {
1967
+ return {
1968
+ attributeName: bufferLayout.name,
1969
+ bufferName: name2,
1970
+ stepMode: bufferLayout.stepMode,
1971
+ vertexFormat: bufferLayout.format,
1972
+ byteOffset: 0,
1973
+ byteStride: bufferLayout.byteStride || 0
1974
+ };
1975
+ }
1976
+ }
1977
+ return null;
1978
+ }
1979
+ function getAttributeFromAttributesList(bufferLayouts, name2) {
1980
+ for (const bufferLayout of bufferLayouts) {
1981
+ let byteStride = bufferLayout.byteStride;
1982
+ if (typeof bufferLayout.byteStride !== "number") {
1983
+ for (const attributeMapping2 of bufferLayout.attributes || []) {
1984
+ const info = decodeVertexFormat(attributeMapping2.format);
1985
+ byteStride += info.byteLength;
1986
+ }
1987
+ }
1988
+ const attributeMapping = bufferLayout.attributes?.find((mapping) => mapping.attribute === name2);
1989
+ if (attributeMapping) {
1990
+ return {
1991
+ attributeName: attributeMapping.attribute,
1992
+ bufferName: bufferLayout.name,
1993
+ stepMode: bufferLayout.stepMode,
1994
+ vertexFormat: attributeMapping.format,
1995
+ byteOffset: attributeMapping.byteOffset,
1996
+ byteStride
1997
+ };
1998
+ }
1999
+ }
2000
+ return null;
2001
+ }
2002
+
2003
+ // ../core/src/adapter/resources/vertex-array.ts
2004
+ var _VertexArray = class extends Resource {
2005
+ get [Symbol.toStringTag]() {
2006
+ return "VertexArray";
2007
+ }
2008
+ indexBuffer = null;
2009
+ constructor(device, props) {
2010
+ super(device, props, _VertexArray.defaultProps);
2011
+ this.maxVertexAttributes = device.limits.maxVertexAttributes;
2012
+ this.attributes = new Array(this.maxVertexAttributes).fill(null);
2013
+ this.attributeInfos = getAttributeInfosByLocation(props.renderPipeline.shaderLayout, props.renderPipeline.bufferLayout, this.maxVertexAttributes);
2014
+ }
2015
+ };
2016
+ var VertexArray = _VertexArray;
2017
+ __publicField(VertexArray, "defaultProps", {
2018
+ ...Resource.defaultProps,
2019
+ renderPipeline: null
2020
+ });
2021
+
2022
+ // ../core/src/utils/cast.ts
2023
+ function cast(value) {
2024
+ return value;
2025
+ }
2026
+
2027
+ // src/adapter/resources/webgpu-buffer.ts
2028
+ function getByteLength(props) {
2029
+ return props.byteLength || props.data?.byteLength || 0;
2030
+ }
2031
+ var WebGPUBuffer = class extends Buffer2 {
2032
+ constructor(device, props) {
2033
+ super(device, props);
2034
+ this.device = device;
2035
+ this.byteLength = getByteLength(props);
2036
+ const mapBuffer = Boolean(props.data);
2037
+ const size = Math.ceil(this.byteLength / 4) * 4;
2038
+ this.handle = this.props.handle || this.device.handle.createBuffer({
2039
+ size,
2040
+ usage: this.props.usage || GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
2041
+ mappedAtCreation: this.props.mappedAtCreation || mapBuffer,
2042
+ label: this.props.id
2043
+ });
2044
+ if (props.data) {
2045
+ this._writeMapped(props.data);
2046
+ }
2047
+ if (mapBuffer && !props.mappedAtCreation) {
2048
+ this.handle.unmap();
2049
+ }
2050
+ }
2051
+ destroy() {
2052
+ this.handle.destroy();
2053
+ }
2054
+ write(data, byteOffset = 0) {
2055
+ this.device.handle.queue.writeBuffer(this.handle, byteOffset, data.buffer, data.byteOffset, data.byteLength);
2056
+ }
2057
+ async readAsync(byteOffset = 0, byteLength = this.byteLength) {
2058
+ const tempBuffer = new WebGPUBuffer(this.device, {
2059
+ usage: Buffer2.MAP_READ | Buffer2.COPY_DST,
2060
+ byteLength
2061
+ });
2062
+ const commandEncoder = this.device.handle.createCommandEncoder();
2063
+ commandEncoder.copyBufferToBuffer(this.handle, byteOffset, tempBuffer.handle, 0, byteLength);
2064
+ this.device.handle.queue.submit([commandEncoder.finish()]);
2065
+ await tempBuffer.handle.mapAsync(GPUMapMode.READ, byteOffset, byteLength);
2066
+ const arrayBuffer = tempBuffer.handle.getMappedRange().slice(0);
2067
+ tempBuffer.handle.unmap();
2068
+ tempBuffer.destroy();
2069
+ return new Uint8Array(arrayBuffer);
2070
+ }
2071
+ _writeMapped(typedArray) {
2072
+ const arrayBuffer = this.handle.getMappedRange();
2073
+ new typedArray.constructor(arrayBuffer).set(typedArray);
2074
+ }
2075
+ mapAsync(mode, offset = 0, size) {
2076
+ return this.handle.mapAsync(mode, offset, size);
2077
+ }
2078
+ getMappedRange(offset = 0, size) {
2079
+ return this.handle.getMappedRange(offset, size);
2080
+ }
2081
+ unmap() {
2082
+ this.handle.unmap();
2083
+ }
2084
+ };
2085
+
2086
+ // src/adapter/helpers/convert-texture-format.ts
2087
+ function getWebGPUTextureFormat(format) {
2088
+ if (format.includes("webgl")) {
2089
+ throw new Error("webgl-only format");
2090
+ }
2091
+ return format;
2092
+ }
2093
+
2094
+ // src/adapter/resources/webgpu-sampler.ts
2095
+ var WebGPUSampler = class extends Sampler {
2096
+ constructor(device, props) {
2097
+ super(device, props);
2098
+ this.device = device;
2099
+ const samplerProps = {
2100
+ ...this.props
2101
+ };
2102
+ if (samplerProps.type !== "comparison-sampler") {
2103
+ delete samplerProps.compare;
2104
+ }
2105
+ this.handle = this.handle || this.device.handle.createSampler(samplerProps);
2106
+ this.handle.label = this.props.id;
2107
+ }
2108
+ destroy() {
2109
+ }
2110
+ };
2111
+
2112
+ // src/adapter/resources/webgpu-texture.ts
2113
+ var BASE_DIMENSIONS = {
2114
+ "1d": "1d",
2115
+ "2d": "2d",
2116
+ "2d-array": "2d",
2117
+ "cube": "2d",
2118
+ "cube-array": "2d",
2119
+ "3d": "3d"
2120
+ };
2121
+ var WebGPUTexture = class extends Texture {
2122
+ height = 1;
2123
+ width = 1;
2124
+ constructor(device, props) {
2125
+ super(device, props);
2126
+ this.device = device;
2127
+ if (props.data instanceof Promise) {
2128
+ props.data.then((resolvedImageData) => {
2129
+ this.props = {
2130
+ ...props,
2131
+ data: resolvedImageData
2132
+ };
2133
+ this.initialize(this.props);
2134
+ });
2135
+ return;
2136
+ }
2137
+ this.initialize(props);
2138
+ }
2139
+ initialize(props) {
2140
+ this.handle = this.props.handle || this.createHandle();
2141
+ this.handle.label ||= this.id;
2142
+ if (this.props.data) {
2143
+ this.setData({
2144
+ data: this.props.data
2145
+ });
2146
+ }
2147
+ this.width = this.handle.width;
2148
+ this.height = this.handle.height;
2149
+ this.sampler = props.sampler instanceof WebGPUSampler ? props.sampler : new WebGPUSampler(this.device, props.sampler);
2150
+ this.view = this.createView();
2151
+ }
2152
+ createHandle() {
2153
+ const width = this.props.width || this.props.data?.width || 1;
2154
+ const height = this.props.height || this.props.data?.height || 1;
2155
+ return this.device.handle.createTexture({
2156
+ label: this.id,
2157
+ size: {
2158
+ width,
2159
+ height,
2160
+ depthOrArrayLayers: this.props.depth
2161
+ },
2162
+ dimension: BASE_DIMENSIONS[this.props.dimension],
2163
+ format: getWebGPUTextureFormat(this.props.format),
2164
+ usage: this.props.usage,
2165
+ mipLevelCount: this.props.mipLevels,
2166
+ sampleCount: this.props.samples
2167
+ });
2168
+ }
2169
+ destroy() {
2170
+ this.handle.destroy();
2171
+ }
2172
+ setSampler(sampler) {
2173
+ this.sampler = sampler instanceof WebGPUSampler ? sampler : new WebGPUSampler(this.device, sampler);
2174
+ return this;
2175
+ }
2176
+ setData(options) {
2177
+ return this.setImage({
2178
+ source: options.data
2179
+ });
2180
+ }
2181
+ setImage(options) {
2182
+ const {
2183
+ source,
2184
+ width = options.source.width,
2185
+ height = options.source.height,
2186
+ depth = 1,
2187
+ sourceX = 0,
2188
+ sourceY = 0,
2189
+ mipLevel = 0,
2190
+ x = 0,
2191
+ y = 0,
2192
+ z = 0,
2193
+ aspect = "all",
2194
+ colorSpace = "srgb",
2195
+ premultipliedAlpha = false
2196
+ } = options;
2197
+ this.device.handle.queue.copyExternalImageToTexture({
2198
+ source,
2199
+ origin: [sourceX, sourceY]
2200
+ }, {
2201
+ texture: this.handle,
2202
+ origin: [x, y, z],
2203
+ mipLevel,
2204
+ aspect,
2205
+ colorSpace,
2206
+ premultipliedAlpha
2207
+ }, [width, height, depth]);
2208
+ return {
2209
+ width,
2210
+ height
2211
+ };
2212
+ }
2213
+ createView() {
2214
+ return this.handle.createView({
2215
+ label: this.id
2216
+ });
2217
+ }
2218
+ };
2219
+
2220
+ // src/adapter/resources/webgpu-external-texture.ts
2221
+ var WebGPUExternalTexture = class extends ExternalTexture {
2222
+ constructor(device, props) {
2223
+ super(device, props);
2224
+ this.device = device;
2225
+ this.handle = this.props.handle || this.device.handle.importExternalTexture({
2226
+ source: props.source,
2227
+ colorSpace: props.colorSpace
2228
+ });
2229
+ this.sampler = null;
2230
+ }
2231
+ destroy() {
2232
+ }
2233
+ setSampler(sampler) {
2234
+ this.sampler = sampler instanceof WebGPUSampler ? sampler : new WebGPUSampler(this.device, sampler);
2235
+ return this;
2236
+ }
2237
+ };
2238
+
2239
+ // src/adapter/resources/webgpu-shader.ts
2240
+ var WebGPUShader = class extends Shader {
2241
+ constructor(device, props) {
2242
+ super(device, props);
2243
+ this.device = device;
2244
+ this.device.handle.pushErrorScope("validation");
2245
+ this.handle = this.props.handle || this.createHandle();
2246
+ this.handle.label = this.props.id;
2247
+ this._checkCompilationError(this.device.handle.popErrorScope());
2248
+ }
2249
+ async _checkCompilationError(errorScope) {
2250
+ const error = await errorScope;
2251
+ if (error) {
2252
+ this.debugShader();
2253
+ const shaderLog = await this.getCompilationInfo();
2254
+ log.error(`Shader compilation error: ${error.message}`, shaderLog)();
2255
+ throw new Error(`Shader compilation error: ${error.message}`);
2256
+ }
2257
+ }
2258
+ destroy() {
2259
+ }
2260
+ async getCompilationInfo() {
2261
+ const compilationInfo = await this.handle.getCompilationInfo();
2262
+ return compilationInfo.messages;
2263
+ }
2264
+ createHandle() {
2265
+ const {
2266
+ source,
2267
+ stage
2268
+ } = this.props;
2269
+ let language = this.props.language;
2270
+ if (language === "auto") {
2271
+ language = source.includes("->") ? "wgsl" : "glsl";
2272
+ }
2273
+ switch (language) {
2274
+ case "wgsl":
2275
+ return this.device.handle.createShaderModule({
2276
+ code: source
2277
+ });
2278
+ case "glsl":
2279
+ return this.device.handle.createShaderModule({
2280
+ code: source,
2281
+ transform: (glsl) => this.device.glslang.compileGLSL(glsl, stage)
2282
+ });
2283
+ default:
2284
+ throw new Error(language);
2285
+ }
2286
+ }
2287
+ };
2288
+
2289
+ // src/adapter/helpers/webgpu-parameters.ts
2290
+ function addDepthStencil(descriptor) {
2291
+ descriptor.depthStencil = descriptor.depthStencil || {
2292
+ format: "depth24plus",
2293
+ stencilFront: {},
2294
+ stencilBack: {},
2295
+ depthWriteEnabled: false,
2296
+ depthCompare: "less-equal"
2297
+ };
2298
+ return descriptor.depthStencil;
2299
+ }
2300
+ var PARAMETER_TABLE = {
2301
+ cullMode: (parameter, value, descriptor) => {
2302
+ descriptor.primitive = descriptor.primitive || {};
2303
+ descriptor.primitive.cullMode = value;
2304
+ },
2305
+ frontFace: (parameter, value, descriptor) => {
2306
+ descriptor.primitive = descriptor.primitive || {};
2307
+ descriptor.primitive.frontFace = value;
2308
+ },
2309
+ depthWriteEnabled: (parameter, value, descriptor) => {
2310
+ const depthStencil = addDepthStencil(descriptor);
2311
+ depthStencil.depthWriteEnabled = value;
2312
+ },
2313
+ depthCompare: (parameter, value, descriptor) => {
2314
+ const depthStencil = addDepthStencil(descriptor);
2315
+ depthStencil.depthCompare = value;
2316
+ },
2317
+ depthFormat: (parameter, value, descriptor) => {
2318
+ const depthStencil = addDepthStencil(descriptor);
2319
+ depthStencil.format = value;
2320
+ },
2321
+ depthBias: (parameter, value, descriptor) => {
2322
+ const depthStencil = addDepthStencil(descriptor);
2323
+ depthStencil.depthBias = value;
2324
+ },
2325
+ depthBiasSlopeScale: (parameter, value, descriptor) => {
2326
+ const depthStencil = addDepthStencil(descriptor);
2327
+ depthStencil.depthBiasSlopeScale = value;
2328
+ },
2329
+ depthBiasClamp: (parameter, value, descriptor) => {
2330
+ const depthStencil = addDepthStencil(descriptor);
2331
+ depthStencil.depthBiasClamp = value;
2332
+ },
2333
+ stencilReadMask: (parameter, value, descriptor) => {
2334
+ const depthStencil = addDepthStencil(descriptor);
2335
+ depthStencil.stencilReadMask = value;
2336
+ },
2337
+ stencilWriteMask: (parameter, value, descriptor) => {
2338
+ const depthStencil = addDepthStencil(descriptor);
2339
+ depthStencil.stencilWriteMask = value;
2340
+ },
2341
+ stencilCompare: (parameter, value, descriptor) => {
2342
+ const depthStencil = addDepthStencil(descriptor);
2343
+ depthStencil.stencilFront.compare = value;
2344
+ depthStencil.stencilBack.compare = value;
2345
+ },
2346
+ stencilPassOperation: (parameter, value, descriptor) => {
2347
+ const depthStencil = addDepthStencil(descriptor);
2348
+ depthStencil.stencilFront.passOp = value;
2349
+ depthStencil.stencilBack.passOp = value;
2350
+ },
2351
+ stencilFailOperation: (parameter, value, descriptor) => {
2352
+ const depthStencil = addDepthStencil(descriptor);
2353
+ depthStencil.stencilFront.failOp = value;
2354
+ depthStencil.stencilBack.failOp = value;
2355
+ },
2356
+ stencilDepthFailOperation: (parameter, value, descriptor) => {
2357
+ const depthStencil = addDepthStencil(descriptor);
2358
+ depthStencil.stencilFront.depthFailOp = value;
2359
+ depthStencil.stencilBack.depthFailOp = value;
2360
+ },
2361
+ sampleCount: (parameter, value, descriptor) => {
2362
+ descriptor.multisample = descriptor.multisample || {};
2363
+ descriptor.multisample.count = value;
2364
+ },
2365
+ sampleMask: (parameter, value, descriptor) => {
2366
+ descriptor.multisample = descriptor.multisample || {};
2367
+ descriptor.multisample.mask = value;
2368
+ },
2369
+ sampleAlphaToCoverageEnabled: (parameter, value, descriptor) => {
2370
+ descriptor.multisample = descriptor.multisample || {};
2371
+ descriptor.multisample.alphaToCoverageEnabled = value;
2372
+ },
2373
+ colorMask: (parameter, value, descriptor) => {
2374
+ const targets = addColorState(descriptor);
2375
+ targets[0].writeMask = value;
2376
+ },
2377
+ blendColorOperation: (parameter, value, descriptor) => {
2378
+ addColorState(descriptor);
2379
+ }
2380
+ };
2381
+ var DEFAULT_PIPELINE_DESCRIPTOR = {
2382
+ primitive: {
2383
+ cullMode: "back",
2384
+ topology: "triangle-list"
2385
+ },
2386
+ vertex: {
2387
+ module: void 0,
2388
+ entryPoint: "main"
2389
+ },
2390
+ fragment: {
2391
+ module: void 0,
2392
+ entryPoint: "main",
2393
+ targets: []
2394
+ },
2395
+ layout: "auto"
2396
+ };
2397
+ function applyParametersToRenderPipelineDescriptor(pipelineDescriptor, parameters = {}) {
2398
+ Object.assign(pipelineDescriptor, {
2399
+ ...DEFAULT_PIPELINE_DESCRIPTOR,
2400
+ ...pipelineDescriptor
2401
+ });
2402
+ setParameters(pipelineDescriptor, parameters);
2403
+ }
2404
+ function setParameters(pipelineDescriptor, parameters) {
2405
+ for (const [key, value] of Object.entries(parameters)) {
2406
+ const setterFunction = PARAMETER_TABLE[key];
2407
+ if (!setterFunction) {
2408
+ throw new Error(`Illegal parameter ${key}`);
2409
+ }
2410
+ setterFunction(key, value, pipelineDescriptor);
2411
+ }
2412
+ }
2413
+ function addColorState(descriptor) {
2414
+ descriptor.fragment.targets = descriptor.fragment?.targets || [];
2415
+ if (!Array.isArray(descriptor.fragment?.targets)) {
2416
+ throw new Error("colorstate");
2417
+ }
2418
+ if (descriptor.fragment?.targets?.length === 0) {
2419
+ descriptor.fragment.targets?.push({});
2420
+ }
2421
+ return descriptor.fragment?.targets;
2422
+ }
2423
+
2424
+ // src/adapter/helpers/get-bind-group.ts
2425
+ function getBindGroup(device, bindGroupLayout, shaderLayout, bindings) {
2426
+ const entries = getBindGroupEntries(bindings, shaderLayout);
2427
+ return device.createBindGroup({
2428
+ layout: bindGroupLayout,
2429
+ entries
2430
+ });
2431
+ }
2432
+ function getShaderLayoutBinding(shaderLayout, bindingName) {
2433
+ const bindingLayout = shaderLayout.bindings.find((binding) => binding.name === bindingName || `${binding.name}uniforms` === bindingName.toLocaleLowerCase());
2434
+ if (!bindingLayout) {
2435
+ log.warn(`Binding ${bindingName} not set: Not found in shader layout.`)();
2436
+ }
2437
+ return bindingLayout;
2438
+ }
2439
+ function getBindGroupEntries(bindings, shaderLayout) {
2440
+ const entries = [];
2441
+ for (const [bindingName, value] of Object.entries(bindings)) {
2442
+ const bindingLayout = getShaderLayoutBinding(shaderLayout, bindingName);
2443
+ if (bindingLayout) {
2444
+ entries.push(getBindGroupEntry(value, bindingLayout.location));
2445
+ }
2446
+ }
2447
+ return entries;
2448
+ }
2449
+ function getBindGroupEntry(binding, index) {
2450
+ if (binding instanceof Buffer2) {
2451
+ return {
2452
+ binding: index,
2453
+ resource: {
2454
+ buffer: cast(binding).handle
2455
+ }
2456
+ };
2457
+ }
2458
+ if (binding instanceof Sampler) {
2459
+ return {
2460
+ binding: index,
2461
+ resource: cast(binding).handle
2462
+ };
2463
+ } else if (binding instanceof Texture) {
2464
+ return {
2465
+ binding: index,
2466
+ resource: cast(binding).handle.createView({
2467
+ label: "bind-group-auto-created"
2468
+ })
2469
+ };
2470
+ }
2471
+ throw new Error("invalid binding");
2472
+ }
2473
+
2474
+ // src/adapter/helpers/get-vertex-buffer-layout.ts
2475
+ function getWebGPUVertexFormat(format) {
2476
+ if (format.endsWith("-webgl")) {
2477
+ throw new Error(`WebGPU does not support vertex format ${format}`);
2478
+ }
2479
+ return format;
2480
+ }
2481
+ function getVertexBufferLayout(shaderLayout, bufferLayout) {
2482
+ const vertexBufferLayouts = [];
2483
+ const usedAttributes = /* @__PURE__ */ new Set();
2484
+ for (const mapping of bufferLayout) {
2485
+ const vertexAttributes = [];
2486
+ let stepMode = "vertex";
2487
+ let byteStride = 0;
2488
+ if (mapping.attributes) {
2489
+ for (const attributeMapping of mapping.attributes) {
2490
+ const attributeName = attributeMapping.attribute;
2491
+ const attributeLayout = findAttributeLayout(shaderLayout, attributeName, usedAttributes);
2492
+ stepMode = attributeLayout.stepMode || (attributeLayout.name.startsWith("instance") ? "instance" : "vertex");
2493
+ vertexAttributes.push({
2494
+ format: getWebGPUVertexFormat(attributeMapping.format || mapping.format),
2495
+ offset: attributeMapping.byteOffset,
2496
+ shaderLocation: attributeLayout.location
2497
+ });
2498
+ byteStride += decodeVertexFormat(mapping.format).byteLength;
2499
+ }
2500
+ } else {
2501
+ const attributeLayout = findAttributeLayout(shaderLayout, mapping.name, usedAttributes);
2502
+ if (!attributeLayout) {
2503
+ continue;
2504
+ }
2505
+ byteStride = decodeVertexFormat(mapping.format).byteLength;
2506
+ stepMode = attributeLayout.stepMode || (attributeLayout.name.startsWith("instance") ? "instance" : "vertex");
2507
+ vertexAttributes.push({
2508
+ format: getWebGPUVertexFormat(mapping.format),
2509
+ offset: 0,
2510
+ shaderLocation: attributeLayout.location
2511
+ });
2512
+ }
2513
+ vertexBufferLayouts.push({
2514
+ arrayStride: mapping.byteStride || byteStride,
2515
+ stepMode,
2516
+ attributes: vertexAttributes
2517
+ });
2518
+ }
2519
+ for (const attribute of shaderLayout.attributes) {
2520
+ if (!usedAttributes.has(attribute.name)) {
2521
+ vertexBufferLayouts.push({
2522
+ arrayStride: decodeVertexFormat("float32x3").byteLength,
2523
+ stepMode: attribute.stepMode || (attribute.name.startsWith("instance") ? "instance" : "vertex"),
2524
+ attributes: [{
2525
+ format: getWebGPUVertexFormat("float32x3"),
2526
+ offset: 0,
2527
+ shaderLocation: attribute.location
2528
+ }]
2529
+ });
2530
+ }
2531
+ }
2532
+ return vertexBufferLayouts;
2533
+ }
2534
+ function findAttributeLayout(shaderLayout, name2, attributeNames) {
2535
+ const attribute = shaderLayout.attributes.find((attribute2) => attribute2.name === name2);
2536
+ if (!attribute) {
2537
+ log.warn(`Unknown attribute ${name2}`)();
2538
+ return null;
2539
+ }
2540
+ if (attributeNames.has(name2)) {
2541
+ throw new Error(`Duplicate attribute ${name2}`);
2542
+ }
2543
+ attributeNames.add(name2);
2544
+ return attribute;
2545
+ }
2546
+
2547
+ // src/adapter/resources/webgpu-render-pipeline.ts
2548
+ var WebGPURenderPipeline = class extends RenderPipeline {
2549
+ fs = null;
2550
+ _bindGroupLayout = null;
2551
+ _bindGroup = null;
2552
+ constructor(device, props) {
2553
+ super(device, props);
2554
+ this.device = device;
2555
+ this.handle = this.props.handle;
2556
+ if (!this.handle) {
2557
+ const descriptor = this._getRenderPipelineDescriptor();
2558
+ log.groupCollapsed(1, `new WebGPURenderPipeline(${this.id})`)();
2559
+ log.probe(1, JSON.stringify(descriptor, null, 2))();
2560
+ log.groupEnd(1)();
2561
+ this.handle = this.device.handle.createRenderPipeline(descriptor);
2562
+ }
2563
+ this.handle.label = this.props.id;
2564
+ this.vs = cast(props.vs);
2565
+ this.fs = cast(props.fs);
2566
+ }
2567
+ destroy() {
2568
+ }
2569
+ setBindings(bindings) {
2570
+ Object.assign(this.props.bindings, bindings);
2571
+ }
2572
+ setUniforms(uniforms) {
2573
+ if (!isObjectEmpty(uniforms)) {
2574
+ throw new Error("WebGPU does not support uniforms");
2575
+ }
2576
+ }
2577
+ draw(options) {
2578
+ const webgpuRenderPass = cast(options.renderPass) || this.device.getDefaultRenderPass();
2579
+ webgpuRenderPass.handle.setPipeline(this.handle);
2580
+ const bindGroup = this._getBindGroup();
2581
+ if (bindGroup) {
2582
+ webgpuRenderPass.handle.setBindGroup(0, bindGroup);
2583
+ }
2584
+ options.vertexArray.bindBeforeRender(options.renderPass);
2585
+ if (options.indexCount) {
2586
+ webgpuRenderPass.handle.drawIndexed(options.indexCount, options.instanceCount, options.firstIndex, options.baseVertex, options.firstInstance);
2587
+ } else {
2588
+ webgpuRenderPass.handle.draw(options.vertexCount || 0, options.instanceCount || 1, options.firstInstance);
2589
+ }
2590
+ options.vertexArray.unbindAfterRender(options.renderPass);
2591
+ }
2592
+ _getBindGroup() {
2593
+ this._bindGroupLayout = this._bindGroupLayout || this.handle.getBindGroupLayout(0);
2594
+ this._bindGroup = this._bindGroup || getBindGroup(this.device.handle, this._bindGroupLayout, this.props.shaderLayout, this.props.bindings);
2595
+ return this._bindGroup;
2596
+ }
2597
+ _getRenderPipelineDescriptor() {
2598
+ const vertex = {
2599
+ module: cast(this.props.vs).handle,
2600
+ entryPoint: this.props.vsEntryPoint || "main",
2601
+ buffers: getVertexBufferLayout(this.props.shaderLayout, this.props.bufferLayout)
2602
+ };
2603
+ let fragment;
2604
+ if (this.props.fs) {
2605
+ fragment = {
2606
+ module: cast(this.props.fs).handle,
2607
+ entryPoint: this.props.fsEntryPoint || "main",
2608
+ targets: [{
2609
+ format: getWebGPUTextureFormat(this.device?.canvasContext?.format)
2610
+ }]
2611
+ };
2612
+ }
2613
+ switch (this.props.topology) {
2614
+ case "triangle-fan-webgl":
2615
+ case "line-loop-webgl":
2616
+ throw new Error(`WebGPU does not support primitive topology ${this.props.topology}`);
2617
+ default:
2618
+ }
2619
+ const descriptor = {
2620
+ vertex,
2621
+ fragment,
2622
+ primitive: {
2623
+ topology: this.props.topology
2624
+ },
2625
+ layout: "auto"
2626
+ };
2627
+ applyParametersToRenderPipelineDescriptor(descriptor, this.props.parameters);
2628
+ return descriptor;
2629
+ }
2630
+ };
2631
+
2632
+ // src/adapter/resources/webgpu-compute-pipeline.ts
2633
+ var WebGPUComputePipeline = class extends ComputePipeline {
2634
+ constructor(device, props) {
2635
+ super(device, props);
2636
+ this.device = device;
2637
+ const webgpuShader = this.props.cs;
2638
+ this.handle = this.props.handle || this.device.handle.createComputePipeline({
2639
+ label: this.props.id,
2640
+ compute: {
2641
+ module: webgpuShader.handle,
2642
+ entryPoint: this.props.csEntryPoint
2643
+ },
2644
+ layout: "auto"
2645
+ });
2646
+ }
2647
+ _getBindGroupLayout() {
2648
+ return this.handle.getBindGroupLayout(0);
2649
+ }
2650
+ };
2651
+
2652
+ // src/adapter/resources/webgpu-render-pass.ts
2653
+ var WebGPURenderPass = class extends RenderPass {
2654
+ pipeline = null;
2655
+ constructor(device, props = {}) {
2656
+ super(device, props);
2657
+ this.device = device;
2658
+ const framebuffer = props.framebuffer || device.canvasContext.getCurrentFramebuffer();
2659
+ const renderPassDescriptor = this.getRenderPassDescriptor(framebuffer);
2660
+ log.groupCollapsed(3, `new WebGPURenderPass(${this.id})`)();
2661
+ log.probe(3, JSON.stringify(renderPassDescriptor, null, 2))();
2662
+ log.groupEnd(3)();
2663
+ this.handle = this.props.handle || device.commandEncoder.beginRenderPass(renderPassDescriptor);
2664
+ this.handle.label = this.props.id;
2665
+ }
2666
+ destroy() {
2667
+ }
2668
+ end() {
2669
+ this.handle.end();
2670
+ }
2671
+ setPipeline(pipeline) {
2672
+ this.pipeline = cast(pipeline);
2673
+ this.handle.setPipeline(this.pipeline.handle);
2674
+ }
2675
+ setBindings(bindings) {
2676
+ this.pipeline?.setBindings(bindings);
2677
+ const bindGroup = this.pipeline?._getBindGroup();
2678
+ if (bindGroup) {
2679
+ this.handle.setBindGroup(0, bindGroup);
2680
+ }
2681
+ }
2682
+ setIndexBuffer(buffer, indexFormat, offset = 0, size) {
2683
+ this.handle.setIndexBuffer(cast(buffer).handle, indexFormat, offset, size);
2684
+ }
2685
+ setVertexBuffer(slot, buffer, offset = 0) {
2686
+ this.handle.setVertexBuffer(slot, cast(buffer).handle, offset);
2687
+ }
2688
+ draw(options) {
2689
+ if (options.indexCount) {
2690
+ this.handle.drawIndexed(options.indexCount, options.instanceCount, options.firstIndex, options.baseVertex, options.firstInstance);
2691
+ } else {
2692
+ this.handle.draw(options.vertexCount || 0, options.instanceCount || 1, options.firstIndex, options.firstInstance);
2693
+ }
2694
+ }
2695
+ drawIndirect() {
2696
+ }
2697
+ setParameters(parameters) {
2698
+ const {
2699
+ blendConstant,
2700
+ stencilReference,
2701
+ scissorRect,
2702
+ viewport
2703
+ } = parameters;
2704
+ if (blendConstant) {
2705
+ this.handle.setBlendConstant(blendConstant);
2706
+ }
2707
+ if (stencilReference) {
2708
+ this.handle.setStencilReference(stencilReference);
2709
+ }
2710
+ if (scissorRect) {
2711
+ this.handle.setScissorRect(scissorRect[0], scissorRect[1], scissorRect[2], scissorRect[3]);
2712
+ }
2713
+ if (viewport) {
2714
+ this.handle.setViewport(viewport[0], viewport[1], viewport[2], viewport[3], viewport[4], viewport[5]);
2715
+ }
2716
+ }
2717
+ pushDebugGroup(groupLabel) {
2718
+ this.handle.pushDebugGroup(groupLabel);
2719
+ }
2720
+ popDebugGroup() {
2721
+ this.handle.popDebugGroup();
2722
+ }
2723
+ insertDebugMarker(markerLabel) {
2724
+ this.handle.insertDebugMarker(markerLabel);
2725
+ }
2726
+ getRenderPassDescriptor(framebuffer) {
2727
+ const renderPassDescriptor = {
2728
+ colorAttachments: []
2729
+ };
2730
+ renderPassDescriptor.colorAttachments = framebuffer.colorAttachments.map((colorAttachment) => ({
2731
+ loadOp: this.props.clearColor !== false ? "clear" : "load",
2732
+ colorClearValue: this.props.clearColor || [0, 0, 0, 0],
2733
+ storeOp: this.props.discard ? "discard" : "store",
2734
+ view: colorAttachment.createView()
2735
+ }));
2736
+ if (framebuffer.depthStencilAttachment) {
2737
+ renderPassDescriptor.depthStencilAttachment = {
2738
+ view: framebuffer.depthStencilAttachment.createView()
2739
+ };
2740
+ const {
2741
+ depthStencilAttachment
2742
+ } = renderPassDescriptor;
2743
+ if (this.props.depthReadOnly) {
2744
+ depthStencilAttachment.depthReadOnly = true;
2745
+ }
2746
+ depthStencilAttachment.depthClearValue = this.props.clearDepth || 0;
2747
+ const hasDepthAspect = true;
2748
+ if (hasDepthAspect) {
2749
+ depthStencilAttachment.depthLoadOp = this.props.clearDepth !== false ? "clear" : "load";
2750
+ depthStencilAttachment.depthStoreOp = "store";
2751
+ }
2752
+ const hasStencilAspect = false;
2753
+ if (hasStencilAspect) {
2754
+ depthStencilAttachment.stencilLoadOp = this.props.clearStencil !== false ? "clear" : "load";
2755
+ depthStencilAttachment.stencilStoreOp = "store";
2756
+ }
2757
+ }
2758
+ return renderPassDescriptor;
2759
+ }
2760
+ };
2761
+
2762
+ // src/adapter/resources/webgpu-compute-pass.ts
2763
+ var WebGPUComputePass = class extends ComputePass {
2764
+ _bindGroupLayout = null;
2765
+ constructor(device, props) {
2766
+ super(device, props);
2767
+ this.device = device;
2768
+ this.handle = this.props.handle || device.commandEncoder?.beginComputePass({
2769
+ label: this.props.id
2770
+ });
2771
+ }
2772
+ destroy() {
2773
+ }
2774
+ end() {
2775
+ this.handle.end();
2776
+ }
2777
+ setPipeline(pipeline) {
2778
+ const wgpuPipeline = pipeline;
2779
+ this.handle.setPipeline(wgpuPipeline.handle);
2780
+ this._bindGroupLayout = wgpuPipeline._getBindGroupLayout();
2781
+ }
2782
+ setBindings(bindings) {
2783
+ throw new Error("fix me");
2784
+ }
2785
+ dispatch(x, y, z) {
2786
+ this.handle.dispatchWorkgroups(x, y, z);
2787
+ }
2788
+ dispatchIndirect(indirectBuffer, indirectOffset = 0) {
2789
+ const webgpuBuffer = indirectBuffer;
2790
+ this.handle.dispatchWorkgroupsIndirect(webgpuBuffer.handle, indirectOffset);
2791
+ }
2792
+ pushDebugGroup(groupLabel) {
2793
+ this.handle.pushDebugGroup(groupLabel);
2794
+ }
2795
+ popDebugGroup() {
2796
+ this.handle.popDebugGroup();
2797
+ }
2798
+ insertDebugMarker(markerLabel) {
2799
+ this.handle.insertDebugMarker(markerLabel);
2800
+ }
2801
+ };
2802
+
2803
+ // src/adapter/resources/webgpu-vertex-array.ts
2804
+ var WebGPUVertexArray = class extends VertexArray {
2805
+ get [Symbol.toStringTag]() {
2806
+ return "WebGPUVertexArray";
2807
+ }
2808
+ static isConstantAttributeZeroSupported(device) {
2809
+ return device.info.type === "webgl2" || getBrowser() === "Chrome";
2810
+ }
2811
+ constructor(device, props) {
2812
+ super(device, props);
2813
+ this.device = device;
2814
+ }
2815
+ destroy() {
2816
+ }
2817
+ setIndexBuffer(buffer) {
2818
+ this.indexBuffer = buffer;
2819
+ }
2820
+ setBuffer(bufferSlot, buffer) {
2821
+ this.attributes[bufferSlot] = buffer;
2822
+ }
2823
+ setConstant(location, value) {
2824
+ log.warn(`${this.id} constant attributes not supported on WebGPU`);
2825
+ }
2826
+ bindBeforeRender(renderPass, firstIndex, indexCount) {
2827
+ const webgpuRenderPass = renderPass;
2828
+ const webgpuIndexBuffer = this.indexBuffer;
2829
+ if (webgpuIndexBuffer?.handle) {
2830
+ log.warn("setting index buffer", webgpuIndexBuffer?.handle, webgpuIndexBuffer?.indexType)();
2831
+ webgpuRenderPass.handle.setIndexBuffer(webgpuIndexBuffer?.handle, webgpuIndexBuffer?.indexType);
2832
+ }
2833
+ for (let location = 0; location < this.maxVertexAttributes; location++) {
2834
+ const webgpuBuffer = this.attributes[location];
2835
+ if (webgpuBuffer?.handle) {
2836
+ log.warn(`setting vertex buffer ${location}`, webgpuBuffer?.handle)();
2837
+ webgpuRenderPass.handle.setVertexBuffer(location, webgpuBuffer?.handle);
2838
+ }
2839
+ }
2840
+ }
2841
+ unbindAfterRender(renderPass) {
2842
+ }
2843
+ };
2844
+
2845
+ // src/adapter/resources/webgpu-framebuffer.ts
2846
+ var WebGPUFramebuffer = class extends Framebuffer {
2847
+ constructor(device, props) {
2848
+ super(device, props);
2849
+ this.device = device;
2850
+ this.autoCreateAttachmentTextures();
2851
+ }
2852
+ };
2853
+
2854
+ // src/adapter/webgpu-canvas-context.ts
2855
+ var WebGPUCanvasContext = class extends CanvasContext {
2856
+ format = navigator.gpu.getPreferredCanvasFormat();
2857
+ depthStencilFormat = "depth24plus";
2858
+ depthStencilAttachment = null;
2859
+ constructor(device, adapter, props) {
2860
+ super(props);
2861
+ this.device = device;
2862
+ this.width = -1;
2863
+ this.height = -1;
2864
+ this._setAutoCreatedCanvasId(`${this.device.id}-canvas`);
2865
+ this.gpuCanvasContext = this.canvas.getContext("webgpu");
2866
+ this.format = "bgra8unorm";
2867
+ }
2868
+ destroy() {
2869
+ this.gpuCanvasContext.unconfigure();
2870
+ }
2871
+ getCurrentFramebuffer() {
2872
+ this.update();
2873
+ const currentColorAttachment = this.getCurrentTexture();
2874
+ this.width = currentColorAttachment.width;
2875
+ this.height = currentColorAttachment.height;
2876
+ this._createDepthStencilAttachment();
2877
+ return new WebGPUFramebuffer(this.device, {
2878
+ colorAttachments: [currentColorAttachment],
2879
+ depthStencilAttachment: this.depthStencilAttachment
2880
+ });
2881
+ }
2882
+ update() {
2883
+ const [width, height] = this.getPixelSize();
2884
+ const sizeChanged = width !== this.width || height !== this.height;
2885
+ if (sizeChanged) {
2886
+ this.width = width;
2887
+ this.height = height;
2888
+ if (this.depthStencilAttachment) {
2889
+ this.depthStencilAttachment.destroy();
2890
+ this.depthStencilAttachment = null;
2891
+ }
2892
+ this.gpuCanvasContext.configure({
2893
+ device: this.device.handle,
2894
+ format: getWebGPUTextureFormat(this.format),
2895
+ colorSpace: this.props.colorSpace,
2896
+ alphaMode: this.props.alphaMode
2897
+ });
2898
+ log.log(1, `Resized to ${this.width}x${this.height}px`)();
2899
+ }
2900
+ }
2901
+ resize(options) {
2902
+ this.update();
2903
+ }
2904
+ getCurrentTexture() {
2905
+ return this.device._createTexture({
2906
+ id: `${this.id}#color-texture`,
2907
+ handle: this.gpuCanvasContext.getCurrentTexture()
2908
+ });
2909
+ }
2910
+ _createDepthStencilAttachment() {
2911
+ if (!this.depthStencilAttachment) {
2912
+ this.depthStencilAttachment = this.device.createTexture({
2913
+ id: `${this.id}#depth-stencil-texture`,
2914
+ format: this.depthStencilFormat,
2915
+ width: this.width,
2916
+ height: this.height,
2917
+ usage: GPUTextureUsage.RENDER_ATTACHMENT
2918
+ });
2919
+ }
2920
+ return this.depthStencilAttachment;
2921
+ }
2922
+ };
2923
+
2924
+ // src/adapter/webgpu-device.ts
2925
+ var _WebGPUDevice = class extends Device {
2926
+ canvasContext = null;
2927
+ commandEncoder = null;
2928
+ renderPass = null;
2929
+ _isLost = false;
2930
+ static isSupported() {
2931
+ return Boolean(typeof navigator !== "undefined" && navigator.gpu);
2932
+ }
2933
+ static async create(props) {
2934
+ if (!navigator.gpu) {
2935
+ throw new Error("WebGPU not available. Open in Chrome Canary and turn on chrome://flags/#enable-unsafe-webgpu");
2936
+ }
2937
+ log.groupCollapsed(1, "WebGPUDevice created")();
2938
+ const adapter = await navigator.gpu.requestAdapter({
2939
+ powerPreference: "high-performance"
2940
+ });
2941
+ if (!adapter) {
2942
+ throw new Error("Failed to request WebGPU adapter");
2943
+ }
2944
+ const adapterInfo = await adapter.requestAdapterInfo();
2945
+ log.probe(2, "Adapter available", adapterInfo)();
2946
+ const gpuDevice = await adapter.requestDevice({
2947
+ requiredFeatures: adapter.features
2948
+ });
2949
+ log.probe(1, "GPUDevice available")();
2950
+ if (typeof props.canvas === "string") {
2951
+ await CanvasContext.pageLoaded;
2952
+ log.probe(1, "DOM is loaded")();
2953
+ }
2954
+ const device = new _WebGPUDevice(gpuDevice, adapter, adapterInfo, props);
2955
+ log.probe(1, "Device created. For more info, set chrome://flags/#enable-webgpu-developer-features")();
2956
+ log.table(1, device.info)();
2957
+ log.groupEnd(1)();
2958
+ return device;
2959
+ }
2960
+ constructor(device, adapter, adapterInfo, props) {
2961
+ super({
2962
+ ...props,
2963
+ id: props.id || uid("webgpu-device")
2964
+ });
2965
+ this.handle = device;
2966
+ this.adapter = adapter;
2967
+ const [driver, driverVersion] = (adapterInfo.driver || "").split(" Version ");
2968
+ const vendor = adapterInfo.vendor || this.adapter.__brand || "unknown";
2969
+ const renderer = driver || "";
2970
+ const version = driverVersion || "";
2971
+ const gpu = vendor === "apple" ? "apple" : "unknown";
2972
+ const gpuArchitecture = adapterInfo.architecture || "unknown";
2973
+ const gpuBackend = adapterInfo.backend || "unknown";
2974
+ const gpuType = (adapterInfo.type || "").split(" ")[0].toLowerCase() || "unknown";
2975
+ this._info = {
2976
+ type: "webgpu",
2977
+ vendor,
2978
+ renderer,
2979
+ version,
2980
+ gpu,
2981
+ gpuType,
2982
+ gpuBackend,
2983
+ gpuArchitecture,
2984
+ shadingLanguage: "wgsl",
2985
+ shadingLanguageVersion: 100
2986
+ };
2987
+ this.lost = new Promise(async (resolve) => {
2988
+ const lostInfo = await this.handle.lost;
2989
+ this._isLost = true;
2990
+ resolve({
2991
+ reason: "destroyed",
2992
+ message: lostInfo.message
2993
+ });
2994
+ });
2995
+ this.canvasContext = new WebGPUCanvasContext(this, this.adapter, {
2996
+ canvas: props.canvas,
2997
+ height: props.height,
2998
+ width: props.width,
2999
+ container: props.container
3000
+ });
3001
+ this.features = this._getFeatures();
3002
+ }
3003
+ destroy() {
3004
+ this.handle.destroy();
3005
+ }
3006
+ get info() {
3007
+ return this._info;
3008
+ }
3009
+ get limits() {
3010
+ return this.handle.limits;
3011
+ }
3012
+ isTextureFormatSupported(format) {
3013
+ return !format.includes("webgl");
3014
+ }
3015
+ isTextureFormatFilterable(format) {
3016
+ return this.isTextureFormatSupported(format);
3017
+ }
3018
+ isTextureFormatRenderable(format) {
3019
+ return this.isTextureFormatSupported(format);
3020
+ }
3021
+ get isLost() {
3022
+ return this._isLost;
3023
+ }
3024
+ createBuffer(props) {
3025
+ const newProps = this._getBufferProps(props);
3026
+ return new WebGPUBuffer(this, newProps);
3027
+ }
3028
+ _createTexture(props) {
3029
+ return new WebGPUTexture(this, props);
3030
+ }
3031
+ createExternalTexture(props) {
3032
+ return new WebGPUExternalTexture(this, props);
3033
+ }
3034
+ createShader(props) {
3035
+ return new WebGPUShader(this, props);
3036
+ }
3037
+ createSampler(props) {
3038
+ return new WebGPUSampler(this, props);
3039
+ }
3040
+ createRenderPipeline(props) {
3041
+ return new WebGPURenderPipeline(this, props);
3042
+ }
3043
+ createFramebuffer(props) {
3044
+ throw new Error("Not implemented");
3045
+ }
3046
+ createComputePipeline(props) {
3047
+ return new WebGPUComputePipeline(this, props);
3048
+ }
3049
+ createVertexArray(props) {
3050
+ return new WebGPUVertexArray(this, props);
3051
+ }
3052
+ beginRenderPass(props) {
3053
+ this.commandEncoder = this.commandEncoder || this.handle.createCommandEncoder();
3054
+ return new WebGPURenderPass(this, props);
3055
+ }
3056
+ beginComputePass(props) {
3057
+ this.commandEncoder = this.commandEncoder || this.handle.createCommandEncoder();
3058
+ return new WebGPUComputePass(this, props);
3059
+ }
3060
+ createTransformFeedback(props) {
3061
+ throw new Error("Transform feedback not supported in WebGPU");
3062
+ }
3063
+ createCanvasContext(props) {
3064
+ return new WebGPUCanvasContext(this, this.adapter, props);
3065
+ }
3066
+ getDefaultRenderPass() {
3067
+ throw new Error("a");
3068
+ }
3069
+ submit() {
3070
+ const commandBuffer = this.commandEncoder?.finish();
3071
+ if (commandBuffer) {
3072
+ this.handle.queue.submit([commandBuffer]);
3073
+ }
3074
+ this.commandEncoder = null;
3075
+ }
3076
+ _getFeatures() {
3077
+ const features = new Set(this.handle.features);
3078
+ if (features.has("depth-clamping")) {
3079
+ features.delete("depth-clamping");
3080
+ features.add("depth-clip-control");
3081
+ }
3082
+ if (features.has("texture-compression-bc")) {
3083
+ features.add("texture-compression-bc5-webgl");
3084
+ }
3085
+ features.add("webgpu");
3086
+ features.add("timer-query-webgl");
3087
+ features.add("vertex-array-object-webgl1");
3088
+ features.add("instanced-rendering-webgl1");
3089
+ features.add("multiple-render-targets-webgl1");
3090
+ features.add("index-uint32-webgl1");
3091
+ features.add("blend-minmax-webgl1");
3092
+ features.add("texture-blend-float-webgl1");
3093
+ features.add("texture-formats-srgb-webgl1");
3094
+ features.add("texture-formats-depth-webgl1");
3095
+ features.add("texture-formats-float32-webgl1");
3096
+ features.add("texture-formats-float16-webgl1");
3097
+ features.add("texture-filter-linear-float32-webgl");
3098
+ features.add("texture-filter-linear-float16-webgl");
3099
+ features.add("texture-filter-anisotropic-webgl");
3100
+ features.add("texture-renderable-rgba32float-webgl");
3101
+ features.add("texture-renderable-float32-webgl");
3102
+ features.add("texture-renderable-float16-webgl");
3103
+ features.add("glsl-frag-data");
3104
+ features.add("glsl-frag-depth");
3105
+ features.add("glsl-derivatives");
3106
+ features.add("glsl-texture-lod");
3107
+ return features;
3108
+ }
3109
+ copyExternalImageToTexture(options) {
3110
+ const {
3111
+ source,
3112
+ sourceX = 0,
3113
+ sourceY = 0,
3114
+ texture,
3115
+ mipLevel = 0,
3116
+ aspect = "all",
3117
+ colorSpace = "display-p3",
3118
+ premultipliedAlpha = false,
3119
+ width = texture.width,
3120
+ height = texture.height,
3121
+ depth = 1
3122
+ } = options;
3123
+ const webGpuTexture = texture;
3124
+ this.handle?.queue.copyExternalImageToTexture({
3125
+ source,
3126
+ origin: [sourceX, sourceY]
3127
+ }, {
3128
+ texture: webGpuTexture.handle,
3129
+ origin: [0, 0, 0],
3130
+ mipLevel,
3131
+ aspect,
3132
+ colorSpace,
3133
+ premultipliedAlpha
3134
+ }, [width, height, depth]);
3135
+ }
3136
+ };
3137
+ var WebGPUDevice = _WebGPUDevice;
3138
+ __publicField(WebGPUDevice, "type", "webgpu");
3139
+ return __toCommonJS(src_exports);
3140
+ })();
3141
+ return __exports__;
3142
+ });