@margoengine/voxel 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1670 -2
  4. package/dist/bevel.d.ts +79 -0
  5. package/dist/bevel.js +453 -0
  6. package/dist/blocks-BabtpQT-.js +179 -0
  7. package/dist/blocks.d.ts +220 -0
  8. package/dist/border.d.ts +9 -0
  9. package/dist/chunk-BCoaKSn4.js +158 -0
  10. package/dist/chunk.d.ts +112 -0
  11. package/dist/codec-BmXhcsFt.js +412 -0
  12. package/dist/codec.d.ts +125 -0
  13. package/dist/codec.js +1 -0
  14. package/dist/debris.d.ts +114 -0
  15. package/dist/debris.js +387 -0
  16. package/dist/faces-DUR7LhrN.js +146 -0
  17. package/dist/faces.d.ts +7 -0
  18. package/dist/fluids.d.ts +74 -0
  19. package/dist/fluids.js +226 -0
  20. package/dist/generate.d.ts +78 -0
  21. package/dist/generate.js +99 -0
  22. package/dist/gi.d.ts +76 -0
  23. package/dist/gi.js +264 -0
  24. package/dist/gpu-mesher.d.ts +77 -0
  25. package/dist/gpu-mesher.js +461 -0
  26. package/dist/granular-mpm.d.ts +40 -0
  27. package/dist/granular-mpm.js +46 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +4 -0
  30. package/dist/light-rgb.d.ts +71 -0
  31. package/dist/light-rgb.js +287 -0
  32. package/dist/light-worker.d.ts +84 -0
  33. package/dist/light-worker.js +110 -0
  34. package/dist/light.d.ts +108 -0
  35. package/dist/light.js +332 -0
  36. package/dist/light.worker.d.ts +1 -0
  37. package/dist/lightmap.d.ts +50 -0
  38. package/dist/lightmap.js +68 -0
  39. package/dist/lod.d.ts +87 -0
  40. package/dist/lod.js +182 -0
  41. package/dist/mesher.d.ts +214 -0
  42. package/dist/mesher.js +539 -0
  43. package/dist/mesher.worker.d.ts +1 -0
  44. package/dist/model-data-D_rIKJCQ.js +41 -0
  45. package/dist/model-data.d.ts +21 -0
  46. package/dist/model-mesh-C4Gi6bMM.js +122 -0
  47. package/dist/model-mesh.d.ts +21 -0
  48. package/dist/model-surface.d.ts +5 -0
  49. package/dist/models.d.ts +74 -0
  50. package/dist/models.js +308 -0
  51. package/dist/objects.d.ts +73 -0
  52. package/dist/objects.js +152 -0
  53. package/dist/octants-C_Ic7gdn.js +10 -0
  54. package/dist/octants.d.ts +16 -0
  55. package/dist/origin-DsMelUxs.js +23 -0
  56. package/dist/origin.d.ts +7 -0
  57. package/dist/physics.d.ts +147 -0
  58. package/dist/physics.js +486 -0
  59. package/dist/query.d.ts +166 -0
  60. package/dist/query.js +305 -0
  61. package/dist/render-post.d.ts +6 -0
  62. package/dist/render.d.ts +296 -0
  63. package/dist/render.js +1616 -0
  64. package/dist/shared/borrowed.d.ts +44 -0
  65. package/dist/smooth-CEwHkXli.js +968 -0
  66. package/dist/smooth-clip.d.ts +24 -0
  67. package/dist/smooth-lod.d.ts +118 -0
  68. package/dist/smooth-lod.js +244 -0
  69. package/dist/smooth.d.ts +171 -0
  70. package/dist/smooth.js +1 -0
  71. package/dist/stream.d.ts +201 -0
  72. package/dist/stream.js +402 -0
  73. package/dist/terrain.worker.d.ts +1 -0
  74. package/dist/textures.d.ts +86 -0
  75. package/dist/ticks.d.ts +126 -0
  76. package/dist/ticks.js +239 -0
  77. package/dist/unit-light-Ch7roJgB.js +7 -0
  78. package/dist/vox.d.ts +237 -0
  79. package/dist/vox.js +780 -0
  80. package/dist/wind-data.d.ts +13 -0
  81. package/dist/wind.d.ts +68 -0
  82. package/dist/wind.js +170 -0
  83. package/dist/worker-DlGRxlc4.js +44 -0
  84. package/dist/worker-pool-sPyC6jCE.js +93 -0
  85. package/dist/workers/light.js +1 -0
  86. package/dist/workers/mesher.js +1 -0
  87. package/dist/workers/terrain.js +1 -0
  88. package/dist/world-CelTlft2.js +153 -0
  89. package/dist/world.d.ts +117 -0
  90. package/package.json +173 -4
