@margoengine/lighting2d 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.
package/dist/height.js ADDED
@@ -0,0 +1,411 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const h=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { a as e, c as t, i as n, l as r, n as i, o as a, r as o, t as s, u as c } from "./resources-Cskg0FqE.js";
5
+ import { a as l, c as u, l as d, r as f, t as p } from "./src-8W7SHUG7.js";
6
+ import { hexColor as m } from "@margoengine/math";
7
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
8
+ //#region src/height.ts
9
+ var g = 0;
10
+ function _(e) {
11
+ if (e.shape !== "box" && e.shape !== "circle" && e.shape !== "segment") throw r("Unknown occluder shape", "pixel-lighting");
12
+ if (!Number.isFinite(e.height) || e.height <= 0) throw r("Invalid occluder height: must be positive finite number", "pixel-lighting");
13
+ if (e.rotation !== void 0 && !Number.isFinite(e.rotation)) throw r("Invalid occluder rotation", "pixel-lighting");
14
+ if (e.elevation !== void 0 && !Number.isFinite(e.elevation)) throw r("Invalid occluder elevation", "pixel-lighting");
15
+ if (e.offset && !e.offset.every(Number.isFinite)) throw r("Invalid occluder offset", "pixel-lighting");
16
+ if (e.shape === "box") {
17
+ if (e.width !== void 0 && (!Number.isFinite(e.width) || e.width <= 0) || e.depth !== void 0 && (!Number.isFinite(e.depth) || e.depth <= 0)) throw r("Invalid box dimensions: width and depth must be positive", "pixel-lighting");
18
+ } else if (e.shape === "circle") {
19
+ if (e.radius !== void 0 && (!Number.isFinite(e.radius) || e.radius <= 0)) throw r("Invalid circle radius: must be positive", "pixel-lighting");
20
+ } else if (e.shape === "segment" && (!e.offset || !e.to || !e.to.every(Number.isFinite))) throw r("Invalid segment endpoints: offset (from) and to must be valid Point2D", "pixel-lighting");
21
+ }
22
+ var v = class extends p {
23
+ constructor(e = {}) {
24
+ super(e);
25
+ }
26
+ };
27
+ function y(e) {
28
+ return _(e), {
29
+ shape: e.shape,
30
+ height: e.height,
31
+ elevation: e.elevation ?? 0,
32
+ width: e.width ?? 16,
33
+ depth: e.depth ?? 16,
34
+ offset: e.offset ? [e.offset[0], e.offset[1]] : [0, 0],
35
+ rotation: e.rotation ?? 0,
36
+ radius: e.radius ?? 8,
37
+ to: e.to ? [e.to[0], e.to[1]] : void 0,
38
+ selfShadow: e.selfShadow ?? !0
39
+ };
40
+ }
41
+ var b = .001;
42
+ function x(e, t, n, r, i, a) {
43
+ let [o, s] = a.offset ?? [0, 0];
44
+ if (a.shape === "box") {
45
+ let c = (a.width ?? 16) / 2, l = (a.depth ?? 16) / 2, u = a.rotation ?? 0, d = Math.cos(-u), f = Math.sin(-u), p = e - o, m = t - s, h = p * d - m * f, g = p * f + m * d, _ = n * d - r * f, v = n * f + r * d, y = -Infinity, x = Infinity;
46
+ if (Math.abs(_) > 1e-7) {
47
+ let e = (-c - h) / _, t = (c - h) / _;
48
+ y = Math.max(y, Math.min(e, t)), x = Math.min(x, Math.max(e, t));
49
+ } else if (Math.abs(h) > c) return null;
50
+ if (Math.abs(v) > 1e-7) {
51
+ let e = (-l - g) / v, t = (l - g) / v;
52
+ y = Math.max(y, Math.min(e, t)), x = Math.min(x, Math.max(e, t));
53
+ } else if (Math.abs(g) > l) return null;
54
+ return y > x + b || x < 1e-4 || y > i ? null : [Math.max(0, y), Math.min(i, x)];
55
+ }
56
+ if (a.shape === "circle") {
57
+ let c = a.radius ?? 8, l = e - o, u = t - s, d = l * n + u * r, f = l * l + u * u - c * c, p = d * d - f;
58
+ if (p < 0) return null;
59
+ let m = Math.sqrt(p), h = -d - m, g = -d + m, _ = Math.min(h, g), v = Math.max(h, g);
60
+ return v < 1e-4 || _ > i ? null : [Math.max(0, _), Math.min(i, v)];
61
+ }
62
+ if (a.shape === "segment") {
63
+ let c = a.to ?? [o, s], l = c[0] - o, u = c[1] - s, d = n * u - r * l;
64
+ if (Math.abs(d) < 1e-7) return null;
65
+ let f = o - e, p = s - t, m = (f * u - p * l) / d, h = (f * r - p * n) / d;
66
+ return m >= 1e-4 && m <= i && h >= 0 && h <= 1 ? [m - .001, m + .001] : null;
67
+ }
68
+ return null;
69
+ }
70
+ function S(e, t, n, r, i = 0) {
71
+ if (!e.shadows) return !1;
72
+ let a = 0, o = 0, s = Infinity, c = 1;
73
+ if (e.kind === "directional") {
74
+ let t = Math.max(.01, Math.min(Math.PI / 2 - .01, e.elevation));
75
+ c = Math.tan(t), a = -Math.cos(e.angle), o = -Math.sin(e.angle), s = 1e4;
76
+ } else {
77
+ let t = e.x - n, i = e.y - r;
78
+ if (s = Math.hypot(t, i), s < 1e-5 || (a = t / s, o = i / s, s > e.radius)) return !1;
79
+ }
80
+ let l = (t) => e.kind === "directional" ? i + t * c : i + t / s * (e.height - i);
81
+ for (let e of t) {
82
+ let t = e.elevation ?? 0, c = t + e.height, u = e.selfShadow ?? !0, d = x(n, r, a, o, s, e);
83
+ if (!d) continue;
84
+ let [f, p] = d;
85
+ if (f <= 1e-4) {
86
+ if (i >= c - .001 || !u) continue;
87
+ let e = l(p);
88
+ if (Math.max(i, e) >= t - b && Math.min(i, e) <= c + b) return !0;
89
+ } else {
90
+ let e = l(f), n = l(p), r = Math.min(e, n);
91
+ if (Math.max(e, n) >= t - b && r <= c + b) return !0;
92
+ }
93
+ }
94
+ return !1;
95
+ }
96
+ function C(e, t, n, r, i = 0) {
97
+ return +!S(e, t, n, r, i);
98
+ }
99
+ function w(e, t, n, r, i = 0, o = [
100
+ 0,
101
+ 0,
102
+ 1
103
+ ], s) {
104
+ if (a(e), s !== void 0 && !l(e, s) || e.mask && !f(e.mask, n, r)) return [
105
+ 0,
106
+ 0,
107
+ 0
108
+ ];
109
+ let c = C(e, t, n, r, i);
110
+ if (c <= 0) return [
111
+ 0,
112
+ 0,
113
+ 0
114
+ ];
115
+ let u = Math.hypot(o[0], o[1], o[2]), d = [
116
+ o[0] / u,
117
+ o[1] / u,
118
+ o[2] / u
119
+ ], p = m(e.color), h = 1, g;
120
+ if (e.kind === "directional") {
121
+ let t = e.elevation, n = e.angle;
122
+ g = [
123
+ -Math.cos(n) * Math.cos(t),
124
+ -Math.sin(n) * Math.cos(t),
125
+ Math.sin(t)
126
+ ];
127
+ } else {
128
+ let t = e.x - n, a = e.y - r, o = e.height - i, s = Math.hypot(t, a), c = Math.hypot(s, o);
129
+ if (h = Math.max(0, 1 - s / e.radius) ** e.falloff, g = c > 0 ? [
130
+ t / c,
131
+ a / c,
132
+ o / c
133
+ ] : d, e.kind === "spot") {
134
+ let n = s ? -(t * Math.cos(e.angle) + a * Math.sin(e.angle)) / s : 1, r = Math.cos(e.cone), i = Math.cos(e.cone * (1 - e.softness));
135
+ h *= i > r ? Math.min(1, Math.max(0, (n - r) / (i - r))) : +(n >= r);
136
+ }
137
+ }
138
+ let _ = h * c * Math.max(0, d[0] * g[0] + d[1] * g[1] + d[2] * g[2]) * e.intensity;
139
+ return [
140
+ p[0] * _,
141
+ p[1] * _,
142
+ p[2] * _
143
+ ];
144
+ }
145
+ var T = "\nstruct LightData{\nposRadius:vec4f,colorIntensity:vec4f,geomParams:vec4f,miscParams:vec4f,camScaleTarget:vec4f,flags:vec4u,layerMasks:vec4u,mask_bounds:vec4f,mask_info:vec4f,}\nstruct OccluderData{\noffset:vec2f,size:vec2f,rotElevH:vec4f,flags:vec4u,}\n@group(0)@binding(0)var<uniform>light:LightData;\n@group(0)@binding(1)var<storage,read>occluders:array<OccluderData>;\nstruct VertexOutput{\n@builtin(position)position:vec4f,@location(0)uv:vec2f,}\n@vertex fn vs_main(@builtin(vertex_index)index:u32)->VertexOutput{\nvar out:VertexOutput;\nlet x=f32((index<<1u)&2u);\nlet y=f32(index&2u);\nout.position=vec4f(x*2.0 - 1.0,1.0 - y*2.0,0.0,1.0);\nout.uv=vec2f(x,y);\nreturn out;\n}\nfn rayOccluderFootprint(px:f32,py:f32,vx:f32,vy:f32,maxDist:f32,idx:u32)->vec2f{\nlet occ=occluders[idx];\nlet shape=occ.flags.x;\nif(shape==0u){\nlet cosR=cos(-occ.rotElevH.x);\nlet sinR=sin(-occ.rotElevH.x);\nlet dx=px - occ.offset.x;\nlet dy=py - occ.offset.y;\nlet plx=dx*cosR - dy*sinR;\nlet ply=dx*sinR+dy*cosR;\nlet vlx=vx*cosR - vy*sinR;\nlet vly=vx*sinR+vy*cosR;\nvar tMin=-1e9;\nvar tMax=1e9;\nif(abs(vlx)>1e-6){\nlet t1=(-occ.size.x - plx)/vlx;\nlet t2=(occ.size.x - plx)/vlx;\ntMin=max(tMin,min(t1,t2));\ntMax=min(tMax,max(t1,t2));\n}\nelse if(abs(plx)>occ.size.x){\nreturn vec2f(-1.0,-1.0);\n}\nif(abs(vly)>1e-6){\nlet t1=(-occ.size.y - ply)/vly;\nlet t2=(occ.size.y - ply)/vly;\ntMin=max(tMin,min(t1,t2));\ntMax=min(tMax,max(t1,t2));\n}\nelse if(abs(ply)>occ.size.y){\nreturn vec2f(-1.0,-1.0);\n}\nif(tMin>tMax+1e-3||tMax<1e-4||tMin>maxDist){\nreturn vec2f(-1.0,-1.0);\n}\nreturn vec2f(max(0.0,tMin),min(maxDist,tMax));\n}\nelse if(shape==1u){\nlet dx=px - occ.offset.x;\nlet dy=py - occ.offset.y;\nlet b=dx*vx+dy*vy;\nlet c=dx*dx+dy*dy - occ.size.x*occ.size.x;\nlet disc=b*b - c;\nif(disc<0.0){\nreturn vec2f(-1.0,-1.0);\n}\nlet s=sqrt(disc);\nlet t1=-b - s;\nlet t2=-b+s;\nlet tMin=min(t1,t2);\nlet tMax=max(t1,t2);\nif(tMax<1e-4||tMin>maxDist){\nreturn vec2f(-1.0,-1.0);\n}\nreturn vec2f(max(0.0,tMin),min(maxDist,tMax));\n}\nelse if(shape==2u){\nlet sx=occ.size.x - occ.offset.x;\nlet sy=occ.size.y - occ.offset.y;\nlet cross=vx*sy - vy*sx;\nif(abs(cross)<1e-6){\nreturn vec2f(-1.0,-1.0);\n}\nlet dx=occ.offset.x - px;\nlet dy=occ.offset.y - py;\nlet t=(dx*sy - dy*sx)/cross;\nlet u=(dx*vy - dy*vx)/cross;\nif(t>=1e-4&&t<=maxDist&&u>=0.0&&u<=1.0){\nreturn vec2f(t - 1e-3,t+1e-3);\n}\n}\nreturn vec2f(-1.0,-1.0);\n}\n@fragment fn fs_main(in:VertexOutput)->@location(0)vec4f{\nif((light.layerMasks.x&light.flags.w)==0u){\nreturn vec4f(0.0,0.0,0.0,1.0);\n}\nlet camX=light.miscParams.z;\nlet camY=light.miscParams.w;\nlet camZoom=light.camScaleTarget.x;\nlet screenPos=in.position.xy;\nlet worldPos=vec2f(camX+screenPos.x/camZoom,camY+screenPos.y/camZoom);\nif(!maskVisible(worldPos,light.mask_bounds,light.mask_info)){\nreturn vec4f(0.0,0.0,0.0,1.0);\n}\nlet rcvElev=light.miscParams.y;\nlet kind=light.flags.x;\nlet lightPos=light.posRadius.xy;\nlet lightRadius=light.posRadius.z;\nlet lightFalloff=light.posRadius.w;\nlet lightColor=light.colorIntensity.xyz;\nlet lightIntensity=light.colorIntensity.w;\nlet lightH=light.geomParams.x;\nlet lightAngle=light.geomParams.y;\nlet lightCone=light.geomParams.z;\nlet lightSoftness=light.geomParams.w;\nlet lightElev=light.miscParams.x;\nvar vx=0.0;\nvar vy=0.0;\nvar maxDist=10000.0;\nvar tanElev=1.0;\nif(kind==2u){\nlet elev=max(0.01,min(1.56079632679,lightElev));\ntanElev=tan(elev);\nvx=-cos(lightAngle);\nvy=-sin(lightAngle);\n}\nelse{\nlet dx=lightPos.x - worldPos.x;\nlet dy=lightPos.y - worldPos.y;\nmaxDist=hypot(dx,dy);\nif(maxDist>=1e-5){\nvx=dx/maxDist;\nvy=dy/maxDist;\n}\nif(maxDist>lightRadius){\nreturn vec4f(0.0,0.0,0.0,1.0);\n}\n}\nvar inShadow=false;\nlet shadowsEnabled=light.flags.y;\nlet occCount=light.flags.z;\nif(shadowsEnabled==1u&&maxDist>=1e-5){\nfor(var i=0u;\ni<occCount;\ni=i+1u){\nlet occ=occluders[i];\nlet baseZ=occ.rotElevH.y;\nlet topZ=baseZ+occ.rotElevH.z;\nlet selfShadow=occ.flags.y;\nlet hit=rayOccluderFootprint(worldPos.x,worldPos.y,vx,vy,maxDist,i);\nif(hit.x<0.0){\ncontinue;\n}\nlet t0=hit.x;\nlet t1=hit.y;\nvar z0=0.0;\nvar z1=0.0;\nif(kind==2u){\nz0=rcvElev+t0*tanElev;\nz1=rcvElev+t1*tanElev;\n}\nelse{\nz0=rcvElev+(t0/maxDist)*(lightH - rcvElev);\nz1=rcvElev+(t1/maxDist)*(lightH - rcvElev);\n}\nif(t0<=1e-4){\nif(rcvElev>=topZ - 1e-3){\ncontinue;\n}\nif(selfShadow==1u){\nif(max(z0,z1)>=baseZ - 1e-3&&min(z0,z1)<=topZ+1e-3){\ninShadow=true;\nbreak;\n}\n}\n}\nelse{\nlet minRayZ=min(z0,z1);\nlet maxRayZ=max(z0,z1);\nif(maxRayZ>=baseZ - 1e-3&&minRayZ<=topZ+1e-3){\ninShadow=true;\nbreak;\n}\n}\n}\n}\nif(inShadow){\nreturn vec4f(0.0,0.0,0.0,1.0);\n}\nvar amount=1.0;\nvar l=vec3f(0.0,0.0,1.0);\nif(kind==2u){\nl=vec3f(-cos(lightAngle)*cos(lightElev),-sin(lightAngle)*cos(lightElev),sin(lightElev));\n}\nelse{\nlet dx=lightPos.x - worldPos.x;\nlet dy=lightPos.y - worldPos.y;\nlet dz=lightH - rcvElev;\nlet flat=hypot(dx,dy);\nlet len=sqrt(flat*flat+dz*dz);\namount=pow(max(0.0,1.0 - flat/lightRadius),lightFalloff);\nif(len>0.0){\nl=vec3f(dx/len,dy/len,dz/len);\n}\nif(kind==1u){\nvar along=1.0;\nif(flat>0.0){\nalong=-(dx*cos(lightAngle)+dy*sin(lightAngle))/flat;\n}\nlet outer=cos(lightCone);\nlet inner=cos(lightCone*(1.0 - lightSoftness));\nif(inner>outer){\namount=amount*clamp((along - outer)/(inner - outer),0.0,1.0);\n}\nelse if(along<outer){\namount=0.0;\n}\n}\n}\nlet n=vec3f(0.0,0.0,1.0);\nlet diffuse=max(0.0,dot(n,l));\nlet finalRgb=lightColor*lightIntensity*amount*diffuse;\nreturn vec4f(finalRgb,1.0);\n}\n@group(1)@binding(0)var sum:texture_2d<f32>;\n@fragment fn present(@builtin(position)p:vec4f)->@location(0)vec4f{\nreturn vec4f(textureLoad(sum,vec2i(p.xy),0).rgb,1);\n}\nfn hypot(x:f32,y:f32)->f32{\nreturn sqrt(x*x+y*y);\n}\n", E = class l {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
146
+ #e = /* @__PURE__ */ new Set();
147
+ #t = [];
148
+ #n = null;
149
+ #r = null;
150
+ #i = null;
151
+ #a = null;
152
+ #o = null;
153
+ #s = null;
154
+ #c = new s();
155
+ #l = null;
156
+ #u = null;
157
+ #d = null;
158
+ #f = null;
159
+ #p = new u();
160
+ #m = !1;
161
+ #h;
162
+ constructor(e = {}) {
163
+ if (this.name = e.name ?? `height-lighting2d-${++g}`, this.order = e.order ?? 15, this.#h = new o(e.target, "HeightLighting2D target", "setTarget"), this.receiverElevation = e.elevation ?? 0, this.layer = e.layer ?? 4294967295, this.camera = e.camera ?? {
164
+ x: 0,
165
+ y: 0,
166
+ zoom: 1
167
+ }, e.occluders && this.setOccluders(e.occluders), e.lights) for (let t of e.lights) this.#e.add(t);
168
+ }
169
+ static attach(e, n = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
170
+ let r = new l(n), i = h(e);
171
+ if (!i.gpu || typeof i.gpu.createShaderModule != "function") throw t("unsupported", "WebGL2 is not supported for @margoengine/lighting2d/height; use WebGPU", "pixel-lighting");
172
+ return i.use(r), r;
173
+ }
174
+ setup(e) {
175
+ if (this.#m) throw t("disposed", "HeightLighting2D disposed; create a new one");
176
+ if (e.backend !== "webgpu" || !e.gpu) throw t("unsupported", "WebGL2 is not supported for @margoengine/lighting2d/height; use WebGPU", "pixel-lighting");
177
+ this.#n = e, this.#h.fix(e.gpu), e.frameGraph.add({
178
+ name: this.name,
179
+ order: this.order,
180
+ execute: (t) => {
181
+ t.backend === "webgpu" && e.gpu && this.render(this.#h.get(e.gpu, e), t.encoder);
182
+ }
183
+ });
184
+ }
185
+ setTarget(e) {
186
+ this.#h.set(e, this.#n?.gpu);
187
+ }
188
+ addLight(e = {}) {
189
+ if (this.#m) throw c("HeightLighting2D has been disposed", "pixel-lighting");
190
+ let t = new v(e);
191
+ return this.#e.add(t), t;
192
+ }
193
+ removeLight(e) {
194
+ return this.#e.delete(e);
195
+ }
196
+ setOccluders(e) {
197
+ if (this.#m) throw c("HeightLighting2D has been disposed", "pixel-lighting");
198
+ for (let t of e) _(t);
199
+ this.#t = e.map(y);
200
+ }
201
+ render(t, o) {
202
+ if (!this.#n || !this.#n.gpu || this.#m) return;
203
+ let s = this.#n.gpu, c = typeof t == "function" ? t() : t;
204
+ if (!c) return;
205
+ if (n(this.camera), e(this.layer), !Number.isFinite(this.receiverElevation)) throw r("Invalid receiver elevation", "pixel-lighting");
206
+ for (let e of this.#e) a(e);
207
+ for (let e of this.#t) _(e);
208
+ if ((this.#d !== s || this.#f !== c.format) && (this.#g(), this.#d = s, this.#f = c.format), this.#p.upload(s, Array.from(this.#e)), !this.#r) {
209
+ let e = s.createShaderModule({ code: d(2) + T });
210
+ this.#u = s.createBindGroupLayout({ entries: [
211
+ {
212
+ binding: 0,
213
+ visibility: GPUShaderStage.FRAGMENT,
214
+ buffer: {
215
+ type: "uniform",
216
+ minBindingSize: 144,
217
+ hasDynamicOffset: !0
218
+ }
219
+ },
220
+ {
221
+ binding: 1,
222
+ visibility: GPUShaderStage.FRAGMENT,
223
+ buffer: { type: "read-only-storage" }
224
+ },
225
+ {
226
+ binding: 2,
227
+ visibility: GPUShaderStage.FRAGMENT,
228
+ buffer: { type: "read-only-storage" }
229
+ }
230
+ ] }), this.#r = s.createRenderPipeline({
231
+ layout: s.createPipelineLayout({ bindGroupLayouts: [this.#u] }),
232
+ vertex: {
233
+ module: e,
234
+ entryPoint: "vs_main"
235
+ },
236
+ fragment: {
237
+ module: e,
238
+ entryPoint: "fs_main",
239
+ targets: [{
240
+ format: "rgba16float",
241
+ blend: {
242
+ color: {
243
+ srcFactor: "one",
244
+ dstFactor: "one",
245
+ operation: "add"
246
+ },
247
+ alpha: {
248
+ srcFactor: "one",
249
+ dstFactor: "zero",
250
+ operation: "add"
251
+ }
252
+ }
253
+ }]
254
+ }
255
+ });
256
+ }
257
+ if ((!this.#a || this.#a.width !== c.width || this.#a.height !== c.height) && (this.#a?.destroy(), this.#a = s.createTexture({
258
+ size: [c.width, c.height],
259
+ format: "rgba16float",
260
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT
261
+ })), !this.#o) {
262
+ let e = s.createShaderModule({ code: d(2) + T });
263
+ this.#o = s.createRenderPipeline({
264
+ layout: "auto",
265
+ vertex: {
266
+ module: e,
267
+ entryPoint: "vs_main"
268
+ },
269
+ fragment: {
270
+ module: e,
271
+ entryPoint: "present",
272
+ targets: [{ format: c.format }]
273
+ }
274
+ }), this.#s = this.#o.getBindGroupLayout(1);
275
+ }
276
+ let l = this.#t.length, u = Math.max(48, l * 48);
277
+ if (u > s.limits.maxStorageBufferBindingSize) throw r("Height occluders exceed maxStorageBufferBindingSize", "pixel-lighting");
278
+ (!this.#l || this.#l.size < u) && (this.#l?.destroy(), this.#l = s.createBuffer({
279
+ size: u,
280
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
281
+ }));
282
+ let f = new Float32Array(u / 4), p = new Uint32Array(f.buffer);
283
+ for (let e = 0; e < l; e++) {
284
+ let t = this.#t[e], n = e * 12;
285
+ f.set([t.offset ? t.offset[0] : 0, t.offset ? t.offset[1] : 0], n + 0), t.shape === "box" ? f.set([(t.width ?? 16) / 2, (t.depth ?? 16) / 2], n + 2) : t.shape === "circle" ? f.set([t.radius ?? 8, 0], n + 2) : t.shape === "segment" && f.set([t.to ? t.to[0] : 0, t.to ? t.to[1] : 0], n + 2), f.set([
286
+ t.rotation ?? 0,
287
+ t.elevation ?? 0,
288
+ t.height,
289
+ 0
290
+ ], n + 4);
291
+ let r = 0;
292
+ t.shape === "circle" ? r = 1 : t.shape === "segment" && (r = 2), p.set([
293
+ r,
294
+ t.selfShadow === !1 ? 0 : 1,
295
+ 0,
296
+ 0
297
+ ], n + 8);
298
+ }
299
+ s.queue.writeBuffer(this.#l, 0, f);
300
+ let h = Math.max(256, s.limits.minUniformBufferOffsetAlignment), g = Math.max(1, this.#e.size) * h;
301
+ if (g > s.limits.maxBufferSize) throw r("Height lights exceed maxBufferSize", "pixel-lighting");
302
+ (!this.#i || this.#i.size < g) && (this.#i?.destroy(), this.#i = s.createBuffer({
303
+ size: g,
304
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
305
+ }));
306
+ let v = o ?? s.createCommandEncoder(), y = v.beginRenderPass({ colorAttachments: [{
307
+ view: i(this.#a),
308
+ loadOp: "clear",
309
+ clearValue: [
310
+ 0,
311
+ 0,
312
+ 0,
313
+ 1
314
+ ],
315
+ storeOp: "store"
316
+ }] });
317
+ y.setPipeline(this.#r);
318
+ let b = new Float32Array(g / 4), x = 0, S = this.#c.get(s, "lights", this.#u, [
319
+ {
320
+ binding: 0,
321
+ resource: {
322
+ buffer: this.#i,
323
+ size: 144
324
+ }
325
+ },
326
+ {
327
+ binding: 1,
328
+ resource: { buffer: this.#l }
329
+ },
330
+ {
331
+ binding: 2,
332
+ resource: { buffer: this.#p.buffer }
333
+ }
334
+ ]);
335
+ for (let e of this.#e) {
336
+ let t = this.#p.fields[x];
337
+ if ((e.layers & this.layer) === 0) {
338
+ x++;
339
+ continue;
340
+ }
341
+ let n = x++ * h, r = new Float32Array(b.buffer, n, 36), i = new Uint32Array(b.buffer, n, 36), a = m(e.color) ?? [
342
+ 1,
343
+ 1,
344
+ 1
345
+ ];
346
+ r.set([
347
+ e.x,
348
+ e.y,
349
+ e.radius,
350
+ e.falloff,
351
+ a[0],
352
+ a[1],
353
+ a[2],
354
+ e.intensity,
355
+ e.height,
356
+ e.angle,
357
+ e.cone,
358
+ e.softness,
359
+ e.elevation,
360
+ this.receiverElevation,
361
+ this.camera.x,
362
+ this.camera.y,
363
+ this.camera.zoom,
364
+ c.width ?? 32,
365
+ c.height ?? 16,
366
+ 0
367
+ ], 0);
368
+ let o = 0;
369
+ e.kind === "spot" ? o = 1 : e.kind === "directional" && (o = 2), i.set([
370
+ o,
371
+ +!!e.shadows,
372
+ l,
373
+ this.layer,
374
+ e.layers,
375
+ 0,
376
+ 0,
377
+ 0
378
+ ], 20), r.set(t, 28), y.setBindGroup(0, S, [n]), y.draw(3);
379
+ }
380
+ y.end(), s.queue.writeBuffer(this.#i, 0, b);
381
+ let C = v.beginRenderPass({ colorAttachments: [{
382
+ view: i(c),
383
+ loadOp: "clear",
384
+ clearValue: [
385
+ 0,
386
+ 0,
387
+ 0,
388
+ 1
389
+ ],
390
+ storeOp: "store"
391
+ }] });
392
+ C.setPipeline(this.#o), C.setBindGroup(1, this.#c.get(s, "show", this.#s, [{
393
+ binding: 0,
394
+ resource: i(this.#a)
395
+ }])), C.draw(3), C.end(), o || s.queue.submit([v.finish()]);
396
+ }
397
+ dispose() {
398
+ this[Symbol.dispose]();
399
+ }
400
+ [Symbol.dispose]() {
401
+ this.#m || (this.#m = !0, this.#e.clear(), this.#t = [], this.#n?.sceneOf(this)?.removePlugin(this.name), this.#n = null, this.#g());
402
+ }
403
+ onDeviceRestored() {
404
+ this.#g();
405
+ }
406
+ #g() {
407
+ this.#a?.destroy(), this.#a = this.#o = this.#s = null, this.#c.clear(), this.#p.dispose(), this.#i?.destroy(), this.#l?.destroy(), this.#i = this.#l = null, this.#r = this.#u = this.#d = this.#f = null;
408
+ }
409
+ };
410
+ //#endregion
411
+ export { v as HeightLight2D, E as HeightLighting2D, _ as checkHeightOccluder, y as createHeightOccluder, w as heightLightAt, C as heightShadowFactor, S as inHeightShadow };
@@ -0,0 +1,192 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
4
+ /** A point in world units. */
5
+ export type Point2D = readonly [number, number];
6
+ /** What a light is: from a point, from a point within a cone, or from far away. */
7
+ export type LightKind2D = 'point' | 'spot' | 'directional';
8
+ /** A geometric mask restricting or clipping where a light can illuminate. */
9
+ export type LightMask2D = {
10
+ kind: 'rect';
11
+ minX: number;
12
+ minY: number;
13
+ maxX: number;
14
+ maxY: number;
15
+ invert?: boolean;
16
+ } | {
17
+ kind: 'circle';
18
+ radius: number;
19
+ center?: Point2D;
20
+ invert?: boolean;
21
+ } | {
22
+ kind: 'polygon';
23
+ points: readonly Point2D[];
24
+ invert?: boolean;
25
+ };
26
+ /** Tests whether point (x, y) is inside the given light mask. */
27
+ export declare function inLightMask(mask: LightMask2D, x: number, y: number): boolean;
28
+ /** Tests whether a light affects a target with the given layer bitmask. */
29
+ export declare function lightAffectsLayer(light: {
30
+ layers?: number;
31
+ }, layerMask: number): boolean;
32
+ /** The fields of a {@link Light2D}, each read each frame. Distances are in world units. */
33
+ export interface Light2DOptions {
34
+ /** Default `'point'`. */
35
+ kind?: LightKind2D;
36
+ /** Position. Default 0. */
37
+ x?: number;
38
+ /** Position, down the screen. Default 0. */
39
+ y?: number;
40
+ /** `#rrggbb`. Default `#ffffff`. */
41
+ color?: string;
42
+ /** Multiplies the colour, 0 or more. Default 1. */
43
+ intensity?: number;
44
+ /** Point and spot: where the light reaches nothing. Default 64. */
45
+ radius?: number;
46
+ /** Point and spot: the power of `1 - distance / radius`, above 0. Default 2. */
47
+ falloff?: number;
48
+ /** Point and spot: how far in front of the picture it sits, 0 or more; a flat surface gets `height / length`. Default 32. */
49
+ height?: number;
50
+ /** Spot and directional: the way it shines, radians clockwise from +x. Default 0. */
51
+ angle?: number;
52
+ /** Spot: half the cone, radians, above 0. Default `Math.PI / 4`. */
53
+ cone?: number;
54
+ /** Spot: the outer part of the cone that fades, 0 (a hard edge) to 1. Default 0. */
55
+ softness?: number;
56
+ /** Directional: how far above the picture, radians; `Math.PI / 2` is straight on. Default `Math.PI / 4`. */
57
+ elevation?: number;
58
+ /** False lets it through occluders. Default true. */
59
+ shadows?: boolean;
60
+ /** Layer bitmask this light illuminates. Tested with bitwise AND against a target's layer. Default ~0 (all layers). */
61
+ layers?: number;
62
+ /** Geometric mask clipping the light. */
63
+ mask?: LightMask2D;
64
+ }
65
+ /** One light. Make it with {@link Lighting2D.addLight}; change any field and the next frame shows it. */
66
+ export declare class Light2D implements Required<Omit<Light2DOptions, 'mask'>> {
67
+ kind: LightKind2D;
68
+ x: number;
69
+ y: number;
70
+ color: string;
71
+ intensity: number;
72
+ radius: number;
73
+ falloff: number;
74
+ height: number;
75
+ angle: number;
76
+ cone: number;
77
+ softness: number;
78
+ elevation: number;
79
+ shadows: boolean;
80
+ layers: number;
81
+ mask?: LightMask2D;
82
+ constructor(options?: Light2DOptions);
83
+ }
84
+ /**
85
+ * The CPU form of the pass, for tools and tests: what `light` adds at world point (x, y), as `[r, g, b]` from 0 up, before
86
+ * shadows. `normal` is the surface direction, x right and y down the screen, as a sprite's normal target holds it.
87
+ * If `layer` is specified, verifies `light.layers & layer !== 0`. If `light.mask` is set, verifies point is inside mask.
88
+ */
89
+ export declare function lightAt(light: Light2D, x: number, y: number, normal?: readonly number[], layer?: number): number[];
90
+ /** Something that blocks light. The shapes of a `tileMapColliders` result from `@margoengine/physics2d` fit as they are. */
91
+ export type Occluder2D = {
92
+ shape: 'polygon';
93
+ points: readonly Point2D[];
94
+ } | {
95
+ shape: 'polyline';
96
+ points: readonly Point2D[];
97
+ } | {
98
+ shape: 'segment';
99
+ from: Point2D;
100
+ to: Point2D;
101
+ } | {
102
+ shape: 'box';
103
+ width: number;
104
+ height: number;
105
+ offset?: Point2D;
106
+ rotation?: number;
107
+ } | {
108
+ shape: 'circle';
109
+ radius: number;
110
+ offset?: Point2D;
111
+ };
112
+ /**
113
+ * The edges occluders cast shadows from, `[ax, ay, bx, by]` each. A polygon closes itself; a polyline stays open; a circle
114
+ * has 24 sides. @throws RangeError for another shape or a value that is not finite.
115
+ */
116
+ export declare function occluderEdges(occluders: readonly Occluder2D[]): Float32Array;
117
+ /** The CPU form of the shadow: whether `edges` (see {@link occluderEdges}) keep `light` from world point (x, y). */
118
+ export declare function inShadow(light: Light2D, edges: ArrayLike<number>, x: number, y: number): boolean;
119
+ /** Settings of {@link Lighting2D}. */
120
+ export interface Lighting2DOptions {
121
+ /**
122
+ * Where the light goes, such as a pixel layer's `target` with `blend: 'multiply'`. Required. A function is read each
123
+ * frame (pass a layer's `() => layer.target`); a plain texture lost at a device restore skips the pass, reported once,
124
+ * until {@link Lighting2D.setTarget} gives a new one.
125
+ */
126
+ target: GPUTexture | (() => GPUTexture);
127
+ /**
128
+ * Surface directions, the size of the target, such as a sprite layer's `normals.target`; a function is read each frame.
129
+ * Default flat. A plain texture lost at a device restore draws flat, reported once, until {@link Lighting2D.setNormals}.
130
+ */
131
+ normals?: GPUTexture | (() => GPUTexture);
132
+ /** World units to pixels, read each frame, such as a pixel layer's `camera`. Default `{x: 0, y: 0, zoom: 1}`. */
133
+ camera?: {
134
+ readonly x: number;
135
+ readonly y: number;
136
+ readonly zoom: number;
137
+ };
138
+ /** The light everything gets, `#rrggbb`, read each frame through {@link Lighting2D.ambient}. Default `#000000`. */
139
+ ambient?: string;
140
+ /** What blocks light. Default none. */
141
+ occluders?: readonly Occluder2D[];
142
+ /** Frame-graph order. Runs after sprites and maps (10), before a compositor (30). Default 20. */
143
+ order?: number;
144
+ /** Plugin name, unique per scene. Default `lighting2d-1`, `lighting2d-2`, ... */
145
+ name?: string;
146
+ /** Layer bitmask this pass illuminates. Lights must share at least one bit with this layer. Default ~0 (all layers). */
147
+ layer?: number;
148
+ }
149
+ /**
150
+ * 2D lights for a pixel picture: point, spot and directional lights with normal-mapped shading and hard shadows from
151
+ * occluder edges. Each frame the lights add up at 16 bits per channel, so many dim ones lose nothing to rounding, and the
152
+ * sum goes to one light target. Show it by multiplying: a pixel layer with `blend: 'multiply'`.
153
+ * WebGPU only.
154
+ * @throws TypeError / RangeError on invalid options or, each frame, an invalid light.
155
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` after `dispose()`, `'state'` when normals differ in size.
156
+ */
157
+ export declare class Lighting2D implements EnginePlugin {
158
+ #private;
159
+ readonly name: string;
160
+ /** The light everything gets, `#rrggbb`, read each frame. */
161
+ ambient: string;
162
+ /** World units to pixels, read each frame. */
163
+ camera: {
164
+ readonly x: number;
165
+ readonly y: number;
166
+ readonly zoom: number;
167
+ };
168
+ /** Layer bitmask of this lighting pass. */
169
+ layer: number;
170
+ /** The lights, in the order added. Use {@link addLight} and {@link removeLight} to change the list. */
171
+ readonly lights: Light2D[];
172
+ constructor(options: Lighting2DOptions);
173
+ /** Creates the lighting and attaches it to `instance`. */
174
+ static attach(instance: EngineKernel, options: Lighting2DOptions): Lighting2D;
175
+ /** Adds a light. Change its fields at any time. */
176
+ addLight(options?: Light2DOptions): Light2D;
177
+ /** Removes a light; one that is not here is ignored. */
178
+ removeLight(light: Light2D): void;
179
+ /** Replaces what blocks light, from the next frame. */
180
+ setOccluders(occluders: readonly Occluder2D[]): void;
181
+ /**
182
+ * Replaces where the light goes, from the next frame: a texture, or a function read each frame. After a device
183
+ * restore, hand in a texture made on `engine.gpu` here.
184
+ */
185
+ setTarget(target: GPUTexture | (() => GPUTexture)): void;
186
+ /** Replaces the surface directions, from the next frame; undefined draws flat. After a device restore, hand in new ones here. */
187
+ setNormals(normals: GPUTexture | (() => GPUTexture) | undefined): void;
188
+ setup(engine: Engine): void;
189
+ onDeviceRestored(): void;
190
+ dispose(): void;
191
+ [Symbol.dispose]: () => void;
192
+ }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { t as Light2D, n as Lighting2D, r as inLightMask, i as inShadow, a as lightAffectsLayer, o as lightAt, s as occluderEdges } from "./src-8W7SHUG7.js";
@@ -0,0 +1,11 @@
1
+ import type { LightMask2D } from './index.js';
2
+ /** Internal, shared CPU packing and GPU clipping contract for every direct-light entry. */
3
+ export declare class MaskData {
4
+ buffer?: GPUBuffer;
5
+ fields: number[][];
6
+ upload(device: GPUDevice, lights: readonly {
7
+ mask?: LightMask2D;
8
+ }[]): void;
9
+ dispose(): void;
10
+ }
11
+ export declare const maskShader: (binding: number) => string;