@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.
@@ -1,5 +1,7 @@
1
- import { a as EventEmitter, f as WHITE_RGB, g as rgbToCss, h as parseColor, l as Scenes, m as packColorAbgr, o as FilterMode, p as createMatrix2D, r as BlendModes, s as HEX_MASK, u as TintModes } from "./types-ChGhuDNX.js";
1
+ import { _ as rgbToCss, a as EventEmitter, g as parseColor, h as packColorAbgr, l as Scenes, m as createMatrix2D, o as FilterMode, p as WHITE_RGB, r as BlendModes, u as TintModes } from "./types-DRFB0Klc.js";
2
+ import { a as CustomPassObject, c as Graphics, d as MsdfIconObject, f as NineSliceObject, g as TileSpriteObject, h as TextObject, i as Container, l as ImageObject, m as RectangleObject, o as DisplayList, p as PanelObject, r as BlitterObject, t as RendererWebGpu, u as InstancedBatchObject } from "./renderer-webgpu-BorAD6Kk.js";
2
3
  import { TweenManager } from "./tween.js";
4
+ import { StageKernel } from "./kernel.js";
3
5
  // src/texture.ts
4
6
  var TextureSource = class {
5
7
  texture;
@@ -304,6 +306,13 @@ var Camera = class {
304
306
  bottom: 0
305
307
  };
306
308
  matrixCombined = createMatrix2D();
309
+ followTarget = null;
310
+ followLerpX = 1;
311
+ followLerpY = 1;
312
+ followOffsetX = 0;
313
+ followOffsetY = 0;
314
+ deadzoneW = 0;
315
+ deadzoneH = 0;
307
316
  constructor(width, height, transparent = false, backgroundColor) {
308
317
  this.width = Math.max(1, width);
309
318
  this.height = Math.max(1, height);
@@ -412,6 +421,90 @@ var Camera = class {
412
421
  const oy = this.height * this.originY;
413
422
  return this.setScroll(x - ox, y - oy);
414
423
  }
424
+ /**
425
+ * One-line HiDPI camera + backing-buffer configurator: maps logical `(0, 0)..(viewportW, viewportH)`
426
+ * 1:1 onto crisp physical `viewportW * dpr` pixels without copy-pasting origin/scroll math.
427
+ * Returns the clamped `dpr` applied.
428
+ */
429
+ configureHiDpi(scale, viewportWidth, viewportHeight, dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1, maxDpr = 2) {
430
+ const safeDpr = Math.min(Math.max(1, maxDpr), Math.max(1, Number.isFinite(dpr) ? dpr : 1));
431
+ const vw = Math.max(1, Math.round(viewportWidth));
432
+ const vh = Math.max(1, Math.round(viewportHeight));
433
+ scale.zoom = 1 / safeDpr;
434
+ scale.resize(Math.round(vw * safeDpr), Math.round(vh * safeDpr));
435
+ if (scale.canvas?.style) {
436
+ scale.canvas.style.width = `${vw}px`;
437
+ scale.canvas.style.height = `${vh}px`;
438
+ }
439
+ const ox = this.width * this.originX;
440
+ const oy = this.height * this.originY;
441
+ this.setZoom(safeDpr);
442
+ this.setScroll(ox / safeDpr - ox, oy / safeDpr - oy);
443
+ return safeDpr;
444
+ }
445
+ /** Convert canvas/backing-buffer coordinates `(screenX, screenY)` into world coordinates. */
446
+ screenToWorld(screenX, screenY, out = {
447
+ x: 0,
448
+ y: 0
449
+ }) {
450
+ const m = this.matrixCombined;
451
+ out.x = (screenX - m.tx) / (m.a || 1);
452
+ out.y = (screenY - m.ty) / (m.d || 1);
453
+ return out;
454
+ }
455
+ /** Convert world coordinates `(worldX, worldY)` into canvas/backing-buffer coordinates. */
456
+ worldToScreen(worldX, worldY, out = {
457
+ x: 0,
458
+ y: 0
459
+ }) {
460
+ const m = this.matrixCombined;
461
+ out.x = worldX * m.a + m.tx;
462
+ out.y = worldY * m.d + m.ty;
463
+ return out;
464
+ }
465
+ /** Lock or smoothly follow any `{ x, y }` actor/point (frame-rate independent lerp + optional deadzone). */
466
+ startFollow(target, options = {}) {
467
+ this.followTarget = target;
468
+ this.followLerpX = Math.max(.001, Math.min(1, options.lerpX ?? 1));
469
+ this.followLerpY = Math.max(.001, Math.min(1, options.lerpY ?? this.followLerpX));
470
+ this.followOffsetX = options.offsetX ?? 0;
471
+ this.followOffsetY = options.offsetY ?? 0;
472
+ this.deadzoneW = Math.max(0, options.deadzoneWidth ?? 0);
473
+ this.deadzoneH = Math.max(0, options.deadzoneHeight ?? 0);
474
+ return this;
475
+ }
476
+ stopFollow() {
477
+ this.followTarget = null;
478
+ return this;
479
+ }
480
+ /** Internal per-step follow update invoked automatically by `Game.step()` before rendering. */
481
+ stepFollow(deltaMs) {
482
+ const target = this.followTarget;
483
+ if (!target) return;
484
+ const tx = target.x + this.followOffsetX;
485
+ const ty = target.y + this.followOffsetY;
486
+ const curCx = this.worldView.x + this.worldView.width * .5;
487
+ const curCy = this.worldView.y + this.worldView.height * .5;
488
+ let wantCx = curCx;
489
+ let wantCy = curCy;
490
+ const halfDzW = this.deadzoneW * .5;
491
+ const halfDzH = this.deadzoneH * .5;
492
+ if (tx < curCx - halfDzW) wantCx = tx + halfDzW;
493
+ else if (tx > curCx + halfDzW) wantCx = tx - halfDzW;
494
+ if (ty < curCy - halfDzH) wantCy = ty + halfDzH;
495
+ else if (ty > curCy + halfDzH) wantCy = ty - halfDzH;
496
+ const frames = Math.max(.1, deltaMs / (1e3 / 60));
497
+ const ax = this.followLerpX >= 1 ? 1 : 1 - Math.pow(1 - this.followLerpX, frames);
498
+ const ay = this.followLerpY >= 1 ? 1 : 1 - Math.pow(1 - this.followLerpY, frames);
499
+ const nextCx = curCx + (wantCx - curCx) * ax;
500
+ const nextCy = curCy + (wantCy - curCy) * ay;
501
+ const ox = this.width * this.originX;
502
+ const oy = this.height * this.originY;
503
+ const z = this.zoom || 1;
504
+ const nextSx = nextCx - this.worldView.width * .5 - ox + ox / z;
505
+ const nextSy = nextCy - this.worldView.height * .5 - oy + oy / z;
506
+ this.setScroll(nextSx, nextSy);
507
+ }
415
508
  /** Recompute `worldView` and world->canvas `matrixCombined`. */
416
509
  syncMetrics() {
417
510
  const z = this.zoom || 1;
@@ -440,1394 +533,6 @@ var Camera = class {
440
533
  m.scaleY = z;
441
534
  }
442
535
  };
443
- // src/display.ts
444
- var DisplayList = class {
445
- list = [];
446
- depthDirty = false;
447
- add(obj) {
448
- if (obj.parentContainer) obj.parentContainer.remove(obj);
449
- if (this.list.indexOf(obj) < 0) {
450
- this.list.push(obj);
451
- this.depthDirty = true;
452
- }
453
- }
454
- remove(obj) {
455
- const i = this.list.indexOf(obj);
456
- if (i >= 0) this.list.splice(i, 1);
457
- }
458
- markDepthDirty() {
459
- this.depthDirty = true;
460
- }
461
- sorted() {
462
- if (this.depthDirty) {
463
- this.depthDirty = false;
464
- this.list.sort((a, b) => a.depth - b.depth);
465
- }
466
- return this.list;
467
- }
468
- clear() {
469
- this.list.length = 0;
470
- this.depthDirty = false;
471
- }
472
- };
473
- var DisplayObject = class extends EventEmitter {
474
- scene;
475
- type;
476
- active = true;
477
- visible = true;
478
- x = 0;
479
- y = 0;
480
- scaleX = 1;
481
- scaleY = 1;
482
- rotation = 0;
483
- alpha = 1;
484
- depth = 0;
485
- zIndex = 0;
486
- trackId = null;
487
- alt = null;
488
- role = null;
489
- surface = null;
490
- originX = .5;
491
- originY = .5;
492
- width = 0;
493
- height = 0;
494
- flipX = false;
495
- flipY = false;
496
- blendMode = BlendModes.NORMAL;
497
- scrollFactorX = 1;
498
- scrollFactorY = 1;
499
- parentContainer = null;
500
- customOrigin = false;
501
- _displayOriginX = 0;
502
- _displayOriginY = 0;
503
- disposers = null;
504
- constructor(scene, type) {
505
- super();
506
- this.scene = scene;
507
- this.type = type;
508
- scene._trackNodeCreated?.();
509
- }
510
- /** Number of pending LIFO teardown callbacks registered on this node via `onDispose()`. */
511
- get disposerCount() {
512
- return this.disposers ? this.disposers.length : 0;
513
- }
514
- /**
515
- * Register a cleanup callback (signal unsubscribe, timer/listener removal, texture ref release) that automatically
516
- * runs in strict LIFO order with error isolation when this node or any ancestor `Container` is destroyed.
517
- */
518
- onDispose(fn) {
519
- if (!this.active) {
520
- try {
521
- fn();
522
- } catch (err) {
523
- this.scene._trackDisposerError?.(err);
524
- }
525
- return () => {};
526
- }
527
- (this.disposers ?? (this.disposers = [])).push(fn);
528
- let cancelled = false;
529
- return () => {
530
- if (cancelled || !this.disposers) return;
531
- cancelled = true;
532
- const idx = this.disposers.lastIndexOf(fn);
533
- if (idx >= 0) this.disposers.splice(idx, 1);
534
- };
535
- }
536
- get displayOriginX() {
537
- return this.customOrigin ? this._displayOriginX : this.width * this.originX;
538
- }
539
- get displayOriginY() {
540
- return this.customOrigin ? this._displayOriginY : this.height * this.originY;
541
- }
542
- get displayWidth() {
543
- return Math.abs(this.width * this.scaleX);
544
- }
545
- get displayHeight() {
546
- return Math.abs(this.height * this.scaleY);
547
- }
548
- setPosition(x, y = x) {
549
- this.x = x;
550
- this.y = y;
551
- return this;
552
- }
553
- setScale(sx, sy = sx) {
554
- this.scaleX = sx;
555
- this.scaleY = sy;
556
- return this;
557
- }
558
- setRotation(rad) {
559
- this.rotation = rad;
560
- return this;
561
- }
562
- setAngle(deg) {
563
- this.rotation = deg * Math.PI / 180;
564
- return this;
565
- }
566
- setAlpha(a) {
567
- this.alpha = a;
568
- return this;
569
- }
570
- setDepth(d) {
571
- if (this.depth !== d) {
572
- this.depth = d;
573
- if (!this.parentContainer) this.scene._displayList.markDepthDirty();
574
- }
575
- return this;
576
- }
577
- /** Native container-local stacking order (0 by default; sorted stably when any sibling has non-zero zIndex). */
578
- setZIndex(z) {
579
- if (this.zIndex !== z) {
580
- this.zIndex = z;
581
- if (this.parentContainer) this.parentContainer._markZDirty(z !== 0);
582
- else this.setDepth(z);
583
- }
584
- return this;
585
- }
586
- /** Attach a stable, privacy-safe telemetry/automation identifier (never user text or PII). */
587
- setTrackId(id) {
588
- this.trackId = id;
589
- return this;
590
- }
591
- /** Attach a concise semantic description for accessibility mirrors and scene snapshots. */
592
- setAlt(alt) {
593
- this.alt = alt;
594
- return this;
595
- }
596
- /** Attach a semantic role token (e.g. `button`, `toggle`, `panel`, `tab`, `canvas-entity`). */
597
- setRole(role) {
598
- this.role = role;
599
- return this;
600
- }
601
- /** Attach an owning surface/panel identifier (e.g. `hud`, `settings`, `poker`). */
602
- setSurface(surface) {
603
- this.surface = surface;
604
- return this;
605
- }
606
- /** Batch-assign semantic metadata (`trackId`, `alt`, `role`, `surface`) on this scene-graph node. */
607
- setSemantics(s) {
608
- if (s.trackId !== void 0) this.trackId = s.trackId;
609
- if (s.alt !== void 0) this.alt = s.alt;
610
- if (s.role !== void 0) this.role = s.role;
611
- if (s.surface !== void 0) this.surface = s.surface;
612
- return this;
613
- }
614
- setVisible(v) {
615
- this.visible = Boolean(v);
616
- return this;
617
- }
618
- setOrigin(ox = .5, oy = ox) {
619
- this.originX = ox;
620
- this.originY = oy;
621
- this.customOrigin = false;
622
- this._displayOriginX = this.width * ox;
623
- this._displayOriginY = this.height * oy;
624
- return this;
625
- }
626
- setDisplayOrigin(dx, dy = dx) {
627
- this.customOrigin = true;
628
- this._displayOriginX = dx;
629
- this._displayOriginY = dy;
630
- this.originX = this.width ? dx / this.width : 0;
631
- this.originY = this.height ? dy / this.height : 0;
632
- return this;
633
- }
634
- setDisplaySize(w, h) {
635
- this.scaleX = this.width ? w / this.width : 1;
636
- this.scaleY = this.height ? h / this.height : 1;
637
- return this;
638
- }
639
- setSize(w, h) {
640
- this.width = w;
641
- this.height = h;
642
- if (!this.customOrigin) {
643
- this._displayOriginX = w * this.originX;
644
- this._displayOriginY = h * this.originY;
645
- }
646
- return this;
647
- }
648
- setFlipX(b) {
649
- this.flipX = !!b;
650
- return this;
651
- }
652
- setFlipY(b) {
653
- this.flipY = !!b;
654
- return this;
655
- }
656
- setBlendMode(mode) {
657
- this.blendMode = mode;
658
- return this;
659
- }
660
- setScrollFactor(x, y = x) {
661
- this.scrollFactorX = x;
662
- this.scrollFactorY = y;
663
- return this;
664
- }
665
- removeFromDisplayList() {
666
- if (this.parentContainer) this.parentContainer.remove(this);
667
- else this.scene._displayList.remove(this);
668
- return this;
669
- }
670
- /** Compute world-space affine transform matrix (matching Phaser's `getWorldTransformMatrix`). */
671
- getWorldTransformMatrix(out = createMatrix2D(), _temp) {
672
- const chain = [];
673
- for (let cur = this; cur; cur = cur.parentContainer) chain.push(cur);
674
- let a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0;
675
- for (let i = chain.length - 1; i >= 0; i--) {
676
- const n = chain[i];
677
- const sx = n.scaleX, sy = n.scaleY, r = n.rotation;
678
- let la, lb, lc, ld;
679
- if (r === 0) {
680
- la = sx;
681
- lb = 0;
682
- lc = 0;
683
- ld = sy;
684
- } else {
685
- const cs = Math.cos(r), sn = Math.sin(r);
686
- la = cs * sx;
687
- lb = sn * sx;
688
- lc = -sn * sy;
689
- ld = cs * sy;
690
- }
691
- const na = a * la + c * lb;
692
- const nb = b * la + d * lb;
693
- const nc = a * lc + c * ld;
694
- const nd = b * lc + d * ld;
695
- const ntx = a * n.x + c * n.y + tx;
696
- const nty = b * n.x + d * n.y + ty;
697
- a = na;
698
- b = nb;
699
- c = nc;
700
- d = nd;
701
- tx = ntx;
702
- ty = nty;
703
- }
704
- out.a = a;
705
- out.b = b;
706
- out.c = c;
707
- out.d = d;
708
- out.tx = tx;
709
- out.ty = ty;
710
- out.scaleX = Math.hypot(a, b);
711
- out.scaleY = Math.hypot(c, d);
712
- return out;
713
- }
714
- /** World-space axis-aligned bounding box. */
715
- getBounds() {
716
- const m = this.getWorldTransformMatrix();
717
- const ox = this.displayOriginX, oy = this.displayOriginY;
718
- const x0 = -ox, y0 = -oy, x1 = this.width - ox, y1 = this.height - oy;
719
- const px0 = m.a * x0 + m.c * y0 + m.tx, py0 = m.b * x0 + m.d * y0 + m.ty;
720
- const px1 = m.a * x1 + m.c * y0 + m.tx, py1 = m.b * x1 + m.d * y0 + m.ty;
721
- const px2 = m.a * x1 + m.c * y1 + m.tx, py2 = m.b * x1 + m.d * y1 + m.ty;
722
- const px3 = m.a * x0 + m.c * y1 + m.tx, py3 = m.b * x0 + m.d * y1 + m.ty;
723
- const left = Math.min(px0, px1, px2, px3);
724
- const right = Math.max(px0, px1, px2, px3);
725
- const top = Math.min(py0, py1, py2, py3);
726
- const bottom = Math.max(py0, py1, py2, py3);
727
- return {
728
- x: left,
729
- y: top,
730
- width: right - left,
731
- height: bottom - top,
732
- left,
733
- right,
734
- top,
735
- bottom
736
- };
737
- }
738
- destroy(_fromScene) {
739
- if (!this.active) return;
740
- this.active = false;
741
- this.visible = false;
742
- const list = this.disposers;
743
- this.disposers = null;
744
- if (list && list.length > 0) {
745
- for (let i = list.length - 1; i >= 0; i--) try {
746
- list[i]();
747
- this.scene._trackDisposerRan?.();
748
- } catch (err) {
749
- this.scene._trackDisposerError?.(err);
750
- }
751
- list.length = 0;
752
- }
753
- this.scene._trackNodeDestroyed?.();
754
- this.emit("destroy", this);
755
- this.removeAllListeners();
756
- this.removeFromDisplayList();
757
- }
758
- };
759
- var ImageObject = class extends DisplayObject {
760
- texture;
761
- frame;
762
- tint = WHITE_RGB;
763
- isTinted = false;
764
- tintMode = TintModes.MULTIPLY;
765
- /** Enable GPU Sharp-Bilinear Pixel-Art AA (crisp square pixels at integer scales, uniform strokes at non-integer scales). */
766
- pixelAA = false;
767
- isCropped = false;
768
- cropX = 0;
769
- cropY = 0;
770
- cropW = 0;
771
- cropH = 0;
772
- customRenderNodes = {};
773
- constructor(scene, x, y, key, frame) {
774
- super(scene, "Image");
775
- this.x = x;
776
- this.y = y;
777
- this.texture = scene.textures.get(key);
778
- this.frame = this.texture.get(frame);
779
- this.width = this.frame.width;
780
- this.height = this.frame.height;
781
- this._displayOriginX = this.width * this.originX;
782
- this._displayOriginY = this.height * this.originY;
783
- }
784
- setTexture(key, frame) {
785
- this.texture = this.scene.textures.get(key);
786
- return this.setFrame(frame ?? "__BASE");
787
- }
788
- setFrame(frame) {
789
- this.frame = this.texture.get(frame);
790
- this.width = this.frame.width;
791
- this.height = this.frame.height;
792
- if (!this.customOrigin) {
793
- this._displayOriginX = this.width * this.originX;
794
- this._displayOriginY = this.height * this.originY;
795
- }
796
- return this;
797
- }
798
- setTint(color) {
799
- this.tint = color & HEX_MASK;
800
- this.isTinted = true;
801
- return this;
802
- }
803
- setTintMode(mode) {
804
- this.tintMode = mode;
805
- return this;
806
- }
807
- clearTint() {
808
- this.tint = WHITE_RGB;
809
- this.isTinted = false;
810
- this.tintMode = TintModes.MULTIPLY;
811
- return this;
812
- }
813
- setPixelAA(on = true) {
814
- this.pixelAA = Boolean(on);
815
- return this;
816
- }
817
- setCrop(x, y, w, h) {
818
- if (x === void 0 || y === void 0 || w === void 0 || h === void 0) {
819
- this.isCropped = false;
820
- this.cropX = this.cropY = this.cropW = this.cropH = 0;
821
- } else {
822
- this.isCropped = true;
823
- this.cropX = x;
824
- this.cropY = y;
825
- this.cropW = Math.max(0, w);
826
- this.cropH = Math.max(0, h);
827
- }
828
- return this;
829
- }
830
- };
831
- var NineSliceObject = class extends DisplayObject {
832
- texture;
833
- frame;
834
- leftWidth;
835
- rightWidth;
836
- topHeight;
837
- bottomHeight;
838
- constructor(scene, x, y, key, frame, width, height, left, right, top, bottom) {
839
- super(scene, "NineSlice");
840
- this.x = x;
841
- this.y = y;
842
- this.texture = scene.textures.get(key);
843
- this.frame = this.texture.get(frame);
844
- this.width = width;
845
- this.height = height;
846
- this.leftWidth = left;
847
- this.rightWidth = right;
848
- this.topHeight = top;
849
- this.bottomHeight = bottom;
850
- }
851
- setTexture(key, frame) {
852
- this.texture = this.scene.textures.get(key);
853
- this.frame = this.texture.get(frame);
854
- return this;
855
- }
856
- setFrame(frame) {
857
- this.frame = this.texture.get(frame);
858
- return this;
859
- }
860
- setSlices(width, height, left, right, top, bottom) {
861
- this.width = Math.max(0, width);
862
- this.height = Math.max(0, height);
863
- this.leftWidth = Math.max(0, left);
864
- this.rightWidth = Math.max(0, right);
865
- this.topHeight = Math.max(0, top);
866
- this.bottomHeight = Math.max(0, bottom);
867
- return this;
868
- }
869
- };
870
- var TileSpriteObject = class extends DisplayObject {
871
- texture;
872
- frame;
873
- tilePositionX = 0;
874
- tilePositionY = 0;
875
- tint = WHITE_RGB;
876
- isTinted = false;
877
- constructor(scene, x, y, width, height, key, frame) {
878
- super(scene, "TileSprite");
879
- this.x = x;
880
- this.y = y;
881
- this.width = Math.max(0, width);
882
- this.height = Math.max(0, height);
883
- this.texture = scene.textures.get(key);
884
- this.frame = this.texture.get(frame);
885
- this.texture.source[0].repeat = true;
886
- }
887
- setTint(color) {
888
- this.tint = color & HEX_MASK;
889
- this.isTinted = true;
890
- return this;
891
- }
892
- clearTint() {
893
- this.tint = WHITE_RGB;
894
- this.isTinted = false;
895
- return this;
896
- }
897
- };
898
- var RectangleObject = class extends DisplayObject {
899
- fillColor;
900
- fillAlpha;
901
- constructor(scene, x, y, width, height, fillColor = 0, fillAlpha = 1) {
902
- super(scene, "Rectangle");
903
- this.x = x;
904
- this.y = y;
905
- this.width = width;
906
- this.height = height;
907
- this.fillColor = fillColor & HEX_MASK;
908
- this.fillAlpha = fillAlpha;
909
- }
910
- setFillStyle(color, alpha = 1) {
911
- this.fillColor = color & HEX_MASK;
912
- this.fillAlpha = alpha;
913
- return this;
914
- }
915
- };
916
- /**
917
- * GPU Signed-Distance-Field (SDF) rounded-rect / border / pill / stepped-pixel panel primitive.
918
- * Batched by `SdfPanelBatcher` on WebGL with zero texture uploads, and mirrored analytically on Canvas2D.
919
- */
920
- var PanelObject = class extends DisplayObject {
921
- fillColor;
922
- fillAlpha;
923
- borderColor;
924
- borderAlpha;
925
- borderWidth;
926
- radiusTL;
927
- radiusTR;
928
- radiusBR;
929
- radiusBL;
930
- pixelStep;
931
- /** Encoded open seam side: `0` = closed, `1` = open left, `-1` = open right. */
932
- openSide = 0;
933
- topGlintColor;
934
- topGlintAlpha;
935
- topGlintHeight;
936
- constructor(scene, x, y, width, height, style = {}) {
937
- super(scene, "Panel");
938
- this.originX = 0;
939
- this.originY = 0;
940
- this.x = x;
941
- this.y = y;
942
- this.width = Math.max(0, width);
943
- this.height = Math.max(0, height);
944
- this.fillColor = (style.fillColor ?? 0xffffff) & HEX_MASK;
945
- this.fillAlpha = style.fillAlpha ?? 1;
946
- this.borderColor = (style.borderColor ?? 0) & HEX_MASK;
947
- this.borderAlpha = style.borderAlpha ?? 1;
948
- this.borderWidth = Math.max(0, style.borderWidth ?? 0);
949
- this.pixelStep = Math.max(0, style.pixelStep ?? 0);
950
- this.radiusTL = 0;
951
- this.radiusTR = 0;
952
- this.radiusBR = 0;
953
- this.radiusBL = 0;
954
- this.topGlintColor = (style.topGlintColor ?? 0xffffff) & HEX_MASK;
955
- this.topGlintAlpha = Math.max(0, Math.min(1, style.topGlintAlpha ?? 0));
956
- this.topGlintHeight = Math.max(0, style.topGlintHeight ?? 0);
957
- if (style.radius !== void 0) this.setRadius(style.radius);
958
- if (style.openSide !== void 0) this.setOpenSide(style.openSide);
959
- }
960
- setFillStyle(color, alpha = 1) {
961
- this.fillColor = color & HEX_MASK;
962
- this.fillAlpha = alpha;
963
- return this;
964
- }
965
- setBorderStyle(width, color = this.borderColor, alpha = 1) {
966
- this.borderWidth = Math.max(0, width);
967
- this.borderColor = color & HEX_MASK;
968
- this.borderAlpha = alpha;
969
- return this;
970
- }
971
- setRadius(radius) {
972
- if (typeof radius === "number") {
973
- const r = Math.max(0, radius);
974
- this.radiusTL = r;
975
- this.radiusTR = r;
976
- this.radiusBR = r;
977
- this.radiusBL = r;
978
- } else {
979
- this.radiusTL = Math.max(0, radius[0] ?? 0);
980
- this.radiusTR = Math.max(0, radius[1] ?? 0);
981
- this.radiusBR = Math.max(0, radius[2] ?? 0);
982
- this.radiusBL = Math.max(0, radius[3] ?? 0);
983
- }
984
- return this;
985
- }
986
- setPixelStep(step) {
987
- this.pixelStep = Math.max(0, step);
988
- return this;
989
- }
990
- setOpenSide(side) {
991
- this.openSide = side === "left" ? 1 : side === "right" ? -1 : 0;
992
- return this;
993
- }
994
- setTopGlint(height, color = this.topGlintColor, alpha = 1) {
995
- this.topGlintHeight = Math.max(0, height);
996
- this.topGlintColor = color & HEX_MASK;
997
- this.topGlintAlpha = Math.max(0, Math.min(1, alpha));
998
- return this;
999
- }
1000
- setPanelStyle(style) {
1001
- if (style.fillColor !== void 0) this.fillColor = style.fillColor & HEX_MASK;
1002
- if (style.fillAlpha !== void 0) this.fillAlpha = style.fillAlpha;
1003
- if (style.borderColor !== void 0) this.borderColor = style.borderColor & HEX_MASK;
1004
- if (style.borderAlpha !== void 0) this.borderAlpha = style.borderAlpha;
1005
- if (style.borderWidth !== void 0) this.borderWidth = Math.max(0, style.borderWidth);
1006
- if (style.radius !== void 0) this.setRadius(style.radius);
1007
- if (style.pixelStep !== void 0) this.pixelStep = Math.max(0, style.pixelStep);
1008
- if (style.openSide !== void 0) this.setOpenSide(style.openSide);
1009
- if (style.topGlintColor !== void 0) this.topGlintColor = style.topGlintColor & HEX_MASK;
1010
- if (style.topGlintAlpha !== void 0) this.topGlintAlpha = Math.max(0, Math.min(1, style.topGlintAlpha));
1011
- if (style.topGlintHeight !== void 0) this.topGlintHeight = Math.max(0, style.topGlintHeight);
1012
- return this;
1013
- }
1014
- };
1015
- /**
1016
- * GPU Multi-channel + True Signed Distance Field (MTSDF) vector icon display object.
1017
- * Batched by `MsdfIconBatcher` on WebGL with arbitrary tint + optional true-SDF outline, and mirrored via `Path2D`
1018
- * on Canvas2D. Resolution-independent from 10 px to 256 px across 1x/2x/3x DPR.
1019
- */
1020
- var MsdfIconObject = class extends DisplayObject {
1021
- texture;
1022
- u0 = 0;
1023
- v0 = 0;
1024
- u1 = 1;
1025
- v1 = 1;
1026
- padRatio = 0;
1027
- rangeUnits = 3.5;
1028
- viewSize = 24;
1029
- fillColor;
1030
- fillAlpha;
1031
- outlineColor;
1032
- outlineAlpha;
1033
- outlineWidth;
1034
- svgPath;
1035
- constructor(scene, x, y, size, config = {}) {
1036
- super(scene, "MsdfIcon");
1037
- this.originX = 0;
1038
- this.originY = 0;
1039
- this.x = x;
1040
- this.y = y;
1041
- const s = Math.max(0, size);
1042
- this.width = s;
1043
- this.height = s;
1044
- this.texture = scene.textures.get(config.textureKey ?? "__DEFAULT");
1045
- this.fillColor = (config.fillColor ?? 0) & HEX_MASK;
1046
- this.fillAlpha = config.fillAlpha ?? 1;
1047
- this.outlineColor = (config.outlineColor ?? 0xffffff) & HEX_MASK;
1048
- this.outlineAlpha = config.outlineAlpha ?? 1;
1049
- this.outlineWidth = Math.max(0, config.outlineWidth ?? 0);
1050
- this.svgPath = config.svgPath ?? null;
1051
- 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);
1052
- }
1053
- setTexture(key) {
1054
- this.texture = this.scene.textures.get(key);
1055
- return this;
1056
- }
1057
- /**
1058
- * Bind an MTSDF atlas cell `(col, row)` with exact half-texel UV inset so bilinear sampling never bleeds from
1059
- * neighboring cells, while expanding the quad symmetrically to cover the full padded SDF field.
1060
- */
1061
- setCell(col, row, cols = 8, rows = 4, cellSize = 32, viewSize = 24, margin = 2, pxRange = 4) {
1062
- const atlasW = Math.max(1, cols * cellSize);
1063
- const atlasH = Math.max(1, rows * cellSize);
1064
- this.u0 = (col * cellSize + .5) / atlasW;
1065
- this.v0 = (row * cellSize + .5) / atlasH;
1066
- this.u1 = ((col + 1) * cellSize - .5) / atlasW;
1067
- this.v1 = ((row + 1) * cellSize - .5) / atlasH;
1068
- const unitsPerTexel = (viewSize + margin * 2) / Math.max(1, cellSize);
1069
- const insetMargin = Math.max(0, margin - .5 * unitsPerTexel);
1070
- this.viewSize = Math.max(1, viewSize);
1071
- this.padRatio = insetMargin / this.viewSize;
1072
- this.rangeUnits = Math.max(.001, pxRange * unitsPerTexel);
1073
- return this;
1074
- }
1075
- setColor(color, alpha = this.fillAlpha) {
1076
- this.fillColor = color & HEX_MASK;
1077
- this.fillAlpha = alpha;
1078
- return this;
1079
- }
1080
- setOutline(width, color = this.outlineColor, alpha = this.outlineAlpha) {
1081
- this.outlineWidth = Math.max(0, width);
1082
- this.outlineColor = color & HEX_MASK;
1083
- this.outlineAlpha = alpha;
1084
- return this;
1085
- }
1086
- setSvgPath(path) {
1087
- this.svgPath = path;
1088
- return this;
1089
- }
1090
- };
1091
- let sharedMeasureCtx = null;
1092
- function getMeasureCtx(doc) {
1093
- if (!sharedMeasureCtx) sharedMeasureCtx = doc.createElement("canvas").getContext("2d");
1094
- return sharedMeasureCtx;
1095
- }
1096
- var TextObject = class extends DisplayObject {
1097
- text = "";
1098
- style;
1099
- lineSpacing = 0;
1100
- isCropped = false;
1101
- cropX = 0;
1102
- cropY = 0;
1103
- cropW = 0;
1104
- cropH = 0;
1105
- frame = {
1106
- width: 1,
1107
- height: 1,
1108
- cutWidth: 1,
1109
- cutHeight: 1,
1110
- source: { resolution: 1 }
1111
- };
1112
- canvas = null;
1113
- ctx = null;
1114
- glTex = null;
1115
- glTexAllocW = 0;
1116
- glTexAllocH = 0;
1117
- glDirty = true;
1118
- dirty = true;
1119
- lines = [];
1120
- ascent = 12;
1121
- lineH = 16;
1122
- constructor(scene, x, y, text, style = {}) {
1123
- super(scene, "Text");
1124
- this.originX = 0;
1125
- this.originY = 0;
1126
- this.x = x;
1127
- this.y = y;
1128
- const pad = style.padding;
1129
- this.style = {
1130
- fontFamily: style.fontFamily ?? "system-ui, sans-serif",
1131
- fontSize: typeof style.fontSize === "number" ? `${style.fontSize}px` : style.fontSize ?? "14px",
1132
- fontStyle: style.fontStyle ?? "",
1133
- color: style.color ?? rgbToCss(0, 1),
1134
- stroke: style.stroke ?? "",
1135
- strokeThickness: style.strokeThickness ?? 0,
1136
- backgroundColor: style.backgroundColor ?? null,
1137
- padding: {
1138
- left: pad?.left ?? pad?.x ?? 0,
1139
- right: pad?.right ?? pad?.x ?? 0,
1140
- top: pad?.top ?? pad?.y ?? 0,
1141
- bottom: pad?.bottom ?? pad?.y ?? 0
1142
- },
1143
- align: style.align ?? "left",
1144
- resolution: style.resolution ?? 1,
1145
- metrics: style.metrics ?? null
1146
- };
1147
- this.lineSpacing = style.lineSpacing ?? 0;
1148
- this.frame.source.resolution = this.style.resolution;
1149
- this.setText(text);
1150
- }
1151
- cssFont() {
1152
- const s = this.style;
1153
- return `${s.fontStyle ? s.fontStyle + " " : ""}${s.fontSize} ${s.fontFamily}`;
1154
- }
1155
- recomputeMetrics() {
1156
- const s = this.style;
1157
- const res = s.resolution || 1;
1158
- this.frame.source.resolution = res;
1159
- if (!this.text) {
1160
- this.lines = [];
1161
- this.width = 0;
1162
- this.height = 0;
1163
- this.frame.width = this.frame.cutWidth = 1;
1164
- this.frame.height = this.frame.cutHeight = 1;
1165
- this.dirty = true;
1166
- return;
1167
- }
1168
- const lines = this.text.split("\n");
1169
- this.lines = lines;
1170
- const mctx = getMeasureCtx(this.scene.doc);
1171
- mctx.font = this.cssFont();
1172
- let maxW = 0;
1173
- for (let i = 0; i < lines.length; i++) {
1174
- const w = mctx.measureText(lines[i]).width;
1175
- if (w > maxW) maxW = w;
1176
- }
1177
- if (s.metrics) {
1178
- this.ascent = s.metrics.ascent;
1179
- this.lineH = s.metrics.fontSize;
1180
- } else {
1181
- const px = parseFloat(s.fontSize) || 14;
1182
- mctx.textBaseline = "alphabetic";
1183
- const tm = mctx.measureText("Mg中");
1184
- const asc = Math.ceil(tm.fontBoundingBoxAscent ?? tm.actualBoundingBoxAscent ?? px * .85);
1185
- const desc = Math.ceil(tm.fontBoundingBoxDescent ?? tm.actualBoundingBoxDescent ?? px * .25);
1186
- this.ascent = asc;
1187
- this.lineH = asc + desc;
1188
- }
1189
- const stroke = s.strokeThickness || 0;
1190
- const w = Math.ceil(maxW + stroke + s.padding.left + s.padding.right);
1191
- const h = Math.ceil(lines.length * this.lineH + Math.max(0, lines.length - 1) * this.lineSpacing + stroke + s.padding.top + s.padding.bottom);
1192
- this.width = w;
1193
- this.height = h;
1194
- this.frame.width = this.frame.cutWidth = Math.max(1, Math.ceil(w * res));
1195
- this.frame.height = this.frame.cutHeight = Math.max(1, Math.ceil(h * res));
1196
- if (!this.customOrigin) {
1197
- this._displayOriginX = w * this.originX;
1198
- this._displayOriginY = h * this.originY;
1199
- }
1200
- this.dirty = true;
1201
- }
1202
- setText(value) {
1203
- const next = Array.isArray(value) ? value.join("\n") : String(value ?? "");
1204
- if (next === this.text && !this.dirty) return this;
1205
- this.text = next;
1206
- this.recomputeMetrics();
1207
- return this;
1208
- }
1209
- setStyle(style) {
1210
- const s = this.style;
1211
- if (style.fontFamily !== void 0) s.fontFamily = style.fontFamily;
1212
- if (style.fontSize !== void 0) s.fontSize = typeof style.fontSize === "number" ? `${style.fontSize}px` : style.fontSize;
1213
- if (style.fontStyle !== void 0) s.fontStyle = style.fontStyle;
1214
- if (style.color !== void 0) s.color = style.color;
1215
- if (style.stroke !== void 0) s.stroke = style.stroke;
1216
- if (style.strokeThickness !== void 0) s.strokeThickness = style.strokeThickness;
1217
- if (style.backgroundColor !== void 0) s.backgroundColor = style.backgroundColor;
1218
- if (style.padding !== void 0) {
1219
- s.padding.left = style.padding.left ?? style.padding.x ?? 0;
1220
- s.padding.right = style.padding.right ?? style.padding.x ?? 0;
1221
- s.padding.top = style.padding.top ?? style.padding.y ?? 0;
1222
- s.padding.bottom = style.padding.bottom ?? style.padding.y ?? 0;
1223
- }
1224
- if (style.align !== void 0) s.align = style.align;
1225
- if (style.resolution !== void 0) s.resolution = style.resolution;
1226
- if (style.lineSpacing !== void 0) this.lineSpacing = style.lineSpacing;
1227
- if (style.metrics !== void 0) s.metrics = style.metrics;
1228
- else if (style.fontSize !== void 0 || style.fontFamily !== void 0 || style.fontStyle !== void 0) s.metrics = null;
1229
- this.recomputeMetrics();
1230
- return this;
1231
- }
1232
- setColor(color) {
1233
- if (this.style.color !== color) {
1234
- this.style.color = color;
1235
- this.dirty = true;
1236
- }
1237
- return this;
1238
- }
1239
- setStroke(color, thickness) {
1240
- this.style.stroke = color;
1241
- this.style.strokeThickness = thickness;
1242
- this.recomputeMetrics();
1243
- return this;
1244
- }
1245
- setFontSize(size) {
1246
- const next = typeof size === "number" ? `${size}px` : size;
1247
- if (this.style.fontSize !== next) {
1248
- this.style.fontSize = next;
1249
- this.style.metrics = null;
1250
- this.recomputeMetrics();
1251
- }
1252
- return this;
1253
- }
1254
- setLineSpacing(v) {
1255
- if (this.lineSpacing !== v) {
1256
- this.lineSpacing = v;
1257
- this.recomputeMetrics();
1258
- }
1259
- return this;
1260
- }
1261
- setAlign(align) {
1262
- if (this.style.align !== align) {
1263
- this.style.align = align;
1264
- this.dirty = true;
1265
- }
1266
- return this;
1267
- }
1268
- setResolution(res) {
1269
- const r = res > 0 ? res : 1;
1270
- if (this.style.resolution !== r) {
1271
- this.style.resolution = r;
1272
- this.recomputeMetrics();
1273
- }
1274
- return this;
1275
- }
1276
- setCrop(x, y, w, h) {
1277
- if (x === void 0 || y === void 0 || w === void 0 || h === void 0) {
1278
- this.isCropped = false;
1279
- this.cropX = this.cropY = this.cropW = this.cropH = 0;
1280
- } else {
1281
- this.isCropped = true;
1282
- this.cropX = x;
1283
- this.cropY = y;
1284
- this.cropW = Math.max(0, w);
1285
- this.cropH = Math.max(0, h);
1286
- }
1287
- return this;
1288
- }
1289
- /** Lazily paint the 2D backing canvas only when visible & rendered. */
1290
- ensureCanvas() {
1291
- if (!this.text || this.width <= 0 || this.height <= 0) return null;
1292
- if (!this.dirty && this.canvas) return this.canvas;
1293
- this.dirty = false;
1294
- const cw = this.frame.width;
1295
- const ch = this.frame.height;
1296
- if (!this.canvas) {
1297
- this.canvas = this.scene.doc.createElement("canvas");
1298
- this.ctx = this.canvas.getContext("2d", { willReadFrequently: true });
1299
- }
1300
- if (!this.ctx) return null;
1301
- if (this.canvas.width !== cw || this.canvas.height !== ch) {
1302
- this.canvas.width = cw;
1303
- this.canvas.height = ch;
1304
- } else this.ctx.clearRect(0, 0, cw, ch);
1305
- const g = this.ctx;
1306
- const s = this.style;
1307
- const res = s.resolution || 1;
1308
- const stroke = s.strokeThickness || 0;
1309
- g.save();
1310
- g.scale(res, res);
1311
- if (s.backgroundColor) {
1312
- g.fillStyle = s.backgroundColor;
1313
- g.fillRect(0, 0, this.width, this.height);
1314
- }
1315
- g.font = this.cssFont();
1316
- g.textBaseline = "alphabetic";
1317
- g.textAlign = s.align;
1318
- g.lineJoin = "round";
1319
- g.miterLimit = 2;
1320
- const innerW = this.width - s.padding.left - s.padding.right - stroke;
1321
- 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;
1322
- let baseY = s.padding.top + stroke * .5 + this.ascent;
1323
- const stepY = this.lineH + this.lineSpacing;
1324
- for (let i = 0; i < this.lines.length; i++) {
1325
- const line = this.lines[i];
1326
- if (stroke > 0 && s.stroke) {
1327
- g.strokeStyle = s.stroke;
1328
- g.lineWidth = stroke;
1329
- g.strokeText(line, baseX, baseY);
1330
- }
1331
- g.fillStyle = s.color;
1332
- g.fillText(line, baseX, baseY);
1333
- baseY += stepY;
1334
- }
1335
- g.restore();
1336
- this.glDirty = true;
1337
- return this.canvas;
1338
- }
1339
- /** Called by the WebGL2 renderer to obtain/update the cached WebGLTexture for this Text.
1340
- * Performs zero GL calls on clean frames; when uploading, binds via `onBindSlot0` so renderer state cache stays exact. */
1341
- ensureGlTexture(gl, onBindSlot0) {
1342
- const cv = this.ensureCanvas();
1343
- if (!cv) return null;
1344
- if (!this.glTex) {
1345
- this.glTex = gl.createTexture();
1346
- this.glTexAllocW = 0;
1347
- this.glTexAllocH = 0;
1348
- this.glDirty = true;
1349
- }
1350
- if (!this.glTex) return null;
1351
- if (this.glDirty || this.glTexAllocW !== cv.width || this.glTexAllocH !== cv.height) {
1352
- if (onBindSlot0) onBindSlot0(this.glTex);
1353
- else {
1354
- gl.activeTexture(gl.TEXTURE0);
1355
- gl.bindTexture(gl.TEXTURE_2D, this.glTex);
1356
- }
1357
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
1358
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
1359
- if (this.glTexAllocW === cv.width && this.glTexAllocH === cv.height) gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, cv);
1360
- else {
1361
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1362
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1363
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
1364
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
1365
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, cv);
1366
- this.glTexAllocW = cv.width;
1367
- this.glTexAllocH = cv.height;
1368
- }
1369
- this.glDirty = false;
1370
- }
1371
- return this.glTex;
1372
- }
1373
- invalidateGl() {
1374
- this.glTex = null;
1375
- this.glTexAllocW = 0;
1376
- this.glTexAllocH = 0;
1377
- this.glDirty = true;
1378
- }
1379
- destroy(fromScene) {
1380
- if (this.glTex) {
1381
- try {
1382
- const gl = this.scene.renderer?.gl;
1383
- if (gl && !this.scene.renderer.contextLost) gl.deleteTexture(this.glTex);
1384
- } catch {}
1385
- this.glTex = null;
1386
- }
1387
- this.canvas = null;
1388
- this.ctx = null;
1389
- super.destroy(fromScene);
1390
- }
1391
- };
1392
- var Graphics = class extends DisplayObject {
1393
- ops = /* @__PURE__ */ new Uint8Array(64);
1394
- nums = /* @__PURE__ */ new Float64Array(256);
1395
- opLen = 0;
1396
- numLen = 0;
1397
- /** Monotonic geometry revision bumped on every clear/draw op so WebGL can cache static tessellation meshes. */
1398
- version = 0;
1399
- /** Renderer-owned tessellated local-space mesh cache (opaque to user code). */
1400
- _glCache = null;
1401
- /** Last filled rectangle bounds (used O(1) by `Pane` and `ScrollList` rect clip masks). */
1402
- maskRect = null;
1403
- constructor(scene) {
1404
- super(scene, "Graphics");
1405
- this.originX = 0;
1406
- this.originY = 0;
1407
- }
1408
- pushOp(op, nCount) {
1409
- if (this.opLen >= this.ops.length) {
1410
- const next = new Uint8Array(this.ops.length * 2);
1411
- next.set(this.ops);
1412
- this.ops = next;
1413
- }
1414
- const base = this.numLen;
1415
- if (base + nCount > this.nums.length) {
1416
- let cap = this.nums.length * 2;
1417
- while (cap < base + nCount) cap *= 2;
1418
- const next = new Float64Array(cap);
1419
- next.set(this.nums);
1420
- this.nums = next;
1421
- }
1422
- this.ops[this.opLen++] = op;
1423
- this.numLen = base + nCount;
1424
- this.version++;
1425
- return base;
1426
- }
1427
- clear() {
1428
- if (this.opLen !== 0 || this.numLen !== 0 || this.maskRect !== null) {
1429
- this.opLen = 0;
1430
- this.numLen = 0;
1431
- this.maskRect = null;
1432
- this.version++;
1433
- }
1434
- return this;
1435
- }
1436
- save() {
1437
- this.pushOp(22, 0);
1438
- return this;
1439
- }
1440
- restore() {
1441
- this.pushOp(23, 0);
1442
- return this;
1443
- }
1444
- fillStyle(color, alpha = 1) {
1445
- const i = this.pushOp(1, 2);
1446
- this.nums[i] = color & HEX_MASK;
1447
- this.nums[i + 1] = alpha;
1448
- return this;
1449
- }
1450
- lineStyle(lineWidth, color, alpha = 1) {
1451
- const i = this.pushOp(2, 3);
1452
- this.nums[i] = lineWidth;
1453
- this.nums[i + 1] = color & HEX_MASK;
1454
- this.nums[i + 2] = alpha;
1455
- return this;
1456
- }
1457
- fillRect(x, y, w, h) {
1458
- const i = this.pushOp(3, 4);
1459
- this.nums[i] = x;
1460
- this.nums[i + 1] = y;
1461
- this.nums[i + 2] = w;
1462
- this.nums[i + 3] = h;
1463
- if (!this.maskRect) this.maskRect = {
1464
- x,
1465
- y,
1466
- w,
1467
- h
1468
- };
1469
- else {
1470
- this.maskRect.x = x;
1471
- this.maskRect.y = y;
1472
- this.maskRect.w = w;
1473
- this.maskRect.h = h;
1474
- }
1475
- return this;
1476
- }
1477
- strokeRect(x, y, w, h) {
1478
- const i = this.pushOp(4, 4);
1479
- this.nums[i] = x;
1480
- this.nums[i + 1] = y;
1481
- this.nums[i + 2] = w;
1482
- this.nums[i + 3] = h;
1483
- return this;
1484
- }
1485
- fillRoundedRect(x, y, w, h, radius = 8) {
1486
- const r = typeof radius === "number" ? radius : radius.tl ?? radius.tr ?? 8;
1487
- const i = this.pushOp(5, 5);
1488
- this.nums[i] = x;
1489
- this.nums[i + 1] = y;
1490
- this.nums[i + 2] = w;
1491
- this.nums[i + 3] = h;
1492
- this.nums[i + 4] = r;
1493
- return this;
1494
- }
1495
- strokeRoundedRect(x, y, w, h, radius = 8) {
1496
- const r = typeof radius === "number" ? radius : radius.tl ?? radius.tr ?? 8;
1497
- const i = this.pushOp(6, 5);
1498
- this.nums[i] = x;
1499
- this.nums[i + 1] = y;
1500
- this.nums[i + 2] = w;
1501
- this.nums[i + 3] = h;
1502
- this.nums[i + 4] = r;
1503
- return this;
1504
- }
1505
- fillCircle(x, y, r) {
1506
- const i = this.pushOp(7, 3);
1507
- this.nums[i] = x;
1508
- this.nums[i + 1] = y;
1509
- this.nums[i + 2] = r;
1510
- return this;
1511
- }
1512
- strokeCircle(x, y, r) {
1513
- const i = this.pushOp(8, 3);
1514
- this.nums[i] = x;
1515
- this.nums[i + 1] = y;
1516
- this.nums[i + 2] = r;
1517
- return this;
1518
- }
1519
- fillEllipse(x, y, width, height) {
1520
- const i = this.pushOp(9, 4);
1521
- this.nums[i] = x;
1522
- this.nums[i + 1] = y;
1523
- this.nums[i + 2] = width;
1524
- this.nums[i + 3] = height;
1525
- return this;
1526
- }
1527
- strokeEllipse(x, y, width, height) {
1528
- const i = this.pushOp(10, 4);
1529
- this.nums[i] = x;
1530
- this.nums[i + 1] = y;
1531
- this.nums[i + 2] = width;
1532
- this.nums[i + 3] = height;
1533
- return this;
1534
- }
1535
- fillTriangle(x0, y0, x1, y1, x2, y2) {
1536
- const i = this.pushOp(11, 6);
1537
- this.nums[i] = x0;
1538
- this.nums[i + 1] = y0;
1539
- this.nums[i + 2] = x1;
1540
- this.nums[i + 3] = y1;
1541
- this.nums[i + 4] = x2;
1542
- this.nums[i + 5] = y2;
1543
- return this;
1544
- }
1545
- strokeTriangle(x0, y0, x1, y1, x2, y2) {
1546
- const i = this.pushOp(12, 6);
1547
- this.nums[i] = x0;
1548
- this.nums[i + 1] = y0;
1549
- this.nums[i + 2] = x1;
1550
- this.nums[i + 3] = y1;
1551
- this.nums[i + 4] = x2;
1552
- this.nums[i + 5] = y2;
1553
- return this;
1554
- }
1555
- lineBetween(x1, y1, x2, y2) {
1556
- const i = this.pushOp(13, 4);
1557
- this.nums[i] = x1;
1558
- this.nums[i + 1] = y1;
1559
- this.nums[i + 2] = x2;
1560
- this.nums[i + 3] = y2;
1561
- return this;
1562
- }
1563
- beginPath() {
1564
- this.pushOp(14, 0);
1565
- return this;
1566
- }
1567
- moveTo(x, y) {
1568
- const i = this.pushOp(15, 2);
1569
- this.nums[i] = x;
1570
- this.nums[i + 1] = y;
1571
- return this;
1572
- }
1573
- lineTo(x, y) {
1574
- const i = this.pushOp(16, 2);
1575
- this.nums[i] = x;
1576
- this.nums[i + 1] = y;
1577
- return this;
1578
- }
1579
- arc(x, y, r, startAngle, endAngle, anticlockwise = false) {
1580
- const i = this.pushOp(17, 6);
1581
- this.nums[i] = x;
1582
- this.nums[i + 1] = y;
1583
- this.nums[i + 2] = r;
1584
- this.nums[i + 3] = startAngle;
1585
- this.nums[i + 4] = endAngle;
1586
- this.nums[i + 5] = anticlockwise ? 1 : 0;
1587
- return this;
1588
- }
1589
- slice(x, y, r, startAngle, endAngle, anticlockwise = false) {
1590
- const i = this.pushOp(18, 6);
1591
- this.nums[i] = x;
1592
- this.nums[i + 1] = y;
1593
- this.nums[i + 2] = r;
1594
- this.nums[i + 3] = startAngle;
1595
- this.nums[i + 4] = endAngle;
1596
- this.nums[i + 5] = anticlockwise ? 1 : 0;
1597
- return this;
1598
- }
1599
- closePath() {
1600
- this.pushOp(19, 0);
1601
- return this;
1602
- }
1603
- fillPath() {
1604
- this.pushOp(20, 0);
1605
- return this;
1606
- }
1607
- strokePath() {
1608
- this.pushOp(21, 0);
1609
- return this;
1610
- }
1611
- fill() {
1612
- return this.fillPath();
1613
- }
1614
- stroke() {
1615
- return this.strokePath();
1616
- }
1617
- fillPoints(points, closeShape = false, closePath = false) {
1618
- if (points.length < 3) return this;
1619
- this.beginPath();
1620
- this.moveTo(points[0].x, points[0].y);
1621
- for (let i = 1; i < points.length; i++) this.lineTo(points[i].x, points[i].y);
1622
- if (closeShape || closePath) this.closePath();
1623
- return this.fillPath();
1624
- }
1625
- strokePoints(points, closeShape = false, closePath = false) {
1626
- if (points.length < 2) return this;
1627
- this.beginPath();
1628
- this.moveTo(points[0].x, points[0].y);
1629
- for (let i = 1; i < points.length; i++) this.lineTo(points[i].x, points[i].y);
1630
- if (closeShape || closePath) this.closePath();
1631
- return this.strokePath();
1632
- }
1633
- createGeometryMask() {
1634
- return {
1635
- graphics: this,
1636
- active: true
1637
- };
1638
- }
1639
- destroy(fromScene) {
1640
- this._glCache = null;
1641
- super.destroy(fromScene);
1642
- }
1643
- };
1644
- var BlitterObject = class extends DisplayObject {
1645
- texture;
1646
- children = { list: [] };
1647
- constructor(scene, x, y, key) {
1648
- super(scene, "Blitter");
1649
- this.originX = 0;
1650
- this.originY = 0;
1651
- this.x = x;
1652
- this.y = y;
1653
- this.texture = scene.textures.get(key);
1654
- }
1655
- create(x, y, frame) {
1656
- const bob = {
1657
- x,
1658
- y,
1659
- visible: true,
1660
- alpha: 1,
1661
- frame: this.texture.get(frame)
1662
- };
1663
- this.children.list.push(bob);
1664
- return bob;
1665
- }
1666
- destroy(fromScene) {
1667
- this.children.list.length = 0;
1668
- super.destroy(fromScene);
1669
- }
1670
- };
1671
- var Container = class extends DisplayObject {
1672
- list = [];
1673
- clipMask = null;
1674
- filters = null;
1675
- hasZOrder = false;
1676
- zDirty = false;
1677
- sortedBuf = null;
1678
- constructor(scene, x = 0, y = 0, children) {
1679
- super(scene, "Container");
1680
- this.originX = 0;
1681
- this.originY = 0;
1682
- this.x = x;
1683
- this.y = y;
1684
- if (children?.length) this.add(children);
1685
- }
1686
- _markZDirty(nonZero) {
1687
- if (nonZero) this.hasZOrder = true;
1688
- this.zDirty = true;
1689
- }
1690
- /** Children in render order: O(1) direct `list` when all zIndex === 0, else cached stable sort by `zIndex`. */
1691
- sortedChildren() {
1692
- if (!this.hasZOrder) return this.list;
1693
- if (this.zDirty || !this.sortedBuf) {
1694
- this.zDirty = false;
1695
- const src = this.list;
1696
- let anyNonZero = false;
1697
- for (let i = 0; i < src.length; i++) if (src[i].zIndex !== 0) {
1698
- anyNonZero = true;
1699
- break;
1700
- }
1701
- if (!anyNonZero) {
1702
- this.hasZOrder = false;
1703
- this.sortedBuf = null;
1704
- return src;
1705
- }
1706
- const buf = this.sortedBuf ?? (this.sortedBuf = []);
1707
- buf.length = src.length;
1708
- for (let i = 0; i < src.length; i++) buf[i] = src[i];
1709
- buf.sort((a, b) => a.zIndex - b.zIndex);
1710
- }
1711
- return this.sortedBuf;
1712
- }
1713
- add(child) {
1714
- if (Array.isArray(child)) for (let i = 0; i < child.length; i++) this.addOne(child[i]);
1715
- else if (child) this.addOne(child);
1716
- return this;
1717
- }
1718
- addOne(child) {
1719
- if (child === this) return;
1720
- if (child.parentContainer === this) return;
1721
- if (child.parentContainer) child.parentContainer.remove(child);
1722
- else this.scene._displayList.remove(child);
1723
- child.parentContainer = this;
1724
- this.list.push(child);
1725
- if (child.zIndex !== 0) this.hasZOrder = true;
1726
- if (this.hasZOrder) this.zDirty = true;
1727
- }
1728
- /** Insert `child` at `index` in `this.list` (clamped to `[0, list.length]`). Moves in-place if already in this container. */
1729
- addAt(child, index) {
1730
- if (!child || child === this) return this;
1731
- const clamped = Math.max(0, Math.min(Math.round(index), this.list.length));
1732
- if (child.parentContainer === this) return this.moveTo(child, Math.min(clamped, Math.max(0, this.list.length - 1)));
1733
- if (child.parentContainer) child.parentContainer.remove(child);
1734
- else this.scene._displayList.remove(child);
1735
- child.parentContainer = this;
1736
- this.list.splice(Math.min(clamped, this.list.length), 0, child);
1737
- if (child.zIndex !== 0) this.hasZOrder = true;
1738
- if (this.hasZOrder) this.zDirty = true;
1739
- return this;
1740
- }
1741
- /** Move an existing child of this container to `index` in `this.list` (clamped to `[0, list.length - 1]`). */
1742
- moveTo(child, index) {
1743
- const cur = this.list.indexOf(child);
1744
- if (cur < 0) return this;
1745
- const target = Math.max(0, Math.min(Math.round(index), this.list.length - 1));
1746
- if (cur === target) return this;
1747
- this.list.splice(cur, 1);
1748
- this.list.splice(target, 0, child);
1749
- if (this.hasZOrder) this.zDirty = true;
1750
- return this;
1751
- }
1752
- remove(child) {
1753
- const i = this.list.indexOf(child);
1754
- if (i >= 0) {
1755
- this.list.splice(i, 1);
1756
- child.parentContainer = null;
1757
- if (this.hasZOrder) this.zDirty = true;
1758
- }
1759
- return this;
1760
- }
1761
- getIndex(child) {
1762
- return this.list.indexOf(child);
1763
- }
1764
- sendToBack(child) {
1765
- const i = this.list.indexOf(child);
1766
- if (i > 0) {
1767
- this.list.splice(i, 1);
1768
- this.list.unshift(child);
1769
- if (this.hasZOrder) this.zDirty = true;
1770
- }
1771
- return this;
1772
- }
1773
- bringToTop(child) {
1774
- const i = this.list.indexOf(child);
1775
- if (i >= 0 && i < this.list.length - 1) {
1776
- this.list.splice(i, 1);
1777
- this.list.push(child);
1778
- if (this.hasZOrder) this.zDirty = true;
1779
- }
1780
- return this;
1781
- }
1782
- setMask(mask) {
1783
- this.clipMask = mask;
1784
- return this;
1785
- }
1786
- clearMask() {
1787
- this.clipMask = null;
1788
- return this;
1789
- }
1790
- /** Zero-FBO compatibility hook for `Pane` & `ScrollList` (clips via hardware `gl.SCISSOR_TEST`). */
1791
- enableFilters() {
1792
- if (!this.filters) this.filters = { external: { addMask: (maskG) => {
1793
- const m = {
1794
- graphics: maskG,
1795
- active: true
1796
- };
1797
- this.clipMask = m;
1798
- return m;
1799
- } } };
1800
- return this;
1801
- }
1802
- destroy(destroyChildren = true) {
1803
- if (!this.active) return;
1804
- if (destroyChildren) {
1805
- const snap = this.list.slice();
1806
- this.list.length = 0;
1807
- for (let i = snap.length - 1; i >= 0; i--) {
1808
- snap[i].parentContainer = null;
1809
- snap[i].destroy(true);
1810
- }
1811
- } else {
1812
- for (let i = 0; i < this.list.length; i++) this.list[i].parentContainer = null;
1813
- this.list.length = 0;
1814
- }
1815
- this.clipMask = null;
1816
- this.filters = null;
1817
- this.sortedBuf = null;
1818
- this.hasZOrder = false;
1819
- this.zDirty = false;
1820
- super.destroy(destroyChildren);
1821
- }
1822
- };
1823
- var CustomPassObject = class extends DisplayObject {
1824
- onRender;
1825
- constructor(scene, onRender) {
1826
- super(scene, "CustomPass");
1827
- this.onRender = onRender;
1828
- this._isCrowdInstanced = true;
1829
- }
1830
- };
1831
536
  // src/sdf-panel.ts
