@holtjs/stage 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lighting.js CHANGED
@@ -1,4 +1,5 @@
1
- import { o as FilterMode, r as BlendModes } from "./types-CXsCvp1p.js";
1
+ import { m as createMatrix2D, o as FilterMode, r as BlendModes } from "./types-CXsCvp1p.js";
2
+ import { c as InstancedBatchObject } from "./display-CZb3yen0.js";
2
3
  // src/lighting.ts
3
4
  function lerpChannel(a, b, t) {
4
5
  return Math.round(a + (b - a) * t) & 255;
@@ -241,18 +242,136 @@ function evaluateNormalLitPixel(baseRgb, normalX, normalY, normalZ, px, py, ambi
241
242
  const b = Math.min(255, Math.round(bb * accB * 255));
242
243
  return r << 16 | g << 8 | b;
243
244
  }
245
+ const RADIAL_GLOW_KEY = "__stage_radial_glow";
246
+ const RADIAL_GLOW_SIZE = 128;
247
+ function ensureRadialGlowTexture(textures) {
248
+ if (textures.exists(RADIAL_GLOW_KEY)) return true;
249
+ try {
250
+ const ct = textures.createCanvas(RADIAL_GLOW_KEY, RADIAL_GLOW_SIZE, RADIAL_GLOW_SIZE);
251
+ if (!ct) return false;
252
+ const ctx = ct.canvas.getContext("2d");
253
+ if (!ctx || typeof ctx.createImageData !== "function" || typeof ctx.putImageData !== "function") {
254
+ textures.remove(RADIAL_GLOW_KEY);
255
+ return false;
256
+ }
257
+ const img = ctx.createImageData(RADIAL_GLOW_SIZE, RADIAL_GLOW_SIZE);
258
+ const data = img.data;
259
+ const half = 63.5;
260
+ const invR = 1 / half;
261
+ for (let y = 0; y < RADIAL_GLOW_SIZE; y++) for (let x = 0; x < RADIAL_GLOW_SIZE; x++) {
262
+ const r = Math.hypot(x - half, y - half) * invR;
263
+ const idx = (y * RADIAL_GLOW_SIZE + x) * 4;
264
+ data[idx] = 255;
265
+ data[idx + 1] = 255;
266
+ data[idx + 2] = 255;
267
+ if (r >= 1) data[idx + 3] = 0;
268
+ else {
269
+ const u = 1 - r;
270
+ const falloff = u * u * (.78 + .22 * u * u);
271
+ data[idx + 3] = Math.round(falloff * 255);
272
+ }
273
+ }
274
+ ctx.putImageData(img, 0, 0);
275
+ ct.refresh();
276
+ ct.source[0]?.setFilter(FilterMode.LINEAR);
277
+ return true;
278
+ } catch {
279
+ if (textures.exists(RADIAL_GLOW_KEY)) textures.remove(RADIAL_GLOW_KEY);
280
+ return false;
281
+ }
282
+ }
283
+ function decomposeMatrix2D(m, out) {
284
+ out.x = m.tx;
285
+ out.y = m.ty;
286
+ const sx = Math.hypot(m.a, m.b);
287
+ const sy = Math.hypot(m.c, m.d);
288
+ out.scaleX = sx;
289
+ out.scaleY = sy;
290
+ const rotX = sx > 1e-6 ? Math.atan2(m.b, m.a) : 0;
291
+ const rotMinusSkewX = sy > 1e-6 ? Math.atan2(-m.c, m.d) : 0;
292
+ out.rotation = rotX;
293
+ out.skewY = 0;
294
+ out.skewX = rotX - rotMinusSkewX;
295
+ }
296
+ function computeNodeScreenMatrix(node, scene, out) {
297
+ node.getWorldTransformMatrix(out);
298
+ let sfX = node.scrollFactorX;
299
+ let sfY = node.scrollFactorY;
300
+ for (let cur = node.parentContainer; cur; cur = cur.parentContainer) if (cur.scrollFactorX === 0 && cur.scrollFactorY === 0) {
301
+ sfX = 0;
302
+ sfY = 0;
303
+ break;
304
+ }
305
+ const cam = scene.cameras.main;
306
+ if (sfX === 1 && sfY === 1) {
307
+ cam.syncMetrics();
308
+ const cm = cam.matrixCombined;
309
+ const na = cm.a * out.a + cm.c * out.b;
310
+ const nb = cm.b * out.a + cm.d * out.b;
311
+ const nc = cm.a * out.c + cm.c * out.d;
312
+ const nd = cm.b * out.c + cm.d * out.d;
313
+ const ntx = cm.a * out.tx + cm.c * out.ty + cm.tx;
314
+ const nty = cm.b * out.tx + cm.d * out.ty + cm.ty;
315
+ out.a = na;
316
+ out.b = nb;
317
+ out.c = nc;
318
+ out.d = nd;
319
+ out.tx = ntx;
320
+ out.ty = nty;
321
+ } else if (sfX !== 0 || sfY !== 0) {
322
+ const z = cam.zoom || 1;
323
+ const ox = cam.width * cam.originX;
324
+ const oy = cam.height * cam.originY;
325
+ const sx = cam.roundPixels ? Math.round(cam.scrollX) : cam.scrollX;
326
+ const sy = cam.roundPixels ? Math.round(cam.scrollY) : cam.scrollY;
327
+ const tx = (-sx * sfX - ox) * z + ox + cam.x;
328
+ const ty = (-sy * sfY - oy) * z + oy + cam.y;
329
+ out.a *= z;
330
+ out.b *= z;
331
+ out.c *= z;
332
+ out.d *= z;
333
+ out.tx = out.tx * z + tx;
334
+ out.ty = out.ty * z + ty;
335
+ }
336
+ out.scaleX = Math.hypot(out.a, out.b);
337
+ out.scaleY = Math.hypot(out.c, out.d);
338
+ return out;
339
+ }
244
340
  var Lighting2DSystem = class {
245
341
  scene;
246
342
  cycle;
247
343
  overlayImage;
344
+ /** Screen-space `BlendModes.ADD` container right above `overlayImage` so emissive flames/eyes shine crisp in pitch-black night! */
345
+ emissiveLayer;
248
346
  renderTarget;
249
347
  lightGraphics;
348
+ glowBatch = null;
349
+ glowCap = 128;
350
+ glowX = /* @__PURE__ */ new Float32Array(128);
351
+ glowY = /* @__PURE__ */ new Float32Array(128);
352
+ glowScale = /* @__PURE__ */ new Float32Array(128);
353
+ glowAlpha = /* @__PURE__ */ new Float32Array(128);
354
+ glowTint = /* @__PURE__ */ new Uint32Array(128);
250
355
  lights = /* @__PURE__ */ new Map();
356
+ emissives = /* @__PURE__ */ new Map();
357
+ activeScreenLights = [];
251
358
  resScale;
252
359
  viewportW;
253
360
  viewportH;
254
361
  elapsedSec = 0;
255
362
  manualAmbientRgb = null;
363
+ lastAmbientRgb = 0xfff8eb;
364
+ nextEmissiveSeq = 1;
365
+ matScratch = createMatrix2D();
366
+ decompScratch = {
367
+ x: 0,
368
+ y: 0,
369
+ scaleX: 1,
370
+ scaleY: 1,
371
+ rotation: 0,
372
+ skewX: 0,
373
+ skewY: 0
374
+ };
256
375
  constructor(scene, opts) {
257
376
  this.scene = scene;
258
377
  this.cycle = opts.cycle ?? new DayNightCycle();
@@ -266,18 +385,38 @@ var Lighting2DSystem = class {
266
385
  this.renderTarget = rtHost.createRenderTarget(rtKey, rtW, rtH, scene.textures, FilterMode.LINEAR);
267
386
  this.lightGraphics = scene.make.graphics({ add: false });
268
387
  this.lightGraphics.blendMode = BlendModes.ADD;
388
+ if (ensureRadialGlowTexture(scene.textures)) {
389
+ this.glowBatch = new InstancedBatchObject(scene, RADIAL_GLOW_KEY, this.glowCap);
390
+ this.glowBatch.blendMode = BlendModes.ADD;
391
+ }
392
+ const baseDepth = opts.depth ?? 5e5;
269
393
  this.overlayImage = scene.add.image(0, 0, rtKey);
270
394
  this.overlayImage.setOrigin(0, 0);
271
395
  this.overlayImage.setScrollFactor(0, 0);
272
396
  this.overlayImage.setDisplaySize(this.viewportW, this.viewportH);
273
397
  this.overlayImage.setBlendMode(BlendModes.MULTIPLY);
274
- if (opts.depth !== void 0) this.overlayImage.setDepth(opts.depth);
275
- else this.overlayImage.setDepth(5e5);
398
+ this.overlayImage.setDepth(baseDepth);
399
+ this.emissiveLayer = scene.add.container(0, 0);
400
+ this.emissiveLayer.setScrollFactor(0, 0);
401
+ this.emissiveLayer.setDepth(baseDepth + 1);
402
+ }
403
+ ensureGlowCapacity(needed) {
404
+ if (needed <= this.glowCap) return;
405
+ let next = this.glowCap;
406
+ while (next < needed) next *= 2;
407
+ this.glowCap = next;
408
+ this.glowX = new Float32Array(next);
409
+ this.glowY = new Float32Array(next);
410
+ this.glowScale = new Float32Array(next);
411
+ this.glowAlpha = new Float32Array(next);
412
+ this.glowTint = new Uint32Array(next);
413
+ if (this.glowBatch) this.glowBatch.maxCount = next;
276
414
  }
277
415
  addLight(light) {
278
416
  const copy = {
279
417
  enabled: true,
280
418
  flicker: 0,
419
+ space: "world",
281
420
  ...light
282
421
  };
283
422
  this.lights.set(copy.id, copy);
@@ -292,6 +431,77 @@ var Lighting2DSystem = class {
292
431
  get lightCount() {
293
432
  return this.lights.size;
294
433
  }
434
+ /** Latest ambient RGB evaluated during `update()` (handy for `createSceneNormalLitPass`). */
435
+ get currentAmbientRgb() {
436
+ return this.lastAmbientRgb;
437
+ }
438
+ /** Live flickering screen-space point lights from the latest `update()` pass. */
439
+ get screenLights() {
440
+ return this.activeScreenLights;
441
+ }
442
+ /**
443
+ * Bind a sprite (`ImageObject` / `SpriteObject`) whose atlas carries `@holtjs/craft` `Frame.emissiveCenter`
444
+ * and/or a sibling `${key}_emissive` self-lit texture:
445
+ * - Automatically tracks `emissiveCenter` in screen space across animations, `flipX`, `rotation`, and `Camera25D` spins!
446
+ * - Optionally drives a flickering `PointLight2D` (`opts.radius > 0`)
447
+ * - Renders `${key}_emissive` in `emissiveLayer` (`BlendModes.ADD` above night darkness) so flames/embers/eyes never dim at night!
448
+ */
449
+ bindEmissive(sprite, opts = {}) {
450
+ const id = `__emissive_${this.nextEmissiveSeq++}`;
451
+ const emissiveKey = opts.emissiveKey ?? `${sprite.texture.key}_emissive`;
452
+ const radius = opts.radius ?? 0;
453
+ const flicker = opts.flicker ?? .1;
454
+ const baseIntensity = opts.intensity ?? 1;
455
+ let light = null;
456
+ if (radius > 0) light = this.addLight({
457
+ id,
458
+ x: 0,
459
+ y: 0,
460
+ z: opts.z ?? 36,
461
+ radius,
462
+ color: opts.color ?? 0xff9a2e,
463
+ intensity: baseIntensity,
464
+ flicker,
465
+ space: "screen",
466
+ screenScale: 1
467
+ });
468
+ let glowSprite = null;
469
+ if (this.scene.textures.exists(emissiveKey)) {
470
+ const frameName = this.scene.textures.get(emissiveKey).has(sprite.frame.name) ? sprite.frame.name : "__BASE";
471
+ glowSprite = this.scene.make.image(0, 0, emissiveKey, frameName);
472
+ glowSprite.setBlendMode(BlendModes.ADD);
473
+ this.emissiveLayer.add(glowSprite);
474
+ }
475
+ const destroyRec = () => {
476
+ const rec = this.emissives.get(id);
477
+ if (!rec) return;
478
+ this.emissives.delete(id);
479
+ rec.cancelDispose();
480
+ if (rec.light) this.lights.delete(rec.light.id);
481
+ if (rec.glowSprite) rec.glowSprite.destroy();
482
+ };
483
+ const cancelDispose = sprite.onDispose(destroyRec);
484
+ const rec = {
485
+ id,
486
+ sprite,
487
+ emissiveKey,
488
+ emissiveAlpha: opts.emissiveAlpha ?? .95,
489
+ emissiveTint: opts.emissiveTint ?? 0xffffff,
490
+ baseIntensity,
491
+ flicker,
492
+ light,
493
+ glowSprite,
494
+ cancelDispose
495
+ };
496
+ this.emissives.set(id, rec);
497
+ return {
498
+ id,
499
+ sprite,
500
+ light,
501
+ glowSprite,
502
+ destroy: destroyRec
503
+ };
504
+ }
295
505
  setAmbientOverride(rgb) {
296
506
  this.manualAmbientRgb = rgb;
297
507
  }
@@ -308,27 +518,110 @@ var Lighting2DSystem = class {
308
518
  this.overlayImage.setTexture(newKey);
309
519
  this.overlayImage.setDisplaySize(this.viewportW, this.viewportH);
310
520
  }
521
+ syncEmissiveBindings() {
522
+ let idx = 0;
523
+ for (const rec of this.emissives.values()) {
524
+ idx++;
525
+ const sp = rec.sprite;
526
+ if (!sp.active) {
527
+ rec.cancelDispose();
528
+ if (rec.light) this.lights.delete(rec.light.id);
529
+ if (rec.glowSprite) rec.glowSprite.destroy();
530
+ this.emissives.delete(rec.id);
531
+ continue;
532
+ }
533
+ let vis = sp.visible && sp.alpha > 0;
534
+ for (let cur = sp.parentContainer; vis && cur; cur = cur.parentContainer) if (!cur.visible || cur.alpha <= 0) vis = false;
535
+ if (!vis) {
536
+ if (rec.light) rec.light.enabled = false;
537
+ if (rec.glowSprite) rec.glowSprite.visible = false;
538
+ continue;
539
+ }
540
+ const m = computeNodeScreenMatrix(sp, this.scene, this.matScratch);
541
+ const fr = sp.frame;
542
+ const ox = sp.displayOriginX;
543
+ const oy = sp.displayOriginY;
544
+ const pivotMirrored = fr.customPivot && !sp.customOrigin && !sp.isCropped;
545
+ if (rec.light) {
546
+ const ec = fr.emissiveCenter;
547
+ const rawX = ec ? ec[0] : fr.width * .5;
548
+ const rawY = ec ? ec[1] : fr.height * .5;
549
+ const lx = sp.flipX ? pivotMirrored ? ox - rawX : sp.width - ox - rawX : rawX - ox;
550
+ const ly = sp.flipY ? pivotMirrored ? oy - rawY : sp.height - oy - rawY : rawY - oy;
551
+ rec.light.enabled = true;
552
+ rec.light.x = m.a * lx + m.c * ly + m.tx;
553
+ rec.light.y = m.b * lx + m.d * ly + m.ty;
554
+ rec.light.screenScale = Math.max(.05, m.scaleX);
555
+ const pwr = fr.emissivePower !== null && fr.emissivePower > 0 ? Math.min(2, Math.max(.35, fr.emissivePower)) : 1;
556
+ rec.light.intensity = rec.baseIntensity * pwr;
557
+ }
558
+ if (!rec.glowSprite && this.scene.textures.exists(rec.emissiveKey)) {
559
+ const frameName = this.scene.textures.get(rec.emissiveKey).has(fr.name) ? fr.name : "__BASE";
560
+ rec.glowSprite = this.scene.make.image(0, 0, rec.emissiveKey, frameName);
561
+ rec.glowSprite.setBlendMode(BlendModes.ADD);
562
+ this.emissiveLayer.add(rec.glowSprite);
563
+ }
564
+ if (rec.glowSprite) {
565
+ const gs = rec.glowSprite;
566
+ if (gs.texture.has(fr.name)) {
567
+ if (gs.frame.name !== fr.name) gs.setFrame(fr.name);
568
+ gs.visible = true;
569
+ gs.customOrigin = sp.customOrigin;
570
+ gs._displayOriginX = ox;
571
+ gs._displayOriginY = oy;
572
+ gs.originX = sp.originX;
573
+ gs.originY = sp.originY;
574
+ gs.flipX = sp.flipX;
575
+ gs.flipY = sp.flipY;
576
+ decomposeMatrix2D(m, this.decompScratch);
577
+ gs.x = this.decompScratch.x;
578
+ gs.y = this.decompScratch.y;
579
+ gs.scaleX = this.decompScratch.scaleX;
580
+ gs.scaleY = this.decompScratch.scaleY;
581
+ gs.rotation = this.decompScratch.rotation;
582
+ gs.skewX = this.decompScratch.skewX;
583
+ gs.skewY = this.decompScratch.skewY;
584
+ const flick = rec.flicker ? 1 + Math.sin(this.elapsedSec * 9.7 + idx * 2.3) * rec.flicker * .5 + Math.sin(this.elapsedSec * 23.1 + idx * 5.1) * rec.flicker * .35 : 1;
585
+ gs.alpha = Math.max(0, Math.min(1, rec.emissiveAlpha * sp.alpha * flick));
586
+ if (rec.emissiveTint !== 0xffffff) {
587
+ gs.tint = rec.emissiveTint;
588
+ gs.isTinted = true;
589
+ } else gs.isTinted = false;
590
+ } else gs.visible = false;
591
+ }
592
+ }
593
+ }
311
594
  /**
312
- * Step the day/night cycle + torch flicker and render the `MULTIPLY` lightmap FBO!
595
+ * Step the day/night cycle + torch flicker, sync bound emissive sprites, and render the `MULTIPLY` lightmap FBO!
313
596
  * Pass `projectToScreen` when using `Camera25D`; otherwise defaults to `scene.cameras.main.worldToScreen`.
314
597
  */
315
598
  update(deltaMs, projectToScreen) {
316
599
  this.elapsedSec += Math.max(0, deltaMs) * .001;
317
600
  const state = this.cycle.step(deltaMs);
318
601
  const amb = this.manualAmbientRgb ?? state.ambientRgb;
319
- const g = this.lightGraphics;
320
- g.clear();
602
+ this.lastAmbientRgb = amb;
603
+ this.syncEmissiveBindings();
321
604
  const s = this.resScale;
322
605
  const pt = {
323
606
  x: 0,
324
607
  y: 0,
325
608
  scale: 1
326
609
  };
610
+ this.activeScreenLights.length = 0;
611
+ const useBatch = this.glowBatch !== null;
612
+ if (useBatch) this.ensureGlowCapacity(Math.max(16, this.lights.size * 2));
613
+ else this.lightGraphics.clear();
614
+ let instCount = 0;
327
615
  let idx = 0;
616
+ const invBaseSize = 2 / RADIAL_GLOW_SIZE;
328
617
  for (const l of this.lights.values()) {
329
618
  idx++;
330
619
  if (l.enabled === false || l.intensity <= 0 || l.radius <= 0) continue;
331
- if (projectToScreen) projectToScreen(l.x, l.y, l.z, pt);
620
+ if (l.space === "screen") {
621
+ pt.x = l.x;
622
+ pt.y = l.y;
623
+ pt.scale = l.screenScale ?? 1;
624
+ } else if (projectToScreen) projectToScreen(l.x, l.y, l.z, pt);
332
625
  else {
333
626
  const wpt = this.scene.cameras.main.worldToScreen(l.x, l.y);
334
627
  pt.x = wpt.x;
@@ -336,42 +629,93 @@ var Lighting2DSystem = class {
336
629
  pt.scale = this.scene.cameras.main.zoom;
337
630
  }
338
631
  const flick = l.flicker ? 1 + Math.sin(this.elapsedSec * 9.7 + idx * 2.3) * l.flicker * .6 + Math.sin(this.elapsedSec * 23.1 + idx * 5.1) * l.flicker * .4 : 1;
339
- const rad = l.radius * pt.scale * s * flick;
632
+ const screenRad = l.radius * pt.scale * flick;
633
+ const effInt = l.intensity * flick;
634
+ if (screenRad <= .5 || effInt <= .002) continue;
635
+ this.activeScreenLights.push({
636
+ screenX: pt.x,
637
+ screenY: pt.y,
638
+ z: l.z,
639
+ radius: screenRad,
640
+ color: l.color,
641
+ intensity: effInt
642
+ });
643
+ const rad = screenRad * s;
340
644
  const sx = pt.x * s;
341
645
  const sy = pt.y * s;
342
- const bands = 5;
343
- for (let b = bands; b >= 1; b--) {
344
- const frac = b / bands;
345
- const alpha = Math.min(1, l.intensity * flick / bands * (1.25 - frac * .5));
346
- g.fillStyle(l.color, alpha);
347
- g.fillCircle(sx, sy, rad * frac);
646
+ if (useBatch) {
647
+ this.glowX[instCount] = sx;
648
+ this.glowY[instCount] = sy;
649
+ this.glowScale[instCount] = rad * invBaseSize;
650
+ this.glowAlpha[instCount] = Math.min(1, effInt);
651
+ this.glowTint[instCount] = l.color >>> 0;
652
+ instCount++;
653
+ if (effInt > 1.02) {
654
+ this.glowX[instCount] = sx;
655
+ this.glowY[instCount] = sy;
656
+ this.glowScale[instCount] = rad * .48 * invBaseSize;
657
+ this.glowAlpha[instCount] = Math.min(1, effInt - 1);
658
+ this.glowTint[instCount] = l.color >>> 0;
659
+ instCount++;
660
+ }
661
+ } else {
662
+ const bands = 5;
663
+ for (let b = bands; b >= 1; b--) {
664
+ const frac = b / bands;
665
+ const alpha = Math.min(1, effInt / bands * (1.25 - frac * .5));
666
+ this.lightGraphics.fillStyle(l.color, alpha);
667
+ this.lightGraphics.fillCircle(sx, sy, rad * frac);
668
+ }
348
669
  }
349
670
  }
350
671
  const rtCam = this.renderTarget.camera;
351
672
  rtCam.setBackgroundColor(amb);
352
- this.scene.renderer.renderToTarget(this.renderTarget, { sorted: () => [g] }, rtCam);
673
+ let drawNode;
674
+ if (useBatch && this.glowBatch) {
675
+ this.glowBatch.setColumns({
676
+ count: instCount,
677
+ x: this.glowX,
678
+ y: this.glowY,
679
+ scaleX: this.glowScale,
680
+ alpha: this.glowAlpha,
681
+ tint: this.glowTint
682
+ });
683
+ drawNode = this.glowBatch;
684
+ } else drawNode = this.lightGraphics;
685
+ this.scene.renderer.renderToTarget(this.renderTarget, { sorted: () => instCount > 0 || !useBatch ? [drawNode] : [] }, rtCam);
353
686
  this.overlayImage.setDisplaySize(this.viewportW, this.viewportH);
354
687
  return state;
355
688
  }
356
689
  destroy() {
690
+ for (const rec of this.emissives.values()) {
691
+ rec.cancelDispose();
692
+ if (rec.glowSprite) rec.glowSprite.destroy();
693
+ }
694
+ this.emissives.clear();
695
+ this.emissiveLayer.destroy();
357
696
  this.overlayImage.destroy();
358
697
  this.lightGraphics.destroy();
698
+ if (this.glowBatch) this.glowBatch.destroy();
359
699
  this.renderTarget.destroy();
360
700
  this.lights.clear();
701
+ this.activeScreenLights.length = 0;
361
702
  }
362
703
  };
704
+ const NL_FLOATS_PER_VERT = 8;
705
+ const NL_STRIDE_BYTES = 32;
363
706
  const NORMAL_LIT_VS = `
364
- attribute vec2 aCorner;
707
+ attribute vec2 aScreenPos;
365
708
  attribute vec2 aUv;
709
+ attribute vec4 aBasis;
366
710
  uniform vec2 uRes;
367
- uniform vec4 uRect;
368
711
  varying vec2 vUv;
369
712
  varying vec2 vScreenPos;
713
+ varying vec4 vBasis;
370
714
  void main() {
371
- vec2 pos = uRect.xy + aCorner * uRect.zw;
372
- vScreenPos = pos;
715
+ vScreenPos = aScreenPos;
373
716
  vUv = aUv;
374
- vec2 clip = (pos / uRes) * 2.0 - 1.0;
717
+ vBasis = aBasis;
718
+ vec2 clip = (aScreenPos / uRes) * 2.0 - 1.0;
375
719
  gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);
376
720
  }
377
721
  `;
@@ -379,9 +723,11 @@ const NORMAL_LIT_FS = `
379
723
  precision mediump float;
380
724
  varying vec2 vUv;
381
725
  varying vec2 vScreenPos;
726
+ varying vec4 vBasis;
382
727
  uniform sampler2D uDiffuse;
383
728
  uniform sampler2D uNormal;
384
729
  uniform vec3 uAmbient;
730
+ uniform float uRimOnly;
385
731
  uniform int uLightCount;
386
732
  uniform vec4 uLightPosRad[8];
387
733
  uniform vec4 uLightColInt[8];
@@ -389,8 +735,9 @@ void main() {
389
735
  vec4 base = texture2D(uDiffuse, vUv);
390
736
  if (base.a <= 0.004) discard;
391
737
  vec3 nSample = texture2D(uNormal, vUv).xyz * 2.0 - 1.0;
392
- vec3 N = normalize(nSample);
393
- vec3 totalLight = uAmbient;
738
+ vec2 nScreenXY = vBasis.xy * nSample.x + vBasis.zw * nSample.y;
739
+ vec3 N = normalize(vec3(nScreenXY, nSample.z));
740
+ vec3 directLight = vec3(0.0);
394
741
  for (int i = 0; i < 8; i++) {
395
742
  if (i >= uLightCount) break;
396
743
  vec4 pr = uLightPosRad[i];
@@ -404,20 +751,91 @@ void main() {
404
751
  float atten = u * u * ci.w;
405
752
  vec3 H = normalize(L + vec3(0.0, 0.0, 1.0));
406
753
  float spec = pow(max(dot(N, H), 0.0), 16.0) * 0.25;
407
- totalLight += ci.rgb * ((ndotl + spec) * atten);
754
+ directLight += ci.rgb * ((ndotl + spec) * atten);
408
755
  }
409
756
  }
410
- vec3 rgb = base.rgb * totalLight;
411
- gl_FragColor = vec4(rgb, base.a);
757
+ if (uRimOnly > 0.0) {
758
+ vec3 rimRgb = base.rgb * directLight * uRimOnly * base.a;
759
+ gl_FragColor = vec4(rimRgb, 0.0);
760
+ } else {
761
+ vec3 rgb = base.rgb * (uAmbient + directLight);
762
+ gl_FragColor = vec4(rgb, base.a);
763
+ }
412
764
  }
413
765
  `;
766
+ function ensureNormalShader(gl) {
767
+ const vs = gl.createShader(gl.VERTEX_SHADER);
768
+ const fs = gl.createShader(gl.FRAGMENT_SHADER);
769
+ if (!vs || !fs) return null;
770
+ gl.shaderSource(vs, NORMAL_LIT_VS);
771
+ gl.compileShader(vs);
772
+ gl.shaderSource(fs, NORMAL_LIT_FS);
773
+ gl.compileShader(fs);
774
+ const prog = gl.createProgram();
775
+ if (!prog) return null;
776
+ gl.attachShader(prog, vs);
777
+ gl.attachShader(prog, fs);
778
+ gl.bindAttribLocation(prog, 0, "aScreenPos");
779
+ gl.bindAttribLocation(prog, 1, "aUv");
780
+ gl.bindAttribLocation(prog, 2, "aBasis");
781
+ gl.linkProgram(prog);
782
+ gl.deleteShader(vs);
783
+ gl.deleteShader(fs);
784
+ const vbo = gl.createBuffer();
785
+ if (!vbo) return null;
786
+ return {
787
+ prog,
788
+ vbo,
789
+ uDiffuse: gl.getUniformLocation(prog, "uDiffuse"),
790
+ uNormal: gl.getUniformLocation(prog, "uNormal"),
791
+ uRes: gl.getUniformLocation(prog, "uRes"),
792
+ uAmbient: gl.getUniformLocation(prog, "uAmbient"),
793
+ uRimOnly: gl.getUniformLocation(prog, "uRimOnly"),
794
+ uLightCount: gl.getUniformLocation(prog, "uLightCount"),
795
+ uLightPosRad: gl.getUniformLocation(prog, "uLightPosRad[0]"),
796
+ uLightColInt: gl.getUniformLocation(prog, "uLightColInt[0]")
797
+ };
798
+ }
799
+ function writeLitQuadVerts(buf, vertOffset, a, b, c, d, tx, ty, x0, y0, x1, y1, u0, v0, u1, v1, flipX, flipY) {
800
+ const lenA = Math.hypot(a, b) || 1;
801
+ const lenC = Math.hypot(c, d) || 1;
802
+ const sgnX = flipX ? -1 : 1;
803
+ const sgnY = flipY ? -1 : 1;
804
+ const btx = a / lenA * sgnX;
805
+ const bty = b / lenA * sgnX;
806
+ const bbx = c / lenC * sgnY;
807
+ const bby = d / lenC * sgnY;
808
+ const px00 = a * x0 + c * y0 + tx, py00 = b * x0 + d * y0 + ty;
809
+ const px10 = a * x1 + c * y0 + tx, py10 = b * x1 + d * y0 + ty;
810
+ const px11 = a * x1 + c * y1 + tx, py11 = b * x1 + d * y1 + ty;
811
+ const px01 = a * x0 + c * y1 + tx, py01 = b * x0 + d * y1 + ty;
812
+ const put = (o, sx, sy, u, v) => {
813
+ buf[o] = sx;
814
+ buf[o + 1] = sy;
815
+ buf[o + 2] = u;
816
+ buf[o + 3] = v;
817
+ buf[o + 4] = btx;
818
+ buf[o + 5] = bty;
819
+ buf[o + 6] = bbx;
820
+ buf[o + 7] = bby;
821
+ return o + NL_FLOATS_PER_VERT;
822
+ };
823
+ let o = vertOffset;
824
+ o = put(o, px00, py00, u0, v0);
825
+ o = put(o, px10, py10, u1, v0);
826
+ o = put(o, px11, py11, u1, v1);
827
+ o = put(o, px00, py00, u0, v0);
828
+ o = put(o, px11, py11, u1, v1);
829
+ o = put(o, px01, py01, u0, v1);
830
+ return o;
831
+ }
414
832
  /**
415
- * Create a state-isolated WebGL2 `CustomPass` that renders normal-mapped 2D props/characters with per-pixel
416
- * 3D tangent-space point lighting (`uDiffuse` + `uNormal`), gracefully no-oping on Canvas2D!
833
+ * Create a state-isolated, single-draw batched WebGL2 `CustomPass` that renders normal-mapped 2D props/characters with per-pixel
834
+ * 3D tangent-space point lighting (`uDiffuse` + `uNormal`, supporting `rotation`, `flipX`, and `flipY`), gracefully no-oping on Canvas2D!
417
835
  */
418
836
  function createNormalLitSpritePass(scene, diffuseKey, normalKey, getQuadsAndLights) {
419
- let prog = null;
420
- let vbo = null;
837
+ let shader = null;
838
+ let vertBuf = new Float32Array(384 * NL_FLOATS_PER_VERT);
421
839
  const posRadArr = /* @__PURE__ */ new Float32Array(32);
422
840
  const colIntArr = /* @__PURE__ */ new Float32Array(32);
423
841
  return scene.add.customPass((_pass, renderer) => {
@@ -430,33 +848,37 @@ function createNormalLitSpritePass(scene, diffuseKey, normalKey, getQuadsAndLigh
430
848
  const diffGl = glRenderer.ensureGlTexture(diffTexObj.source[0]);
431
849
  const normGl = glRenderer.ensureGlTexture(normTexObj.source[0]);
432
850
  if (!diffGl || !normGl) return;
433
- if (!prog) {
434
- const vs = gl.createShader(gl.VERTEX_SHADER);
435
- gl.shaderSource(vs, NORMAL_LIT_VS);
436
- gl.compileShader(vs);
437
- const fs = gl.createShader(gl.FRAGMENT_SHADER);
438
- gl.shaderSource(fs, NORMAL_LIT_FS);
439
- gl.compileShader(fs);
440
- prog = gl.createProgram();
441
- gl.attachShader(prog, vs);
442
- gl.attachShader(prog, fs);
443
- gl.bindAttribLocation(prog, 0, "aCorner");
444
- gl.bindAttribLocation(prog, 1, "aUv");
445
- gl.linkProgram(prog);
446
- gl.deleteShader(vs);
447
- gl.deleteShader(fs);
448
- vbo = gl.createBuffer();
449
- }
450
- if (!prog || !vbo) return;
851
+ if (!shader) shader = ensureNormalShader(gl);
852
+ if (!shader) return;
451
853
  const { ambientRgb, quads, lights } = getQuadsAndLights();
452
854
  if (!quads.length) return;
453
- gl.useProgram(prog);
855
+ const neededFloats = quads.length * 6 * NL_FLOATS_PER_VERT;
856
+ if (vertBuf.length < neededFloats) vertBuf = new Float32Array(Math.max(neededFloats, vertBuf.length * 2));
857
+ let vo = 0;
858
+ for (let i = 0; i < quads.length; i++) {
859
+ const q = quads[i];
860
+ const ox = q.width * (q.originX ?? .5);
861
+ const oy = q.height * (q.originY ?? 1);
862
+ const rot = q.rotation ?? 0;
863
+ const cs = rot === 0 ? 1 : Math.cos(rot);
864
+ const sn = rot === 0 ? 0 : Math.sin(rot);
865
+ const rawU0 = q.u0 ?? 0, rawV0 = q.v0 ?? 0, rawU1 = q.u1 ?? 1, rawV1 = q.v1 ?? 1;
866
+ const flipX = Boolean(q.flipX);
867
+ const flipY = Boolean(q.flipY);
868
+ const u0 = flipX ? rawU1 : rawU0;
869
+ const u1 = flipX ? rawU0 : rawU1;
870
+ const v0 = flipY ? rawV1 : rawV0;
871
+ const v1 = flipY ? rawV0 : rawV1;
872
+ vo = writeLitQuadVerts(vertBuf, vo, cs, sn, -sn, cs, q.x, q.y, -ox, -oy, q.width - ox, q.height - oy, u0, v0, u1, v1, flipX, flipY);
873
+ }
874
+ gl.useProgram(shader.prog);
454
875
  glRenderer.bindTextureAt(0, diffGl);
455
876
  glRenderer.bindTextureAt(1, normGl);
456
- gl.uniform1i(gl.getUniformLocation(prog, "uDiffuse"), 0);
457
- gl.uniform1i(gl.getUniformLocation(prog, "uNormal"), 1);
458
- gl.uniform2f(gl.getUniformLocation(prog, "uRes"), glRenderer.width, glRenderer.height);
459
- gl.uniform3f(gl.getUniformLocation(prog, "uAmbient"), (ambientRgb >> 16 & 255) / 255, (ambientRgb >> 8 & 255) / 255, (ambientRgb & 255) / 255);
877
+ gl.uniform1i(shader.uDiffuse, 0);
878
+ gl.uniform1i(shader.uNormal, 1);
879
+ gl.uniform2f(shader.uRes, glRenderer.width, glRenderer.height);
880
+ gl.uniform3f(shader.uAmbient, (ambientRgb >> 16 & 255) / 255, (ambientRgb >> 8 & 255) / 255, (ambientRgb & 255) / 255);
881
+ gl.uniform1f(shader.uRimOnly, 0);
460
882
  const nL = Math.min(8, lights.length);
461
883
  for (let i = 0; i < nL; i++) {
462
884
  const l = lights[i];
@@ -469,54 +891,136 @@ function createNormalLitSpritePass(scene, diffuseKey, normalKey, getQuadsAndLigh
469
891
  colIntArr[i * 4 + 2] = (l.color & 255) / 255;
470
892
  colIntArr[i * 4 + 3] = l.intensity;
471
893
  }
472
- gl.uniform1i(gl.getUniformLocation(prog, "uLightCount"), nL);
473
- gl.uniform4fv(gl.getUniformLocation(prog, "uLightPosRad[0]"), posRadArr);
474
- gl.uniform4fv(gl.getUniformLocation(prog, "uLightColInt[0]"), colIntArr);
475
- gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
894
+ gl.uniform1i(shader.uLightCount, nL);
895
+ gl.uniform4fv(shader.uLightPosRad, posRadArr);
896
+ gl.uniform4fv(shader.uLightColInt, colIntArr);
897
+ gl.bindBuffer(gl.ARRAY_BUFFER, shader.vbo);
898
+ gl.bufferData(gl.ARRAY_BUFFER, vertBuf.subarray(0, vo), gl.STREAM_DRAW);
476
899
  gl.enableVertexAttribArray(0);
477
900
  gl.enableVertexAttribArray(1);
478
- gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 16, 0);
479
- gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 16, 8);
480
- const uRectLoc = gl.getUniformLocation(prog, "uRect");
481
- const quadVerts = /* @__PURE__ */ new Float32Array(24);
482
- for (let i = 0; i < quads.length; i++) {
483
- const q = quads[i];
484
- const ox = q.originX ?? .5;
485
- const oy = q.originY ?? 1;
486
- const x0 = q.x - q.width * ox;
487
- const y0 = q.y - q.height * oy;
488
- const u0 = q.u0 ?? 0, v0 = q.v0 ?? 0, u1 = q.u1 ?? 1, v1 = q.v1 ?? 1;
489
- quadVerts.set([
490
- 0,
491
- 0,
492
- u0,
493
- v0,
494
- 1,
495
- 0,
496
- u1,
497
- v0,
498
- 1,
499
- 1,
500
- u1,
501
- v1,
502
- 0,
503
- 0,
504
- u0,
505
- v0,
506
- 1,
507
- 1,
508
- u1,
509
- v1,
510
- 0,
511
- 1,
512
- u0,
513
- v1
514
- ]);
515
- gl.bufferData(gl.ARRAY_BUFFER, quadVerts, gl.STREAM_DRAW);
516
- gl.uniform4f(uRectLoc, x0, y0, q.width, q.height);
517
- gl.drawArrays(gl.TRIANGLES, 0, 6);
518
- glRenderer.recordCustomDraw(1);
901
+ gl.enableVertexAttribArray(2);
902
+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, NL_STRIDE_BYTES, 0);
903
+ gl.vertexAttribPointer(1, 2, gl.FLOAT, false, NL_STRIDE_BYTES, 8);
904
+ gl.vertexAttribPointer(2, 4, gl.FLOAT, false, NL_STRIDE_BYTES, 16);
905
+ gl.drawArrays(gl.TRIANGLES, 0, quads.length * 6);
906
+ glRenderer.recordCustomDraw(1);
907
+ }, { restoreState: true });
908
+ }
909
+ /**
910
+ * Scene-graph native 2D Normal-Map lighting pass: automatically traverses `source` (`stage25d.billboardLayer` or nested `Container`s),
911
+ * discovers matching `${texture.key}_normal` atlases registered by `@holtjs/craft`, transforms `customPivot` (`ax/ay`), `flipX`, `flipY`,
912
+ * `rotation`, and `skew` into tangent-space screen basis vectors, and batches consecutive same-atlas sprites into a single WebGL draw call!
913
+ */
914
+ function createSceneNormalLitPass(scene, opts) {
915
+ let shader = null;
916
+ let vertBuf = new Float32Array(768 * NL_FLOATS_PER_VERT);
917
+ const posRadArr = /* @__PURE__ */ new Float32Array(32);
918
+ const colIntArr = /* @__PURE__ */ new Float32Array(32);
919
+ const matScratch = createMatrix2D();
920
+ const mode = opts.mode ?? "rim";
921
+ const rimStrength = opts.rimStrength ?? .6;
922
+ const pass = scene.add.customPass((_pass, renderer) => {
923
+ const gl = renderer.gl;
924
+ if (!gl) return;
925
+ const lights = opts.lighting.screenLights;
926
+ if (mode === "rim" && lights.length === 0) return;
927
+ if (!shader) shader = ensureNormalShader(gl);
928
+ if (!shader) return;
929
+ const glRenderer = renderer;
930
+ gl.useProgram(shader.prog);
931
+ gl.uniform1i(shader.uDiffuse, 0);
932
+ gl.uniform1i(shader.uNormal, 1);
933
+ gl.uniform2f(shader.uRes, glRenderer.width, glRenderer.height);
934
+ const amb = opts.lighting.currentAmbientRgb;
935
+ gl.uniform3f(shader.uAmbient, (amb >> 16 & 255) / 255, (amb >> 8 & 255) / 255, (amb & 255) / 255);
936
+ gl.uniform1f(shader.uRimOnly, mode === "rim" ? rimStrength : 0);
937
+ const nL = Math.min(8, lights.length);
938
+ for (let i = 0; i < nL; i++) {
939
+ const l = lights[i];
940
+ posRadArr[i * 4] = l.screenX;
941
+ posRadArr[i * 4 + 1] = l.screenY;
942
+ posRadArr[i * 4 + 2] = l.z;
943
+ posRadArr[i * 4 + 3] = l.radius;
944
+ colIntArr[i * 4] = (l.color >> 16 & 255) / 255;
945
+ colIntArr[i * 4 + 1] = (l.color >> 8 & 255) / 255;
946
+ colIntArr[i * 4 + 2] = (l.color & 255) / 255;
947
+ colIntArr[i * 4 + 3] = l.intensity;
519
948
  }
949
+ gl.uniform1i(shader.uLightCount, nL);
950
+ gl.uniform4fv(shader.uLightPosRad, posRadArr);
951
+ gl.uniform4fv(shader.uLightColInt, colIntArr);
952
+ gl.enable(gl.BLEND);
953
+ if (mode === "rim") gl.blendFunc(gl.ONE, gl.ONE);
954
+ else gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
955
+ gl.bindBuffer(gl.ARRAY_BUFFER, shader.vbo);
956
+ gl.enableVertexAttribArray(0);
957
+ gl.enableVertexAttribArray(1);
958
+ gl.enableVertexAttribArray(2);
959
+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, NL_STRIDE_BYTES, 0);
960
+ gl.vertexAttribPointer(1, 2, gl.FLOAT, false, NL_STRIDE_BYTES, 8);
961
+ gl.vertexAttribPointer(2, 4, gl.FLOAT, false, NL_STRIDE_BYTES, 16);
962
+ let curDiffGl = null;
963
+ let curNormGl = null;
964
+ let vo = 0;
965
+ let quadCount = 0;
966
+ const flushBatch = () => {
967
+ if (quadCount <= 0 || !curDiffGl || !curNormGl || !shader) return;
968
+ glRenderer.bindTextureAt(0, curDiffGl);
969
+ glRenderer.bindTextureAt(1, curNormGl);
970
+ gl.bufferData(gl.ARRAY_BUFFER, vertBuf.subarray(0, vo), gl.STREAM_DRAW);
971
+ gl.drawArrays(gl.TRIANGLES, 0, quadCount * 6);
972
+ glRenderer.recordCustomDraw(1);
973
+ vo = 0;
974
+ quadCount = 0;
975
+ };
976
+ const visit = (node) => {
977
+ if (!node.active || !node.visible || node.alpha <= 0) return;
978
+ if (node.type === "Container") {
979
+ const children = node.sortedChildren();
980
+ for (let i = 0; i < children.length; i++) visit(children[i]);
981
+ return;
982
+ }
983
+ if (node.type !== "Image" && node.type !== "Sprite") return;
984
+ const img = node;
985
+ const fr = img.frame;
986
+ if (!fr || fr.width <= 0 || fr.height <= 0) return;
987
+ const normKey = `${img.texture.key}_normal`;
988
+ if (!scene.textures.exists(normKey)) return;
989
+ const normTex = scene.textures.get(normKey);
990
+ const diffGl = glRenderer.ensureGlTexture(fr.source);
991
+ const normGl = glRenderer.ensureGlTexture(normTex.source[0]);
992
+ if (!diffGl || !normGl) return;
993
+ if (diffGl !== curDiffGl || normGl !== curNormGl) {
994
+ flushBatch();
995
+ curDiffGl = diffGl;
996
+ curNormGl = normGl;
997
+ }
998
+ const needed = vo + 48;
999
+ if (vertBuf.length < needed) {
1000
+ const grown = new Float32Array(Math.max(needed, vertBuf.length * 2));
1001
+ grown.set(vertBuf.subarray(0, vo));
1002
+ vertBuf = grown;
1003
+ }
1004
+ const m = computeNodeScreenMatrix(img, scene, matScratch);
1005
+ const ox = img.displayOriginX;
1006
+ const oy = img.displayOriginY;
1007
+ const pivotMirrored = fr.customPivot && !img.customOrigin && !img.isCropped;
1008
+ const x0 = pivotMirrored && img.flipX ? ox - img.width : -ox;
1009
+ const y0 = pivotMirrored && img.flipY ? oy - img.height : -oy;
1010
+ const x1 = pivotMirrored && img.flipX ? ox : img.width - ox;
1011
+ const y1 = pivotMirrored && img.flipY ? oy : img.height - oy;
1012
+ const u0 = img.flipX ? fr.u1 : fr.u0;
1013
+ const u1 = img.flipX ? fr.u0 : fr.u1;
1014
+ const v0 = img.flipY ? fr.v1 : fr.v0;
1015
+ const v1 = img.flipY ? fr.v0 : fr.v1;
1016
+ vo = writeLitQuadVerts(vertBuf, vo, m.a, m.b, m.c, m.d, m.tx, m.ty, x0, y0, x1, y1, u0, v0, u1, v1, img.flipX, img.flipY);
1017
+ quadCount++;
1018
+ };
1019
+ if (Array.isArray(opts.source)) for (let i = 0; i < opts.source.length; i++) visit(opts.source[i]);
1020
+ else visit(opts.source);
1021
+ flushBatch();
520
1022
  }, { restoreState: true });
1023
+ pass.setDepth(opts.depth ?? opts.lighting.overlayImage.depth - 1);
1024
+ return pass;
521
1025
  }
522
- export { DayNightCycle, Lighting2DSystem, bakeNormalMapCanvas, computeNormalMapPixels, createNormalLitSpritePass, evaluateNormalLitPixel, lerpRgb };
1026
+ export { DayNightCycle, Lighting2DSystem, bakeNormalMapCanvas, computeNormalMapPixels, createNormalLitSpritePass, createSceneNormalLitPass, evaluateNormalLitPixel, lerpRgb };