@holtjs/stage 0.3.0 → 0.4.1

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.
@@ -0,0 +1,2619 @@
1
+ import { _ as rgbToCss, a as EventEmitter, h as packColorAbgr, m as createMatrix2D, o as FilterMode, p as WHITE_RGB, r as BlendModes, s as HEX_MASK, u as TintModes } from "./types-DRFB0Klc.js";
2
+ // src/display.ts
3
+ var DisplayList = class {
4
+ list = [];
5
+ depthDirty = false;
6
+ add(obj) {
7
+ if (obj.parentContainer) obj.parentContainer.remove(obj);
8
+ if (this.list.indexOf(obj) < 0) {
9
+ this.list.push(obj);
10
+ this.depthDirty = true;
11
+ }
12
+ }
13
+ remove(obj) {
14
+ const i = this.list.indexOf(obj);
15
+ if (i >= 0) this.list.splice(i, 1);
16
+ }
17
+ markDepthDirty() {
18
+ this.depthDirty = true;
19
+ }
20
+ sorted() {
21
+ if (this.depthDirty) {
22
+ this.depthDirty = false;
23
+ this.list.sort((a, b) => a.depth - b.depth);
24
+ }
25
+ return this.list;
26
+ }
27
+ clear() {
28
+ this.list.length = 0;
29
+ this.depthDirty = false;
30
+ }
31
+ };
32
+ var DisplayObject = class extends EventEmitter {
33
+ scene;
34
+ type;
35
+ active = true;
36
+ visible = true;
37
+ x = 0;
38
+ y = 0;
39
+ scaleX = 1;
40
+ scaleY = 1;
41
+ rotation = 0;
42
+ alpha = 1;
43
+ depth = 0;
44
+ zIndex = 0;
45
+ trackId = null;
46
+ alt = null;
47
+ role = null;
48
+ surface = null;
49
+ originX = .5;
50
+ originY = .5;
51
+ width = 0;
52
+ height = 0;
53
+ flipX = false;
54
+ flipY = false;
55
+ blendMode = BlendModes.NORMAL;
56
+ scrollFactorX = 1;
57
+ scrollFactorY = 1;
58
+ parentContainer = null;
59
+ customOrigin = false;
60
+ _displayOriginX = 0;
61
+ _displayOriginY = 0;
62
+ disposers = null;
63
+ constructor(scene, type) {
64
+ super();
65
+ this.scene = scene;
66
+ this.type = type;
67
+ scene._trackNodeCreated?.();
68
+ }
69
+ /** Number of pending LIFO teardown callbacks registered on this node via `onDispose()`. */
70
+ get disposerCount() {
71
+ return this.disposers ? this.disposers.length : 0;
72
+ }
73
+ /**
74
+ * Register a cleanup callback (signal unsubscribe, timer/listener removal, texture ref release) that automatically
75
+ * runs in strict LIFO order with error isolation when this node or any ancestor `Container` is destroyed.
76
+ */
77
+ onDispose(fn) {
78
+ if (!this.active) {
79
+ try {
80
+ fn();
81
+ } catch (err) {
82
+ this.scene._trackDisposerError?.(err);
83
+ }
84
+ return () => {};
85
+ }
86
+ (this.disposers ?? (this.disposers = [])).push(fn);
87
+ let cancelled = false;
88
+ return () => {
89
+ if (cancelled || !this.disposers) return;
90
+ cancelled = true;
91
+ const idx = this.disposers.lastIndexOf(fn);
92
+ if (idx >= 0) this.disposers.splice(idx, 1);
93
+ };
94
+ }
95
+ get displayOriginX() {
96
+ return this.customOrigin ? this._displayOriginX : this.width * this.originX;
97
+ }
98
+ get displayOriginY() {
99
+ return this.customOrigin ? this._displayOriginY : this.height * this.originY;
100
+ }
101
+ get displayWidth() {
102
+ return Math.abs(this.width * this.scaleX);
103
+ }
104
+ get displayHeight() {
105
+ return Math.abs(this.height * this.scaleY);
106
+ }
107
+ setPosition(x, y = x) {
108
+ this.x = x;
109
+ this.y = y;
110
+ return this;
111
+ }
112
+ setScale(sx, sy = sx) {
113
+ this.scaleX = sx;
114
+ this.scaleY = sy;
115
+ return this;
116
+ }
117
+ setRotation(rad) {
118
+ this.rotation = rad;
119
+ return this;
120
+ }
121
+ setAngle(deg) {
122
+ this.rotation = deg * Math.PI / 180;
123
+ return this;
124
+ }
125
+ setAlpha(a) {
126
+ this.alpha = a;
127
+ return this;
128
+ }
129
+ setDepth(d) {
130
+ if (this.depth !== d) {
131
+ this.depth = d;
132
+ if (!this.parentContainer) this.scene._displayList.markDepthDirty();
133
+ }
134
+ return this;
135
+ }
136
+ /** Native container-local stacking order (0 by default; sorted stably when any sibling has non-zero zIndex). */
137
+ setZIndex(z) {
138
+ if (this.zIndex !== z) {
139
+ this.zIndex = z;
140
+ if (this.parentContainer) this.parentContainer._markZDirty(z !== 0);
141
+ else this.setDepth(z);
142
+ }
143
+ return this;
144
+ }
145
+ /** Attach a stable, privacy-safe telemetry/automation identifier (never user text or PII). */
146
+ setTrackId(id) {
147
+ this.trackId = id;
148
+ return this;
149
+ }
150
+ /** Attach a concise semantic description for accessibility mirrors and scene snapshots. */
151
+ setAlt(alt) {
152
+ this.alt = alt;
153
+ return this;
154
+ }
155
+ /** Attach a semantic role token (e.g. `button`, `toggle`, `panel`, `tab`, `canvas-entity`). */
156
+ setRole(role) {
157
+ this.role = role;
158
+ return this;
159
+ }
160
+ /** Attach an owning surface/panel identifier (e.g. `hud`, `settings`, `poker`). */
161
+ setSurface(surface) {
162
+ this.surface = surface;
163
+ return this;
164
+ }
165
+ /** Batch-assign semantic metadata (`trackId`, `alt`, `role`, `surface`) on this scene-graph node. */
166
+ setSemantics(s) {
167
+ if (s.trackId !== void 0) this.trackId = s.trackId;
168
+ if (s.alt !== void 0) this.alt = s.alt;
169
+ if (s.role !== void 0) this.role = s.role;
170
+ if (s.surface !== void 0) this.surface = s.surface;
171
+ return this;
172
+ }
173
+ setVisible(v) {
174
+ this.visible = Boolean(v);
175
+ return this;
176
+ }
177
+ setOrigin(ox = .5, oy = ox) {
178
+ this.originX = ox;
179
+ this.originY = oy;
180
+ this.customOrigin = false;
181
+ this._displayOriginX = this.width * ox;
182
+ this._displayOriginY = this.height * oy;
183
+ return this;
184
+ }
185
+ setDisplayOrigin(dx, dy = dx) {
186
+ this.customOrigin = true;
187
+ this._displayOriginX = dx;
188
+ this._displayOriginY = dy;
189
+ this.originX = this.width ? dx / this.width : 0;
190
+ this.originY = this.height ? dy / this.height : 0;
191
+ return this;
192
+ }
193
+ setDisplaySize(w, h) {
194
+ this.scaleX = this.width ? w / this.width : 1;
195
+ this.scaleY = this.height ? h / this.height : 1;
196
+ return this;
197
+ }
198
+ setSize(w, h) {
199
+ this.width = w;
200
+ this.height = h;
201
+ if (!this.customOrigin) {
202
+ this._displayOriginX = w * this.originX;
203
+ this._displayOriginY = h * this.originY;
204
+ }
205
+ return this;
206
+ }
207
+ setFlipX(b) {
208
+ this.flipX = !!b;
209
+ return this;
210
+ }
211
+ setFlipY(b) {
212
+ this.flipY = !!b;
213
+ return this;
214
+ }
215
+ setBlendMode(mode) {
216
+ this.blendMode = mode;
217
+ return this;
218
+ }
219
+ setScrollFactor(x, y = x) {
220
+ this.scrollFactorX = x;
221
+ this.scrollFactorY = y;
222
+ return this;
223
+ }
224
+ removeFromDisplayList() {
225
+ if (this.parentContainer) this.parentContainer.remove(this);
226
+ else this.scene._displayList.remove(this);
227
+ return this;
228
+ }
229
+ /** Compute world-space affine transform matrix (matching Phaser's `getWorldTransformMatrix`). */
230
+ getWorldTransformMatrix(out = createMatrix2D(), _temp) {
231
+ const chain = [];
232
+ for (let cur = this; cur; cur = cur.parentContainer) chain.push(cur);
233
+ let a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0;
234
+ for (let i = chain.length - 1; i >= 0; i--) {
235
+ const n = chain[i];
236
+ const sx = n.scaleX, sy = n.scaleY, r = n.rotation;
237
+ let la, lb, lc, ld;
238
+ if (r === 0) {
239
+ la = sx;
240
+ lb = 0;
241
+ lc = 0;
242
+ ld = sy;
243
+ } else {
244
+ const cs = Math.cos(r), sn = Math.sin(r);
245
+ la = cs * sx;
246
+ lb = sn * sx;
247
+ lc = -sn * sy;
248
+ ld = cs * sy;
249
+ }
250
+ const na = a * la + c * lb;
251
+ const nb = b * la + d * lb;
252
+ const nc = a * lc + c * ld;
253
+ const nd = b * lc + d * ld;
254
+ const ntx = a * n.x + c * n.y + tx;
255
+ const nty = b * n.x + d * n.y + ty;
256
+ a = na;
257
+ b = nb;
258
+ c = nc;
259
+ d = nd;
260
+ tx = ntx;
261
+ ty = nty;
262
+ }
263
+ out.a = a;
264
+ out.b = b;
265
+ out.c = c;
266
+ out.d = d;
267
+ out.tx = tx;
268
+ out.ty = ty;
269
+ out.scaleX = Math.hypot(a, b);
270
+ out.scaleY = Math.hypot(c, d);
271
+ return out;
272
+ }
273
+ /** World-space axis-aligned bounding box. */
274
+ getBounds() {
275
+ const m = this.getWorldTransformMatrix();
276
+ const ox = this.displayOriginX, oy = this.displayOriginY;
277
+ const x0 = -ox, y0 = -oy, x1 = this.width - ox, y1 = this.height - oy;
278
+ const px0 = m.a * x0 + m.c * y0 + m.tx, py0 = m.b * x0 + m.d * y0 + m.ty;
279
+ const px1 = m.a * x1 + m.c * y0 + m.tx, py1 = m.b * x1 + m.d * y0 + m.ty;
280
+ const px2 = m.a * x1 + m.c * y1 + m.tx, py2 = m.b * x1 + m.d * y1 + m.ty;
281
+ const px3 = m.a * x0 + m.c * y1 + m.tx, py3 = m.b * x0 + m.d * y1 + m.ty;
282
+ const left = Math.min(px0, px1, px2, px3);
283
+ const right = Math.max(px0, px1, px2, px3);
284
+ const top = Math.min(py0, py1, py2, py3);
285
+ const bottom = Math.max(py0, py1, py2, py3);
286
+ return {
287
+ x: left,
288
+ y: top,
289
+ width: right - left,
290
+ height: bottom - top,
291
+ left,
292
+ right,
293
+ top,
294
+ bottom
295
+ };
296
+ }
297
+ destroy(_fromScene) {
298
+ if (!this.active) return;
299
+ this.active = false;
300
+ this.visible = false;
301
+ const list = this.disposers;
302
+ this.disposers = null;
303
+ if (list && list.length > 0) {
304
+ for (let i = list.length - 1; i >= 0; i--) try {
305
+ list[i]();
306
+ this.scene._trackDisposerRan?.();
307
+ } catch (err) {
308
+ this.scene._trackDisposerError?.(err);
309
+ }
310
+ list.length = 0;
311
+ }
312
+ this.scene._trackNodeDestroyed?.();
313
+ this.emit("destroy", this);
314
+ this.removeAllListeners();
315
+ this.removeFromDisplayList();
316
+ }
317
+ };
318
+ var ImageObject = class extends DisplayObject {
319
+ texture;
320
+ frame;
321
+ tint = WHITE_RGB;
322
+ isTinted = false;
323
+ tintMode = TintModes.MULTIPLY;
324
+ /** Enable GPU Sharp-Bilinear Pixel-Art AA (crisp square pixels at integer scales, uniform strokes at non-integer scales). */
325
+ pixelAA = false;
326
+ isCropped = false;
327
+ cropX = 0;
328
+ cropY = 0;
329
+ cropW = 0;
330
+ cropH = 0;
331
+ customRenderNodes = {};
332
+ constructor(scene, x, y, key, frame) {
333
+ super(scene, "Image");
334
+ this.x = x;
335
+ this.y = y;
336
+ this.texture = scene.textures.get(key);
337
+ this.frame = this.texture.get(frame);
338
+ this.width = this.frame.width;
339
+ this.height = this.frame.height;
340
+ this._displayOriginX = this.width * this.originX;
341
+ this._displayOriginY = this.height * this.originY;
342
+ }
343
+ setTexture(key, frame) {
344
+ this.texture = this.scene.textures.get(key);
345
+ return this.setFrame(frame ?? "__BASE");
346
+ }
347
+ setFrame(frame) {
348
+ this.frame = this.texture.get(frame);
349
+ this.width = this.frame.width;
350
+ this.height = this.frame.height;
351
+ if (!this.customOrigin) {
352
+ this._displayOriginX = this.width * this.originX;
353
+ this._displayOriginY = this.height * this.originY;
354
+ }
355
+ return this;
356
+ }
357
+ setTint(color) {
358
+ this.tint = color & HEX_MASK;
359
+ this.isTinted = true;
360
+ return this;
361
+ }
362
+ setTintMode(mode) {
363
+ this.tintMode = mode;
364
+ return this;
365
+ }
366
+ clearTint() {
367
+ this.tint = WHITE_RGB;
368
+ this.isTinted = false;
369
+ this.tintMode = TintModes.MULTIPLY;
370
+ return this;
371
+ }
372
+ setPixelAA(on = true) {
373
+ this.pixelAA = Boolean(on);
374
+ return this;
375
+ }
376
+ setCrop(x, y, w, h) {
377
+ if (x === void 0 || y === void 0 || w === void 0 || h === void 0) {
378
+ this.isCropped = false;
379
+ this.cropX = this.cropY = this.cropW = this.cropH = 0;
380
+ } else {
381
+ this.isCropped = true;
382
+ this.cropX = x;
383
+ this.cropY = y;
384
+ this.cropW = Math.max(0, w);
385
+ this.cropH = Math.max(0, h);
386
+ }
387
+ return this;
388
+ }
389
+ };
390
+ var NineSliceObject = class extends DisplayObject {
391
+ texture;
392
+ frame;
393
+ leftWidth;
394
+ rightWidth;
395
+ topHeight;
396
+ bottomHeight;
397
+ constructor(scene, x, y, key, frame, width, height, left, right, top, bottom) {
398
+ super(scene, "NineSlice");
399
+ this.x = x;
400
+ this.y = y;
401
+ this.texture = scene.textures.get(key);
402
+ this.frame = this.texture.get(frame);
403
+ this.width = width;
404
+ this.height = height;
405
+ this.leftWidth = left;
406
+ this.rightWidth = right;
407
+ this.topHeight = top;
408
+ this.bottomHeight = bottom;
409
+ }
410
+ setTexture(key, frame) {
411
+ this.texture = this.scene.textures.get(key);
412
+ this.frame = this.texture.get(frame);
413
+ return this;
414
+ }
415
+ setFrame(frame) {
416
+ this.frame = this.texture.get(frame);
417
+ return this;
418
+ }
419
+ setSlices(width, height, left, right, top, bottom) {
420
+ this.width = Math.max(0, width);
421
+ this.height = Math.max(0, height);
422
+ this.leftWidth = Math.max(0, left);
423
+ this.rightWidth = Math.max(0, right);
424
+ this.topHeight = Math.max(0, top);
425
+ this.bottomHeight = Math.max(0, bottom);
426
+ return this;
427
+ }
428
+ };
429
+ var TileSpriteObject = class extends DisplayObject {
430
+ texture;
431
+ frame;
432
+ tilePositionX = 0;
433
+ tilePositionY = 0;
434
+ tint = WHITE_RGB;
435
+ isTinted = false;
436
+ constructor(scene, x, y, width, height, key, frame) {
437
+ super(scene, "TileSprite");
438
+ this.x = x;
439
+ this.y = y;
440
+ this.width = Math.max(0, width);
441
+ this.height = Math.max(0, height);
442
+ this.texture = scene.textures.get(key);
443
+ this.frame = this.texture.get(frame);
444
+ this.texture.source[0].repeat = true;
445
+ }
446
+ setTint(color) {
447
+ this.tint = color & HEX_MASK;
448
+ this.isTinted = true;
449
+ return this;
450
+ }
451
+ clearTint() {
452
+ this.tint = WHITE_RGB;
453
+ this.isTinted = false;
454
+ return this;
455
+ }
456
+ };
457
+ var RectangleObject = class extends DisplayObject {
458
+ fillColor;
459
+ fillAlpha;
460
+ constructor(scene, x, y, width, height, fillColor = 0, fillAlpha = 1) {
461
+ super(scene, "Rectangle");
462
+ this.x = x;
463
+ this.y = y;
464
+ this.width = width;
465
+ this.height = height;
466
+ this.fillColor = fillColor & HEX_MASK;
467
+ this.fillAlpha = fillAlpha;
468
+ }
469
+ setFillStyle(color, alpha = 1) {
470
+ this.fillColor = color & HEX_MASK;
471
+ this.fillAlpha = alpha;
472
+ return this;
473
+ }
474
+ };
475
+ /**
476
+ * GPU Signed-Distance-Field (SDF) rounded-rect / border / pill / stepped-pixel panel primitive.
477
+ * Batched by `SdfPanelBatcher` on WebGL with zero texture uploads, and mirrored analytically on Canvas2D.
478
+ */
479
+ var PanelObject = class extends DisplayObject {
480
+ fillColor;
481
+ fillAlpha;
482
+ borderColor;
483
+ borderAlpha;
484
+ borderWidth;
485
+ radiusTL;
486
+ radiusTR;
487
+ radiusBR;
488
+ radiusBL;
489
+ pixelStep;
490
+ /** Encoded open seam side: `0` = closed, `1` = open left, `-1` = open right. */
491
+ openSide = 0;
492
+ topGlintColor;
493
+ topGlintAlpha;
494
+ topGlintHeight;
495
+ constructor(scene, x, y, width, height, style = {}) {
496
+ super(scene, "Panel");
497
+ this.originX = 0;
498
+ this.originY = 0;
499
+ this.x = x;
500
+ this.y = y;
501
+ this.width = Math.max(0, width);
502
+ this.height = Math.max(0, height);
503
+ this.fillColor = (style.fillColor ?? 0xffffff) & HEX_MASK;
504
+ this.fillAlpha = style.fillAlpha ?? 1;
505
+ this.borderColor = (style.borderColor ?? 0) & HEX_MASK;
506
+ this.borderAlpha = style.borderAlpha ?? 1;
507
+ this.borderWidth = Math.max(0, style.borderWidth ?? 0);
508
+ this.pixelStep = Math.max(0, style.pixelStep ?? 0);
509
+ this.radiusTL = 0;
510
+ this.radiusTR = 0;
511
+ this.radiusBR = 0;
512
+ this.radiusBL = 0;
513
+ this.topGlintColor = (style.topGlintColor ?? 0xffffff) & HEX_MASK;
514
+ this.topGlintAlpha = Math.max(0, Math.min(1, style.topGlintAlpha ?? 0));
515
+ this.topGlintHeight = Math.max(0, style.topGlintHeight ?? 0);
516
+ if (style.radius !== void 0) this.setRadius(style.radius);
517
+ if (style.openSide !== void 0) this.setOpenSide(style.openSide);
518
+ }
519
+ setFillStyle(color, alpha = 1) {
520
+ this.fillColor = color & HEX_MASK;
521
+ this.fillAlpha = alpha;
522
+ return this;
523
+ }
524
+ setBorderStyle(width, color = this.borderColor, alpha = 1) {
525
+ this.borderWidth = Math.max(0, width);
526
+ this.borderColor = color & HEX_MASK;
527
+ this.borderAlpha = alpha;
528
+ return this;
529
+ }
530
+ setRadius(radius) {
531
+ if (typeof radius === "number") {
532
+ const r = Math.max(0, radius);
533
+ this.radiusTL = r;
534
+ this.radiusTR = r;
535
+ this.radiusBR = r;
536
+ this.radiusBL = r;
537
+ } else {
538
+ this.radiusTL = Math.max(0, radius[0] ?? 0);
539
+ this.radiusTR = Math.max(0, radius[1] ?? 0);
540
+ this.radiusBR = Math.max(0, radius[2] ?? 0);
541
+ this.radiusBL = Math.max(0, radius[3] ?? 0);
542
+ }
543
+ return this;
544
+ }
545
+ setPixelStep(step) {
546
+ this.pixelStep = Math.max(0, step);
547
+ return this;
548
+ }
549
+ setOpenSide(side) {
550
+ this.openSide = side === "left" ? 1 : side === "right" ? -1 : 0;
551
+ return this;
552
+ }
553
+ setTopGlint(height, color = this.topGlintColor, alpha = 1) {
554
+ this.topGlintHeight = Math.max(0, height);
555
+ this.topGlintColor = color & HEX_MASK;
556
+ this.topGlintAlpha = Math.max(0, Math.min(1, alpha));
557
+ return this;
558
+ }
559
+ setPanelStyle(style) {
560
+ if (style.fillColor !== void 0) this.fillColor = style.fillColor & HEX_MASK;
561
+ if (style.fillAlpha !== void 0) this.fillAlpha = style.fillAlpha;
562
+ if (style.borderColor !== void 0) this.borderColor = style.borderColor & HEX_MASK;
563
+ if (style.borderAlpha !== void 0) this.borderAlpha = style.borderAlpha;
564
+ if (style.borderWidth !== void 0) this.borderWidth = Math.max(0, style.borderWidth);
565
+ if (style.radius !== void 0) this.setRadius(style.radius);
566
+ if (style.pixelStep !== void 0) this.pixelStep = Math.max(0, style.pixelStep);
567
+ if (style.openSide !== void 0) this.setOpenSide(style.openSide);
568
+ if (style.topGlintColor !== void 0) this.topGlintColor = style.topGlintColor & HEX_MASK;
569
+ if (style.topGlintAlpha !== void 0) this.topGlintAlpha = Math.max(0, Math.min(1, style.topGlintAlpha));
570
+ if (style.topGlintHeight !== void 0) this.topGlintHeight = Math.max(0, style.topGlintHeight);
571
+ return this;
572
+ }
573
+ };
574
+ /**
575
+ * GPU Multi-channel + True Signed Distance Field (MTSDF) vector icon display object.
576
+ * Batched by `MsdfIconBatcher` on WebGL with arbitrary tint + optional true-SDF outline, and mirrored via `Path2D`
577
+ * on Canvas2D. Resolution-independent from 10 px to 256 px across 1x/2x/3x DPR.
578
+ */
579
+ var MsdfIconObject = class extends DisplayObject {
580
+ texture;
581
+ u0 = 0;
582
+ v0 = 0;
583
+ u1 = 1;
584
+ v1 = 1;
585
+ padRatio = 0;
586
+ rangeUnits = 3.5;
587
+ viewSize = 24;
588
+ fillColor;
589
+ fillAlpha;
590
+ outlineColor;
591
+ outlineAlpha;
592
+ outlineWidth;
593
+ svgPath;
594
+ constructor(scene, x, y, size, config = {}) {
595
+ super(scene, "MsdfIcon");
596
+ this.originX = 0;
597
+ this.originY = 0;
598
+ this.x = x;
599
+ this.y = y;
600
+ const s = Math.max(0, size);
601
+ this.width = s;
602
+ this.height = s;
603
+ this.texture = scene.textures.get(config.textureKey ?? "__DEFAULT");
604
+ this.fillColor = (config.fillColor ?? 0) & HEX_MASK;
605
+ this.fillAlpha = config.fillAlpha ?? 1;
606
+ this.outlineColor = (config.outlineColor ?? 0xffffff) & HEX_MASK;
607
+ this.outlineAlpha = config.outlineAlpha ?? 1;
608
+ this.outlineWidth = Math.max(0, config.outlineWidth ?? 0);
609
+ this.svgPath = config.svgPath ?? null;
610
+ if (config.col !== void 0 && config.row !== void 0) this.setCell(config.col, config.row, config.cols ?? 8, config.rows ?? 4, config.cellSize ?? 32, config.viewSize ?? 24, config.margin ?? 2, config.pxRange ?? 4);
611
+ }
612
+ setTexture(key) {
613
+ this.texture = this.scene.textures.get(key);
614
+ return this;
615
+ }
616
+ /**
617
+ * Bind an MTSDF atlas cell `(col, row)` with exact half-texel UV inset so bilinear sampling never bleeds from
618
+ * neighboring cells, while expanding the quad symmetrically to cover the full padded SDF field.
619
+ */
620
+ setCell(col, row, cols = 8, rows = 4, cellSize = 32, viewSize = 24, margin = 2, pxRange = 4) {
621
+ const atlasW = Math.max(1, cols * cellSize);
622
+ const atlasH = Math.max(1, rows * cellSize);
623
+ this.u0 = (col * cellSize + .5) / atlasW;
624
+ this.v0 = (row * cellSize + .5) / atlasH;
625
+ this.u1 = ((col + 1) * cellSize - .5) / atlasW;
626
+ this.v1 = ((row + 1) * cellSize - .5) / atlasH;
627
+ const unitsPerTexel = (viewSize + margin * 2) / Math.max(1, cellSize);
628
+ const insetMargin = Math.max(0, margin - .5 * unitsPerTexel);
629
+ this.viewSize = Math.max(1, viewSize);
630
+ this.padRatio = insetMargin / this.viewSize;
631
+ this.rangeUnits = Math.max(.001, pxRange * unitsPerTexel);
632
+ return this;
633
+ }
634
+ setColor(color, alpha = this.fillAlpha) {
635
+ this.fillColor = color & HEX_MASK;
636
+ this.fillAlpha = alpha;
637
+ return this;
638
+ }
639
+ setOutline(width, color = this.outlineColor, alpha = this.outlineAlpha) {
640
+ this.outlineWidth = Math.max(0, width);
641
+ this.outlineColor = color & HEX_MASK;
642
+ this.outlineAlpha = alpha;
643
+ return this;
644
+ }
645
+ setSvgPath(path) {
646
+ this.svgPath = path;
647
+ return this;
648
+ }
649
+ };
650
+ let sharedMeasureCtx = null;
651
+ function getMeasureCtx(doc) {
652
+ if (!sharedMeasureCtx) sharedMeasureCtx = doc.createElement("canvas").getContext("2d");
653
+ return sharedMeasureCtx;
654
+ }
655
+ var TextObject = class extends DisplayObject {
656
+ text = "";
657
+ style;
658
+ lineSpacing = 0;
659
+ isCropped = false;
660
+ cropX = 0;
661
+ cropY = 0;
662
+ cropW = 0;
663
+ cropH = 0;
664
+ frame = {
665
+ width: 1,
666
+ height: 1,
667
+ cutWidth: 1,
668
+ cutHeight: 1,
669
+ source: { resolution: 1 }
670
+ };
671
+ canvas = null;
672
+ ctx = null;
673
+ glTex = null;
674
+ glTexAllocW = 0;
675
+ glTexAllocH = 0;
676
+ glDirty = true;
677
+ dirty = true;
678
+ lines = [];
679
+ ascent = 12;
680
+ lineH = 16;
681
+ constructor(scene, x, y, text, style = {}) {
682
+ super(scene, "Text");
683
+ this.originX = 0;
684
+ this.originY = 0;
685
+ this.x = x;
686
+ this.y = y;
687
+ const pad = style.padding;
688
+ this.style = {
689
+ fontFamily: style.fontFamily ?? "system-ui, sans-serif",
690
+ fontSize: typeof style.fontSize === "number" ? `${style.fontSize}px` : style.fontSize ?? "14px",
691
+ fontStyle: style.fontStyle ?? "",
692
+ color: style.color ?? rgbToCss(0, 1),
693
+ stroke: style.stroke ?? "",
694
+ strokeThickness: style.strokeThickness ?? 0,
695
+ backgroundColor: style.backgroundColor ?? null,
696
+ padding: {
697
+ left: pad?.left ?? pad?.x ?? 0,
698
+ right: pad?.right ?? pad?.x ?? 0,
699
+ top: pad?.top ?? pad?.y ?? 0,
700
+ bottom: pad?.bottom ?? pad?.y ?? 0
701
+ },
702
+ align: style.align ?? "left",
703
+ resolution: style.resolution ?? 1,
704
+ metrics: style.metrics ?? null
705
+ };
706
+ this.lineSpacing = style.lineSpacing ?? 0;
707
+ this.frame.source.resolution = this.style.resolution;
708
+ this.setText(text);
709
+ }
710
+ cssFont() {
711
+ const s = this.style;
712
+ return `${s.fontStyle ? s.fontStyle + " " : ""}${s.fontSize} ${s.fontFamily}`;
713
+ }
714
+ recomputeMetrics() {
715
+ const s = this.style;
716
+ const res = s.resolution || 1;
717
+ this.frame.source.resolution = res;
718
+ if (!this.text) {
719
+ this.lines = [];
720
+ this.width = 0;
721
+ this.height = 0;
722
+ this.frame.width = this.frame.cutWidth = 1;
723
+ this.frame.height = this.frame.cutHeight = 1;
724
+ this.dirty = true;
725
+ return;
726
+ }
727
+ const lines = this.text.split("\n");
728
+ this.lines = lines;
729
+ const mctx = getMeasureCtx(this.scene.doc);
730
+ mctx.font = this.cssFont();
731
+ let maxW = 0;
732
+ for (let i = 0; i < lines.length; i++) {
733
+ const w = mctx.measureText(lines[i]).width;
734
+ if (w > maxW) maxW = w;
735
+ }
736
+ if (s.metrics) {
737
+ this.ascent = s.metrics.ascent;
738
+ this.lineH = s.metrics.fontSize;
739
+ } else {
740
+ const px = parseFloat(s.fontSize) || 14;
741
+ mctx.textBaseline = "alphabetic";
742
+ const tm = mctx.measureText("Mg中");
743
+ const asc = Math.ceil(tm.fontBoundingBoxAscent ?? tm.actualBoundingBoxAscent ?? px * .85);
744
+ const desc = Math.ceil(tm.fontBoundingBoxDescent ?? tm.actualBoundingBoxDescent ?? px * .25);
745
+ this.ascent = asc;
746
+ this.lineH = asc + desc;
747
+ }
748
+ const stroke = s.strokeThickness || 0;
749
+ const w = Math.ceil(maxW + stroke + s.padding.left + s.padding.right);
750
+ const h = Math.ceil(lines.length * this.lineH + Math.max(0, lines.length - 1) * this.lineSpacing + stroke + s.padding.top + s.padding.bottom);
751
+ this.width = w;
752
+ this.height = h;
753
+ this.frame.width = this.frame.cutWidth = Math.max(1, Math.ceil(w * res));
754
+ this.frame.height = this.frame.cutHeight = Math.max(1, Math.ceil(h * res));
755
+ if (!this.customOrigin) {
756
+ this._displayOriginX = w * this.originX;
757
+ this._displayOriginY = h * this.originY;
758
+ }
759
+ this.dirty = true;
760
+ }
761
+ setText(value) {
762
+ const next = Array.isArray(value) ? value.join("\n") : String(value ?? "");
763
+ if (next === this.text && !this.dirty) return this;
764
+ this.text = next;
765
+ this.recomputeMetrics();
766
+ return this;
767
+ }
768
+ setStyle(style) {
769
+ const s = this.style;
770
+ if (style.fontFamily !== void 0) s.fontFamily = style.fontFamily;
771
+ if (style.fontSize !== void 0) s.fontSize = typeof style.fontSize === "number" ? `${style.fontSize}px` : style.fontSize;
772
+ if (style.fontStyle !== void 0) s.fontStyle = style.fontStyle;
773
+ if (style.color !== void 0) s.color = style.color;
774
+ if (style.stroke !== void 0) s.stroke = style.stroke;
775
+ if (style.strokeThickness !== void 0) s.strokeThickness = style.strokeThickness;
776
+ if (style.backgroundColor !== void 0) s.backgroundColor = style.backgroundColor;
777
+ if (style.padding !== void 0) {
778
+ s.padding.left = style.padding.left ?? style.padding.x ?? 0;
779
+ s.padding.right = style.padding.right ?? style.padding.x ?? 0;
780
+ s.padding.top = style.padding.top ?? style.padding.y ?? 0;
781
+ s.padding.bottom = style.padding.bottom ?? style.padding.y ?? 0;
782
+ }
783
+ if (style.align !== void 0) s.align = style.align;
784
+ if (style.resolution !== void 0) s.resolution = style.resolution;
785
+ if (style.lineSpacing !== void 0) this.lineSpacing = style.lineSpacing;
786
+ if (style.metrics !== void 0) s.metrics = style.metrics;
787
+ else if (style.fontSize !== void 0 || style.fontFamily !== void 0 || style.fontStyle !== void 0) s.metrics = null;
788
+ this.recomputeMetrics();
789
+ return this;
790
+ }
791
+ setColor(color) {
792
+ if (this.style.color !== color) {
793
+ this.style.color = color;
794
+ this.dirty = true;
795
+ }
796
+ return this;
797
+ }
798
+ setStroke(color, thickness) {
799
+ this.style.stroke = color;
800
+ this.style.strokeThickness = thickness;
801
+ this.recomputeMetrics();
802
+ return this;
803
+ }
804
+ setFontSize(size) {
805
+ const next = typeof size === "number" ? `${size}px` : size;
806
+ if (this.style.fontSize !== next) {
807
+ this.style.fontSize = next;
808
+ this.style.metrics = null;
809
+ this.recomputeMetrics();
810
+ }
811
+ return this;
812
+ }
813
+ setLineSpacing(v) {
814
+ if (this.lineSpacing !== v) {
815
+ this.lineSpacing = v;
816
+ this.recomputeMetrics();
817
+ }
818
+ return this;
819
+ }
820
+ setAlign(align) {
821
+ if (this.style.align !== align) {
822
+ this.style.align = align;
823
+ this.dirty = true;
824
+ }
825
+ return this;
826
+ }
827
+ setResolution(res) {
828
+ const r = res > 0 ? res : 1;
829
+ if (this.style.resolution !== r) {
830
+ this.style.resolution = r;
831
+ this.recomputeMetrics();
832
+ }
833
+ return this;
834
+ }
835
+ setCrop(x, y, w, h) {
836
+ if (x === void 0 || y === void 0 || w === void 0 || h === void 0) {
837
+ this.isCropped = false;
838
+ this.cropX = this.cropY = this.cropW = this.cropH = 0;
839
+ } else {
840
+ this.isCropped = true;
841
+ this.cropX = x;
842
+ this.cropY = y;
843
+ this.cropW = Math.max(0, w);
844
+ this.cropH = Math.max(0, h);
845
+ }
846
+ return this;
847
+ }
848
+ /** Lazily paint the 2D backing canvas only when visible & rendered. */
849
+ ensureCanvas() {
850
+ if (!this.text || this.width <= 0 || this.height <= 0) return null;
851
+ if (!this.dirty && this.canvas) return this.canvas;
852
+ this.dirty = false;
853
+ const cw = this.frame.width;
854
+ const ch = this.frame.height;
855
+ if (!this.canvas) {
856
+ this.canvas = this.scene.doc.createElement("canvas");
857
+ this.ctx = this.canvas.getContext("2d", { willReadFrequently: true });
858
+ }
859
+ if (!this.ctx) return null;
860
+ if (this.canvas.width !== cw || this.canvas.height !== ch) {
861
+ this.canvas.width = cw;
862
+ this.canvas.height = ch;
863
+ } else this.ctx.clearRect(0, 0, cw, ch);
864
+ const g = this.ctx;
865
+ const s = this.style;
866
+ const res = s.resolution || 1;
867
+ const stroke = s.strokeThickness || 0;
868
+ g.save();
869
+ g.scale(res, res);
870
+ if (s.backgroundColor) {
871
+ g.fillStyle = s.backgroundColor;
872
+ g.fillRect(0, 0, this.width, this.height);
873
+ }
874
+ g.font = this.cssFont();
875
+ g.textBaseline = "alphabetic";
876
+ g.textAlign = s.align;
877
+ g.lineJoin = "round";
878
+ g.miterLimit = 2;
879
+ const innerW = this.width - s.padding.left - s.padding.right - stroke;
880
+ const baseX = s.align === "center" ? s.padding.left + stroke * .5 + innerW * .5 : s.align === "right" ? this.width - s.padding.right - stroke * .5 : s.padding.left + stroke * .5;
881
+ let baseY = s.padding.top + stroke * .5 + this.ascent;
882
+ const stepY = this.lineH + this.lineSpacing;
883
+ for (let i = 0; i < this.lines.length; i++) {
884
+ const line = this.lines[i];
885
+ if (stroke > 0 && s.stroke) {
886
+ g.strokeStyle = s.stroke;
887
+ g.lineWidth = stroke;
888
+ g.strokeText(line, baseX, baseY);
889
+ }
890
+ g.fillStyle = s.color;
891
+ g.fillText(line, baseX, baseY);
892
+ baseY += stepY;
893
+ }
894
+ g.restore();
895
+ this.glDirty = true;
896
+ return this.canvas;
897
+ }
898
+ /** Called by the WebGL2 renderer to obtain/update the cached WebGLTexture for this Text.
899
+ * Performs zero GL calls on clean frames; when uploading, binds via `onBindSlot0` so renderer state cache stays exact. */
900
+ ensureGlTexture(gl, onBindSlot0) {
901
+ const cv = this.ensureCanvas();
902
+ if (!cv) return null;
903
+ if (!this.glTex) {
904
+ this.glTex = gl.createTexture();
905
+ this.glTexAllocW = 0;
906
+ this.glTexAllocH = 0;
907
+ this.glDirty = true;
908
+ }
909
+ if (!this.glTex) return null;
910
+ if (this.glDirty || this.glTexAllocW !== cv.width || this.glTexAllocH !== cv.height) {
911
+ if (onBindSlot0) onBindSlot0(this.glTex);
912
+ else {
913
+ gl.activeTexture(gl.TEXTURE0);
914
+ gl.bindTexture(gl.TEXTURE_2D, this.glTex);
915
+ }
916
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
917
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
918
+ if (this.glTexAllocW === cv.width && this.glTexAllocH === cv.height) gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, cv);
919
+ else {
920
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
921
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
922
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
923
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
924
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, cv);
925
+ this.glTexAllocW = cv.width;
926
+ this.glTexAllocH = cv.height;
927
+ }
928
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
929
+ this.glDirty = false;
930
+ }
931
+ return this.glTex;
932
+ }
933
+ invalidateGl() {
934
+ this.glTex = null;
935
+ this.glTexAllocW = 0;
936
+ this.glTexAllocH = 0;
937
+ this.glDirty = true;
938
+ }
939
+ destroy(fromScene) {
940
+ if (this.glTex) {
941
+ try {
942
+ const gl = this.scene.renderer?.gl;
943
+ if (gl && !this.scene.renderer.contextLost) gl.deleteTexture(this.glTex);
944
+ } catch {}
945
+ this.glTex = null;
946
+ }
947
+ this.canvas = null;
948
+ this.ctx = null;
949
+ super.destroy(fromScene);
950
+ }
951
+ };
952
+ var Graphics = class extends DisplayObject {
953
+ ops = /* @__PURE__ */ new Uint8Array(64);
954
+ nums = /* @__PURE__ */ new Float64Array(256);
955
+ opLen = 0;
956
+ numLen = 0;
957
+ /** Monotonic geometry revision bumped on every clear/draw op so WebGL can cache static tessellation meshes. */
958
+ version = 0;
959
+ /** Renderer-owned tessellated local-space mesh cache (opaque to user code). */
960
+ _glCache = null;
961
+ /** Last filled rectangle bounds (used O(1) by `Pane` and `ScrollList` rect clip masks). */
962
+ maskRect = null;
963
+ constructor(scene) {
964
+ super(scene, "Graphics");
965
+ this.originX = 0;
966
+ this.originY = 0;
967
+ }
968
+ pushOp(op, nCount) {
969
+ if (this.opLen >= this.ops.length) {
970
+ const next = new Uint8Array(this.ops.length * 2);
971
+ next.set(this.ops);
972
+ this.ops = next;
973
+ }
974
+ const base = this.numLen;
975
+ if (base + nCount > this.nums.length) {
976
+ let cap = this.nums.length * 2;
977
+ while (cap < base + nCount) cap *= 2;
978
+ const next = new Float64Array(cap);
979
+ next.set(this.nums);
980
+ this.nums = next;
981
+ }
982
+ this.ops[this.opLen++] = op;
983
+ this.numLen = base + nCount;
984
+ this.version++;
985
+ return base;
986
+ }
987
+ clear() {
988
+ if (this.opLen !== 0 || this.numLen !== 0 || this.maskRect !== null) {
989
+ this.opLen = 0;
990
+ this.numLen = 0;
991
+ this.maskRect = null;
992
+ this.version++;
993
+ }
994
+ return this;
995
+ }
996
+ save() {
997
+ this.pushOp(22, 0);
998
+ return this;
999
+ }
1000
+ restore() {
1001
+ this.pushOp(23, 0);
1002
+ return this;
1003
+ }
1004
+ fillStyle(color, alpha = 1) {
1005
+ const i = this.pushOp(1, 2);
1006
+ this.nums[i] = color & HEX_MASK;
1007
+ this.nums[i + 1] = alpha;
1008
+ return this;
1009
+ }
1010
+ lineStyle(lineWidth, color, alpha = 1) {
1011
+ const i = this.pushOp(2, 3);
1012
+ this.nums[i] = lineWidth;
1013
+ this.nums[i + 1] = color & HEX_MASK;
1014
+ this.nums[i + 2] = alpha;
1015
+ return this;
1016
+ }
1017
+ fillRect(x, y, w, h) {
1018
+ const i = this.pushOp(3, 4);
1019
+ this.nums[i] = x;
1020
+ this.nums[i + 1] = y;
1021
+ this.nums[i + 2] = w;
1022
+ this.nums[i + 3] = h;
1023
+ if (!this.maskRect) this.maskRect = {
1024
+ x,
1025
+ y,
1026
+ w,
1027
+ h
1028
+ };
1029
+ else {
1030
+ this.maskRect.x = x;
1031
+ this.maskRect.y = y;
1032
+ this.maskRect.w = w;
1033
+ this.maskRect.h = h;
1034
+ }
1035
+ return this;
1036
+ }
1037
+ strokeRect(x, y, w, h) {
1038
+ const i = this.pushOp(4, 4);
1039
+ this.nums[i] = x;
1040
+ this.nums[i + 1] = y;
1041
+ this.nums[i + 2] = w;
1042
+ this.nums[i + 3] = h;
1043
+ return this;
1044
+ }
1045
+ fillRoundedRect(x, y, w, h, radius = 8) {
1046
+ const r = typeof radius === "number" ? radius : radius.tl ?? radius.tr ?? 8;
1047
+ const i = this.pushOp(5, 5);
1048
+ this.nums[i] = x;
1049
+ this.nums[i + 1] = y;
1050
+ this.nums[i + 2] = w;
1051
+ this.nums[i + 3] = h;
1052
+ this.nums[i + 4] = r;
1053
+ return this;
1054
+ }
1055
+ strokeRoundedRect(x, y, w, h, radius = 8) {
1056
+ const r = typeof radius === "number" ? radius : radius.tl ?? radius.tr ?? 8;
1057
+ const i = this.pushOp(6, 5);
1058
+ this.nums[i] = x;
1059
+ this.nums[i + 1] = y;
1060
+ this.nums[i + 2] = w;
1061
+ this.nums[i + 3] = h;
1062
+ this.nums[i + 4] = r;
1063
+ return this;
1064
+ }
1065
+ fillCircle(x, y, r) {
1066
+ const i = this.pushOp(7, 3);
1067
+ this.nums[i] = x;
1068
+ this.nums[i + 1] = y;
1069
+ this.nums[i + 2] = r;
1070
+ return this;
1071
+ }
1072
+ strokeCircle(x, y, r) {
1073
+ const i = this.pushOp(8, 3);
1074
+ this.nums[i] = x;
1075
+ this.nums[i + 1] = y;
1076
+ this.nums[i + 2] = r;
1077
+ return this;
1078
+ }
1079
+ fillEllipse(x, y, width, height) {
1080
+ const i = this.pushOp(9, 4);
1081
+ this.nums[i] = x;
1082
+ this.nums[i + 1] = y;
1083
+ this.nums[i + 2] = width;
1084
+ this.nums[i + 3] = height;
1085
+ return this;
1086
+ }
1087
+ strokeEllipse(x, y, width, height) {
1088
+ const i = this.pushOp(10, 4);
1089
+ this.nums[i] = x;
1090
+ this.nums[i + 1] = y;
1091
+ this.nums[i + 2] = width;
1092
+ this.nums[i + 3] = height;
1093
+ return this;
1094
+ }
1095
+ fillTriangle(x0, y0, x1, y1, x2, y2) {
1096
+ const i = this.pushOp(11, 6);
1097
+ this.nums[i] = x0;
1098
+ this.nums[i + 1] = y0;
1099
+ this.nums[i + 2] = x1;
1100
+ this.nums[i + 3] = y1;
1101
+ this.nums[i + 4] = x2;
1102
+ this.nums[i + 5] = y2;
1103
+ return this;
1104
+ }
1105
+ strokeTriangle(x0, y0, x1, y1, x2, y2) {
1106
+ const i = this.pushOp(12, 6);
1107
+ this.nums[i] = x0;
1108
+ this.nums[i + 1] = y0;
1109
+ this.nums[i + 2] = x1;
1110
+ this.nums[i + 3] = y1;
1111
+ this.nums[i + 4] = x2;
1112
+ this.nums[i + 5] = y2;
1113
+ return this;
1114
+ }
1115
+ lineBetween(x1, y1, x2, y2) {
1116
+ const i = this.pushOp(13, 4);
1117
+ this.nums[i] = x1;
1118
+ this.nums[i + 1] = y1;
1119
+ this.nums[i + 2] = x2;
1120
+ this.nums[i + 3] = y2;
1121
+ return this;
1122
+ }
1123
+ beginPath() {
1124
+ this.pushOp(14, 0);
1125
+ return this;
1126
+ }
1127
+ moveTo(x, y) {
1128
+ const i = this.pushOp(15, 2);
1129
+ this.nums[i] = x;
1130
+ this.nums[i + 1] = y;
1131
+ return this;
1132
+ }
1133
+ lineTo(x, y) {
1134
+ const i = this.pushOp(16, 2);
1135
+ this.nums[i] = x;
1136
+ this.nums[i + 1] = y;
1137
+ return this;
1138
+ }
1139
+ arc(x, y, r, startAngle, endAngle, anticlockwise = false) {
1140
+ const i = this.pushOp(17, 6);
1141
+ this.nums[i] = x;
1142
+ this.nums[i + 1] = y;
1143
+ this.nums[i + 2] = r;
1144
+ this.nums[i + 3] = startAngle;
1145
+ this.nums[i + 4] = endAngle;
1146
+ this.nums[i + 5] = anticlockwise ? 1 : 0;
1147
+ return this;
1148
+ }
1149
+ slice(x, y, r, startAngle, endAngle, anticlockwise = false) {
1150
+ const i = this.pushOp(18, 6);
1151
+ this.nums[i] = x;
1152
+ this.nums[i + 1] = y;
1153
+ this.nums[i + 2] = r;
1154
+ this.nums[i + 3] = startAngle;
1155
+ this.nums[i + 4] = endAngle;
1156
+ this.nums[i + 5] = anticlockwise ? 1 : 0;
1157
+ return this;
1158
+ }
1159
+ closePath() {
1160
+ this.pushOp(19, 0);
1161
+ return this;
1162
+ }
1163
+ fillPath() {
1164
+ this.pushOp(20, 0);
1165
+ return this;
1166
+ }
1167
+ strokePath() {
1168
+ this.pushOp(21, 0);
1169
+ return this;
1170
+ }
1171
+ fill() {
1172
+ return this.fillPath();
1173
+ }
1174
+ stroke() {
1175
+ return this.strokePath();
1176
+ }
1177
+ fillPoints(points, closeShape = false, closePath = false) {
1178
+ if (points.length < 3) return this;
1179
+ this.beginPath();
1180
+ this.moveTo(points[0].x, points[0].y);
1181
+ for (let i = 1; i < points.length; i++) this.lineTo(points[i].x, points[i].y);
1182
+ if (closeShape || closePath) this.closePath();
1183
+ return this.fillPath();
1184
+ }
1185
+ strokePoints(points, closeShape = false, closePath = false) {
1186
+ if (points.length < 2) return this;
1187
+ this.beginPath();
1188
+ this.moveTo(points[0].x, points[0].y);
1189
+ for (let i = 1; i < points.length; i++) this.lineTo(points[i].x, points[i].y);
1190
+ if (closeShape || closePath) this.closePath();
1191
+ return this.strokePath();
1192
+ }
1193
+ createGeometryMask() {
1194
+ return {
1195
+ graphics: this,
1196
+ active: true
1197
+ };
1198
+ }
1199
+ destroy(fromScene) {
1200
+ this._glCache = null;
1201
+ super.destroy(fromScene);
1202
+ }
1203
+ };
1204
+ var BlitterObject = class extends DisplayObject {
1205
+ texture;
1206
+ children = { list: [] };
1207
+ constructor(scene, x, y, key) {
1208
+ super(scene, "Blitter");
1209
+ this.originX = 0;
1210
+ this.originY = 0;
1211
+ this.x = x;
1212
+ this.y = y;
1213
+ this.texture = scene.textures.get(key);
1214
+ }
1215
+ create(x, y, frame) {
1216
+ const bob = {
1217
+ x,
1218
+ y,
1219
+ visible: true,
1220
+ alpha: 1,
1221
+ frame: this.texture.get(frame)
1222
+ };
1223
+ this.children.list.push(bob);
1224
+ return bob;
1225
+ }
1226
+ destroy(fromScene) {
1227
+ this.children.list.length = 0;
1228
+ super.destroy(fromScene);
1229
+ }
1230
+ };
1231
+ var Container = class extends DisplayObject {
1232
+ list = [];
1233
+ clipMask = null;
1234
+ filters = null;
1235
+ hasZOrder = false;
1236
+ zDirty = false;
1237
+ sortedBuf = null;
1238
+ constructor(scene, x = 0, y = 0, children) {
1239
+ super(scene, "Container");
1240
+ this.originX = 0;
1241
+ this.originY = 0;
1242
+ this.x = x;
1243
+ this.y = y;
1244
+ if (children?.length) this.add(children);
1245
+ }
1246
+ _markZDirty(nonZero) {
1247
+ if (nonZero) this.hasZOrder = true;
1248
+ this.zDirty = true;
1249
+ }
1250
+ /** Children in render order: O(1) direct `list` when all zIndex === 0, else cached stable sort by `zIndex`. */
1251
+ sortedChildren() {
1252
+ if (!this.hasZOrder) return this.list;
1253
+ if (this.zDirty || !this.sortedBuf) {
1254
+ this.zDirty = false;
1255
+ const src = this.list;
1256
+ let anyNonZero = false;
1257
+ for (let i = 0; i < src.length; i++) if (src[i].zIndex !== 0) {
1258
+ anyNonZero = true;
1259
+ break;
1260
+ }
1261
+ if (!anyNonZero) {
1262
+ this.hasZOrder = false;
1263
+ this.sortedBuf = null;
1264
+ return src;
1265
+ }
1266
+ const buf = this.sortedBuf ?? (this.sortedBuf = []);
1267
+ buf.length = src.length;
1268
+ for (let i = 0; i < src.length; i++) buf[i] = src[i];
1269
+ buf.sort((a, b) => a.zIndex - b.zIndex);
1270
+ }
1271
+ return this.sortedBuf;
1272
+ }
1273
+ add(child) {
1274
+ if (Array.isArray(child)) for (let i = 0; i < child.length; i++) this.addOne(child[i]);
1275
+ else if (child) this.addOne(child);
1276
+ return this;
1277
+ }
1278
+ addOne(child) {
1279
+ if (child === this) return;
1280
+ if (child.parentContainer === this) return;
1281
+ if (child.parentContainer) child.parentContainer.remove(child);
1282
+ else this.scene._displayList.remove(child);
1283
+ child.parentContainer = this;
1284
+ this.list.push(child);
1285
+ if (child.zIndex !== 0) this.hasZOrder = true;
1286
+ if (this.hasZOrder) this.zDirty = true;
1287
+ }
1288
+ /** Insert `child` at `index` in `this.list` (clamped to `[0, list.length]`). Moves in-place if already in this container. */
1289
+ addAt(child, index) {
1290
+ if (!child || child === this) return this;
1291
+ const clamped = Math.max(0, Math.min(Math.round(index), this.list.length));
1292
+ if (child.parentContainer === this) return this.moveTo(child, Math.min(clamped, Math.max(0, this.list.length - 1)));
1293
+ if (child.parentContainer) child.parentContainer.remove(child);
1294
+ else this.scene._displayList.remove(child);
1295
+ child.parentContainer = this;
1296
+ this.list.splice(Math.min(clamped, this.list.length), 0, child);
1297
+ if (child.zIndex !== 0) this.hasZOrder = true;
1298
+ if (this.hasZOrder) this.zDirty = true;
1299
+ return this;
1300
+ }
1301
+ /** Move an existing child of this container to `index` in `this.list` (clamped to `[0, list.length - 1]`). */
1302
+ moveTo(child, index) {
1303
+ const cur = this.list.indexOf(child);
1304
+ if (cur < 0) return this;
1305
+ const target = Math.max(0, Math.min(Math.round(index), this.list.length - 1));
1306
+ if (cur === target) return this;
1307
+ this.list.splice(cur, 1);
1308
+ this.list.splice(target, 0, child);
1309
+ if (this.hasZOrder) this.zDirty = true;
1310
+ return this;
1311
+ }
1312
+ remove(child) {
1313
+ const i = this.list.indexOf(child);
1314
+ if (i >= 0) {
1315
+ this.list.splice(i, 1);
1316
+ child.parentContainer = null;
1317
+ if (this.hasZOrder) this.zDirty = true;
1318
+ }
1319
+ return this;
1320
+ }
1321
+ getIndex(child) {
1322
+ return this.list.indexOf(child);
1323
+ }
1324
+ sendToBack(child) {
1325
+ const i = this.list.indexOf(child);
1326
+ if (i > 0) {
1327
+ this.list.splice(i, 1);
1328
+ this.list.unshift(child);
1329
+ if (this.hasZOrder) this.zDirty = true;
1330
+ }
1331
+ return this;
1332
+ }
1333
+ bringToTop(child) {
1334
+ const i = this.list.indexOf(child);
1335
+ if (i >= 0 && i < this.list.length - 1) {
1336
+ this.list.splice(i, 1);
1337
+ this.list.push(child);
1338
+ if (this.hasZOrder) this.zDirty = true;
1339
+ }
1340
+ return this;
1341
+ }
1342
+ setMask(mask) {
1343
+ this.clipMask = mask;
1344
+ return this;
1345
+ }
1346
+ clearMask() {
1347
+ this.clipMask = null;
1348
+ return this;
1349
+ }
1350
+ /** Zero-FBO compatibility hook for `Pane` & `ScrollList` (clips via hardware `gl.SCISSOR_TEST`). */
1351
+ enableFilters() {
1352
+ if (!this.filters) this.filters = { external: { addMask: (maskG) => {
1353
+ const m = {
1354
+ graphics: maskG,
1355
+ active: true
1356
+ };
1357
+ this.clipMask = m;
1358
+ return m;
1359
+ } } };
1360
+ return this;
1361
+ }
1362
+ destroy(destroyChildren = true) {
1363
+ if (!this.active) return;
1364
+ if (destroyChildren) {
1365
+ const snap = this.list.slice();
1366
+ this.list.length = 0;
1367
+ for (let i = snap.length - 1; i >= 0; i--) {
1368
+ snap[i].parentContainer = null;
1369
+ snap[i].destroy(true);
1370
+ }
1371
+ } else {
1372
+ for (let i = 0; i < this.list.length; i++) this.list[i].parentContainer = null;
1373
+ this.list.length = 0;
1374
+ }
1375
+ this.clipMask = null;
1376
+ this.filters = null;
1377
+ this.sortedBuf = null;
1378
+ this.hasZOrder = false;
1379
+ this.zDirty = false;
1380
+ super.destroy(destroyChildren);
1381
+ }
1382
+ };
1383
+ var CustomPassObject = class extends DisplayObject {
1384
+ onRender;
1385
+ restoreState;
1386
+ constructor(scene, onRender, options) {
1387
+ super(scene, "CustomPass");
1388
+ this.onRender = onRender;
1389
+ this.restoreState = options?.restoreState !== false;
1390
+ this._isCrowdInstanced = true;
1391
+ }
1392
+ };
1393
+ /**
1394
+ * High-throughput SoA instanced sprite/quad batch (`scene.add.instancedBatch(key, maxCount)`).
1395
+ * Consumes `SoaWorld` `Float32Array` columns directly: renders via hardware `drawElementsInstanced`
1396
+ * in WebGL2, instanced storage/vertex buffer in WebGPU, and zero-alloc loop in Canvas2D / Headless Node.
1397
+ */
1398
+ var InstancedBatchObject = class extends DisplayObject {
1399
+ texture;
1400
+ defaultFrame;
1401
+ maxCount;
1402
+ columns = null;
1403
+ /** Renderer-owned GPU instance buffer cache (opaque to user code). */
1404
+ _gpuCache = null;
1405
+ constructor(scene, key, maxCount = 1024, frame) {
1406
+ super(scene, "InstancedBatch");
1407
+ this.maxCount = Math.max(1, Math.floor(maxCount));
1408
+ this.originX = .5;
1409
+ this.originY = .5;
1410
+ this.setTexture(key, frame);
1411
+ }
1412
+ setTexture(key, frame) {
1413
+ this.texture = this.scene.textures.get(key);
1414
+ this.defaultFrame = this.texture.get(frame);
1415
+ this.width = this.defaultFrame.width;
1416
+ this.height = this.defaultFrame.height;
1417
+ return this;
1418
+ }
1419
+ /** Bind or update the SoA column views read on each render pass (zero copying on caller side). */
1420
+ setColumns(columns) {
1421
+ this.columns = columns;
1422
+ return this;
1423
+ }
1424
+ destroy(fromScene) {
1425
+ if (this._gpuCache && typeof this._gpuCache.destroy === "function") try {
1426
+ this._gpuCache.destroy();
1427
+ } catch {}
1428
+ this._gpuCache = null;
1429
+ this.columns = null;
1430
+ super.destroy(fromScene);
1431
+ }
1432
+ };
1433
+ // src/renderer-webgpu.ts
1434
+ const GPUShaderStage_VERTEX = 1;
1435
+ const GPUShaderStage_FRAGMENT = 2;
1436
+ /**
1437
+ * Asynchronously acquire a browser `GPUDevice` + configured `GPUCanvasContext` ready to pass directly into
1438
+ * `new Game({ type: WEBGPU, gpuDevice: gpu.device, gpuContext: gpu.context, gpuFormat: gpu.format })`.
1439
+ * Returns `null` cleanly when WebGPU is unsupported on the current browser/OS.
1440
+ */
1441
+ async function requestWebGpuDevice(canvas, options = {}) {
1442
+ const nav = typeof navigator !== "undefined" ? navigator : null;
1443
+ if (!nav?.gpu || typeof nav.gpu.requestAdapter !== "function") return null;
1444
+ try {
1445
+ const adapter = await nav.gpu.requestAdapter({ powerPreference: options.powerPreference ?? "high-performance" });
1446
+ if (!adapter) return null;
1447
+ const device = await adapter.requestDevice();
1448
+ const ctx = canvas.getContext("webgpu");
1449
+ if (!ctx) return null;
1450
+ const format = typeof nav.gpu.getPreferredCanvasFormat === "function" ? nav.gpu.getPreferredCanvasFormat() : "bgra8unorm";
1451
+ ctx.configure({
1452
+ device,
1453
+ format,
1454
+ alphaMode: options.transparent ? "premultiplied" : "opaque"
1455
+ });
1456
+ return {
1457
+ device,
1458
+ context: ctx,
1459
+ format
1460
+ };
1461
+ } catch {
1462
+ return null;
1463
+ }
1464
+ }
1465
+ const MAX_VERTS = 16384;
1466
+ const MAX_INDICES = 32768;
1467
+ const VERT_FLOATS = 6;
1468
+ const VERT_STRIDE = 24;
1469
+ const MAX_SDF_PANELS = 1024;
1470
+ const SDF_FLOATS = 16;
1471
+ const SDF_STRIDE = 64;
1472
+ const WGSL_BATCH_SRC = `
1473
+ struct Globals {
1474
+ resolution: vec2<f32>,
1475
+ _pad: vec2<f32>,
1476
+ };
1477
+ @group(0) @binding(0) var<uniform> uGlobals: Globals;
1478
+ @group(0) @binding(1) var uSampler: sampler;
1479
+ @group(0) @binding(2) var uTex: texture_2d<f32>;
1480
+
1481
+ struct VsIn {
1482
+ @location(0) pos: vec2<f32>,
1483
+ @location(1) uv: vec2<f32>,
1484
+ @location(2) color: u32,
1485
+ @location(3) mode: f32,
1486
+ };
1487
+
1488
+ struct VsOut {
1489
+ @builtin(position) pos: vec4<f32>,
1490
+ @location(0) uv: vec2<f32>,
1491
+ @location(1) color: vec4<f32>,
1492
+ @location(2) mode: f32,
1493
+ };
1494
+
1495
+ fn unpackAbgr(c: u32) -> vec4<f32> {
1496
+ return vec4<f32>(
1497
+ f32(c & 255u) / 255.0,
1498
+ f32((c >> 8u) & 255u) / 255.0,
1499
+ f32((c >> 16u) & 255u) / 255.0,
1500
+ f32((c >> 24u) & 255u) / 255.0,
1501
+ );
1502
+ }
1503
+
1504
+ @vertex
1505
+ fn vsMain(in: VsIn) -> VsOut {
1506
+ var out: VsOut;
1507
+ let clip = (in.pos / uGlobals.resolution) * 2.0 - 1.0;
1508
+ out.pos = vec4<f32>(clip.x, -clip.y, 0.0, 1.0);
1509
+ out.uv = in.uv;
1510
+ out.color = unpackAbgr(in.color);
1511
+ out.mode = in.mode;
1512
+ return out;
1513
+ }
1514
+
1515
+ @fragment
1516
+ fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
1517
+ if (in.mode > 1.5) {
1518
+ return vec4<f32>(in.color.rgb * in.color.a, in.color.a);
1519
+ }
1520
+ let tex = textureSample(uTex, uSampler, in.uv);
1521
+ if (in.mode > 0.5) {
1522
+ let a = tex.a * in.color.a;
1523
+ return vec4<f32>(in.color.rgb * a, a);
1524
+ }
1525
+ return vec4<f32>(tex.rgb * in.color.rgb * in.color.a, tex.a * in.color.a);
1526
+ }
1527
+ `;
1528
+ const WGSL_SDF_SRC = `
1529
+ struct Globals {
1530
+ resolution: vec2<f32>,
1531
+ _pad: vec2<f32>,
1532
+ };
1533
+ @group(0) @binding(0) var<uniform> uGlobals: Globals;
1534
+
1535
+ struct SdfIn {
1536
+ @location(0) corner: vec2<f32>,
1537
+ @location(1) mat: vec4<f32>,
1538
+ @location(2) transSize: vec4<f32>,
1539
+ @location(3) radii: vec4<f32>,
1540
+ @location(4) style: vec4<f32>, // borderW, pixelStep, fillAbgrBits, borderAbgrBits
1541
+ };
1542
+
1543
+ struct SdfOut {
1544
+ @builtin(position) pos: vec4<f32>,
1545
+ @location(0) localPos: vec2<f32>,
1546
+ @location(1) halfSize: vec2<f32>,
1547
+ @location(2) radii: vec4<f32>,
1548
+ @location(3) borderW: f32,
1549
+ @location(4) pixelStep: f32,
1550
+ @location(5) fillCol: vec4<f32>,
1551
+ @location(6) borderCol: vec4<f32>,
1552
+ };
1553
+
1554
+ fn unpackAbgrBits(bits: f32) -> vec4<f32> {
1555
+ let c = bitcast<u32>(bits);
1556
+ return vec4<f32>(
1557
+ f32(c & 255u) / 255.0,
1558
+ f32((c >> 8u) & 255u) / 255.0,
1559
+ f32((c >> 16u) & 255u) / 255.0,
1560
+ f32((c >> 24u) & 255u) / 255.0,
1561
+ );
1562
+ }
1563
+
1564
+ @vertex
1565
+ fn vsSdf(in: SdfIn) -> SdfOut {
1566
+ var out: SdfOut;
1567
+ let w = in.transSize.z;
1568
+ let h = in.transSize.w;
1569
+ let lx = in.corner.x * w;
1570
+ let ly = in.corner.y * h;
1571
+ let sx = in.mat.x * lx + in.mat.z * ly + in.transSize.x;
1572
+ let sy = in.mat.y * lx + in.mat.w * ly + in.transSize.y;
1573
+ let clip = (vec2<f32>(sx, sy) / uGlobals.resolution) * 2.0 - 1.0;
1574
+ out.pos = vec4<f32>(clip.x, -clip.y, 0.0, 1.0);
1575
+ out.halfSize = vec2<f32>(w * 0.5, h * 0.5);
1576
+ out.localPos = vec2<f32>(lx, ly) - out.halfSize;
1577
+ out.radii = in.radii;
1578
+ out.borderW = in.style.x;
1579
+ out.pixelStep = in.style.y;
1580
+ out.fillCol = unpackAbgrBits(in.style.z);
1581
+ out.borderCol = unpackAbgrBits(in.style.w);
1582
+ return out;
1583
+ }
1584
+
1585
+ fn sdRoundBox(p: vec2<f32>, b: vec2<f32>, r: vec4<f32>) -> f32 {
1586
+ var rx: f32;
1587
+ if (p.x > 0.0) {
1588
+ rx = select(r.y, r.z, p.y > 0.0); // tr (y<0), br (y>0)
1589
+ } else {
1590
+ rx = select(r.x, r.w, p.y > 0.0); // tl (y<0), bl (y>0)
1591
+ }
1592
+ let q = abs(p) - b + vec2<f32>(rx, rx);
1593
+ return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0, 0.0))) - rx;
1594
+ }
1595
+
1596
+ @fragment
1597
+ fn fsSdf(in: SdfOut) -> @location(0) vec4<f32> {
1598
+ var p = in.localPos;
1599
+ let stepPx = in.pixelStep;
1600
+ if (stepPx >= 1.0) {
1601
+ p = (floor((p + in.halfSize) / stepPx) + 0.5) * stepPx - in.halfSize;
1602
+ }
1603
+ let d = sdRoundBox(p, in.halfSize, in.radii);
1604
+ let aa = select(0.75, 0.02, stepPx >= 1.0);
1605
+ let outerMask = 1.0 - smoothstep(-aa, aa, d);
1606
+ if (outerMask <= 0.001) {
1607
+ discard;
1608
+ }
1609
+ if (in.borderW > 0.0 && in.borderCol.a > 0.0) {
1610
+ let innerMask = 1.0 - smoothstep(-aa, aa, d + in.borderW);
1611
+ let bFactor = clamp(outerMask - innerMask, 0.0, 1.0);
1612
+ let fCol = vec4<f32>(in.fillCol.rgb * in.fillCol.a, in.fillCol.a) * innerMask;
1613
+ let bCol = vec4<f32>(in.borderCol.rgb * in.borderCol.a, in.borderCol.a) * bFactor;
1614
+ return fCol + bCol;
1615
+ }
1616
+ let a = in.fillCol.a * outerMask;
1617
+ return vec4<f32>(in.fillCol.rgb * a, a);
1618
+ }
1619
+ `;
1620
+ function blendTargetState(format, mode) {
1621
+ if (mode === BlendModes.ADD) return {
1622
+ format,
1623
+ blend: {
1624
+ color: {
1625
+ srcFactor: "one",
1626
+ dstFactor: "one",
1627
+ operation: "add"
1628
+ },
1629
+ alpha: {
1630
+ srcFactor: "one",
1631
+ dstFactor: "one",
1632
+ operation: "add"
1633
+ }
1634
+ }
1635
+ };
1636
+ if (mode === BlendModes.MULTIPLY) return {
1637
+ format,
1638
+ blend: {
1639
+ color: {
1640
+ srcFactor: "dst",
1641
+ dstFactor: "one-minus-src-alpha",
1642
+ operation: "add"
1643
+ },
1644
+ alpha: {
1645
+ srcFactor: "one",
1646
+ dstFactor: "one-minus-src-alpha",
1647
+ operation: "add"
1648
+ }
1649
+ }
1650
+ };
1651
+ if (mode === BlendModes.SCREEN) return {
1652
+ format,
1653
+ blend: {
1654
+ color: {
1655
+ srcFactor: "one",
1656
+ dstFactor: "one-minus-src",
1657
+ operation: "add"
1658
+ },
1659
+ alpha: {
1660
+ srcFactor: "one",
1661
+ dstFactor: "one-minus-src-alpha",
1662
+ operation: "add"
1663
+ }
1664
+ }
1665
+ };
1666
+ return {
1667
+ format,
1668
+ blend: {
1669
+ color: {
1670
+ srcFactor: "one",
1671
+ dstFactor: "one-minus-src-alpha",
1672
+ operation: "add"
1673
+ },
1674
+ alpha: {
1675
+ srcFactor: "one",
1676
+ dstFactor: "one-minus-src-alpha",
1677
+ operation: "add"
1678
+ }
1679
+ }
1680
+ };
1681
+ }
1682
+ function multiplyMat(parent, x, y, sx, sy, rot, out) {
1683
+ let la, lb, lc, ld;
1684
+ if (rot === 0) {
1685
+ la = sx;
1686
+ lb = 0;
1687
+ lc = 0;
1688
+ ld = sy;
1689
+ } else {
1690
+ const cs = Math.cos(rot), sn = Math.sin(rot);
1691
+ la = cs * sx;
1692
+ lb = sn * sx;
1693
+ lc = -sn * sy;
1694
+ ld = cs * sy;
1695
+ }
1696
+ out.a = parent.a * la + parent.c * lb;
1697
+ out.b = parent.b * la + parent.d * lb;
1698
+ out.c = parent.a * lc + parent.c * ld;
1699
+ out.d = parent.b * lc + parent.d * ld;
1700
+ out.tx = parent.a * x + parent.c * y + parent.tx;
1701
+ out.ty = parent.b * x + parent.d * y + parent.ty;
1702
+ return out;
1703
+ }
1704
+ var RendererWebGpu = class extends EventEmitter {
1705
+ type = 3;
1706
+ isWebGL2 = false;
1707
+ isWebGPU = true;
1708
+ gl = null;
1709
+ contextLost = false;
1710
+ maxTextures = 16;
1711
+ canvas;
1712
+ device;
1713
+ gpuContext;
1714
+ format;
1715
+ width;
1716
+ height;
1717
+ globalsBuf;
1718
+ vbo;
1719
+ ibo;
1720
+ sdfCornerVbo;
1721
+ sdfInstVbo;
1722
+ sdfQuadIbo;
1723
+ samplerLinear;
1724
+ samplerNearest;
1725
+ batchBgl;
1726
+ sdfBgl;
1727
+ sdfBindGroup;
1728
+ batchPipelines = /* @__PURE__ */ new Map();
1729
+ sdfPipelines = /* @__PURE__ */ new Map();
1730
+ texCache = /* @__PURE__ */ new WeakMap();
1731
+ dummyEntry;
1732
+ vertRaw = new ArrayBuffer(MAX_VERTS * VERT_STRIDE);
1733
+ f32 = new Float32Array(this.vertRaw);
1734
+ u32 = new Uint32Array(this.vertRaw);
1735
+ indices = new Uint16Array(MAX_INDICES);
1736
+ sdfRaw = new ArrayBuffer(MAX_SDF_PANELS * SDF_STRIDE);
1737
+ sdfF32 = new Float32Array(this.sdfRaw);
1738
+ sdfU32 = new Uint32Array(this.sdfRaw);
1739
+ vertCount = 0;
1740
+ indexCount = 0;
1741
+ cmdStartIndex = 0;
1742
+ sdfCount = 0;
1743
+ sdfCmdStart = 0;
1744
+ curBlend = BlendModes.NORMAL;
1745
+ curBindGroup = null;
1746
+ cmds = [];
1747
+ scissorStack = [];
1748
+ matPool = [];
1749
+ sfMat = createMatrix2D();
1750
+ maskWorldMat = createMatrix2D();
1751
+ lastStats = {
1752
+ drawCalls: 0,
1753
+ flushes: 0,
1754
+ quads: 0,
1755
+ tris: 0,
1756
+ culled: 0,
1757
+ texBinds: 0,
1758
+ batchMaxUnits: 1,
1759
+ sdfPanels: 0,
1760
+ sdfDraws: 0,
1761
+ msdfIcons: 0,
1762
+ msdfDraws: 0,
1763
+ pixelAaIcons: 0,
1764
+ pixelAaDraws: 0
1765
+ };
1766
+ constructor(canvas, width, height, opts) {
1767
+ super();
1768
+ this.canvas = canvas;
1769
+ this.width = Math.max(1, Math.round(width));
1770
+ this.height = Math.max(1, Math.round(height));
1771
+ this.device = opts.device;
1772
+ const format = opts.format ?? "bgra8unorm";
1773
+ this.format = format;
1774
+ const ctx = opts.context ?? canvas.getContext("webgpu");
1775
+ if (!ctx) throw new Error("Stage: WebGPU canvas context unavailable");
1776
+ this.gpuContext = ctx;
1777
+ ctx.configure({
1778
+ device: this.device,
1779
+ format,
1780
+ alphaMode: opts.transparent ? "premultiplied" : "opaque"
1781
+ });
1782
+ for (let i = 0; i < 32; i++) this.matPool.push(createMatrix2D());
1783
+ const dev = this.device;
1784
+ this.globalsBuf = dev.createBuffer({
1785
+ size: 16,
1786
+ usage: 72
1787
+ });
1788
+ this.vbo = dev.createBuffer({
1789
+ size: this.vertRaw.byteLength,
1790
+ usage: 40
1791
+ });
1792
+ this.ibo = dev.createBuffer({
1793
+ size: this.indices.byteLength,
1794
+ usage: 24
1795
+ });
1796
+ this.sdfCornerVbo = dev.createBuffer({
1797
+ size: 32,
1798
+ usage: 40
1799
+ });
1800
+ dev.queue.writeBuffer(this.sdfCornerVbo, 0, new Float32Array([
1801
+ 0,
1802
+ 0,
1803
+ 1,
1804
+ 0,
1805
+ 1,
1806
+ 1,
1807
+ 0,
1808
+ 1
1809
+ ]));
1810
+ this.sdfQuadIbo = dev.createBuffer({
1811
+ size: 16,
1812
+ usage: 24
1813
+ });
1814
+ dev.queue.writeBuffer(this.sdfQuadIbo, 0, new Uint16Array([
1815
+ 0,
1816
+ 1,
1817
+ 2,
1818
+ 0,
1819
+ 2,
1820
+ 3,
1821
+ 0,
1822
+ 0
1823
+ ]));
1824
+ this.sdfInstVbo = dev.createBuffer({
1825
+ size: this.sdfRaw.byteLength,
1826
+ usage: 40
1827
+ });
1828
+ this.samplerLinear = dev.createSampler({
1829
+ magFilter: "linear",
1830
+ minFilter: "linear"
1831
+ });
1832
+ this.samplerNearest = dev.createSampler({
1833
+ magFilter: "nearest",
1834
+ minFilter: "nearest"
1835
+ });
1836
+ this.batchBgl = dev.createBindGroupLayout({ entries: [
1837
+ {
1838
+ binding: 0,
1839
+ visibility: GPUShaderStage_VERTEX,
1840
+ buffer: { type: "uniform" }
1841
+ },
1842
+ {
1843
+ binding: 1,
1844
+ visibility: GPUShaderStage_FRAGMENT,
1845
+ sampler: { type: "filtering" }
1846
+ },
1847
+ {
1848
+ binding: 2,
1849
+ visibility: GPUShaderStage_FRAGMENT,
1850
+ texture: { sampleType: "float" }
1851
+ }
1852
+ ] });
1853
+ this.sdfBgl = dev.createBindGroupLayout({ entries: [{
1854
+ binding: 0,
1855
+ visibility: GPUShaderStage_VERTEX,
1856
+ buffer: { type: "uniform" }
1857
+ }] });
1858
+ this.sdfBindGroup = dev.createBindGroup({
1859
+ layout: this.sdfBgl,
1860
+ entries: [{
1861
+ binding: 0,
1862
+ resource: { buffer: this.globalsBuf }
1863
+ }]
1864
+ });
1865
+ const batchMod = dev.createShaderModule({ code: WGSL_BATCH_SRC });
1866
+ const batchLayout = dev.createPipelineLayout({ bindGroupLayouts: [this.batchBgl] });
1867
+ const sdfMod = dev.createShaderModule({ code: WGSL_SDF_SRC });
1868
+ const sdfLayout = dev.createPipelineLayout({ bindGroupLayouts: [this.sdfBgl] });
1869
+ for (const mode of [
1870
+ BlendModes.NORMAL,
1871
+ BlendModes.ADD,
1872
+ BlendModes.MULTIPLY,
1873
+ BlendModes.SCREEN
1874
+ ]) {
1875
+ this.batchPipelines.set(mode, dev.createRenderPipeline({
1876
+ layout: batchLayout,
1877
+ vertex: {
1878
+ module: batchMod,
1879
+ entryPoint: "vsMain",
1880
+ buffers: [{
1881
+ arrayStride: VERT_STRIDE,
1882
+ attributes: [
1883
+ {
1884
+ shaderLocation: 0,
1885
+ offset: 0,
1886
+ format: "float32x2"
1887
+ },
1888
+ {
1889
+ shaderLocation: 1,
1890
+ offset: 8,
1891
+ format: "float32x2"
1892
+ },
1893
+ {
1894
+ shaderLocation: 2,
1895
+ offset: 16,
1896
+ format: "uint32"
1897
+ },
1898
+ {
1899
+ shaderLocation: 3,
1900
+ offset: 20,
1901
+ format: "float32"
1902
+ }
1903
+ ]
1904
+ }]
1905
+ },
1906
+ fragment: {
1907
+ module: batchMod,
1908
+ entryPoint: "fsMain",
1909
+ targets: [blendTargetState(format, mode)]
1910
+ },
1911
+ primitive: { topology: "triangle-list" }
1912
+ }));
1913
+ this.sdfPipelines.set(mode, dev.createRenderPipeline({
1914
+ layout: sdfLayout,
1915
+ vertex: {
1916
+ module: sdfMod,
1917
+ entryPoint: "vsSdf",
1918
+ buffers: [{
1919
+ arrayStride: 8,
1920
+ stepMode: "vertex",
1921
+ attributes: [{
1922
+ shaderLocation: 0,
1923
+ offset: 0,
1924
+ format: "float32x2"
1925
+ }]
1926
+ }, {
1927
+ arrayStride: SDF_STRIDE,
1928
+ stepMode: "instance",
1929
+ attributes: [
1930
+ {
1931
+ shaderLocation: 1,
1932
+ offset: 0,
1933
+ format: "float32x4"
1934
+ },
1935
+ {
1936
+ shaderLocation: 2,
1937
+ offset: 16,
1938
+ format: "float32x4"
1939
+ },
1940
+ {
1941
+ shaderLocation: 3,
1942
+ offset: 32,
1943
+ format: "float32x4"
1944
+ },
1945
+ {
1946
+ shaderLocation: 4,
1947
+ offset: 48,
1948
+ format: "float32x4"
1949
+ }
1950
+ ]
1951
+ }]
1952
+ },
1953
+ fragment: {
1954
+ module: sdfMod,
1955
+ entryPoint: "fsSdf",
1956
+ targets: [blendTargetState(format, mode)]
1957
+ },
1958
+ primitive: { topology: "triangle-list" }
1959
+ }));
1960
+ }
1961
+ const dummyTex = dev.createTexture({
1962
+ size: [
1963
+ 1,
1964
+ 1,
1965
+ 1
1966
+ ],
1967
+ format: "rgba8unorm",
1968
+ usage: 6
1969
+ });
1970
+ const dummyView = dummyTex.createView();
1971
+ this.dummyEntry = {
1972
+ tex: dummyTex,
1973
+ view: dummyView,
1974
+ width: 1,
1975
+ height: 1,
1976
+ bindGroupLinear: this.makeBatchBindGroup(dummyView, this.samplerLinear),
1977
+ bindGroupNearest: this.makeBatchBindGroup(dummyView, this.samplerNearest)
1978
+ };
1979
+ }
1980
+ makeBatchBindGroup(view, sampler) {
1981
+ return this.device.createBindGroup({
1982
+ layout: this.batchBgl,
1983
+ entries: [
1984
+ {
1985
+ binding: 0,
1986
+ resource: { buffer: this.globalsBuf }
1987
+ },
1988
+ {
1989
+ binding: 1,
1990
+ resource: sampler
1991
+ },
1992
+ {
1993
+ binding: 2,
1994
+ resource: view
1995
+ }
1996
+ ]
1997
+ });
1998
+ }
1999
+ stats() {
2000
+ return { ...this.lastStats };
2001
+ }
2002
+ resize(width, height) {
2003
+ const w = Math.max(1, Math.round(width));
2004
+ const h = Math.max(1, Math.round(height));
2005
+ this.width = w;
2006
+ this.height = h;
2007
+ this.canvas.width = w;
2008
+ this.canvas.height = h;
2009
+ }
2010
+ ensureGpuTexture(keyObj, image, w, h, nearest, dirty) {
2011
+ if (w <= 0 || h <= 0 || !image) return null;
2012
+ let entry = this.texCache.get(keyObj);
2013
+ if (!entry || entry.width !== w || entry.height !== h) {
2014
+ try {
2015
+ entry?.tex?.destroy?.();
2016
+ } catch {}
2017
+ const tex = this.device.createTexture({
2018
+ size: [
2019
+ w,
2020
+ h,
2021
+ 1
2022
+ ],
2023
+ format: "rgba8unorm",
2024
+ usage: 22
2025
+ });
2026
+ const view = tex.createView();
2027
+ entry = {
2028
+ tex,
2029
+ view,
2030
+ width: w,
2031
+ height: h,
2032
+ bindGroupLinear: this.makeBatchBindGroup(view, this.samplerLinear),
2033
+ bindGroupNearest: this.makeBatchBindGroup(view, this.samplerNearest)
2034
+ };
2035
+ this.texCache.set(keyObj, entry);
2036
+ dirty = true;
2037
+ }
2038
+ if (dirty && entry) this.device.queue.copyExternalImageToTexture({ source: image }, {
2039
+ texture: entry.tex,
2040
+ premultipliedAlpha: true
2041
+ }, [w, h]);
2042
+ return nearest ? entry.bindGroupNearest : entry.bindGroupLinear;
2043
+ }
2044
+ ensureSourceBindGroup(src) {
2045
+ const bg = this.ensureGpuTexture(src, src.image, src.width, src.height, src.filterMode === FilterMode.NEAREST, src.dirty);
2046
+ src.dirty = false;
2047
+ return bg;
2048
+ }
2049
+ currentScissor() {
2050
+ return this.scissorStack.length > 0 ? { ...this.scissorStack[this.scissorStack.length - 1] } : null;
2051
+ }
2052
+ flushPendingBatch() {
2053
+ const count = this.indexCount - this.cmdStartIndex;
2054
+ if (count <= 0) return;
2055
+ this.cmds.push({
2056
+ kind: "batch",
2057
+ blend: this.curBlend,
2058
+ bindGroup: this.curBindGroup ?? this.dummyEntry.bindGroupLinear,
2059
+ firstIndex: this.cmdStartIndex,
2060
+ indexCount: count,
2061
+ scissor: this.currentScissor()
2062
+ });
2063
+ this.cmdStartIndex = this.indexCount;
2064
+ }
2065
+ flushPendingSdf() {
2066
+ const count = this.sdfCount - this.sdfCmdStart;
2067
+ if (count <= 0) return;
2068
+ this.cmds.push({
2069
+ kind: "sdf",
2070
+ blend: this.curBlend,
2071
+ firstInstance: this.sdfCmdStart,
2072
+ instanceCount: count,
2073
+ scissor: this.currentScissor()
2074
+ });
2075
+ this.sdfCmdStart = this.sdfCount;
2076
+ }
2077
+ flushAllPending() {
2078
+ this.flushPendingBatch();
2079
+ this.flushPendingSdf();
2080
+ }
2081
+ bindBatch(blend, bindGroup) {
2082
+ if (this.sdfCount > this.sdfCmdStart) this.flushPendingSdf();
2083
+ if (this.curBlend !== blend || this.curBindGroup !== bindGroup && this.indexCount > this.cmdStartIndex) this.flushPendingBatch();
2084
+ this.curBlend = blend;
2085
+ this.curBindGroup = bindGroup;
2086
+ }
2087
+ pushQuad(m, x0, y0, x1, y1, u0, v0, u1, v1, abgr, mode, blend, bindGroup) {
2088
+ if (this.vertCount + 4 > MAX_VERTS || this.indexCount + 6 > MAX_INDICES) return;
2089
+ this.bindBatch(blend, bindGroup);
2090
+ const bv = this.vertCount;
2091
+ let fi = bv * VERT_FLOATS;
2092
+ const f32 = this.f32;
2093
+ const u32 = this.u32;
2094
+ const a = m.a, b = m.b, c = m.c, d = m.d, tx = m.tx, ty = m.ty;
2095
+ f32[fi] = a * x0 + c * y0 + tx;
2096
+ f32[fi + 1] = b * x0 + d * y0 + ty;
2097
+ f32[fi + 2] = u0;
2098
+ f32[fi + 3] = v0;
2099
+ u32[fi + 4] = abgr;
2100
+ f32[fi + 5] = mode;
2101
+ fi += VERT_FLOATS;
2102
+ f32[fi] = a * x1 + c * y0 + tx;
2103
+ f32[fi + 1] = b * x1 + d * y0 + ty;
2104
+ f32[fi + 2] = u1;
2105
+ f32[fi + 3] = v0;
2106
+ u32[fi + 4] = abgr;
2107
+ f32[fi + 5] = mode;
2108
+ fi += VERT_FLOATS;
2109
+ f32[fi] = a * x1 + c * y1 + tx;
2110
+ f32[fi + 1] = b * x1 + d * y1 + ty;
2111
+ f32[fi + 2] = u1;
2112
+ f32[fi + 3] = v1;
2113
+ u32[fi + 4] = abgr;
2114
+ f32[fi + 5] = mode;
2115
+ fi += VERT_FLOATS;
2116
+ f32[fi] = a * x0 + c * y1 + tx;
2117
+ f32[fi + 1] = b * x0 + d * y1 + ty;
2118
+ f32[fi + 2] = u0;
2119
+ f32[fi + 3] = v1;
2120
+ u32[fi + 4] = abgr;
2121
+ f32[fi + 5] = mode;
2122
+ const ii = this.indexCount;
2123
+ const ind = this.indices;
2124
+ ind[ii] = bv;
2125
+ ind[ii + 1] = bv + 1;
2126
+ ind[ii + 2] = bv + 2;
2127
+ ind[ii + 3] = bv;
2128
+ ind[ii + 4] = bv + 2;
2129
+ ind[ii + 5] = bv + 3;
2130
+ this.vertCount = bv + 4;
2131
+ this.indexCount = ii + 6;
2132
+ }
2133
+ pushTri(m, x0, y0, x1, y1, x2, y2, abgr, blend) {
2134
+ if (this.vertCount + 3 > MAX_VERTS || this.indexCount + 3 > MAX_INDICES) return;
2135
+ this.bindBatch(blend, this.dummyEntry.bindGroupLinear);
2136
+ const bv = this.vertCount;
2137
+ let fi = bv * VERT_FLOATS;
2138
+ const f32 = this.f32;
2139
+ const u32 = this.u32;
2140
+ const a = m.a, b = m.b, c = m.c, d = m.d, tx = m.tx, ty = m.ty;
2141
+ f32[fi] = a * x0 + c * y0 + tx;
2142
+ f32[fi + 1] = b * x0 + d * y0 + ty;
2143
+ f32[fi + 2] = 0;
2144
+ f32[fi + 3] = 0;
2145
+ u32[fi + 4] = abgr;
2146
+ f32[fi + 5] = 2;
2147
+ fi += VERT_FLOATS;
2148
+ f32[fi] = a * x1 + c * y1 + tx;
2149
+ f32[fi + 1] = b * x1 + d * y1 + ty;
2150
+ f32[fi + 2] = 0;
2151
+ f32[fi + 3] = 0;
2152
+ u32[fi + 4] = abgr;
2153
+ f32[fi + 5] = 2;
2154
+ fi += VERT_FLOATS;
2155
+ f32[fi] = a * x2 + c * y2 + tx;
2156
+ f32[fi + 1] = b * x2 + d * y2 + ty;
2157
+ f32[fi + 2] = 0;
2158
+ f32[fi + 3] = 0;
2159
+ u32[fi + 4] = abgr;
2160
+ f32[fi + 5] = 2;
2161
+ const ii = this.indexCount;
2162
+ this.indices[ii] = bv;
2163
+ this.indices[ii + 1] = bv + 1;
2164
+ this.indices[ii + 2] = bv + 2;
2165
+ this.vertCount = bv + 3;
2166
+ this.indexCount = ii + 3;
2167
+ }
2168
+ renderPanel(panel, m, alpha) {
2169
+ if (this.sdfCount >= MAX_SDF_PANELS) return;
2170
+ if (this.indexCount > this.cmdStartIndex) this.flushPendingBatch();
2171
+ if (this.curBlend !== panel.blendMode && this.sdfCount > this.sdfCmdStart) this.flushPendingSdf();
2172
+ this.curBlend = panel.blendMode;
2173
+ const w = panel.width;
2174
+ const h = panel.height;
2175
+ if (w <= 0 || h <= 0) return;
2176
+ const ox = panel.displayOriginX;
2177
+ const oy = panel.displayOriginY;
2178
+ const tx = m.a * -ox + m.c * -oy + m.tx;
2179
+ const ty = m.b * -ox + m.d * -oy + m.ty;
2180
+ const maxR = Math.min(w, h) * .5;
2181
+ const base = this.sdfCount * SDF_FLOATS;
2182
+ const f = this.sdfF32;
2183
+ const u = this.sdfU32;
2184
+ f[base] = m.a;
2185
+ f[base + 1] = m.b;
2186
+ f[base + 2] = m.c;
2187
+ f[base + 3] = m.d;
2188
+ f[base + 4] = tx;
2189
+ f[base + 5] = ty;
2190
+ f[base + 6] = w;
2191
+ f[base + 7] = h;
2192
+ f[base + 8] = Math.min(maxR, panel.radiusTL);
2193
+ f[base + 9] = Math.min(maxR, panel.radiusTR);
2194
+ f[base + 10] = Math.min(maxR, panel.radiusBR);
2195
+ f[base + 11] = Math.min(maxR, panel.radiusBL);
2196
+ f[base + 12] = panel.borderWidth;
2197
+ f[base + 13] = panel.pixelStep;
2198
+ u[base + 14] = packColorAbgr(panel.fillColor, panel.fillAlpha * alpha);
2199
+ u[base + 15] = packColorAbgr(panel.borderColor, panel.borderAlpha * alpha);
2200
+ this.sdfCount++;
2201
+ }
2202
+ renderGraphics(g, m, alpha) {
2203
+ const ops = g.ops;
2204
+ const nums = g.nums;
2205
+ let ni = 0;
2206
+ let fillRgb = WHITE_RGB, fillA = 1;
2207
+ let lineW = 1, lineRgb = WHITE_RGB, lineA = 1;
2208
+ const stateStack = [];
2209
+ let px = [];
2210
+ let py = [];
2211
+ const lineSeg = (x0, y0, x1, y1, abgr) => {
2212
+ const dx = x1 - x0, dy = y1 - y0;
2213
+ const len = Math.hypot(dx, dy);
2214
+ if (len < 1e-5) return;
2215
+ const nx = -dy / len * lineW * .5;
2216
+ const ny = dx / len * lineW * .5;
2217
+ this.pushTri(m, x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, abgr, g.blendMode);
2218
+ this.pushTri(m, x0 + nx, y0 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny, abgr, g.blendMode);
2219
+ };
2220
+ for (let oi = 0; oi < g.opLen; oi++) {
2221
+ const op = ops[oi];
2222
+ switch (op) {
2223
+ case 22:
2224
+ stateStack.push(fillRgb, fillA, lineW, lineRgb, lineA);
2225
+ break;
2226
+ case 23:
2227
+ if (stateStack.length >= 5) {
2228
+ lineA = stateStack.pop();
2229
+ lineRgb = stateStack.pop();
2230
+ lineW = stateStack.pop();
2231
+ fillA = stateStack.pop();
2232
+ fillRgb = stateStack.pop();
2233
+ }
2234
+ break;
2235
+ case 1:
2236
+ fillRgb = nums[ni++];
2237
+ fillA = nums[ni++];
2238
+ break;
2239
+ case 2:
2240
+ lineW = nums[ni++];
2241
+ lineRgb = nums[ni++];
2242
+ lineA = nums[ni++];
2243
+ break;
2244
+ case 3:
2245
+ case 5: {
2246
+ const x = nums[ni++], y = nums[ni++], w = nums[ni++], h = nums[ni++];
2247
+ if (op === 5) ni++;
2248
+ if (fillA * alpha > 0) this.pushQuad(m, x, y, x + w, y + h, 0, 0, 1, 1, packColorAbgr(fillRgb, fillA * alpha), 2, g.blendMode, this.dummyEntry.bindGroupLinear);
2249
+ break;
2250
+ }
2251
+ case 4:
2252
+ case 6: {
2253
+ const x = nums[ni++], y = nums[ni++], w = nums[ni++], h = nums[ni++];
2254
+ if (op === 6) ni++;
2255
+ if (lineA * alpha > 0 && lineW > 0) {
2256
+ const abgr = packColorAbgr(lineRgb, lineA * alpha);
2257
+ lineSeg(x, y, x + w, y, abgr);
2258
+ lineSeg(x + w, y, x + w, y + h, abgr);
2259
+ lineSeg(x + w, y + h, x, y + h, abgr);
2260
+ lineSeg(x, y + h, x, y, abgr);
2261
+ }
2262
+ break;
2263
+ }
2264
+ case 7:
2265
+ case 9: {
2266
+ const cx = nums[ni++], cy = nums[ni++];
2267
+ const rx = op === 7 ? nums[ni++] : nums[ni++] * .5;
2268
+ const ry = op === 7 ? rx : nums[ni++] * .5;
2269
+ if (fillA * alpha > 0 && rx > 0 && ry > 0) {
2270
+ const segs = Math.max(12, Math.min(48, Math.ceil(Math.max(rx, ry) * 1.4)));
2271
+ const abgr = packColorAbgr(fillRgb, fillA * alpha);
2272
+ for (let s = 0; s < segs; s++) {
2273
+ const a0 = s / segs * Math.PI * 2;
2274
+ const a1 = (s + 1) / segs * Math.PI * 2;
2275
+ this.pushTri(m, cx, cy, cx + Math.cos(a0) * rx, cy + Math.sin(a0) * ry, cx + Math.cos(a1) * rx, cy + Math.sin(a1) * ry, abgr, g.blendMode);
2276
+ }
2277
+ }
2278
+ break;
2279
+ }
2280
+ case 8:
2281
+ case 10: {
2282
+ const cx = nums[ni++], cy = nums[ni++];
2283
+ const rx = op === 8 ? nums[ni++] : nums[ni++] * .5;
2284
+ const ry = op === 8 ? rx : nums[ni++] * .5;
2285
+ if (lineA * alpha > 0 && lineW > 0 && rx > 0 && ry > 0) {
2286
+ const segs = Math.max(12, Math.min(48, Math.ceil(Math.max(rx, ry) * 1.4)));
2287
+ const abgr = packColorAbgr(lineRgb, lineA * alpha);
2288
+ for (let s = 0; s < segs; s++) {
2289
+ const a0 = s / segs * Math.PI * 2;
2290
+ const a1 = (s + 1) / segs * Math.PI * 2;
2291
+ lineSeg(cx + Math.cos(a0) * rx, cy + Math.sin(a0) * ry, cx + Math.cos(a1) * rx, cy + Math.sin(a1) * ry, abgr);
2292
+ }
2293
+ }
2294
+ break;
2295
+ }
2296
+ case 11: {
2297
+ const x0 = nums[ni++], y0 = nums[ni++], x1 = nums[ni++], y1 = nums[ni++], x2 = nums[ni++], y2 = nums[ni++];
2298
+ if (fillA * alpha > 0) this.pushTri(m, x0, y0, x1, y1, x2, y2, packColorAbgr(fillRgb, fillA * alpha), g.blendMode);
2299
+ break;
2300
+ }
2301
+ case 12: {
2302
+ const x0 = nums[ni++], y0 = nums[ni++], x1 = nums[ni++], y1 = nums[ni++], x2 = nums[ni++], y2 = nums[ni++];
2303
+ if (lineA * alpha > 0 && lineW > 0) {
2304
+ const abgr = packColorAbgr(lineRgb, lineA * alpha);
2305
+ lineSeg(x0, y0, x1, y1, abgr);
2306
+ lineSeg(x1, y1, x2, y2, abgr);
2307
+ lineSeg(x2, y2, x0, y0, abgr);
2308
+ }
2309
+ break;
2310
+ }
2311
+ case 13: {
2312
+ const x0 = nums[ni++], y0 = nums[ni++], x1 = nums[ni++], y1 = nums[ni++];
2313
+ if (lineA * alpha > 0 && lineW > 0) lineSeg(x0, y0, x1, y1, packColorAbgr(lineRgb, lineA * alpha));
2314
+ break;
2315
+ }
2316
+ case 14:
2317
+ px = [];
2318
+ py = [];
2319
+ break;
2320
+ case 15:
2321
+ case 16:
2322
+ px.push(nums[ni++]);
2323
+ py.push(nums[ni++]);
2324
+ break;
2325
+ case 17:
2326
+ case 18: {
2327
+ const cx = nums[ni++], cy = nums[ni++], r = nums[ni++], a0 = nums[ni++], a1 = nums[ni++];
2328
+ ni++;
2329
+ if (op === 18) {
2330
+ px.push(cx);
2331
+ py.push(cy);
2332
+ }
2333
+ const segs = 16;
2334
+ for (let s = 0; s <= segs; s++) {
2335
+ const a = a0 + (a1 - a0) * s / segs;
2336
+ px.push(cx + Math.cos(a) * r);
2337
+ py.push(cy + Math.sin(a) * r);
2338
+ }
2339
+ break;
2340
+ }
2341
+ case 19:
2342
+ if (px.length > 1) {
2343
+ px.push(px[0]);
2344
+ py.push(py[0]);
2345
+ }
2346
+ break;
2347
+ case 20:
2348
+ if (fillA * alpha > 0 && px.length >= 3) {
2349
+ const abgr = packColorAbgr(fillRgb, fillA * alpha);
2350
+ for (let i = 1; i < px.length - 1; i++) this.pushTri(m, px[0], py[0], px[i], py[i], px[i + 1], py[i + 1], abgr, g.blendMode);
2351
+ }
2352
+ break;
2353
+ case 21: if (lineA * alpha > 0 && lineW > 0 && px.length >= 2) {
2354
+ const abgr = packColorAbgr(lineRgb, lineA * alpha);
2355
+ for (let i = 0; i < px.length - 1; i++) lineSeg(px[i], py[i], px[i + 1], py[i + 1], abgr);
2356
+ }
2357
+ }
2358
+ }
2359
+ }
2360
+ renderNode(obj, camera, parentMat, parentAlpha, depth) {
2361
+ if (!obj.visible || obj.alpha <= 0) return;
2362
+ const effAlpha = parentAlpha * obj.alpha;
2363
+ if (effAlpha <= 0) return;
2364
+ let baseMat = parentMat;
2365
+ if (!baseMat) {
2366
+ if (obj.scrollFactorX === 1 && obj.scrollFactorY === 1) baseMat = camera.matrixCombined;
2367
+ else {
2368
+ const z = camera.zoom || 1;
2369
+ const ox = camera.width * camera.originX;
2370
+ const oy = camera.height * camera.originY;
2371
+ const sx = camera.roundPixels ? Math.round(camera.scrollX) : camera.scrollX;
2372
+ const sy = camera.roundPixels ? Math.round(camera.scrollY) : camera.scrollY;
2373
+ const sm = this.sfMat;
2374
+ sm.a = z;
2375
+ sm.b = 0;
2376
+ sm.c = 0;
2377
+ sm.d = z;
2378
+ sm.tx = (-sx * obj.scrollFactorX - ox) * z + ox + camera.x;
2379
+ sm.ty = (-sy * obj.scrollFactorY - oy) * z + oy + camera.y;
2380
+ baseMat = sm;
2381
+ }
2382
+ }
2383
+ let m;
2384
+ if (obj.x === 0 && obj.y === 0 && obj.scaleX === 1 && obj.scaleY === 1 && obj.rotation === 0) m = baseMat;
2385
+ else {
2386
+ if (depth >= this.matPool.length) this.matPool.push(createMatrix2D());
2387
+ m = multiplyMat(baseMat, obj.x, obj.y, obj.scaleX, obj.scaleY, obj.rotation, this.matPool[depth]);
2388
+ }
2389
+ switch (obj.type) {
2390
+ case "Image": {
2391
+ const img = obj;
2392
+ const fr = img.frame;
2393
+ if (!fr || fr.width <= 0 || fr.height <= 0) break;
2394
+ const bg = this.ensureSourceBindGroup(fr.source);
2395
+ if (!bg) break;
2396
+ const ox = img.displayOriginX, oy = img.displayOriginY;
2397
+ const u0 = img.flipX ? fr.u1 : fr.u0, u1 = img.flipX ? fr.u0 : fr.u1;
2398
+ const v0 = img.flipY ? fr.v1 : fr.v0, v1 = img.flipY ? fr.v0 : fr.v1;
2399
+ const rgb = img.isTinted ? img.tint : WHITE_RGB;
2400
+ const mode = img.isTinted && img.tintMode === TintModes.FILL ? 1 : 0;
2401
+ this.pushQuad(m, -ox, -oy, img.width - ox, img.height - oy, u0, v0, u1, v1, packColorAbgr(rgb, effAlpha), mode, img.blendMode, bg);
2402
+ break;
2403
+ }
2404
+ case "Rectangle": {
2405
+ const r = obj;
2406
+ if (r.isFilled && r.fillAlpha * effAlpha > 0) {
2407
+ const ox = r.displayOriginX, oy = r.displayOriginY;
2408
+ this.pushQuad(m, -ox, -oy, r.width - ox, r.height - oy, 0, 0, 1, 1, packColorAbgr(r.fillColor, r.fillAlpha * effAlpha), 2, r.blendMode, this.dummyEntry.bindGroupLinear);
2409
+ }
2410
+ break;
2411
+ }
2412
+ case "Panel":
2413
+ this.renderPanel(obj, m, effAlpha);
2414
+ break;
2415
+ case "Text": {
2416
+ const txt = obj;
2417
+ const cv = txt.ensureCanvas();
2418
+ if (!cv || cv.width <= 0 || cv.height <= 0) break;
2419
+ const prevRev = txt._wgpuRev ?? -1;
2420
+ const curRev = txt.canvasDirty ? -2 : txt._wgpuSeq ?? 0;
2421
+ const dirty = prevRev !== curRev || txt.glDirty;
2422
+ const bg = this.ensureGpuTexture(txt, cv, cv.width, cv.height, false, dirty);
2423
+ txt.glDirty = false;
2424
+ txt._wgpuRev = curRev;
2425
+ if (!bg) break;
2426
+ const ox = txt.displayOriginX, oy = txt.displayOriginY;
2427
+ const rgb = txt.isTinted ? txt.tint : WHITE_RGB;
2428
+ this.pushQuad(m, -ox, -oy, txt.width - ox, txt.height - oy, 0, 0, 1, 1, packColorAbgr(rgb, effAlpha), 0, txt.blendMode, bg);
2429
+ break;
2430
+ }
2431
+ case "NineSlice":
2432
+ case "TileSprite": {
2433
+ const ns = obj;
2434
+ const fr = ns.frame;
2435
+ if (!fr) break;
2436
+ const bg = this.ensureSourceBindGroup(fr.source);
2437
+ if (!bg) break;
2438
+ const ox = ns.displayOriginX, oy = ns.displayOriginY;
2439
+ this.pushQuad(m, -ox, -oy, ns.width - ox, ns.height - oy, fr.u0, fr.v0, fr.u1, fr.v1, packColorAbgr(ns.isTinted ? ns.tint : WHITE_RGB, effAlpha), 0, ns.blendMode, bg);
2440
+ break;
2441
+ }
2442
+ case "Graphics":
2443
+ this.renderGraphics(obj, m, effAlpha);
2444
+ break;
2445
+ case "Blitter": {
2446
+ const blitter = obj;
2447
+ const list = blitter.children.list;
2448
+ for (let i = 0; i < list.length; i++) {
2449
+ const bob = list[i];
2450
+ if (!bob.visible || bob.alpha <= 0) continue;
2451
+ const fr = bob.frame;
2452
+ const bg = this.ensureSourceBindGroup(fr.source);
2453
+ if (!bg) continue;
2454
+ this.pushQuad(m, bob.x, bob.y, bob.x + fr.width, bob.y + fr.height, fr.u0, fr.v0, fr.u1, fr.v1, packColorAbgr(WHITE_RGB, effAlpha * bob.alpha), 0, blitter.blendMode, bg);
2455
+ }
2456
+ break;
2457
+ }
2458
+ case "InstancedBatch": {
2459
+ const batch = obj;
2460
+ const cols = batch.columns;
2461
+ if (!cols || cols.count <= 0) break;
2462
+ const src = batch.texture?.source?.[0];
2463
+ if (!src) break;
2464
+ const bg = this.ensureSourceBindGroup(src);
2465
+ if (!bg) break;
2466
+ const n = Math.min(cols.count, batch.maxCount, cols.x.length, cols.y.length);
2467
+ for (let i = 0; i < n; i++) {
2468
+ const s = cols.order ? cols.order[i] : i;
2469
+ const a = effAlpha * (cols.alpha ? cols.alpha[s] : 1);
2470
+ if (a <= 0) continue;
2471
+ const fr = cols.frameIndex ? batch.texture.get(cols.frameIndex[s]) : batch.defaultFrame;
2472
+ const sx = cols.scaleX ? cols.scaleX[s] : 1;
2473
+ const sy = cols.scaleY ? cols.scaleY[s] : sx;
2474
+ const rot = cols.rotation ? cols.rotation[s] : 0;
2475
+ const im = depth + 1 >= this.matPool.length ? createMatrix2D() : this.matPool[depth + 1];
2476
+ multiplyMat(m, cols.x[s], cols.y[s], sx, sy, rot, im);
2477
+ const ox = fr.width * batch.originX, oy = fr.height * batch.originY;
2478
+ const rgb = cols.tint ? cols.tint[s] : WHITE_RGB;
2479
+ this.pushQuad(im, -ox, -oy, fr.width - ox, fr.height - oy, fr.u0, fr.v0, fr.u1, fr.v1, packColorAbgr(rgb, a), 0, batch.blendMode, bg);
2480
+ }
2481
+ break;
2482
+ }
2483
+ case "Container": {
2484
+ const cont = obj;
2485
+ const mask = cont.clipMask;
2486
+ let clipped = false;
2487
+ if (mask && mask.active && mask.graphics?.maskRect) {
2488
+ this.flushAllPending();
2489
+ const mr = mask.graphics.maskRect;
2490
+ const mw = mask.graphics.getWorldTransformMatrix(this.maskWorldMat);
2491
+ const cm = camera.matrixCombined;
2492
+ const wx0 = mw.a * mr.x + mw.c * mr.y + mw.tx;
2493
+ const wy0 = mw.b * mr.x + mw.d * mr.y + mw.ty;
2494
+ const wx1 = mw.a * (mr.x + mr.w) + mw.c * (mr.y + mr.h) + mw.tx;
2495
+ const wy1 = mw.b * (mr.x + mr.w) + mw.d * (mr.y + mr.h) + mw.ty;
2496
+ const sx0 = cm.a * wx0 + cm.c * wy0 + cm.tx;
2497
+ const sy0 = cm.b * wx0 + cm.d * wy0 + cm.ty;
2498
+ const sx1 = cm.a * wx1 + cm.c * wy1 + cm.tx;
2499
+ const sy1 = cm.b * wx1 + cm.d * wy1 + cm.ty;
2500
+ const l = Math.max(0, Math.floor(Math.min(sx0, sx1)));
2501
+ const t = Math.max(0, Math.floor(Math.min(sy0, sy1)));
2502
+ const r = Math.min(this.width, Math.ceil(Math.max(sx0, sx1)));
2503
+ const b = Math.min(this.height, Math.ceil(Math.max(sy0, sy1)));
2504
+ this.scissorStack.push({
2505
+ x: l,
2506
+ y: t,
2507
+ w: Math.max(0, r - l),
2508
+ h: Math.max(0, b - t)
2509
+ });
2510
+ clipped = true;
2511
+ }
2512
+ const children = cont.sortedChildren();
2513
+ for (let i = 0; i < children.length; i++) this.renderNode(children[i], camera, m, effAlpha, depth + 1);
2514
+ if (clipped) {
2515
+ this.flushAllPending();
2516
+ this.scissorStack.pop();
2517
+ }
2518
+ break;
2519
+ }
2520
+ case "CustomPass": {
2521
+ this.flushAllPending();
2522
+ const pass = obj;
2523
+ pass.onRender(pass, this, camera);
2524
+ break;
2525
+ }
2526
+ }
2527
+ }
2528
+ render(displayList, camera) {
2529
+ camera.syncMetrics();
2530
+ this.vertCount = 0;
2531
+ this.indexCount = 0;
2532
+ this.cmdStartIndex = 0;
2533
+ this.sdfCount = 0;
2534
+ this.sdfCmdStart = 0;
2535
+ this.cmds.length = 0;
2536
+ this.scissorStack.length = 0;
2537
+ this.curBlend = BlendModes.NORMAL;
2538
+ this.curBindGroup = null;
2539
+ const list = displayList.sorted();
2540
+ const camAlpha = camera.alpha;
2541
+ for (let i = 0; i < list.length; i++) this.renderNode(list[i], camera, null, camAlpha, 0);
2542
+ this.flushAllPending();
2543
+ this.device.queue.writeBuffer(this.globalsBuf, 0, new Float32Array([
2544
+ this.width,
2545
+ this.height,
2546
+ 0,
2547
+ 0
2548
+ ]));
2549
+ if (this.vertCount > 0) {
2550
+ this.device.queue.writeBuffer(this.vbo, 0, this.f32.subarray(0, this.vertCount * VERT_FLOATS));
2551
+ this.device.queue.writeBuffer(this.ibo, 0, this.indices.subarray(0, this.indexCount));
2552
+ }
2553
+ if (this.sdfCount > 0) this.device.queue.writeBuffer(this.sdfInstVbo, 0, this.sdfF32.subarray(0, this.sdfCount * SDF_FLOATS));
2554
+ const bg = camera.backgroundColor;
2555
+ const clearColor = camera.transparent ? {
2556
+ r: 0,
2557
+ g: 0,
2558
+ b: 0,
2559
+ a: 0
2560
+ } : {
2561
+ r: bg.r * bg.a,
2562
+ g: bg.g * bg.a,
2563
+ b: bg.b * bg.a,
2564
+ a: bg.a
2565
+ };
2566
+ const view = this.gpuContext.getCurrentTexture().createView();
2567
+ const encoder = this.device.createCommandEncoder();
2568
+ const pass = encoder.beginRenderPass({ colorAttachments: [{
2569
+ view,
2570
+ clearValue: clearColor,
2571
+ loadOp: "clear",
2572
+ storeOp: "store"
2573
+ }] });
2574
+ let sdfDraws = 0;
2575
+ for (let i = 0; i < this.cmds.length; i++) {
2576
+ const cmd = this.cmds[i];
2577
+ if (cmd.scissor) {
2578
+ if (cmd.scissor.w <= 0 || cmd.scissor.h <= 0) continue;
2579
+ pass.setScissorRect(cmd.scissor.x, cmd.scissor.y, cmd.scissor.w, cmd.scissor.h);
2580
+ } else pass.setScissorRect(0, 0, this.width, this.height);
2581
+ if (cmd.kind === "batch") {
2582
+ pass.setPipeline(this.batchPipelines.get(cmd.blend) ?? this.batchPipelines.get(BlendModes.NORMAL));
2583
+ pass.setBindGroup(0, cmd.bindGroup);
2584
+ pass.setVertexBuffer(0, this.vbo);
2585
+ pass.setIndexBuffer(this.ibo, "uint16");
2586
+ pass.drawIndexed(cmd.indexCount, 1, cmd.firstIndex, 0, 0);
2587
+ } else {
2588
+ sdfDraws++;
2589
+ pass.setPipeline(this.sdfPipelines.get(cmd.blend) ?? this.sdfPipelines.get(BlendModes.NORMAL));
2590
+ pass.setBindGroup(0, this.sdfBindGroup);
2591
+ pass.setVertexBuffer(0, this.sdfCornerVbo);
2592
+ pass.setVertexBuffer(1, this.sdfInstVbo);
2593
+ pass.setIndexBuffer(this.sdfQuadIbo, "uint16");
2594
+ pass.drawIndexed(6, cmd.instanceCount, 0, 0, cmd.firstInstance);
2595
+ }
2596
+ }
2597
+ pass.end();
2598
+ this.device.queue.submit([encoder.finish()]);
2599
+ this.lastStats.drawCalls = this.cmds.length;
2600
+ this.lastStats.flushes = this.cmds.length;
2601
+ this.lastStats.tris = (this.indexCount / 3 | 0) + this.sdfCount * 2;
2602
+ this.lastStats.quads = (this.vertCount >> 2) + this.sdfCount;
2603
+ this.lastStats.sdfPanels = this.sdfCount;
2604
+ this.lastStats.sdfDraws = sdfDraws;
2605
+ }
2606
+ destroy() {
2607
+ this.removeAllListeners();
2608
+ try {
2609
+ this.globalsBuf?.destroy?.();
2610
+ this.vbo?.destroy?.();
2611
+ this.ibo?.destroy?.();
2612
+ this.sdfCornerVbo?.destroy?.();
2613
+ this.sdfInstVbo?.destroy?.();
2614
+ this.sdfQuadIbo?.destroy?.();
2615
+ this.dummyEntry?.tex?.destroy?.();
2616
+ } catch {}
2617
+ }
2618
+ };
2619
+ export { CustomPassObject as a, Graphics as c, MsdfIconObject as d, NineSliceObject as f, TileSpriteObject as g, TextObject as h, Container as i, ImageObject as l, RectangleObject as m, requestWebGpuDevice as n, DisplayList as o, PanelObject as p, BlitterObject as r, DisplayObject as s, RendererWebGpu as t, InstancedBatchObject as u };