package/dist/render.js ADDED
@@ -0,0 +1,1616 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const f=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { c as e } from "./chunk-BCoaKSn4.js";
5
+ import { n as t, r as n } from "./worker-pool-sPyC6jCE.js";
6
+ import { r, t as i } from "./faces-DUR7LhrN.js";
7
+ import { VoxelMesher as a, blockMaterials as o, decodeQuad as s, quadCenters as c, sortQuads as l } from "./mesher.js";
8
+ import { t as u } from "./unit-light-Ch7roJgB.js";
9
+ import { MargoError as d } from "@margoengine/math/errors";
10
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
11
+ import { Frustum as p } from "@margoengine/math/frustum";
12
+ import { invertMatrix as m } from "@margoengine/math/mat4";
13
+ //#region ../shared/borrowed.js
14
+ function h(e, t, n) {
15
+ return e.value = t, e.device = typeof t == "function" ? void 0 : n, e.made = void 0, e.told = !1, e;
16
+ }
17
+ function g(e, t) {
18
+ typeof e.value != "function" && (e.device ??= t);
19
+ }
20
+ var _ = (e, t, n, r) => h({
21
+ name: t,
22
+ setter: n
23
+ }, e, r);
24
+ function v(e, n, r) {
25
+ let { value: i } = e;
26
+ if (typeof i == "function") return e.device !== n && (e.made = i(e.device = n)), e.made;
27
+ if (i != null) {
28
+ if (e.device ??= n, e.device === n) return i;
29
+ e.told || (e.told = !0, r?.onError(t("state", `${e.name} lost with the device; pass a function or call ${e.setter}`, "borrowed-lost")));
30
+ }
31
+ }
32
+ var y = "fn pbrNeutral(input:vec3f)->vec3f {let x=min(input.r,min(input.g,input.b));let offset=select(0.04,x-6.25*x*x,x<0.08);var v=input-offset;let peak=max(v.r,max(v.g,v.b));if(peak<0.76){return v;}let newPeak=1.0-0.24*0.24/(peak+0.24-0.76);v*=newPeak/peak;return mix(v,vec3f(newPeak),1.0-1.0/(0.15*(peak-newPeak)+1.0));}\nfn toDisplay(c:vec3f)->vec3f {let x=pbrNeutral(max(c,vec3f(0)));return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>=vec3f(0.0031308));}\n", b = "((1-mix(max(dielectricF0.r,max(dielectricF0.g,dielectricF0.b)),dielectricF90,pow(1-vh,5.0)))*(1-metal)*base/3.14159265+d*g*fresnel/max(4*nl*nv,0.0001))", x = (e, t) => `a2/(3.14159265*pow(max(dot(cross(${e},${t}),cross(${e},${t})),step(nh,0.0))+a2*nh*nh,2.0))`, S = "2.0*nl*nv/max(nl*sqrt(a2+(1.0-a2)*nv*nv)+nv*sqrt(a2+(1.0-a2)*nl*nl),1e-30)", C = /* @__PURE__ */ new WeakMap();
33
+ function w(e, t) {
34
+ let n = C.get(t), r = n?.get(e);
35
+ return r === void 0 ? te(e, t, n) : r;
36
+ }
37
+ var T = /mix\(vec3f\(0\.35,0\.3,0\.25\),vec3f\(1(?:\.0)?\),clamp\(([\w.]+)\.y\*0\.5\+0\.5,0\.0,1\.0\)\)/g, ee = (e) => e.replace(T, "margoSkyHook($1)").replaceAll("*f.radiance.w", ""), E = (e) => e !== void 0 && new RegExp(T.source).test(e);
38
+ function te(e, t, r) {
39
+ let i = (t) => t && (e.includes(" f0:vec3f") ? t : t.replaceAll("s.f0", "vec3f(0.04)")).replaceAll("s.sw", e.includes(" sw:f32") ? "s.sw" : "1.0"), a = e, o = (e, t) => {
40
+ if (typeof e == "string" ? !a.includes(e) : a.search(e) < 0) throw n("unsupported", `PBR lighting hook point missing: ${e}; use matching @margoengine/gltf/pbr and effect package versions`);
41
+ a = a.replace(e, t);
42
+ }, s = e.includes("fn margoAmbientLayers(");
43
+ if (t.direct) {
44
+ let n = t.direct("direct", e.includes("fn margoLightSide(") ? "margoLightSide(s.n,l)" : void 0);
45
+ if (e.includes("var<private> margoDirectVisible:vec3f=vec3f(1);") && n !== "direct") {
46
+ let t = e.includes("fn margoLit(") ? "margoLit(s,l,direct)" : "vec3f(1)";
47
+ o(/(?:let margoAmbient=[^;]*;)?var color=/, (e) => `{let direct=${t};margoDirectVisible=${n};}\n ${e}`), o("direct+ambient(s)", "direct*margoDirectVisible+ambient(s)");
48
+ } else o("direct+ambient(s)", n + "+ambient(s)");
49
+ }
50
+ if (t.light) {
51
+ if (s) {
52
+ let e = a.split("fn margoLocal").length - 1;
53
+ o("var color=", `var color=margoLocal${e}(i,margoFront(s),v)+`), a += `\nfn margoLocal${e}(i:Out,s:Surface,v:vec3f)->vec3f {return ${i(t.light)};}\n`;
54
+ } else o("var color=", "var color=" + i(t.light) + "+");
55
+ }
56
+ let c = a.includes("fn margoSkyHook(");
57
+ t.ambient && ((!c || E(t.ambient)) && o(/fn ambient\(s:Surface\)->vec3f \{[^}]*\}/, "fn ambient(s:Surface)->vec3f {return vec3f(0);}"), s && o("fn margoAmbientTerm(i:Out,s:Surface,v:vec3f)->vec3f {return vec3f(0);}", () => `fn margoAmbientTerm(i:Out,s:Surface,v:vec3f)->vec3f {return ${i(t.ambient)};}`), o(/var color=([^;]+)\+s\.emissive;/, (e, n) => `let margoAmbient=${s ? "margoAmbientLayers(i,s,v)" : i(t.ambient)};var color=${n}+s.emissive+margoAmbient;`));
58
+ for (let [e, n] of [["margoCoatAmbient", t.coat], ["margoSheenAmbient", t.sheen]]) n && a.includes(`fn ${e}(`) && o(RegExp(`fn ${e}\\(s:Surface,v:vec3f\\)->vec3f \\{return [^;]*;\\}`), () => `fn ${e}(s:Surface,v:vec3f)->vec3f {return ${n};}`);
59
+ if (t.sky) {
60
+ if (c) throw n("unsupported", "Two sky lighting hooks on one shader; attach one HemisphereLight per engine");
61
+ let e = /let margoAmbient=([^;]*);/.exec(a)?.[1], r = /fn margoAmbientTerm\(i:Out,s:Surface,v:vec3f\)->vec3f \{return ([^;]*);\}/.exec(a)?.[1];
62
+ e !== void 0 && !E(e) && !E(r) && o("fn ambient(s:Surface)->vec3f {return vec3f(0);}", `fn ambient(s:Surface)->vec3f {${a.includes("fn margoHemisphere(") ? "return margoHemisphere(s);" : a.includes("fn hemisphere_ambient(") ? "return hemisphere_ambient(s);" : "let f0=mix(vec3f(0.04),s.base.rgb,s.metal);return (s.base.rgb*(1.0-s.metal)+f0*0.5)*margoSkyHook(s.n)*s.occlusion;"}}`), a += `
63
+ fn margoSkyHook(n:vec3f)->vec3f {return ${t.sky};}
64
+ `;
65
+ }
66
+ (t.sky || c) && (a = ee(a));
67
+ let l = "if(f.settings.w<0.5) {color=toDisplay(color);}";
68
+ if (t.output) {
69
+ let e = a.includes(l);
70
+ o(e ? l : "if(f.settings.w<0.5) {color=pbrNeutral(max(color,vec3f(0)));", `color=${t.output("select(color,pbrNeutral(max(color,vec3f(0))),f.settings.w<0.5)")};if(f.settings.w<0.5) {${e ? "color=select(color*12.92,1.055*pow(color,vec3f(1.0/2.4))-0.055,color>=vec3f(0.0031308));}" : ""}`);
71
+ }
72
+ return a = t.declarations + a, t.finish && (a = t.finish(a)), r || C.set(t, r = /* @__PURE__ */ new Map()), r.size >= 64 && r.clear(), r.set(e, a), a;
73
+ }
74
+ //#endregion
75
+ //#region ../shared/view.js
76
+ function ne(e, t) {
77
+ let n = t.position, r = t.up ?? [
78
+ 0,
79
+ 1,
80
+ 0
81
+ ], i = n[0] - t.target[0], a = n[1] - t.target[1], o = n[2] - t.target[2], s = Math.abs(i), c = Math.abs(a), l = Math.abs(o), u = s > c ? s : c, d = u > l ? u : l, f;
82
+ if (s === Infinity || c === Infinity || l === Infinity) f = Infinity;
83
+ else if (s !== s || c !== c || l !== l) f = s + c + l;
84
+ else if (d === 0) f = 0;
85
+ else {
86
+ let e = s / d * (s / d), t = c / d * (c / d), n = e + t - e - t, r = l / d * (l / d) - n;
87
+ f = Math.sqrt(e + t + r) * d;
88
+ }
89
+ i /= f, a /= f, o /= f;
90
+ let p = r[1] * o - r[2] * a, m = r[2] * i - r[0] * o, h = r[0] * a - r[1] * i, g = Math.abs(p), _ = Math.abs(m), v = Math.abs(h), y = g > _ ? g : _, b = y > v ? y : v, x;
91
+ if (g === Infinity || _ === Infinity || v === Infinity) x = Infinity;
92
+ else if (g !== g || _ !== _ || v !== v) x = g + _ + v;
93
+ else if (b === 0) x = 0;
94
+ else {
95
+ let e = g / b * (g / b), t = _ / b * (_ / b), n = e + t - e - t, r = v / b * (v / b) - n;
96
+ x = Math.sqrt(e + t + r) * b;
97
+ }
98
+ if (!f || !x) throw RangeError("Invalid camera view; pass distinct eye and target and another up vector");
99
+ p /= x, m /= x, h /= x;
100
+ let S = a * h - o * m, C = o * p - i * h, w = i * m - a * p;
101
+ return e[0] = p, e[1] = S, e[2] = i, e[3] = 0, e[4] = m, e[5] = C, e[6] = a, e[7] = 0, e[8] = h, e[9] = w, e[10] = o, e[11] = 0, e[12] = -p * n[0] - m * n[1] - h * n[2], e[13] = -S * n[0] - C * n[1] - w * n[2], e[14] = -i * n[0] - a * n[1] - o * n[2], e[15] = 1, e;
102
+ }
103
+ //#endregion
104
+ //#region ../shared/view-rect.js
105
+ function re(e) {
106
+ return e?.view?.viewport;
107
+ }
108
+ function D(e, t) {
109
+ let n = re(t);
110
+ if (!n) return;
111
+ e.setViewport(n[0], n[1], n[2], n[3], 0, 1);
112
+ let r = t.view.scissor ?? n;
113
+ e.setScissorRect(r[0], r[1], r[2], r[3]);
114
+ }
115
+ //#endregion
116
+ //#region src/render-post.ts
117
+ function O(e, t, n = "") {
118
+ let r = "@fragment fn fragment(o:Out,@builtin(front_facing) front:bool)->@location(0) vec4f", i = e.indexOf(r), a = e.indexOf("var color=", i), o = e.indexOf("\n}", a), s = e.includes("let margoAmbient=") ? "margoAmbient" : "ambient(s)", c = e.includes("var<private> voxelBaked:") ? `select(${s},s.base.rgb*(1.0-s.metal)*voxelBaked.rgb,voxelBaked.a>0.0)` : s, l = "vec4f(normalize((voxelPostView*vec4f(s.n,0)).xyz),-(voxelPostView*vec4f(i.position,1)).z)", u = "select(1.0,s.base.a,MODE==3u)", d = e.slice(a, o).replace(/return (vec4f\([^\n]+?\));/g, "_=$1;");
119
+ if (i < 0 || a < 0 || o < 0) throw TypeError("VoxelRenderer post replay requires its native material shader; use matching voxel package sources");
120
+ let f = "", p = "", m = "@location(0) vec4f";
121
+ return t === "capture" ? (f = n, s === "margoAmbient" && (f = f.replace(/ambient\(s\)/g, "voxelCaptureAmbient") + "\nvar<private> voxelCaptureAmbient:vec3f;\n", p += `voxelCaptureAmbient=${c};`), f.includes("var<private> margoPosition:") && (p += "margoPosition=i.position;"), p += "return margoCapture(s,v,vec3f(1));", m = "MargoCapture") : t === "ambient" ? p = `return vec4f(${c},${u});` : (f = "@group(0) @binding(7) var<uniform> voxelPostView:mat4x4f;\n", t === "gbuffer" ? p = `return ${l};` : (f += "struct MargoVoxelOcclusion {@location(0) normal:vec4f,@location(1) ambient:vec4f}\n", m = "MargoVoxelOcclusion", p = `return MargoVoxelOcclusion(${l},vec4f(${c},${u}));`)), f + e.slice(0, a).replace(r, r.replace("->@location(0) vec4f", `->${m}`)) + `if(false){${d}}${p}` + e.slice(o);
122
+ }
123
+ //#endregion
124
+ //#region src/textures.ts
125
+ var k = /* @__PURE__ */ new WeakMap(), A = 2048, ie = Float32Array.from({ length: 256 }, (e, t) => t <= 10 ? t / 255 / 12.92 : ((t / 255 + .055) / 1.055) ** 2.4), ae = (e) => Math.round(255 * (e <= .0031308 ? Math.max(0, e) * 12.92 : 1.055 * Math.min(1, e) ** (1 / 2.4) - .055));
126
+ function j(e, t) {
127
+ let n = 0;
128
+ for (let r = 0; r < e.length; r++) Math.round(255 * Math.min(1, e[r] * t)) >= 128 && n++;
129
+ return n / e.length;
130
+ }
131
+ function M(e, t) {
132
+ let n = [e], r = t, i = Float32Array.from({ length: r * r }, (t, n) => e[n * 4 + 3] / 255), a = Float32Array.from({ length: r * r * 3 }, (t, n) => ie[e[(n / 3 | 0) * 4 + n % 3]]), o = i.every((e) => e === 0 || e === 1) && !i.every((e) => e === 1) ? j(i, 1) : -1;
133
+ for (; r > 1;) {
134
+ let e = r >> 1, t = new Float32Array(e * e), s = new Float32Array(e * e * 3), c = new Uint8Array(e * e * 4);
135
+ for (let n = 0; n < e; n++) for (let o = 0; o < e; o++) {
136
+ let c = n * e + o, l = 2 * n * r + 2 * o, u = [
137
+ l,
138
+ l + 1,
139
+ l + r,
140
+ l + r + 1
141
+ ], d = 0;
142
+ for (let e of u) d += i[e];
143
+ for (let e = 0; e < 3; e++) {
144
+ let t = 0;
145
+ for (let n of u) t += a[n * 3 + e] * (d ? i[n] : 1);
146
+ s[c * 3 + e] = t / (d || 4);
147
+ }
148
+ t[c] = d / 4;
149
+ }
150
+ let l = 1;
151
+ if (o >= 0) {
152
+ let e = 0, n = 4096;
153
+ for (let r = 0; r < 40; r++) {
154
+ let r = (e + n) / 2;
155
+ j(t, r) < o ? e = r : n = r;
156
+ }
157
+ l = Math.abs(j(t, e) - o) < Math.abs(j(t, n) - o) ? e : n;
158
+ }
159
+ for (let n = 0; n < e * e; n++) {
160
+ for (let e = 0; e < 3; e++) c[n * 4 + e] = ae(s[n * 3 + e]);
161
+ c[n * 4 + 3] = Math.round(255 * Math.min(1, t[n] * l));
162
+ }
163
+ n.push(c), r = e, i = t, a = s;
164
+ }
165
+ return n;
166
+ }
167
+ var oe = (e) => !!e && typeof e == "object" && "data" in e && typeof e.data?.length == "number";
168
+ function N(e) {
169
+ let t = e;
170
+ if (t.naturalWidth) return [t.naturalWidth, t.naturalHeight ?? 0];
171
+ if (t.displayWidth) return [t.displayWidth, t.displayHeight ?? 0];
172
+ let { width: n, height: r } = e;
173
+ return [Number(n), Number(r)];
174
+ }
175
+ function se(e, t, n, r, i, a, o) {
176
+ if (oe(e)) {
177
+ let { width: s, height: c, data: l } = e;
178
+ if (i !== t || a !== t || n + t > s || r + t > c || l.length < s * c * 4) throw RangeError(`${o} has ${s} x ${c} raw pixels, which do not hold a ${t} x ${t} tile; pass pixels of the texture size or an image the browser can scale`);
179
+ let u = new Uint8Array(t * t * 4);
180
+ for (let e = 0; e < t; e++) for (let i = 0; i < t * 4; i++) u[e * t * 4 + i] = l[((r + e) * s + n) * 4 + i];
181
+ return u;
182
+ }
183
+ if (typeof OffscreenCanvas != "function") throw new d("unsupported", `${o} needs OffscreenCanvas to read its pixels; pass {width, height, data} pixels instead`);
184
+ let s = new OffscreenCanvas(t, t).getContext("2d", { willReadFrequently: !0 });
185
+ if (!s) throw new d("unsupported", `${o} needs a 2D OffscreenCanvas context to read its pixels`);
186
+ return s.imageSmoothingEnabled = !1, s.drawImage(e, n, r, i, a, 0, 0, t, t), new Uint8Array(s.getImageData(0, 0, t, t).data.buffer);
187
+ }
188
+ function P(e) {
189
+ if (typeof e != "number") throw TypeError("BlockTextures size must be a number of texels, such as 16");
190
+ if (!Number.isInteger(e) || e < 1 || e > 4096 || e & e - 1) throw RangeError(`BlockTextures size ${e} is not a power of two from 1 to 4,096; pass 16, 32 or 64`);
191
+ return e;
192
+ }
193
+ function ce(e) {
194
+ if (typeof e != "number") throw TypeError("Block texture layer must be a number from 0 to 2047");
195
+ if (!Number.isInteger(e) || e < 0 || e >= A) throw RangeError(`Block texture layer ${e} is not an integer from 0 to 2047; pass a layer index`);
196
+ return e;
197
+ }
198
+ var F = class e {
199
+ constructor(e = {}) {
200
+ if (!e || typeof e != "object") throw TypeError("BlockTextures options must be an object");
201
+ let t = e.images ?? [];
202
+ if (!Array.isArray(t)) throw TypeError("BlockTextures images must be an array of images");
203
+ if (t.length > A) throw RangeError(`BlockTextures got ${t.length} images; a texture array holds at most 2048 layers`);
204
+ this.size = P(e.size ?? (t.length ? N(t[0])[0] : 16)), k.set(this, {
205
+ levels: [],
206
+ dirty: /* @__PURE__ */ new Set(),
207
+ disposed: !1,
208
+ users: /* @__PURE__ */ new Set()
209
+ });
210
+ for (let e = 0; e < t.length; e++) this.#t(e, t[e]);
211
+ }
212
+ static async load(t, { fetch: n = globalThis.fetch, ...r } = {}) {
213
+ if (!Array.isArray(t) || !t.length || t.length > A) throw TypeError("BlockTextures.load expects an array of 1 to 2048 image URLs");
214
+ let i = await Promise.allSettled(t.map(async (e) => {
215
+ let t = await n(e);
216
+ if (!t.ok) throw new d("failed", `Block texture ${e} answered HTTP ${t.status}; check the URL`);
217
+ return createImageBitmap(await t.blob(), {
218
+ premultiplyAlpha: "none",
219
+ colorSpaceConversion: "none"
220
+ });
221
+ })), a = i.flatMap((e) => e.status === "fulfilled" ? [e.value] : []);
222
+ try {
223
+ let t = i.find((e) => e.status === "rejected");
224
+ if (t) throw t.reason;
225
+ return new e({
226
+ ...r,
227
+ images: a
228
+ });
229
+ } finally {
230
+ for (let e of a) e.close();
231
+ }
232
+ }
233
+ static fromAtlas(t, n = {}) {
234
+ if (!t || typeof t != "object") throw TypeError("BlockTextures.fromAtlas expects an image or pixels");
235
+ let r = P(n?.size ?? 16), [i, a] = N(t), o = Math.floor(i / r), s = Math.floor(a / r);
236
+ if (!o || !s || o * s > A) throw RangeError(`Atlas of ${i} x ${a} holds ${o * s} tiles of ${r} texels; it needs 1 to 2,048 tiles`);
237
+ let c = new e({ size: r });
238
+ for (let e = 0; e < s; e++) for (let n = 0; n < o; n++) c.#t(e * o + n, t, n * r, e * r, [r, r]);
239
+ return c;
240
+ }
241
+ get layers() {
242
+ return Math.max(1, this.#e().levels.length);
243
+ }
244
+ set(e, t) {
245
+ this.#t(ce(e), t);
246
+ }
247
+ dispose() {
248
+ let e = this.#e(!1);
249
+ e.disposed = !0, e.gpu?.texture.destroy(), e.gpu = void 0;
250
+ }
251
+ [Symbol.dispose]() {
252
+ this.dispose();
253
+ }
254
+ #e(e = !0) {
255
+ let t = k.get(this);
256
+ if (e && t.disposed) throw new d("disposed", "BlockTextures is disposed; create new BlockTextures");
257
+ return t;
258
+ }
259
+ #t(e, t, n = 0, r = 0, i) {
260
+ let a = this.#e(), o = `Block texture layer ${e}`;
261
+ if (!t || typeof t != "object") throw TypeError(`${o} must be an image, canvas, ImageBitmap or {width, height, data} pixels`);
262
+ let [s, c] = i ?? (oe(t) ? [t.width, t.height] : N(t)), l = M(se(t, this.size, n, r, s, c, o), this.size);
263
+ for (let t = a.levels.length; t < e; t++) a.levels[t] = M(new Uint8Array(this.size * this.size * 4).fill(255), this.size), a.dirty.add(t);
264
+ a.levels[e] = l, a.dirty.add(e);
265
+ }
266
+ };
267
+ function le(e, t, n) {
268
+ let r = k.get(e);
269
+ if (r.disposed) throw new d("disposed", "VoxelRenderer textures are disposed; pass live BlockTextures to the renderer");
270
+ let i = e.layers, a = e.size;
271
+ if (i > t.limits.maxTextureArrayLayers) throw new d("unsupported", `BlockTextures needs ${i} array layers but this device allows ${t.limits.maxTextureArrayLayers}; reduce the texture layers or request a device with a sufficient maxTextureArrayLayers limit`);
272
+ let o = r.gpu;
273
+ if (o?.device !== t || o.layers !== i) {
274
+ o?.texture.destroy();
275
+ let e = t.createTexture({
276
+ size: [
277
+ a,
278
+ a,
279
+ i
280
+ ],
281
+ format: "rgba8unorm-srgb",
282
+ mipLevelCount: Math.log2(a) + 1,
283
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
284
+ });
285
+ o = r.gpu = {
286
+ device: t,
287
+ texture: e,
288
+ view: e.createView({ dimension: "2d-array" }),
289
+ layers: i
290
+ };
291
+ for (let e = 0; e < i; e++) r.dirty.add(e);
292
+ }
293
+ for (let e of r.dirty) {
294
+ let n = r.levels[e] ?? M(new Uint8Array(a * a * 4).fill(255), a);
295
+ for (let r = 0, i = a; r < n.length; r++, i >>= 1) t.queue.writeTexture({
296
+ texture: o.texture,
297
+ mipLevel: r,
298
+ origin: [
299
+ 0,
300
+ 0,
301
+ e
302
+ ]
303
+ }, n[r], {
304
+ bytesPerRow: i * 4,
305
+ rowsPerImage: i
306
+ }, [
307
+ i,
308
+ i,
309
+ 1
310
+ ]);
311
+ }
312
+ return r.dirty.clear(), r.users.add(n), o.view;
313
+ }
314
+ function ue(e, t) {
315
+ let n = k.get(e);
316
+ n.users.delete(t) && !n.users.size && n.gpu && (n.gpu.texture.destroy(), n.gpu = void 0);
317
+ }
318
+ //#endregion
319
+ //#region ../shared/pass.js
320
+ var de = /* @__PURE__ */ Object.freeze({
321
+ color: {
322
+ srcFactor: "src-alpha",
323
+ dstFactor: "one-minus-src-alpha",
324
+ operation: "add"
325
+ },
326
+ alpha: {
327
+ srcFactor: "one",
328
+ dstFactor: "one-minus-src-alpha",
329
+ operation: "add"
330
+ }
331
+ }), fe = (e) => typeof e == "string" && e.endsWith("float"), pe = {
332
+ opaque: /* @__PURE__ */ new Uint32Array(),
333
+ cutout: /* @__PURE__ */ new Uint32Array(),
334
+ translucent: /* @__PURE__ */ new Uint32Array(),
335
+ visibility: 549687102
336
+ }, me = (e) => {
337
+ let t = [
338
+ [],
339
+ [],
340
+ []
341
+ ];
342
+ for (let n of e ?? []) t[n >>> 21 & 3]?.push({
343
+ x: (n & 63) - 1,
344
+ y: (n >>> 6 & 63) - 1,
345
+ z: (n >>> 12 & 63) - 1,
346
+ face: n >>> 18 & 7,
347
+ w: 1,
348
+ h: 1
349
+ });
350
+ return t;
351
+ }, I = 64, L = 768, R = 196608, he = 4 << 20, ge = 4 << 20, _e = 4, ve = 1 / 128, z = {
352
+ operation: "add",
353
+ srcFactor: "one",
354
+ dstFactor: "one-minus-src-alpha"
355
+ }, B = "\n@group(0) @binding(4) var<storage,read> voxelMaterials:array<vec4u>;\n@group(0) @binding(5) var voxelTextures:texture_2d_array<f32>;\n@group(0) @binding(6) var voxelSampler:sampler;\nfn voxelLayer(m:vec4u,t:vec4f)->u32 {let r=m.z>>16u;let n=((m.x>>11u)&2047u)+1u;return (m.x&2047u)+(((bitcast<u32>(t.y)%n)*(r%n))%n+u32(floor(t.x*f32(r)/256.0)))%n;}\nfn voxelOpaque(m:vec4u,uv:vec2f,t:vec4f)->bool {return (m.x&4194304u)!=0u||textureSampleLevel(voxelTextures,voxelSampler,uv,voxelLayer(m,t),0.0).a>=0.5;}\n", V = `${B}
356
+ @group(0) @binding(1) var<storage,read> voxelQuads:array<u32>;
357
+ @group(0) @binding(2) var<storage,read> voxelPages:array<u32>;
358
+ @group(0) @binding(3) var<storage,read> voxelOrigins:array<vec4f>;
359
+ fn voxelRise(w1:u32,t:vec4f)->f32 {return select(0.0,0.04*sin(t.z),(w1&0x100000u)!=0u);}
360
+
361
+ struct VoxelPart {lo:vec2f,hi:vec2f,n:f32}
362
+ fn voxelPart(w0:u32,w1:u32)->VoxelPart {
363
+ let b=vec4f(vec4u(w1>>22u,w1>>23u,w1>>24u,w1>>25u)&vec4u(1u))*0.5;
364
+ let size=vec2f(f32(((w0>>18u)&31u)+1u),f32(((w0>>23u)&31u)+1u));
365
+ return VoxelPart(b.xz,size-b.yw,abs(f32(((w0>>15u)&1u)==0u)-f32((w1>>21u)&1u)*0.5));
366
+ }
367
+ fn voxelPlace(w0:u32,w1:u32,c:u32,t:vec4f)->vec3f {
368
+ let face=(w0>>15u)&7u;let r=voxelPart(w0,w1);let su=select(r.lo.x,r.hi.x,c==1u||c==2u);let sv=select(r.lo.y,r.hi.y,c>=2u);
369
+ var p=vec3f(f32(w0&31u),f32((w0>>5u)&31u),f32((w0>>10u)&31u));
370
+ switch face {
371
+ case 0u,1u {p+=vec3f(r.n,sv,su);}
372
+ case 2u,3u {p+=vec3f(su,r.n,sv);}
373
+ case 4u,5u {p+=vec3f(su,sv,r.n);}
374
+ case 6u {p+=vec3f(su,sv,su);}
375
+ default {p+=vec3f(1.0-su,sv,su);}
376
+ }
377
+ if(face==2u||(face!=3u&&face<6u&&c>=2u)){p.y+=voxelRise(w1,t)-f32(w0>>29u)*0.125;}
378
+
379
+ if((w0>>29u)!=0u&&(face<2u||(face>3u&&face<6u))&&(w1&0x3000000u)!=0u){
380
+ let y0=f32((w0>>5u)&31u);p.y=min(y0+select(r.lo.y,r.hi.y,c>=2u),y0+1.0-f32(w0>>29u)*0.125)+select(0.0,voxelRise(w1,t),c>=2u);
381
+ }
382
+ return p;
383
+ }
384
+ ${r}`, H = "fn voxelSun(p:vec3f,sky:f32)->f32 {return sky*sky;}", ye = (e) => `fn voxelSun(p:vec3f,sky:f32)->f32 {let d=-(shadowFrame.view*vec4f(p,1.0)).z;return mix(1.0,sky*sky,smoothstep(0.9*${e},${e},d));}`, U = `${y}
385
+ struct Frame {camera:mat4x4f,inverse:mat4x4f,eye:vec4f,light:vec4f,radiance:vec4f,ambient:vec4f,glow:vec4f,viewport:vec4f,settings:vec4f,time:vec4f,waves:vec4f,shift:vec4f}
386
+ @group(0) @binding(0) var<uniform> f:Frame;
387
+ override MODE:u32=0u;
388
+ struct Surface {base:vec4f,n:vec3f,roughness:f32,metal:f32,occlusion:f32,emissive:vec3f}
389
+ struct VoxelPixel {clip:vec4f,position:vec3f}
390
+ ${i}${H}
391
+ fn ambient(s:Surface)->vec3f {let f0=mix(vec3f(0.04),s.base.rgb,s.metal);return (s.base.rgb*(1.0-s.metal)+f0*0.5)*mix(vec3f(0.35,0.3,0.25),vec3f(1.0),clamp(s.n.y*0.5+0.5,0.0,1.0))*f.ambient.rgb*f.radiance.w*s.occlusion;}
392
+ fn direct_light(s:Surface,v:vec3f,l:vec3f)->vec3f {
393
+ let h=(v+l)/max(length(v+l),0.0001);
394
+ let nl=clamp(dot(s.n,l),0.0,1.0);let nv=clamp(dot(s.n,v),0.0001,1.0);let nh=clamp(dot(s.n,h),0.0,1.0);let vh=clamp(dot(v,h),0.0,1.0);
395
+ let a=s.roughness*s.roughness;let a2=a*a;let d=${/* @__PURE__ */ x("s.n", "h")};
396
+ let g=${S};
397
+ let base=s.base.rgb;let metal=s.metal;const dielectricF0=vec3f(0.04);const dielectricF90=1.0;let f0=mix(dielectricF0,base,metal);let fresnel=f0+(1.0-f0)*pow(1.0-vh,5.0);
398
+ return ${b}*nl*f.radiance.rgb*f.light.w;
399
+ }
400
+ `, W = "\n i.position-=f.shift.xyz;\n let tc=unpack4x8unorm(m.y).rgb;let tint=select(tc/12.92,pow((tc+0.055)/1.055,vec3f(2.4)),tc>vec3f(0.04045));\n let texel=textureSampleGrad(voxelTextures,voxelSampler,uv,voxelLayer(m,f.time),dx,dy);\n var s:Surface;s.base=vec4f(texel.rgb*tint,select(texel.a,1.0,(m.x&4194304u)!=0u));\n if(MODE==1u&&s.base.a<0.5){discard;}\n s.n=normal;s.roughness=clamp(f32(m.z&255u)/255.0,0.045,1.0);s.metal=f32((m.z>>8u)&255u)/255.0;\n let nLayer=maps.x&2047u;if(nLayer!=0u){s.n=voxelNormal(normal,tangent,textureSampleGrad(voxelTextures,voxelSampler,uv,nLayer,dx,dy).rgb*2.0-1.0);}\n let rLayer=(maps.x>>11u)&2047u;if(rLayer!=0u){s.roughness=clamp(textureSampleGrad(voxelTextures,voxelSampler,uv,rLayer,dx,dy).r,0.045,1.0);}\n let eLayer=maps.z&2047u;var eMap=1.0;if(eLayer!=0u){eMap=textureSampleGrad(voxelTextures,voxelSampler,uv,eLayer,dx,dy).r;}\n\n\n\n\n let sky=clamp(lit.y,0.0,15.0);let block=clamp(lit.z,0.0,15.0);\n let lightness=vec2f(sky,block)*100.0/15.0;let cube=(lightness+16.0)/116.0;\n let brightness=select(lightness*(27.0/24389.0),cube*cube*cube,lightness>vec2f(8.0));let skyLight=brightness.x;\n let ao=0.4+0.2*lit.x;\n s.occlusion=ao*(0.03+skyLight*f.ambient.w);\n s.emissive=s.base.rgb*(bitcast<f32>(m.w)*eMap+brightness.y*ao*f.glow.rgb);\n let v=normalize(f.eye.xyz-i.position);let lightDirection=f.light.xyz;\n let direct=direct_light(s,v,lightDirection)*voxelSun(i.position,skyLight);\n var color=direct+ambient(s)+s.emissive;\n if(f.settings.w<0.5) {color=toDisplay(color);}\n if(MODE==3u){let through=f32((maps.z>>11u)&255u)/255.0*(1.0-bitcast<f32>(maps.y)*0.5);let alpha=s.base.a*(1.0-through*0.85);return vec4f((color*(1.0-through)+s.base.rgb*through)*alpha,alpha);}\n return vec4f(color,select(1.0,(s.base.a-0.5)/max(fwidth(s.base.a),0.0001)+0.5,MODE==2u));\n}", G = `${U}${V}
401
+ override EDGE:f32=0.0;
402
+ struct Out {@builtin(position) clip:vec4f,@location(0) @interpolate(flat) words:vec3u,@location(1) @interpolate(flat) origin:vec4f,@location(2) @interpolate(flat) material:vec4u,@location(3) @interpolate(flat) maps:vec4u}
403
+ fn voxelStretch(s:vec2f,along:vec2f,across:vec2f)->f32 {
404
+ let d=s-along;let l=length(d);let a=s-across;if(l<0.0625){return 0.0;}
405
+ return min(min(EDGE/max(abs(dot(vec2f(-d.y,d.x)/l,a)),0.000001),0.5),1.0/max(length(a),0.000001));
406
+ }
407
+ @vertex fn vertex(@builtin(vertex_index) index:u32)->Out {
408
+ let q=index>>2u;let w0=voxelQuads[q*3u];let w1=voxelQuads[q*3u+1u];let face=(w0>>15u)&7u;var c=index&3u;let t=f.time;
409
+ if((w0&0x10000000u)!=0u){c=(c+1u)&3u;}
410
+ if(face==0u||face==2u||face==5u){c=(4u-c)&3u;}
411
+ let origin=voxelOrigins[voxelPages[q>>6u]];var clip=f.camera*vec4f(origin.xyz+voxelPlace(w0,w1,c,t),1.0);
412
+ if(EDGE>0.0&&(((w0>>18u)&0x3ffu)!=0u||(w1&0x3e00000u)!=0u)){
413
+ let u=f.camera*vec4f(origin.xyz+voxelPlace(w0,w1,c^1u,t),1.0);let v=f.camera*vec4f(origin.xyz+voxelPlace(w0,w1,3u-c,t),1.0);
414
+ if(clip.w>0.0&&u.w>0.0&&v.w>0.0){
415
+ let half=f.viewport.xy*0.5;let s=clip.xy/clip.w*half;let su=u.xy/u.w*half;let sv=v.xy/v.w*half;
416
+ clip+=voxelStretch(s,su,sv)*(clip-v)+voxelStretch(s,sv,su)*(clip-u);
417
+ }
418
+ }
419
+ var o:Out;o.clip=clip;o.words=vec3u(w0,w1,voxelQuads[q*3u+2u]);o.origin=origin;o.material=voxelMaterials[(w1&4095u)*2u];o.maps=voxelMaterials[(w1&4095u)*2u+1u];return o;
420
+ }
421
+ fn voxelHit(px:vec2f,n:vec3f,k:f32)->vec3f {
422
+ let q=(px-f.settings.xy)*f.viewport.zw;let a=f.inverse*vec4f(q.x*2.0-1.0,1.0-q.y*2.0,0.0,1.0);let b=f.inverse[2];
423
+ let h=a-b*((dot(n,a.xyz)-k*a.w)/(dot(n,b.xyz)-k*b.w));return h.xyz/h.w;
424
+ }
425
+ fn voxelCorner(w:vec3u,c:u32)->vec3f {return vec3f(f32((w.y>>(12u+2u*c))&3u),f32((w.z>>(8u*c))&15u),f32((w.z>>(8u*c+4u))&15u));}
426
+ fn voxelMix(a:vec3f,b:vec3f,t:f32)->vec3f {return a+(b-a)*t;}
427
+ fn voxelRipple(p:vec2f,t:vec4f)->vec3f {
428
+ let a=0.035*cos(dot(p,vec2f(1.3,0.4))+t.x);let b=0.03*cos(dot(p,vec2f(-0.5,1.6))+t.y);let c=0.015*cos(dot(p,vec2f(2.9,2.3))+t.z);
429
+ return normalize(vec3f(-(1.3*a-0.5*b+2.9*c),1.0,-(0.4*a+1.6*b+2.3*c)));
430
+ }
431
+ @fragment fn fragment(o:Out,@builtin(front_facing) front:bool)->@location(0) vec4f {
432
+ let w=o.words;let face=(w.x>>15u)&7u;let O=o.origin.xyz;let t=f.time;let drop=f32(w.x>>29u)*0.125-voxelRise(w.y,t);
433
+ let cell=vec3f(f32(w.x&31u),f32((w.x>>5u)&31u),f32((w.x>>10u)&31u));let part=voxelPart(w.x,w.y);let size=part.hi-part.lo;
434
+ let axis=face>>1u;var n=vec3f(f32(axis==0u),f32(axis==1u),f32(axis==2u));var k=dot(n,O+cell)+part.n;
435
+ if(face==2u){k-=drop;}
436
+ if(face==6u){n=vec3f(1.0,0.0,-1.0);k=(O.x+cell.x)-(O.z+cell.z);}
437
+ if(face==7u){n=vec3f(1.0,0.0,1.0);k=O.x+cell.x+1.0+O.z+cell.z;}
438
+ var i:VoxelPixel;i.clip=o.clip;i.position=voxelHit(o.clip.xy,n,k);let l=i.position-O;
439
+ var at=l.xy;var start=cell.xy;
440
+ if(axis==0u){at=l.zy;start=cell.zy;} else if(axis==1u){at=l.xz;start=cell.xz;}
441
+ start+=part.lo;
442
+ var high=size.y-select(0.0,drop,face<6u&&axis!=1u);
443
+ if((w.x>>29u)!=0u&&face<6u&&axis!=1u&&(w.y&0x3000000u)!=0u){high=max(min(part.hi.y,1.0-drop)-part.lo.y,0.0001);}
444
+ let r=clamp((at-start)/vec2f(size.x,high),vec2f(0.0),vec2f(1.0));
445
+ let lit=voxelMix(voxelMix(voxelCorner(w,0u),voxelCorner(w,1u),r.x),voxelMix(voxelCorner(w,3u),voxelCorner(w,2u),r.x),r.y);
446
+ let m=o.material;let maps=o.maps;
447
+ let uv=voxelTile(face,l,cell);let dx=voxelTile(face,voxelHit(o.clip.xy+vec2f(1.0,0.0),n,k)-O,cell)-uv;let dy=voxelTile(face,voxelHit(o.clip.xy+vec2f(0.0,1.0),n,k)-O,cell)-uv;
448
+ let side=select(-1.0,1.0,front);let outward=n*select(-1.0,1.0,(face&1u)==0u);let tangent=voxelTangent(face);
449
+ var normal=select(vec3f(0.0,1.0,0.0),outward*side,face<6u);
450
+ if(face==2u&&(w.y&0x100000u)!=0u){normal=voxelRipple(i.position.xz,f.waves)*side;}
451
+ ${W}`, K = `
452
+ struct VoxelShadow {matrix:mat4x4f,time:vec4f}
453
+ @group(0) @binding(0) var<uniform> shadow:VoxelShadow;
454
+ ${V}
455
+ struct ShadowOut {@builtin(position) @invariant clip:vec4f,@location(0) @interpolate(flat) words:vec2u,@location(1) local:vec3f}
456
+ @vertex fn shadowVertex(@builtin(vertex_index) index:u32)->ShadowOut {
457
+ let q=index>>2u;let w0=voxelQuads[q*3u];let w1=voxelQuads[q*3u+1u];let c=index&3u;let t=shadow.time;
458
+ var p=voxelPlace(w0,w1,c,t);
459
+ p+=(normalize(p-voxelPlace(w0,w1,c^1u,t))+normalize(p-voxelPlace(w0,w1,3u-c,t)))*${1 / 64};
460
+ var o:ShadowOut;o.clip=shadow.matrix*vec4f(voxelOrigins[voxelPages[q>>6u]].xyz+p,1.0);o.words=vec2u(w0,w1);o.local=p;return o;
461
+ }
462
+ @fragment fn shadowCutout(o:ShadowOut) {
463
+ let cell=vec3f(f32(o.words.x&31u),f32((o.words.x>>5u)&31u),f32((o.words.x>>10u)&31u));
464
+ if(!voxelOpaque(voxelMaterials[(o.words.y&4095u)*2u],voxelTile((o.words.x>>15u)&7u,o.local,cell),shadow.time)){discard;}
465
+ }
466
+ `, q = 2 * Math.PI, J = (e) => e - Math.floor(e / q) * q;
467
+ function Y(e, t, n) {
468
+ let r = Math.floor(e / 256);
469
+ t[n] = e - r * 256, new Uint32Array(t.buffer, t.byteOffset)[n + 1] = r >>> 0, t[n + 2] = J(e * 1.6), t[n + 3] = 0;
470
+ }
471
+ function be(e, t, n, r) {
472
+ let [i, , a] = r;
473
+ t[n] = J(e * 1.7 + i * 1.3 + a * .4), t[n + 1] = J(e * 1.3 - i * .5 + a * 1.6), t[n + 2] = J(e * 2.9 + i * 2.9 + a * 2.3), t[n + 3] = 0;
474
+ }
475
+ var X = (e, t) => [
476
+ t[0] - e.x,
477
+ t[1] - e.y,
478
+ t[2] - e.z
479
+ ].map((e) => Math.min(Math.max(Math.floor(e), -1), 32)).join(), xe = class {
480
+ constructor() {
481
+ this.runs = [], this.capacity = 0, this.used = 0;
482
+ }
483
+ grow(e) {
484
+ this.#e(this.capacity, e - this.capacity), this.capacity = e;
485
+ }
486
+ alloc(e) {
487
+ let t = this.runs;
488
+ for (let n = 0; n < t.length; n += 2) if (t[n + 1] >= e) {
489
+ let r = t[n];
490
+ return t[n] += e, t[n + 1] -= e, t[n + 1] || t.splice(n, 2), this.used += e, r;
491
+ }
492
+ return -1;
493
+ }
494
+ release(e, t) {
495
+ t && (this.used -= t, this.#e(e, t));
496
+ }
497
+ #e(e, t) {
498
+ let n = this.runs, r = 0;
499
+ for (; r < n.length && n[r] < e;) r += 2;
500
+ r < n.length && e + t === n[r] ? (n[r] = e, n[r + 1] += t) : n.splice(r, 0, e, t), r && n[r - 2] + n[r - 1] === e && (n[r - 1] += n[r + 1], n.splice(r, 2));
501
+ }
502
+ }, Se = 0, Z = /* @__PURE__ */ new WeakMap(), Ce = 0, we = (e) => {
503
+ let t = Z.get(e);
504
+ return t === void 0 && Z.set(e, t = ++Ce), t;
505
+ }, Te = 4;
506
+ function Q(e, t) {
507
+ return new Promise((n) => e.ahead.push(() => n(t())));
508
+ }
509
+ function Ee(e, t, n) {
510
+ let r;
511
+ for (let t of e.keys()) r = t;
512
+ r !== t && (e.delete(t), e.set(t, n));
513
+ }
514
+ function De(e, t, n, r = Te, i = !1) {
515
+ let a = 1;
516
+ for (let [o, s] of [...e].reverse()) o === n || s.ready?.target !== t || i && !s.ready.effects.length || ++a > r && e.delete(o);
517
+ }
518
+ var $ = (e, t, n) => {
519
+ if (typeof e != "number") throw TypeError(`VoxelRenderer ${t} must be a number; ${n}`);
520
+ return e;
521
+ }, Oe = class t {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
522
+ #e;
523
+ #t;
524
+ #n;
525
+ #r;
526
+ #i;
527
+ #a;
528
+ #o;
529
+ #s;
530
+ #c;
531
+ #l;
532
+ #u;
533
+ #d;
534
+ #f;
535
+ #p;
536
+ #m;
537
+ #h;
538
+ #g;
539
+ #_;
540
+ #v;
541
+ #y;
542
+ #b;
543
+ #x;
544
+ #S;
545
+ #C;
546
+ #w;
547
+ #T;
548
+ #E;
549
+ #D;
550
+ #O;
551
+ #k;
552
+ #A;
553
+ #j;
554
+ #M;
555
+ #N;
556
+ #P;
557
+ #F;
558
+ #I;
559
+ #L;
560
+ #R;
561
+ #z;
562
+ #B;
563
+ #V;
564
+ #H;
565
+ #U;
566
+ #W;
567
+ #G;
568
+ #K;
569
+ #q;
570
+ #J;
571
+ #Y;
572
+ #X;
573
+ #Z;
574
+ #Q;
575
+ #$;
576
+ constructor(e) {
577
+ if (this.#t = -1, this.name = `voxel:${Se++}`, this.#o = 0, this.#d = 1, this.#f = !1, this.#m = new xe(), this.#h = /* @__PURE__ */ new Map(), this.#_ = /* @__PURE__ */ new Set(), this.#v = /* @__PURE__ */ new Map(), this.#y = !1, this.#b = 0, this.#x = [], this.#S = 0, this.#C = /* @__PURE__ */ new Float32Array(), this.#w = /* @__PURE__ */ new Uint32Array(), this.#T = 0, this.#E = /* @__PURE__ */ new Uint8Array(), this.#D = 0, this.#O = 0, this.#k = 0, this.#j = [], this.#M = /* @__PURE__ */ new Float32Array(72), this.#N = /* @__PURE__ */ new Float64Array(16), this.#P = /* @__PURE__ */ new Float32Array(16), this.#F = new p(), this.#I = {
578
+ min: {
579
+ x: 0,
580
+ y: 0,
581
+ z: 0
582
+ },
583
+ max: {
584
+ x: 0,
585
+ y: 0,
586
+ z: 0
587
+ }
588
+ }, this.#L = {
589
+ chunks: 0,
590
+ visible: 0,
591
+ quads: 0,
592
+ triangles: 0,
593
+ bytes: 0,
594
+ draws: 0,
595
+ compiling: !1,
596
+ pending: 0,
597
+ poolFull: !1
598
+ }, this.#R = /* @__PURE__ */ new Map(), this.#z = 0, this.#B = /* @__PURE__ */ new Set(), this.#H = /* @__PURE__ */ new Set(), this.#U = {
599
+ from: "",
600
+ lit: !1,
601
+ id: 0,
602
+ next: 0,
603
+ code: G,
604
+ bevel: "",
605
+ effects: [],
606
+ ids: /* @__PURE__ */ new Map()
607
+ }, this.#W = 0, this.#G = 0, this.#K = -1, this.#q = [], this.#J = [
608
+ 1,
609
+ .82,
610
+ .6
611
+ ], this.#Y = 1, this.#X = [
612
+ 0,
613
+ 0,
614
+ 0
615
+ ], this.#Z = [
616
+ 0,
617
+ 0,
618
+ 0
619
+ ], this.#Q = [
620
+ 0,
621
+ 0,
622
+ 0
623
+ ], this.origin = null, this.#$ = /* @__PURE__ */ new Float32Array(24), !e || typeof e != "object") throw TypeError("VoxelRenderer.attach expects (engine, {world, textures})");
624
+ let { world: t, textures: n, workers: r, mesher: i, maxQuadBytes: o, daylight: s = 1, fancyLeaves: c = !0, bevel: l, lightmap: u, scale: d = 1, origin: f = null } = e;
625
+ if (typeof t?.getChunk != "function" || !(t.dirty instanceof Set) || !Array.isArray(t.blocks?.table)) throw TypeError("VoxelRenderer world must be a VoxelWorld; pass {world: new VoxelWorld({blocks})}");
626
+ if (!(n instanceof F)) throw TypeError("VoxelRenderer textures must be BlockTextures; pass {textures: await BlockTextures.load(urls)}");
627
+ if (this.#a = o, o !== void 0 && ($(o, "maxQuadBytes", "pass bytes, such as 96 << 20"), !Number.isInteger(o) || o < L)) throw RangeError(`VoxelRenderer maxQuadBytes ${o} is not a whole number of at least 768 bytes`);
628
+ if (typeof c != "boolean") throw TypeError("VoxelRenderer fancyLeaves must be true or false");
629
+ if ($(d, "scale", "pass a power of two, such as 8"), !Number.isInteger(d) || d < 1 || d > 4096 || d & d - 1) throw RangeError(`VoxelRenderer scale ${d} is not a power of two from 1 to 4096; pass 1, 2, 4, 8 and so on`);
630
+ if (this.#Y = d, f !== null && typeof f?.origin?.length != "number") throw TypeError("VoxelRenderer origin must be null or an object with origin [x, y, z], such as a FloatingOrigin");
631
+ if (this.origin = f, this.world = t, this.textures = n, this.#s = c, l !== void 0 && typeof l?.mesh != "function") throw TypeError("VoxelRenderer bevel must come from voxelBevel(amount) of @margoengine/voxel/bevel");
632
+ if (this.#c = l, this.lightmap = u, this.daylight = s, i !== void 0 && (typeof i?.mesh != "function" || typeof i.cancel != "function" || typeof i.dispose != "function")) throw TypeError("VoxelRenderer mesher needs mesh, cancel and dispose; pass a GpuVoxelMesher or VoxelMesher");
633
+ this.#i = !i, this.#r = i ?? new a(r === void 0 ? {} : { workers: r });
634
+ }
635
+ static attach(e, n) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
636
+ let r = new t(n);
637
+ try {
638
+ f(e).use(r);
639
+ } catch (e) {
640
+ throw r.dispose(), e;
641
+ }
642
+ return r;
643
+ }
644
+ get scale() {
645
+ return this.#Y;
646
+ }
647
+ get daylight() {
648
+ return this.#d;
649
+ }
650
+ set daylight(e) {
651
+ if ($(e, "daylight", "pass 0 (night) to 1 (day)"), !(e >= 0) || !Number.isFinite(e)) throw RangeError(`VoxelRenderer daylight ${e} must be finite and >= 0; pass 0 (night) to 1 (day)`);
652
+ this.#d = e;
653
+ }
654
+ get blockLightColor() {
655
+ return this.#J;
656
+ }
657
+ set blockLightColor(e) {
658
+ if (!Array.isArray(e) || e.length !== 3 || e.some((e) => typeof e != "number")) throw TypeError("VoxelRenderer blockLightColor must be [r, g, b]; pass linear numbers such as [1, 0.82, 0.6]");
659
+ if (!e.every((e) => e >= 0 && Number.isFinite(e))) throw RangeError(`VoxelRenderer blockLightColor [${e}] must be finite and >= 0`);
660
+ this.#J = [
661
+ e[0],
662
+ e[1],
663
+ e[2]
664
+ ];
665
+ }
666
+ get stats() {
667
+ return this.#L;
668
+ }
669
+ get disposed() {
670
+ return this.#f;
671
+ }
672
+ onDispose(e) {
673
+ if (typeof e != "function") throw TypeError("VoxelRenderer onDispose needs a callback");
674
+ return this.#f ? (e(), () => {}) : (this.#H.add(e), () => {
675
+ this.#H.delete(e);
676
+ });
677
+ }
678
+ setCapture(e) {
679
+ if (this.#f) throw new d("disposed", "VoxelRenderer is disposed; attach a new one");
680
+ if (this.#ve("capture"), !e || typeof e.declarations != "function" || typeof e.begin != "function" || !Array.isArray(e.targets) || !e.targets.length) throw TypeError("VoxelRenderer capture needs declarations, targets and begin; pass a post capture hook");
681
+ return this.#V = e, () => {
682
+ this.#V === e && (this.#V = void 0);
683
+ };
684
+ }
685
+ draw(e, t, n, r, i = "all", a) {
686
+ let o = this.#p, s = t === "capture" ? this.#V : void 0;
687
+ if (this.#f || !o || o.device !== e.device || !this.#h.size || t === "capture" && !s) return !1;
688
+ if (t === "occlusion" && !a) throw TypeError("VoxelRenderer occlusion needs the post owner's two-target external pass");
689
+ let { code: c, bevel: l, effects: u, id: d, lit: f } = this.#Te(), p = s?.declarations(c) ?? "", m = e.descriptor.multisample?.count ?? 1, h = e.descriptor.depthStencil.format, g = s ? [...s.targets] : Array.from({ length: t === "occlusion" ? 2 : 1 }, () => ({ format: "rgba16float" })), _ = a?.depthCompare ?? "greater-equal", v = `${t}|${m}|${h}|${_}|${g.map((e) => e.format).join(",")}`, y = `${v}|${d}|${p}`, b = t === "gbuffer" || t === "occlusion", x = o.post ??= {
690
+ view: e.device.createBuffer({
691
+ size: 64,
692
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
693
+ }),
694
+ states: /* @__PURE__ */ new Map()
695
+ }, S = x.states.get(y);
696
+ if (!S) {
697
+ let e = S = {};
698
+ x.states.set(y, S), this.#De(o, O(c, t, p), l && O(l, t, s?.declarations(l)), t === "capture" ? 2 : 3, (e) => ({
699
+ mode: e === 0 ? 0 : e === 2 ? 3 : m > 1 && _ === "equal" ? 2 : 1,
700
+ targets: g.map((n, r) => e === 2 && t !== "gbuffer" && r === +(t === "occlusion") ? {
701
+ ...n,
702
+ blend: de
703
+ } : n),
704
+ write: t === "capture",
705
+ compare: _,
706
+ coverage: !1
707
+ }), m, h).then(([t, n]) => {
708
+ this.#p === o && (e.ready = {
709
+ target: v,
710
+ layers: t,
711
+ bevel: n,
712
+ effects: u,
713
+ lit: f,
714
+ motion: this.#e,
715
+ motionVersion: this.#e?.version
716
+ }, De(x.states, v, y));
717
+ }).catch((e) => this.#n?.onError(e));
718
+ }
719
+ let C = S.ready;
720
+ if (!C) return !1;
721
+ Ee(x.states, y, S);
722
+ let w = a?.view ?? ne(this.#P, e.camera);
723
+ b && o.device.queue.writeBuffer(x.view, 0, Float32Array.from(w)), this.#Me(o, C, b ? [{
724
+ binding: 7,
725
+ resource: { buffer: x.view }
726
+ }] : []);
727
+ let T = s ? s.begin() : a?.pass ?? e.encoder.beginRenderPass({
728
+ colorAttachments: [{
729
+ view: n,
730
+ loadOp: "load",
731
+ storeOp: "store"
732
+ }],
733
+ depthStencilAttachment: {
734
+ view: r,
735
+ depthReadOnly: !0,
736
+ stencilReadOnly: !0
737
+ }
738
+ });
739
+ D(T, e);
740
+ for (let e = 0; e < C.layers.length; e++) if (!(i === "blend" && e < 2 || i === "opaque" && e === 2)) {
741
+ if (e === 2) this.#ze(o, T, C);
742
+ else {
743
+ T.setPipeline(C.layers[e]), T.setBindGroup(0, C.groups[e]), C.lights && T.setBindGroup(1, C.lights[e]), T.setIndexBuffer(o.index, "uint32");
744
+ for (let t of this.#_e()) t.quads[e] && T.drawIndexedIndirect(o.args, t.slot * 40 + e * 20);
745
+ this.#Re(T, C, e);
746
+ }
747
+ }
748
+ return !s && !a && T.end(), !0;
749
+ }
750
+ get shadowVersion() {
751
+ return this.#G;
752
+ }
753
+ get lightmap() {
754
+ return this.#l;
755
+ }
756
+ set lightmap(e) {
757
+ if (this.#f) throw new d("disposed", "VoxelRenderer is disposed; attach a new one");
758
+ if (e !== void 0 && typeof e?.shader != "function") throw TypeError("VoxelRenderer lightmap must come from voxelLightmap(options) of @margoengine/voxel/lightmap");
759
+ this.#l = e, this.#u = e ? _(e.texture, "VoxelRenderer lightmap texture", "set lightmap", this.#n?.gpu) : void 0;
760
+ let t = this.#p;
761
+ t?.lightmap && (t.lightmap.buffer.destroy(), t.lightmap.index.destroy(), t.lightmap = void 0), this.#D++;
762
+ }
763
+ addLighting(e) {
764
+ if (this.#f) throw new d("disposed", "VoxelRenderer is disposed; attach a new one");
765
+ if (!e || typeof e.pbr != "function" || typeof e.bindings != "function") throw TypeError("VoxelRenderer lighting effects need pbr(group) and bindings(); pass Shadows, Clustered, Fog or EnvironmentLighting");
766
+ this.#ve("lighting effects");
767
+ let t = e.owner;
768
+ if (t && this.#n && t !== this.#n) throw new d("attached", "VoxelRenderer lighting effect belongs to another engine; use one of this engine");
769
+ return this.#B.add(e), () => {
770
+ this.#B.delete(e);
771
+ };
772
+ }
773
+ addVertexMotion(e) {
774
+ if (this.#ve("Vertex motion"), this.#e) throw new d("attached", "VoxelRenderer already has vertex motion; remove it before adding another");
775
+ return this.#e = e, this.#t = -1, this.#D++, () => {
776
+ this.#e === e && (this.#e = void 0, this.#t = -1, this.#p?.shadow?.uniform.destroy(), this.#p && (this.#p.shadow = void 0), this.#D++, this.#G++);
777
+ };
778
+ }
779
+ drawShadow({ context: e, pass: t, matrix: n, cascade: r }) {
780
+ let i = this.#p;
781
+ if (this.#f || !i || i.device !== e.device || !this.#h.size || this.#Y !== 1) return !1;
782
+ let a = this.#xe(i);
783
+ if (!a.ready) return !1;
784
+ let o = (this.#q[r] ??= new p()).setFromProjectionMatrix({ elements: n });
785
+ a.values.set(n);
786
+ let [s, c, l] = this.#Q;
787
+ for (let e = 0; e < 4; e++) a.values[12 + e] = n[12 + e] - (s * n[e] + c * n[4 + e] + l * n[8 + e]);
788
+ if (Y(this.#k, a.values, 16), i.device.queue.writeBuffer(a.uniform, r * 256, a.values), a.groupVersion !== this.#D) {
789
+ let e = [
790
+ {
791
+ binding: 1,
792
+ resource: { buffer: i.pool }
793
+ },
794
+ {
795
+ binding: 2,
796
+ resource: { buffer: i.pageTable }
797
+ },
798
+ {
799
+ binding: 3,
800
+ resource: { buffer: i.origins }
801
+ },
802
+ {
803
+ binding: 4,
804
+ resource: { buffer: i.materials }
805
+ },
806
+ {
807
+ binding: 5,
808
+ resource: i.view
809
+ },
810
+ {
811
+ binding: 6,
812
+ resource: i.sampler
813
+ }
814
+ ], t = (e, t, n) => e?.map((e, r) => [
815
+ 0,
816
+ 1,
817
+ 2,
818
+ 3
819
+ ].map((o) => i.device.createBindGroup({
820
+ layout: e.getBindGroupLayout(0),
821
+ entries: [
822
+ {
823
+ binding: 0,
824
+ resource: {
825
+ buffer: a.uniform,
826
+ offset: o * 256,
827
+ size: 80
828
+ }
829
+ },
830
+ ...r ? n : t,
831
+ ...this.#e?.bindings(i.device) ?? []
832
+ ]
833
+ })));
834
+ a.groups = t(a.ready, e.slice(0, 3), e), a.bevelGroups = t(a.bevel, [], e.slice(3)), a.groupVersion = this.#D;
835
+ }
836
+ for (let e = 0; e < 2; e++) {
837
+ t.setPipeline(a.ready[e]), t.setBindGroup(0, a.groups[e][r]), t.setIndexBuffer(i.index, "uint32");
838
+ for (let n of this.#_e()) n.quads[e] && o.intersectsBox(this.#ye(n)) && t.drawIndexed(n.quads[e] * 6, 1, 0, n.start[e] * I * 4, 0);
839
+ if (a.bevel) {
840
+ t.setPipeline(a.bevel[e]), t.setBindGroup(0, a.bevelGroups[e][r]);
841
+ for (let n of this.#_e()) {
842
+ let r = n.bevel?.[e];
843
+ r && o.intersectsBox(this.#ye(n)) && this.#Le(t, r);
844
+ }
845
+ }
846
+ }
847
+ return !0;
848
+ }
849
+ setup(e) {
850
+ if (this.#f) throw new d("disposed", "VoxelRenderer is disposed; attach a new one");
851
+ this.#r.warm?.();
852
+ let t = e.gpu;
853
+ if (!t) throw new d("unsupported", "VoxelRenderer needs the WebGPU backend; create the engine with WebGPU; see https://margoengine.com/errors#webgpu");
854
+ let n = Math.min(t.limits.maxStorageBufferBindingSize, t.limits.maxBufferSize ?? Infinity), r = this.#a;
855
+ if (r !== void 0 && r > n) throw RangeError(`VoxelRenderer maxQuadBytes is over this device's ${n}-byte storage binding limit; lower maxQuadBytes`);
856
+ this.#o = Math.floor((r ?? n) / L), this.#n = e, this.#u && g(this.#u, t);
857
+ }
858
+ registerPasses(e) {
859
+ let t = (e) => (t) => {
860
+ t.backend === "webgpu" && !this.#f && e(t);
861
+ };
862
+ e.add({
863
+ name: `${this.name}:prepare`,
864
+ order: -6,
865
+ execute: t((e) => this.#re(e))
866
+ }), e.add({
867
+ name: this.name,
868
+ order: 1,
869
+ execute: t((e) => this.#Be(e))
870
+ }), e.add({
871
+ name: `${this.name}:translucent`,
872
+ order: 4.5,
873
+ execute: t((e) => this.#Ve(e))
874
+ });
875
+ }
876
+ get time() {
877
+ return this.#k;
878
+ }
879
+ advanceTime(e) {
880
+ e > 0 && (this.#k += e);
881
+ }
882
+ onPreUpdate(e) {
883
+ this.advanceTime(e);
884
+ }
885
+ onDeviceRestored() {
886
+ let e = this.#n?.gpu;
887
+ e && this.#r.setDevice?.(e), this.#te();
888
+ }
889
+ dispose() {
890
+ if (!this.#f) {
891
+ this.#f = !0;
892
+ for (let e of this.#H) e();
893
+ if (this.#H.clear(), this.#V = void 0, this.#n?.sceneOf(this)?.removePlugin(this.name), this.#i) this.#r.dispose();
894
+ else for (let e of this.#R.keys()) this.#r.cancel(e);
895
+ this.#ne(), this.#h.clear(), this.#g = void 0, this.#v.clear(), this.#_.clear(), this.#B.clear(), this.#n = void 0;
896
+ }
897
+ }
898
+ [Symbol.dispose]() {
899
+ this.dispose();
900
+ }
901
+ #ee(e) {
902
+ if (this.#p?.device === e) return this.#p;
903
+ this.#p && this.#te();
904
+ let t = (t, n) => e.createBuffer({
905
+ size: t,
906
+ usage: n
907
+ }), n = e.createBuffer({
908
+ size: R * 24,
909
+ usage: GPUBufferUsage.INDEX,
910
+ mappedAtCreation: !0
911
+ }), r = new Uint32Array(n.getMappedRange());
912
+ for (let e = 0, t = 0; e < R; e++, t += 6) {
913
+ let n = e * 4;
914
+ r[t] = r[t + 3] = n, r[t + 1] = n + 1, r[t + 2] = r[t + 4] = n + 2, r[t + 5] = n + 3;
915
+ }
916
+ n.unmap();
917
+ let i = Math.min(this.#o, Math.floor(he / L)), a = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC;
918
+ return this.#m = new xe(), this.#m.grow(i), this.#p = {
919
+ device: e,
920
+ frame: t(288, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST),
921
+ pool: t(i * L, a),
922
+ pageTable: t(i * 4, a),
923
+ origins: t(16, a | GPUBufferUsage.VERTEX),
924
+ args: t(40, GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_DST),
925
+ materials: t(16, a),
926
+ index: n,
927
+ sampler: e.createSampler({
928
+ addressModeU: "repeat",
929
+ addressModeV: "repeat",
930
+ magFilter: "nearest",
931
+ minFilter: "linear",
932
+ mipmapFilter: "linear"
933
+ }),
934
+ pipelines: /* @__PURE__ */ new Map(),
935
+ ahead: []
936
+ }, this.#T = 0, this.#D++, this.#p;
937
+ }
938
+ #te() {
939
+ this.#ne();
940
+ for (let e of this.#_) this.world.dirty.add(e);
941
+ this.#h.clear(), this.#g = void 0, this.#v.clear(), this.#b++;
942
+ }
943
+ #ne() {
944
+ let e = this.#p;
945
+ if (e) for (let t of [
946
+ e.frame,
947
+ e.pool,
948
+ e.pageTable,
949
+ e.origins,
950
+ e.args,
951
+ e.materials,
952
+ e.index,
953
+ e.shadow?.uniform,
954
+ e.post?.view,
955
+ e.lightmap?.buffer,
956
+ e.lightmap?.index
957
+ ]) t?.destroy();
958
+ for (let e of this.#h.values()) this.#ue(e);
959
+ ue(this.textures, this), this.#p = this.#A = void 0, this.#G++, this.#x = [], this.#S = 0, this.#C = /* @__PURE__ */ new Float32Array(), this.#w = /* @__PURE__ */ new Uint32Array(), this.#j = [], this.#y = !1;
960
+ }
961
+ #re(e) {
962
+ let t = this.#ee(e.device), { device: n } = t, r = 1 / this.#Y;
963
+ this.#me(t);
964
+ let i = [
965
+ e.camera.position[0] * r,
966
+ e.camera.position[1] * r,
967
+ e.camera.position[2] * r
968
+ ], a = [
969
+ i[0] + this.#X[0],
970
+ i[1] + this.#X[1],
971
+ i[2] + this.#X[2]
972
+ ];
973
+ this.#e && (this.#e.bindings(n, this.#k, this.#Z), this.#t !== this.#e.version && (t.shadow?.uniform.destroy(), t.shadow = void 0, this.#t = this.#e.version, this.#D++), this.#G++), this.#ie(t);
974
+ let o = le(this.textures, n, this);
975
+ o !== t.view && (t.view = o, this.#D++), this.#ae(a), this.#oe(t), this.#K !== this.#D && (this.#K = this.#D, this.#G++);
976
+ let s = this.#M, c = this.#n.lighting;
977
+ if (!m(e.camera.matrix, this.#N)) return;
978
+ let l = e.camera.matrix, d = this.#N, f = this.#Y, [p, h, g] = this.#Q;
979
+ for (let e = 0; e < 4; e++) for (let t = 0; t < 4; t++) s[e * 4 + t] = e < 3 ? l[e * 4 + t] * f : l[12 + t] - f * (p * l[t] + h * l[4 + t] + g * l[8 + t]), s[16 + e * 4 + t] = t < 3 ? r * d[e * 4 + t] + this.#Q[t] * d[e * 4 + 3] : d[e * 4 + 3];
980
+ this.#$.set(e.camera.planes);
981
+ for (let e = 3; e < 24; e += 4) this.#$[e] *= r;
982
+ s.set(i, 32), u(s, 36, c.direction), s.set(c.radiance, 40), s.set(c.ambient ?? [
983
+ 1,
984
+ 1,
985
+ 1
986
+ ], 44), s[47] = this.#d, s.set(this.#J, 48), Y(this.#k, s, 60), be(this.#k, s, 64, this.#Z), s.set(this.#Q, 68);
987
+ let [_, v, y, b] = e.view?.viewport ?? [
988
+ 0,
989
+ 0,
990
+ e.width,
991
+ e.height
992
+ ];
993
+ s[52] = y, s[53] = b, s[54] = 1 / y, s[55] = 1 / b, s[56] = _, s[57] = v, s[59] = +fe(e.format), n.queue.writeBuffer(t.frame, 0, s), this.#Ee(e, t, a);
994
+ let x = this.#je(e, t);
995
+ this.#A = x, x ? this.#Fe(e, t, x) : this.#L.draws = 0;
996
+ }
997
+ #ie(e) {
998
+ let t = this.world.blocks.table;
999
+ if (t.length === this.#T) return;
1000
+ this.#T = t.length;
1001
+ let n = o(t), r = 1;
1002
+ for (let e of n) e !== 65535 && (r = Math.max(r, e + 1));
1003
+ let i = new Uint32Array(r * 8), a = new Float32Array(i.buffer), s = new Uint8Array(r), c = (e) => Math.round(255 * (e <= .0031308 ? e * 12.92 : 1.055 * e ** (1 / 2.4) - .055));
1004
+ for (let e = 0; e < t.length; e++) for (let r = 0; r < 6; r++) {
1005
+ let o = n[e * 6 + r], l = t[e], u = o * 8;
1006
+ if (o === 65535) continue;
1007
+ let d = l.layer === "opaque" || !this.#s && l.layer === "cutout" && l.shape === "cube";
1008
+ i[u] = l.textures[r] | l.animation.frames - 1 << 11 | d << 22, i[u + 1] = (c(l.color[0]) | c(l.color[1]) << 8 | c(l.color[2]) << 16 | 255 << 24) >>> 0, i[u + 2] = (Math.round(l.roughness * 255) | Math.round(l.metalness * 255) << 8 | Math.min(65535, Math.round(l.animation.fps * 256)) << 16) >>> 0, a[u + 3] = l.emissive, i[u + 4] = l.maps.normal | l.maps.roughness << 11, a[u + 5] = l.scatter, i[u + 6] = l.maps.emissive | Math.round(l.transmission * 255) << 11, s[o] = +(l.shape === "liquid");
1009
+ }
1010
+ this.#E = s, e.materials.size < i.byteLength && (e.materials.destroy(), e.materials = e.device.createBuffer({
1011
+ size: i.byteLength,
1012
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
1013
+ }), this.#D++), e.device.queue.writeBuffer(e.materials, 0, i);
1014
+ }
1015
+ #ae(t) {
1016
+ let n = this.world;
1017
+ for (let r of n.dirty) {
1018
+ n.dirty.delete(r);
1019
+ let [i, a, o] = r.split(",").map(Number), s = n.getChunk(i, a, o);
1020
+ if (!s) {
1021
+ this.#r.cancel(r), this.#ge(r), this.#v.delete(r), this.#_.delete(r);
1022
+ continue;
1023
+ }
1024
+ this.#_.add(r);
1025
+ let c = Math.hypot(i * 32 + 16 - t[0], a * 32 + 16 - t[1], o * 32 + 16 - t[2]), l = this.#b, u = e(s);
1026
+ if (u !== void 0 && n.blocks.table[u & 65535]?.layer === "invisible") {
1027
+ this.#r.cancel(r), this.#v.set(r, {
1028
+ mesh: pe,
1029
+ priority: c,
1030
+ eye: t
1031
+ });
1032
+ continue;
1033
+ }
1034
+ let d = ++this.#z;
1035
+ this.#R.set(r, d);
1036
+ let f = () => {
1037
+ this.#R.get(r) === d && this.#R.delete(r);
1038
+ };
1039
+ this.#r.mesh(n, r, c, t, !!this.#c).then((e) => {
1040
+ f(), e && l === this.#b && !this.#f && this.#v.set(r, {
1041
+ mesh: e,
1042
+ priority: c,
1043
+ eye: t
1044
+ });
1045
+ }, (e) => {
1046
+ f(), this.#n?.onError(e);
1047
+ });
1048
+ }
1049
+ }
1050
+ #oe(e) {
1051
+ if (this.#v.size && !this.#y) {
1052
+ let t = [...this.#v].sort((e, t) => e[1].priority - t[1].priority), n = 0;
1053
+ for (let [r, i] of t) {
1054
+ if (n >= ge) break;
1055
+ let { opaque: t, cutout: a, translucent: o } = i.mesh;
1056
+ if (!this.#se(e, r, i)) {
1057
+ this.#y = !0;
1058
+ break;
1059
+ }
1060
+ this.#v.delete(r), n += t.byteLength + a.byteLength + o.byteLength;
1061
+ }
1062
+ }
1063
+ }
1064
+ #se(e, t, { mesh: n, eye: r }) {
1065
+ let i = [
1066
+ n.opaque,
1067
+ n.cutout,
1068
+ n.translucent
1069
+ ];
1070
+ if (!i.some((e) => e.length)) return this.#ge(t), !0;
1071
+ let a = this.#h.get(t);
1072
+ if (!a) {
1073
+ let [e, n, i] = t.split(",").map(Number);
1074
+ a = {
1075
+ key: t,
1076
+ x: e * 32,
1077
+ y: n * 32,
1078
+ z: i * 32,
1079
+ slot: -1,
1080
+ start: /* @__PURE__ */ new Int32Array(3),
1081
+ pages: /* @__PURE__ */ new Int32Array(3),
1082
+ quads: /* @__PURE__ */ new Int32Array(3),
1083
+ visible: !1,
1084
+ sortedAt: r
1085
+ }, this.#h.set(t, a), this.#g = void 0;
1086
+ }
1087
+ a.slot < 0 && (a.slot = this.#he(e, a)), (a.quads[0] || a.quads[1] || a.bevel || n.opaque.length || n.cutout.length) && this.#be(a);
1088
+ let o = this.#c ? i.map((e) => this.#ce(e)) : void 0, s = o ? o.map(([e]) => e) : i;
1089
+ for (let n = 0; n < 3; n++) {
1090
+ let r = s[n].length / 3, i = Math.ceil(r / I);
1091
+ if (i > a.pages[n]) {
1092
+ this.#m.release(a.start[n], a.pages[n]), a.pages[n] = 0;
1093
+ let r = this.#fe(e, i);
1094
+ if (r < 0) return this.#ge(t), !1;
1095
+ a.start[n] = r;
1096
+ } else this.#m.release(a.start[n] + i, a.pages[n] - i);
1097
+ n < 2 && !r != !a.quads[n] && this.#O++, a.pages[n] = i, a.quads[n] = r;
1098
+ }
1099
+ for (let t = 0; t < 3; t++) a.quads[t] && (e.device.queue.writeBuffer(e.pool, a.start[t] * L, s[t]), e.device.queue.writeBuffer(e.pageTable, a.start[t] * 4, new Uint32Array(a.pages[t]).fill(a.slot)));
1100
+ if (a.translucent = s[2].length ? s[2] : void 0, a.sortedAt = r, o) {
1101
+ this.#ue(a);
1102
+ let t = me(n.border), i = o.map(([, n], r) => n.length ? this.#le(e, a, n, t[r], r) : void 0);
1103
+ a.bevel = i.some(Boolean) ? i : void 0, a.centers = a.translucent && c(a.translucent), this.#de(e, a, r);
1104
+ }
1105
+ return !0;
1106
+ }
1107
+ #ce(e) {
1108
+ let t = [], n = [];
1109
+ for (let r = 0; r < e.length; r += 3) {
1110
+ let i = s(e, r / 3);
1111
+ i.face > 5 || this.#E[i.material] || i.inset || i.trim ? t.push(e[r], e[r + 1], e[r + 2]) : n.push({
1112
+ ...i,
1113
+ material: i.material | i.face << 12
1114
+ });
1115
+ }
1116
+ return [Uint32Array.from(t), n];
1117
+ }
1118
+ #le(e, t, n, r, i) {
1119
+ let { vertices: a, indices: o, centers: s } = this.#c.mesh(n, [
1120
+ 0,
1121
+ 0,
1122
+ 0
1123
+ ], r), c = (t, n) => {
1124
+ let r = e.device.createBuffer({
1125
+ size: t.byteLength,
1126
+ usage: n | GPUBufferUsage.COPY_DST
1127
+ });
1128
+ return e.device.queue.writeBuffer(r, 0, t), r;
1129
+ };
1130
+ return {
1131
+ vertices: c(a, GPUBufferUsage.VERTEX),
1132
+ index: c(o, GPUBufferUsage.INDEX),
1133
+ count: o.length,
1134
+ slot: t.slot,
1135
+ ...i === 2 ? {
1136
+ indices: o,
1137
+ centers: s
1138
+ } : {}
1139
+ };
1140
+ }
1141
+ #ue(e) {
1142
+ for (let t of e.bevel ?? []) t?.vertices.destroy(), t?.index.destroy();
1143
+ e.bevel = e.runs = void 0;
1144
+ }
1145
+ #de(e, t, n) {
1146
+ let r = t.bevel?.[2], i = t.translucent, a = t.centers ?? /* @__PURE__ */ new Float32Array(), o = r?.centers ?? /* @__PURE__ */ new Float32Array(), s = a.length / 3, c = s + o.length / 3, l = new Float64Array(c), u = new Uint32Array(c), d = n[0] - t.x, f = n[1] - t.y, p = n[2] - t.z;
1147
+ for (let e = 0; e < c; e++) {
1148
+ let t = e < s ? a : o, n = (e < s ? e : e - s) * 3;
1149
+ l[e] = (t[n] - d) ** 2 + (t[n + 1] - f) ** 2 + (t[n + 2] - p) ** 2, u[e] = e;
1150
+ }
1151
+ u.sort((e, t) => l[t] - l[e] || e - t);
1152
+ let m = new Uint32Array(s * 3), h = new Uint32Array(o.length), g = [], _ = 0, v = 0;
1153
+ for (let e of u) {
1154
+ let t = +(e >= s);
1155
+ g.length && g[g.length - 3] === t ? g[g.length - 1]++ : g.push(t, t ? v : _, 1), t ? h.set(r.indices.subarray((e - s) * 3, (e - s) * 3 + 3), v++ * 3) : m.set(i.subarray(e * 3, e * 3 + 3), _++ * 3);
1156
+ }
1157
+ _ && e.device.queue.writeBuffer(e.pool, t.start[2] * L, m), v && e.device.queue.writeBuffer(r.index, 0, h), t.runs = g;
1158
+ }
1159
+ #fe(e, t) {
1160
+ let n = this.#m, r = n.alloc(t);
1161
+ for (; r < 0 && n.capacity < this.#o;) {
1162
+ let i = Math.min(this.#o, Math.max(n.capacity * 2, n.capacity + t)), { device: a } = e, o = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC, s = a.createBuffer({
1163
+ size: i * L,
1164
+ usage: o
1165
+ }), c = a.createBuffer({
1166
+ size: i * 4,
1167
+ usage: o
1168
+ }), l = a.createCommandEncoder();
1169
+ l.copyBufferToBuffer(e.pool, 0, s, 0, n.capacity * L), l.copyBufferToBuffer(e.pageTable, 0, c, 0, n.capacity * 4), a.queue.submit([l.finish()]), e.pool.destroy(), e.pageTable.destroy(), e.pool = s, e.pageTable = c, n.grow(i), this.#D++, r = n.alloc(t);
1170
+ }
1171
+ return r;
1172
+ }
1173
+ #pe(e) {
1174
+ return [
1175
+ e.x - this.#Z[0],
1176
+ e.y - this.#Z[1],
1177
+ e.z - this.#Z[2],
1178
+ 0
1179
+ ];
1180
+ }
1181
+ #me(e) {
1182
+ let t = this.origin?.origin, n = 1 / this.#Y, r = this.#X, i = this.#Z, a = !1, o = !1;
1183
+ for (let e = 0; e < 3; e++) {
1184
+ let s = t ? +t[e] * n : 0;
1185
+ if (!Number.isFinite(s)) throw RangeError(`VoxelRenderer origin[${e}] ${t[e]} is not a finite number; use finite world coordinates`);
1186
+ s !== r[e] && (r[e] = s, a = !0);
1187
+ let c = Math.round(s / 1024) * 1024;
1188
+ c !== i[e] && (i[e] = c, o = !0), this.#Q[e] = s - c;
1189
+ }
1190
+ if (a && this.#G++, o) {
1191
+ for (let e of this.#h.values()) e.slot >= 0 && this.#C.set(this.#pe(e), e.slot * 4);
1192
+ this.#C.length && e.device.queue.writeBuffer(e.origins, 0, this.#C);
1193
+ }
1194
+ }
1195
+ #he(e, t) {
1196
+ let n = this.#x.pop() ?? this.#S++;
1197
+ if (n * 4 < this.#C.length) this.#C.set(this.#pe(t), n * 4), e.device.queue.writeBuffer(e.origins, n * 16, this.#C, n * 4, 4);
1198
+ else {
1199
+ let r = Math.max(64, this.#S * 2), i = new Float32Array(r * 4), a = new Uint32Array(r * 10);
1200
+ i.set(this.#C), a.set(this.#w), this.#C = i, this.#w = a, e.origins.destroy(), e.args.destroy(), e.origins = e.device.createBuffer({
1201
+ size: i.byteLength,
1202
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.VERTEX
1203
+ }), e.args = e.device.createBuffer({
1204
+ size: a.byteLength,
1205
+ usage: GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_DST
1206
+ }), this.#D++, i.set(this.#pe(t), n * 4), e.device.queue.writeBuffer(e.origins, 0, i);
1207
+ }
1208
+ return n;
1209
+ }
1210
+ #ge(e) {
1211
+ let t = this.#h.get(e);
1212
+ if (t) {
1213
+ this.#h.delete(e), this.#g = void 0;
1214
+ for (let e = 0; e < 3; e++) this.#m.release(t.start[e], t.pages[e]);
1215
+ t.slot >= 0 && (this.#x.push(t.slot), this.#w.fill(0, t.slot * 10, t.slot * 10 + 10)), (t.quads[0] || t.quads[1]) && this.#O++, (t.quads[0] || t.quads[1] || t.bevel) && this.#be(t), this.#ue(t), this.#y = !1;
1216
+ }
1217
+ }
1218
+ #_e() {
1219
+ return this.#g ??= [...this.#h.values()].sort((e, t) => e.y - t.y || e.z - t.z || e.x - t.x);
1220
+ }
1221
+ #ve(e) {
1222
+ if (this.#Y !== 1) throw new d("unsupported", `VoxelRenderer with scale ${this.#Y} takes no ${e}; use a scale 1 renderer`);
1223
+ }
1224
+ #ye(e) {
1225
+ let t = this.#I, n = this.#e?.padding ?? 0, [r, i, a] = this.#X;
1226
+ return t.min.x = e.x - r - n, t.min.y = e.y - i - n, t.min.z = e.z - a - n, t.max.x = e.x - r + 32 + n, t.max.y = e.y - i + 32 + n, t.max.z = e.z - a + 32 + n, t;
1227
+ }
1228
+ #be(e) {
1229
+ let t = this.#q;
1230
+ if (!t.length) this.#G++;
1231
+ else {
1232
+ let n = this.#ye(e);
1233
+ t.some((e) => e?.intersectsBox(n)) && this.#G++;
1234
+ }
1235
+ }
1236
+ #xe(e) {
1237
+ if (e.shadow) return e.shadow;
1238
+ let t = e.device, n = {
1239
+ uniform: t.createBuffer({
1240
+ size: 1024,
1241
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
1242
+ }),
1243
+ values: /* @__PURE__ */ new Float32Array(20)
1244
+ }, r = this.#c, i = t.createShaderModule({ code: this.#e?.shader(K + (r?.shadow ?? "")) ?? K + (r?.shadow ?? "") }), a = (e, n) => t.createRenderPipelineAsync({
1245
+ layout: "auto",
1246
+ vertex: {
1247
+ module: i,
1248
+ entryPoint: e,
1249
+ buffers: e === "bevelVertex" ? [r.layout, r.origins] : []
1250
+ },
1251
+ ...n ? { fragment: {
1252
+ module: i,
1253
+ entryPoint: n,
1254
+ targets: []
1255
+ } } : {},
1256
+ primitive: { cullMode: "none" },
1257
+ depthStencil: {
1258
+ format: "depth32float",
1259
+ depthWriteEnabled: !0,
1260
+ depthCompare: "less-equal"
1261
+ }
1262
+ });
1263
+ return e.shadow = n, Promise.all([
1264
+ a("shadowVertex"),
1265
+ a("shadowVertex", "shadowCutout"),
1266
+ ...r ? [a("bevelVertex"), a("bevelVertex", "bevelCutout")] : []
1267
+ ]).then((t) => {
1268
+ this.#p === e && (n.ready = t.slice(0, 2), t.length > 2 && (n.bevel = t.slice(2)), this.#G++);
1269
+ }).catch((e) => this.#n?.onError(e)), n;
1270
+ }
1271
+ #Se(e) {
1272
+ let t = G, n = this.#c ? `${U}${B}${this.#c.shader}${W}` : "", r = [];
1273
+ for (let i of e) {
1274
+ let e = i.pbr(1);
1275
+ e && (t = w(t, e), n &&= w(n, e), r.push(i));
1276
+ }
1277
+ return this.#e && (t = this.#e.shader(t), n &&= this.#e.shader(n)), {
1278
+ code: t,
1279
+ bevel: n,
1280
+ effects: r
1281
+ };
1282
+ }
1283
+ #Ce(e, t) {
1284
+ let n = t ? this.#l.shader(e) : e;
1285
+ return n.includes("var<uniform> shadowFrame") ? n.replace(H, ye(n.includes("fn shadowReach") ? "shadowReach()" : "shadowFrame.splits.w")) : n;
1286
+ }
1287
+ #we(e, t, n, r) {
1288
+ let i = this.#U, a = `${e.map(we).join(",")}|${t}|${n}|${r}`, o = i.ids.get(a) ?? ++i.next;
1289
+ i.ids.delete(a), i.ids.set(a, o);
1290
+ for (let e of i.ids.keys()) i.ids.size > 16 && i.ids.delete(e);
1291
+ return o;
1292
+ }
1293
+ #Te() {
1294
+ let { code: e, bevel: t, effects: n } = this.#Se(this.#B), r = !!this.#l && (!this.#p || this.#Ne(this.#p) !== void 0), i = this.#U, a = i.from !== e || i.lit !== r;
1295
+ return (a || n.length !== i.effects.length || n.some((e, t) => e !== i.effects[t])) && (a && (i.from = e, i.lit = r, i.code = this.#Ce(e, r), i.bevel = t && this.#Ce(t, r)), i.effects = n, i.id = this.#we(n, r, i.code, i.bevel)), {
1296
+ code: i.code,
1297
+ bevel: i.bevel,
1298
+ effects: n,
1299
+ id: i.id,
1300
+ lit: r
1301
+ };
1302
+ }
1303
+ #Ee(e, t, n) {
1304
+ let r = this.#F.fromArray(this.#$), i = this.#w, a = this.#j, o = this.#L, s = (e) => (e.x + 16 - n[0]) ** 2 + (e.y + 16 - n[1]) ** 2 + (e.z + 16 - n[2]) ** 2;
1305
+ a.length = o.chunks = o.visible = o.quads = o.triangles = o.draws = 0;
1306
+ for (let e of this.#_e()) {
1307
+ let t = r.intersectsBox(this.#ye(e)), n = e.slot * 10;
1308
+ e.visible = t;
1309
+ for (let r = 0; r < 2; r++) i[n + r * 5] = e.quads[r] * 6, i[n + r * 5 + 1] = +(t && e.quads[r] > 0), i[n + r * 5 + 2] = 0, i[n + r * 5 + 3] = e.start[r] * I * 4, i[n + r * 5 + 4] = 0, o.draws += i[n + r * 5 + 1] + +(t && !!e.bevel?.[r]);
1310
+ o.chunks++, o.quads += e.quads[0] + e.quads[1] + e.quads[2];
1311
+ for (let t of e.bevel ?? []) o.triangles += (t?.count ?? 0) / 3;
1312
+ t && o.visible++, t && (e.quads[2] || e.bevel?.[2]) && a.push(e);
1313
+ }
1314
+ o.bytes = this.#m.used * L, o.draws += a.length, o.pending = this.world.dirty.size + this.#R.size + this.#v.size, o.poolFull = this.#y && this.#v.size > 0, this.#S && t.device.queue.writeBuffer(t.args, 0, i, 0, this.#S * 10);
1315
+ let c = Math.floor(n[0] / 32), u = Math.floor(n[1] / 32), d = Math.floor(n[2] / 32), f = (e) => Math.abs(e.x / 32 - c) + Math.abs(e.y / 32 - u) + Math.abs(e.z / 32 - d);
1316
+ a.sort((e, t) => f(t) - f(e) || s(t) - s(e));
1317
+ for (let e = a.length - 1, r = 0; e >= 0 && r < _e; e--) {
1318
+ let i = a[e];
1319
+ X(i, n) !== X(i, i.sortedAt) && (this.#c ? this.#de(t, i, n) : i.translucent && (l(i.translucent, [
1320
+ n[0] - i.x,
1321
+ n[1] - i.y,
1322
+ n[2] - i.z
1323
+ ]), t.device.queue.writeBuffer(t.pool, i.start[2] * L, i.translucent)), i.sortedAt = n, r++);
1324
+ }
1325
+ }
1326
+ #De(e, t, n, r, i, a, o, s = !1) {
1327
+ let c = e.device, l = (t) => s ? Q(e, t) : t(), u = (e, t) => Promise.all(Array.from({ length: r }, (n, r) => {
1328
+ let s = i(r);
1329
+ return l(() => c.createRenderPipelineAsync({
1330
+ layout: "auto",
1331
+ vertex: t ? {
1332
+ module: e,
1333
+ entryPoint: "vertex",
1334
+ constants: { EDGE: r === 2 ? 0 : ve }
1335
+ } : {
1336
+ module: e,
1337
+ entryPoint: "vertex",
1338
+ buffers: [this.#c.layout, this.#c.origins]
1339
+ },
1340
+ fragment: {
1341
+ module: e,
1342
+ entryPoint: "fragment",
1343
+ constants: { MODE: s.mode },
1344
+ targets: s.targets
1345
+ },
1346
+ primitive: { cullMode: r ? "none" : "back" },
1347
+ depthStencil: {
1348
+ format: o,
1349
+ depthWriteEnabled: s.write,
1350
+ depthCompare: s.compare
1351
+ },
1352
+ multisample: {
1353
+ count: a,
1354
+ alphaToCoverageEnabled: s.coverage
1355
+ }
1356
+ }));
1357
+ })), d = async (e, t) => u(await l(() => c.createShaderModule({ code: e })), t);
1358
+ return s ? Promise.all([d(t, !0), n ? d(n, !1) : void 0]) : Promise.all([u(c.createShaderModule({ code: t }), !0), n ? u(c.createShaderModule({ code: n }), !1) : void 0]);
1359
+ }
1360
+ #Oe(e, t, n, r, i, a, o, s, c = !1) {
1361
+ let l = e.descriptor.multisample?.count ?? 1, u = this.#e, d = u?.version, f = {}, p = e.format, m = e.descriptor.depthStencil.format;
1362
+ return t.pipelines.set(n, f), Promise.all([this.#De(t, i, a, 3, (e) => {
1363
+ let t = e === 2 ? 3 : e && l > 1 ? 2 : e;
1364
+ return {
1365
+ mode: t,
1366
+ targets: [{
1367
+ format: p,
1368
+ ...e === 2 ? { blend: {
1369
+ color: z,
1370
+ alpha: z
1371
+ } } : {}
1372
+ }],
1373
+ write: e < 2,
1374
+ compare: "greater-equal",
1375
+ coverage: t === 2
1376
+ };
1377
+ }, l, m, c), this.#Ae(t, i, a, l, m, c)]).then(([[e, i], a]) => {
1378
+ this.#p === t && (f.ready = {
1379
+ target: r,
1380
+ layers: e,
1381
+ bevel: i,
1382
+ effects: o,
1383
+ lit: s,
1384
+ surface: a,
1385
+ motion: u,
1386
+ motionVersion: d
1387
+ }, De(t.pipelines, r, n, Te + this.#B.size, !0));
1388
+ }).catch((e) => this.#n?.onError(e)), f;
1389
+ }
1390
+ #ke(e, t, n, r, i, a) {
1391
+ let o = this.#Se(r), s = this.#Ce(o.code, i), c = o.bevel && this.#Ce(o.bevel, i), l = `${n}|${this.#we(o.effects, i, s, c)}`;
1392
+ t.pipelines.has(l) || this.#Oe(e, t, l, n, s, c, o.effects, i, a);
1393
+ }
1394
+ #Ae(e, t, n, r, i, a) {
1395
+ let o = e.device, s = (e, t) => o.createRenderPipelineAsync({
1396
+ layout: "auto",
1397
+ vertex: {
1398
+ module: e,
1399
+ entryPoint: "vertex",
1400
+ ...t
1401
+ },
1402
+ primitive: { cullMode: "none" },
1403
+ depthStencil: {
1404
+ format: i,
1405
+ depthWriteEnabled: !0,
1406
+ depthCompare: "greater-equal"
1407
+ },
1408
+ multisample: { count: r }
1409
+ }), c = a ? async (t, n) => {
1410
+ let r = await Q(e, () => o.createShaderModule({ code: t }));
1411
+ return Q(e, () => s(r, n));
1412
+ } : (e, t) => s(o.createShaderModule({ code: e }), t);
1413
+ return Promise.all([c(t, { constants: { EDGE: 0 } }), n ? c(n, { buffers: [this.#c.layout, this.#c.origins] }) : void 0]);
1414
+ }
1415
+ #je(e, t) {
1416
+ let n = e.descriptor.multisample?.count ?? 1, r = e.descriptor.depthStencil.format, i = `${e.format}|${n}|${r}`, { code: a, bevel: o, effects: s, id: c, lit: l } = this.#Te(), u = `${i}|${c}`, d = t.pipelines.get(u), f = d ?? this.#Oe(e, t, u, i, a, o, s, l), p = f.ready;
1417
+ if (!d && s.length && this.#ke(e, t, i, [], l, !1), this.#L.compiling = !p, p) {
1418
+ if (Ee(t.pipelines, u, f), t.ahead.shift()?.(), !p.ahead) {
1419
+ p.ahead = !0;
1420
+ for (let n of s) this.#ke(e, t, i, s.filter((e) => e !== n), l, !0);
1421
+ }
1422
+ return p;
1423
+ }
1424
+ for (let e of t.ahead.splice(0)) e();
1425
+ let m;
1426
+ for (let { ready: e } of t.pipelines.values()) e?.target === i && e.lit === l && e.motion === this.#e && e.motionVersion === this.#e?.version && (!m || e.effects.length >= m.effects.length) && e.effects.every((e) => this.#B.has(e) && e.pbr(1)) && (m = e);
1427
+ return m;
1428
+ }
1429
+ #Me(e, t, n = []) {
1430
+ let r = (t, n, r) => e.device.createBindGroup({
1431
+ layout: t.getBindGroupLayout(n),
1432
+ entries: r
1433
+ });
1434
+ if (t.groupVersion !== this.#D) {
1435
+ let i = [
1436
+ {
1437
+ binding: 0,
1438
+ resource: { buffer: e.frame }
1439
+ },
1440
+ {
1441
+ binding: 1,
1442
+ resource: { buffer: e.pool }
1443
+ },
1444
+ {
1445
+ binding: 2,
1446
+ resource: { buffer: e.pageTable }
1447
+ },
1448
+ {
1449
+ binding: 3,
1450
+ resource: { buffer: e.origins }
1451
+ },
1452
+ {
1453
+ binding: 4,
1454
+ resource: { buffer: e.materials }
1455
+ },
1456
+ {
1457
+ binding: 5,
1458
+ resource: e.view
1459
+ },
1460
+ {
1461
+ binding: 6,
1462
+ resource: e.sampler
1463
+ },
1464
+ ...t.lit ? this.#Pe(e) : [],
1465
+ ...n,
1466
+ ...this.#e?.bindings(e.device) ?? []
1467
+ ], a = i.filter((e) => e.binding < 1 || e.binding > 3);
1468
+ t.surface && (t.surfaceGroups = [r(t.surface[0], 0, i.filter((e) => e.binding <= 4 || e.binding >= 11)), t.surface[1] && r(t.surface[1], 0, i.filter((e) => e.binding === 0 || e.binding >= 11))]), t.groups = t.layers.map((e) => r(e, 0, i)), t.bevelGroups = t.bevel?.map((e) => r(e, 0, a)), t.groupVersion = this.#D;
1469
+ }
1470
+ if (t.effects.length) {
1471
+ let e = t.effects.flatMap((e) => e.bindings()), n = e.map((e) => "buffer" in e.resource ? e.resource.buffer : e.resource);
1472
+ (!t.lights || n.length !== t.lightBound.length || n.some((e, n) => e !== t.lightBound[n])) && (t.lights = t.layers.map((t) => r(t, 1, e)), t.bevelLights = t.bevel?.map((t) => r(t, 1, e)), t.lightBound = n, t.lightVersion = ++this.#W);
1473
+ }
1474
+ }
1475
+ #Ne(e) {
1476
+ return this.#u && v(this.#u, e.device, this.#n);
1477
+ }
1478
+ #Pe(e) {
1479
+ let t = this.#l, n = (t) => {
1480
+ let n = e.device.createBuffer({
1481
+ size: t.byteLength,
1482
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
1483
+ });
1484
+ return e.device.queue.writeBuffer(n, 0, t), n;
1485
+ }, r = e.lightmap ??= {
1486
+ view: this.#Ne(e).createView(),
1487
+ buffer: n(t.charts),
1488
+ index: n(t.index)
1489
+ };
1490
+ return [
1491
+ {
1492
+ binding: 8,
1493
+ resource: r.view
1494
+ },
1495
+ {
1496
+ binding: 9,
1497
+ resource: { buffer: r.buffer }
1498
+ },
1499
+ {
1500
+ binding: 10,
1501
+ resource: { buffer: r.index }
1502
+ }
1503
+ ];
1504
+ }
1505
+ #Fe(e, t, n) {
1506
+ this.#Me(t, n);
1507
+ let r = `${this.#D}|${this.#O}|${n.lightVersion}`;
1508
+ if (n.bundleKey === r) return;
1509
+ let i = t.device.createRenderBundleEncoder({
1510
+ colorFormats: [e.format],
1511
+ depthStencilFormat: e.descriptor.depthStencil.format,
1512
+ sampleCount: e.descriptor.multisample?.count ?? 1,
1513
+ stencilReadOnly: !0
1514
+ });
1515
+ i.setIndexBuffer(t.index, "uint32");
1516
+ for (let e = 0; e < 2; e++) {
1517
+ i.setPipeline(n.layers[e]), i.setBindGroup(0, n.groups[e]), n.lights && i.setBindGroup(1, n.lights[e]);
1518
+ for (let n of this.#_e()) n.quads[e] && i.drawIndexedIndirect(t.args, n.slot * 40 + e * 20);
1519
+ }
1520
+ n.bundle = i.finish(), n.bundleKey = r;
1521
+ }
1522
+ #Ie(e) {
1523
+ let t = e.descriptor.depthStencil.format.includes("stencil"), n = e.encoder.beginRenderPass({
1524
+ colorAttachments: [{
1525
+ view: e.color,
1526
+ loadOp: "load",
1527
+ storeOp: "store"
1528
+ }],
1529
+ depthStencilAttachment: {
1530
+ view: e.depth,
1531
+ depthLoadOp: "load",
1532
+ depthStoreOp: "store",
1533
+ ...t ? {
1534
+ stencilLoadOp: "load",
1535
+ stencilStoreOp: "store"
1536
+ } : {}
1537
+ }
1538
+ });
1539
+ return D(n, e), n;
1540
+ }
1541
+ #Le(e, t) {
1542
+ e.setVertexBuffer(0, t.vertices), e.setVertexBuffer(1, this.#p.origins, t.slot * 16, 16), e.setIndexBuffer(t.index, "uint32"), e.drawIndexed(t.count);
1543
+ }
1544
+ #Re(e, t, n) {
1545
+ if (t.bevel) {
1546
+ e.setPipeline(t.bevel[n]), e.setBindGroup(0, t.bevelGroups[n]), t.bevelLights && e.setBindGroup(1, t.bevelLights[n]);
1547
+ for (let t of this.#_e()) {
1548
+ let r = t.bevel?.[n];
1549
+ t.visible && r && this.#Le(e, r);
1550
+ }
1551
+ }
1552
+ }
1553
+ #ze(e, t, n) {
1554
+ let r = [
1555
+ n.layers[2],
1556
+ n.groups[2],
1557
+ n.lights?.[2]
1558
+ ], i = n.bevel && [
1559
+ n.bevel[2],
1560
+ n.bevelGroups[2],
1561
+ n.bevelLights?.[2]
1562
+ ], a = -1, o = 0;
1563
+ for (let n of this.#j) {
1564
+ let s = n.runs ?? [
1565
+ 0,
1566
+ 0,
1567
+ n.quads[2]
1568
+ ], c = n.bevel?.[2];
1569
+ for (let l = 0; l < s.length; l += 3) {
1570
+ let u = s[l], d = s[l + 1], f = s[l + 2];
1571
+ if (u !== a) {
1572
+ let [n, a, o] = u ? i : r;
1573
+ t.setPipeline(n), t.setBindGroup(0, a), o && t.setBindGroup(1, o), u || t.setIndexBuffer(e.index, "uint32");
1574
+ }
1575
+ u && (u !== a || !l) && (t.setVertexBuffer(0, c.vertices), t.setVertexBuffer(1, e.origins, c.slot * 16, 16), t.setIndexBuffer(c.index, "uint32")), a = u, u ? t.drawIndexed(f * 3, 1, d * 3) : t.drawIndexed(f * 6, 1, d * 6, n.start[2] * I * 4, 0), o++;
1576
+ }
1577
+ }
1578
+ return o;
1579
+ }
1580
+ #Be(e) {
1581
+ let t = this.#A;
1582
+ if (!t?.bundle || !this.#h.size) return;
1583
+ let n = this.#Ie(e);
1584
+ n.executeBundles([t.bundle]), this.#Re(n, t, 0), this.#Re(n, t, 1), n.end(), this.#n.stats.drawCalls += this.#L.draws - this.#j.length;
1585
+ }
1586
+ #Ve(e) {
1587
+ let t = this.#A, n = this.#p;
1588
+ if (!t?.groups || !n || !this.#j.length) return;
1589
+ let r = this.#Ie(e);
1590
+ this.#n.stats.drawCalls += this.#ze(n, r, t), r.end(), this.#He(e, n, t);
1591
+ }
1592
+ #He(e, t, n) {
1593
+ if (!n.surface || !n.surfaceGroups) return;
1594
+ let r = e.encoder.beginRenderPass({
1595
+ colorAttachments: [],
1596
+ depthStencilAttachment: {
1597
+ view: e.depth,
1598
+ depthLoadOp: "load",
1599
+ depthStoreOp: "store",
1600
+ stencilReadOnly: !0
1601
+ }
1602
+ }), i = 0;
1603
+ D(r, e), r.setPipeline(n.surface[0]), r.setBindGroup(0, n.surfaceGroups[0]), r.setIndexBuffer(t.index, "uint32");
1604
+ for (let e of this.#j) e.quads[2] && (r.drawIndexed(e.quads[2] * 6, 1, 0, e.start[2] * I * 4, 0), i++);
1605
+ if (n.surface[1]) {
1606
+ r.setPipeline(n.surface[1]), r.setBindGroup(0, n.surfaceGroups[1]);
1607
+ for (let e of this.#j) {
1608
+ let t = e.bevel?.[2];
1609
+ t && (this.#Le(r, t), i++);
1610
+ }
1611
+ }
1612
+ r.end(), this.#n.stats.drawCalls += i;
1613
+ }
1614
+ };
1615
+ //#endregion
1616
+ export { F as BlockTextures, Oe as VoxelRenderer };