1832
537
  const MAX_PANELS = 1024;
1833
538
  const MAX_VERTS$3 = MAX_PANELS * 4;
@@ -2804,6 +1509,48 @@ const MODE_MULTIPLY = 0;
2804
1509
  const MODE_FILL = 1;
2805
1510
  const MODE_SOLID = 2;
2806
1511
  const BATCH_MAX_UNITS = 8;
1512
+ const INST_FLOATS = 11;
1513
+ const INST_STRIDE = 44;
1514
+ const INST_VERT_SRC = [
1515
+ "#version 300 es",
1516
+ "precision highp float;",
1517
+ "uniform vec2 uResolution;",
1518
+ "layout(location = 0) in vec2 aCorner;",
1519
+ "layout(location = 1) in vec4 aInstMat;",
1520
+ "layout(location = 2) in vec2 aInstTrans;",
1521
+ "layout(location = 3) in vec4 aInstUv;",
1522
+ "layout(location = 4) in vec4 aInstColor;",
1523
+ "out vec2 vUv;",
1524
+ "out vec4 vColor;",
1525
+ "void main() {",
1526
+ " vec2 p = vec2(",
1527
+ " aInstMat.x * aCorner.x + aInstMat.z * aCorner.y + aInstTrans.x,",
1528
+ " aInstMat.y * aCorner.x + aInstMat.w * aCorner.y + aInstTrans.y",
1529
+ " );",
1530
+ " vec2 clip = (p / uResolution) * 2.0 - 1.0;",
1531
+ " gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);",
1532
+ " vUv = mix(aInstUv.xy, aInstUv.zw, aCorner);",
1533
+ " vColor = aInstColor;",
1534
+ "}"
1535
+ ].join("\n");
1536
+ const INST_FRAG_SRC = [
1537
+ "#version 300 es",
1538
+ "precision mediump float;",
1539
+ "uniform sampler2D uSampler;",
1540
+ "in highp vec2 vUv;",
1541
+ "in vec4 vColor;",
1542
+ "out vec4 outColor;",
1543
+ "void main() {",
1544
+ " vec4 tex = texture(uSampler, vUv);",
1545
+ " outColor = vec4(tex.rgb * vColor.rgb * vColor.a, tex.a * vColor.a);",
1546
+ "}"
1547
+ ].join("\n");
1548
+ function applyGlBlendMode(gl, mode) {
1549
+ if (mode === BlendModes.ADD) gl.blendFunc(gl.ONE, gl.ONE);
1550
+ else if (mode === BlendModes.MULTIPLY) gl.blendFunc(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA);
1551
+ else if (mode === BlendModes.SCREEN) gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR);
1552
+ else gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
1553
+ }
2807
1554
  const VERT_SRC = [
2808
1555
  "precision highp float;",
2809
1556
  "uniform vec2 uResolution;",
@@ -3579,6 +2326,15 @@ var RendererGl = class extends EventEmitter {
3579
2326
  sfMat = createMatrix2D();
3580
2327
  maskWorldMat = createMatrix2D();
3581
2328
  bindTextSlot0;
2329
+ activeFbo = null;
2330
+ instProgram = null;
2331
+ instUres = null;
2332
+ instVao = null;
2333
+ instCornerVbo = null;
2334
+ instDataVbo = null;
2335
+ instStagingBuf = new ArrayBuffer(1024 * INST_STRIDE);
2336
+ instF32 = new Float32Array(this.instStagingBuf);
2337
+ instU32 = new Uint32Array(this.instStagingBuf);
3582
2338
  onLostDom;
3583
2339
  onRestoredDom;
3584
2340
  constructor(canvas, width, height, opts = {}) {
@@ -3619,6 +2375,7 @@ var RendererGl = class extends EventEmitter {
3619
2375
  this.onLostDom = (e) => {
3620
2376
  e.preventDefault();
3621
2377
  this.contextLost = true;
2378
+ this.activeFbo = null;
3622
2379
  this.boundTexCache.fill(null);
3623
2380
  this.activeTexUnit = -1;
3624
2381
  this.batchStateBound = false;
@@ -3654,12 +2411,12 @@ var RendererGl = class extends EventEmitter {
3654
2411
  /** State-cached texture binding shared across the Stage2D batcher and external CustomPass renderers. */
3655
2412
  bindTextureAt(unit, tex) {
3656
2413
  const target = tex ?? this.dummyTex;
2414
+ const gl = this.gl;
2415
+ if (this.activeTexUnit !== unit) {
2416
+ gl.activeTexture(gl.TEXTURE0 + unit);
2417
+ this.activeTexUnit = unit;
2418
+ }
3657
2419
  if (this.boundTexCache[unit] !== target) {
3658
- const gl = this.gl;
3659
- if (this.activeTexUnit !== unit) {
3660
- gl.activeTexture(gl.TEXTURE0 + unit);
3661
- this.activeTexUnit = unit;
3662
- }
3663
2420
  gl.bindTexture(gl.TEXTURE_2D, target);
3664
2421
  this.boundTexCache[unit] = target;
3665
2422
  this.curTexBinds++;
@@ -3883,7 +2640,7 @@ var RendererGl = class extends EventEmitter {
3883
2640
  src.glRepeat = canRepeat;
3884
2641
  src.glPremultiplyAlpha = src.premultiplyAlpha;
3885
2642
  }
3886
- if (!src.premultiplyAlpha) gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
2643
+ if (src.premultiplyAlpha) gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
3887
2644
  src.dirty = false;
3888
2645
  }
3889
2646
  setTextureFilter(src) {
@@ -3931,17 +2688,24 @@ var RendererGl = class extends EventEmitter {
3931
2688
  this.lastResH = this.height;
3932
2689
  }
3933
2690
  if (!this.batchStateBound) {
3934
- if (this.curBlend === BlendModes.ADD) gl.blendFunc(gl.ONE, gl.ONE);
3935
- else gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
2691
+ applyGlBlendMode(gl, this.curBlend);
3936
2692
  this.batchStateBound = true;
3937
2693
  }
3938
2694
  }
3939
- /** Full state restore for external callers that may have mutated viewport/blend/textures directly. */
2695
+ /** Full state restore for external callers that may have mutated viewport/blend/textures/pixelStore/FBO directly. */
3940
2696
  restoreState() {
3941
2697
  const gl = this.gl;
3942
2698
  this.invalidateProgramState();
3943
2699
  this.boundTexCache.fill(null);
3944
2700
  this.activeTexUnit = -1;
2701
+ if (typeof gl.bindFramebuffer === "function") gl.bindFramebuffer(gl.FRAMEBUFFER, this.activeFbo);
2702
+ if (typeof gl.pixelStorei === "function") {
2703
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
2704
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
2705
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
2706
+ const gl2 = gl;
2707
+ if (gl2.UNPACK_ROW_LENGTH !== void 0) gl.pixelStorei(gl2.UNPACK_ROW_LENGTH, 0);
2708
+ }
3945
2709
  gl.viewport(0, 0, this.width, this.height);
3946
2710
  gl.enable(gl.BLEND);
3947
2711
  this.ensureBatchState();
@@ -3951,11 +2715,7 @@ var RendererGl = class extends EventEmitter {
3951
2715
  if (this.curBlend === mode) return;
3952
2716
  this.flushAll();
3953
2717
  this.curBlend = mode;
3954
- if (this.batchStateBound) {
3955
- const gl = this.gl;
3956
- if (mode === BlendModes.ADD) gl.blendFunc(gl.ONE, gl.ONE);
3957
- else gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
3958
- }
2718
+ if (this.batchStateBound) applyGlBlendMode(this.gl, mode);
3959
2719
  }
3960
2720
  assignTextureUnit(tex) {
3961
2721
  for (let i = 0; i < this.batchTexCount; i++) if (this.batchTexs[i] === tex) return i;
@@ -4012,11 +2772,7 @@ var RendererGl = class extends EventEmitter {
4012
2772
  const msdf = this.msdfBatcher;
4013
2773
  if (!msdf || msdf.pending === 0 || this.contextLost) return;
4014
2774
  const count = msdf.pending;
4015
- if (!this.batchStateBound) {
4016
- const gl = this.gl;
4017
- if (this.curBlend === BlendModes.ADD) gl.blendFunc(gl.ONE, gl.ONE);
4018
- else gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
4019
- }
2775
+ if (!this.batchStateBound) applyGlBlendMode(this.gl, this.curBlend);
4020
2776
  if (msdf.flush(this.width, this.height)) {
4021
2777
  this.curDrawCalls++;
4022
2778
  this.curFlushes++;
@@ -4029,11 +2785,7 @@ var RendererGl = class extends EventEmitter {
4029
2785
  const paa = this.pixelAaBatcher;
4030
2786
  if (!paa || paa.pending === 0 || this.contextLost) return;
4031
2787
  const count = paa.pending;
4032
- if (!this.batchStateBound) {
4033
- const gl = this.gl;
4034
- if (this.curBlend === BlendModes.ADD) gl.blendFunc(gl.ONE, gl.ONE);
4035
- else gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
4036
- }
2788
+ if (!this.batchStateBound) applyGlBlendMode(this.gl, this.curBlend);
4037
2789
  if (paa.flush(this.width, this.height)) {
4038
2790
  this.curDrawCalls++;
4039
2791
  this.curFlushes++;
@@ -4689,6 +3441,272 @@ var RendererGl = class extends EventEmitter {
4689
3441
  this.invalidateProgramState();
4690
3442
  }
4691
3443
  }
3444
+ ensureInstancedResources() {
3445
+ if (!this.isWebGL2 || this.contextLost) return false;
3446
+ if (this.instProgram && this.instVao && this.instDataVbo) return true;
3447
+ const gl2 = this.gl;
3448
+ const vs = compileShader(gl2, gl2.VERTEX_SHADER, INST_VERT_SRC);
3449
+ const fs = compileShader(gl2, gl2.FRAGMENT_SHADER, INST_FRAG_SRC);
3450
+ const prog = gl2.createProgram();
3451
+ if (!prog) return false;
3452
+ gl2.attachShader(prog, vs);
3453
+ gl2.attachShader(prog, fs);
3454
+ gl2.linkProgram(prog);
3455
+ gl2.deleteShader(vs);
3456
+ gl2.deleteShader(fs);
3457
+ if (!gl2.getProgramParameter(prog, gl2.LINK_STATUS)) {
3458
+ gl2.deleteProgram(prog);
3459
+ return false;
3460
+ }
3461
+ gl2.useProgram(prog);
3462
+ const uSampler = gl2.getUniformLocation(prog, "uSampler");
3463
+ if (uSampler) gl2.uniform1i(uSampler, 0);
3464
+ this.instUres = gl2.getUniformLocation(prog, "uResolution");
3465
+ this.instProgram = prog;
3466
+ const cornerVbo = gl2.createBuffer();
3467
+ const dataVbo = gl2.createBuffer();
3468
+ const vao = gl2.createVertexArray();
3469
+ if (!cornerVbo || !dataVbo || !vao || !this.quadIbo) return false;
3470
+ this.instCornerVbo = cornerVbo;
3471
+ this.instDataVbo = dataVbo;
3472
+ this.instVao = vao;
3473
+ gl2.bindVertexArray(vao);
3474
+ gl2.bindBuffer(gl2.ARRAY_BUFFER, cornerVbo);
3475
+ gl2.bufferData(gl2.ARRAY_BUFFER, new Float32Array([
3476
+ 0,
3477
+ 0,
3478
+ 1,
3479
+ 0,
3480
+ 1,
3481
+ 1,
3482
+ 0,
3483
+ 1
3484
+ ]), gl2.STATIC_DRAW);
3485
+ gl2.enableVertexAttribArray(0);
3486
+ gl2.vertexAttribPointer(0, 2, gl2.FLOAT, false, 8, 0);
3487
+ gl2.bindBuffer(gl2.ARRAY_BUFFER, dataVbo);
3488
+ gl2.enableVertexAttribArray(1);
3489
+ gl2.vertexAttribPointer(1, 4, gl2.FLOAT, false, INST_STRIDE, 0);
3490
+ gl2.vertexAttribDivisor(1, 1);
3491
+ gl2.enableVertexAttribArray(2);
3492
+ gl2.vertexAttribPointer(2, 2, gl2.FLOAT, false, INST_STRIDE, 16);
3493
+ gl2.vertexAttribDivisor(2, 1);
3494
+ gl2.enableVertexAttribArray(3);
3495
+ gl2.vertexAttribPointer(3, 4, gl2.FLOAT, false, INST_STRIDE, 24);
3496
+ gl2.vertexAttribDivisor(3, 1);
3497
+ gl2.enableVertexAttribArray(4);
3498
+ gl2.vertexAttribPointer(4, 4, gl2.UNSIGNED_BYTE, true, INST_STRIDE, 40);
3499
+ gl2.vertexAttribDivisor(4, 1);
3500
+ gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, this.quadIbo);
3501
+ gl2.bindVertexArray(null);
3502
+ this.invalidateProgramState();
3503
+ return true;
3504
+ }
3505
+ renderInstancedBatch(batch, m, alpha) {
3506
+ const cols = batch.columns;
3507
+ if (!cols || cols.count <= 0) return;
3508
+ const src = batch.texture?.source?.[0];
3509
+ if (!src) return;
3510
+ const glTex = this.ensureGlTexture(src);
3511
+ if (!glTex) return;
3512
+ this.setBlend(batch.blendMode);
3513
+ const n = Math.min(cols.count, batch.maxCount, cols.x.length, cols.y.length);
3514
+ if (n <= 0) return;
3515
+ if (!this.ensureInstancedResources()) {
3516
+ const unit = this.assignTextureUnit(glTex);
3517
+ for (let i = 0; i < n; i++) {
3518
+ const s = cols.order ? cols.order[i] : i;
3519
+ const fr = cols.frameIndex ? batch.texture.get(cols.frameIndex[s]) : batch.defaultFrame;
3520
+ const sx = cols.scaleX ? cols.scaleX[s] : 1;
3521
+ const sy = cols.scaleY ? cols.scaleY[s] : sx;
3522
+ const a = alpha * (cols.alpha ? cols.alpha[s] : 1);
3523
+ if (a <= 0) continue;
3524
+ const rgb = cols.tint ? cols.tint[s] : WHITE_RGB;
3525
+ const abgr = packColorAbgr(rgb, a);
3526
+ const w = fr.width * sx;
3527
+ const h = fr.height * sy;
3528
+ const x0 = cols.x[s] - w * batch.originX;
3529
+ const y0 = cols.y[s] - h * batch.originY;
3530
+ this.pushQuad(m, x0, y0, x0 + w, y0 + h, fr.u0, fr.v0, fr.u1, fr.v1, abgr, unit, MODE_MULTIPLY);
3531
+ }
3532
+ return;
3533
+ }
3534
+ this.flushAll();
3535
+ if (this.instF32.length < n * INST_FLOATS) {
3536
+ let cap = Math.max(1024, this.instF32.length / INST_FLOATS);
3537
+ while (cap < n) cap <<= 1;
3538
+ this.instStagingBuf = new ArrayBuffer(cap * INST_STRIDE);
3539
+ this.instF32 = new Float32Array(this.instStagingBuf);
3540
+ this.instU32 = new Uint32Array(this.instStagingBuf);
3541
+ }
3542
+ const f32 = this.instF32;
3543
+ const u32 = this.instU32;
3544
+ const ma = m.a, mb = m.b, mc = m.c, md = m.d, mtx = m.tx, mty = m.ty;
3545
+ const oxRatio = batch.originX;
3546
+ const oyRatio = batch.originY;
3547
+ let vis = 0;
3548
+ for (let i = 0; i < n; i++) {
3549
+ const s = cols.order ? cols.order[i] : i;
3550
+ const instA = alpha * (cols.alpha ? cols.alpha[s] : 1);
3551
+ if (instA <= 0) continue;
3552
+ const fr = cols.frameIndex ? batch.texture.get(cols.frameIndex[s]) : batch.defaultFrame;
3553
+ const sx = (cols.scaleX ? cols.scaleX[s] : 1) * fr.width;
3554
+ const sy = (cols.scaleY ? cols.scaleY[s] : cols.scaleX ? cols.scaleX[s] : 1) * fr.height;
3555
+ const rot = cols.rotation ? cols.rotation[s] : 0;
3556
+ const px = cols.x[s];
3557
+ const py = cols.y[s];
3558
+ let la, lb, lc, ld;
3559
+ if (rot === 0) {
3560
+ la = sx;
3561
+ lb = 0;
3562
+ lc = 0;
3563
+ ld = sy;
3564
+ } else {
3565
+ const cs = Math.cos(rot), sn = Math.sin(rot);
3566
+ la = cs * sx;
3567
+ lb = sn * sx;
3568
+ lc = -sn * sy;
3569
+ ld = cs * sy;
3570
+ }
3571
+ const ltx = px - la * oxRatio - lc * oyRatio;
3572
+ const lty = py - lb * oxRatio - ld * oyRatio;
3573
+ const ga = ma * la + mc * lb;
3574
+ const gb = mb * la + md * lb;
3575
+ const gc = ma * lc + mc * ld;
3576
+ const gd = mb * lc + md * ld;
3577
+ const gtx = ma * ltx + mc * lty + mtx;
3578
+ const gty = mb * ltx + md * lty + mty;
3579
+ const rgb = cols.tint ? cols.tint[s] : WHITE_RGB;
3580
+ const base = vis * INST_FLOATS;
3581
+ f32[base] = ga;
3582
+ f32[base + 1] = gb;
3583
+ f32[base + 2] = gc;
3584
+ f32[base + 3] = gd;
3585
+ f32[base + 4] = gtx;
3586
+ f32[base + 5] = gty;
3587
+ f32[base + 6] = fr.u0;
3588
+ f32[base + 7] = fr.v0;
3589
+ f32[base + 8] = fr.u1;
3590
+ f32[base + 9] = fr.v1;
3591
+ u32[base + 10] = packColorAbgr(rgb, instA);
3592
+ vis++;
3593
+ }
3594
+ if (vis === 0) return;
3595
+ const gl2 = this.gl;
3596
+ gl2.useProgram(this.instProgram);
3597
+ if (this.instUres) gl2.uniform2f(this.instUres, this.width, this.height);
3598
+ applyGlBlendMode(gl2, this.curBlend);
3599
+ this.bindTextureAt(0, glTex);
3600
+ gl2.bindVertexArray(this.instVao);
3601
+ gl2.bindBuffer(gl2.ARRAY_BUFFER, this.instDataVbo);
3602
+ gl2.bufferData(gl2.ARRAY_BUFFER, f32.subarray(0, vis * INST_FLOATS), gl2.STREAM_DRAW);
3603
+ gl2.drawElementsInstanced(gl2.TRIANGLES, 6, gl2.UNSIGNED_SHORT, 0, vis);
3604
+ gl2.bindVertexArray(null);
3605
+ this.curDrawCalls++;
3606
+ this.curFlushes++;
3607
+ this.curQuads += vis;
3608
+ this.curTris += vis * 2;
3609
+ this.invalidateProgramState();
3610
+ }
3611
+ /** Create an offscreen WebGL framebuffer target backed by a registered Stage `Texture` (`key`). */
3612
+ createRenderTarget(key, width, height, textures, filterMode = FilterMode.LINEAR) {
3613
+ const w = Math.max(1, Math.round(width));
3614
+ const h = Math.max(1, Math.round(height));
3615
+ const gl = this.gl;
3616
+ const fbo = gl.createFramebuffer();
3617
+ const glTex = gl.createTexture();
3618
+ if (!fbo || !glTex) throw new Error("Stage: failed to allocate WebGL RenderTarget");
3619
+ this.bindTextureAt(0, glTex);
3620
+ const filt = filterMode === FilterMode.NEAREST ? gl.NEAREST : gl.LINEAR;
3621
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
3622
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
3623
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filt);
3624
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filt);
3625
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
3626
+ gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
3627
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glTex, 0);
3628
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
3629
+ const dummyStub = {
3630
+ width: w,
3631
+ height: h
3632
+ };
3633
+ const tex = textures.addImage(key, dummyStub, { filterMode });
3634
+ if (!tex) throw new Error("Stage: failed to register WebGL RenderTarget texture");
3635
+ const src = tex.source[0];
3636
+ src.glTexture = glTex;
3637
+ src.glWidth = w;
3638
+ src.glHeight = h;
3639
+ src.dirty = false;
3640
+ const baseFrame = tex.get();
3641
+ baseFrame.v0 = 1;
3642
+ baseFrame.v1 = 0;
3643
+ return {
3644
+ key,
3645
+ width: w,
3646
+ height: h,
3647
+ texture: tex,
3648
+ _fbo: fbo,
3649
+ destroy: () => {
3650
+ try {
3651
+ if (!this.contextLost) {
3652
+ gl.deleteFramebuffer(fbo);
3653
+ gl.deleteTexture(glTex);
3654
+ }
3655
+ src.glTexture = null;
3656
+ textures.remove(key);
3657
+ } catch {}
3658
+ }
3659
+ };
3660
+ }
3661
+ /** Render a `DisplayList` (or custom pass callback) into an offscreen `StageRenderTarget` FBO. */
3662
+ renderToTarget(target, content, camera) {
3663
+ if (this.contextLost) return;
3664
+ this.flushAll();
3665
+ const gl = this.gl;
3666
+ const src = target.texture.source[0];
3667
+ if (!src?.glTexture) return;
3668
+ let fbo = target._fbo;
3669
+ if (!fbo) {
3670
+ const created = gl.createFramebuffer();
3671
+ if (!created) return;
3672
+ gl.bindFramebuffer(gl.FRAMEBUFFER, created);
3673
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, src.glTexture, 0);
3674
+ fbo = created;
3675
+ target._fbo = fbo;
3676
+ } else gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
3677
+ const prevFbo = this.activeFbo;
3678
+ const prevW = this.width;
3679
+ const prevH = this.height;
3680
+ this.activeFbo = fbo;
3681
+ this.width = target.width;
3682
+ this.height = target.height;
3683
+ this.updateProjection();
3684
+ gl.viewport(0, 0, target.width, target.height);
3685
+ this.syncClipBounds();
3686
+ camera.syncMetrics();
3687
+ if (camera.transparent) gl.clearColor(0, 0, 0, 0);
3688
+ else {
3689
+ const bg = camera.backgroundColor;
3690
+ gl.clearColor(bg.r * bg.a, bg.g * bg.a, bg.b * bg.a, bg.a);
3691
+ }
3692
+ gl.clear(gl.COLOR_BUFFER_BIT);
3693
+ this.invalidateProgramState();
3694
+ if (typeof content === "function") content(this, camera);
3695
+ else {
3696
+ const list = content.sorted();
3697
+ const camAlpha = camera.alpha;
3698
+ for (let i = 0; i < list.length; i++) this.renderNode(list[i], camera, null, camAlpha, 0);
3699
+ }
3700
+ this.flushAll();
3701
+ this.activeFbo = prevFbo;
3702
+ gl.bindFramebuffer(gl.FRAMEBUFFER, prevFbo);
3703
+ this.width = prevW;
3704
+ this.height = prevH;
3705
+ this.updateProjection();
3706
+ gl.viewport(0, 0, prevW, prevH);
3707
+ this.invalidateProgramState();
3708
+ this.applyCurrentScissor();
3709
+ }
4692
3710
  renderBlitter(blitter, m, alpha) {
4693
3711
  const list = blitter.children.list;
4694
3712
  if (!list.length) return;
@@ -4766,6 +3784,9 @@ var RendererGl = class extends EventEmitter {
4766
3784
  case "Blitter":
4767
3785
  this.renderBlitter(obj, m, effAlpha);
4768
3786
  break;
3787
+ case "InstancedBatch":
3788
+ this.renderInstancedBatch(obj, m, effAlpha);
3789
+ break;
4769
3790
  case "Container": {
4770
3791
  const cont = obj;
4771
3792
  const mask = cont.clipMask;
@@ -4792,10 +3813,14 @@ var RendererGl = class extends EventEmitter {
4792
3813
  if (clipped) this.popScissor();
4793
3814
  break;
4794
3815
  }
4795
- case "CustomPass":
3816
+ case "CustomPass": {
3817
+ const pass = obj;
4796
3818
  this.flushAll();
4797
- obj.onRender(obj, this, camera);
4798
- this.invalidateProgramState();
3819
+ pass.onRender(pass, this, camera);
3820
+ if (pass.restoreState) this.restoreState();
3821
+ else this.invalidateProgramState();
3822
+ break;
3823
+ }
4799
3824
  }
4800
3825
  }
4801
3826
  render(displayList, camera) {
@@ -4861,13 +3886,17 @@ var RendererGl = class extends EventEmitter {
4861
3886
  const gl2 = gl;
4862
3887
  if (this.quadVao) gl2.deleteVertexArray(this.quadVao);
4863
3888
  if (this.polyVao) gl2.deleteVertexArray(this.polyVao);
3889
+ if (this.instVao) gl2.deleteVertexArray(this.instVao);
4864
3890
  }
4865
3891
  if (this.vbo) gl.deleteBuffer(this.vbo);
4866
3892
  if (this.quadIbo) gl.deleteBuffer(this.quadIbo);
4867
3893
  if (this.polyIbo) gl.deleteBuffer(this.polyIbo);
3894
+ if (this.instCornerVbo) gl.deleteBuffer(this.instCornerVbo);
3895
+ if (this.instDataVbo) gl.deleteBuffer(this.instDataVbo);
4868
3896
  if (this.dummyTex) gl.deleteTexture(this.dummyTex);
4869
3897
  if (this.program) gl.deleteProgram(this.program);
4870
3898
  if (this.singleProgram) gl.deleteProgram(this.singleProgram);
3899
+ if (this.instProgram) gl.deleteProgram(this.instProgram);
4871
3900
  } catch {}
4872
3901
  this.quadVao = null;
4873
3902
  this.polyVao = null;
@@ -4930,7 +3959,7 @@ function roundedRectPath(ctx, x, y, w, h, radius) {
4930
3959
  ctx.quadraticCurveTo(x, y, x + r, y);
4931
3960
  ctx.closePath();
4932
3961
  }
4933
- var Renderer2D = class extends EventEmitter {
3962
+ var Renderer2D = class Renderer2D extends EventEmitter {
4934
3963
  type = 1;
4935
3964
  canvas;
4936
3965
  ctx;
@@ -5385,6 +4414,68 @@ var Renderer2D = class extends EventEmitter {
5385
4414
  case 21: if (lineA > 0 && lineW > 0) ctx.stroke();
5386
4415
  }
5387
4416
  }
4417
+ renderInstancedBatch(batch, ctx) {
4418
+ const cols = batch.columns;
4419
+ if (!cols || cols.count <= 0) return;
4420
+ const baseAlpha = ctx.globalAlpha;
4421
+ const n = Math.min(cols.count, batch.maxCount, cols.x.length, cols.y.length);
4422
+ for (let i = 0; i < n; i++) {
4423
+ const s = cols.order ? cols.order[i] : i;
4424
+ const a = baseAlpha * (cols.alpha ? cols.alpha[s] : 1);
4425
+ if (a <= 0) continue;
4426
+ const fr = cols.frameIndex ? batch.texture.get(cols.frameIndex[s]) : batch.defaultFrame;
4427
+ const sx = cols.scaleX ? cols.scaleX[s] : 1;
4428
+ const sy = cols.scaleY ? cols.scaleY[s] : sx;
4429
+ const rot = cols.rotation ? cols.rotation[s] : 0;
4430
+ const px = cols.x[s];
4431
+ const py = cols.y[s];
4432
+ ctx.save();
4433
+ ctx.globalAlpha = a;
4434
+ ctx.imageSmoothingEnabled = fr.source.filterMode !== FilterMode.NEAREST;
4435
+ ctx.translate(px, py);
4436
+ if (rot !== 0) ctx.rotate(rot);
4437
+ if (sx !== 1 || sy !== 1) ctx.scale(sx, sy);
4438
+ ctx.drawImage(fr.source.image, fr.cutX, fr.cutY, fr.cutWidth, fr.cutHeight, -fr.width * batch.originX, -fr.height * batch.originY, fr.width, fr.height);
4439
+ ctx.restore();
4440
+ }
4441
+ ctx.globalAlpha = baseAlpha;
4442
+ }
4443
+ /** Create an offscreen Canvas2D render target backed by a registered Stage `Texture` (`key`). */
4444
+ createRenderTarget(key, width, height, textures, filterMode = FilterMode.LINEAR) {
4445
+ const w = Math.max(1, Math.round(width));
4446
+ const h = Math.max(1, Math.round(height));
4447
+ const doc = this.canvas?.ownerDocument ?? (typeof document !== "undefined" ? document : void 0);
4448
+ if (!doc) throw new Error("Stage: ownerDocument unavailable for Canvas2D RenderTarget");
4449
+ const rtCanvas = doc.createElement("canvas");
4450
+ rtCanvas.width = w;
4451
+ rtCanvas.height = h;
4452
+ const tex = textures.addCanvas(key, rtCanvas);
4453
+ if (!tex) throw new Error("Stage: failed to register Canvas2D RenderTarget texture");
4454
+ tex.source[0]?.setFilter(filterMode);
4455
+ const rtRenderer = new Renderer2D(rtCanvas, w, h);
4456
+ return {
4457
+ key,
4458
+ width: w,
4459
+ height: h,
4460
+ texture: tex,
4461
+ _rtRenderer: rtRenderer,
4462
+ destroy: () => {
4463
+ rtRenderer.destroy();
4464
+ textures.remove(key);
4465
+ }
4466
+ };
4467
+ }
4468
+ /** Render a `DisplayList` (or callback) into an offscreen `StageRenderTarget` in Canvas2D / Headless Node. */
4469
+ renderToTarget(target, content, camera) {
4470
+ const sub = target._rtRenderer;
4471
+ if (!sub) return;
4472
+ if (typeof content === "function") {
4473
+ camera.syncMetrics();
4474
+ content(sub, camera);
4475
+ } else sub.render(content, camera);
4476
+ const src = target.texture.source[0];
4477
+ if (src) src.dirty = true;
4478
+ }
5388
4479
  renderBlitter(blitter, ctx) {
5389
4480
  const list = blitter.children.list;
5390
4481
  const baseAlpha = ctx.globalAlpha;
@@ -5438,6 +4529,8 @@ var Renderer2D = class extends EventEmitter {
5438
4529
  }
5439
4530
  ctx.globalAlpha *= obj.alpha;
5440
4531
  if (obj.blendMode === BlendModes.ADD) ctx.globalCompositeOperation = "lighter";
4532
+ else if (obj.blendMode === BlendModes.MULTIPLY) ctx.globalCompositeOperation = "multiply";
4533
+ else if (obj.blendMode === BlendModes.SCREEN) ctx.globalCompositeOperation = "screen";
5441
4534
  if (obj.x !== 0 || obj.y !== 0) ctx.translate(obj.x, obj.y);
5442
4535
  if (obj.rotation !== 0) ctx.rotate(obj.rotation);
5443
4536
  if (obj.scaleX !== 1 || obj.scaleY !== 1) ctx.scale(obj.scaleX, obj.scaleY);
@@ -5469,6 +4562,9 @@ var Renderer2D = class extends EventEmitter {
5469
4562
  case "Blitter":
5470
4563
  this.renderBlitter(obj, ctx);
5471
4564
  break;
4565
+ case "InstancedBatch":
4566
+ this.renderInstancedBatch(obj, ctx);
4567
+ break;
5472
4568
  case "Container": {
5473
4569
  const list = obj.sortedChildren();
5474
4570
  for (let i = 0; i < list.length; i++) this.renderNode(list[i], camera, ctx, false);
@@ -5542,27 +4638,96 @@ var Pointer = class {
5542
4638
  };
5543
4639
  }
5544
4640
  };
4641
+ function normalizeKeyToken(codeOrKey) {
4642
+ const raw = String(codeOrKey ?? "").trim();
4643
+ if (!raw) return "";
4644
+ if (raw === " ") return "SPACE";
4645
+ const up = raw.toUpperCase();
4646
+ if (up.length === 1 && up >= "A" && up <= "Z") return `KEY${up}`;
4647
+ if (up.length === 1 && up >= "0" && up <= "9") return `DIGIT${up}`;
4648
+ return up;
4649
+ }
5545
4650
  var KeyboardPlugin = class extends EventEmitter {
5546
4651
  win;
4652
+ getFrameSeq;
4653
+ downCodes = /* @__PURE__ */ new Set();
4654
+ pressedFrame = /* @__PURE__ */ new Map();
4655
+ releasedFrame = /* @__PURE__ */ new Map();
5547
4656
  onKeyDown;
5548
4657
  onKeyUp;
5549
- constructor(win) {
4658
+ onBlur;
4659
+ constructor(win, getFrameSeq = () => 0) {
5550
4660
  super();
5551
4661
  this.win = win;
4662
+ this.getFrameSeq = getFrameSeq;
5552
4663
  this.onKeyDown = (e) => {
4664
+ const code = normalizeKeyToken(e.code || e.key);
4665
+ if (code) {
4666
+ if (!this.downCodes.has(code)) {
4667
+ this.downCodes.add(code);
4668
+ this.pressedFrame.set(code, this.getFrameSeq());
4669
+ }
4670
+ }
5553
4671
  this.emit("keydown", e);
5554
- if (e.code) this.emit(`keydown-${e.code.toUpperCase()}`, e);
4672
+ if (code) this.emit(`keydown-${code}`, e);
5555
4673
  };
5556
4674
  this.onKeyUp = (e) => {
4675
+ const code = normalizeKeyToken(e.code || e.key);
4676
+ if (code && this.downCodes.delete(code)) this.releasedFrame.set(code, this.getFrameSeq());
5557
4677
  this.emit("keyup", e);
5558
- if (e.code) this.emit(`keyup-${e.code.toUpperCase()}`, e);
4678
+ if (code) this.emit(`keyup-${code}`, e);
4679
+ };
4680
+ this.onBlur = () => {
4681
+ this.resetKeys();
5559
4682
  };
5560
4683
  win.addEventListener("keydown", this.onKeyDown);
5561
4684
  win.addEventListener("keyup", this.onKeyUp);
4685
+ win.addEventListener("blur", this.onBlur);
4686
+ }
4687
+ /** Returns `true` while `codeOrKey` (e.g. `'KeyW'`, `'W'`, `'ArrowLeft'`, `'Space'`) is held down. */
4688
+ isDown(codeOrKey) {
4689
+ const code = normalizeKeyToken(codeOrKey);
4690
+ return code ? this.downCodes.has(code) : false;
4691
+ }
4692
+ /** Returns `true` only on the simulation frame during which `codeOrKey` transitioned up -> down. */
4693
+ justPressed(codeOrKey) {
4694
+ const code = normalizeKeyToken(codeOrKey);
4695
+ if (!code) return false;
4696
+ return this.pressedFrame.get(code) === this.getFrameSeq();
4697
+ }
4698
+ /** Returns `true` only on the simulation frame during which `codeOrKey` transitioned down -> up. */
4699
+ justReleased(codeOrKey) {
4700
+ const code = normalizeKeyToken(codeOrKey);
4701
+ if (!code) return false;
4702
+ return this.releasedFrame.get(code) === this.getFrameSeq();
4703
+ }
4704
+ /** Synthesize a deterministic key event from an `InputProvider` (headless timeline, replay, or Mod controller). */
4705
+ injectKey(type, codeOrKey, key) {
4706
+ const code = normalizeKeyToken(codeOrKey);
4707
+ if (!code) return;
4708
+ const synth = {
4709
+ type,
4710
+ code: codeOrKey,
4711
+ key: key ?? codeOrKey,
4712
+ repeat: type === "keydown" && this.downCodes.has(code),
4713
+ preventDefault() {}
4714
+ };
4715
+ if (type === "keydown") this.onKeyDown(synth);
4716
+ else this.onKeyUp(synth);
4717
+ }
4718
+ /** Release all currently held keys (called automatically on window blur). */
4719
+ resetKeys() {
4720
+ const f = this.getFrameSeq();
4721
+ for (const c of this.downCodes) this.releasedFrame.set(c, f);
4722
+ this.downCodes.clear();
5562
4723
  }
5563
4724
  destroy() {
5564
4725
  this.win.removeEventListener("keydown", this.onKeyDown);
5565
4726
  this.win.removeEventListener("keyup", this.onKeyUp);
4727
+ this.win.removeEventListener("blur", this.onBlur);
4728
+ this.downCodes.clear();
4729
+ this.pressedFrame.clear();
4730
+ this.releasedFrame.clear();
5566
4731
  this.removeAllListeners();
5567
4732
  }
5568
4733
  };
@@ -5581,7 +4746,7 @@ var InputPlugin = class extends EventEmitter {
5581
4746
  coalescedScratch = [];
5582
4747
  resizeObserver = null;
5583
4748
  lastTouchMs = -1e9;
5584
- constructor(canvas, win, getCamera, config = {}) {
4749
+ constructor(canvas, win, getCamera, config = {}, getFrameSeq = () => 0) {
5585
4750
  super();
5586
4751
  this.canvas = canvas;
5587
4752
  this.win = win;
@@ -5599,7 +4764,7 @@ var InputPlugin = class extends EventEmitter {
5599
4764
  pointers: [this.mousePointer, ...this.touchPointers],
5600
4765
  canvas
5601
4766
  };
5602
- this.keyboard = config.keyboard === false ? null : new KeyboardPlugin(win);
4767
+ this.keyboard = config.keyboard === false ? null : new KeyboardPlugin(win, getFrameSeq);
5603
4768
  const preventDown = config.mouse?.preventDefaultDown ?? false;
5604
4769
  const preventMove = config.mouse?.preventDefaultMove ?? false;
5605
4770
  const preventUp = config.mouse?.preventDefaultUp ?? false;
@@ -6300,11 +5465,14 @@ var GameObjectFactory = class {
6300
5465
  blitter(x, y, key) {
6301
5466
  return this.register(new BlitterObject(this.scene, x, y, key));
6302
5467
  }
5468
+ instancedBatch(key, maxCount = 1024, frame) {
5469
+ return this.register(new InstancedBatchObject(this.scene, key, maxCount, frame));
5470
+ }
6303
5471
  container(x = 0, y = 0, children) {
6304
5472
  return this.register(new Container(this.scene, x, y, children));
6305
5473
  }
6306
- customPass(onRender) {
6307
- return this.register(new CustomPassObject(this.scene, onRender));
5474
+ customPass(onRender, options) {
5475
+ return this.register(new CustomPassObject(this.scene, onRender, options));
6308
5476
  }
6309
5477
  };
6310
5478
  var ScaleManager = class extends EventEmitter {
@@ -6606,6 +5774,7 @@ var Game = class {
6606
5774
  cache;
6607
5775
  events = new EventEmitter();
6608
5776
  clock = new EngineClock();
5777
+ kernel;
6609
5778
  scene;
6610
5779
  loop;
6611
5780
  transparent;
@@ -6646,6 +5815,12 @@ var Game = class {
6646
5815
  this.backgroundColor = config.backgroundColor;
6647
5816
  const wantType = config.type ?? 0;
6648
5817
  if (wantType === 1) this.renderer = new Renderer2D(this.canvas, width, height, config.context);
5818
+ else if (wantType === 3 && config.gpuDevice) this.renderer = new RendererWebGpu(this.canvas, width, height, {
5819
+ device: config.gpuDevice,
5820
+ context: config.gpuContext,
5821
+ format: config.gpuFormat,
5822
+ transparent: this.transparent
5823
+ });
6649
5824
  else try {
6650
5825
  this.renderer = new RendererGl(this.canvas, width, height, {
6651
5826
  transparent: this.transparent,
@@ -6667,7 +5842,9 @@ var Game = class {
6667
5842
  this.scale = new ScaleManager(this.canvas, this.renderer, width, height, zoom);
6668
5843
  this.cache = { json: new JsonCache() };
6669
5844
  this.scene = new SceneManager(this);
6670
- this.input = new InputPlugin(this.canvas, this.win, () => this.scene.getPrimaryCamera(), config.input);
5845
+ this.input = new InputPlugin(this.canvas, this.win, () => this.scene.getPrimaryCamera(), config.input, () => this.clock.frameSeq);
5846
+ this.kernel = new StageKernel(this);
5847
+ if (config.plugins) for (let i = 0; i < config.plugins.length; i++) this.kernel.use(config.plugins[i]);
6671
5848
  this.loop = new GameLoop(this, this.win);
6672
5849
  config.callbacks?.preBoot?.(this);
6673
5850
  const initialScenes = config.scene ? Array.isArray(config.scene) ? config.scene : [config.scene] : [];
@@ -6682,10 +5859,11 @@ var Game = class {
6682
5859
  }
6683
5860
  if (autoStart) this.loop.start();
6684
5861
  }
6685
- step(time, delta) {
6686
- if (this.pendingDestroy || this.destroyed) return;
6687
- if (this.isPaused) return;
5862
+ /** Advance simulation, tweens, kernel plugins, and camera follow by one deterministic tick WITHOUT rendering pixels. */
5863
+ stepSimOnly(time, delta) {
5864
+ if (this.pendingDestroy || this.destroyed || this.isPaused) return false;
6688
5865
  this.clock.advance(time, delta);
5866
+ this.kernel._prestep(time, delta);
6689
5867
  this.events.emit("prestep", time, delta);
6690
5868
  const scenes = this.scene.scenes;
6691
5869
  for (let i = 0; i < scenes.length; i++) {
@@ -6694,15 +5872,23 @@ var Game = class {
6694
5872
  sc.events.emit("preupdate", time, delta);
6695
5873
  if (sc.tweens.hasActive) sc.tweens.step(this.clock.lastDeltaMs);
6696
5874
  sc.update?.(time, delta);
5875
+ this.kernel._updateScene(sc, time, delta);
5876
+ sc.cameras.main.stepFollow(this.clock.lastDeltaMs);
6697
5877
  sc.events.emit("update", time, delta);
6698
5878
  sc.events.emit("postupdate", time, delta);
6699
5879
  }
6700
5880
  }
5881
+ return true;
5882
+ }
5883
+ step(time, delta) {
5884
+ if (!this.stepSimOnly(time, delta)) return;
5885
+ const scenes = this.scene.scenes;
6701
5886
  this.events.emit("prerender", this.renderer);
6702
5887
  for (let i = 0; i < scenes.length; i++) {
6703
5888
  const sc = scenes[i];
6704
5889
  if (sc.sys.settings.status === Scenes.RUNNING) this.renderer.render(sc._displayList, sc.cameras.main);
6705
5890
  }
5891
+ this.kernel._postrender(this.renderer);
6706
5892
  this.events.emit("postrender", this.renderer);
6707
5893
  }
6708
5894
  destroy(removeCanvas = false) {
@@ -6711,6 +5897,7 @@ var Game = class {
6711
5897
  this.destroyed = true;
6712
5898
  this.loop.destroy();
6713
5899
  this.events.emit("destroy", this);
5900
+ this.kernel.dispose();
6714
5901
  this.scene.destroy();
6715
5902
  this.input.destroy();
6716
5903
  this.textures.destroy();
@@ -6722,4 +5909,4 @@ var Game = class {
6722
5909
  else if (removeCanvas) this.canvas.remove();
6723
5910
  }
6724
5911
  };
6725
- export { TileSpriteObject as A, Graphics as C, PanelObject as D, NineSliceObject as E, TextureManager as F, TextureSource as I, CanvasTexture as M, Frame as N, RectangleObject as O, Texture as P, DisplayObject as S, MsdfIconObject as T, SdfPanelBatcher as _, JsonCache as a, CustomPassObject as b, Scene as c, KeyboardPlugin as d, Pointer as f, MsdfIconBatcher as g, PixelAaBatcher as h, GameObjectFactory as i, Camera as j, TextObject as k, SceneManager as l, RendererGl as m, Game as n, LoaderPlugin as o, Renderer2D as p, GameLoop as r, ScaleManager as s, EngineClock as t, InputPlugin as u, BlitterObject as v, ImageObject as w, DisplayList as x, Container as y };
5912
+ export { TextureSource as C, TextureManager as S, SdfPanelBatcher as _, JsonCache as a, Frame as b, Scene as c, KeyboardPlugin as d, Pointer as f, MsdfIconBatcher as g, PixelAaBatcher as h, GameObjectFactory as i, SceneManager as l, RendererGl as m, Game as n, LoaderPlugin as o, Renderer2D as p, GameLoop as r, ScaleManager as s, EngineClock as t, InputPlugin as u, Camera as v, Texture as x, CanvasTexture as y };